From 9ac38222e12e9bec2bb171d2a30aa8b69aeb4b9a Mon Sep 17 00:00:00 2001 From: Fabio Lussi <198260595+itrycodinganditsbad@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:07:40 +0200 Subject: [PATCH 0001/1092] Alt/Option-drag previews for clipping and sharpening Holding Alt (Option on macOS) while dragging an Edit slider shows Lightroom's temporary previews: highlight clipping for Exposure, Highlights and Whites, shadow clipping for Shadows and Blacks, greyscale for Sharpening Amount, the detail band for Radius / Detail and the sharpening mask for Masking. They are render overlays (pipeline visualize), drawn the same way after the CPU and GPU renderers; the sharpening views read each renderer's own detail planes. Settings and normal output are unchanged. Fixes #937 Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/render.rs | 8 + crates/gpu/tests/equivalence.rs | 28 ++++ crates/pipeline/src/finish.rs | 11 +- crates/pipeline/src/lib.rs | 7 +- crates/pipeline/src/local.rs | 7 +- crates/pipeline/src/spots.rs | 4 +- crates/pipeline/src/visualize.rs | 239 +++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/detail.rs | 16 +- crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/tests_panels.rs | 37 +++++ docs/parity-checklist.md | 21 +-- docs/ui-parity.md | 11 +- docs/whats-new.md | 11 ++ 14 files changed, 382 insertions(+), 25 deletions(-) diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 44458350f0..bb920d4c0c 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -747,6 +747,14 @@ pub fn render( lightcraft_pipeline::masks::evaluate_one(m, &plan.frame, w, h, &img, &l, s.light.exposure as f32, plan.mattes.as_deref()) } }); + // a sharpening view: the detail planes this render sharpened with + let overlay_mask = overlay_mask.or_else(|| { + req.overlay.reads_detail().then(|| { + let l = host.log_l.get_or_insert_with(|| Arc::new(cx.read_plane(&prep.log_l, w, h))).clone(); + let tex = prep.texture.as_deref().map(|b| cx.read_plane(b, w, h)); + lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, tex.as_ref(), plan.px_per_long) + })? + }); lightcraft_pipeline::visualize::apply(&mut image, req.overlay, &plan, overlay_mask.as_ref()); // spots grew the window the render worked on: cut it back to the request if let Some(k) = plan.keep { diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/equivalence.rs index 96771a971f..96d46340bc 100644 --- a/crates/gpu/tests/equivalence.rs +++ b/crates/gpu/tests/equivalence.rs @@ -660,6 +660,34 @@ fn overlays_match() { let req = RenderRequest { overlay: Overlay::Mask { id, view, color: [230, 30, 40], opacity: 50 }, ..RenderRequest::fit(640, 640) }; check(&format!("mask {id} overlay {}", view.name()), &src, &raw, &s, &req); } + // Alt-drag previews: clipping and greyscale on the finished image; the sharpening views from + // each renderer's own detail planes (with sharpening on, and off: no texture plane then). + let mut s = DevelopSettings::default(); + (s.light.whites, s.light.blacks, s.detail.sharpen_masking) = (80.0, -80.0, 40.0); + for amount in [50.0, 0.0] { + s.detail.sharpen_amount = amount; + for o in [Overlay::ClipHighlights, Overlay::ClipShadows, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask] { + let req = RenderRequest { overlay: o, ..RenderRequest::fit(640, 640) }; + if matches!(o, Overlay::ClipHighlights | Overlay::ClipShadows) { + // a binary view: a 1-LSB difference at 0 / 255 flips a channel, so compare shares + let cpu = render(&src, &raw, &s, &req).image; + let gpu = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu").image; + let differ = cpu.data.iter().zip(&gpu.data).filter(|(a, b)| a != b).count() as f64 / cpu.data.len() as f64; + assert!(differ < 0.002, "{o:?} sharpen {amount}: {differ}"); + } else if o == Overlay::Grayscale { + check(&format!("{o:?} preview"), &src, &raw, &s, &req); + } else { + // the sharpening views amplify the detail planes (the mask through a steep + // smoothstep): allow a few larger differences where the planes differ slightly + let cpu = render(&src, &raw, &s, &req).image; + let gpu = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu").image; + let (mean, max, _) = diff(&cpu, &gpu); + let far = cpu.data.iter().zip(&gpu.data).filter(|(a, b)| a[0].abs_diff(b[0]) > 8).count() as f64 / cpu.data.len() as f64; + eprintln!("{o:?} sharpen {amount:<4} mean {mean:.4} max {max} >8: {:.4}%", far * 100.0); + assert!(mean < 1.0 && far < 0.005, "{o:?} sharpen {amount}: mean {mean:.4}, >8 LSB {far}"); + } + } + } } #[test] diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index eb65d51a2b..99c83dc42b 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -20,6 +20,15 @@ fn smooth(e0: f32, e1: f32, x: f32) -> f32 { t * t * (3.0 - 2.0 * t) } +/// How much of the sharpening a pixel gets (0..1) under Masking `masking` (0..1), from its fine +/// detail `det` (log luminance minus its texture blur): 1 everywhere at 0, only stronger edges +/// as it rises. The GPU kernel (`finish.wgsl`) computes the same; Alt-drag on Masking shows it +/// ([`crate::Overlay::SharpenMask`]). +#[inline] +pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } +} + /// Parametric region curve (encoded domain) composed with the master point curve. fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> { let parametric = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; @@ -509,7 +518,7 @@ pub(crate) fn finish_with( let tame = 1.0 - 0.6 * smooth(0.4, 1.6, det.abs()); delta += tx * 1.1 * det.clamp(-1.0, 1.0) * tame; if sp != 0.0 { - let m = if sharpen_mask > 0.0 { smooth(sharpen_mask * 0.25, sharpen_mask * 0.25 + 0.15, det.abs()) } else { 1.0 }; + let m = sharpen_mask_weight(sharpen_mask, det); delta += sp * 1.3 * det.clamp(-0.8, 0.8) * m; } } diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 6fbb156e89..a1d9e2aa5c 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -637,9 +637,12 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, Some(acc.map(|v| v / n)) } -/// The alpha plane a mask overlay shows: the one the render evaluated, or (for a hidden mask) a -/// fresh evaluation. +/// The plane an overlay shows: a sharpening view's detail plane, or the alpha of a mask overlay +/// (the one the render evaluated, or for a hidden mask a fresh evaluation). fn overlay_alpha(o: Overlay, plan: &Plan<'_>, prep: &Prepared) -> Option { + if o.reads_detail() { + return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, prep.texture_blur.as_deref(), plan.px_per_long); + } let m = o.mask(&plan.settings)?; if let Some(e) = prep.masks.iter().find(|e| e.id == m.id) { return Some(e.alpha.clone()); diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index ce3994cd8b..4ddd885cb4 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -452,6 +452,11 @@ pub struct PlaneSigmas { pub chroma: Option, } +/// Gaussian sigma (pixels) of the texture / sharpening band at `px_per_long`. +pub fn texture_sigma(px_per_long: f64) -> f32 { + (0.0018 * px_per_long as f32).max(0.6) +} + pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas { let ppl = px_per_long as f32; let local_any = |f: fn(&lightcraft_develop::LocalAdjustments) -> f64| s.masks.iter().any(|m| f(&m.adjust) != 0.0); @@ -472,7 +477,7 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS || local_any(|a| a.sharpness) || local_any(|a| a.noise) || s.masks.iter().any(|m| m.adjust.defringe > 0.0)) - .then(|| (0.0018 * ppl).max(0.6)); + .then(|| texture_sigma(px_per_long)); let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); let chroma = (local_any(|a| a.moire) || s.masks.iter().any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; diff --git a/crates/pipeline/src/spots.rs b/crates/pipeline/src/spots.rs index 483f83f3cf..f8b3fbbdfd 100644 --- a/crates/pipeline/src/spots.rs +++ b/crates/pipeline/src/spots.rs @@ -247,8 +247,8 @@ fn fill_box(src: &mut [[f32; 3]], tgt: &[[f32; 3]], alpha: &[f32], bw: usize, bh let flat: Vec = tgt.iter().flatten().copied().collect(); let out = lightcraft_inpaint::complete(bw, bh, 3, &flat, &hole, &lightcraft_inpaint::CompleteParams::default()) .unwrap_or_else(|| lightcraft_inpaint::membrane_fill(bw, bh, 3, &flat, &hole)); - for (d, v) in src.iter_mut().zip(out.chunks_exact(3)) { - *d = [v[0], v[1], v[2]]; + for (d, v) in src.iter_mut().zip(out.as_chunks::<3>().0) { + *d = *v; } } diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index fc3d8390f5..baa992fd17 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -9,6 +9,11 @@ //! - **Mask overlay** (Masking): the evaluated alpha of one mask, drawn as a colour tint, a colour //! tint on a black-and-white image, the image on black / white, or the alpha as white on black //! ([`MaskView`]). Both renderers hand the same alpha plane (the one the render used) to [`apply`]. +//! - **Alt/Option-drag previews** (Lightroom's temporary views while a slider is dragged with the +//! modifier held; [`Overlay::for_control`] picks one per control): shadow / highlight clipping +//! (white or black, with the clipped channels shown), greyscale (Sharpening Amount), the fine +//! detail band sharpening works on (Radius / Detail) and the sharpening mask (Masking). The +//! sharpening views read the render's own detail planes ([`sharpen_plane`]). use std::borrow::Cow; @@ -36,6 +41,19 @@ pub enum Overlay { /// Visualize HDR (photos edited in HDR): the SDR image dimmed to grey, with every pixel the HDR /// rendition puts above SDR white painted by how far above it is ([`HDR_BANDS`]). HdrRange, + /// Shadow clipping (Alt-drag on Blacks / Shadows): white, a channel at 0 drops out of the + /// colour, so pixels clipped in every channel are black and partly clipped ones are coloured. + ClipShadows, + /// Highlight clipping (Alt-drag on Exposure / Highlights / Whites): black, a channel at 255 + /// shows in the colour, so pixels clipped in every channel are white. + ClipHighlights, + /// The photo in greyscale (Alt-drag on Sharpening Amount). + Grayscale, + /// The fine detail band sharpening amplifies, as grey ± detail (Alt-drag on Sharpening Radius + /// / Detail). + SharpenDetail, + /// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking). + SharpenMask, } /// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white. @@ -121,6 +139,11 @@ impl Overlay { Overlay::Spots(t) => (2, t as f64), Overlay::Mask { id, view, color, opacity } => (3, pack_mask(id, view, color, opacity) as f64), Overlay::HdrRange => (4, 0.0), + Overlay::ClipShadows => (5, 0.0), + Overlay::ClipHighlights => (6, 0.0), + Overlay::Grayscale => (7, 0.0), + Overlay::SharpenDetail => (8, 0.0), + Overlay::SharpenMask => (9, 0.0), } } @@ -131,6 +154,11 @@ impl Overlay { 2 => Overlay::Spots(v.clamp(0.0, 100.0) as u8), 3 if v.is_finite() && v >= 0.0 => unpack_mask(v as u64), 4 => Overlay::HdrRange, + 5 => Overlay::ClipShadows, + 6 => Overlay::ClipHighlights, + 7 => Overlay::Grayscale, + 8 => Overlay::SharpenDetail, + 9 => Overlay::SharpenMask, _ => Overlay::None, } } @@ -143,9 +171,38 @@ impl Overlay { Overlay::Spots(t) => 0x2000 + t as u64, Overlay::Mask { id, view, color, opacity } => 3 << 60 | pack_mask(id, view, color, opacity), Overlay::HdrRange => 0x4000, + Overlay::ClipShadows => 0x5000, + Overlay::ClipHighlights => 0x5001, + Overlay::Grayscale => 0x5002, + Overlay::SharpenDetail => 0x5003, + Overlay::SharpenMask => 0x5004, } } + /// The temporary preview Lightroom shows while develop control `id` is dragged with Alt + /// (Option on macOS) held, if it has one. + pub fn for_control(id: &str) -> Option { + match id { + "light.exposure" | "light.highlights" | "light.whites" => Some(Overlay::ClipHighlights), + "light.shadows" | "light.blacks" => Some(Overlay::ClipShadows), + "detail.sharpenAmount" => Some(Overlay::Grayscale), + "detail.sharpenRadius" | "detail.sharpenDetail" => Some(Overlay::SharpenDetail), + "detail.sharpenMasking" => Some(Overlay::SharpenMask), + _ => None, + } + } + + /// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]). + pub fn reads_detail(self) -> bool { + matches!(self, Overlay::SharpenDetail | Overlay::SharpenMask) + } + + /// Whether the overlay works pixel by pixel on the finished image, so a window render shows + /// the same as the whole frame would. + pub fn per_pixel(self) -> bool { + matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale) + } + /// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components). pub fn mask(self, s: &DevelopSettings) -> Option<&lightcraft_develop::Mask> { match self { @@ -167,9 +224,44 @@ pub fn adjust_settings(o: Overlay, s: &mut Cow<'_, DevelopSettings>) { } } -/// Draw overlay `o` over `img` (rendered with `plan`). `mask` is the evaluated alpha of the mask -/// an [`Overlay::Mask`] shows, at the image's size (see [`Overlay::mask`]). -pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, mask: Option<&Plane>) { +/// The plane a sharpening view draws ([`Overlay::reads_detail`]), from the render's log luminance +/// `log_l` and its texture blur (`None` when the render didn't need it: blurred here with the same +/// sigma). [`Overlay::SharpenDetail`]: the detail band (log luminance minus its blur, in EV); +/// [`Overlay::SharpenMask`]: the sharpening weight under the photo's Masking. Both renderers call +/// this with their own planes. +pub fn sharpen_plane(o: Overlay, s: &DevelopSettings, log_l: &Plane, texture: Option<&Plane>, px_per_long: f64) -> Option { + if !o.reads_detail() { + return None; + } + let own; + let blur = match texture.filter(|b| (b.width, b.height) == (log_l.width, log_l.height)) { + Some(b) => b, + None => { + own = lightcraft_raster::blur::gaussian(log_l, crate::local::texture_sigma(px_per_long)); + &own + } + }; + let masking = (s.detail.sharpen_masking / 100.0).clamp(0.0, 1.0) as f32; + let mask = o == Overlay::SharpenMask; + let data = log_l + .data + .iter() + .zip(&blur.data) + .map(|(l, b)| { + let det = l - b; + if mask { crate::finish::sharpen_mask_weight(masking, det) } else { det } + }) + .collect(); + Some(Plane { width: log_l.width, height: log_l.height, data }) +} + +/// [`Overlay::SharpenDetail`]: encoded grey per EV of detail (±0.4 EV spans black to white). +const DETAIL_GAIN: f32 = 320.0; + +/// Draw overlay `o` over `img` (rendered with `plan`). `plane` is what the overlay shows, at the +/// image's size: the evaluated alpha of the mask an [`Overlay::Mask`] shows (see +/// [`Overlay::mask`]) or a sharpening view's [`sharpen_plane`]. +pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane>) { match o { // drawn by the renderer from the HDR rendition ([`hdr_range`]) Overlay::None | Overlay::HdrRange => {} @@ -180,13 +272,60 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, mask: Option<&Plane>) } Overlay::Spots(t) => spots(img, t, plan.px_per_long), Overlay::Mask { view, color, opacity, .. } => { - if let Some(a) = mask.filter(|a| (a.width, a.height) == (img.width, img.height)) { + if let Some(a) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { mask_view(img, a, view, color, opacity); } } + Overlay::ClipShadows => clipping(img, false), + Overlay::ClipHighlights => clipping(img, true), + Overlay::Grayscale => grayscale(img), + Overlay::SharpenDetail | Overlay::SharpenMask => { + if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { + let detail = o == Overlay::SharpenDetail; + let w = img.width; + for_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let v = p.data[y * w + x]; + let g = if detail { 128.0 + v * DETAIL_GAIN } else { 255.0 * v }; + let g = g.round().clamp(0.0, 255.0) as u8; + *px = [g, g, g, 255]; + } + }); + } + } } } +/// [`Overlay::ClipHighlights`] (`high`) or [`Overlay::ClipShadows`]: each channel shows only +/// whether it is clipped, on black (highlights) or white (shadows). +pub fn clipping(img: &mut Rgba8, high: bool) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + for c in &mut px[..3] { + *c = if high { + if *c == 255 { 255 } else { 0 } + } else if *c == 0 { + 0 + } else { + 255 + }; + } + px[3] = 255; + } + }); +} + +fn grayscale(img: &mut Rgba8) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + let g = (0.2126 * px[0] as f32 + 0.7152 * px[1] as f32 + 0.0722 * px[2] as f32).round().clamp(0.0, 255.0) as u8; + *px = [g, g, g, 255]; + } + }); +} + /// Draw mask alpha `a` over `img` as `view`. pub fn mask_view(img: &mut Rgba8, a: &Plane, view: MaskView, color: [u8; 3], opacity: u8) { let op = opacity.min(100) as f32 / 100.0; @@ -380,4 +519,96 @@ mod tests { assert_eq!(MaskView::WhiteOnBlack.next(), MaskView::Color); assert_eq!(MaskView::parse("colorOnBw"), Some(MaskView::ColorOnBw)); } + + #[test] + fn clipping_views_show_the_clipped_channels() { + let mut img = Rgba8 { + width: 5, + height: 1, + data: vec![[0, 0, 0, 255], [255, 255, 255, 255], [255, 40, 0, 255], [0, 128, 200, 255], [120, 130, 140, 255]], + }; + let mut hi = img.clone(); + clipping(&mut hi, true); + // black background, white where every channel clips, the clipped channels' colour otherwise + assert_eq!(hi.data, vec![[0, 0, 0, 255], [255; 4], [255, 0, 0, 255], [0, 0, 0, 255], [0, 0, 0, 255]]); + clipping(&mut img, false); + // white background, black where every channel clips, the unclipped channels' colour otherwise + assert_eq!(img.data, vec![[0, 0, 0, 255], [255; 4], [255, 255, 0, 255], [0, 255, 255, 255], [255; 4]]); + } + + #[test] + fn clipping_previews_follow_the_rendered_clipping() { + // left: deep shadow, middle: grey, right: bright highlight + let src = Rgb32f::from_fn(60, 20, |x, _| match x / 20 { + 0 => [0.0; 3], + 1 => [0.18; 3], + _ => [3.0; 3], + }); + let info = SourceInfo::default(); + let mut s = DevelopSettings::default(); + s.light.blacks = -100.0; + s.light.whites = 100.0; + let req = |o| RenderRequest { overlay: o, ..RenderRequest::fit(60, 20) }; + let plain = render(&src, &info, &s, &req(Overlay::None)); + let hi = render(&src, &info, &s, &req(Overlay::ClipHighlights)); + let lo = render(&src, &info, &s, &req(Overlay::ClipShadows)); + let at = |i: &Rgba8, x: usize| i.data[10 * 60 + x]; + assert_eq!(at(&plain.image, 55), [255; 4], "the highlight clips"); + assert_eq!(at(&plain.image, 5), [0, 0, 0, 255], "the shadow clips"); + assert_eq!((at(&hi.image, 55), at(&hi.image, 30), at(&hi.image, 5)), ([255; 4], [0, 0, 0, 255], [0, 0, 0, 255])); + assert_eq!((at(&lo.image, 5), at(&lo.image, 30), at(&lo.image, 55)), ([0, 0, 0, 255], [255; 4], [255; 4])); + // a preview only: the histogram is the photo's + assert_eq!(hi.histogram, plain.histogram); + assert_eq!(render(&src, &info, &s, &req(Overlay::None)).image, plain.image); + } + + #[test] + fn sharpening_previews_show_the_mask_and_detail() { + // a smooth ramp (left) and a hard edge (at x = 60) + let src = Rgb32f::from_fn(80, 40, |x, _| if x < 60 { [0.05 + 0.002 * x as f32; 3] } else { [0.6; 3] }); + let info = SourceInfo::default(); + let mut s = DevelopSettings::default(); + s.detail.sharpen_amount = 60.0; + let shot = |s: &DevelopSettings, o| render(&src, &info, s, &RenderRequest { overlay: o, ..RenderRequest::fit(80, 40) }).image; + let (flat, edge) = (20 * 80 + 20, 20 * 80 + 60); + // Masking 0 sharpens everything: an all-white mask + let m = shot(&s, Overlay::SharpenMask); + assert!(m.data.iter().all(|p| *p == [255; 4])); + // Masking 100 keeps the edge, protects the ramp + s.detail.sharpen_masking = 100.0; + let m = shot(&s, Overlay::SharpenMask); + assert_eq!((m.data[edge], m.data[flat]), ([255; 4], [0, 0, 0, 255])); + // the same without sharpening on (the render has no texture plane then) + s.detail.sharpen_amount = 0.0; + assert_eq!(shot(&s, Overlay::SharpenMask), m); + // detail: mid grey on the ramp, light / dark either side of the edge + let d = shot(&s, Overlay::SharpenDetail); + assert!(d.data[flat][0].abs_diff(128) <= 3, "{:?}", d.data[flat]); + assert!(d.data[edge][0] > 200 && d.data[edge - 1][0] < 60, "{:?} {:?}", d.data[edge], d.data[edge - 1]); + // greyscale + let src = Rgb32f::from_fn(8, 8, |_, _| [0.4, 0.1, 0.05]); + let g = render(&src, &info, &s, &RenderRequest { overlay: Overlay::Grayscale, ..RenderRequest::fit(8, 8) }).image; + assert!(g.data.iter().all(|p| p[0] == p[1] && p[1] == p[2] && p[0] > 0)); + } + + #[test] + fn alt_previews_map_to_controls_and_round_trip() { + assert_eq!(Overlay::for_control("light.blacks"), Some(Overlay::ClipShadows)); + assert_eq!(Overlay::for_control("light.shadows"), Some(Overlay::ClipShadows)); + assert_eq!(Overlay::for_control("light.whites"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("light.exposure"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("light.highlights"), Some(Overlay::ClipHighlights)); + assert_eq!(Overlay::for_control("detail.sharpenAmount"), Some(Overlay::Grayscale)); + assert_eq!(Overlay::for_control("detail.sharpenDetail"), Some(Overlay::SharpenDetail)); + assert_eq!(Overlay::for_control("detail.sharpenMasking"), Some(Overlay::SharpenMask)); + assert_eq!(Overlay::for_control("light.contrast"), None); + let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask]; + for o in all { + let (k, v) = o.to_parts(); + assert_eq!(Overlay::from_parts(k, v), o); + assert_eq!(all.iter().filter(|p| p.key() == o.key()).count(), 1); + assert_ne!(o.key(), Overlay::HdrRange.key()); + } + assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel()); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9a387c77cd..5dc9651299 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1018,6 +1018,8 @@ impl LightcraftApp { } } self.ui.was_focused = focused; + // Alt (Option on macOS) while a slider is dragged shows its temporary preview + self.ui.alt_held = ctx.input(|i| i.modifiers.alt); // auto import: list the watched folder every few seconds (on a worker thread: it may be on // a network share), then import what's new like any import (also on a worker thread) #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 234476167e..4eb03c8c6c 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -253,7 +253,7 @@ fn animated_rect(ctx: &egui::Context, anim: &mut bool, target: Rect) -> Rect { /// Mask overlays are evaluated from the same mask alpha as the full render; the other diagnostic /// overlays either need whole-frame context or deliberately replace the loupe. pub(crate) fn overlay_supports_window(overlay: lightcraft_pipeline::Overlay) -> bool { - matches!(overlay, lightcraft_pipeline::Overlay::None | lightcraft_pipeline::Overlay::Mask { .. }) + overlay.per_pixel() } /// What a window render of the loupe needs to know about the view it belongs to. @@ -444,7 +444,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let look = d.hash64(); let overlay = view_overlay(app, &d); // Diagnostic views that need whole-frame context, soft proofing, or reads too far for one - // window still render the whole frame at the size it is drawn. A mask overlay is window-safe. + // window still render the whole frame at the size it is drawn. Per-pixel ones (a mask, + // clipping) are window-safe. let sizes = crate::region::ViewSizes { drawn_long, canvas_long: canvas.width().max(canvas.height()) * ppp, @@ -1118,13 +1119,20 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap } } -/// The diagnostic overlay the loupe shows (the selected mask, Point Color's visualized range, -/// Visualize Spots). +/// The diagnostic overlay the loupe shows (an Alt-drag preview, the selected mask, Point Color's +/// visualized range, Visualize Spots). pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay { use lightcraft_pipeline::{MaskView, Overlay}; if app.ui.fullscreen { return Overlay::None; } + // Lightroom's temporary previews: clipping, greyscale, sharpening detail / mask + if app.ui.right == RightPanel::Edit + && app.ui.alt_held + && let Some(o) = app.ui.dragging_control.as_deref().and_then(Overlay::for_control) + { + return o; + } if app.ui.right == RightPanel::Masking && app.ui.mask_overlay && let Some(m) = app.session.active_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b76066d55b..839bfa7a4f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -603,6 +603,10 @@ pub struct UiState { /// The develop control whose slider is being dragged (geometry sliders show a grid). #[serde(skip)] pub dragging_control: Option, + /// Alt (Option on macOS) is held this frame: a dragged Edit slider shows its temporary + /// preview ([`lightcraft_pipeline::Overlay::for_control`]). + #[serde(skip)] + pub alt_held: bool, pub search: String, /// Focus the search field on the next frame (Edit → Find…). #[serde(skip)] @@ -1074,6 +1078,7 @@ impl Default for UiState { unnamed_focus: false, hidden_locations: Vec::new(), dragging_control: None, + alt_held: false, external_edits: Vec::new(), was_focused: true, auto_import_at: 0.0, diff --git a/crates/ui-egui/src/tests_panels.rs b/crates/ui-egui/src/tests_panels.rs index 25edf3bfab..a7accb362b 100644 --- a/crates/ui-egui/src/tests_panels.rs +++ b/crates/ui-egui/src/tests_panels.rs @@ -2141,3 +2141,40 @@ fn right_click_add_to_album_offers_a_new_album_when_there_is_none() { assert!(trip.photos.contains(&photo), "the right-clicked photo is in it: {:?}", trip.photos); assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); } + +#[test] +fn alt_while_dragging_an_edit_slider_shows_its_preview() { + use crate::state::RightPanel; + use lightcraft_pipeline::Overlay; + let mut h = demo([1400.0, 900.0], json!({"view": "detail", "right": "edit"})); + let id = h.app.session.active().expect("active photo"); + let d = (*h.app.session.develop_of(id).unwrap_or_default()).clone(); + let view = |h: &Headless| crate::panels::detail::view_overlay(&h.app, &d); + assert_eq!(h.app.ui.right, RightPanel::Edit); + h.app.ui.dragging_control = Some("light.blacks".into()); + assert_eq!(view(&h), Overlay::None, "dragging without Alt shows the photo"); + h.app.ui.alt_held = true; + assert_eq!(view(&h), Overlay::ClipShadows); + for (c, o) in [ + ("light.whites", Overlay::ClipHighlights), + ("light.exposure", Overlay::ClipHighlights), + ("detail.sharpenAmount", Overlay::Grayscale), + ("detail.sharpenRadius", Overlay::SharpenDetail), + ("detail.sharpenMasking", Overlay::SharpenMask), + ("light.contrast", Overlay::None), + ] { + h.app.ui.dragging_control = Some(c.into()); + assert_eq!(view(&h), o, "{c}"); + } + // Alt alone (no drag) or released mid-drag: back to the photo + h.app.ui.dragging_control = None; + assert_eq!(view(&h), Overlay::None); + h.app.ui.dragging_control = Some("light.whites".into()); + h.app.ui.alt_held = false; + assert_eq!(view(&h), Overlay::None); + // the Masking panel's local Blacks slider is not a global clipping preview + h.app.ui.alt_held = true; + h.app.ui.right = RightPanel::Masking; + h.app.ui.dragging_control = Some("light.blacks".into()); + assert_eq!(view(&h), Overlay::None); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 77ae26e4c5..75d2aed250 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-11 · **Change:** minor (rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Alt/Option-drag previews, LR-EDIT-DETAIL-SHARPEN to 🟡; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **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 @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 15 | 1 | 1 | 0 | 8/9 (89%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 43 | 2 | 3 | 1 | 28/28 (100%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 42 | 3 | 3 | 1 | 27/28 (96%) | 13/14 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 9 | 0 | 0 | 1 | 6/6 (100%) | 3/3 (100%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 76 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) | | Lightroom Classic extras | 34 | 16 | 35 | 8 | — | 24/26 (92%) | -| **Total** | 407 | 50 | 73 | 35 | 192/200 (96%) | 145/157 (92%) | +| **Total** | 406 | 51 | 73 | 35 | 191/200 (96%) | 145/157 (92%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.5%** of 530 in-scope rows — P0 98.0% of 200 · P1 95.2% of 157 · P2 49.7% of 172. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.4%** of 530 in-scope rows — P0 97.8% of 200 · P1 95.2% of 157 · P2 49.7% of 172. ## Top gaps and shortcut notes @@ -177,12 +177,12 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-AUTO | Auto settings | P0 | ✅ | `cmd:develop.auto`, `crates/pipeline/src/auto.rs` | a Lightroom-like recipe calibrated black-box on Lightroom's Auto results for 24 Sony raws: Exposure from the scene's scene-linear log-average luminance (Lightroom's observed slope, -0.41 EV per EV), Highlights -66 and Shadows +52 (Lightroom's average Auto values), Contrast +68 and Vibrance +30 fitted on our scales. Held out one photo at a time: on the 16 photos whose start Sony's DRO doesn't brighten, a median dE76 of 6.4 from Lightroom's Auto results against 8.3 unedited; on all 24, 7.7 against 7.9 (issues #318, #209). Calibrated on Sony files only; Whites and Blacks stay 0 | | LR-EDIT-BW | Black & white | P0 | ✅ | `cmd:develop.treatment` | | | LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on); see Q. HDR | -| LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | | +| LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | -| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp | -| LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632) | -| LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites` | | -| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks` | | +| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp. Alt/Option-drag shows highlight clipping | +| LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | +| LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | +| LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | | LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*` | | | LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | | @@ -203,7 +203,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | -| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | ✅ | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking` | no Alt-drag mask preview | +| LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | 🟡 | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Amount and Masking work; Radius and Detail are stored (XMP round trip) but do not change the render yet (the band is a fixed 0.18 % of the long edge). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | | | LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, opt-in weights, pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lightcraft-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922) | @@ -787,6 +787,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-11 | minor | Alt/Option-drag previews on Exposure, Highlights, Shadows, Whites, Blacks and Sharpening (issue #937); LR-EDIT-DETAIL-SHARPEN ✅ → 🟡: Radius and Detail don't change the render | | 2026-10-11 | minor | KEY-SLIDER-TYPE: honor immediate Return/Escape and keep typed keys in the value editor; add regression references | | 2026-10-11 | minor | LR-PROF-CAMERACOLOR: raws with a black-and-white camera JPEG take its tone curve (issue #577) | | 2026-10-11 | minor | LR-VIEW-ZOOM and LR-VIEW-COMPARE: Compare and Reference are sharp at 1:1 (zoom windows per pane, two originals kept decoded while they are open); statuses unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 44aa1c7036..06a728db47 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (zoom row: Compare and Reference sharp at 1:1) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Alt/Option-drag slider previews) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 How LightCraft's interaction compares with Lightroom's: views, panels, tools and handles, modifier keys, shortcuts, zoom, context menus and feel. Rows for individual menu items and shortcuts live in @@ -67,6 +67,14 @@ under the UI command that wraps it (a no-op error); the UI command now wins. **Library culling (KEYC-RATING):** `0–5`, `6–9` and `P/X/U` reach egui on macOS even when displayed in the native menu (adapted from PR #261; issue #283). `Shift+0–9` applies and advances once; `Shift+P` picks and advances in Photo Grid / Square Grid and retains Presets elsewhere. See [library shortcuts](library-shortcuts.md) for the verified Classic mapping and regression coverage. Remaining Classic gaps: rating `[` / `]`, flag cycling and filter-bar keys. +**Alt/Option-drag previews (issue #937):** hold Alt (Option on macOS) while dragging an Edit slider, before or during +the drag. Exposure, Highlights and Whites show highlight clipping (black, clipped channels in their colour, white where +all three clip); Shadows and Blacks show shadow clipping (white, black where all three clip). Sharpening Amount shows +greyscale, Radius and Detail the detail band sharpening amplifies, Masking the mask (white = sharpened). Releasing the +key or the slider brings the photo back; the edit and its history are unchanged. Not yet: Noise Reduction, mask range +sliders and the Masking panel's local sliders. On Linux desktops that move windows with Alt+drag (KDE Plasma's +default, also some GNOME / Xfce setups) the window manager takes the drag first: set its window-move modifier to Meta. + **Still missing / broken:** - No command yet: F1 help (verify the rest of the old list: full screen, settings, stacks, visualize spots and merges have commands now). @@ -78,5 +86,6 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | Date | Change | Summary | |---|---|---| +| 2026-10-11 | minor | Alt/Option-drag slider previews (clipping, sharpening) and the Linux window-manager note | | 2026-10-11 | minor | Zoom row: Compare and Reference get zoom windows; what remains of LR-VIEW-ZOOM is overlays and soft proofing | | 2026-10-10 | major | Created: measured command and shortcut counts, assessment by area, estimates; moved the shortcut conflicts section here from the checklist | diff --git a/docs/whats-new.md b/docs/whats-new.md index fb8b285a38..5107eae27e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -11,6 +11,17 @@ - Lossy JPEG XL files in Display P3 or Rec. 2020 now open in their real colours; saturated colours used to come in noticeably duller. +### Alt/Option-drag previews +- Hold Alt (Option on macOS) while dragging Exposure, Highlights or Whites to see which areas clip to white: the + photo turns black, fully clipped areas show white and areas clipped in one or two channels show those channels' + colour. Shadows and Blacks do the same for clipping to black, on white (issue #937). +- In Detail ▸ Sharpening the same key shows Amount in greyscale, Radius and Detail as the fine detail being + sharpened, and Masking as the mask: white is sharpened, black is protected. Radius and Detail don't change the + render yet, so their preview stays the same while you drag them. +- The preview lasts while the key and the slider are held, and never changes the edit, its history or exports. +- Linux: KDE Plasma (and some other desktops) move windows with Alt+drag. If Alt+drag moves the window instead, + set the window manager's move modifier to Meta. + ### Open Library knows a Lightroom catalog - Choosing a Lightroom Classic catalog folder in File → Open Library… (or one of its `Previews.lrdata` / `.lrcat-data` folders, or the `.lrcat`) no longer makes an empty LightCraft library inside it (issue #891). The From 86f4bde867d1ffa44519b23d39733eac015e6e52 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 12 Oct 2026 13:53:24 +0200 Subject: [PATCH 0002/1092] LR-VIEW-CLIPPING: Alt-drag previews keep the histogram on profiled displays; NR previews (#937) Folds the parts of #995 that #999 lacked into #999: - engine/media.rs: with a display profile, a diagnostic view keeps the photo's histogram (taken before the overlay is drawn) and stays out of the view cache; the clipping previews test sRGB values and are converted for the display afterwards. Before, holding Alt on a P3 display swapped the histogram for the clipping view's (mean luma 0.59 -> 0.999). - Noise Reduction Luminance / Detail / Contrast show greyscale while Alt-dragged (Overlay::for_control). - Tests: diagnostic_views_keep_the_photos_histogram (P3 display; fails without the media.rs change), an end-to-end headless drag that presses and releases Alt mid-drag and checks the loupe pixels (tests_alt_preview.rs), and every Alt-mapped id is a real control. - Docs: NR row, What's New and ui-parity note; parity summary refreshed. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/display.rs | 19 +++++++ crates/engine/src/media.rs | 15 +++++- crates/pipeline/src/visualize.rs | 31 ++++++++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/tests_alt_preview.rs | 71 +++++++++++++++++++++++++ docs/parity-checklist.md | 6 +-- docs/ui-parity.md | 7 +-- docs/whats-new.md | 3 +- 8 files changed, 145 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/tests_alt_preview.rs diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index f47e099b65..34840e46d3 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -152,6 +152,25 @@ mod tests { } } + /// Alt-drag previews on a profiled display (issue #937): the histogram stays the photo's (not + /// the preview's), and the clipping view is tested and drawn in sRGB, so it stays black and white. + #[test] + fn diagnostic_views_keep_the_photos_histogram() { + use lightcraft_pipeline::Overlay; + let mut session = crate::Session::with_demo(); + let id = session.visible_cloned()[0]; + let d = std::sync::Arc::new(p3()); + let mut run = |o| session.loupe_job(id, 320, 240, true).unwrap().with_display(Some(d.clone())).with_overlay(o).run().rendered.unwrap(); + let plain = run(Overlay::None); + let clip = run(Overlay::ClipShadows); + let (a, b) = (plain.histogram.mean_luma(), clip.histogram.mean_luma()); + assert!((a - b).abs() < 0.02, "the photo's histogram: {a} vs {b}"); + let px = &clip.image.data; + // (the profile may round white to 254) + let binary = px.iter().filter(|p| p[..3].iter().all(|v| *v <= 2 || *v >= 253)).count(); + assert!(binary as f64 > 0.99 * px.len() as f64, "{binary} of {}", px.len()); + } + #[test] fn load_reports_and_rejects() { let dir = std::env::temp_dir().join(format!("lightcraft-display-{}", std::process::id())); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 6f6f0359c4..cd26f222d3 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -838,11 +838,24 @@ impl RenderJob { // Thumbnails (many small jobs side by side) stay on the CPU; views and exports use // the GPU when there is one. let gpu = self.cache.is_none(); - let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &self.request, self.stages.as_deref(), gpu); + // a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then + // converted for the display below + let clip_view = self.request.overlay.is_clipping(); + let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request }; + let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu); // for a display profile: the image goes to the display's values, the histogram // and the cached view preview stay sRGB let mut srgb = None; let display = match (&self.display, self.request.display) { + // a diagnostic view: the histogram stays the photo's (taken before the overlay + // was drawn), and nothing goes to the view cache + (Some(d), Some(_)) if self.request.overlay != lightcraft_pipeline::Overlay::None => { + let converted = if clip_view { d.profile.from_srgb(&mut rendered.image) } else { d.profile.correct(&mut rendered.image) }; + if let Err(e) = converted { + log::warn!("display profile: {e}"); + } + Some(d.id()) + } (Some(d), Some(_)) => { let keep = self.view_cache.is_some() && self.request.quality == Quality::Full; let (s, h) = crate::display::finish_render(&mut rendered.image, d, keep); diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index baa992fd17..50b959332d 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -185,13 +185,19 @@ impl Overlay { match id { "light.exposure" | "light.highlights" | "light.whites" => Some(Overlay::ClipHighlights), "light.shadows" | "light.blacks" => Some(Overlay::ClipShadows), - "detail.sharpenAmount" => Some(Overlay::Grayscale), + "detail.sharpenAmount" | "detail.nrLuminance" | "detail.nrDetail" | "detail.nrContrast" => Some(Overlay::Grayscale), "detail.sharpenRadius" | "detail.sharpenDetail" => Some(Overlay::SharpenDetail), "detail.sharpenMasking" => Some(Overlay::SharpenMask), _ => None, } } + /// The clipping previews, which test the sRGB values the histogram counts (a render for a + /// display profile draws them in sRGB, then converts). + pub fn is_clipping(self) -> bool { + matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights) + } + /// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]). pub fn reads_detail(self) -> bool { matches!(self, Overlay::SharpenDetail | Overlay::SharpenMask) @@ -601,7 +607,30 @@ mod tests { assert_eq!(Overlay::for_control("detail.sharpenAmount"), Some(Overlay::Grayscale)); assert_eq!(Overlay::for_control("detail.sharpenDetail"), Some(Overlay::SharpenDetail)); assert_eq!(Overlay::for_control("detail.sharpenMasking"), Some(Overlay::SharpenMask)); + for c in ["detail.nrLuminance", "detail.nrDetail", "detail.nrContrast"] { + assert_eq!(Overlay::for_control(c), Some(Overlay::Grayscale), "{c}"); + } + assert_eq!(Overlay::for_control("detail.nrColor"), None); assert_eq!(Overlay::for_control("light.contrast"), None); + // every mapped id is a real control (a rename would silently drop its preview) + for c in [ + "light.exposure", + "light.highlights", + "light.whites", + "light.shadows", + "light.blacks", + "detail.sharpenAmount", + "detail.sharpenRadius", + "detail.sharpenDetail", + "detail.sharpenMasking", + "detail.nrLuminance", + "detail.nrDetail", + "detail.nrContrast", + ] { + assert!(lightcraft_develop::controls::find(c).is_some(), "{c}"); + assert!(Overlay::for_control(c).is_some(), "{c}"); + } + assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping()); let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask]; for o in all { let (k, v) = o.to_parts(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5dc9651299..be0b6653e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,6 +44,8 @@ mod tests_activity; #[cfg(test)] mod tests_album_picker; #[cfg(test)] +mod tests_alt_preview; +#[cfg(test)] mod tests_appearance; #[cfg(test)] mod tests_before_after; diff --git a/crates/ui-egui/src/tests_alt_preview.rs b/crates/ui-egui/src/tests_alt_preview.rs new file mode 100644 index 0000000000..7a212869fc --- /dev/null +++ b/crates/ui-egui/src/tests_alt_preview.rs @@ -0,0 +1,71 @@ +//! Headless test of the Alt-drag previews (issue #937) through real input: a slider drag, Alt +//! (Option) pressed and released during it, and the loupe's pixels at each step. + +use std::time::Duration; + +use egui::{Event, Modifiers, PointerButton}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn detail() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 1400.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + if !h.app.ui.section_open("light") { + h.app.ui.toggle_section("light"); + } + h.app.renderer.keep_pixels = true; + h.settle(SETTLE); + h +} + +/// Share of the loupe render's pixels whose channels are all 0 or 255 (a clipping view). +fn binary_share(h: &Headless) -> f64 { + let t = h.app.renderer.textures.get(&crate::render::Slot::Main).expect("loupe render"); + let px = &t.pixels.as_ref().expect("pixels kept").pixels; + let binary = px.iter().filter(|c| [c.r(), c.g(), c.b()].iter().all(|v| *v == 0 || *v == 255)).count(); + binary as f64 / px.len().max(1) as f64 +} + +#[test] +fn alt_during_a_blacks_drag_shows_shadow_clipping_until_released() { + let mut h = detail(); + assert!(binary_share(&h) < 0.5, "the photo itself is no clipping view"); + let track = h.app.widgets.iter().find(|(w, _)| w == "slider:light.blacks").map(|(_, r)| *r).expect("Blacks slider on screen"); + let from = track.center(); + let before = h.app.session.develop_of(h.app.session.active().expect("photo")).expect("develop").light.blacks; + // a plain drag to the left, button held: the photo as usual + h.app.synthetic.push(Event::PointerMoved(from)); + h.app.synthetic.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + for i in 1..=8 { + h.app.synthetic.push(Event::PointerMoved(from - egui::vec2(6.0 * i as f32, 0.0))); + } + h.settle(SETTLE); + assert_eq!(h.app.ui.dragging_control.as_deref(), Some("light.blacks")); + assert!(binary_share(&h) < 0.5, "no preview without Alt"); + // Alt pressed mid-drag: the shadow clipping view + h.app.synthetic.push(Event::ModifiersChanged(Modifiers::ALT)); + h.settle(SETTLE); + assert!(binary_share(&h) > 0.99, "the clipping view: {}", binary_share(&h)); + // Alt released: the photo again, the drag still on + h.app.synthetic.push(Event::ModifiersChanged(Modifiers::NONE)); + h.settle(SETTLE); + assert!(binary_share(&h) < 0.5, "the photo is back"); + h.app.synthetic.push(Event::PointerButton { + pos: from - egui::vec2(48.0, 0.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + h.settle(SETTLE); + assert_eq!(h.app.ui.dragging_control, None); + let after = h.app.session.develop_of(h.app.session.active().expect("photo")).expect("develop").light.blacks; + assert!(after < before, "the drag itself still moved Blacks: {before} → {after}"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 75d2aed250..cfd9248dfb 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 76 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) | | Lightroom Classic extras | 34 | 16 | 35 | 8 | — | 24/26 (92%) | -| **Total** | 406 | 51 | 73 | 35 | 191/200 (96%) | 145/157 (92%) | +| **Total** | 407 | 52 | 72 | 35 | 192/201 (96%) | 145/157 (92%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.4%** of 530 in-scope rows — P0 97.8% of 200 · P1 95.2% of 157 · P2 49.7% of 172. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.5%** of 531 in-scope rows — P0 97.8% of 201 · P1 95.2% of 157 · P2 50.0% of 172. ## Top gaps and shortcut notes @@ -204,7 +204,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | | LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | 🟡 | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Amount and Masking work; Radius and Detail are stored (XMP round trip) but do not change the render yet (the band is a fixed 0.18 % of the long edge). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | -| LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | | +| LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | | | LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, opt-in weights, pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lightcraft-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; closing the model setup without installing turns the switch back off (#922) | | LR-EDIT-DETAIL-RAWDETAILS | Improved demosaic toggle | P2 | ⬜ | | | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 06a728db47..6782cc6b3f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -70,9 +70,10 @@ under the UI command that wraps it (a no-op error); the UI command now wins. **Alt/Option-drag previews (issue #937):** hold Alt (Option on macOS) while dragging an Edit slider, before or during the drag. Exposure, Highlights and Whites show highlight clipping (black, clipped channels in their colour, white where all three clip); Shadows and Blacks show shadow clipping (white, black where all three clip). Sharpening Amount shows -greyscale, Radius and Detail the detail band sharpening amplifies, Masking the mask (white = sharpened). Releasing the -key or the slider brings the photo back; the edit and its history are unchanged. Not yet: Noise Reduction, mask range -sliders and the Masking panel's local sliders. On Linux desktops that move windows with Alt+drag (KDE Plasma's +greyscale, Radius and Detail the detail band sharpening amplifies, Masking the mask (white = sharpened); luminance Noise +Reduction (Luminance, Detail, Contrast) shows greyscale. Releasing the key or the slider brings the photo back; the +edit, its history and the histogram are unchanged (on a profiled display too). Not yet: mask range sliders and the +Masking panel's local sliders. On Linux desktops that move windows with Alt+drag (KDE Plasma's default, also some GNOME / Xfce setups) the window manager takes the drag first: set its window-move modifier to Meta. **Still missing / broken:** diff --git a/docs/whats-new.md b/docs/whats-new.md index 5107eae27e..8d2329dbc3 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -17,7 +17,8 @@ colour. Shadows and Blacks do the same for clipping to black, on white (issue #937). - In Detail ▸ Sharpening the same key shows Amount in greyscale, Radius and Detail as the fine detail being sharpened, and Masking as the mask: white is sharpened, black is protected. Radius and Detail don't change the - render yet, so their preview stays the same while you drag them. + render yet, so their preview stays the same while you drag them. Noise Reduction's Luminance, Detail and Contrast + show the photo in greyscale. - The preview lasts while the key and the slider are held, and never changes the edit, its history or exports. - Linux: KDE Plasma (and some other desktops) move windows with Alt+drag. If Alt+drag moves the window instead, set the window manager's move modifier to Meta. From 55e7c335fd9170302e89f86bdccbe84884aec9a7 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:36:05 +0200 Subject: [PATCH 0003/1092] Do not read a sibling's shared stem sidecar for a non-owner photo (#1523) --- crates/engine/src/cmd/query.rs | 2 +- crates/engine/src/sidecar.rs | 50 ++++++++++++++++++++++++++++++---- crates/engine/src/sync.rs | 24 ++++++++-------- crates/engine/src/tests_xmp.rs | 30 ++++++++++++++++++++ 4 files changed, 88 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index 2e0b6f1579..5e02f0967d 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -130,7 +130,7 @@ pub fn specs() -> Vec { .map(|r| json!({"group": r.group, "tag": r.tag, "name": r.name, "value": r.value})) .collect(); // XMP: the sidecar if there is one, else the file's own packet - let packet = crate::sidecar::read_packet(path, ph.kind, s.sidecar_naming(ph.id)).map(|(x, _)| x).or_else(|| lightcraft_meta::embedded(&bytes).xmp); + let packet = crate::sidecar::read_packet(path, ph.kind, s.sidecar_lookup(ph.id)).map(|(x, _)| x).or_else(|| lightcraft_meta::embedded(&bytes).xmp); let xmp: Vec = packet .and_then(|x| lightcraft_meta::parse_xmp(&x).ok()) .map(|d| d.properties.into_iter().filter(|(k, _)| !k.starts_with("lc:")).map(|(k, v)| json!({"name": k, "value": v.join("; ")})).collect()) diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 9aaf7e937a..9ae8122e74 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -62,12 +62,27 @@ pub fn sidecar_path(original: &str, naming: SidecarNaming) -> PathBuf { } } +/// Where to look for a catalogued photo's sidecar. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SidecarLookup { + pub naming: SidecarNaming, + /// Whether a shared stem sidecar (`IMG_0001.xmp`) may be read for this photo. False when + /// another catalogued file with the same stem owns it (see [`Session::sidecar_naming`]). + pub stem_ok: bool, +} + /// An existing sidecar for `original`: the preferred naming first, then the other one (also /// accepting an upper-case `.XMP`). pub fn find_sidecar(original: &str, naming: SidecarNaming) -> Option { - let other = if naming == SidecarNaming::Stem { SidecarNaming::Full } else { SidecarNaming::Stem }; - [naming, other] + find_sidecar_in(original, SidecarLookup { naming, stem_ok: true }) +} + +/// [`find_sidecar`] for a catalogued photo: never a stem sidecar that a sibling owns. +pub fn find_sidecar_in(original: &str, lookup: SidecarLookup) -> Option { + let other = if lookup.naming == SidecarNaming::Stem { SidecarNaming::Full } else { SidecarNaming::Stem }; + [lookup.naming, other] .into_iter() + .filter(|n| *n != SidecarNaming::Stem || lookup.stem_ok) .flat_map(|n| { let p = sidecar_path(original, n); let upper = p.with_extension("XMP"); @@ -458,8 +473,8 @@ fn file_path(p: &Photo) -> Option<&str> { } /// The XMP packet that describes a photo on disk: its sidecar, else (raw/DNG) the embedded XMP. -pub fn read_packet(original: &str, kind: MediaKind, naming: SidecarNaming) -> Option<(String, PathBuf)> { - if let Some(sc) = find_sidecar(original, naming) +pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Option<(String, PathBuf)> { + if let Some(sc) = find_sidecar_in(original, lookup) && let Ok(s) = std::fs::read_to_string(&sc) { return Some((s, sc)); @@ -512,6 +527,12 @@ impl StemOwners { _ => naming, } } + + /// [`StemOwners::naming`], plus whether the stem sidecar may be read for `p`. + fn lookup(&self, p: &Photo, naming: SidecarNaming) -> SidecarLookup { + let stem_ok = file_path(p).is_none_or(|path| self.0.get(&stem_key(path)).is_none_or(|owner| *owner == p.id)); + SidecarLookup { naming: self.naming(p, naming), stem_ok } + } } impl Session { @@ -531,6 +552,25 @@ impl Session { .collect() } + /// [`Session::sidecar_naming`] and the stem-sidecar ownership, for reading `ids`' sidecars. + pub fn sidecar_lookups(&self, ids: &[PhotoId]) -> Vec { + let owners = StemOwners::of(&self.catalog); + ids.iter() + .map(|id| match self.catalog.photo(*id) { + Some(p) => owners.lookup(p, self.xmp.naming), + None => SidecarLookup { naming: self.xmp.naming, stem_ok: true }, + }) + .collect() + } + + pub fn sidecar_lookup(&self, id: PhotoId) -> SidecarLookup { + let owners = StemOwners::of(&self.catalog); + match self.catalog.photo(id) { + Some(p) => owners.lookup(p, self.xmp.naming), + None => SidecarLookup { naming: self.xmp.naming, stem_ok: true }, + } + } + pub fn sidecar_naming(&self, id: PhotoId) -> SidecarNaming { match self.catalog.photo(id) { Some(p) if self.xmp.naming == SidecarNaming::Stem => StemOwners::of(&self.catalog).naming(p, self.xmp.naming), @@ -590,7 +630,7 @@ impl Session { pub fn read_sidecar_op_with_warnings(&self, id: PhotoId) -> Result)>> { let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?; let Some(orig) = file_path(p) else { return Ok(None) }; - let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_naming(id)) else { return Ok(None) }; + let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_lookup(id)) else { return Ok(None) }; let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?; let mut warnings = sc.warnings.clone(); for warning in &mut warnings { diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 0a00a59abd..3d091d5e2f 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -46,7 +46,7 @@ use serde::Serialize; use crate::import::{ImportCandidate, ImportMode, ImportOptions, ScanInput, ScanProgress}; use crate::media::ProbeInfo; -use crate::sidecar::SidecarNaming; +use crate::sidecar::SidecarLookup; use crate::{EngineError, Result, Session}; /// The largest XMP sidecar read when looking for metadata updates; a bigger one is skipped. @@ -75,7 +75,7 @@ pub struct SyncInput { folder: String, scan: ScanInput, /// The library's photos in the folder, each with how its sidecar is named. - photos: Vec<(Arc, SidecarNaming)>, + photos: Vec<(Arc, SidecarLookup)>, /// For the colour label names a sidecar may use. labels: Catalog, } @@ -176,7 +176,7 @@ impl SyncInput { if !disk && (lightcraft_catalog::folders::is_disk_root(path) || crate::cmd::library::covers_other_disks(s, path, &ids)) { return Err(invalid(format!("{path} is a whole disk or holds disks: pass `disk: true` to synchronize it"))); } - let namings = s.sidecar_namings(&ids); + let namings = s.sidecar_lookups(&ids); let photos = ids.iter().zip(namings).filter_map(|(id, naming)| s.catalog.photo(*id).map(|p| (Arc::clone(p), naming))).collect(); let (scan, _) = ScanInput::new(s, &[path.to_string()]); Ok(SyncInput { folder: path.to_string(), scan, photos, labels: s.catalog.clone() }) @@ -327,7 +327,7 @@ enum Check { News, } -fn check_photo(p: &Photo, naming: SidecarNaming, labels: &Catalog) -> Check { +fn check_photo(p: &Photo, naming: SidecarLookup, labels: &Catalog) -> Check { let Some(file) = crate::cmd::missing::checked_path(p) else { return Check::Nothing }; if !Path::new(file).exists() { Check::Missing @@ -340,11 +340,11 @@ fn check_photo(p: &Photo, naming: SidecarNaming, labels: &Catalog) -> Check { /// [`check_photo`] for each photo, in order, on several threads (each file is a wait on the /// disk, not work for the CPU). Photos not reached before a cancel count as nothing found. -fn check_photos(photos: &[(Arc, SidecarNaming)], labels: &Catalog, progress: &SyncProgress) -> Vec { +fn check_photos(photos: &[(Arc, SidecarLookup)], labels: &Catalog, progress: &SyncProgress) -> Vec { use std::sync::atomic::Ordering::Relaxed; progress.to_check.store(photos.len(), Relaxed); let cancel = &progress.files.cancel; - let check = |p: &Photo, naming: SidecarNaming| { + let check = |p: &Photo, naming: SidecarLookup| { let c = check_photo(p, naming, labels); progress.checked.fetch_add(1, Relaxed); c @@ -413,9 +413,9 @@ impl Session { /// Whether `p`'s XMP sidecar file was saved after the library last had its say about the photo /// (imported, or edited here) and says something the library doesn't. -fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming) -> bool { +fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarLookup) -> bool { let Source::File { path } = &p.source else { return false }; - let Some(file) = crate::sidecar::find_sidecar(path, naming) else { return false }; + let Some(file) = crate::sidecar::find_sidecar_in(path, naming) else { return false }; let Ok(meta) = std::fs::metadata(&file) else { return false }; if meta.len() > MAX_SIDECAR_BYTES { return false; @@ -464,7 +464,7 @@ pub struct SyncWork { moved: Vec, missing: Vec, /// (photo, its file, how its sidecar is named) - sidecars: Vec<(PhotoId, String, SidecarNaming, crate::crs::Target)>, + sidecars: Vec<(PhotoId, String, SidecarLookup, crate::crs::Target)>, } /// The catalog half of a synchronize (see [`SyncJob`]). @@ -512,7 +512,7 @@ impl SyncJob { }; let now = import.as_ref().map_or_else(|| (s.clock)(), |(j, _)| j.now().to_string()); let sidecars = if choice.read_metadata { - let namings = s.sidecar_namings(&metadata.iter().map(|m| PhotoId(m.id)).collect::>()); + let namings = s.sidecar_lookups(&metadata.iter().map(|m| PhotoId(m.id)).collect::>()); metadata .into_iter() .zip(namings) @@ -604,8 +604,8 @@ impl SyncWork { } /// Read and parse photo file `path`'s XMP sidecar file. -fn read_sidecar(path: &str, naming: SidecarNaming, target: crate::crs::Target) -> std::result::Result { - let file = crate::sidecar::find_sidecar(path, naming).ok_or_else(|| "no XMP sidecar".to_string())?; +fn read_sidecar(path: &str, naming: SidecarLookup, target: crate::crs::Target) -> std::result::Result { + let file = crate::sidecar::find_sidecar_in(path, naming).ok_or_else(|| "no XMP sidecar".to_string())?; let len = std::fs::metadata(&file).map_err(|e| format!("{}: {e}", file.display()))?.len(); if len > MAX_SIDECAR_BYTES { return Err(format!("{}: too large for an XMP sidecar", file.display())); diff --git a/crates/engine/src/tests_xmp.rs b/crates/engine/src/tests_xmp.rs index 58d0d7a149..d801676389 100644 --- a/crates/engine/src/tests_xmp.rs +++ b/crates/engine/src/tests_xmp.rs @@ -1209,3 +1209,33 @@ fn files_sharing_a_stem_get_their_own_sidecars() { let _ = std::fs::remove_dir_all(&src); let _ = std::fs::remove_dir_all(&lib); } + +/// A file that shares its stem with another catalogued file never reads the stem sidecar the +/// other one owns, whichever naming the library uses. +#[test] +fn a_non_owner_does_not_read_its_siblings_stem_sidecar() { + let src = temp_dir("stem-read"); + let lib = temp_dir("stem-read-lib"); + write_png(&src.join("IMG_1.png"), 1); + let img = lightcraft_raster::Rgba8::from_fn(40, 24, |x, y| [(x * 6) as u8, (y * 9) as u8, 7, 255]); + let jpg = + crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Jpeg, ..Default::default() }).unwrap(); + std::fs::write(src.join("IMG_1.jpg"), jpg).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; + let (j, p) = (id(&s, "IMG_1.jpg"), id(&s, "IMG_1.png")); + s.execute("photo.rate", &json!({"ids": [j.0], "rating": 2})).unwrap(); + s.execute("photo.saveMetadataToFile", &json!({"ids": [j.0]})).unwrap(); + assert!(src.join("IMG_1.xmp").is_file()); + assert!(!src.join("IMG_1.png.xmp").exists()); + // the owner reads its packet; the other file has none of its own + assert!(s.read_sidecar_op(j).unwrap().is_some()); + assert!(s.read_sidecar_op(p).unwrap().is_none()); + s.xmp.naming = crate::sidecar::SidecarNaming::Full; + assert!(s.read_sidecar_op(j).unwrap().is_some()); + assert!(s.read_sidecar_op(p).unwrap().is_none()); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&lib); +} 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 0004/1092] 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 da49bb5f7fb4ff9a47398aefa900c8a28cfef1d5 Mon Sep 17 00:00:00 2001 From: harrisonoconnorhover <130776285+harrisonoconnorhover@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:45:35 -0400 Subject: [PATCH 0005/1092] CI: reconcile lint and known unsupported corpus expectations Simplify an equivalent slideshow bounds guard and remove an unnecessary closure drop from an export test for strict Rust 1.95 Clippy. Include the E-PL7 sample among known unsupported variants, matching the documented preview-only status; retain its format and embedded-preview checks. Generated with Codex. --- crates/engine/src/slide_overlay.rs | 2 +- crates/engine/src/tests_export.rs | 1 - crates/raw/tests/corpus.rs | 9 +++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/slide_overlay.rs b/crates/engine/src/slide_overlay.rs index 4097393353..a27f75d496 100644 --- a/crates/engine/src/slide_overlay.rs +++ b/crates/engine/src/slide_overlay.rs @@ -903,7 +903,7 @@ fn shadow(img: &mut Rgba8, tl: &crate::text::TextLayout, x: f64, y: f64, sigma: let my0 = (y - pad).floor().max(-pad); let mx1 = (x + tl.width as f64 + pad).ceil().min(iw + pad); let my1 = (y + tl.height as f64 + pad).ceil().min(ih + pad); - if !(mx1 > mx0 && my1 > my0) || !mx0.is_finite() || !my0.is_finite() { + if !(mx1 > mx0 && my1 > my0 && mx0.is_finite() && my0.is_finite()) { return; } let (w, h) = ((mx1 - mx0) as usize, (my1 - my0) as usize); diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 2f1a051168..e66090b39b 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -1038,7 +1038,6 @@ fn same_folder_as_original_refuses_photos_without_a_folder() { assert_eq!(f["photo"], id.0, "{f}"); assert!(f["error"].as_str().unwrap().contains("no folder on disk"), "{f}"); } - drop(write); assert!(written.is_empty(), "{written:?}"); // a photo on disk whose folder is gone (moved, an unplugged drive) diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index 31e62f7dcc..cb7f6791ae 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -16,10 +16,11 @@ fn corpus_root() -> PathBuf { /// Variants known not to decode yet (see the crate docs): matched against the lower-case file name. const KNOWN_UNSUPPORTED: &[&str] = &[ - "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. - "orf-olympus-em", // Olympus compressed ORF - "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 - "sraw", // Canon sRAW / mRAW + "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. + "orf-olympus-em", // Olympus compressed ORF + "orf-olympus-epl7.orf", // E-PL7 is preview-only too (docs/raw/coverage.tsv). + "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 + "sraw", // Canon sRAW / mRAW ]; #[test] From 47972900e7c37b52805e57f0945a5668dc7d6ae5 Mon Sep 17 00:00:00 2001 From: harrisonoconnorhover <130776285+harrisonoconnorhover@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:45:35 -0400 Subject: [PATCH 0006/1092] LRC-LIB-CATALOG-IMPORT: classify Lightroom video records Honor VIDEO when importing catalog records and repair older image-classified records on reimport with existing atomic, reversible operations. Preserve IDs, source facts, edits/history and album/stack membership. Cover native catalog import, type filtering, repair and Undo/Redo with synthetic SQLite regressions. Document the filter-only scope of issue #1940. Generated with Codex. --- crates/engine/src/lightroom_catalog.rs | 90 +++++++++++++++++++++++++- docs/gaps.md | 5 +- docs/lightroom-catalog-import.md | 5 ++ docs/parity-checklist.md | 5 +- 4 files changed, 100 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 777206bcb8..7e24a74ff7 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -763,6 +763,10 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, data: CatalogImport, contex } p }; + // Offline videos bypass file probing; Lightroom's format still identifies their kind. + if text(&src.image, "fileFormat").eq_ignore_ascii_case("VIDEO") { + p.kind = lightcraft_catalog::MediaKind::Video; + } ids.insert(src.source_id, p.id); index.photos.insert(identity(&data, src), p.id.0); let keep_develop = existing_id.is_some() && p.edited.is_some() && !update_existing; @@ -827,7 +831,14 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, data: CatalogImport, contex if copy_masters.contains(&src.source_id) { planned.insert(photo_id, p.clone()); } - if s.catalog.photo(p.id).is_some() { + if let Some(old) = s.catalog.photo(p.id) { + if old.kind != p.kind { + // Repair older imports with existing reversible operations. Removing just the + // record leaves album/stack membership intact; the enclosing batch is atomic. + let mut repaired = (**old).clone(); + repaired.kind = p.kind; + ops.extend([Op::RemovePhoto { id: p.id }, Op::AddPhoto { photo: Box::new(repaired) }]); + } if was_local && promoted.insert(p.id) { imported += 1; ops.push(Op::SetLocal { id: p.id, local: false }); @@ -1422,6 +1433,83 @@ mod tests { ] } + #[test] + fn native_video_import_is_visible_in_video_filter() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-video-filter-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("videos.lrcat"); + let mut tables = photo_tables((dir.to_str().unwrap(), "")); + tables[2].2[2] = SqlValue::Text("clip.MOV".into()); + tables[3].2[3] = SqlValue::Text("VIDEO".into()); + std::fs::write(&path, native_catalog(&tables)).unwrap(); + let mut s = crate::Session::new(); + let imported = s.execute("library.importLightroom", &json!({"path": path})).unwrap(); + let id = PhotoId(imported["mapping"]["1"].as_u64().unwrap()); + assert_eq!(s.catalog.photo(id).unwrap().kind, lightcraft_catalog::MediaKind::Video); + s.execute("library.filter", &json!({"kind": "video"})).unwrap(); + assert_eq!(s.visible(), &[id]); + s.execute("library.filter", &json!({"kind": "image"})).unwrap(); + assert!(s.visible().is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("library.filter", &json!({"kind": "video"})).unwrap(); + assert_eq!(s.visible(), &[id]); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn native_video_reimport_repairs_kind_without_losing_edits_or_memberships() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-video-reimport-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("videos.lrcat"); + let mut tables = photo_tables((dir.to_str().unwrap(), "")); + tables[2].2[2] = SqlValue::Text("clip.MOV".into()); + tables[3].2[3] = SqlValue::Text("VIDEO".into()); + std::fs::write(&path, native_catalog(&tables)).unwrap(); + let mut s = crate::Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut photo = + Photo::new(id, Source::File { path: dir.join("Photos/clip.MOV").to_string_lossy().into() }, "clip.MOV", "VIDEO", 1920, 1080, "before"); + photo.rating = 5; + photo.flag = Flag::Pick; + photo.file_size = 1234; + photo.content_hash = Some("existing-content".into()); + s.commit("Previous import", Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + let mut settings = lightcraft_develop::DevelopSettings::default(); + settings.light.exposure = 0.75; + s.set_develop(id, settings, "Personal edit").unwrap(); + let peer_id = s.catalog.alloc_photo_id(); + let peer = Photo::new(peer_id, Source::File { path: "/missing/peer.jpg".into() }, "peer.jpg", "JPEG", 20, 10, "before"); + s.commit("Peer", Op::AddPhoto { photo: Box::new(peer) }).unwrap(); + let mut album = Album::new(s.catalog.alloc_album_id(), "Personal album"); + album.photos = vec![id, peer_id]; + s.commit("Album", Op::AddAlbum { album: album.clone() }).unwrap(); + let stack = lightcraft_catalog::Stack { id: s.catalog.alloc_stack_id(), photos: vec![id, peer_id], collapsed: false }; + s.commit("Stack", Op::AddStack { stack: stack.clone() }).unwrap(); + let before = s.catalog.to_snapshot(); + let mut expected = (**s.catalog.photo(id).unwrap()).clone(); + expected.kind = lightcraft_catalog::MediaKind::Video; + s.execute("library.filter", &json!({"kind": "video"})).unwrap(); + assert!(s.visible().is_empty()); + let result = s.execute("library.importLightroom", &json!({"path": path})).unwrap(); + assert_eq!(result["mapping"]["1"], id.0); + assert_eq!(result["imported"], 0); + assert_eq!(result["preservedExistingEdits"], 1); + assert_eq!(s.catalog.photo(id).unwrap().as_ref(), &expected); + assert_eq!(s.visible(), &[id]); + let after = s.catalog.to_snapshot(); + assert_eq!(s.catalog.album(album.id), Some(&album)); + assert_eq!(s.catalog.stack(stack.id), Some(&stack)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.to_snapshot(), before); + assert!(s.visible().is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.to_snapshot(), after); + assert_eq!(s.visible(), &[id]); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn reads_native_sqlite_tables_without_lightroom_or_external_processes() { let bytes = native_catalog(&photo_tables(("/catalog/", ""))); diff --git a/docs/gaps.md b/docs/gaps.md index f11a74f7a0..c3d89b1576 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (gap 10: 515 of 1,446 models verified, ~84% of photographers on a verified body) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-16 · **Change:** patch (gap 13: imported video classification repaired) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -27,7 +27,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 545 of 1,446 Adobe models verified (38%), ~85% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 / F828 regression (#702), DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; AI denoise without shippable weights or X-Trans** | ENH rows 0%; denoise Bayer only, RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; nobody gets it out of the box | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | | 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) | -| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; offline record counts and destination are now shown in a lasting import result | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | +| 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | | 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) | | 15 | **Print module**: identity plate / watermark / page numbers / crop marks / photo info overlays, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) | | 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) | @@ -77,6 +77,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-16 | patch | Gap 13: catalog VIDEO records match the Videos filter, including after reimport of older records (#1940, filter issue only). Video playback, frame previews and folder-sync discovery remain outside this repair; no gap closed or counts changed. | | 2026-10-14 | minor | Gap 26: at 100k photos stack and album lookups are indexed, so an "In a Stack" or "Album" smart album counts in ~14 ms (was 0.6–2.7 s); open time unchanged | | 2026-10-14 | minor | Gap 10: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277) | | 2026-10-14 | minor | Gap 21: de, es, fr, ja and uk catalogs filled (97–99%); 55–90 h → 40–70 h | diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 5ad4383fdb..ed5426a812 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -34,6 +34,11 @@ edits are preserved by default; `updateExisting=true` explicitly replaces them. identity prevents reimport from duplicating virtual copies and collections. One undo step reverses catalog changes; any saved recovery archives remain available. +Records marked `VIDEO` in the source catalog appear in the **Videos** type filter, including +offline originals. Reimport also repairs the classification of videos imported as images by +older builds, preserving their IDs, edits and album/stack membership. This does not add video +playback, frame previews or video discovery through folder synchronization. + Before changing records, the importer attempts to save source image records, decoded XMP, verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 95dcd2aefc..7d6642ad3d 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-14 · **Change:** minor (integration batch 36: slideshow module, print-ready PDF fixes, local adjustment presets, Layout Image loupe overlay, Delete in an album removes from it, new languages Czech, Polish, Italian-ready catalogs; many rows' notes updated by their PRs) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** patch (Lightroom catalog video classification; statuses unchanged) · **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 @@ -698,7 +698,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `docs/lightroom-catalog-import.md` | read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `docs/lightroom-catalog-import.md` | read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders; VIDEO records match the Videos filter, with reimport repairing older image classification while keeping edits and memberships; a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/left.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Clear), the open library's name under My Photos and in the window title (issue #902); a library that can't be opened leaves the current one open; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests_keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-16 | patch | LRC-LIB-CATALOG-IMPORT: VIDEO records appear in the Videos filter; reimport repairs older classification with edits, memberships and undo preserved (#1940, filter issue only). Status and summary counts 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 (✅) | From f6fd65f6c1637ff82067852a5058018ad074c324 Mon Sep 17 00:00:00 2001 From: Michael Anderson Date: Sat, 17 Oct 2026 08:22:53 -0500 Subject: [PATCH 0007/1092] Never crash: Refuse an ERF or MEF whose raw strip runs past the file (#2119) --- crates/raw/src/vendor/erf.rs | 37 +++++++++++++++++++++++++++++++++++- crates/raw/src/vendor/mef.rs | 37 +++++++++++++++++++++++++++++++++++- docs/whats-new.md | 7 +++++++ 3 files changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/raw/src/vendor/erf.rs b/crates/raw/src/vendor/erf.rs index b9861ef386..7f88dae2af 100644 --- a/crates/raw/src/vendor/erf.rs +++ b/crates/raw/src/vendor/erf.rs @@ -95,8 +95,12 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { _ => Rect::new(0, 0, w, h), }; // the white balance is measured from the samples, so the header probe reads them too + // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it let chunks = info.chunks(bytes.len() as u64); - let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Erf strip outside file".into()))?; + let src = chunks + .first() + .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) + .ok_or_else(|| RawError::Corrupt("Erf strip outside file".into()))?; let mut d = vec![0u16; n]; unpack(src, &mut d); let white = super::white_from_data(&d, 12); @@ -196,4 +200,35 @@ mod tests { } } } + + /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). + fn declare(f: &mut [u8], rows: u32, strip_len: u32) { + let tiff = Tiff::parse(f).unwrap(); + let raw = &tiff.ifds[0].sub_ifds[0]; + let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] + .into_iter() + .map(|(tag, v)| { + let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); + (e.offset as usize, matches!(e.value, Value::Short(_)), v) + }) + .collect(); + for (at, short, v) in spots { + if short { + f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); + } else { + f[at..at + 4].copy_from_slice(&v.to_be_bytes()); + } + } + } + + #[test] + fn a_strip_longer_than_the_file_is_an_error() { + // #2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame + let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); + let mut f = sample(20, 2, &px); + declare(&mut f, 2000, 32 * 2000); + assert_eq!(crate::probe(&f), Some(RawFormat::Erf)); + assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); + assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); + } } diff --git a/crates/raw/src/vendor/mef.rs b/crates/raw/src/vendor/mef.rs index 207bc8871e..30993ad729 100644 --- a/crates/raw/src/vendor/mef.rs +++ b/crates/raw/src/vendor/mef.rs @@ -87,8 +87,12 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { None => Rect::new(0, 0, w, h), }; // the white balance is measured from the samples, so the header probe reads them too + // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it let chunks = info.chunks(bytes.len() as u64); - let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?; + let src = chunks + .first() + .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) + .ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?; let mut d = vec![0u16; n]; crate::unpack::unpack_msb(src, 12, &mut d); let white = super::white_from_data(&d, 12); @@ -184,4 +188,35 @@ mod tests { } } } + + /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). + fn declare(f: &mut [u8], rows: u32, strip_len: u32) { + let tiff = Tiff::parse(f).unwrap(); + let raw = &tiff.ifds[0].sub_ifds[0]; + let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] + .into_iter() + .map(|(tag, v)| { + let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); + (e.offset as usize, matches!(e.value, Value::Short(_)), v) + }) + .collect(); + for (at, short, v) in spots { + if short { + f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); + } else { + f[at..at + 4].copy_from_slice(&v.to_be_bytes()); + } + } + } + + #[test] + fn a_strip_longer_than_the_file_is_an_error() { + // #2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame + let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); + let mut f = sample(20, 2, &px); + declare(&mut f, 2000, 30 * 2000); + assert_eq!(crate::probe(&f), Some(RawFormat::Mef)); + assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); + assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); + } } diff --git a/docs/whats-new.md b/docs/whats-new.md index 97e1367a89..6d4a3fcbab 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,12 @@ # What's new in LightCraft +## 2026-10-17 + +### Short Epson and Mamiya raws are refused +- An Epson ERF or Mamiya MEF whose raw strip runs past the end of the file is now an error on import (issue #2119). + Before, the header probe trusted the declared strip length and sized its sample buffer from it, so a few KB of file + could make it allocate gigabytes. + ## 2026-10-14 ### Lightroom radial masks on the right side From 6a0ced426d32d55fed392a185358d1f4c115801f Mon Sep 17 00:00:00 2001 From: tylerphotos <93777540+tylerphotos@users.noreply.github.com> Date: Sun, 18 Oct 2026 08:03:05 -0500 Subject: [PATCH 0008/1092] LR-IMP-ADD-DIALOG: add import thumbnail-size slider Remember an independent 80-320 point size for import review thumbnails. Reflow the grid without changing candidate checks, request density-aware previews, and retain only nearby import textures and pending work. Add control-channel access, interaction and persistence regressions, and update the import guide, parity row and remaining loupe gap. This is the thumbnail-size portion of #2056; pre-import loupe remains separate. Correct Windows test portability issues exposed by the required gate: a Unix-only import, export path comparisons and folder widget path ids. Validation: cargo xtask ci; native control-channel acceptance including small/large sizes, selection, short-window layout and restart persistence. --- crates/catalog/src/store.rs | 1 + crates/engine/src/import.rs | 5 +- crates/engine/src/tests_export.rs | 10 +- crates/ui-egui/src/import.rs | 73 +++++++-- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 13 ++ crates/ui-egui/src/render.rs | 20 ++- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/tests_folder_drop.rs | 15 +- crates/ui-egui/src/tests_import_thumbnails.rs | 149 ++++++++++++++++++ docs/control-protocol.md | 6 + docs/gaps.md | 7 +- docs/parity-checklist.md | 5 +- docs/user/guides/import-photos.md | 2 +- 14 files changed, 282 insertions(+), 30 deletions(-) create mode 100644 crates/ui-egui/src/tests_import_thumbnails.rs diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 2f3dc4912b..a5976c14cc 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -244,6 +244,7 @@ impl Store for MemStore { #[cfg(test)] mod tests_staging { + #[cfg(unix)] use super::*; /// A link planted at a staging name (`.tmp`) is removed, never followed: the file it points to keeps its diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 9aa847b01f..e30137bbe3 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1544,8 +1544,9 @@ impl Session { p.preview_only = info.preview_only.clone(); } p.develop = std::sync::Arc::new(p.import_defaults()); - let edge = edge.clamp(64, crate::media::SourceLevel::Thumb.max_edge()); - let level = crate::media::SourceLevel::Thumb; + // Large import tiles on high-density displays need more than a 512-pixel source. + let edge = edge.clamp(64, 1024); + let level = crate::media::SourceLevel::for_size(edge); let source = self.media.origin_ref(&p.source, level.max_edge()); let key = lightcraft_preview::Hasher128::new().str(&c.path).u64(c.file_size).u64(edge as u64).finish().0 as u64; let small = crate::media::RenderJob { diff --git a/crates/engine/src/tests_export.rs b/crates/engine/src/tests_export.rs index 0ac8df804a..2f70ae2087 100644 --- a/crates/engine/src/tests_export.rs +++ b/crates/engine/src/tests_export.rs @@ -991,15 +991,19 @@ fn same_folder_as_original_exports_next_to_each_photo() { let exists = |p: &str| std::path::Path::new(p).exists(); let files = crate::export::export_batch(&mut s, &ids, &o, &to, &mut crate::export::write_file, &exists).unwrap(); let written: Vec<&str> = files.iter().map(|f| f["path"].as_str().unwrap()).collect(); - let mut want = vec![a.join("Exports/IMG_1.jpg").to_string_lossy().to_string(), b.join("Exports/IMG_1.jpg").to_string_lossy().to_string()]; - let mut got: Vec = written.iter().map(|p| p.to_string()).collect(); + // Compare path components: Windows accepts both separators in returned paths. + let mut want = vec![a.join("Exports").join("IMG_1.jpg"), b.join("Exports").join("IMG_1.jpg")]; + let mut got: Vec = written.iter().map(std::path::PathBuf::from).collect(); want.sort(); got.sort(); assert_eq!(got, want); assert!(!dir.join("unused").exists(), "nothing written to the specific folder"); // again: each folder's own collision gets the next free name let files = crate::export::export_batch(&mut s, &ids, &o, &to, &mut crate::export::write_file, &exists).unwrap(); - assert!(files.iter().all(|f| f["path"].as_str().unwrap().ends_with("Exports/IMG_1-2.jpg")), "{files:?}"); + assert!( + files.iter().all(|f| std::path::Path::new(f["path"].as_str().unwrap()).ends_with(std::path::Path::new("Exports").join("IMG_1-2.jpg"))), + "{files:?}" + ); // no subfolder: next to the original, which is never written over let beside = ExportOptions { subfolder: String::new(), conflict: Conflict::Overwrite, ..o.clone() }; let err = crate::export::export_batch(&mut s, &ids, &beside, &to, &mut crate::export::write_file, &exists).unwrap_err(); diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index e851463d17..65f0f1467c 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -8,7 +8,7 @@ //! catalog between frames, with a row and ✕ in the activity stack (issue #345); the whole import is //! one undo step. -use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; +use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use lightcraft_engine::import::{ ImportCandidate, ImportUprightMode, ImportWarning, ImportWarningCode, ScanInput, ScanOutput, ScanProgress, scan_with, }; @@ -35,6 +35,23 @@ const CONTENT_BOTTOM: &str = "import-content-bottom"; /// Room below the grid before it has been measured (more than the options and buttons take). const DEFAULT_BELOW_GRID: f32 = 360.0; +pub(crate) const THUMB_SIZE_MIN: f32 = 80.0; +pub(crate) const THUMB_SIZE_MAX: f32 = 320.0; +pub(crate) const THUMB_SIZE_DEFAULT: f32 = 116.0; + +/// Bound values from saved preferences and the control channel before laying out the grid. +pub(crate) fn thumb_size(size: f32) -> f32 { + if size.is_finite() { size.clamp(THUMB_SIZE_MIN, THUMB_SIZE_MAX) } else { THUMB_SIZE_DEFAULT } +} + +/// A few physical-pixel sizes avoid decoding on every point of a slider drag. The engine caps +/// candidate previews at 1024 pixels; this covers the largest tile at up to 3× display density. +fn thumb_edge(size: f32, pixels_per_point: f32) -> usize { + let scale = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { pixels_per_point } else { 1.0 }; + let pixels = (thumb_size(size) - 8.0) * scale; + [192, 384, 512, 768, 1024].into_iter().find(|edge| *edge as f32 >= pixels).unwrap_or(1024) +} + /// Height of the photo grid: what is `available` once `below` (options and buttons) is left free, /// in whole points so the window never grows by a fraction each frame, and at least one `row`. pub(crate) fn grid_height(available: f32, below: f32, row: f32) -> f32 { @@ -1026,8 +1043,18 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } }); } + ui.horizontal(|ui| { + let mut size = thumb_size(app.ui.import_thumb_size); + let response = + ui.add(egui::Slider::new(&mut size, THUMB_SIZE_MIN..=THUMB_SIZE_MAX).text(crate::i18n::tr("Thumbnail size")).show_value(false)); + // Slider's response includes its label; automation addresses the track itself. + register(ui.ctx(), "slider:importThumbSize", Rect::from_min_size(response.rect.min, vec2(ui.spacing().slider_width, response.rect.height()))); + if response.changed() { + let _ = app.run("view.importThumbSize", json!({"size": size})); + } + }); // candidate grid - let cell = 116.0; + let cell = thumb_size(app.ui.import_thumb_size).min(ui.available_width().max(1.0)); let avail = ui.available_width(); let cols = ((avail + 6.0) / (cell + 6.0)).floor().max(1.0) as usize; let rows = n.div_ceil(cols); @@ -1038,6 +1065,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { y(CONTENT_BOTTOM).zip(y(GRID_BOTTOM)).map(|(content, grid)| content - grid) }); let grid_h = grid_height(ui.available_height(), below.unwrap_or(DEFAULT_BELOW_GRID), cell + 26.0); + let mut visible = std::collections::HashSet::new(); let grid = egui::ScrollArea::vertical().id_salt("import-grid").max_height(grid_h).auto_shrink([false, false]).show_viewport(ui, |ui, viewport| { let (area, _) = ui.allocate_exact_size(vec2(avail, rows as f32 * (cell + 26.0)), Sense::hover()); @@ -1047,10 +1075,15 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { if !local.intersects(viewport.expand(cell)) { continue; } + let Ok(slot) = u32::try_from(i) else { continue }; + visible.insert(slot); let rect = local.translate(area.min.to_vec2()); candidate_cell(app, ui, d, i, rect); } }); + if !ui.is_sizing_pass() { + app.renderer.retain_imports(&visible); + } if !ui.is_sizing_pass() { ui.ctx().data_mut(|m| m.insert_temp(egui::Id::new(GRID_BOTTOM), grid.inner_rect.bottom())); } @@ -1314,7 +1347,8 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog, i: usize, rect: Rect) { let t = Tokens::get(ui.ctx()); - let c = d.candidates[i].clone(); + let Some(c) = d.candidates.get(i).cloned() else { return }; + let Ok(slot_index) = u32::try_from(i) else { return }; let ok = d.importable(i); let img = Rect::from_min_size(rect.min, vec2(rect.width(), rect.width())); let resp = ui.interact(img, egui::Id::new(("import-cell", i)), Sense::click()); @@ -1323,9 +1357,10 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let p = ui.painter(); p.rect_filled(img, 3.0, Color32::from_gray(30)); // thumbnail (background job; the grid only asks for the cells in view) - let slot = Slot::Import(i as u32); - if !app.renderer.textures.contains_key(&slot) - && let Some(job) = app.session.candidate_thumb_job(&c, 192, i as u64) + let slot = Slot::Import(slot_index); + let edge = thumb_edge(img.width(), ui.ctx().pixels_per_point()); + if app.renderer.textures.get(&slot).is_none_or(|tex| tex.size.into_iter().max().unwrap_or(0) < edge) + && let Some(job) = app.session.candidate_thumb_job(&c, edge, u64::from(slot_index)) { app.renderer.request_quick(slot, job, 4); } @@ -1336,7 +1371,7 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let tint = if ok { Color32::WHITE } else { Color32::from_gray(110) }; p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); } - let on = d.checked[i] && ok; + let on = d.checked.get(i).copied().unwrap_or(false) && ok; if on { p.rect_stroke(img, 3.0, Stroke::new(2.0, t.accent), StrokeKind::Inside); } @@ -1358,13 +1393,20 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial _ => None, }; if let Some(b) = badge { - let g = p.layout_no_wrap(crate::i18n::tr(b).to_string(), t.semibold(10.0), Color32::WHITE); + let mut label = egui::text::LayoutJob::simple_singleline(crate::i18n::tr(b).to_string(), t.semibold(10.0), Color32::WHITE); + label.wrap.max_width = (img.width() - 16.0).max(1.0); + label.wrap.max_rows = 1; + let g = p.layout_job(label); let br = badge_rect(img, cb, g.size()); p.rect_filled(br, 3.0, Color32::from_rgba_unmultiplied(170, 60, 50, 220)); p.galley(br.min + vec2(4.0, 2.0), g, Color32::WHITE); } - let name = if c.name.chars().count() > 18 { format!("{}…", c.name.chars().take(17).collect::()) } else { c.name.clone() }; - p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.font(10.5), if ok { t.text_label } else { t.text_dim }); + let color = if ok { t.text_label } else { t.text_dim }; + let mut name = egui::text::LayoutJob::simple_singleline(c.name.clone(), t.font(10.5), color); + name.wrap.max_width = (rect.width() - 4.0).max(1.0); + name.wrap.max_rows = 1; + let name = p.layout_job(name); + p.galley(pos2(rect.left() + 2.0, img.bottom() + 2.0), name, color); let tip = format!( "{}\n{} × {} · {} · {:.1} MB{}", c.path, @@ -1581,6 +1623,17 @@ fn field(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R mod tests { use super::*; + #[test] + fn import_thumb_edges_follow_size_and_display_density() { + assert_eq!(thumb_edge(116.0, 1.0), 192); + assert_eq!(thumb_edge(320.0, 1.0), 384); + assert_eq!(thumb_edge(320.0, 2.0), 768); + assert_eq!(thumb_edge(320.0, 3.0), 1024); + assert_eq!(thumb_edge(320.0, f32::MAX), 1024); + assert_eq!(thumb_edge(f32::NAN, f32::NAN), 192); + assert_eq!(thumb_edge(116.0, -1.0), 192); + } + #[test] fn grid_height_follows_the_window() { // the grid takes what the options and buttons leave, in whole points diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86e..ca1a8ab0ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -98,6 +98,8 @@ mod tests_grading; #[cfg(test)] mod tests_grid; #[cfg(test)] +mod tests_import_thumbnails; +#[cfg(test)] mod tests_info_dialogs; #[cfg(test)] mod tests_keymap; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d575d7490e..f3ec4fbc5e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -100,6 +100,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // Library grids only (Photo Grid, Square Grid, People): the bottom-bar slider's step by key ("view.thumbSizeUp", "Increase Grid Thumbnail Size", Some("="), "View"), ("view.thumbSizeDown", "Decrease Grid Thumbnail Size", Some("-"), "View"), + ("view.importThumbSize", "Import Thumbnail Size", None, ""), ("view.clipping", "Show Clipping", Some("J"), "View"), ("view.visualizeHdr", "Visualize HDR", None, "View"), // in grids S expands/collapses stacks (the engine command it shadows) @@ -866,6 +867,18 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { + // {size?: points}; without a size, read the current preference. + let size = match p.get("size") { + None => app.ui.import_thumb_size, + Some(value) => match value.as_f64().map(|n| n as f32).filter(|n| n.is_finite()) { + Some(size) => size, + None => return Some(Err("view.importThumbSize: size must be a finite number".into())), + }, + }; + app.ui.import_thumb_size = crate::import::thumb_size(size); + Ok(json!({"size": app.ui.import_thumb_size})) + } "view.navigate" => { // {zoom?: "fit"|"fill"|{percent: number}, pan?: [x, y]} (normalized image centre). // Validate the complete request before changing either part of the viewport. diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 64ab067b7d..5dee1bc1cb 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -954,12 +954,20 @@ impl Renderer { /// Drop the import review thumbnails (a new review, or the dialog closed). pub fn forget_imports(&mut self) { - self.pool.reprioritize(|s, p| if matches!(s, Slot::Import(_)) { None } else { Some(p) }); - self.queue.retain(|q| !matches!(q.slot, Slot::Import(_))); - self.pending.retain(|s, _| !matches!(s, Slot::Import(_))); - self.request_ids.retain(|s, _| !matches!(s, Slot::Import(_))); - self.textures.retain(|s, _| !matches!(s, Slot::Import(_))); - self.quick_tried.retain(|s, _| !matches!(s, Slot::Import(_))); + self.retain_imports(&Default::default()); + } + + /// Keep only the import tiles near the viewport, including queued work. Large thumbnails + /// must not accumulate for every candidate while scrolling through a whole card. + pub fn retain_imports(&mut self, keep: &std::collections::HashSet) { + let retained = |s: &Slot| !matches!(s, Slot::Import(i) if !keep.contains(i)); + self.pool.reprioritize(|s, p| retained(s).then_some(p)); + self.queue.retain(|q| retained(&q.slot)); + self.pending.retain(|s, _| retained(s)); + self.request_ids.retain(|s, _| retained(s)); + self.textures.retain(|s, _| retained(s)); + self.quick_tried.retain(|s, _| retained(s)); + self.failed.retain(|s, _| retained(s)); } /// Drop thumbnails that aren't in `keep` (bounded memory for huge libraries), and queued diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8c8cc0d41..0b6b28cccb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -662,6 +662,8 @@ pub struct UiState { pub zoom_anim: bool, pub before_after: BeforeAfter, pub thumb_size: f32, + /// Import review thumbnail size in points, independent of the library grid. + pub import_thumb_size: f32, /// Open Edit sections by id. pub open_sections: Vec, /// Open flyouts (curve, mixer, grading…). @@ -1283,6 +1285,7 @@ impl Default for UiState { zoom_anim: false, before_after: BeforeAfter::Off, thumb_size: 220.0, + import_thumb_size: crate::import::THUMB_SIZE_DEFAULT, open_sections: vec!["light".into()], open_flyouts: vec![], single_panel: false, @@ -1467,6 +1470,7 @@ impl UiState { /// Clamp values restored from disk. pub fn sanitized(mut self) -> Self { self.thumb_size = self.thumb_size.clamp(THUMB_SIZE_MIN, THUMB_SIZE_MAX); + self.import_thumb_size = crate::import::thumb_size(self.import_thumb_size); self.left_width = LEFT_WIDTH.clamp(self.left_width); self.right_width = RIGHT_WIDTH.clamp(self.right_width); self.brush_size = self.brush_size.clamp(0.002, 0.5); diff --git a/crates/ui-egui/src/tests_folder_drop.rs b/crates/ui-egui/src/tests_folder_drop.rs index 9b4cb860a2..4d37f57091 100644 --- a/crates/ui-egui/src/tests_folder_drop.rs +++ b/crates/ui-egui/src/tests_folder_drop.rs @@ -50,8 +50,13 @@ fn widget(h: &Headless, id: &str) -> Option { h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) } +fn folder_id(prefix: &str, dir: &Path) -> String { + // FolderNode paths (and their widget ids) use forward slashes on every platform. + format!("{prefix}:{}", dir.to_string_lossy().replace('\\', "/")) +} + fn folder_row(h: &Headless, dir: &Path) -> Option { - widget(h, &format!("source:libfolder:{}", dir.to_string_lossy())) + widget(h, &folder_id("source:libfolder", dir)) } fn id_of(h: &Headless, file: &str) -> u64 { @@ -180,7 +185,7 @@ fn photos_already_in_the_folder_stay_put() { let (root, trip, home) = folders("here"); let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); // open the folder holding both - let toggle = widget(&h, &format!("libraryFolderToggle:{}", root.to_string_lossy())).unwrap(); + let toggle = widget(&h, &folder_id("libraryFolderToggle", &root)).unwrap(); h.app.synthetic.push(egui::Event::PointerMoved(toggle.center())); h.app.synthetic.push(egui::Event::PointerButton { pos: toggle.center(), @@ -284,7 +289,7 @@ fn cancelling_the_question_moves_nothing() { let target = if folder_row(&h, &home).is_some() { target } else { - click(&mut h, &format!("libraryFolderToggle:{}", root.to_string_lossy())); + click(&mut h, &folder_id("libraryFolderToggle", &root)); folder_row(&h, &home).unwrap() }; let undo = h.app.session.undo.len(); @@ -302,7 +307,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { let (root, trip, home) = folders("dont-ask"); std::fs::copy(trip.join("beach.png"), trip.join("dunes.png")).unwrap(); let mut h = app(&[(trip.join("beach.png"), false), (trip.join("dunes.png"), false), (home.join("garden.png"), false)]); - click(&mut h, &format!("libraryFolderToggle:{}", root.to_string_lossy())); + click(&mut h, &folder_id("libraryFolderToggle", &root)); let target = folder_row(&h, &home).unwrap(); let beach = id_of(&h, "beach.png"); h.app.session.selection = lightcraft_engine::Selection::single(lightcraft_catalog::PhotoId(beach)); @@ -327,7 +332,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { fn a_question_left_open_while_another_library_opens_moves_nothing() { let (root, trip, home) = folders("other-library"); let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); - click(&mut h, &format!("libraryFolderToggle:{}", root.to_string_lossy())); + click(&mut h, &folder_id("libraryFolderToggle", &root)); let beach = id_of(&h, "beach.png"); let target = folder_row(&h, &home).unwrap(); drop_beach(&mut h, beach, target); diff --git a/crates/ui-egui/src/tests_import_thumbnails.rs b/crates/ui-egui/src/tests_import_thumbnails.rs new file mode 100644 index 0000000000..cdf1788262 --- /dev/null +++ b/crates/ui-egui/src/tests_import_thumbnails.rs @@ -0,0 +1,149 @@ +//! Import review sizes change the real grid and its preview resolution, preserving culling. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::import::ImportDialog; +use crate::render::Slot; +use crate::state::{Dialog, UiState}; +use crate::{LightcraftApp, Services}; +use lightcraft_engine::import::ImportCandidate; + +const T: Duration = Duration::from_secs(30); + +struct Review { + h: Headless, + dir: std::path::PathBuf, +} + +impl Review { + fn new(scale: f32) -> Self { + let dir = std::env::temp_dir().join(format!("lc-import-thumbnails-{}-{}", std::process::id(), lightcraft_preview::next_tick())); + std::fs::create_dir_all(&dir).unwrap(); + let image = lightcraft_raster::Rgba8 { + width: 1600, + height: 1200, + data: (0..1600 * 1200).map(|i| [((i % 1600) / 7) as u8, ((i / 1600) / 5) as u8, 100, 255]).collect(), + }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&image), &Default::default()).unwrap(); + let path = dir.join("original.png"); + std::fs::write(&path, &bytes).unwrap(); + let mut candidates: Vec<_> = (0..60) + .map(|i| ImportCandidate { + path: path.to_string_lossy().into(), + name: format!("a-long-photo-name-{i:02}.png"), + format: "PNG".into(), + width: 1600, + height: 1200, + file_size: bytes.len() as u64, + ..Default::default() + }) + .collect(); + candidates[1].duplicate = Some("content".into()); + candidates[2].error = Some("Unreadable test candidate".into()); + let mut app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services::default()); + app.ui.dialog = Some(Dialog::Import { opts: Box::new(ImportDialog::new(candidates)) }); + let mut h = Headless::new(app, [1366.0, 1000.0], scale); + assert!(h.settle(T)); + Self { h, dir } + } + + fn rect(&self, id: &str) -> egui::Rect { + self.h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("missing {id}")) + } + + fn checks(&self) -> Vec { + let Some(Dialog::Import { opts }) = &self.h.app.ui.dialog else { panic!("import review closed") }; + opts.checked.clone() + } + + fn request(&mut self, method: &str, params: serde_json::Value) { + let response = self.h.request(method, params, T); + assert_eq!(response["ok"], true, "{method}: {response}"); + } + + fn size(&mut self, size: f32) { + self.request("engine.execute", json!({"command": "view.importThumbSize", "params": {"size": size}})); + assert!(self.h.settle(T)); + } +} + +impl Drop for Review { + fn drop(&mut self) { + self.h.app.ui.dialog = None; + self.h.app.renderer.forget_imports(); + self.h.settle(T); + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +#[test] +fn import_thumbnail_slider_reflows_without_changing_selection_or_badges() { + let mut review = Review::new(1.0); + assert_eq!(review.rect("import:0").width(), 116.0); + review.request("ui.clickWidget", json!({"id": "import:0"})); + let checked = review.checks(); + assert!(!checked[0] && !checked[1] && !checked[2]); + // Real pointer input on the slider, including its end stops. + review.request("ui.clickWidget", json!({"id": "slider:importThumbSize", "fx": 0.0})); + assert!(review.h.settle(T)); + assert_eq!(review.rect("import:0").width(), 80.0); + let slider = review.rect("slider:importThumbSize"); + review.request("ui.dragWidget", json!({"id": "slider:importThumbSize", "toX": slider.right(), "toY": slider.center().y})); + assert!(review.h.settle(T)); + assert_eq!(review.rect("import:0").width(), 320.0); + assert_eq!(review.checks(), checked); + let text = review.h.painted_text().join("\n"); + assert!(text.contains("Duplicate") && text.contains("Unreadable"), "badges remain visible: {text}"); + assert!(review.rect("import:3").top() > review.rect("import:0").top(), "larger tiles wrap into more rows"); + review.size(80.0); + assert_eq!(review.rect("import:3").top(), review.rect("import:0").top()); + assert_eq!(review.checks(), checked); + // The preference survives closing/reopening the review and a settings round trip. + let saved = serde_json::to_value(&review.h.app.ui).unwrap(); + let restored: UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(restored.sanitized().import_thumb_size, 80.0); +} + +#[test] +fn import_thumbnail_previews_upgrade_for_density_and_stay_bounded_when_scrolling() { + let mut review = Review::new(2.0); + assert_eq!(review.h.app.renderer.textures[&Slot::Import(0)].size, [384, 288]); + review.size(320.0); + assert_eq!(review.h.app.renderer.textures[&Slot::Import(0)].size, [768, 576]); + // Shrinking keeps the sharp preview instead of replacing it with a smaller decode. + let sharp = review.h.app.renderer.textures[&Slot::Import(0)].key; + review.size(116.0); + assert_eq!(review.h.app.renderer.textures[&Slot::Import(0)].key, sharp); + review.size(320.0); + // Scrolling a large card retains only the nearby tiles and drops obsolete requests. + review.request("ui.hoverWidget", json!({"id": "import:0"})); + review.request("ui.scroll", json!({"dy": -20000.0})); + assert!(review.h.settle(T)); + assert!(!review.h.app.renderer.textures.contains_key(&Slot::Import(0))); + let imports: Vec<_> = review.h.app.renderer.textures.keys().filter_map(|s| if let Slot::Import(i) = s { Some(*i) } else { None }).collect(); + assert!(!imports.is_empty() && imports.len() < 20, "bounded visible previews: {imports:?}"); + for i in imports { + assert!(review.h.app.widgets.iter().any(|(w, _)| w == &format!("import:{i}"))); + } +} + +#[test] +fn import_thumbnail_size_rejects_bad_commands_and_restores_old_preferences() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + assert_eq!(app.run("view.importThumbSize", json!({})).unwrap()["size"], 116.0); + for bad in [json!("large"), json!(null), json!([120]), json!(1e300)] { + assert!(app.run("view.importThumbSize", json!({"size": bad})).is_err()); + assert_eq!(app.ui.import_thumb_size, 116.0); + } + assert_eq!(app.run("view.importThumbSize", json!({"size": -10})).unwrap()["size"], 80.0); + assert_eq!(app.run("view.importThumbSize", json!({"size": 1e6})).unwrap()["size"], 320.0); + let legacy: UiState = serde_json::from_value(json!({})).unwrap(); + assert_eq!(legacy.import_thumb_size, 116.0); + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let state = UiState { import_thumb_size: bad, ..Default::default() }.sanitized(); + assert_eq!(state.import_thumb_size, 116.0); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 31ecbf8c2c..f67bd4fcd8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -239,6 +239,12 @@ For MCP, use `lightcraft-cli mcp --connect 127.0.0.1:7980`: `run_command` reache `lightcraft://controls` ([mcp.md](mcp.md#resources)). Headless CLI/MCP mode owns a separate engine session; use connect mode for feedback from edits in the desktop app. +The import review's **Thumbnail size** slider is `slider:importThumbSize` in `ui.widgets`. +`engine.execute {command: "view.importThumbSize", params: {size: 240}}` sets its size in points +(80–320, clamped); omitting `size` reads it. Both return `{size}`. Non-numeric or non-finite +values are refused. The preference is `importThumbSize` in the UI state, independent of the +library grid's `thumbSize`; resizing keeps the import checkboxes and duplicate markers. + ## Headless rendering (no window, no GPU) The egui UI can be rasterized on the CPU (`crates/ui-egui/src/softpaint.rs`, driven by diff --git a/docs/gaps.md b/docs/gaps.md index f11a74f7a0..aae2389fb4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (gap 10: 515 of 1,446 models verified, ~84% of photographers on a verified body) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-17 · **Change:** minor (import grid thumbnail size adjustable; gap 30 tracks the remaining pre-import loupe, #2056) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -44,6 +44,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 27 | **Windows / Linux runtime coverage**: Windows installer UI unverified on Windows (#79); GPU path proven on Apple and on one AMD GPU on Linux (Radeon 8060S, Vulkan); NVIDIA, Intel and DX12 unverified; the Linux riscv64 tarball (new in 0.6.0, #844) is cross-compiled and never run beyond a QEMU smoke test | ROADMAP, issues, `release.yml` | non-Mac users find bugs first | 13–27 | [hardware-parity](hardware-parity.md) | | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: rating `[` `]`, flag cycling, filter-bar keys, F1 help, panel keys (Tab, F5, F8; F6 and F7 toggle the filmstrip and the left panel) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 4–8 | [ui-parity](ui-parity.md) | +| 30 | **Pre-import loupe and keyboard culling** (#2056): the import review now has an 80–320 pt thumbnail slider, with suitably sized previews and preserved selection; opening a candidate large and next/previous culling before import remain | `crates/ui-egui/src/import.rs`, `crates/ui-egui/src/tests_import_thumbnails.rs` | photographers culling a large card before adding it to their library | 6–10 | [import guide](user/guides/import-photos.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -60,6 +61,9 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-10-17: import review grid thumbnail-size slider (part of #2056, LR-IMP-ADD-DIALOG): 80–320 pt, + remembered separately from the library grid, density-aware previews and bounded visible textures. + Gap 30 retains the loupe request; headline readiness estimates unchanged. - 2026-10-12: original-pixel detail at 100% (gap 4, LR-VIEW-ZOOM, #323): soft proofing gets zoom windows like Detail, Before/After, Compare, Reference and mask overlays; 1:1 tested equal to the full-size export. - 2026-10-11: Sony ILCA-99M2 profile. @@ -77,6 +81,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | Import thumbnail-size slider (part of #2056); gap 30 records the remaining pre-import loupe and keyboard culling | | 2026-10-14 | minor | Gap 26: at 100k photos stack and album lookups are indexed, so an "In a Stack" or "Album" smart album counts in ~14 ms (was 0.6–2.7 s); open time unchanged | | 2026-10-14 | minor | Gap 10: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277) | | 2026-10-14 | minor | Gap 21: de, es, fr, ja and uk catalogs filled (97–99%); 55–90 h → 40–70 h | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index de7ba697f8..da25ec0191 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-14 · **Change:** minor (integration batch 36: slideshow module, print-ready PDF fixes, local adjustment presets, Layout Image loupe overlay, Delete in an album removes from it, new languages Czech, Polish, Italian-ready catalogs; many rows' notes updated by their PRs) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (import grid thumbnail-size slider, #2056; status and summary counts unchanged) · **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 @@ -71,7 +71,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | 2026-10-12 | minor | LR-IMP-FORMATS: Mamiya MEF decodes from sensor data and is imported (`vendor/mef.rs`) | | 2026-10-12 | minor | LR-IMP-FORMATS: Epson ERF decodes from sensor data (`vendor/erf.rs`), no longer preview-only | -| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new), preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) | +| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with an 80–320 pt Thumbnail size slider (`cmd:view.importThumbSize`, `crates/ui-egui/src/tests_import_thumbnails.rs`; remembered separately from the library grid; density-aware previews, bounded visible textures), thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new), preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → `cmd:library.import`) | dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests_import.rs` | | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/import.rs`) | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | LR-IMP-ADD-DIALOG: import grid thumbnail-size slider, density-aware previews, bounded visible textures and preserved culling; remaining loupe tracked in gap 30 (#2056); status and summary counts 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/user/guides/import-photos.md b/docs/user/guides/import-photos.md index 8130272ae6..b688f3d16f 100644 --- a/docs/user/guides/import-photos.md +++ b/docs/user/guides/import-photos.md @@ -10,7 +10,7 @@ Use **File** > **Import Photos…** to pick files, or **File** > **Import from F ## Steps 1. Open the **File** menu and choose **Import Photos…** or **Import from Folder…**, then pick the files or the folder. -2. Look at the thumbnails. Every photo that can be imported has a checkbox. Click a photo to check or uncheck it. Shift-click sets a range. **Check All** and **Uncheck All** change every photo at once. +2. Look at the thumbnails. Use **Thumbnail size** above the grid to make them smaller or larger; the size is remembered for the next import. Every photo that can be imported has a checkbox. Click a photo to check or uncheck it. Shift-click sets a range. **Check All** and **Uncheck All** change every photo at once. 3. Photos already in your library are marked **Duplicate** or **In library** and start unchecked. A file LightCraft cannot read is marked **Unreadable**. A photo you deleted that is still in **Recently Deleted** is marked **Will be restored**. **In Recently Deleted** sets what happens to those: **Restore them** (the default) brings the photos back with their edits, ratings and albums, **Import as new** deletes the old record first, and **Leave them** skips them. 4. Under **Transfer**, choose how the files get into the library: - **Add in place** keeps the files where they are. The library only points to them. Nothing is copied or moved. 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 0009/1092] 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 6c2ff558d90a9ab6e314f9ce4f19bd1d542fee6b Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Sun, 18 Oct 2026 20:57:13 -0700 Subject: [PATCH 0010/1092] #2284: read the Exif and XMP items of HEIF files A HEIC imported with no capture time. `container::embedded` knew JPEG, PNG, WebP, TIFF-based files, RAF and CR3, but no ISO base media still image, so every HEIC produced an empty `Embedded` and carried no Exif at all (#1233). With no date in the file and none in a sidecar, the import falls back to the file's modification time, which LightCraft writes as UTC: a photo taken at 13:00 in UTC-5 was catalogued as 18:00, and one taken after 19:00 local time landed in the next day's folder. `meta::heif` reads the `meta` box's item information (`iinf`) and item location (`iloc`) boxes and returns the `Exif` item's TIFF stream and the XMP `mime` item. It parses the container only, so it is in every build and the HEVC decoder stays behind the `heif` feature. The box walker `cr3` already had is now shared instead of written twice. Camera, lens, ISO, GPS and keywords come through with the date. HEIF puts orientation in the container and its Exif tag only mirrors that, so the probe still takes the orientation from the container; a test checks that a HEIC whose Exif says 6 imports upright. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 1 + crates/engine/src/tests_import.rs | 43 ++++ crates/meta/Cargo.toml | 2 + crates/meta/src/container.rs | 5 + crates/meta/src/cr3.rs | 20 +- crates/meta/src/heif.rs | 398 ++++++++++++++++++++++++++++++ crates/meta/src/lib.rs | 6 +- crates/meta/tests/robust.rs | 4 +- 8 files changed, 465 insertions(+), 14 deletions(-) create mode 100644 crates/meta/src/heif.rs diff --git a/Cargo.lock b/Cargo.lock index 5d7f5111ac..e836d6ba29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3379,6 +3379,7 @@ name = "lightcraft-meta" version = "0.9.1" dependencies = [ "lightcraft-geom", + "lightcraft-heif", "lightcraft-tiff", "proptest", "quick-xml 0.38.4", diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 13f02ce778..b9455e617e 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1606,6 +1606,49 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() { let _ = std::fs::remove_dir_all(&src); } +/// Issue #2284: a photo taken at 13:00 in UTC-5 must be catalogued as 13:00. HEICs carried no Exif +/// (issue #1233), so every one of them fell back to the file's modification time, which the import +/// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day. +#[test] +fn a_heic_is_dated_by_its_exif_and_not_by_the_file() { + use lightcraft_heif::testdata::{Spec, build}; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + let src = temp_dir("heic-capture-time"); + let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; + let mut exif = IfdBuilder::new(); + exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii("2026:10:18 13:00:00".into())); + exif.set(t::OFFSET_TIME_ORIGINAL, Value::Ascii("-05:00".into())); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Apple".into())); + ifd0.set(t::MODEL, Value::Ascii("iPhone 15 Pro".into())); + // HEIF turns the picture in the container; its Exif Orientation only mirrors that, so reading + // the Exif must not turn it a second time. + ifd0.set(t::ORIENTATION, Value::Short(vec![6])); + ifd0.set_child(t::EXIF_IFD, exif); + let exif = TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap(); + let bytes = build(&Spec { exif: Some(exif), ..Spec::new(96, 64, &photo) }); + let path = src.join("IMG_0002.HEIC"); + std::fs::write(&path, &bytes).unwrap(); + // The probe reads the metadata in every build; only decoding the picture needs the feature. + let info = crate::files::probe_bytes("IMG_0002.HEIC", &bytes); + if lightcraft_codecs::Format::Heif.can_decode() { + let info = info.unwrap(); + assert_eq!(info.captured.as_deref(), Some("2026-10-18T13:00:00-05:00")); + assert_eq!(info.meta.camera, "Apple iPhone 15 Pro"); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "failed")), (1, 0), "{r}"); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.captured.as_deref(), Some("2026-10-18T13:00:00-05:00"), "the time the camera wrote, not the file's"); + assert_eq!((p.width, p.height), (96, 64), "upright: the container's own transforms, not the Exif tag as well"); + assert_eq!(lightcraft_catalog::dates::display_time(p.date()), "October 18, 2026 at 1:00:00 PM"); + } else { + assert!(info.is_err(), "without the feature a HEIC cannot be opened at all"); + assert_eq!(lightcraft_meta::extract(&bytes).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); + } + let _ = std::fs::remove_dir_all(&src); +} + /// Issue #705: Nikon (and most cameras) write `.JPG` and `.NEF`, and a user may rename to `.Jpg`. /// The folder scan, `library.browse` and the sidecar lookup match extensions in any letter /// case. (The file dialog's filters, the one place that was case-sensitive on Linux before diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 0ef8903d2f..26dffbadb5 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -15,5 +15,7 @@ serde = { workspace = true } quick-xml = { workspace = true } [dev-dependencies] +# Lossless synthetic HEIC files: the HEIF item reader is proved against a real container writer. +lightcraft-heif = { workspace = true, features = ["testdata"] } proptest = { workspace = true } serde_json = { workspace = true } diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index 8dda6b55d1..b15251cca7 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -9,6 +9,8 @@ //! IPTC (33723) from IFD0. //! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the //! XMP `uuid` box. +//! - HEIF/HEIC/AVIF (ISO base media file, see [`crate::heif`]): the `Exif` item's TIFF stream and the XMP +//! `mime` item. use lightcraft_tiff::{Tiff, tags}; @@ -39,6 +41,9 @@ pub fn embedded(bytes: &[u8]) -> Embedded { if let Some(c) = crate::cr3::parse_cr3(bytes) { return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() }; } + if crate::heif::is_heif(bytes) { + return crate::heif::metadata(bytes); + } if bytes.starts_with(&[0xff, 0xd8]) { jpeg_segments(bytes) } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { diff --git a/crates/meta/src/cr3.rs b/crates/meta/src/cr3.rs index 55b3ae6a6d..77d8dec4a7 100644 --- a/crates/meta/src/cr3.rs +++ b/crates/meta/src/cr3.rs @@ -229,7 +229,7 @@ const CANON_UUID: [u8; 16] = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x /// The `uuid` of the top-level box holding the XMP packet. pub const XMP_UUID: [u8; 16] = [0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac]; const MAX_DEPTH: usize = 12; -const MAX_BOXES: usize = 4096; +pub(crate) const MAX_BOXES: usize = 4096; /// A `VisualSampleEntry` (78 bytes after the box header) plus 4 bytes Canon adds before the child boxes. const CRAW_CHILDREN_AT: usize = 82; @@ -256,16 +256,16 @@ pub fn parse_cr3(bytes: &[u8]) -> Option> { Some(out) } -struct BoxRef { - kind: [u8; 4], +pub(crate) struct BoxRef { + pub(crate) kind: [u8; 4], /// Start of the payload (after the header and, for `uuid`, the 16-byte uuid). - body: usize, - end: usize, - uuid: Option<[u8; 16]>, + pub(crate) body: usize, + pub(crate) end: usize, + pub(crate) uuid: Option<[u8; 16]>, } /// The boxes directly inside `[from, to)`; stops at the first malformed header. -fn boxes(bytes: &[u8], from: usize, to: usize, budget: &mut usize) -> Vec { +pub(crate) fn boxes(bytes: &[u8], from: usize, to: usize, budget: &mut usize) -> Vec { let mut out = Vec::new(); let mut at = from; let to = to.min(bytes.len()); @@ -407,13 +407,13 @@ fn sample_entry(bytes: &[u8], e: &BoxRef, budget: &mut usize) -> Cr3TrackKind { Cr3TrackKind::Raw { width, height, cmp1, iad1 } } -fn be16(b: &[u8], at: usize) -> Option { +pub(crate) fn be16(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]])) } -fn be32(b: &[u8], at: usize) -> Option { +pub(crate) fn be32(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } -fn be64(b: &[u8], at: usize) -> Option { +pub(crate) fn be64(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(8)?)?; let mut a = [0u8; 8]; a.copy_from_slice(s); diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs new file mode 100644 index 0000000000..98f3f0a3e6 --- /dev/null +++ b/crates/meta/src/heif.rs @@ -0,0 +1,398 @@ +//! HEIF / HEIC / AVIF metadata: the `Exif` and XMP items of the ISO base media file container +//! (box structure from ISO/IEC 14496-12, item model from ISO/IEC 23008-12). +//! +//! HEIC is what iPhones and Macs write. Its pixels need an HEVC decoder (the optional +//! `lightcraft-heif` crate), its metadata does not, so this reader is in every build: a HEIC +//! imports with its capture time, camera and lens whether or not the build can show the picture. +//! +//! The `meta` box holds an item information box (`iinf`, one `infe` per item) naming each item's +//! type, and an item location box (`iloc`) saying where its bytes are: in the file, or in the +//! `idat` box next to it. The `Exif` item is a four-byte offset followed by a TIFF stream; the XMP +//! packet is a `mime` item whose content type is `application/rdf+xml`. The ICC profile is an item +//! *property*, not an item, and is read by the decoder instead. + +use crate::container::Embedded; +use crate::cr3::{MAX_BOXES, be16, be32, be64, boxes}; + +/// Brands that declare a still image in the ISO base media container. +const IMAGE_BRANDS: [&[u8]; 12] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs", b"mif1", b"msf1", b"avif", b"avis"]; + +/// Longest `ftyp` box this reads brands from. +const MAX_FTYP: usize = 4096; +/// Most items one file's `iinf` / `iloc` describes (an iPhone HEIC has a handful). +const MAX_ITEMS: usize = 1024; +/// Most extents one item's bytes are split into. +const MAX_EXTENTS: u16 = 1024; +/// Largest metadata item this returns; a real photo's Exif and XMP are a few hundred kilobytes. +const MAX_ITEM: usize = 32 << 20; + +/// Does this file declare an ISO base media still image (HEIF / HEIC / AVIF)? +pub fn is_heif(bytes: &[u8]) -> bool { + if bytes.get(4..8) != Some(b"ftyp".as_slice()) { + return false; + } + let Some(size) = be32(bytes, 0).map(|v| v as usize) else { + return false; + }; + let end = size.min(bytes.len()).min(MAX_FTYP); + let brand = |at: usize| bytes.get(at..at.saturating_add(4)).is_some_and(|b| IMAGE_BRANDS.contains(&b)); + // the major brand, then (after the minor version) the compatible brands + brand(8) || (16..end).step_by(4).any(brand) +} + +/// The Exif and XMP blocks of a HEIF file. Anything malformed is left out rather than reported: +/// a file whose items can't be located simply has no metadata, as before this reader existed. +pub fn metadata(bytes: &[u8]) -> Embedded { + let mut out = Embedded::default(); + let mut budget = MAX_BOXES; + let Some(meta) = boxes(bytes, 0, bytes.len(), &mut budget).into_iter().find(|b| &b.kind == b"meta") else { + return out; + }; + // `meta` is a FullBox: a version and flags before its children + let (mut items, mut locs, mut idat) = (Vec::new(), Vec::new(), None); + for b in boxes(bytes, meta.body.saturating_add(4), meta.end, &mut budget) { + match &b.kind { + b"iinf" => items = item_infos(bytes, &b, &mut budget), + b"iloc" => locs = item_locations(bytes.get(b.body..b.end).unwrap_or_default()), + b"idat" => idat = bytes.get(b.body..b.end), + _ => {} + } + } + for (id, kind, content_type) in items { + let want_exif = &kind == b"Exif" && out.exif.is_none(); + let want_xmp = &kind == b"mime" && content_type == "application/rdf+xml" && out.xmp.is_none(); + if !want_exif && !want_xmp { + continue; + } + let Some(loc) = locs.iter().find(|l| l.id == id) else { continue }; + let Some(block) = item_bytes(bytes, idat, loc) else { continue }; + if want_exif { + // ISO/IEC 23008-12 A.2.1: a four-byte offset from the end of itself to the TIFF header + let skip = be32(&block, 0).and_then(|v| usize::try_from(v).ok()).and_then(|v| v.checked_add(4)); + out.exif = skip.and_then(|at| block.get(at..)).filter(|b| !b.is_empty()).map(<[u8]>::to_vec); + } else { + out.xmp = Some(String::from_utf8_lossy(&block).trim_end_matches('\0').to_string()); + } + } + out +} + +/// `iinf` → one `(item_ID, item_type, content_type)` per `infe` entry. Entries of version 0 and 1 +/// name no item type and are skipped; HEIF files use version 2 or 3. +fn item_infos(bytes: &[u8], iinf: &crate::cr3::BoxRef, budget: &mut usize) -> Vec<(u32, [u8; 4], String)> { + // FullBox version and flags, then a 16- or 32-bit entry count before the `infe` boxes + let version = *bytes.get(iinf.body).unwrap_or(&0); + let entries_at = iinf.body.saturating_add(if version == 0 { 6 } else { 8 }); + let mut out = Vec::new(); + for b in boxes(bytes, entries_at, iinf.end, budget) { + if &b.kind != b"infe" || out.len() >= MAX_ITEMS { + continue; + } + let Some(e) = bytes.get(b.body..b.end) else { continue }; + let (id, kind_at) = match *e.first().unwrap_or(&0) { + 2 => (be16(e, 4).map(u32::from), 8), + 3 => (be32(e, 4), 10), + _ => continue, + }; + let (Some(id), Some(kind)) = (id, e.get(kind_at..kind_at + 4)) else { continue }; + let mut kind4 = [0u8; 4]; + kind4.copy_from_slice(kind); + // the item name, then (for a `mime` item) the content type, both NUL-terminated + let mut strings = e.get(kind_at + 4..).unwrap_or_default().split(|&c| c == 0).skip(1); + let content_type = String::from_utf8_lossy(strings.next().unwrap_or_default()).into_owned(); + out.push((id, kind4, content_type)); + } + out +} + +/// Where one item's bytes are. +struct Loc { + id: u32, + /// 0 = offsets into the file, 1 = into the `idat` box, 2 = another item (not read). + construction: u8, + base: u64, + /// `(offset, length)` per extent, in order. + extents: Vec<(u64, u64)>, +} + +/// `iloc` (payload after the box header) → one [`Loc`] per entry, stopping at the first +/// unreadable one. +fn item_locations(p: &[u8]) -> Vec { + let version = *p.first().unwrap_or(&0); + let (Some(sizes), Some(base_index)) = (p.get(4), p.get(5)) else { return Vec::new() }; + let (offset_size, length_size) = ((sizes >> 4) as usize, (sizes & 0xf) as usize); + let (base_size, index_size) = ((base_index >> 4) as usize, if version > 0 { (base_index & 0xf) as usize } else { 0 }); + let (count, mut at) = match version { + 0 | 1 => (be16(p, 6).map(usize::from), 8), + 2 => (be32(p, 6).and_then(|v| usize::try_from(v).ok()), 10), + _ => return Vec::new(), + }; + let mut out = Vec::new(); + for _ in 0..count.unwrap_or(0).min(MAX_ITEMS) { + let (id, after_id) = match version { + 2 => (be32(p, at), at + 4), + _ => (be16(p, at).map(u32::from), at + 2), + }; + // version 1 and 2 put the construction method in the low nibble of a reserved 16-bit field + let construction = if version == 0 { Some(0) } else { be16(p, after_id).map(|v| (v & 0xf) as u8) }; + let after_method = after_id + if version == 0 { 0 } else { 2 }; + // a data reference index of 0 means this file; an external reference has no bytes here + let external = be16(p, after_method).is_some_and(|v| v != 0); + let base = uint(p, after_method + 2, base_size); + let extent_at = after_method + 2 + base_size; + let (Some(id), Some(construction), Some(base), Some(extent_count)) = (id, construction, base, be16(p, extent_at)) else { + break; + }; + let stride = index_size + offset_size + length_size; + let mut extents = Vec::new(); + let mut e = extent_at + 2; + for _ in 0..extent_count.min(MAX_EXTENTS) { + let (Some(offset), Some(length)) = (uint(p, e + index_size, offset_size), uint(p, e + index_size + offset_size, length_size)) else { + return out; + }; + extents.push((offset, length)); + e += stride; + } + at = e; + if !external { + out.push(Loc { id, construction, base, extents }); + } + } + out +} + +/// A big-endian unsigned integer of `size` bytes; `size` 0 is the value 0, and the item boxes +/// allow no other width than 4 or 8. +fn uint(b: &[u8], at: usize, size: usize) -> Option { + match size { + 0 => Some(0), + 4 => be32(b, at).map(u64::from), + 8 => be64(b, at), + _ => None, + } +} + +/// An item's bytes, its extents concatenated. `None` when they don't fit the file (or the `idat` +/// box), when the item is built by referencing another one, or when it is implausibly large. +fn item_bytes(bytes: &[u8], idat: Option<&[u8]>, loc: &Loc) -> Option> { + let src = match loc.construction { + 0 => bytes, + 1 => idat?, + _ => return None, + }; + let mut out = Vec::new(); + for &(offset, length) in &loc.extents { + let at = loc.base.checked_add(offset)?; + let (start, end) = (usize::try_from(at).ok()?, usize::try_from(at.checked_add(length)?).ok()?); + let extent = src.get(start..end)?; + if out.len().checked_add(extent.len())? > MAX_ITEM { + return None; + } + out.extend_from_slice(extent); + } + (!out.is_empty()).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + // the whole routing, not just this module: a HEIC must reach the HEIF branch of `embedded` + use crate::embedded; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + + fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); + v.extend_from_slice(kind); + v.extend_from_slice(payload); + v + } + + fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec { + bx(kind, &[&[version, 0, 0, 0][..], payload].concat()) + } + + struct Item<'a> { + kind: &'a [u8; 4], + content_type: &'a str, + data: Vec, + } + + /// A HEIC-shaped file holding `items`: `ftyp`, a `meta` box with one `infe` per item, and the + /// item bytes in `idat` (`in_idat`, construction method 1) or in `mdat` (method 0). + fn heic(items: &[Item<'_>], iloc_version: u8, in_idat: bool) -> Vec { + let mut iinf = (items.len() as u16).to_be_bytes().to_vec(); + for (i, it) in items.iter().enumerate() { + let mut e = vec![2u8, 0, 0, 0]; // version 2, flags + e.extend_from_slice(&(i as u16 + 1).to_be_bytes()); + e.extend_from_slice(&[0, 0]); // protection index + e.extend_from_slice(it.kind); + e.extend_from_slice(b"an item\0"); + if it.kind == b"mime" { + e.extend_from_slice(it.content_type.as_bytes()); + e.push(0); + } + iinf.extend_from_slice(&bx(b"infe", &e)); + } + let iinf = full_box(b"iinf", 0, &iinf); + let payload: Vec = items.iter().flat_map(|i| i.data.iter().copied()).collect(); + let idat = if in_idat { bx(b"idat", &payload) } else { Vec::new() }; + let iloc = |base: u32| { + // four-byte offsets and lengths, no base offset and no extent index + let mut l = vec![0x44, 0x00]; + match iloc_version { + 2 => l.extend_from_slice(&(items.len() as u32).to_be_bytes()), + _ => l.extend_from_slice(&(items.len() as u16).to_be_bytes()), + } + let mut at = base; + for (i, it) in items.iter().enumerate() { + match iloc_version { + 2 => l.extend_from_slice(&(i as u32 + 1).to_be_bytes()), + _ => l.extend_from_slice(&(i as u16 + 1).to_be_bytes()), + } + if iloc_version > 0 { + l.extend_from_slice(&[0, u8::from(in_idat)]); // construction method + } + l.extend_from_slice(&[0, 0]); // data reference index: this file + l.extend_from_slice(&[0, 1]); // one extent + l.extend_from_slice(&at.to_be_bytes()); + l.extend_from_slice(&(it.data.len() as u32).to_be_bytes()); + at += it.data.len() as u32; + } + full_box(b"iloc", iloc_version, &l) + }; + let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic"); + let meta = |base| full_box(b"meta", 0, &[iloc(base), iinf.clone(), idat.clone()].concat()); + if in_idat { + // the offsets are into `idat`, so they don't depend on where the box lands + return [ftyp, meta(0)].concat(); + } + let base = (ftyp.len() + meta(0).len() + 8) as u32; + [ftyp, meta(base), bx(b"mdat", &payload)].concat() + } + + /// What an iPhone writes: the civil time it was taken at, plus the UTC offset it was taken in. + fn iphone_exif(date: &str, offset: &str) -> Vec { + let mut exif = IfdBuilder::new(); + exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii(date.into())); + exif.set(t::OFFSET_TIME_ORIGINAL, Value::Ascii(offset.into())); + exif.set(t::ISO_SPEED, Value::Short(vec![64])); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Apple".into())); + ifd0.set(t::MODEL, Value::Ascii("iPhone 15 Pro".into())); + ifd0.set_child(t::EXIF_IFD, exif); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap_or_default() + } + + /// An `Exif` item's payload: the offset from the end of this field to the TIFF header, then + /// `skip` bytes of padding, then the TIFF stream. + fn exif_item(tiff: &[u8], skip: usize) -> Vec { + [&(skip as u32).to_be_bytes()[..], &vec![0u8; skip], tiff].concat() + } + + fn exif_only(tiff: &[u8]) -> Vec> { + vec![Item { kind: b"Exif", content_type: "", data: exif_item(tiff, 0) }] + } + + /// Issue #2284: a photo taken at 13:00 in UTC-5 must stay 13:00, not become 18:00. Before the + /// HEIF items were read a HEIC carried no capture time at all, and the import fell back to the + /// file's modification time, which LightCraft writes as UTC. + #[test] + fn an_iphone_heic_keeps_the_time_the_camera_wrote() { + let file = heic(&exif_only(&iphone_exif("2026:10:18 13:00:00", "-05:00")), 1, false); + let m = crate::extract(&file); + let captured = m.capture_time.expect("a capture time"); + assert_eq!(captured.hour, 13); + assert_eq!(captured.offset_minutes, Some(-5 * 60)); + assert_eq!(captured.to_iso(), "2026-10-18T13:00:00-05:00"); + assert_eq!(m.model.as_deref(), Some("iPhone 15 Pro")); + assert_eq!(m.iso, Some(64)); + } + + #[test] + fn the_xmp_packet_is_the_rdf_mime_item() { + let xmp = crate::write_xmp(&crate::Metadata { title: Some("Cusco".into()), ..Default::default() }, None); + let items = vec![ + Item { kind: b"mime", content_type: "text/plain", data: b"not the packet".to_vec() }, + Item { kind: b"mime", content_type: "application/rdf+xml", data: xmp.clone().into_bytes() }, + Item { kind: b"Exif", content_type: "", data: exif_item(&iphone_exif("2026:10:18 13:00:00", "-05:00"), 0) }, + ]; + let e = embedded(&heic(&items, 1, false)); + assert_eq!(e.xmp.as_deref(), Some(xmp.as_str())); + assert!(e.exif.is_some()); + assert_eq!(crate::extract(&heic(&items, 1, false)).title.as_deref(), Some("Cusco")); + } + + /// Every item location box the format allows: counts and ids are 16-bit before version 2 and + /// 32-bit in it, and the bytes live in `mdat` or in `idat` next to the location box itself. + #[test] + fn items_are_located_in_every_iloc_version() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + for (version, in_idat) in [(0, false), (1, false), (1, true), (2, false), (2, true)] { + let file = heic(&exif_only(&tiff), version, in_idat); + let found = embedded(&file).exif; + assert_eq!(found.as_deref(), Some(tiff.as_slice()), "iloc v{version}, idat {in_idat}"); + } + } + + #[test] + fn the_exif_items_tiff_header_offset_is_honoured() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + let items = vec![Item { kind: b"Exif", content_type: "", data: exif_item(&tiff, 6) }]; + assert_eq!(embedded(&heic(&items, 1, false)).exif.as_deref(), Some(tiff.as_slice())); + } + + #[test] + fn brands() { + for brand in ["heic", "heix", "mif1", "avif", "hevc", "msf1"] { + let file = bx(b"ftyp", format!("{brand}\0\0\0\0mif1").as_bytes()); + assert!(is_heif(&file), "{brand}"); + } + // a compatible brand counts too, a CR3, a JPEG XL and a non-ISO file do not + assert!(is_heif(&bx(b"ftyp", b"mp41\0\0\0\0isomheic"))); + assert!(!is_heif(&bx(b"ftyp", b"crx \0\0\0\0crx isom"))); + assert!(!is_heif(&bx(b"ftyp", b"jxl \0\0\0\0jxl "))); + assert!(!is_heif(b"\xff\xd8\xff\xe1 a jpeg")); + assert!(!is_heif(b"")); + } + + /// A truncated or scrambled file must come back empty, never panic (the never-crash rule). + #[test] + fn broken_files_yield_nothing_without_panicking() { + let good = heic( + &[ + Item { kind: b"Exif", content_type: "", data: exif_item(&iphone_exif("2026:10:18 13:00:00", "-05:00"), 0) }, + Item { kind: b"mime", content_type: "application/rdf+xml", data: b"".to_vec() }, + ], + 1, + false, + ); + for cut in 0..good.len() { + let _ = embedded(&good[..cut]); + } + for at in 0..good.len() { + let mut bad = good.clone(); + bad[at] ^= 0xff; + let _ = embedded(&bad); + } + // an item whose extent is outside the file, and a `meta` box that claims more than it has + let mut lying = good.clone(); + let item_count = u32::MAX.to_be_bytes(); + if let Some(at) = lying.windows(4).position(|w| w == b"iloc") { + lying.splice(at + 8..at + 12, item_count); + } + assert!(embedded(&lying).exif.is_none()); + } + + /// The real container writer of `lightcraft-heif`, so the reader is proved against the layout + /// a HEIF encoder produces and not only against this module's own test builder. + #[test] + fn a_synthetic_heif_file_carries_its_exif() { + let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); + let mut spec = lightcraft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); + spec.exif = Some(tiff.clone()); + let file = lightcraft_heif::testdata::build(&spec); + assert!(is_heif(&file)); + assert_eq!(embedded(&file).exif.as_deref(), Some(tiff.as_slice())); + assert_eq!(crate::extract(&file).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); + } +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index a8c0431533..04fe3b532f 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -1,4 +1,4 @@ -//! Photo metadata for LightCraft: EXIF (TIFF/raw files, JPEG APP1, PNG `eXIf`, WebP `EXIF`), XMP packets +//! Photo metadata for LightCraft: EXIF (TIFF/raw files, JPEG APP1, PNG `eXIf`, WebP `EXIF`, HEIF items), XMP packets //! (read + write, standard namespaces plus our own `lc:` namespace) and basic IPTC-IIM. //! //! Entry points: @@ -7,8 +7,9 @@ //! - [`parse_xmp`] / [`write_xmp`] — XMP packets (interchange fields + the opaque `lc:settings` JSON). //! - [`parse_iptc`] — IPTC-IIM record 2 datasets. //! - [`parse_gpx`] — GPS track logs (GPX) for geotagging by capture time. -//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, Canon CR3). +//! - [`extract`] — all of the above for a whole file (JPEG, PNG, WebP, TIFF/DNG/raw, Canon CR3, HEIF/HEIC/AVIF). //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). +//! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed). #![forbid(unsafe_code)] mod container; @@ -18,6 +19,7 @@ mod exif; pub mod focus; mod focus_read; mod gpx; +pub mod heif; mod iptc; pub mod tags; mod xmp; diff --git a/crates/meta/tests/robust.rs b/crates/meta/tests/robust.rs index cd60e00a92..e1e1efcbf5 100644 --- a/crates/meta/tests/robust.rs +++ b/crates/meta/tests/robust.rs @@ -5,8 +5,8 @@ proptest! { #![proptest_config(ProptestConfig { cases: 1500, .. ProptestConfig::default() })] #[test] - fn random_containers_never_panic(mut data in proptest::collection::vec(any::(), 0..600), kind in 0usize..6) { - let heads: [&[u8]; 6] = [b"\xff\xd8\xff\xe1", b"\x89PNG\r\n\x1a\n", b"RIFF\0\0\0\0WEBP", b"II*\0", b"MM\0*", b"\0\0\0\x18ftypcrx "]; + fn random_containers_never_panic(mut data in proptest::collection::vec(any::(), 0..600), kind in 0usize..7) { + let heads: [&[u8]; 7] = [b"\xff\xd8\xff\xe1", b"\x89PNG\r\n\x1a\n", b"RIFF\0\0\0\0WEBP", b"II*\0", b"MM\0*", b"\0\0\0\x18ftypcrx ", b"\0\0\0\x18ftypheic"]; let h = heads[kind]; if data.len() >= h.len() { data[..h.len()].copy_from_slice(h); From 60843a0c668ada97e3133011e3ae8a527f2a5e5c Mon Sep 17 00:00:00 2001 From: tecari0 <121329615+tecari0@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:15:49 -0700 Subject: [PATCH 0011/1092] #2284: document the HEIF reader's test helpers and the shared box readers The pre-merge docstring check counts every function the diff touches. The `be16` / `be32` / `be64` readers became crate-public here, and the HEIF tests added helpers and cases without a line saying what each one covers. Co-Authored-By: Claude Opus 5 --- crates/meta/src/cr3.rs | 3 +++ crates/meta/src/heif.rs | 7 +++++++ crates/meta/tests/robust.rs | 2 ++ 3 files changed, 12 insertions(+) diff --git a/crates/meta/src/cr3.rs b/crates/meta/src/cr3.rs index 77d8dec4a7..a95b8baada 100644 --- a/crates/meta/src/cr3.rs +++ b/crates/meta/src/cr3.rs @@ -407,12 +407,15 @@ fn sample_entry(bytes: &[u8], e: &BoxRef, budget: &mut usize) -> Cr3TrackKind { Cr3TrackKind::Raw { width, height, cmp1, iad1 } } +/// A big-endian `u16` at `at`, or `None` when the buffer is shorter than that. pub(crate) fn be16(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]])) } +/// A big-endian `u32` at `at`, or `None` when the buffer is shorter than that. pub(crate) fn be32(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } +/// A big-endian `u64` at `at`, or `None` when the buffer is shorter than that. pub(crate) fn be64(b: &[u8], at: usize) -> Option { let s = b.get(at..at.checked_add(8)?)?; let mut a = [0u8; 8]; diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs index 98f3f0a3e6..1d768f7a69 100644 --- a/crates/meta/src/heif.rs +++ b/crates/meta/src/heif.rs @@ -200,6 +200,7 @@ mod tests { use crate::embedded; use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + /// One box: its own size, its four-letter kind, then its payload. fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); v.extend_from_slice(kind); @@ -207,6 +208,7 @@ mod tests { v } + /// A FullBox: a box whose payload begins with a version byte and three flag bytes. fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec { bx(kind, &[&[version, 0, 0, 0][..], payload].concat()) } @@ -289,6 +291,7 @@ mod tests { [&(skip as u32).to_be_bytes()[..], &vec![0u8; skip], tiff].concat() } + /// One `Exif` item holding `tiff`, the only item in the file. fn exif_only(tiff: &[u8]) -> Vec> { vec![Item { kind: b"Exif", content_type: "", data: exif_item(tiff, 0) }] } @@ -308,6 +311,7 @@ mod tests { assert_eq!(m.iso, Some(64)); } + /// The XMP packet is the `mime` item that declares `application/rdf+xml`, not any other one. #[test] fn the_xmp_packet_is_the_rdf_mime_item() { let xmp = crate::write_xmp(&crate::Metadata { title: Some("Cusco".into()), ..Default::default() }, None); @@ -334,6 +338,8 @@ mod tests { } } + /// The `Exif` item's leading offset may point past padding, not only straight at the TIFF + /// header, and the reader has to follow it. #[test] fn the_exif_items_tiff_header_offset_is_honoured() { let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); @@ -341,6 +347,7 @@ mod tests { assert_eq!(embedded(&heic(&items, 1, false)).exif.as_deref(), Some(tiff.as_slice())); } + /// Which `ftyp` brands count as a still image in this container, major or compatible. #[test] fn brands() { for brand in ["heic", "heix", "mif1", "avif", "hevc", "msf1"] { diff --git a/crates/meta/tests/robust.rs b/crates/meta/tests/robust.rs index e1e1efcbf5..7a3179d579 100644 --- a/crates/meta/tests/robust.rs +++ b/crates/meta/tests/robust.rs @@ -4,6 +4,8 @@ use proptest::prelude::*; proptest! { #![proptest_config(ProptestConfig { cases: 1500, .. ProptestConfig::default() })] + /// Random bytes behind each container's magic: reading them yields whatever can be read and + /// never panics. #[test] fn random_containers_never_panic(mut data in proptest::collection::vec(any::(), 0..600), kind in 0usize..7) { let heads: [&[u8]; 7] = [b"\xff\xd8\xff\xe1", b"\x89PNG\r\n\x1a\n", b"RIFF\0\0\0\0WEBP", b"II*\0", b"MM\0*", b"\0\0\0\x18ftypcrx ", b"\0\0\0\x18ftypheic"]; From 78a01f47dbe1c61f6bf533df0e258abc2a1efacf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 19 Oct 2026 11:29:52 +0000 Subject: [PATCH 0012/1092] #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 `