From fade8e7d4b7b3e148c13ab5e4750e91eca4ccb13 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:51:51 +0200 Subject: [PATCH 01/29] LR-PROF-CAMERACOLOR: align lens-corrected camera JPEG training pairs Use resolved lens geometry and independently gated framing alignment for RAW/camera-JPEG calibration pairs, including pooled calibration and DNG color tags. Resolve unnamed fixed-lens profiles only through a unique exact fixed mount. Invalidate cached looks and previews. Add synthetic geometry, mask, orientation and fixed-mount regressions. Validate actual RAW renders against the previously tested fix, and run all eight cargo xtask ci gates on the separate Clippy prerequisite. --- crates/engine/src/camera_preview.rs | 355 ++++++++++++++++++++++++--- crates/engine/src/camera_profiles.rs | 3 +- crates/engine/src/lens_profiles.rs | 63 ++++- crates/engine/src/media.rs | 2 +- docs/camera-preview-colour.md | 12 +- docs/gaps.md | 5 +- docs/lens-profiles.md | 10 +- docs/parity-checklist.md | 7 +- 8 files changed, 415 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index d074567a79..bb0667b4d5 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -39,7 +39,8 @@ use lightcraft_raw::{ /// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a /// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data /// stored with each smart preview. -pub const LOOK_VERSION: u32 = 12; +/// 13: geometry-gated external lens and camera framing for JPEG calibration correspondences. +pub const LOOK_VERSION: u32 = 13; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -87,7 +88,8 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool { /// as-shot white, the camera transform at it and the fitted look. /// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from /// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing. -/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit. +/// `embedded` is the resolved lens correction in the oriented default crop: its geometry may align +/// file-local calibration correspondences, and its vignetting is used by the DNG tone fit. pub(crate) fn starting_colour( raw: &mut RawImage, bytes: &[u8], @@ -96,13 +98,13 @@ pub(crate) fn starting_colour( ) -> (Xy, CameraTransform, Option) { let (xy, t, look) = starting_colour_with( raw, - |raw, t| fit_preview(raw, bytes, t, lens), - |raw, t| monochrome_look(raw, bytes, t, lens), + |raw, t| fit_preview(raw, bytes, t, lens, embedded), + |raw, t| monochrome_look(raw, bytes, t, lens, embedded), |raw, t| { if !file_local_look(raw.format) { return None; } - let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens, embedded)?; fit_dark_tone(&sensor, &reference, &clipped) }, ); @@ -175,11 +177,20 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option, +) -> Option { // the white the source shows, decided before `starting_colour` may fill in measured matrices let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw)); // (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling) - let (_, t, look) = starting_colour(raw, bytes, None, None); + let (_, t, look) = starting_colour(raw, bytes, None, correction); dng_colour(&raw.color, &white, &t, look.as_ref()) } @@ -277,11 +288,17 @@ fn dng_tone_curve(tone: &CameraTone) -> Option { } /// The look fitted to the file's camera JPEG, and whether that JPEG is black and white ([`monochrome`]). -pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> (Option, bool) { +pub(crate) fn fit_preview( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> (Option, bool) { if !transform.matrix_is_fallback || !file_local_look(raw.format) { return (None, false); } - let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens) else { return (None, false) }; + let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens, correction) else { return (None, false) }; let black_and_white = monochrome(&reference); // A camera profile pooled from many photos knows colours this photo shows too little of; // try its colour first and fit tone/chroma per photo (picture styles vary). @@ -467,7 +484,9 @@ fn fit_dng_tone(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: } None }; - let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None) else { return refuse("preview") }; + let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None, None) else { + return refuse("preview"); + }; // As the loader renders it: the profile's tables around the baseline exposure. let xy = lightcraft_raw::color::as_shot_white_xy(raw); if let Some(tables) = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy)) { @@ -618,6 +637,7 @@ fn proxies( size: usize, min_fraction: f64, lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { let edge = (2 * size).max(384) as u32; let decoded = crate::files::decode_raw_preview( @@ -661,6 +681,23 @@ fn proxies( .and_then(|l| Some((into_lens_geometry(&sensor, raw, k, l)?, into_lens_geometry(&clipped, raw, k, l)?))); let gain = 2f32.powf(transform.baseline_exposure as f32); let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain)); + // External profiles describe the developed default crop, unlike OpcodeList3's active-area warp. + // Keep the established CR3/in-file routes; only an uncalibrated file with no in-file warp + // may propose this additional correspondence geometry. Its acceptance uses edges, never RGB error. + let aligned_external = correction + .filter(|correction| { + raw.format != RawFormat::Cr3 && file_local_look(raw.format) && transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some() + }) + .and_then(|correction| { + let mut working = sensor.clone(); + working.map_in_place(to_working); + align_profile_geometry(&working, &clipped, &reference, correction, raw.orientation) + }); + let external_applied = aligned_external.is_some(); + if let Some((aligned, mask)) = aligned_external { + sensor = aligned; + clipped = mask; + } if raw.format == RawFormat::Cr3 { // Orient the camera JPEG and the sensor identically before collecting pixel correspondences. sensor = sensor.into_oriented(raw.orientation); @@ -685,7 +722,7 @@ fn proxies( // NaN: those pixels are left out of the pairs anyway). Resized to exactly the proxy's size, like // the reference, so the mask pairs pixel for pixel. let clipped: Vec = resize(&clipped, sensor.width, sensor.height, Filter::Box).data.iter().map(|p| p[0] > 0.0).collect(); - if raw.format != RawFormat::Cr3 { + if raw.format != RawFormat::Cr3 && !external_applied { sensor.map_in_place(to_working); } Some((sensor, reference, clipped)) @@ -721,6 +758,12 @@ impl Cr3Framing { /// A separate third of the edges must confirm a substantial improvement and a close match. /// A weak, flat or unrelated preview leaves the sensor framing unchanged. fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option { + estimate_framing_against(sensor, reference, sensor) +} + +/// Score both a proposed lens geometry and its bounded framing against the original sensor. +/// The identity framing is a valid candidate: lens correction alone may already align the JPEG. +fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option { if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() { return None; } @@ -733,7 +776,12 @@ fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option Option Option Option { + let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool| -> Option { let (mut agreement, mut weight, mut valid, mut total) = (0.0, 0.0, 0usize, 0usize); for &(x, y, target, magnitude, holdout) in &edges { if holdout != held_out { @@ -779,15 +829,15 @@ fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight) }; - let before = score(Cr3Framing::IDENTITY, false)?; - let mut best = (before, Cr3Framing::IDENTITY); + let before = score(&original_gradients, Cr3Framing::IDENTITY, false)?; + let mut best = (score(&gradients, Cr3Framing::IDENTITY, false).unwrap_or(-1.0), Cr3Framing::IDENTITY); // At most 10% zoom and two proxy pixels of translation; a coarse search followed by one // local refinement prevents unbounded optimisation on the photograph's contents. for s in -10..=10 { for tx in -4..=4 { for ty in -4..=4 { let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] }; - if let Some(value) = score(framing, false) + if let Some(value) = score(&gradients, framing, false) && value > best.0 { best = (value, framing); @@ -806,7 +856,7 @@ fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 { continue; } - if let Some(value) = score(framing, false) + if let Some(value) = score(&gradients, framing, false) && value > best.0 { best = (value, framing); @@ -814,12 +864,12 @@ fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option {held_after:.4}", best.1); + eprintln!("[profile] camera JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1); } Some(best.1) } @@ -839,15 +889,71 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg (apply(&sensor), apply(&clipped)) } +/// Resample a correspondence image with a common source map. Nonfinite/outside coordinates +/// become NaN so they cannot contribute colour or tone training pairs. A nonnegative clip mask +/// uses the same bilinear map: any clipped contributing sample remains strictly positive. +fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) -> lightcraft_geom::Point) -> Rgb32f { + let (w, h) = (image.width, image.height); + let mut out = Rgb32f::new(w, h); + if w == 0 || h == 0 { + return out; + } + for (i, pixel) in out.data.iter_mut().enumerate() { + let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + *pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 { + image.sample_bilinear(p.x as f32, p.y as f32) + } else { + [f32::NAN; 3] + }; + } + out +} + +/// A resolved profile is a proposal for camera-JPEG geometry, never an instruction to change +/// the rendered RAW's optics. The lens is already relative to the oriented default crop; +/// re-express it in this un-oriented sensor proxy's frame before using its green-plane warp. +/// Candidate and original are judged on the same fixed edges, with independent held-out edges. +fn align_profile_geometry( + sensor: &Rgb32f, + clipped: &Rgb32f, + reference: &Rgb32f, + correction: &lightcraft_develop::EmbeddedLens, + orientation: lightcraft_geom::Orientation, +) -> Option<(Rgb32f, Rgb32f)> { + if correction.warp.is_none() || (sensor.width, sensor.height) != (clipped.width, clipped.height) { + return None; + } + let (w, h) = (sensor.width as f64, sensor.height as f64); + let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) }; + let correction = lightcraft_pipeline::optics::reorient_lens(correction, orientation.inverse(), ow, oh); + let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h); + warp.lens = Some(correction); + warp.lens_dist = 1.0; + let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1); + let candidate = resample_correspondence(sensor, source); + let framing = estimate_framing_against(&candidate, reference, sensor)?; + let mask = resample_correspondence(clipped, source); + let frame = |x: f64, y: f64| { + let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); + lightcraft_geom::Point::new(f64::from(x), f64::from(y)) + }; + Some((resample_correspondence(&candidate, frame), resample_correspondence(&mask, frame))) +} + /// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the /// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own /// colour matrices, other files or unusable previews. -pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option> { +pub(crate) fn profile_pairs( + raw: &RawImage, + bytes: &[u8], + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option> { if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) { return None; } let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw)); - let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?; let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); @@ -1479,11 +1585,17 @@ fn monochrome(reference: &Rgb32f) -> bool { /// `transform` is the colour the photo gets otherwise (the spectral matrices or the fallback's); the look keeps it and /// adds the tone curve alone ([`fit_tone_only_with`]), as [`fit_look_with`] tries the photo's own colour after a profile's. The /// chroma curve stays neutral: the JPEG has no colourfulness to learn. -fn monochrome_look(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> Option { +fn monochrome_look( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + lens: Option<&LensGeometry>, + correction: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option { if !file_local_look(raw.format) { return None; } - let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens)?; + let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens, correction)?; if !monochrome(&reference) { return None; } @@ -2769,7 +2881,7 @@ mod tests { raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); let (Some((plain, reference, _)), Some((chosen, chosen_reference, _))) = - (proxies(&raw, &bytes, &t, PROXY, 0.0, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens))) + (proxies(&raw, &bytes, &t, PROXY, 0.0, None, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens), None)) else { continue; }; @@ -3013,6 +3125,193 @@ mod tests { assert!(estimate_cr3_framing(&sensor, &reference).is_none(), "unrelated edges cannot change the framing"); } + fn profile_geometry_scene(w: usize, h: usize) -> Rgb32f { + let mut sensor = Rgb32f::new(w, h); + for (i, p) in sensor.data.iter_mut().enumerate() { + let (x, y) = ((i % w) as f32 * 192.0 / w as f32, (i / w) as f32 * 128.0 / h as f32); + let v = 0.35 + 0.13 * (x * 0.15 + y * 0.22).sin() + 0.1 * (x * 0.33 - y * 0.14).sin() + 0.07 * (x * 0.09 - y * 0.31).cos(); + *p = [v * (0.9 + 0.15 * (y * 0.023).sin()), v, v * (0.9 + 0.15 * (x * 0.019).cos())]; + } + sensor + } + + fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { + lightcraft_develop::EmbeddedLens { + warp: Some(lightcraft_develop::EmbeddedWarp { + planes: [[1.04, -0.24, 0.08, 0.0, 0.0, 0.0]; 3], + center: lightcraft_geom::Point::new(0.48, 0.53), + radius: 0.61, + }), + ..Default::default() + } + } + + fn profile_geometry_target(sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedLens, framing: Cr3Framing) -> Rgb32f { + let mut warp = lightcraft_pipeline::optics::Warp::identity(sensor.width as f64, sensor.height as f64); + warp.lens = Some(*lens); + warp.lens_dist = 1.0; + let warped = resample_correspondence(sensor, |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1)); + resample_correspondence(&warped, |x, y| { + let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); + lightcraft_geom::Point::new(f64::from(x), f64::from(y)) + }) + } + + fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 { + let mut error = 0.0; + let mut n = 0; + for (a, b) in a.data.iter().zip(&b.data) { + for (&a, &b) in a.iter().zip(b) { + if a.is_finite() && b.is_finite() { + error += f64::from(a - b).powi(2); + n += 1; + } + } + } + assert!(n > 256); + (error / f64::from(n)).sqrt() + } + + #[test] + fn external_profile_geometry_aligns_lens_and_framing_before_colour() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let expected = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + let mut jpeg = expected.clone(); + jpeg.map_in_place(|p| p.map(|v| v.powf(0.7))); + let mask = Rgb32f::new(sensor.width, sensor.height); + let (aligned, _) = align_profile_geometry(&sensor, &mask, &jpeg, &lens, lightcraft_geom::Orientation::Normal) + .expect("lens and bounded framing pass independent geometry gates"); + assert!(geometry_rms(&aligned, &expected) < 0.008, "the training sensor is correctly registered despite a nonlinear camera tone"); + assert!(geometry_rms(&sensor, &expected) > 0.05, "synthetic mismatch is material"); + } + + #[test] + fn external_profile_geometry_accepts_lens_only_and_rejects_unrelated_or_already_aligned() { + let sensor = profile_geometry_scene(384, 256); + let lens = synthetic_profile_lens(); + let expected = profile_geometry_target(&sensor, &lens, Cr3Framing::IDENTITY); + let mask = Rgb32f::new(sensor.width, sensor.height); + let (aligned, _) = align_profile_geometry(&sensor, &mask, &expected, &lens, lightcraft_geom::Orientation::Normal) + .expect("lens alone aligns; no improvement over its own framing is required"); + assert!(geometry_rms(&aligned, &expected) < 0.001); + assert!( + align_profile_geometry(&sensor, &mask, &sensor, &lens, lightcraft_geom::Orientation::Normal).is_none(), + "already aligned original is preserved" + ); + let mut unrelated = sensor.clone(); + for (i, p) in unrelated.data.iter_mut().enumerate() { + let (x, y) = ((i % sensor.width) as f32, (i / sensor.width) as f32); + *p = [0.35 + 0.13 * (x * 0.41 - y * 0.07).sin() + 0.1 * (x * 0.04 + y * 0.39).cos(); 3]; + } + assert!(align_profile_geometry(&sensor, &mask, &unrelated, &lens, lightcraft_geom::Orientation::Normal).is_none()); + unrelated.data.fill([0.2; 3]); + assert!(align_profile_geometry(&sensor, &mask, &unrelated, &lens, lightcraft_geom::Orientation::Normal).is_none()); + assert!( + align_profile_geometry(&sensor, &mask, &expected, &Default::default(), lightcraft_geom::Orientation::Normal).is_none(), + "no geometric profile leaves the established path alone" + ); + } + + #[test] + fn external_profile_geometry_preserves_oriented_default_crop_and_resolution() { + let lens = synthetic_profile_lens(); + for (w, h) in [(192, 128), (384, 256)] { + // This is the developed default crop: no active-area offset is applied a second time. + let sensor = profile_geometry_scene(w, h); + let target = profile_geometry_target(&sensor, &lens, Cr3Framing::IDENTITY); + let mask = Rgb32f::new(w, h); + for exif in 1..=8 { + let orientation = lightcraft_geom::Orientation::from_exif(exif); + let oriented = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, w as f64, h as f64); + let (aligned, _) = align_profile_geometry(&sensor, &mask, &target, &oriented, orientation) + .expect("oriented resolved lens maps back to the sensor crop"); + assert!(geometry_rms(&aligned, &target) < 0.001, "orientation {exif}, {w}x{h}"); + } + } + } + + #[test] + fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { + use lightcraft_raw::{BlackLevel, RawData, Rect}; + let (w, h) = (416, 288); + let scene = profile_geometry_scene(w, h); + let mut raw = raw_of(RawFormat::Cr2, "Synthetic", "Uncalibrated", Default::default()); + raw.width = w; + raw.height = h; + raw.cpp = 3; + raw.data = RawData::F32(scene.data.iter().flatten().copied().collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.active_area = Rect::new(0, 0, w, h); + raw.crop = Rect::new(16, 16, 384, 256); + raw.linearized = true; + raw.wb_multipliers = Some([1.0; 3]); + let transform = lightcraft_raw::color::camera_transform(&raw, D65); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + assert_eq!((sensor.width, sensor.height), (384, 256)); + sensor.map_in_place(|p| transform.matrix.apply_f32(p)); + let lens = synthetic_profile_lens(); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = + target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); + for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { + file.extend(tag.to_le_bytes()); + file.extend(4u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(value.to_le_bytes()); + } + file.extend(0u32.to_le_bytes()); + file.extend(jpeg); + let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); + let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); + let mut plain_render = plain; + plain_render.map_in_place(|p| p.map(|v| v.powf(0.7))); + aligned.map_in_place(|p| p.map(|v| v.powf(0.7))); + assert!( + geometry_rms(&aligned, &reference) < geometry_rms(&plain_render, &reference) * 0.3, + "the file-local route uses the resolved crop-relative correction" + ); + let error = |pairs: Vec<([f64; 3], [f64; 3])>| { + let sum: f64 = + pairs.iter().map(|(x, y)| transform.matrix.apply(*x).iter().zip(y).map(|(x, y)| (x.powf(0.7) - y).powi(2)).sum::()).sum(); + sum / pairs.len() as f64 + }; + let before = error(profile_pairs(&raw, &file, None, None).unwrap()); + let after = error(profile_pairs(&raw, &file, None, Some(&lens)).unwrap()); + assert!(after < before * 0.1, "pooled colour calibration uses the same geometry: {before} -> {after}"); + // Merge / DNG conversion must encode the same calibrated colour as opening the RAW. + let mut opened = raw.clone(); + let (_, t, look) = starting_colour(&mut opened, &file, None, Some(&lens)); + assert!(look.is_some(), "the synthetic corrected preview supplies a camera look"); + let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); + let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(&raw)); + let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); + let tags = starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap(); + assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too"); + } + + #[test] + fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_border() { + let mut mask = Rgb32f::new(8, 6); + mask.data[2 * 8 + 3] = [1.0; 3]; + let result = resample_correspondence(&mask, |x, y| lightcraft_geom::Point::new(x + 0.75, y + 0.5)); + assert!(result.data[8 + 2][0] > 0.0 && result.data[8 + 3][0] > 0.0); + assert!(result.data[2 * 8 + 2][0] > 0.0 && result.data[2 * 8 + 3][0] > 0.0); + assert_eq!(result.data[0][0], 0.0); + assert!(result.data[7][0].is_nan() && result.data[5 * 8][0].is_nan()); + // The final box reduction retains fractional positive masks as clipped too. + let reduced = resize(&result, 4, 3, Filter::Box); + assert!(reduced.data.iter().any(|p| p[0] > 0.0)); + } + /// The guarded fit is assessed on real sensor data, never on the JPEG fallback. A corpus /// download or an unfinished codec cannot make this test claim a successful RAW calibration. #[test] @@ -3036,7 +3335,7 @@ mod tests { assert_eq!(raw.format, RawFormat::Cr3); assert_eq!(raw.info().developed_size(), (6000, 4000)); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0; + let look = fit_preview(&raw, &bytes, &transform, None, None).0; eprintln!("R100 guarded colour fit accepted: {}", look.is_some()); assert!(look.is_some(), "this R100 corpus photo has enough matching colour after camera-framing alignment"); let (_, info) = crate::files::load_bytes(&bytes, 400).unwrap(); @@ -3069,7 +3368,7 @@ mod tests { let raw = lightcraft_raw::decode(&bytes).unwrap(); assert_eq!(raw.metadata.model.as_deref(), Some(model)); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0.expect("fit accepted"); + let look = fit_preview(&raw, &bytes, &transform, None, None).0.expect("fit accepted"); let expected = bundled.matrix().mul(&transform.matrix.inverse().unwrap()); for (row, want) in look.matrix.0.iter().zip(expected.0) { for (got, want) in row.iter().zip(want) { @@ -3450,9 +3749,9 @@ mod tests { let mut raw = lightcraft_raw::decode(&bytes).unwrap(); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = fit_preview(&raw, &bytes, &transform, None).0.expect("a camera look"); + let look = fit_preview(&raw, &bytes, &transform, None, None).0.expect("a camera look"); // the look fitted to the JPEG, as before this change - let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None).unwrap(); + let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None, None).unwrap(); let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get); let colour = profile.as_ref().and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone()))); let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap(); @@ -4149,12 +4448,12 @@ mod tests { tiff }; let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); - let look = monochrome_look(&raw, &file([1.0; 3]), &t, None).expect("a tone curve from the black-and-white JPEG"); + let look = monochrome_look(&raw, &file([1.0; 3]), &t, None, None).expect("a tone curve from the black-and-white JPEG"); assert!(look.matrix == Mat3::IDENTITY && look.hue_sat.is_none(), "on the transform's colour"); let curve = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0); let mid = curve.apply(0.25); assert!((mid - (1.0 - (-0.75f32).exp())).abs() < 0.05, "the camera's curve at 0.25: {mid}"); - assert!(monochrome_look(&raw, &file([1.0, 0.9, 0.8]), &t, None).is_none(), "a tinted JPEG is not black and white"); + assert!(monochrome_look(&raw, &file([1.0, 0.9, 0.8]), &t, None, None).is_none(), "a tinted JPEG is not black and white"); } /// The black-and-white fit has the partial look's checks: a JPEG of another picture, or one the default curve diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index c7b6c437b1..ff558cd57a 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -202,10 +202,11 @@ impl Pool { let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?; // colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow // the warp the camera applied to its JPEG) + let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes)); let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; - let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) }; + let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref(), correction.as_ref()) else { return Ok(None) }; let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1); let entry = self.models.entry(model.to_owned()).or_default(); entry.0 += 1; diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index 6e7f28120f..9a43931625 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -36,7 +36,8 @@ pub fn database() -> Option<&'static LensDb> { } /// The database profile for a photo with metadata `m`, for its `w × h` (unoriented, default-cropped) image, -/// re-expressed after `orientation`. `None` without a database, lens name, focal length or matching profile. +/// re-expressed after `orientation`. Without a lens name/specification, a unique fixed-mount profile may identify it. +/// `None` without a database, focal length or unambiguous matching profile. pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orientation: lightcraft_geom::Orientation) -> Option { let focal = m.focal_length.filter(|f| f.is_finite() && *f > 0.0)?; let camera = db.find_camera(m.make.as_deref().unwrap_or_default(), m.model.as_deref().unwrap_or_default()); @@ -44,10 +45,27 @@ pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orient Some(model) => db.find_lens(m.lens_make.as_deref(), model, camera)?, // Nikon DSLRs record only the lens specification ("24-70mm f/2.8"); a profile must be named exactly that // (a user's alias), since the specification fits other makers' lenses too - None => { - let name = lightcraft_lensdb::spec_name(m.lens_spec?); - db.find_lens_named(m.lens_make.as_deref(), &name, camera)? - } + None => match m.lens_spec { + Some(spec) => { + let name = lightcraft_lensdb::spec_name(spec); + db.find_lens_named(m.lens_make.as_deref(), &name, camera)? + } + None => { + let camera = camera?; + // Lensfun reserves lowercase initial mount names for fixed-lens cameras: + // https://lensfun.github.io/manual/latest/el_mount.html + // This is an exact identity, never interchangeable-mount compatibility. + if !camera.mount.chars().next().is_some_and(char::is_lowercase) { + return None; + } + let mut profiles = db.lenses.iter().filter(|lens| lens.mounts.iter().any(|mount| mount == &camera.mount)); + let profile = profiles.next()?; + if profiles.next().is_some() { + return None; + } + profile + } + }, }; let crop = frame_crop_factor(camera.map(|c| c.crop_factor), focal, m.focal_length_35mm); let shot = Shot { focal, aperture: m.f_number, distance: None, crop_factor: crop, width: w, height: h }; @@ -102,6 +120,41 @@ mod tests { } } + #[test] + fn unnamed_fixed_lens_requires_unique_exact_lowercase_mount() { + let mut db = LensDb::parse(DB).unwrap(); + db.cameras[0].mount = "compact-tc1".into(); + db.lenses[0].mounts = vec!["compact-tc1".into()]; + let unnamed = lightcraft_meta::Metadata { lens_model: None, lens_spec: None, ..meta() }; + let at = |db: &LensDb, m: &lightcraft_meta::Metadata| lookup(db, m, 6000.0, 4000.0, Orientation::Normal); + let expected = at(&db, &meta()).unwrap(); + assert_eq!(at(&db, &unnamed), Some(expected)); + let mut changed = db.clone(); + changed.lenses.push(changed.lenses[0].clone()); + assert!(at(&changed, &unnamed).is_none(), "duplicate profiles are ambiguous"); + assert_eq!(at(&changed, &meta()), Some(expected), "named route keeps existing behaviour"); + changed = db.clone(); + changed.lenses[0].mounts = vec!["Compact-tc1".into()]; + assert!(at(&changed, &unnamed).is_none(), "mount identity is case sensitive"); + changed.lenses[0].mounts = vec!["compact-other".into()]; + assert!(at(&changed, &unnamed).is_none(), "another fixed mount is not compatible"); + changed.lenses[0].mounts.clear(); + assert!(at(&changed, &unnamed).is_none(), "missing mount is not an identity"); + for mount in ["Interchangeable", "", "1fixed"] { + changed = db.clone(); + changed.cameras[0].mount = mount.into(); + changed.lenses[0].mounts = vec![mount.into()]; + assert!(at(&changed, &unnamed).is_none(), "only lowercase initial fixed mounts qualify: {mount}"); + } + changed = db.clone(); + changed.cameras.clear(); + assert!(at(&changed, &unnamed).is_none(), "no camera means no fixed mount"); + let specified = lightcraft_meta::Metadata { lens_spec: Some([18.0, 55.0, 3.5, 5.6]), ..unnamed }; + assert!(at(&db, &specified).is_none(), "unmatched specification does not fall back to a fixed mount"); + let wrongly_named = lightcraft_meta::Metadata { lens_model: Some("Unknown 1000mm".into()), ..meta() }; + assert!(at(&db, &wrongly_named).is_none(), "unmatched lens name does not fall back"); + } + #[test] fn exif_lens_is_found_and_converted() { let db = LensDb::parse(DB).unwrap(); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 292a9fb1e7..e76ef81691 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 69; +pub const RENDER_CACHE_VERSION: u64 = 70; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 7a1235ab35..4547780f2b 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -2,6 +2,10 @@ ARW, NEF, RW2, RAF, CR3, CR2, PEF, SRW, ORF, ERF and MRW decoding supply sensor data and camera white-balance multipliers, but currently no measured camera colour matrix. Treating camera RGB as linear sRGB produces a dark, muted default rendering. The loader now estimates a file-local starting look from that file's embedded camera JPEG, only when a usable camera matrix is absent. All output pixels still come from the RAW sensor data; there is no JPEG replacement or uniform saturation boost. +## Geometry validation scope + +On five private Canon PowerShot G7 X Mark II photographs, native fixed-mount lookup plus the gated profile/framing correspondence path reproduces the validated local correction. Four full-resolution renders remove the large pink sky regions and substantially reduce skin posterization. Four other RAWs (Sony A7 III, Canon 5D, 6D and 7D) and four JPEGs stay pixel-identical at 1600 px; without a configured matching profile the tested G7 X II frame stays unchanged. CPU and Metal differ by at most one 8-bit level on a full-resolution frame. The camera JPEG is a visual reference, not a colorimetric ground truth; private files are not included. Synthetic regression tests are the reproducible coverage in the repository. These observations do not establish all-camera colour correctness. + ## Colour and tone are separate A fixed sensor proxy of at most 96×96 is developed with the file's WB, black/white levels and active crop. The embedded JPEG is decoded with DCT scaling and a 128-million-pixel input limit (61 MP bodies' JPEGs, e.g. the ILCE-7RM6 full frame at 66.5 MP, exceed 64 MP; the codec checks the cap before decoding at full size, about 200 MB transient), converted through the codec's colour management, and reduced to the same size. Aspect ratios must agree within 2%. For colour fitting, near-black, clipped and nonfinite samples are excluded. Learning a colour matrix requires at least 256 paired pixels, 5% coloured samples (linear channel spread >0.05) and a nonsingular input covariance with bounded condition. An existing camera profile supplies the colour model: fitting only tone still requires 256 pairs and 5% non-monochrome samples, but permits channel spread >0.005 so dark or dull scenes can use the known colours. Any tone curve (full, partial or black-and-white look) also needs some contrast: the scene luminance of the brightest 1/32 of the pairs must be at least 1.2× that of the darkest 1/32 (`MIN_TONE_RANGE`); below that, the range check refuses the curve, which leaves only nearly uniform frames. A curve under 1.5× (the limit until issue #631) must also render the frame's bright areas, which the fit and the held-out gates leave out (camera JPEG luminance 0.85 and up), no further from the camera JPEG than the neutral fallback does (in luminance for a black-and-white JPEG): fitted to a narrow range, it extrapolates them. A hazy ILCE-7RM4 burst at 1.46 to 1.49 opened with the neutral fallback, 18 L\* darker than its camera JPEG, while the frame at 1.51 got a look at a held-out RMS of 0.013; with 1.2 they all do. Across 135 public Sony files the lowest range is 4.0, so none of them changes. @@ -16,10 +20,16 @@ Matrix-only and matrix + table looks are each completed (tone curve, then chroma The matrix is applied to scene-linear sensor pixels. The curve is carried in `SourceInfo` and applied in the pipeline finish stage, after exposure/WB/local edits. It is never baked into decoded luminance or clipped to JPEG precision. CPU and GPU use the same tone LUT. Contrast, whites and blacks adjust the starting look through the display-domain controls. JPEG neutral rendering and the existing DNG colour model are unchanged. -One third of the pixels are held out from both fits. The combined model must reduce linear-display squared error by at least 30% and have per-channel RMS error ≤0.10 (0.055 rejected half of the public raw.pixls.us samples tried — ILCE-6400, -6700, -7M4 — whose fits were still 1.5–3× closer to the camera JPEG than the fallback and visibly better). When the fit on all pixels fails these gates, it is tried once more, with the same gates, on the pixels away from edges (where the 3×3 neighbourhood in either proxy spans a luminance ratio above 3). Many camera JPEGs are lens-corrected while the raw is not (Sony "Distortion Comp.: Auto", compacts and kit zooms), and on a detailed scene the misaligned edges alone fail the gate although the colours agree everywhere else (issue #232). Sony's embedded lens tables now correct ILCE-7RM6 renders under Enable Lens Corrections ([Sony ARW lens corrections](sony-ilce7rm6-lens-corrections.md)), but this fit still matches its pairs without them (the sensor proxy is uncorrected); aligning the pairs first is a follow-up. The public ILCE-7RM2 samples (raw.pixls.us, one façade shot in seven compression/correction variants, 24–70 mm at 51 mm) are up to 15 px of 1440 off their JPEG; the six with distortion correction on missed the gate at held-out RMS 0.108–0.115 and opened in the grey neutral fallback, 13 L* too dark (ΔE76 16.6–16.9 against the JPEG after registering its geometry). Away from edges they pass at 0.049–0.052 and land at ΔE 3.7–3.8 with lightness within 0.6 L*, like the variant shot with distortion correction off (0.059 on all pixels, ΔE 3.9). The corpus GX80 kit-zoom sample (up to 63 px of 1440 off) passes too: 0.107 → 0.081, ΔE 19.1 → 7.9. Fits accepted on all pixels are unchanged. These are provisional acceptance gates, not a colour-accuracy certification. Singular, unrelated and aspect-mismatched references retain the documented fallback; poor-fitting ones get the partial look below when it is clearly closer to the camera JPEG, and black-and-white ones only their tone curve (below). Both fits use the same fixed proxy at every decode resolution. +One third of the pixels are held out from both fits. The combined model must reduce linear-display squared error by at least 30% and have per-channel RMS error ≤0.10 (0.055 rejected half of the public raw.pixls.us samples tried — ILCE-6400, -6700, -7M4 — whose fits were still 1.5–3× closer to the camera JPEG than the fallback and visibly better). When the fit on all pixels fails these gates, it is tried once more, with the same gates, on the pixels away from edges (where the 3×3 neighbourhood in either proxy spans a luminance ratio above 3). Many camera JPEGs are lens-corrected while the raw is not (Sony "Distortion Comp.: Auto", compacts and kit zooms), and on a detailed scene the misaligned edges alone fail the gate although the colours agree everywhere else (issue #232). Sony's embedded lens tables now correct ILCE-7RM6 renders under Enable Lens Corrections ([Sony ARW lens corrections](sony-ilce7rm6-lens-corrections.md)), and can now also propose that resolved correction when pairing the sensor with the JPEG (subject to the independent geometry gates below). The public ILCE-7RM2 samples (raw.pixls.us, one façade shot in seven compression/correction variants, 24–70 mm at 51 mm) are up to 15 px of 1440 off their JPEG; the six with distortion correction on missed the gate at held-out RMS 0.108–0.115 and opened in the grey neutral fallback, 13 L* too dark (ΔE76 16.6–16.9 against the JPEG after registering its geometry). Away from edges they pass at 0.049–0.052 and land at ΔE 3.7–3.8 with lightness within 0.6 L*, like the variant shot with distortion correction off (0.059 on all pixels, ΔE 3.9). The corpus GX80 kit-zoom sample (up to 63 px of 1440 off) passes too: 0.107 → 0.081, ΔE 19.1 → 7.9. Fits accepted on all pixels are unchanged. These are provisional acceptance gates, not a colour-accuracy certification. Singular, unrelated and aspect-mismatched references retain the documented fallback; poor-fitting ones get the partial look below when it is clearly closer to the camera JPEG, and black-and-white ones only their tone curve (below). Both fits use the same fixed proxy at every decode resolution. **Lens-corrected camera JPEGs.** Some raws carry the camera's own lens correction (Fujifilm and Panasonic tables, the ILCE-7RM4A, Nikon's NikonNEFInfo) and the camera often applies it to its JPEG. Nikon Z lenses always do, and that JPEG can be zoomed in by up to 9% to fill the frame. The fit used to pair the uncorrected sensor with the corrected JPEG, so near the edges it compared pixels from different parts of the scene. Now the sensor proxy is also warped with the file's correction (`into_lens_geometry`, pixels that land outside the picture are dropped), and the fit uses whichever of the two lines up better with the JPEG, going by the correlation of their high-passed log luminance. Files whose JPEG isn't corrected keep the plain proxy. On the 29 CC0 corpus raws with a warp the alignment goes up by 0.13 on average (Panasonic GX80 0.41 to 0.83, Fujifilm X-T20 0.44 to 0.95). Mean ΔE against the camera JPEG over the 35 corpus raws of those formats goes from 3.73 to 3.61, and on 299 private Z 6II photos with Nikon's correction read it goes from 3.22 to 2.68. +**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route; absent profiles, CR3 and the established opcode-warp route retain their existing behaviour. + +This changes calibration correspondences only, including `calibrate`'s pooled pairs and the colour tags used by merge/DNG conversion. It is independent of the user's Optics switch and does not bake geometric correction into the rendered RAW. Sensor and clipping mask follow the same sampling maps; invalid borders cannot train the look. Matrix, hue/saturation, tone fitting and their colour-error acceptance gates are unchanged. A physically plausible lens correction alone is not assumed to match a camera JPEG: geometry must establish the correspondence before it is used. Cached renders and camera looks have new versions so online originals rebuild their calibration. Cameras without a safely resolved geometric profile receive no new guarantee of colour accuracy. + +Synthetic regression tests cover lens-only and lens-plus-framing alignment, rejection of unrelated/flat/already-aligned references, all eight EXIF orientations, default cropping at two resolutions, file-local and pooled pairs, DNG colour tags, and clipped-sample/invalid-border masks. These tests establish correspondence behaviour, not camera-specific colour accuracy. A user-supplied database and native metadata that safely resolve a profile are still required for external-profile alignment; unnamed fixed lenses can use a unique exact lowercase camera mount as described in [Lens profiles](lens-profiles.md). + **A partial look when the full look misses the gates.** The neutral fallback (camera RGB taken as sRGB, the default tone map) is far from the camera JPEG. Rendered for every photo on this path in the CC0 archive (1,150 files with a camera JPEG), it is 10.7 L\* too dark (median; about one stop), keeps 0.36 of the camera's colourfulness and has hues 7° off on the coloured pixels (median CIEDE2000 13.6). Its white balance is right: on the pixels the camera renders near-neutral the cast is under 1 a\*/b\* (median, every maker). The "blue" fallback on newer Sony bodies (Δb\* −22 over the whole frame on the ILCE-7RM5 sample) is a warm scene losing its colour, not a cast: its near-neutral pixels are within −1.6 b\*. So before falling back, a partial look is fitted (`fit_partial`): the quantile tone curve (registration-free, the largest part of the error), the chroma curve, and, when the scene has enough colour to learn a matrix (the full look's condition), the photo's own colour matrix at half weight, the other half the identity (`PARTIAL_MATRIX_WEIGHT`). No hue/saturation table. Half weight because, on the held-out proxy pixels of the 23 colourful photos without a look, the full matrix left 2 of them more than 2° further from the camera's hues than the neutral fallback and half weight none (median hue error 9.6° with the generic colour, 5.1° at half weight, 4.2° at full weight; on the 1,080 photos with a look 3.9° and 2.7°). Without a matrix (tone and chroma curve alone, or with one global saturation scale) about a third of all photos ended up more than 2° further from the camera's hues than the fallback, as the added colour makes the generic matrix's hue errors visible. The partial look is tried on all pixels, then away from edges, and used only when it cuts the held-out squared error below 0.7 of the neutral fallback's in linear and in gamma-encoded display values, and when the JPEG's luminance ranks the pixels like the scene's (Spearman ≥ 0.5, `PARTIAL_MIN_RANK_CORRELATION`): a curve matched to the brightness of an unrelated picture also beats the dark fallback pixel for pixel. The accepted full looks have 0.55 or more; three old Coolpix files whose raws decode wrongly have 0.07–0.27 and keep the fallback. There is no limit on the partial look's own error. On the archive (1,783 renders): all 1,087 full looks are byte-identical; of the 55 photos that reach the partial fit, 49 get it (40 on all pixels, 9 away from edges; 13 with the damped matrix, 41 with a chroma curve) and 6 keep the fallback (lens-corrected compacts: RX10, TZ80 1:1, D-LUX 4, G10 16:9, GF2 ×2). On the 49, median CIEDE2000 to the camera JPEG 14.0 → 2.1, ΔL\* −11.5 → +0.6, colourfulness 0.36 → 0.87, hue error 10.1° → 7.1°; every one is closer, by at least 1.3. Most of the others without a look never reach a fit: on 48 files (Nikon D4, Df, D300/D300S, D7000, D5100 and others) the camera JPEG proxy comes out a pixel narrower than the sensor proxy and no pairs are collected (the resize in PR #531 fixes this; with it 46 of them pass the full look's gates, CIEDE2000 17.9 → 2.9). **A tone curve from a black-and-white JPEG.** A raw shot in a monochrome picture style (Canon Monochrome, Sony B/W, Nikon Monochrome) records full colour, but its camera JPEG is grey, so neither the full look nor the partial look has colour to fit. Such a photo started from the spectral matrices or the neutral fallback with the default tone curve: on a Canon EOS RP, about 1.3 EV darker and flatter than the same body's photos shot in colour (issue #577). The grey JPEG still shows the camera's tone curve. When no look was fitted and every pixel of the JPEG proxy but one in a thousand has its channels within 0.002 of each other (`monochrome`; a sepia-toned JPEG has colour and isn't one), the quantile tone curve is fitted alone, luminance against luminance, on top of the colour the photo gets otherwise: the model's camera profile when it has one (in `fit_preview`, like the profile's colour looks), else its spectral matrices or the neutral fallback's (`monochrome_look`). The chroma curve stays neutral. It has the partial look's checks: the JPEG must rank the pixels like the scene (Spearman ≥ 0.5, with tied values sharing their rank, so a flat grey JPEG relates to nothing), and the curve must cut the held-out squared luminance error below 0.7 of the default curve's, in linear and gamma-encoded values, on all pixels or away from edges. Sony's DRO is handled as for colour JPEGs, and white balance stays relative to the as-shot look. The check reads pixels, not the picture style: a colour JPEG of a scene so colourless that every pixel is grey within 0.002 counts too (such a photo gets no look today either). Photos whose JPEG has colour render as before. diff --git a/docs/gaps.md b/docs/gaps.md index be411a2050..ab2aeab22f 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-21 · **Change:** minor (gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** patch (camera-preview correspondences can use safely resolved lens geometry after independent edge gates; synthetic coverage, calibration status and counts unchanged) 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 @@ -15,7 +15,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | # | Gap | Evidence | User impact | Hours | Doc | |---:|---|---|---|---:|---| -| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 5 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | +| 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 5 bundled profiles or 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307; resolved geometric profiles may align camera-JPEG training pairs after independent edge gates, with synthetic regression coverage) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 0 chart-calibrated models vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | | 3 B | **Render fidelity unmeasured** (LR-BEHAV-RENDER-FIDELITY): tone, highlights, texture / clarity / dehaze, NR and sharpening are tuned by eye | no side-by-side suite; a retune needs a new process version (only V1 exists) | edits imported from Lightroom look different; the look "isn't Lightroom's" | 30–60 | [raw-parity](raw-parity.md), [process-versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | @@ -79,6 +79,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-10-23 | patch | LR-PROF-CAMERACOLOR: gate resolved-profile calibration geometry against original sensor edges; synthetic regressions; camera-calibration status, counts and readiness estimates unchanged | | 2026-10-21 | minor | Gap 28 shrinks: F8 shows / hides the right panel (`view.rightPanel`); rating `[` `]`, flag cycling and F1 help were already bound, so the entry lists only filter-bar keys, Tab / ⇧Tab and F5; 2–4 h (was 4–8) | | 2026-10-20 | minor | #2362: import destination albums use the shared hierarchy/search picker instead of a flat name list; existing import workflows retained; ranked gaps/readiness counts unchanged | | 2026-10-19 | minor | Gap 21: Indonesian (`id`) shipped with every catalog message but What's New; four new languages left (Hindi, Arabic, Korean, Vietnamese), 135–239 h | diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index 13d1b2b7a7..d9e6f6e014 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -30,6 +30,14 @@ nor a name with a maker in it ("Samyang 85mm f/1.4" for "85mm f/1.4") is taken; files names its profile that way, e.g. a lensfun entry with an extra `24-70mm f/2.8` for the one 24-70 f/2.8 the photographer owns. lensfun's own database has no such names, so it doesn't correct these files. +A fixed-lens camera that records neither a lens model nor a lens specification can use its camera database +entry's mount instead. [Lensfun reserves lowercase initial mount names for fixed-lens cameras](https://lensfun.github.io/manual/latest/el_mount.html). +The existing camera lookup is retained; exactly one lens profile with its case-sensitive mount is accepted. Missing, +uppercase interchangeable, mismatching or ambiguous mounts retain the no-profile fallback. Named lenses and +specification aliases keep their existing lookup rules; an unmatched name/specification does not trigger this +fallback. This identifies an available correction, not evidence that the camera JPEG uses it: calibration still +requires the independent geometry gates described in [Camera preview colour](camera-preview-colour.md). + | Correction | Models | Interpolated over | |---|---|---| | Distortion | `poly3`, `poly5`, `ptlens` | focal length | @@ -51,4 +59,4 @@ the image centre (lensfun's `
` offsets are not read). - Only raws: rendered images (JPEG, HEIF, TIFF) are often already corrected in camera. - The focus distance is not read from maker notes yet: vignetting uses the farthest calibrated distance. - No manual make / model picker yet; matching is automatic. -- Not yet validated against real photos and another renderer; the tests use synthetic profiles and grids. +- Automated tests use synthetic profiles and grids. Limited real-file validation of the fixed-mount fallback and its use for colour correspondences covers five private G7 X II photographs; this does not establish geometric accuracy across other cameras or profiles. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 99f17561e3..6f832067d6 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-21 · **Change:** minor (LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** patch (camera-preview correspondences can use safely resolved lens geometry after independent edge gates; synthetic coverage, calibration status and 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 @@ -212,7 +212,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | ⬜ | | | | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-S20, X-T30 III, X-M5, X-T5 crops) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; no settings switch or bundled database yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-S20, X-T30 III, X-M5, X-T5 crops) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; no settings switch or bundled database yet Fixed lenses without a recorded lens name/specification may use a unique profile on the resolved camera's exact lowercase mount; ambiguous profiles are rejected (`docs/lens-profiles.md`); camera lookup and named/specification routes unchanged. | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | @@ -236,7 +236,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PROF-ADOBE | Standard raw looks (own equivalents) | P0 | ✅ | `crates/engine/src/presets.rs` (`PROFILES`), `crates/pipeline/src/profiles.rs` | six own looks: Color, Neutral, Vivid, Landscape, Portrait, Monochrome | | LR-PROF-ADAPTIVE | Adaptive profiles | P2 | ⬜ | | | | LR-PROF-CAMERA | Camera-matching looks | P2 | ⬜ | | | -| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) | +| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG whose profile defines no tone curve (absent or identity `ProfileToneCurve`, with or without a `LookTable`, as Adobe Standard in Lightroom-written DNGs) gets its tone fitted to its embedded preview when that is at least 10% of the raw's long edge and 384 px (Lightroom's 1024 px previews qualify): two Lightroom Classic 15.1 lossy ILCE-7CM2 DNGs went from about 0.8 EV darker and flat to within 3% of Lightroom's mean linear RGB. A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it; bundled ILCA-99M2 from 144 photos: 30 held-out 5.11 → 4.87, 25 of them closer); the tone fit also uses dark JPEG samples excluded from colour training, so deep shadows follow the camera toe (#1307); near-black frames with too few colour pairs can take a guarded tone-only fallback on their existing source colour (#1587); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today; ILCE-7RM6: per-file fit now runs on previews above 64 MP, a pooled profile (46 photos) was tried and not bundled (withheld ΔE 5.71 → 6.40, 11 of 15 regressed), kept with smart previews (see docs/camera-preview-colour.md); the fit pairs the sensor moved into the file's lens-warp geometry when that lines up better with a lens-corrected camera JPEG (29 CC0 raws: alignment +0.13, mean ΔE 3.73 → 3.61); bundled NIKON Z 6_2 profile (296 photos; 59 held-back photos mean ΔE 2.73 → 2.54) NIKON Z 8 profile (261 photos; 55 held back 2.55 → 2.33) and NIKON D5300 profile (264 photos; 53 held back 2.86 → 2.66) Resolved geometric profiles may align file-local and pooled training pairs only after independent edge-direction gates; synthetic geometry tests cover framing, orientation, crop and masks; camera-calibration status remains 🟡. | | LR-PROF-CREATIVE | Creative profiles (own) | P2 | ✅ | `cmd:develop.profile`, `crates/pipeline/src/profiles.rs` | 16 own looks in Film / Cinematic / Muted / B&W (tone + point-curve fades, colour grading, mixer / B&W mix); scale with `ctl:profile.amount`; sliders untouched | | LR-PROF-LEGACY | Legacy profiles | P2 | ⬜ | | | | LR-PROF-NONRAW | Profiles for non-raw files | P0 | ✅ | `cmd:develop.profile` | same looks apply to JPEG/TIFF | @@ -798,6 +798,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-23 | patch | LR-PROF-CAMERACOLOR: gate resolved-profile calibration geometry against original sensor edges; synthetic regressions; unnamed fixed lenses can resolve a unique exact lowercase mount (LR-EDIT-OPTICS-PROFILE); camera-calibration status, counts and readiness estimates unchanged | | 2026-10-21 | patch | LR-IMP-ADD-DIALOG: reconcile #2362 with current main; deleted-album guard and hierarchical picker retained; counts unchanged | | 2026-10-20 | minor | LR-IMP-ADD-DIALOG: #2362 gives the import review the shared hierarchy/search album picker while retaining None/New album and existing destination IDs; status and feature counts unchanged | | 2026-10-21 | patch | KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the slider's row; leaving it (even between two frames) or Tab focus alone does not arm them (issue #1355); status unchanged | From a4e70cbfe2ddb8aefb451be0ed076cc4a4bbb3f6 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:33:41 +0100 Subject: [PATCH 02/29] MENU-EDIT-SELECTBY: Select by lists each star rating on its own (#3311) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit > Select by only offered "and higher" rows, so there was no way to select just the three-star photos. A second block of rows, one per rating ("★★★ only"), now sits above Unrated and runs library.selectBy with ratingOp eq. A menu test checks the rows and that the three-star row selects exactly the photos in view rated three. --- crates/ui-egui/src/menus/menubar.rs | 12 +++++++++ crates/ui-egui/src/menus/menubar/tests.rs | 33 +++++++++++++++++++++++ docs/parity-checklist.md | 5 ++-- docs/whats-new.md | 7 +++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 5c1bcb9fc1..e134c6fa4a 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -754,6 +754,18 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> v.extend((1..=5u8).map(|r| { item("library.selectBy", json!({"rating": r}), crate::i18n::tr_format!("{} and higher", "★".repeat(r as usize)), None, true, None) })); + // each rating on its own (#3311), with Unrated as the zero row + v.push(MenuNode::Separator); + v.extend((1..=5u8).map(|r| { + item( + "library.selectBy", + json!({"rating": r, "ratingOp": "eq"}), + crate::i18n::tr_format!("{} only", "★".repeat(r as usize)), + None, + true, + None, + ) + })); v.push(item("library.selectBy", json!({"rating": 0, "ratingOp": "eq"}), "Unrated", None, true, None)); v.push(MenuNode::Separator); v.extend(lightcraft_catalog::ColorLabel::ALL.iter().map(|l| { diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index 1e2fe388dd..34353533db 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -372,6 +372,39 @@ fn select_by_submenu_and_text_prompt() { assert_eq!(app.session.catalog.photo(id).unwrap().versions[0].name, "Final"); } +/// #3311: Select by offers each rating on its own beside "and higher", and an exact row selects +/// only the photos in view with that rating. +#[test] +fn select_by_offers_exact_ratings() { + let mut app = app(); + let ids = app.session.visible().to_vec(); + for (i, id) in ids.iter().enumerate() { + app.session.execute("library.select", &json!({"ids": [id]})).unwrap(); + app.session.execute("photo.rate", &json!({"rating": i % 6})).unwrap(); + } + let bar = menu_bar(&app); + let edit = &bar.iter().find(|(t, _)| t == "Edit").unwrap().1; + let Some(MenuNode::Submenu { children, .. }) = edit.iter().find(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Select by")) else { + panic!("no Select by submenu") + }; + let exact = |r: u8| { + children.iter().find_map(|n| match n { + MenuNode::Item { id, params, .. } if id == "library.selectBy" && *params == json!({"rating": r, "ratingOp": "eq"}) => { + Some(params.clone()) + } + _ => None, + }) + }; + for r in 1..=5 { + assert!(exact(r).is_some(), "no row for exactly {r} stars"); + } + let visible = app.session.visible().to_vec(); + let want: Vec<_> = visible.iter().copied().filter(|&p| app.session.catalog.photo(p).unwrap().rating == 3).collect(); + assert!(!want.is_empty() && want.len() < visible.len(), "the demo holds photos rated 3 and others"); + run_item(&mut app, "library.selectBy", exact(3).unwrap()).unwrap(); + assert_eq!(app.session.selection.ids, want); +} + #[test] fn help_opens_the_docs_and_merge_last_needs_photos() { let mut app = app(); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f6..e837f48d12 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-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (MENU-EDIT-SELECTBY: exact-rating rows (★ only … ★★★★★ only) beside the "and higher" rows, #3311; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **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 @@ -525,7 +525,7 @@ visible menu bar yet: the menu model is only exposed through the control channel | MENU-EDIT-PASTESELECTED | Paste Selected Settings | P0 | ✅ | `cmd:dialog.pasteSettings`, `cmd:develop.paste` (`groups`) | checklist prefilled with the copied groups; only copied groups can be pasted; Return pastes, Esc cancels | | MENU-EDIT-SELECTALL | Select All | P0 | ✅ | `cmd:library.selectAll` | | | MENU-EDIT-SELECTNONE | Select None | P0 | ✅ | `cmd:library.selectNone` | | -| MENU-EDIT-SELECTBY | Select by flag / rating | P1 | ✅ | `cmd:library.selectBy` | Edit → Select by: picks, rejects, unflagged, ★…★★★★★ and higher, unrated, colour labels; `add` extends the selection | +| MENU-EDIT-SELECTBY | Select by flag / rating | P1 | ✅ | `cmd:library.selectBy` | Edit → Select by: picks, rejects, unflagged, ★…★★★★★ and higher, ★…★★★★★ only (`ratingOp: eq`, #3311), unrated, colour labels; `add` extends the selection | | MENU-EDIT-FIND | Find… | P0 | ✅ | `cmd:view.focusSearch`, `crates/ui-egui/src/panels/topbar.rs` | ⌘F focuses the search field | | MENU-VIEW-PHOTOGRID | Photo Grid | P0 | ✅ | `cmd:view.photoGrid` | | | MENU-VIEW-SQUAREGRID | Square Grid | P0 | ✅ | `cmd:view.squareGrid` | | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | MENU-EDIT-SELECTBY: Edit → Select by lists each rating on its own (★ only … ★★★★★ only, `library.selectBy` with `ratingOp: eq`) after the "and higher" rows, beside Unrated (#3311); status unchanged (✅) | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..363cd3ca03 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,12 @@ # What's new in LightCraft +## 2026-10-29 + +### Select by a single star rating +- Edit ▸ Select by now lists each rating on its own (★ only through ★★★★★ only) below the “and higher” rows, + next to Unrated. Choosing ★★★ only selects the photos in view rated exactly three stars, where before the menu + could only select three stars and up (#3311). + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From 94d905f481e2c0dfdb55900203f43159d3973fe1 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:56:24 +0100 Subject: [PATCH 03/29] MENU-EDIT-SELECTBY: translate the Select by exact-rating rows (#3311) --- crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/src/menus/menubar/tests.rs | 19 +++++++++++++++++++ 18 files changed, 36 insertions(+) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d..38e6bb63cb 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -233,6 +233,7 @@ "{} label (click more labels to show any of them)": "Štítek {} (kliknutím na další štítky zobrazíte fotografie s kterýmkoli z nich)", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} ze 4 vodítek — táhněte podél čar, které mají být svislé nebo vodorovné.", "{} of {} from {host}": "{} z {} z {host}", + "{} only": "pouze {}", "{} photos": "Fotografií: {}", "{} photos · exposures {} EV": "Fotografií: {} · expozice {} EV", "{} photos · {} · {:.0}° × {:.0}°": "Fotografií: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f1364..8ad1817dbe 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -181,6 +181,7 @@ "{} files and {f} folder{}": "{} Dateien und {f} Ordner{:.0}", "{} item{}": "Elemente: {}{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} von 4 Hilfslinien – entlang von Linien ziehen, die senkrecht oder waagerecht sein sollen.", + "{} only": "nur {}", "{} photos": "Fotos: {}", "{} photos · exposures {} EV": "{} Fotos · Belichtungen {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} Fotos · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6..78a2b0a252 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -181,6 +181,7 @@ "{} files and {f} folder{}": "{} archivos y {f} carpeta{}", "{} item{}": "{0} elemento{1}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} de 4 guías: arrastrar a lo largo de líneas que deban ser verticales u horizontales.", + "{} only": "solo {}", "{} photos": "{} fotos", "{} photos · exposures {} EV": "{} fotos · exposiciones {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} fotos · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9..e7d81e3a18 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -281,6 +281,7 @@ "{} label (click more labels to show any of them)": "Merkintä: {} (napsauta lisää merkintöjä näyttääksesi minkä tahansa niistä)", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} / 4 apuviivaa — vedä pysty- tai vaakasuoraksi tarkoitettujen viivojen suuntaisesti.", "{} of {} from {host}": "{} / {} kohteesta {host}", + "{} only": "vain {}", "{} photos": "Kuvia: {}", "{} photos · exposures {} EV": "Kuvia: {} · valotukset {} EV", "{} photos · {} · {:.0}° × {:.0}°": "Kuvia: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e..be61762ca3 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -181,6 +181,7 @@ "{} files and {f} folder{}": "{} fichiers et {f} dossier{}", "{} item{}": "{} élément{}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} guides sur 4 — faites-les glisser le long des lignes qui doivent être verticales ou horizontales.", + "{} only": "{} uniquement", "{} photos": "{} photos", "{} photos · exposures {} EV": "{} photos · expositions {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} photos · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221..bc2ae40dff 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -108,6 +108,7 @@ "{} files": "{} file", "{} files and {f} folder{}": "{} file dan {f} folder{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} dari 4 garis panduan — seret di sepanjang garis yang seharusnya vertikal atau horizontal.", + "{} only": "hanya {}", "{} photos": "{} foto", "{} photo{} not readable": "{} foto tidak dapat dibaca{:.0}", "{} spot(s) on this photo": "{} bintik di foto ini", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e94..0ffe46247d 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -178,6 +178,7 @@ "{} files and {f} folder{}": "{} file, cartelle: {f}{:.0}", "{} item{}": "Elementi: {}{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} di 4 guide: trascina lungo le linee che dovrebbero essere verticali o orizzontali.", + "{} only": "solo {}", "{} photos": "{} foto", "{} photos · exposures {} EV": "{} foto · esposizioni {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} foto · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16d..a6cc4f88fa 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -108,6 +108,7 @@ "{} files": "{}個のファイル", "{} files and {f} folder{}": "{}個のファイルと{f}個のフォルダ{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "ガイド4本中{}本:垂直または水平にする線に沿ってドラッグ", + "{} only": "{}のみ", "{} photos": "{}枚", "{} photo{} not readable": "{}枚を読み込めません{:.0}", "{} spot(s) on this photo": "この写真に{}か所のスポット", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 4603682618..9a257342e7 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -232,6 +232,7 @@ "{} label (click more labels to show any of them)": "იარლიყი „{}“ (დაწკაპეთ სხვა იარლიყებზე, რომ ნებისმიერი მათგანის მქონე ფოტო გამოჩნდეს)", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "დამხმარე ხაზი: {} / 4 — გაავლეთ ხაზებზე, რომლებიც ვერტიკალური ან ჰორიზონტალური უნდა იყოს.", "{} of {} from {host}": "{} / {} — {host}-დან", + "{} only": "მხოლოდ {}", "{} photos": "ფოტო: {}", "{} photos · exposures {} EV": "ფოტო: {} · ექსპოზიციები {} EV", "{} photos · {} · {:.0}° × {:.0}°": "ფოტო: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6..52e9ea49ac 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -170,6 +170,7 @@ "{} files and {f} folder{}": "Pliki: {}, foldery: {f}{:.0}", "{} item{}": "Elementy: {}{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} z 4 prowadnic — przeciągnij wzdłuż linii, które powinny być pionowe lub poziome.", + "{} only": "tylko {}", "{} photos": "Zdjęcia: {}", "{} photos · exposures {} EV": "Zdjęcia: {} · ekspozycje {} EV", "{} photos · {} · {:.0}° × {:.0}°": "Zdjęcia: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4..db3bb84d41 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -136,6 +136,7 @@ "{} files": "{} arquivos", "{} files and {f} folder{}": "{} arquivos e {f} pasta{}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} de 4 guias — arraste ao longo das linhas que devem ficar verticais ou horizontais.", + "{} only": "somente {}", "{} photos": "{} fotos", "{} photo{} not readable": "{} foto(s) não legível(is){:.0}", "{} spot(s) on this photo": "{} ponto(s) nesta foto", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af4276..9baf6eb183 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -188,6 +188,7 @@ "{} item{}": "Элементов: {}{:.0}", "{} label (click more labels to show any of them)": "Метка «{}» (щёлкните другие метки, чтобы показать фото с любой из них)", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "Направляющих: {} из 4 — проведите вдоль линий, которые должны быть вертикальными или горизонтальными.", + "{} only": "только {}", "{} photos": "Фото: {}", "{} photos · exposures {} EV": "Фото: {} · экспозиции {} EV", "{} photos · {} · {:.0}° × {:.0}°": "Фото: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c..62123d5697 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -272,6 +272,7 @@ "{} MB": "{} MB", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} av 4 stödlinjer – dra längs linjer som ska vara vertikala eller horisontella.", "{} of {} from {host}": "{} av {} från {host}", + "{} only": "endast {}", "{} photos": "{} foton", "{} photos · exposures {} EV": "{} foton · exponeringar {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} foton · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a2..e64aa4a0ad 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -181,6 +181,7 @@ "{} files and {f} folder{}": "Файлів: {}, тек: {f}{:.0}", "{} item{}": "Елементів: {}{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "Напрямних: {} із 4 — проведіть уздовж ліній, які мають бути вертикальними або горизонтальними.", + "{} only": "лише {}", "{} photos": "Фото: {}", "{} photos · exposures {} EV": "Фото: {} · експозиції {} EV", "{} photos · {} · {:.0}° × {:.0}°": "Фото: {} · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff06..7a2ab59ac9 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -281,6 +281,7 @@ "{} label (click more labels to show any of them)": "Nhãn «{}» (nhấp thêm nhãn để hiện ảnh có bất kỳ nhãn nào)", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "{} / 4 đường dẫn — kéo dọc các đường cần thẳng đứng hoặc nằm ngang.", "{} of {} from {host}": "{} / {} từ {host}", + "{} only": "chỉ {}", "{} photos": "{} ảnh", "{} photos · exposures {} EV": "{} ảnh · phơi sáng {} EV", "{} photos · {} · {:.0}° × {:.0}°": "{} ảnh · {} · {:.0}° × {:.0}°", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b86..f1ec24656a 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -108,6 +108,7 @@ "{} files": "{0} 个文件", "{} files and {f} folder{}": "{0} 个文件和 {f} 个文件夹{1:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "已画 {0} 条参考线(共 4 条)— 沿应为垂直或水平的线拖动。", + "{} only": "仅 {0}", "{} photos": "{0} 张照片", "{} photo{} not readable": "{0} 张照片无法读取{1:.0}", "{} spot(s) on this photo": "此照片上有 {0} 处污点", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a..8805822495 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -132,6 +132,7 @@ "{} files": "{} 個檔案", "{} files and {f} folder{}": "{} 個檔案與 {f} 個資料夾{:.0}", "{} of 4 guides — drag along lines that should be vertical or horizontal.": "已繪製 {}/4 條參考線 — 沿應為垂直或水平的線條拖曳。", + "{} only": "僅 {}", "{} photos": "{} 張照片", "{} photo{} not readable": "{} 張照片無法讀取{:.0}", "{} spot(s) on this photo": "此照片有 {} 個斑點", diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index 34353533db..94851e3a0b 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -405,6 +405,25 @@ fn select_by_offers_exact_ratings() { assert_eq!(app.session.selection.ids, want); } +/// #3311: the exact-rating rows are translated like "and higher" ones, not left in English. +#[test] +fn select_by_exact_rating_rows_are_translated() { + fn label_of(nodes: &[MenuNode], want: &serde_json::Value) -> Option { + nodes.iter().find_map(|n| match n { + MenuNode::Item { id, params, label, .. } if id == "library.selectBy" && params == want => Some(label.clone()), + MenuNode::Submenu { children, .. } => label_of(children, want), + _ => None, + }) + } + let app = app(); + crate::i18n::set_language(crate::i18n::Locale::De); + let bar = menu_bar(&app); + crate::i18n::set_language(crate::i18n::Locale::En); + let edit = &bar.iter().find(|(t, _)| t == "Edit").unwrap().1; + assert_eq!(label_of(edit, &json!({"rating": 3, "ratingOp": "eq"})).as_deref(), Some("nur ★★★")); + assert_eq!(label_of(edit, &json!({"rating": 3})).as_deref(), Some("★★★ und höher")); +} + #[test] fn help_opens_the_docs_and_merge_last_needs_photos() { let mut app = app(); From 06db61e5e5cb1354b9f1df0ce2aa0d43623470f9 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:42:09 +0100 Subject: [PATCH 04/29] LR-BEHAV-TITLEBAR: pressing at the search box's edge no longer moves the window (#2807) The search field paints a 28 px box, but its text field fills only the middle (10 px in from each side, 4 px from top and bottom). That padding was still the title bar's empty area, so on macOS a press there, where a text selection often starts, dragged the window. The whole box is now a click-only widget of the field's: the window stays still there, and a click on it puts the cursor in the field. It is not focusable, so Tab still stops once, on the field. Test: the_search_box_edges_keep_the_window_from_moving. --- crates/ui-egui/src/panels/topbar.rs | 10 +++++++++ crates/ui-egui/src/tests/titlebar.rs | 33 ++++++++++++++++++++++++++++ docs/parity-checklist.md | 5 +++-- docs/whats-new.md | 8 +++++++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index 5e3fea8a11..c22efff505 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -89,6 +89,12 @@ fn search_field(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rect if std::mem::take(&mut app.ui.focus_search) { ui.memory_mut(|m| m.request_focus(id)); } + // The whole painted box is the field's, not the title bar's: the text field below fills only + // its middle, so without this a press on its padding (where a selection often starts) landed + // on the empty bar and, on macOS, moved the window (#2807). A click there focuses the field. + // `Sense::CLICK` and not `Sense::click()`: not focusable, so Tab still stops once, on the field, + // and screen readers get no second node beside it. + let bx = ui.interact(sr, id.with("box"), Sense::CLICK).on_hover_cursor(egui::CursorIcon::Text); let focused = ui.memory(|m| m.has_focus(id)); ui.painter().rect( sr, @@ -115,6 +121,10 @@ fn search_field(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rect .text_color(t.text) .show(&mut child) .response; + // after the field: it gives up the focus on a click outside its own rect + if bx.clicked() { + ui.memory_mut(|m| m.request_focus(id)); + } if resp.changed() { let q = app.ui.search.clone(); let _ = app.run("library.filter", json!({"text": q})); diff --git a/crates/ui-egui/src/tests/titlebar.rs b/crates/ui-egui/src/tests/titlebar.rs index 8d40f212ec..694c4eb9ad 100644 --- a/crates/ui-egui/src/tests/titlebar.rs +++ b/crates/ui-egui/src/tests/titlebar.rs @@ -191,3 +191,36 @@ fn a_panel_floating_over_the_bar_keeps_the_window_from_moving() { play(&mut h); assert!(!hover(&mut h, empty), "the floating panel covers the empty bar there"); } + +// Scenario: the search box's padding, around the text, is the field's too: pressing there (where +// a selection often starts) never moves the window, and a click there puts the cursor in the +// field (#2807) +#[test] +fn the_search_box_edges_keep_the_window_from_moving() { + let mut h = integrated(); + let r = widget(&h, "field:search"); + let hover = |h: &mut Headless, p: egui::Pos2| { + h.events.push(egui::Event::PointerMoved(p)); + play(h); + craft_window::title_bar::window_movable(&h.view.ctx) + }; + // the painted box is 28 high, centred on the field, and 10 wider on each side + let left_edge = egui::pos2(r.left() - 5.0, r.center().y); + let top_edge = egui::pos2(r.center().x, r.center().y - 12.0); + assert!(r.top() > top_edge.y, "the top edge point is outside the text field: {r:?}"); + assert!(!hover(&mut h, left_edge), "the box's left padding"); + assert!(!hover(&mut h, top_edge), "the box's top padding"); + assert!(!hover(&mut h, r.center()), "the text field"); + // above the box, the bar is empty again + assert!(hover(&mut h, egui::pos2(r.center().x, r.center().y - 18.0)), "the empty bar above the box moves the window"); + h.request("ui.click", json!({"x": left_edge.x, "y": left_edge.y}), T); + play(&mut h); + let field = crate::text_field::id("field:search"); + assert!(h.view.ctx.memory(|m| m.has_focus(field)), "a click on the box's edge focuses the field"); + assert!(h.window_commands.is_empty(), "{:?}", h.window_commands); + // the box takes no keyboard focus: Shift+Tab from the field goes past it + h.request("ui.key", json!({"key": "Tab", "shift": true}), T); + play(&mut h); + let focused = h.view.ctx.memory(|m| m.focused()); + assert!(focused.is_some_and(|f| f != field && f != field.with("box")), "{focused:?}"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f6..6fedab3c74 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-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-TITLEBAR: pressing at the search box's edge, around its text, no longer moves the window, #2807; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **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 @@ -485,7 +485,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-LEARN | Tutorials | OOS | 🚫 | | | | LR-BEHAV-WHATSNEW | What's new | P2 | ✅ | `cmd:app.whatsNew`, `docs/whats-new.md` | Help ▸ What's New: release highlights | | LR-BEHAV-AI-EA | Early-access badges | P2 | ⬜ | | | -| LR-BEHAV-TITLEBAR | Title bar drag and double-click zoom (macOS) | P2 | 🟡 | `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/tests/titlebar.rs` | the native title bar is hidden on macOS, so the top bar's empty space (including the traffic-light margin) moves the window and a double-click does what System Settings › “Double-click a window's title bar to” says (zoom or restore, minimize, nothing; craft-window's `title_bar`); buttons and the search field keep their clicks; ignored in full screen, where the traffic lights are gone and the bar's left buttons move into their space (#1763). A press that starts on a button, the search field or a panel floating over the bar never moves the window (AppKit's `movable` is off while the pointer is there). Known gap: egui-winit reads the zoomed state only at start-up and after our own `Maximized` command, so a window zoomed another way (green button, Window ▸ Zoom, snapping) makes the first double-click a no-op before the toggle catches up. Checked by hand on a real macOS window (drag, zoom, restore) | +| LR-BEHAV-TITLEBAR | Title bar drag and double-click zoom (macOS) | P2 | 🟡 | `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/tests/titlebar.rs` | the native title bar is hidden on macOS, so the top bar's empty space (including the traffic-light margin) moves the window and a double-click does what System Settings › “Double-click a window's title bar to” says (zoom or restore, minimize, nothing; craft-window's `title_bar`); buttons and the search field keep their clicks; ignored in full screen, where the traffic lights are gone and the bar's left buttons move into their space (#1763). A press that starts on a button, the search field or a panel floating over the bar never moves the window (AppKit's `movable` is off while the pointer is there). The search field is its whole painted box, the padding around the text included: a click there puts the cursor in the field (#2807). Known gap: egui-winit reads the zoomed state only at start-up and after our own `Maximized` command, so a window zoomed another way (green button, Window ▸ Zoom, snapping) makes the first double-click a no-op before the toggle catches up. Checked by hand on a real macOS window (drag, zoom, restore) | ## Y. Menus @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-30 | patch | LR-BEHAV-TITLEBAR: the search box's padding around its text is the field's, not the title bar's: pressing there no longer moves the window on macOS, and a click there focuses the field (#2807); status counts unchanged | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..78227010c7 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-30 + +### Pressing at the search box's edge no longer moves the window +- On macOS the top bar is the window's title bar, and the search box's padding around its text still belonged to + it: a press there, where a text selection often starts, dragged the whole window instead. The whole box is now + the search field's. A click anywhere in it puts the cursor in the field, and only the bar's empty space moves the + window (#2807). + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From 1424afa3a7065f8f5cbee8ba39e38466f5e1fe6e Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:36:35 +0100 Subject: [PATCH 05/29] LR-PROF-CAMERACOLOR: reject gains from dropped correspondence edges Compare original and profile proposal on shared valid edges during search and held-out validation. Keep thresholds, bounded search and existing CR3 framing behavior. Co-authored-by: Codex --- crates/engine/src/camera_preview/proxy.rs | 59 ++++++++++++++++++----- crates/engine/src/camera_preview/tests.rs | 22 +++++++++ docs/camera-preview-colour.md | 2 +- 3 files changed, 70 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 7cd6c9b828..306f87e3aa 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -213,15 +213,17 @@ impl Cr3Framing { /// A separate third of the edges must confirm a substantial improvement and a close match. /// A weak, flat or unrelated preview leaves the sensor framing unchanged. pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option { - estimate_framing_against(sensor, reference, sensor) + estimate_framing_against(sensor, reference, None) } /// Score both a proposed lens geometry and its bounded framing against the original sensor. /// The identity framing is a valid candidate: lens correction alone may already align the JPEG. -fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option { +fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Option<&Rgb32f>) -> Option { if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() { return None; } + let proposal = original.is_some(); + let original = original.unwrap_or(sensor); let sensor = fit(sensor, PROXY, PROXY, Filter::Box); let (w, h) = (sensor.width, sensor.height); if w < 16 || h < 16 { @@ -261,7 +263,7 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if edges.len() < 192 { return None; } - let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool| -> Option { + let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool, support: Option<(&Rgb32f, Cr3Framing)>| -> Option { let (mut agreement, mut weight, mut valid, mut total) = (0.0, 0.0, 0usize, 0usize); for &(x, y, target, magnitude, holdout) in &edges { if holdout != held_out { @@ -277,6 +279,19 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if !length.is_finite() || length <= 0.01 { continue; } + // Pairwise comparisons use exactly the same valid edges on both sides, + // including the same reference weights. + if let Some((other, map)) = support { + let (ox, oy) = map.source(x, y, w, h); + if ox < 1.5 || oy < 1.5 || ox > w as f32 - 1.5 || oy > h as f32 - 1.5 { + continue; + } + let p = other.sample_bilinear(ox, oy); + let length = p[0].hypot(p[1]); + if !length.is_finite() || length <= 0.01 { + continue; + } + } let k = f64::from(magnitude.min(0.25)); agreement += k * f64::from((sample[0] * target[0] + sample[1] * target[1]) / (length * magnitude)); weight += k; @@ -284,18 +299,26 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 } (valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight) }; - let before = score(&original_gradients, Cr3Framing::IDENTITY, false)?; - let mut best = (score(&gradients, Cr3Framing::IDENTITY, false).unwrap_or(-1.0), Cr3Framing::IDENTITY); + // Only profile proposals use common-support improvement during candidate selection. + // The public CR3 framing fallback retains its original independent-support search. + let before = score(&original_gradients, Cr3Framing::IDENTITY, false, None)?; + let training = |framing| -> Option<(f64, f64)> { + let after = score(&gradients, framing, false, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?; + let before = if proposal { score(&original_gradients, Cr3Framing::IDENTITY, false, Some((&gradients, framing)))? } else { before }; + (!proposal || (after >= 0.9 && after >= before + 0.04)).then_some((before, after)) + }; + let initial = training(Cr3Framing::IDENTITY); + let mut best = (initial.map_or(-1.0, |v| v.1), Cr3Framing::IDENTITY, initial.map_or(before, |v| v.0)); // At most 10% zoom and two proxy pixels of translation; a coarse search followed by one // local refinement prevents unbounded optimisation on the photograph's contents. for s in -10..=10 { for tx in -4..=4 { for ty in -4..=4 { let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] }; - if let Some(value) = score(&gradients, framing, false) + if let Some((before, value)) = training(framing) && value > best.0 { - best = (value, framing); + best = (value, framing, before); } } } @@ -311,16 +334,22 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 if !(0.9..=1.1).contains(&framing.scale) || framing.offset[0].abs() > 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 { continue; } - if let Some(value) = score(&gradients, framing, false) + if let Some((before, value)) = training(framing) && value > best.0 { - best = (value, framing); + best = (value, framing, before); } } } } - let (held_before, held_after) = (score(&original_gradients, Cr3Framing::IDENTITY, true)?, score(&gradients, best.1, true)?); - if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { + if proposal && best.0 < 0.9 { + return None; + } + let (held_before, held_after) = ( + score(&original_gradients, Cr3Framing::IDENTITY, true, proposal.then_some((&gradients, best.1)))?, + score(&gradients, best.1, true, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?, + ); + if best.0 < 0.9 || best.0 < best.2 + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 { return None; } if lightcraft_pipeline::profiling() { @@ -329,6 +358,12 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb3 Some(best.1) } +/// Exercise the proposal gate independently of lens-map construction in regressions. +#[cfg(test)] +pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option { + estimate_framing_against(candidate, reference, Some(original)) +} + /// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing. fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) { let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) }; @@ -386,7 +421,7 @@ pub(super) fn align_profile_geometry( warp.lens_dist = 1.0; let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1); let candidate = resample_correspondence(sensor, source); - let framing = estimate_framing_against(&candidate, reference, sensor)?; + let framing = estimate_framing_against(&candidate, reference, Some(sensor))?; let mask = resample_correspondence(clipped, source); let frame = |x: f64, y: f64| { let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index f0601e36c6..473ec93e9d 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -986,6 +986,28 @@ fn profile_geometry_scene(w: usize, h: usize) -> Rgb32f { sensor } +#[test] +fn external_profile_geometry_cannot_improve_by_dropping_disagreeing_borders() { + // At the scoring resolution, about 14% of side-strip edges disagree. A candidate + // that merely discards those strips has no improvement on their common support. + let reference = profile_geometry_scene(96, 64); + let mut original = reference.clone(); + let mut candidate = reference.clone(); + for y in 0..reference.height { + for x in 0..reference.width { + if !(7..89).contains(&x) { + let i = y * reference.width + x; + original.data[i] = reference.data[i].map(|v| 0.8 - v); + candidate.data[i] = [f32::NAN; 3]; + } + } + } + assert!( + super::proxy::estimate_profile_framing(&candidate, &reference, &original).is_none(), + "discarding mismatched edges must not manufacture the required 0.04 improvement" + ); +} + fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { lightcraft_develop::EmbeddedLens { warp: Some(lightcraft_develop::EmbeddedWarp { diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index a5ae8928d3..3fe0b16a59 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -24,7 +24,7 @@ One third of the pixels are held out from both fits. The combined model must red **Lens-corrected camera JPEGs.** Some raws carry the camera's own lens correction (Fujifilm and Panasonic tables, the ILCE-7RM4A, Nikon's NikonNEFInfo) and the camera often applies it to its JPEG. Nikon Z lenses always do, and that JPEG can be zoomed in by up to 9% to fill the frame. The fit used to pair the uncorrected sensor with the corrected JPEG, so near the edges it compared pixels from different parts of the scene. Now the sensor proxy is also warped with the file's correction (`into_lens_geometry`, pixels that land outside the picture are dropped), and the fit uses whichever of the two lines up better with the JPEG, going by the correlation of their high-passed log luminance. Files whose JPEG isn't corrected keep the plain proxy. On the 29 CC0 corpus raws with a warp the alignment goes up by 0.13 on average (Panasonic GX80 0.41 to 0.83, Fujifilm X-T20 0.44 to 0.95). Mean ΔE against the camera JPEG over the 35 corpus raws of those formats goes from 3.73 to 3.61, and on 299 private Z 6II photos with Nikon's correction read it goes from 3.22 to 2.68. -**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route; absent profiles, CR3 and the established opcode-warp route retain their existing behaviour. +**Resolved profiles and remaining camera framing.** For file-local fitting without a camera matrix or an in-file opcode warp, the resolved lens profile can additionally propose a corrected sensor proxy. Its green-plane map is evaluated through the same `Warp::corrected_to_source` used by the renderer, in the developed default crop; oriented profiles are re-expressed in sensor coordinates first. The existing bounded framing search (scale 0.9–1.1, translation at most two pixels on a fixed 96-pixel proxy) may then align the camera JPEG's remaining crop. At least 192 edges are required. Both training and held-out edge directions must agree by at least 0.90 and improve by at least 0.04 over the **original unwarped** geometry, with at least 80% usable edges in each split. For each proposal candidate, the original and candidate scores use the exact intersection of valid edges with the same reference weights, during both training selection and held-out confirmation. Lens correction alone can pass with identity framing. Weak, unrelated or already aligned previews keep the original route; absent profiles, CR3 and the established opcode-warp route retain their existing behaviour. This changes calibration correspondences only, including `calibrate`'s pooled pairs and the colour tags used by merge/DNG conversion. It is independent of the user's Optics switch and does not bake geometric correction into the rendered RAW. Sensor and clipping mask follow the same sampling maps; invalid borders cannot train the look. Matrix, hue/saturation, tone fitting and their colour-error acceptance gates are unchanged. A physically plausible lens correction alone is not assumed to match a camera JPEG: geometry must establish the correspondence before it is used. Cached renders and camera looks have new versions so online originals rebuild their calibration. Cameras without a safely resolved geometric profile receive no new guarantee of colour accuracy. From 04f8c67ca557f3a70c7956dac4ad44d8e1294329 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:14:50 +0100 Subject: [PATCH 06/29] LR-PROF-CAMERACOLOR: preserve lens dependencies in colour fits Resolve file corrections before DNG and merge colour fitting removes lens opcodes. Include the loaded lens database identity in camera render keys and smart-preview staleness/scan markers. Cover real lookup wiring, file-warp precedence, cache transitions, finite support and clipped masks; retain geometry gates and newer/offline proxy handling. Validated with focused regressions and full cargo xtask ci (8/8, Rust 1.95.0, Apple M5 Max Metal and WASM). DNG/merge regressions fail against the previous ordering. Synthetic headless demo smoke passed; historical photo comparisons were not rerun. Co-authored-by: Codex --- crates/engine/src/camera_preview/colour.rs | 12 ++- crates/engine/src/camera_preview/proxy.rs | 5 +- crates/engine/src/camera_preview/tests.rs | 117 ++++++++++++++++----- crates/engine/src/camera_profiles.rs | 18 +++- crates/engine/src/lens_profiles.rs | 104 ++++++++++++++++++ crates/engine/src/smart.rs | 47 +++++++-- crates/engine/src/smart/tests.rs | 43 ++++++++ crates/engine/src/tests/import.rs | 5 +- crates/merge/src/frame.rs | 22 +++- docs/camera-preview-colour.md | 14 +++ docs/parity-checklist.md | 2 +- 11 files changed, 340 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index 4dd7933819..e03018a18d 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -143,8 +143,13 @@ pub(super) fn starting_colour_tags_with_correction( // the white the source shows, decided before `starting_colour` may fill in measured matrices let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw)); - // (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling) - let (_, t, look) = starting_colour(raw, bytes, None, correction); + // Resolve the file warp before removing lens opcodes, just as opening the RAW does. + // The fit needs uncorrected sensor samples; the caller still owns the original opcodes. + let lens = super::lens_geometry(&raw.opcodes.list3); + let list3 = std::mem::take(&mut raw.opcodes.list3); + raw.opcodes.list3 = list3.iter().filter(|op| !op.is_lens_correction()).cloned().collect(); + let (_, t, look) = starting_colour(raw, bytes, lens.as_ref(), correction); + raw.opcodes.list3 = list3; dng_colour(&raw.color, &white, &t, look.as_ref()) } @@ -156,10 +161,7 @@ pub(crate) fn with_starting_colour(raw: &mut RawImage, bytes: &[u8]) { if lightcraft_raw::color::has_matrix(&raw.color) { return; } - let list3 = raw.opcodes.list3.clone(); - raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let tags = starting_colour_tags(raw, bytes); - raw.opcodes.list3 = list3; if let Some(tags) = tags { raw.color = tags; } diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index 306f87e3aa..6be0926a7f 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -304,8 +304,11 @@ fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: Optio let before = score(&original_gradients, Cr3Framing::IDENTITY, false, None)?; let training = |framing| -> Option<(f64, f64)> { let after = score(&gradients, framing, false, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?; + if proposal && after < 0.9 { + return None; + } let before = if proposal { score(&original_gradients, Cr3Framing::IDENTITY, false, Some((&gradients, framing)))? } else { before }; - (!proposal || (after >= 0.9 && after >= before + 0.04)).then_some((before, after)) + (!proposal || after >= before + 0.04).then_some((before, after)) }; let initial = training(Cr3Framing::IDENTITY); let mut best = (initial.map_or(-1.0, |v| v.1), Cr3Framing::IDENTITY, initial.map_or(before, |v| v.0)); diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 473ec93e9d..4abd411397 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1,4 +1,3 @@ -use super::colour::starting_colour_tags_with_correction; use super::proxy::{align_profile_geometry, resample_correspondence}; use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity}; use super::*; @@ -991,21 +990,23 @@ fn external_profile_geometry_cannot_improve_by_dropping_disagreeing_borders() { // At the scoring resolution, about 14% of side-strip edges disagree. A candidate // that merely discards those strips has no improvement on their common support. let reference = profile_geometry_scene(96, 64); - let mut original = reference.clone(); - let mut candidate = reference.clone(); - for y in 0..reference.height { - for x in 0..reference.width { - if !(7..89).contains(&x) { - let i = y * reference.width + x; - original.data[i] = reference.data[i].map(|v| 0.8 - v); - candidate.data[i] = [f32::NAN; 3]; + for border in [f32::NAN, 0.0] { + let mut original = reference.clone(); + let mut candidate = reference.clone(); + for y in 0..reference.height { + for x in 0..reference.width { + if !(7..89).contains(&x) { + let i = y * reference.width + x; + original.data[i] = reference.data[i].map(|v| 0.8 - v); + candidate.data[i] = [border; 3]; + } } } + assert!( + super::proxy::estimate_profile_framing(&candidate, &reference, &original).is_none(), + "discarding mismatched edges must not manufacture the required 0.04 improvement (border {border})" + ); } - assert!( - super::proxy::estimate_profile_framing(&candidate, &reference, &original).is_none(), - "discarding mismatched edges must not manufacture the required 0.04 improvement" - ); } fn synthetic_profile_lens() -> lightcraft_develop::EmbeddedLens { @@ -1041,7 +1042,8 @@ fn geometry_rms(a: &Rgb32f, b: &Rgb32f) -> f64 { } } } - assert!(n > 256); + let expected = b.data.iter().flatten().filter(|v| v.is_finite()).count(); + assert!(n > 256 && n as usize * 100 >= expected * 95, "finite overlap {n}/{expected}"); (error / f64::from(n)).sqrt() } @@ -1106,6 +1108,33 @@ fn external_profile_geometry_preserves_oriented_default_crop_and_resolution() { #[test] fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { + const DB: &str = r#" + SyntheticUncalibratedT1.5 + SyntheticSynthetic 18mmT1.5 + + "#; + const CHILD: &str = "LIGHTCRAFT_TEST_COLOUR_TAG_LOOKUP_CHILD"; + if std::env::var_os(CHILD).is_none() { + // Set the database only for a fresh process: no mutation of the test runner's environment + // or races with other tests initializing the process-wide lens database. + let dir = std::env::temp_dir().join(format!("lightcraft-colour-tags-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("synthetic.xml"), DB).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "camera_preview::tests::external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop", "--nocapture"]) + .env(CHILD, "1") + .env(crate::lens_profiles::ENV, &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!( + output.status.success(), + "child regression: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } use lightcraft_raw::{BlackLevel, RawData, Rect}; let (w, h) = (416, 288); let scene = profile_geometry_scene(w, h); @@ -1125,7 +1154,15 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); assert_eq!((sensor.width, sensor.height), (384, 256)); sensor.map_in_place(|p| transform.matrix.apply_f32(p)); - let lens = synthetic_profile_lens(); + let db = lightcraft_lensdb::LensDb::parse(DB).unwrap(); + let metadata = lightcraft_meta::Metadata { + make: Some("Synthetic".into()), + model: Some("Uncalibrated".into()), + lens_model: Some("Synthetic 18mm".into()), + focal_length: Some(18.0), + ..Default::default() + }; + let lens = crate::lens_profiles::lookup(&db, &metadata, 384.0, 256.0, raw.orientation).unwrap(); let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); target.map_in_place(|p| p.map(|v| v.powf(0.7))); let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); @@ -1133,14 +1170,20 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); let image = lightcraft_codecs::EncodeImage::new(384, 256, 3, lightcraft_codecs::Samples::U8(&pixels)); let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); - let mut file = b"II*\0\x08\0\0\0\x02\0".to_vec(); - for (tag, value) in [(0x0201u16, 38u32), (0x0202, jpeg.len() as u32)] { - file.extend(tag.to_le_bytes()); - file.extend(4u16.to_le_bytes()); - file.extend(1u32.to_le_bytes()); - file.extend(value.to_le_bytes()); - } - file.extend(0u32.to_le_bytes()); + use lightcraft_tiff::{IfdBuilder, TiffWriter, Value, tags}; + let mut ifd = IfdBuilder::new(); + ifd.set(tags::MAKE, Value::Ascii("Synthetic".into())); + ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into())); + let mut exif = IfdBuilder::new(); + exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)])); + exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())); + ifd.set_child(tags::EXIF_IFD, exif); + ifd.set(0x0201, Value::Long(vec![0])); + ifd.set(0x0202, Value::Long(vec![jpeg.len() as u32])); + let offset = TiffWriter::default().write(&[ifd.clone()]).unwrap().len(); + ifd.set(0x0201, Value::Long(vec![offset as u32])); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + assert_eq!(file.len(), offset); file.extend(jpeg); let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap(); let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap(); @@ -1165,8 +1208,30 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(&raw)); let expected_tags = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); - let tags = starting_colour_tags_with_correction(&mut raw, &file, Some(&lens)).unwrap(); - assert_eq!(tags, expected_tags, "DNG tags use the resolved correspondence geometry too"); + assert_eq!(lightcraft_meta::extract(&file).focal_length, Some(18.0)); + assert_eq!(crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&file)), Some(lens)); + let tags = starting_colour_tags(&mut raw.clone(), &file).unwrap(); + assert_eq!(tags, expected_tags, "production DNG tags resolve the database geometry too"); + let mut converted = raw.clone(); + with_starting_colour(&mut converted, &file); + assert_eq!(converted.color, expected_tags); + + // A file's own (identity) warp must suppress the unrelated database proposal. This also + // checks that colour fitting temporarily strips, then restores, the original opcodes. + raw.opcodes.list3.push(lightcraft_raw::Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }); + let ops = raw.opcodes.list3.clone(); + let own = crate::files::embedded_lens(&raw.info()).unwrap(); + assert_ne!(own, lens); + let mut opened = raw.clone(); + let geometry = lens_geometry(&opened.opcodes.list3); + opened.opcodes.list3.clear(); + let (_, t, look) = starting_colour(&mut opened, &file, geometry.as_ref(), Some(&own)); + let expected = dng_colour(&raw.color, &white, &t, look.as_ref()).unwrap(); + assert_ne!(expected, expected_tags, "fixture distinguishes own warp from database geometry"); + assert_eq!(starting_colour_tags(&mut raw.clone(), &file), Some(expected.clone())); + with_starting_colour(&mut raw, &file); + assert_eq!(raw.color, expected, "standalone DNG colour agrees with opening the RAW"); + assert_eq!(raw.opcodes.list3, ops, "DNG retains its file corrections"); } #[test] @@ -1180,7 +1245,7 @@ fn correspondence_mask_keeps_every_contributing_clipped_sample_and_invalid_borde assert!(result.data[7][0].is_nan() && result.data[5 * 8][0].is_nan()); // The final box reduction retains fractional positive masks as clipped too. let reduced = resize(&result, 4, 3, Filter::Box); - assert!(reduced.data.iter().any(|p| p[0] > 0.0)); + assert!(reduced.data[1][0] > 0.0 && reduced.data[5][0] > 0.0); } /// The guarded fit is assessed on real sensor data, never on the JPEG fallback. A corpus diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 810d035ce4..323a0e0c86 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -157,13 +157,19 @@ pub fn get(model: &str) -> Option> { } /// Changes when the profiles folder's contents change (per process): part of the render cache -/// keys, so thumbnails rendered before a profile existed are not reused after. +/// keys, so thumbnails rendered before a profile existed are not reused after. Includes the +/// loaded lens database: its geometry determines which sensor/JPEG samples fit the camera look. pub fn cache_key() -> u64 { static KEY: OnceLock = OnceLock::new(); - *KEY.get_or_init(|| cache_key_for(dir().as_deref())) + *KEY.get_or_init(|| cache_key_with_lens(dir().as_deref(), crate::lens_profiles::cache_key())) } +#[cfg(test)] fn cache_key_for(directory: Option<&Path>) -> u64 { + cache_key_with_lens(directory, 0) +} + +fn cache_key_with_lens(directory: Option<&Path>, lens_key: u64) -> u64 { let entries = directory.and_then(|d| std::fs::read_dir(d).ok()); let mut files: Vec<(String, u64, std::time::Duration)> = entries .into_iter() @@ -178,6 +184,7 @@ fn cache_key_for(directory: Option<&Path>) -> u64 { .collect(); files.sort(); let mut h = lightcraft_preview::Hasher128::new(); + h.str("camera-profiles-with-lens-v1").u64(lens_key); for (name, len, modified) in &files { h.str(name).u64(*len).u64(modified.as_secs()).u64(u64::from(modified.subsec_nanos())); } @@ -298,6 +305,13 @@ mod tests { assert!(bundled("No Such Camera").is_none()); } + #[test] + fn lens_database_identity_invalidates_camera_render_cache() { + assert_ne!(cache_key_with_lens(None, 0), cache_key_with_lens(None, 123)); + assert_ne!(cache_key_with_lens(None, 123), cache_key_with_lens(None, 456)); + assert_eq!(cache_key_with_lens(None, 123), cache_key_with_lens(None, 123)); + } + #[test] fn same_second_profile_replacement_changes_render_cache_key() { let dir = std::env::temp_dir().join(format!("lc-camera-profile-cache-{}", std::process::id())); diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index 9a43931625..ba4cdf62e6 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -35,6 +35,70 @@ pub fn database() -> Option<&'static LensDb> { .as_ref() } +/// Identity of exactly the database this process uses, not files that may have changed since it +/// was loaded. The loader bounds file count/size and sorts paths; vector order is significant +/// because equally good matches use the first profile. No directory path or timestamps enter it. +pub(crate) fn cache_key() -> u64 { + static KEY: OnceLock = OnceLock::new(); + *KEY.get_or_init(|| cache_key_for(database())) +} + +fn cache_key_for(db: Option<&LensDb>) -> u64 { + use lightcraft_lensdb::{Distortion, Tca}; + let Some(db) = db else { return 0 }; + let mut h = lightcraft_preview::Hasher128::new(); + h.str("lens-db-v1").u64(db.cameras.len() as u64); + for c in &db.cameras { + h.str(&c.maker).str(&c.model).str(&c.mount).u64(c.crop_factor.to_bits()); + } + h.u64(db.lenses.len() as u64); + for p in &db.lenses { + h.str(&p.maker).u64(p.models.len() as u64); + for name in &p.models { + h.str(name); + } + h.u64(p.mounts.len() as u64); + for mount in &p.mounts { + h.str(mount); + } + h.u64(p.crop_factor.to_bits()).u64(p.aspect_ratio.to_bits()).u64(u64::from(p.rectilinear)); + h.u64(p.distortion.len() as u64); + for (focal, model) in &p.distortion { + h.u64(focal.to_bits()); + match *model { + Distortion::Poly3 { k1 } => { + h.u64(0).u64(k1.to_bits()); + } + Distortion::Poly5 { k1, k2 } => { + h.u64(1).u64(k1.to_bits()).u64(k2.to_bits()); + } + Distortion::PtLens { a, b, c } => { + h.u64(2).u64(a.to_bits()).u64(b.to_bits()).u64(c.to_bits()); + } + } + } + h.u64(p.tca.len() as u64); + for (focal, model) in &p.tca { + h.u64(focal.to_bits()); + match *model { + Tca::Linear { kr, kb } => { + h.u64(0).u64(kr.to_bits()).u64(kb.to_bits()); + } + Tca::Poly3 { vr, vb, cr, cb, br, bb } => { + h.u64(1).u64(vr.to_bits()).u64(vb.to_bits()).u64(cr.to_bits()).u64(cb.to_bits()).u64(br.to_bits()).u64(bb.to_bits()); + } + } + } + h.u64(p.vignetting.len() as u64); + for v in &p.vignetting { + h.u64(v.focal.to_bits()).u64(v.aperture.to_bits()).u64(v.distance.to_bits()); + h.u64(v.model.k1.to_bits()).u64(v.model.k2.to_bits()).u64(v.model.k3.to_bits()); + } + } + // Reserve zero for a process with no usable database. + (h.finish().0 as u64).max(1) +} + /// The database profile for a photo with metadata `m`, for its `w × h` (unoriented, default-cropped) image, /// re-expressed after `orientation`. Without a lens name/specification, a unique fixed-mount profile may identify it. /// `None` without a database, focal length or unambiguous matching profile. @@ -109,6 +173,46 @@ mod tests { "#; + #[test] + fn database_identity_tracks_loaded_geometry_not_xml_formatting() { + let db = LensDb::parse(DB).unwrap(); + let key = cache_key_for(Some(&db)); + assert_ne!(key, cache_key_for(None), "installing a database invalidates no-database fits"); + assert_eq!(key, cache_key_for(Some(&LensDb::parse(&DB.replace("", "\n ")).unwrap()))); + let changed = LensDb::parse(&DB.replace("-0.03", "-0.05")).unwrap(); + assert_ne!(key, cache_key_for(Some(&changed)), "equal-length calibration changes matter"); + assert_eq!(key, cache_key_for(Some(&db)), "an already-loaded snapshot stays unchanged"); + let mut changed = db.clone(); + changed.cameras[0].mount = "other-fixed-mount".into(); + assert_ne!(key, cache_key_for(Some(&changed)), "camera matching affects the fit too"); + changed = db.clone(); + changed.lenses[0].aspect_ratio = 2.0; + assert_ne!(key, cache_key_for(Some(&changed)), "calibration frame changes matter"); + changed = db.clone(); + changed.lenses[0].vignetting[0].model.k1 = -0.8; + assert_ne!(key, cache_key_for(Some(&changed)), "vignetting is a fit dependency"); + } + + #[test] + fn database_identity_uses_the_loaders_sorted_file_order() { + let dir = std::env::temp_dir().join(format!("lc-lens-identity-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let changed = DB.replace("-0.03", "-0.05"); + std::fs::write(dir.join("b.xml"), &changed).unwrap(); + std::fs::write(dir.join("a.xml"), DB).unwrap(); + let first = LensDb::load_dir(&dir).unwrap().0; + std::fs::remove_file(dir.join("a.xml")).unwrap(); + std::fs::remove_file(dir.join("b.xml")).unwrap(); + std::fs::write(dir.join("a.xml"), DB).unwrap(); + std::fs::write(dir.join("b.xml"), &changed).unwrap(); + let second = LensDb::load_dir(&dir).unwrap().0; + assert_eq!(cache_key_for(Some(&first)), cache_key_for(Some(&second)), "directory enumeration order is irrelevant"); + let mut reversed = first.clone(); + reversed.lenses.reverse(); + assert_ne!(cache_key_for(Some(&first)), cache_key_for(Some(&reversed)), "tie-breaking profile order matters"); + std::fs::remove_dir_all(&dir).unwrap(); + } + fn meta() -> lightcraft_meta::Metadata { lightcraft_meta::Metadata { make: Some("Testcam".into()), diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index b936830f83..189bbc3e8e 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -59,6 +59,9 @@ const HEADER_MAX: u64 = 4096; /// wrote the proxy's pixels (colour matrix and profile are baked into them) and stored tone curve. const LOOK_FIELD: &str = "look_version"; +/// Geometry database used by the camera-look fit baked into the proxy's pixels. +const LENS_FIELD: &str = "lens_db"; + /// The JPEG quality a smart preview's pixels are stored at. The original 92 left the 8×8 DCT's /// quantised DC — each block's own mean, luma and chroma — visible as block steps across the frame /// and as a small constant colour shift; that is the largest part of what a proxy gets wrong @@ -173,6 +176,7 @@ pub fn encode(img: &Rgb32f, info: Option<&SourceInfo>) -> Result, String "h": img.height, "scale": scale, LOOK_FIELD: crate::camera_preview::LOOK_VERSION, + LENS_FIELD: crate::lens_profiles::cache_key(), ENC_FIELD: ENCODE_VERSION, }); // The tail: the decoder facts (and the file's semantic mattes) after the JPEG, so the header @@ -429,7 +433,8 @@ fn header_encode_version(head: &serde_json::Value) -> u64 { /// reaches every proxy — or, when the photo takes the per-file camera look (`look`, /// [`lightcraft_catalog::Photo::fitted_look`]), by an older camera-look fit than this build's (so /// its stored curve, and the colour baked into its pixels, are out of date; the fit only reaches -/// those raws, so a JPEG's or DNG's proxy is never stale for it). A proxy from a newer build is +/// those raws, so a JPEG's or DNG's proxy is never stale for it), or a different loaded lens +/// database used to align that fit. A proxy from a newer build is /// left alone (rebuilding it here would only undo that build's work), as is one that can't be /// read: those are [`is_valid`]'s business. pub fn is_stale_for(path: &Path, look: bool) -> bool { @@ -444,9 +449,21 @@ pub fn is_stale_for(path: &Path, look: bool) -> bool { } let Some(rest) = head.strip_prefix(MAGIC) else { return false }; let Some(nl) = rest.iter().position(|b| *b == b'\n') else { return false }; - rest.get(..nl).and_then(|h| serde_json::from_slice::(h).ok()).is_some_and(|h| { - header_encode_version(&h) < ENCODE_VERSION || (look && header_look_version(&h) < u64::from(crate::camera_preview::LOOK_VERSION)) - }) + rest.get(..nl) + .and_then(|h| serde_json::from_slice::(h).ok()) + .is_some_and(|h| header_is_stale(&h, look, crate::lens_profiles::cache_key())) +} + +/// Compare only identities from the same fit/encoding generation. Newer proxies remain usable, +/// including offline: staleness is a rebuild hint, never a decoding requirement. +fn header_is_stale(head: &serde_json::Value, look: bool, lens_key: u64) -> bool { + let enc = header_encode_version(head); + let fit = header_look_version(head); + let current_fit = u64::from(crate::camera_preview::LOOK_VERSION); + enc < ENCODE_VERSION + || (look + && (fit < current_fit + || (fit == current_fit && enc == ENCODE_VERSION && head.get(LENS_FIELD).and_then(serde_json::Value::as_u64) != Some(lens_key)))) } /// [`is_stale_for`] for a photo that takes the per-file camera look: both conditions apply. @@ -455,14 +472,13 @@ pub fn is_stale(path: &Path) -> bool { } /// The marker file in a smart previews folder: the camera-look fit version and encode version its -/// proxies were last checked at ([`look_checked`]). +/// proxies were last checked at, plus the loaded lens database identity ([`look_checked`]). const LOOK_MARKER: &str = "look-version"; /// Whether the smart previews folder `dir` has been checked for out-of-date proxies at this build's /// camera-look fit version and encode version (or newer ones). A missing or unreadable marker counts -/// as not, and so does one written before the encode version was recorded — it only says the look -/// was checked, so this build scans the folder once more and rebuilds the proxies [`is_stale`] -/// finds. +/// as not, as does one without the loaded lens database identity. Changes to that identity force +/// another scan, so unchanged fit/encode versions cannot hide stale fitted previews. pub fn look_checked(dir: &Path) -> bool { use std::io::Read; let Ok(f) = std::fs::File::open(dir.join(LOOK_MARKER)) else { return false }; @@ -470,19 +486,28 @@ pub fn look_checked(dir: &Path) -> bool { if f.take(64).read_to_string(&mut text).is_err() { return false; } + marker_is_current(&text, crate::lens_profiles::cache_key()) +} + +fn marker_is_current(text: &str, lens_key: u64) -> bool { let mut versions = text.split_whitespace(); let (Some(look), Some(enc)) = (versions.next(), versions.next()) else { return false }; match (look.parse::(), enc.parse::()) { - (Ok(look), Ok(enc)) => look >= u64::from(crate::camera_preview::LOOK_VERSION) && enc >= ENCODE_VERSION, + (Ok(look), Ok(enc)) => { + let current_fit = u64::from(crate::camera_preview::LOOK_VERSION); + look >= current_fit + && enc >= ENCODE_VERSION + && (look > current_fit || enc > ENCODE_VERSION || versions.next().and_then(|v| v.parse::().ok()) == Some(lens_key)) + } _ => false, } } /// Record that the proxies in `dir` were checked at this build's camera-look fit version and encode -/// version. +/// version and loaded lens database identity. pub fn mark_look_checked(dir: &Path) -> Result<(), String> { let path = dir.join(LOOK_MARKER); - let text = format!("{} {}\n", crate::camera_preview::LOOK_VERSION, ENCODE_VERSION); + let text = format!("{} {} {}\n", crate::camera_preview::LOOK_VERSION, ENCODE_VERSION, crate::lens_profiles::cache_key()); lightcraft_catalog::safe_file::write_atomic(&path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display())) } diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index e4bbd548cd..84d7920c14 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -347,3 +347,46 @@ fn a_proxy_from_an_older_encode_is_stale() { assert!(!look_checked(&dir), "a look-only marker is not enough to skip the rebuild"); let _ = std::fs::remove_dir_all(&dir); } + +/// A lens database changes the geometry used to align the fitted camera look, although the fit +/// algorithm version stays the same. Keep these checks independent of process-global environment. +#[test] +fn lens_database_changes_rebuild_fitted_smart_previews_and_scan_markers() { + let fit = u64::from(crate::camera_preview::LOOK_VERSION); + let mut head = serde_json::json!({LOOK_FIELD: fit, ENC_FIELD: ENCODE_VERSION, LENS_FIELD: 123}); + assert!(!header_is_stale(&head, true, 123)); + for next_db in [0, 456] { + assert!(header_is_stale(&head, true, next_db), "removing or replacing the database rebuilds fitted pixels"); + assert!(!header_is_stale(&head, false, next_db), "non-fitted photos do not depend on lens alignment"); + assert!(!marker_is_current(&format!("{fit} {ENCODE_VERSION} 123"), next_db), "the folder must be scanned again"); + } + assert!(marker_is_current(&format!("{fit} {ENCODE_VERSION} 123"), 123)); + head.as_object_mut().unwrap().remove(LENS_FIELD); + assert!(header_is_stale(&head, true, 123), "adding a database rebuilds legacy fits"); + assert!(header_is_stale(&head, true, 0), "a legacy fit may have used a database that is no longer installed"); + head[LENS_FIELD] = serde_json::json!(0); + assert!(!header_is_stale(&head, true, 0), "an explicit no-database identity remains valid"); + assert!(!marker_is_current(&format!("{fit} {ENCODE_VERSION}"), 123), "old markers require a new scan"); + for field in [LOOK_FIELD, ENC_FIELD] { + let mut newer = head.clone(); + newer[field] = serde_json::json!(newer[field].as_u64().unwrap() + 1); + assert!(!header_is_stale(&newer, true, 123), "a different database does not downgrade newer proxies"); + } + assert!(marker_is_current(&format!("{} {ENCODE_VERSION} 456", fit + 1), 123)); + assert!(marker_is_current(&format!("{fit} {} 456", ENCODE_VERSION + 1), 123)); +} + +#[test] +fn smart_preview_from_another_database_stays_decodable_offline() { + let image = lightcraft_scenes::demo_library()[0].render(64, 40); + let bytes = encode(&image, None).unwrap(); + let nl = MAGIC.len() + bytes[MAGIC.len()..].iter().position(|b| *b == b'\n').unwrap(); + let mut head: serde_json::Value = serde_json::from_slice(&bytes[MAGIC.len()..nl]).unwrap(); + head[LENS_FIELD] = serde_json::json!(123); + assert!(header_is_stale(&head, true, 456)); + let mut changed = MAGIC.to_vec(); + changed.extend_from_slice(head.to_string().as_bytes()); + changed.extend_from_slice(&bytes[nl..]); + let (decoded, _, _) = decode(&changed).unwrap(); + assert_eq!((decoded.width, decoded.height), (image.width, image.height)); +} diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 18a9659618..87d26a9dcd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2362,6 +2362,7 @@ fn smart_preview_look_marker_is_read_safely() { assert!(!crate::smart::look_checked(&dir), "no marker"); let cur = crate::camera_preview::LOOK_VERSION; let enc = crate::smart::ENCODE_VERSION; + let lens = crate::lens_profiles::cache_key(); for (text, checked) in [ (String::new(), false), ("banana".into(), false), @@ -2373,7 +2374,9 @@ fn smart_preview_look_marker_is_read_safely() { (format!("{cur}\n"), false), (format!("{cur} {}\n", enc.saturating_sub(1)), false), (format!("{cur} banana\n"), false), - (format!("{cur} {enc}\n"), true), + (format!("{cur} {enc}\n"), false), + (format!("{cur} {enc} {lens}\n"), true), + (format!("{cur} {enc} {}\n", lens.wrapping_add(1)), false), (format!(" {} {}\n", cur + 1, enc + 1), true), ] { std::fs::write(dir.join("look-version"), &text).unwrap(); diff --git a/crates/merge/src/frame.rs b/crates/merge/src/frame.rs index 1316bfd13b..70821fbf2d 100644 --- a/crates/merge/src/frame.rs +++ b/crates/merge/src/frame.rs @@ -152,7 +152,8 @@ pub fn detect_clip(img: &Rgb32f) -> f32 { } /// The colour tags a raw source starts from when the caller knows better than the file (`None`: the -/// file's own tags). Called with the decoded raw, its samples still there, and the file's bytes. +/// file's own tags). Called with the decoded raw, its samples and lens opcodes still there, and the file's bytes. +/// The callback must leave those opcodes intact; it can temporarily remove them for a colour-only fit. pub type RawColour<'a> = dyn Fn(&mut lightcraft_raw::RawImage, &[u8]) -> Option + Sync + 'a; /// Decode a photo (raw or standard format) into a frame no larger than `max_edge` (when given). @@ -224,10 +225,10 @@ fn raw_frame( op => op, }) .collect(); - raw.opcodes.list3.retain(|op| !op.is_lens_correction()); if let Some(color) = colour(&mut raw, bytes) { raw.color = color; } + raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let small = max_edge.is_some_and(|m| m <= 1200); let method = if small { lightcraft_raw::Method::Bilinear } else { lightcraft_raw::Method::Ahd }; let mut image = raw.develop(method).map_err(|e| MergeError::Decode(e.to_string()))?; @@ -318,6 +319,23 @@ mod tests { raw_frame(raw, &[], Metadata::default(), None, None, true, colour).unwrap() } + #[test] + fn colour_callback_sees_file_lens_but_merge_pixels_stay_uncorrected() { + let plain = mosaic(None); + let expected = frame_of(plain.clone(), &|_, _| None); + let mut raw = plain; + let warp = Opcode::WarpRectilinear { planes: vec![[1.05, -0.15, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + raw.opcodes.list3.push(warp.clone()); + let actual = frame_of(raw, &|raw, _| { + assert_eq!(raw.opcodes.list3, vec![warp.clone()], "resolve file correction before stripping it"); + Some(ColorData { as_shot_neutral: Some([0.5, 1.0, 0.6]), ..Default::default() }) + }); + assert_eq!(actual.image, expected.image, "the merge itself still uses unwarped camera samples"); + assert_eq!(actual.lens.len(), 1, "output DNG keeps the reference correction"); + let FrameColor::Camera(tags) = actual.color else { panic!("camera colour") }; + assert_eq!(tags.as_shot_neutral, Some([0.5, 1.0, 0.6])); + } + /// Issue #1144: the as-shot multipliers of a CR2, NEF… (its only white balance) were dropped on loading, so /// nothing downstream could tell a merged DNG what the camera had balanced to. #[test] diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 3fe0b16a59..abd874f984 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -340,3 +340,17 @@ the neutral fallback): E-1 0.126 → 0.014, E-400 0.087 → 0.022, XZ-2 0.061 still open from their embedded JPEG. Against Lightroom Classic's render of a CC0 E-1 photo (2000 px, ΔE00 of the unedited render) the starting look moved from 11.25 to 8.30. Lightroom frames that E-1 file about 4 × 11 sensor pixels differently from the crop the file records (`CropLeft`/`CropTop` 36, 34); the file's own crop is kept. + +### Database identity and DNG colour tags (PR #2675 review) + +The loaded lens database is immutable for a process. Its matching and calibration values, including profile order, +form a semantic identity in camera-look render/view cache keys and smart-preview headers and scan markers. +Changing, adding or removing the database takes effect after restarting; fitted smart previews then rebuild when +their originals are available. Existing offline proxies remain readable. Missing legacy identities require one +new check; proxies from newer fit/encoding versions retain the existing downgrade protection. + +DNG conversion and merge resolve the file's own lens warp and correction before removing lens opcodes from the +colour-only sensor fit. The opcodes remain in standalone DNGs and in merge reference corrections. Synthetic tests +exercise the production database lookup in a fresh child process, file-warp precedence and merge callback ordering; +they add no real-photo validation beyond the historical evidence above. Profile proposals below 0.90 training +agreement now skip the unnecessary original-side scan; thresholds are unchanged and no timing improvement is claimed. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e1c8863a82..6825ce61ae 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1029,4 +1029,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove ## Proposed external-profile correspondence geometry -LR-DEV-CAMERAPROFILE remains partial; summary counts and status are unchanged. PR #2675 proposes geometry-gated external-profile alignment for file-local RAW colour fitting and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses. It preserves in-file geometry and the established CR3 framing path, applies source-position vignetting before geometry, and uses held-out edge agreement rather than RGB error to accept a candidate. Historical private-file observations and their limits are recorded in [Camera preview colour](camera-preview-colour.md); they are not a claim of validation of this rebased source. +LR-PROF-CAMERACOLOR remains partial; summary counts and status are unchanged. PR #2675 proposes geometry-gated external-profile alignment for file-local RAW colour fitting and pooled calibration, plus unique exact-mount lookup for unnamed fixed lenses. It preserves in-file geometry and the established CR3 framing path, applies source-position vignetting before geometry, and uses held-out edge agreement rather than RGB error to accept a candidate. Historical private-file observations and their limits are recorded in [Camera preview colour](camera-preview-colour.md); they are not a claim of validation of this rebased source. From d305b7bcac70c8a0b5c6aec62c0150336747c7ee Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:55:41 +0100 Subject: [PATCH 07/29] LR-PROF-CAMERACOLOR: require original provenance for proxy repairs Apply the original-source guard to every smart-preview rebuild and repair so damaged or missing targets cannot relabel older proxy pixels with current fit/database identities. Keep valid offline proxies unchanged and retain successful repair from an online original. Cover the actual legacy-fallback cache path, proxy/reduced cached inputs, public lens/camera cache keys, on-disk staleness and Pool::add through a decoded procedural NEF. Full cargo xtask ci passes 8/8 with Rust 1.95.0, Apple M5 Max Metal and WASM. Targeted negative checks reject the previous repair path and missing dependency forwarding. Co-authored-by: Codex --- crates/engine/src/camera_preview/tests.rs | 105 ++++++++++++++++++++ crates/engine/src/camera_profiles.rs | 33 +++++++ crates/engine/src/cmd/previews.rs | 115 +++++++++++++++++++++- crates/engine/src/lens_profiles.rs | 25 +++++ crates/engine/src/smart/tests.rs | 15 ++- 5 files changed, 284 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 4abd411397..e83e3215da 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1106,6 +1106,109 @@ fn external_profile_geometry_preserves_oriented_default_crop_and_resolution() { } } +#[test] +fn configured_lens_geometry_reaches_pool_add_after_raw_decode() { + const DB: &str = r#" + NikonUncalibratedT1.5 + SyntheticSynthetic 18mmT1.5 + + "#; + const CHILD: &str = "LIGHTCRAFT_TEST_POOL_DECODE_GEOMETRY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lightcraft-pool-decode-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("synthetic.xml"), DB).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "camera_preview::tests::configured_lens_geometry_reaches_pool_add_after_raw_decode", "--nocapture"]) + .env(CHILD, "1") + .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + + // A complete, bounded uncompressed NEF: production decode reads a real Bayer strip, + // EXIF lens identity and an embedded JPEG. No corpus or injected RawImage is involved. + use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags}; + let (w, h) = (768, 512); + let scene = profile_geometry_scene(w, h); + let samples: Vec = scene + .data + .iter() + .enumerate() + .flat_map(|(i, p)| { + let channel = match (i / w % 2, i % w % 2) { + (0, 0) => 0, + (1, 1) => 2, + _ => 1, + }; + ((p[channel] * 16383.0).round() as u16).to_le_bytes() + }) + .collect(); + let mut mosaic = IfdBuilder::new(); + mosaic.set(tags::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + mosaic.set(tags::IMAGE_WIDTH, Value::Long(vec![w as u32])); + mosaic.set(tags::IMAGE_LENGTH, Value::Long(vec![h as u32])); + mosaic.set(tags::BITS_PER_SAMPLE, Value::Short(vec![14])); + mosaic.set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![1])); + mosaic.set(tags::COMPRESSION, Value::Short(vec![1])); + mosaic.set(tags::PHOTOMETRIC, Value::Short(vec![32803])); + mosaic.set(tags::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + mosaic.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + mosaic.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![samples] }); + let mut ifd = IfdBuilder::new(); + ifd.set(tags::MAKE, Value::Ascii("Nikon".into())); + ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into())); + ifd.add_sub_ifd(mosaic); + let mut exif = IfdBuilder::new(); + exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)])); + exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())); + ifd.set_child(tags::EXIF_IFD, exif); + let shell = TiffWriter::default().write(&[ifd.clone()]).unwrap(); + let raw = lightcraft_raw::decode(&shell).expect("procedural NEF decodes through the production reader"); + assert_eq!(raw.format, RawFormat::Nef); + assert!(raw.opcodes.list3.is_empty()); + assert_eq!(raw.info().developed_size(), (w, h)); + let lens = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&shell)).expect("configured database resolves EXIF identity"); + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(target.width as u32, target.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + ifd.set(0x0201, Value::Long(vec![0])); + ifd.set(0x0202, Value::Long(vec![jpeg.len() as u32])); + let offset = TiffWriter::default().write(&[ifd.clone()]).unwrap().len(); + ifd.set(0x0201, Value::Long(vec![offset as u32])); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + assert_eq!(file.len(), offset); + file.extend(jpeg); + let decoded = lightcraft_raw::decode(&file).unwrap(); + let corrected = profile_pairs(&decoded, &file, None, Some(&lens)).expect("corrected decoded NEF contributes colour pairs"); + let plain = profile_pairs(&decoded, &file, None, None).unwrap(); + assert_ne!(corrected, plain, "fixture distinguishes forwarding the resolved correction from dropping it"); + // Match the documented per-photo cap, then observe the result through Pool's public fit API. + let step = corrected.len().div_ceil(4000).max(1); + let expected: Vec<_> = corrected.into_iter().step_by(step).collect(); + let (matrix, hue_sat) = fit_profile(&expected).expect("synthetic scene spans enough colours for pooled calibration"); + let expected = crate::camera_profiles::CameraProfile::new("Uncalibrated", 1, expected.len(), matrix, hue_sat); + let mut pool = crate::camera_profiles::Pool::default(); + assert_eq!(pool.add(&file).unwrap(), Some("Uncalibrated".into())); + assert_eq!(pool.files(), vec![("Uncalibrated".into(), 1)]); + assert_eq!(pool.fit(1), vec![Ok(expected)], "Pool::add must forward the database correction after decoding the actual bytes"); +} + #[test] fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { const DB: &str = r#" @@ -1124,6 +1227,8 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() .args(["--exact", "camera_preview::tests::external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop", "--nocapture"]) .env(CHILD, "1") .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) .output() .unwrap(); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 323a0e0c86..990b859d16 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -262,6 +262,39 @@ mod tests { CameraProfile::new("ILCE-7M4", 12, 3456, Mat3([[1.6, -0.5, -0.1], [-0.2, 1.3, -0.1], [-0.1, -0.2, 1.3]]), Some(table)) } + #[test] + fn public_cache_key_includes_the_configured_lens_database() { + const CHILD: &str = "LIGHTCRAFT_TEST_CAMERA_CACHE_KEY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lc-camera-key-wiring-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("lens.xml"), + r#"Test18mmT1.5 + "#, + ) + .unwrap(); + // Both OnceLocks and the configured camera-profile folder belong to the child only. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "camera_profiles::tests::public_cache_key_includes_the_configured_lens_database", "--nocapture"]) + .env(CHILD, "1") + .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + assert!(crate::lens_profiles::database().is_some(), "fixture database was loaded by the public loader"); + let lens_key = crate::lens_profiles::cache_key(); + assert_ne!(lens_key, 0); + let directory = dir(); + assert_eq!(cache_key(), cache_key_with_lens(directory.as_deref(), lens_key)); + assert_ne!(cache_key(), cache_key_with_lens(directory.as_deref(), 0), "public camera key must forward the loaded lens key"); + } + #[test] fn profiles_round_trip_and_reject_bad_files() { let dir = std::env::temp_dir().join(format!("lc-camera-profiles-{}", std::process::id())); diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index dc1f2c864a..a3be4dc255 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -354,8 +354,8 @@ struct SmartCounts { /// `source` if it reads the photo's original, else `None`. A source decoded from a smart preview /// (it now carries the proxy's stored facts), a proxy standing in for an offline original, and the -/// proxy fallback of a file source are not the original: refreshing a stale proxy from one of them -/// would stamp its older look as current. +/// proxy fallback of a file source are not the original: building or repairing a proxy from one +/// of them would stamp its older look as current. #[cfg(not(target_arch = "wasm32"))] fn original_only(source: crate::media::SourceRef) -> Option { use crate::media::SourceRef; @@ -364,6 +364,7 @@ fn original_only(source: crate::media::SourceRef) -> Option Some(SourceRef::Loaded(d)), + source @ SourceRef::Demo { .. } => Some(source), _ => None, } } @@ -410,9 +411,9 @@ fn smart_run( if damaged && !stale && crate::smart::is_valid(&path) { n.built += 1; } else { - // a stale proxy is rebuilt from the original only: never from itself (the file - // fallback or a source decoded from a proxy would stamp the old look as current) - let source = if stale { source.and_then(original_only) } else { source }; + // Every encode stamps current identities, including repairs and missing targets. + // Never relabel pixels from a proxy, even when the destination has no readable header. + let source = source.and_then(original_only); // atomic: a failed write leaves no partial proxy that would pass for a built one; // and synced (issue #134): built so the photo can be edited while its original // is offline, when it is the only copy — the sync is small next to the decode @@ -420,6 +421,9 @@ fn smart_run( .ok_or_else(|| "nothing to build from".to_string()) .and_then(|s| s.load_source()) .and_then(|src| { + if src.from_proxy || src.reduced { + return Err("smart previews need the original source".to_string()); + } let info = src.info_or(Default::default()); crate::smart::encode(&src.image, Some(&info)) }) @@ -737,3 +741,104 @@ mod tests { assert_eq!(r["failed"], json!(0)); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod smart_provenance_tests { + use super::smart_run; + use crate::media::{SourceLevel, SourceRef}; + use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source}; + use std::sync::Arc; + + fn temp(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-smart-provenance-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn damaged_shard_never_relabels_cached_legacy_fallback_and_repairs_from_online_original() { + let dir = temp("legacy-fallback"); + let mut photo = Photo::new( + PhotoId(1), + Source::File { path: dir.join("offline.arw").to_string_lossy().into_owned() }, + "offline.arw", + "ARW", + 48, + 32, + "2026-11-02T00:00:00", + ); + photo.kind = MediaKind::Raw; + let shard = crate::smart::sharded_file_path(&dir, &photo); + let legacy = dir.join(crate::smart::file_name(&photo)); + std::fs::create_dir_all(shard.parent().unwrap()).unwrap(); + let mut image = lightcraft_raster::Rgb32f::new(48, 32); + image.data.fill([0.25, 0.3, 0.2]); + let bytes = crate::smart::encode(&image, None).unwrap(); + let start = b"LCSP1\n".len(); + let nl = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap(); + let mut head: serde_json::Value = serde_json::from_slice(&bytes[start..nl]).unwrap(); + head["lens_db"] = serde_json::json!(crate::lens_profiles::cache_key().wrapping_add(1)); + let mut old = bytes[..start].to_vec(); + old.extend_from_slice(head.to_string().as_bytes()); + old.extend_from_slice(&bytes[nl..]); + std::fs::write(&legacy, &old).unwrap(); + std::fs::write(&shard, b"broken").unwrap(); + assert!(crate::smart::is_stale_for(&legacy, true)); + assert!(!crate::smart::is_stale_for(&shard, true), "a damaged header is not stale"); + + let mut session = crate::Session::new(); + session.media.smart_dir = Some(dir.clone()); + session.media.file_loader = Some(Arc::new(|_, _| Err("original is offline".into()))); + // Reproduce the UI cache selecting legacy while the worker sees the damaged shard. + let cached_missing = shard.to_string_lossy().into_owned(); + session.media.availability.set_probe(Arc::new(move |path| path != cached_missing)); + let source = session.media.source_ref(&photo, SourceLevel::Preview); + assert!(matches!(&source, SourceRef::File { fallback: Some(p), .. } if p == &legacy)); + assert!(source.load_source().unwrap().from_proxy, "the renderer can still use the offline fallback"); + let counts = smart_run(&dir, false, false, vec![(photo.id, shard.clone(), Some(source), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.stale_kept, counts.failed.len()), (0, 0, 0, 0, 1)); + assert_eq!(std::fs::read(&shard).unwrap(), b"broken", "a failed repair leaves its destination untouched"); + assert_eq!(std::fs::read(&legacy).unwrap(), old); + assert!(crate::smart::load(&legacy).unwrap().from_proxy); + + session.media.file_loader = Some(Arc::new(move |_, _| Ok((image.clone(), Default::default())))); + let source = session.media.source_ref(&photo, SourceLevel::Preview); + let counts = smart_run(&dir, false, false, vec![(photo.id, shard.clone(), Some(source), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.failed.len()), (1, 1, 0, 0)); + assert!(crate::smart::is_valid(&shard)); + assert!(!crate::smart::is_stale_for(&shard, true)); + assert_eq!(std::fs::read(&legacy).unwrap(), old, "repair does not overwrite the valid legacy copy"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn missing_target_never_encodes_proxy_sources_but_keeps_valid_offline_proxies() { + let dir = temp("missing-target"); + let legacy = dir.join("legacy.lcsp"); + let image = lightcraft_raster::Rgb32f::new(48, 32); + let bytes = crate::smart::encode(&image, Some(&Default::default())).unwrap(); + std::fs::write(&legacy, &bytes).unwrap(); + let loaded = crate::smart::load(&legacy).unwrap(); + assert!(loaded.info.is_some(), "stored facts do not confer original provenance"); + let mut reduced = crate::media::DecodedSource::new(Arc::new(image.clone()), Some(Default::default())); + reduced.reduced = true; + let sources = [ + SourceRef::Loaded(Box::new(reduced)), + SourceRef::Loaded(Box::new(loaded.clone())), + SourceRef::Fit { from: Box::new(loaded), max_edge: 24 }, + SourceRef::Smart { path: legacy.clone() }, + ]; + for (i, source) in sources.into_iter().enumerate() { + let target = dir.join(format!("missing-{i}.lcsp")); + let counts = smart_run(&dir, false, false, vec![(PhotoId(1), target.clone(), Some(source), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.failed.len()), (0, 0, 1)); + assert!(!target.exists()); + } + let source = SourceRef::Smart { path: legacy.clone() }; + let counts = smart_run(&dir, false, false, vec![(PhotoId(1), legacy.clone(), Some(source), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.failed.len()), (1, 0, 0)); + assert_eq!(std::fs::read(&legacy).unwrap(), bytes); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index ba4cdf62e6..052c256939 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -173,6 +173,31 @@ mod tests { "#; + #[test] + fn public_cache_key_hashes_the_configured_database() { + const CHILD: &str = "LIGHTCRAFT_TEST_LENS_CACHE_KEY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lc-lens-key-wiring-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("lens.xml"), DB).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "lens_profiles::tests::public_cache_key_hashes_the_configured_database", "--nocapture"]) + .env(CHILD, "1") + .env(ENV, &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + let loaded = database().expect("fixture database was loaded by the public loader"); + assert_eq!(loaded, &LensDb::parse(DB).unwrap()); + assert_ne!(cache_key(), 0, "configured nonempty database cannot use the no-database identity"); + assert_eq!(cache_key(), cache_key_for(Some(loaded)), "public lens key hashes the actual loaded snapshot"); + } + #[test] fn database_identity_tracks_loaded_geometry_not_xml_formatting() { let db = LensDb::parse(DB).unwrap(); diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index 84d7920c14..10b318a109 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -382,11 +382,18 @@ fn smart_preview_from_another_database_stays_decodable_offline() { let bytes = encode(&image, None).unwrap(); let nl = MAGIC.len() + bytes[MAGIC.len()..].iter().position(|b| *b == b'\n').unwrap(); let mut head: serde_json::Value = serde_json::from_slice(&bytes[MAGIC.len()..nl]).unwrap(); - head[LENS_FIELD] = serde_json::json!(123); - assert!(header_is_stale(&head, true, 456)); + head[LENS_FIELD] = serde_json::json!(crate::lens_profiles::cache_key().wrapping_add(1)); let mut changed = MAGIC.to_vec(); changed.extend_from_slice(head.to_string().as_bytes()); changed.extend_from_slice(&bytes[nl..]); - let (decoded, _, _) = decode(&changed).unwrap(); - assert_eq!((decoded.width, decoded.height), (image.width, image.height)); + let dir = temp("lens-database-offline"); + let path = dir.join("old.lcsp"); + std::fs::write(&path, &changed).unwrap(); + assert!(is_stale_for(&path, true), "the public disk check compares the current lens identity"); + assert!(!is_stale_for(&path, false), "non-fitted photos do not depend on the lens database"); + assert!(is_valid(&path), "staleness does not invalidate the offline copy"); + let decoded = load(&path).unwrap(); + assert!(decoded.from_proxy); + assert_eq!((decoded.image.width, decoded.image.height), (image.width, image.height)); + let _ = std::fs::remove_dir_all(&dir); } From be6894acdea621631c65ceef87bf67f8c44cdcc6 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:03:45 +0100 Subject: [PATCH 08/29] =?UTF-8?q?KEY-NEXTPREV:=20=E2=86=91=20/=20=E2=86=93?= =?UTF-8?q?=20step=20through=20Survey=20and=20Compare=20instead=20of=20lea?= =?UTF-8?q?ving=20one=20photo=20selected=20(#3640)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Survey and Compare, → / ← go to the next / previous photo on screen, but ↑ / ↓ ran library.down / library.up, which replace the selection with a single photo: one key press took every other photo out of the survey. They now step like → / ←, and survey_up_and_down_step_through_its_photos covers it. --- crates/ui-egui/src/shortcuts.rs | 6 ++++-- crates/ui-egui/src/tests/compare.rs | 16 ++++++++++++++++ docs/whats-new.md | 5 +++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 07cfe8ba03..64ff537a61 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -629,8 +629,10 @@ fn fire_grid_key(app: &mut LightcraftApp, f: &str) -> bool { } } else if let Some(step) = f.strip_prefix("grid:extend:") { extend_selection(app, step.parse::().unwrap_or(0)); - } else if compare::culling(app) && (f == "library.next" || f == "library.previous") { - let d = if f == "library.next" { 1 } else { -1 }; + } else if compare::culling(app) && matches!(f, "library.next" | "library.previous" | "library.down" | "library.up") { + // ↑ / ↓ step like → / ←: run as the grid's Photo Below / Above, they would leave one photo + // of the survey (or the pair) selected (issue #3640) + let d = if matches!(f, "library.next" | "library.down") { 1 } else { -1 }; let _ = if app.ui.view == crate::state::ViewMode::Compare { compare::compare_step(app, d) } else { compare::survey_step(app, d) }; } else { return false; diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index f570df33a8..3333d55e30 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -416,3 +416,19 @@ fn survey_command_click_on_the_active_photo_activates_the_last_one() { let sel: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); assert_eq!((sel, h.app.session.selection.active.map(|p| p.0)), (vec![b, c], Some(c))); } + +/// Issue #3640: ↑ / ↓ in Survey step through its photos like → / ←; they used to run the grid's +/// Photo Below / Above, which selected one photo and left the other two out of the survey. +#[test] +fn survey_up_and_down_step_through_its_photos() { + let mut h = demo(); + let [a, b, c] = survey_of_three(&mut h); + let sel = |h: &Headless| h.app.session.selection.ids.iter().map(|p| p.0).collect::>(); + for (key, want) in [("down", c), ("down", c), ("up", b), ("up", a), ("right", b), ("left", a)] { + let r = h.request("ui.key", json!({"key": key}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!((sel(&h), h.app.session.selection.active.map(|p| p.0)), (vec![a, b, c], Some(want)), "after {key}"); + } + assert_eq!(h.app.ui.view, crate::state::ViewMode::Survey); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index 98a0ac7157..2867230513 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,11 @@ ## 2026-10-30 +### ↑ and ↓ keep the Survey together +- In Survey (N) and Compare (C), ↑ and ↓ now step through the photos on screen, as → and ← do. Before, they ran the + grid's Photo Below and Photo Above, which selected a single photo, so the survey shrank to that one photo + (issue #3640). + ### The Flatpak may talk to the accessibility bus - The Flatpak package now has access to the accessibility bus (`org.a11y.Bus`) and no other new permission; its network, Pictures folder and GPU access are unchanged. Without it the sandbox hid the bus, which AccessKit needs to reach a screen reader such as Orca; this has not been tried with Orca yet. The Flatpak build is the only one affected. From 3ee89dfc9b09769ab89bae0439f8cadde5c20287 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:26:28 +0100 Subject: [PATCH 09/29] =?UTF-8?q?KEY-NEXTPREV:=20a=20Compare=20test=20for?= =?UTF-8?q?=20=E2=86=91=20/=20=E2=86=93=20(#3640)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit compare_up_and_down_step_the_candidate checks that ↓ / ↑ change the candidate as → / ← do while the select stays. Without the fix ↓ left the pair as (21, 14) where → gave (21, 7). --- crates/ui-egui/src/tests/compare.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 3333d55e30..5462499d7b 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -432,3 +432,26 @@ fn survey_up_and_down_step_through_its_photos() { } assert_eq!(h.app.ui.view, crate::state::ViewMode::Survey); } + +/// The same keys in Compare: ↓ / ↑ change the candidate as → / ← do, and the select stays (#3640). +#[test] +fn compare_up_and_down_step_the_candidate() { + let mut h = demo(); + let vis: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [vis[0], vis[1]], "active": vis[0]}}), T); + let r = h.request("engine.execute", json!({"command": "view.compare"}), T); + let (sel, cand) = (r["result"]["select"].as_u64().unwrap(), r["result"]["candidate"].as_u64().unwrap()); + h.settle(SETTLE); + let press = |h: &mut Headless, key: &str| { + let r = h.request("ui.key", json!({"key": key}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h.app.ui.compare + }; + let after_right = press(&mut h, "right"); + assert!(after_right.is_some_and(|(s, c)| s == sel && c != cand), "{after_right:?}"); + assert_eq!(press(&mut h, "left"), Some((sel, cand))); + assert_eq!(press(&mut h, "down"), after_right, "↓ steps like →"); + assert_eq!(press(&mut h, "up"), Some((sel, cand)), "↑ steps like ←"); + assert_eq!(h.app.ui.view, crate::state::ViewMode::Compare); +} From fbb318a83a91b045911ca94a5fd644f6f694e263 Mon Sep 17 00:00:00 2001 From: r3d42-git <279915996+r3d42-git@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:45:53 +0100 Subject: [PATCH 10/29] LR-PROF-CAMERACOLOR: publish known activity totals before worker dispatch A delayed Find Similar worker left its visible task total at zero although the search plan already knew the count. Initialize tracked activity progress synchronously before spawning the worker; Find Similar, Missing Photos and Reload pass the work counts they already computed without file-system IO. Subsequent progress and cancellation still run through the existing handle. A per-app test-only gate holds the next worker before its first instruction. The regression fails deterministically on the old initialization (0 instead of 12) and verifies the known count, no UI-thread IO, exact reads and cleanup. Existing assertions/timeouts remain unchanged. All three caller suites and all eight local CI gates pass with Rust 1.95.0, actual Metal and WASM on the exact committed tree. No workflow, cache, calibration or photo-data changes. Co-authored-by: Codex --- crates/ui-egui/src/find_similar.rs | 3 +-- crates/ui-egui/src/missing_sweep.rs | 3 +-- crates/ui-egui/src/reload.rs | 3 +-- crates/ui-egui/src/tasks.rs | 13 +++++++++++- crates/ui-egui/src/tests/find_similar.rs | 26 ++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/find_similar.rs b/crates/ui-egui/src/find_similar.rs index d96424317c..77d80a23b7 100644 --- a/crates/ui-egui/src/find_similar.rs +++ b/crates/ui-egui/src/find_similar.rs @@ -41,7 +41,6 @@ fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp let (flag, stopped) = (cancel.clone(), cancel.clone()); let work = move |task: lightcraft_engine::activity::TaskHandle| { let total = count as u64; - task.progress(0, total); lightcraft_engine::guard::catch(LABEL, || similar::measure(reads, &flag, &|done| task.progress(done as u64, total))) }; let done = move |app: &mut LightcraftApp, ctx: &egui::Context, found: Result, String>| { @@ -62,7 +61,7 @@ fn start(app: &mut LightcraftApp, p: &Value, end: impl FnOnce(&mut LightcraftApp }; end(app, ctx, ended); }; - crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, work, done)?; + crate::tasks::spawn_tracked(app, LABEL, similar::KIND, cancel, count as u64, work, done)?; Ok(count) } diff --git a/crates/ui-egui/src/missing_sweep.rs b/crates/ui-egui/src/missing_sweep.rs index 1afd0a2806..d78990d28b 100644 --- a/crates/ui-egui/src/missing_sweep.rs +++ b/crates/ui-egui/src/missing_sweep.rs @@ -90,7 +90,6 @@ pub fn ask(app: &mut LightcraftApp, reply: Sender) -> Outcome { let cancel = Arc::new(AtomicBool::new(false)); let flag = cancel.clone(); let work = move |task: lightcraft_engine::activity::TaskHandle| { - task.progress(0, total); // (a panic is this check's failure, answered to the callers: they would wait for it in vain) lightcraft_engine::guard::catch("Missing Photos", || { missing::sweep(files, |f| exists(f), || flag.load(Ordering::Relaxed), |done| task.progress(done as u64, total)) @@ -113,7 +112,7 @@ pub fn ask(app: &mut LightcraftApp, reply: Sender) -> Outcome { app.missing.kept = Some(Kept { library, snapshot, at: Instant::now(), answer }); } }; - if let Err(e) = crate::tasks::spawn_tracked(app, LABEL, KIND, cancel, work, done) { + if let Err(e) = crate::tasks::spawn_tracked(app, LABEL, KIND, cancel, total, work, done) { app.missing.fail(library, &e); } Outcome::Later diff --git a/crates/ui-egui/src/reload.rs b/crates/ui-egui/src/reload.rs index 8748bfd655..8eef14fb9d 100644 --- a/crates/ui-egui/src/reload.rs +++ b/crates/ui-egui/src/reload.rs @@ -46,7 +46,6 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option Option, /// Repaints the window when a task finishes (set every frame). pub(crate) repaint: Option, + /// Pause the next worker before its first instruction, without relying on OS scheduling. + #[cfg(test)] + pub(crate) next_worker_start: Option>, } impl Tasks { @@ -57,16 +60,18 @@ pub fn spawn( /// [`spawn`] for a task with progress that can stop: its row (`kind`, `label`) adopts `cancel`, /// the flag `work` checks, so the row's ✕ and `activity.cancel` stop it; `work` reports progress -/// through the handle it is given. +/// through the handle it is given. `total` is published before the worker starts (0 if unknown). pub fn spawn_tracked( app: &mut LightcraftApp, label: &str, kind: &'static str, cancel: std::sync::Arc, + total: u64, work: impl FnOnce(lightcraft_engine::activity::TaskHandle) -> T + Send + 'static, done: impl FnOnce(&mut LightcraftApp, &egui::Context, T) + Send + 'static, ) -> Result<(), String> { let guard = app.session.activity.start(kind, label, lightcraft_engine::activity::Cancel::Flag(cancel)); + guard.progress(0, total); let handle = guard.handle(); start(app, label, Some(guard), move || work(handle), done) } @@ -81,7 +86,13 @@ fn start( ) -> Result<(), String> { let (tx, rx) = channel::(); let repaint = app.tasks.repaint.clone(); + #[cfg(test)] + let gate = app.tasks.next_worker_start.take(); let job = move || { + #[cfg(test)] + if let Some(gate) = gate { + let _ = gate.recv(); + } let t = work(); let _ = tx.send(Box::new(move |app: &mut LightcraftApp, ctx: &egui::Context| done(app, ctx, t))); if let Some(c) = repaint { diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index f68fb5e2e8..1da2f633a5 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -121,6 +121,32 @@ fn a_search_from_the_menu_reads_off_the_ui_thread_and_the_window_goes_on() { assert!(toast.starts_with(&format!("{shown} similar photos")), "{toast}"); } +/// A worker may not be scheduled before the next frames: the known work count is published by +/// the command itself, rather than depending on a first worker instruction. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_known_total_is_visible_before_the_worker_can_start() { + let (mut h, drive) = app_on_a_slow_drive(GUARD); + let (resume, paused) = std::sync::mpsc::channel(); + h.app.tasks.next_worker_start = Some(paused); + let started = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); + let before = rows(&h); + let read_before = drive.reads.load(Ordering::SeqCst); + // Always release and drain the worker before asserting, including the negative counterprobe. + drive.open.store(true, Ordering::SeqCst); + resume.send(()).unwrap(); + until_done(&mut h); + assert_eq!(started, json!({"background": true, "count": PHOTOS})); + assert_eq!(before.len(), 1); + assert_eq!((before[0].done, before[0].total), (0, PHOTOS)); + assert_eq!(before[0].label, LABEL); + assert!(before[0].cancellable); + assert_eq!(read_before, 0, "the worker was stopped before measuring any photo"); + assert_eq!(drive.on_ui.load(Ordering::SeqCst), 0); + assert_eq!(drive.reads.load(Ordering::SeqCst), PHOTOS as usize); + assert!(rows(&h).is_empty()); +} + /// One search at a time: the menu row is off while one runs and on again after it, and a second /// request is refused without touching the first. #[test] From d0929d9ddd8936b3a0247b1e2a52a83ec15f6bec Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:30:03 +0100 Subject: [PATCH 11/29] Loupe: the info overlay starts below the filter pill (#3837) With a filter active, the pill at the canvas' top left covered the overlay's first line (the file name). info_overlay_top now starts the overlay below the pill outside the full-screen preview, so info_overlay_extent and the labels placed under it (Before, a hovered preset) follow too. --- crates/ui-egui/src/panels/detail/info.rs | 38 ++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index 99a0fc1108..ce7f3bc969 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -96,12 +96,23 @@ pub(super) fn info_overlay_extent(app: &LightcraftApp, p: &egui::Painter, photo: } /// Where the info overlay's text starts below the canvas' top: the full-screen preview has no top -/// bar, so on macOS it starts below the window controls that sit over the photo there (#2460). +/// bar, so on macOS it starts below the window controls that sit over the photo there (#2460); in +/// the loupe it starts below the filter pill when a filter is active (#3837), as the Before label +/// does. fn info_overlay_top(app: &LightcraftApp, t: &Tokens) -> f32 { let controls = app.ui.fullscreen && app.integrated_titlebar && !app.window_is_fullscreen; - if controls { t.top_bar_h } else { INFO_OVERLAY_TOP } + if controls { + t.top_bar_h + } else if !app.ui.fullscreen && filter_pill_shown(app) { + FILTER_PILL_INSET + FILTER_PILL_HEIGHT + INFO_OVERLAY_BELOW_PILL + } else { + INFO_OVERLAY_TOP + } } +/// The gap between the filter pill and the info overlay's first line under it. +const INFO_OVERLAY_BELOW_PILL: f32 = 6.0; + /// The info overlay's lines for `photo`, or `None` when it is off. fn info_overlay_lines(app: &LightcraftApp, photo: &lightcraft_catalog::Photo) -> Option> { use crate::state::InfoOverlay; @@ -533,6 +544,29 @@ mod info_overlay_tests { assert_eq!(name_top(&app, &photo), 12.0, "the loupe's canvas starts below the top bar"); } + /// #3837: with a filter active, the file name starts below the loupe's filter pill instead of + /// under it, and a label placed below the overlay clears both; the full-screen preview, which + /// has no pill, keeps the usual top. + #[test] + fn the_file_name_starts_below_the_filter_pill() { + let (mut app, photo) = demo_app(); + assert_eq!(name_top(&app, &photo), INFO_OVERLAY_TOP, "no filter, no pill"); + app.session.execute("library.filter", &serde_json::json!({"text": "x"})).unwrap(); + assert!(filter_pill_shown(&app), "the search shows the pill"); + let top = name_top(&app, &photo); + assert!(top >= FILTER_PILL_INSET + FILTER_PILL_HEIGHT, "the name starts below the pill: {top}"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let raw = crate::headless::HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + let mut extent = 0.0; + ctx.run_ui(raw, |ui| extent = info_overlay_extent(&app, ui.painter(), &photo)).textures_delta.clear(); + let (texts, _) = paint_overlay(&app, &photo); + let bottom = texts.iter().map(|t| t.pos.y + t.galley.size().y).fold(0.0, f32::max); + assert!(extent >= bottom, "the extent follows the overlay down: {extent} < {bottom}"); + app.ui.fullscreen = true; + assert_eq!(name_top(&app, &photo), INFO_OVERLAY_TOP, "the full-screen preview has no pill"); + } + /// #2460: a rated or flagged photo shows its stars and flag under the date and size. #[test] fn the_info_overlay_shows_the_rating_and_flag_under_the_date() { From 44d51441fb38ca14a03b954c89b1c583cacb7ca7 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:36:12 +0100 Subject: [PATCH 12/29] Info overlay test: the extent clears the badges below the filter pill too --- crates/ui-egui/src/panels/detail/info.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index ce7f3bc969..5071243bb7 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -563,6 +563,15 @@ mod info_overlay_tests { let (texts, _) = paint_overlay(&app, &photo); let bottom = texts.iter().map(|t| t.pos.y + t.galley.size().y).fold(0.0, f32::max); assert!(extent >= bottom, "the extent follows the overlay down: {extent} < {bottom}"); + // with badges under the text, a label below the overlay clears them too + let mut rated = photo.clone(); + rated.rating = 3; + let (_, rects) = paint_overlay(&app, &rated); + let badges = rects.into_iter().find(|(id, _)| id == "canvas:infoOverlayBadges").map(|(_, r)| r).expect("three stars"); + let mut extent = 0.0; + let raw = crate::headless::HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + ctx.run_ui(raw, |ui| extent = info_overlay_extent(&app, ui.painter(), &rated)).textures_delta.clear(); + assert!(extent >= badges.bottom(), "the extent clears the moved badges: {extent} < {badges:?}"); app.ui.fullscreen = true; assert_eq!(name_top(&app, &photo), INFO_OVERLAY_TOP, "the full-screen preview has no pill"); } From 03301a027d1df366f9e5cf276fbab97e15c2a940 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:30:12 +0100 Subject: [PATCH 13/29] =?UTF-8?q?Survey=20=E2=86=91/=E2=86=93=20test:=20th?= =?UTF-8?q?e=20grid=20keeps=20Photo=20Below=20/=20Above=20(review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/tests/compare.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 5e518d0c07..4bbc7cf808 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -568,3 +568,28 @@ fn compare_up_and_down_step_the_candidate() { assert_eq!(press(&mut h, "up"), Some((sel, cand)), "↑ steps like ←"); assert_eq!(h.app.ui.view, crate::state::ViewMode::Compare); } + +/// Outside Survey and Compare, ↑ / ↓ keep the grid's Photo Below / Above (#3640 only changed the +/// culling views): from two selected photos in the grid, ↓ selects the one photo it moves to (the +/// Survey path would have kept both selected), and ↑ comes back. +#[test] +fn grid_up_and_down_still_move_to_one_photo() { + let mut h = demo(); + let vis: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let r = h.request("ui.set", json!({"view": "photoGrid"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [vis[0], vis[1]], "active": vis[0]}}), T); + h.settle(SETTLE); + let key = |h: &mut Headless, k: &str| { + let r = h.request("ui.key", json!({"key": k}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + }; + key(&mut h, "down"); + let below = h.app.session.selection.active.map(|p| p.0).expect("an active photo"); + assert_ne!(below, vis[0], "↓ moved"); + assert_eq!(h.app.session.selection.ids.iter().map(|p| p.0).collect::>(), vec![below], "one photo selected, as Photo Below does"); + key(&mut h, "up"); + assert_eq!(h.app.session.selection.active.map(|p| p.0), Some(vis[0]), "↑ comes back"); + assert_eq!(h.app.ui.view, crate::state::ViewMode::PhotoGrid); +} From 9b2b2de8d2179c8b1460abf7f538d0c7198ccf60 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:09:32 +0100 Subject: [PATCH 14/29] Low-disk notice: warn under 20 GB free, not under 10 % of the drive (#4013) The notice also fired when less than a tenth of the drive was free. On a large drive that is a lot of room: 76 GB free of 926 GB warned that the drive was almost full while the preview cache took 249 MB. The share no longer counts; under 20 GB free still warns, on any drive. Below 200 GB the share never fired before the 20 GB floor anyway, so only large drives change. --- crates/engine/src/disk_space.rs | 29 +++++++++++++---------------- docs/parity-checklist.md | 3 ++- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/disk_space.rs b/crates/engine/src/disk_space.rs index eb7f29e967..163cb64740 100644 --- a/crates/engine/src/disk_space.rs +++ b/crates/engine/src/disk_space.rs @@ -3,8 +3,8 @@ //! The automatic preview cache budget grows with the library and has no ceiling //! ([`crate::media::default_disk_cache_bytes`]): a large library can fill its drive. Rather than cap //! it, the session looks at the drive's free space when the library opens and, at most every -//! [`CHECK_EVERY`] while the app runs (thumbnails and previews fill the cache); when it is under [`LOW_FREE_PERCENT`] of the drive or -//! under [`LOW_FREE_BYTES`], it hands out one [`LowDiskAlert`] ([`crate::Session::take_disk_space_alert`]) +//! [`CHECK_EVERY`] while the app runs (thumbnails and previews fill the cache); when it has under +//! [`LOW_FREE_BYTES`] free, it hands out one [`LowDiskAlert`] ([`crate::Session::take_disk_space_alert`]) //! that the UI shows with a way to Settings ▸ Performance, where the cache can be given a limit. It is //! not repeated until the next library open or app run. Reading the free space can fail (a network //! share that doesn't say, the web build): then there is no alert, only a log line. @@ -13,9 +13,8 @@ use std::path::Path; -/// The drive is low when less than this share of it (percent) is free… -pub const LOW_FREE_PERCENT: u64 = 10; -/// …or when less than this is free (20 GB), whichever comes first. +/// The drive is low when less than this is free (20 GB). Not a share of the drive: 10 % of a 1 TB +/// drive is 100 GB, years of previews, and a notice then only alarms (#4013: 76 GB free of 926 GB). pub const LOW_FREE_BYTES: u64 = 20 << 30; /// While a library is open, the free space is read at most this often (statvfs on the cache's /// drive: cheap, but not something for every frame or every write). @@ -43,11 +42,9 @@ pub struct DiskSpace { } impl DiskSpace { - /// Under [`LOW_FREE_PERCENT`] of the drive free, or under [`LOW_FREE_BYTES`]. A drive that - /// reports no size isn't judged by its share. + /// Under [`LOW_FREE_BYTES`] free, whatever the drive's size. pub fn is_low(&self) -> bool { - let under_share = self.total > 0 && u128::from(self.available) * 100 < u128::from(self.total) * u128::from(LOW_FREE_PERCENT); - under_share || self.available < LOW_FREE_BYTES + self.available < LOW_FREE_BYTES } } @@ -325,14 +322,14 @@ mod tests { } #[test] - fn under_ten_percent_free_raises_the_alert() { + fn a_small_share_of_a_large_drive_free_raises_no_alert() { let mut s = Session::new(); - // 300 GB is far above 20 GB, but only 7.5 % of a 4 TB drive - let space = DiskSpace { available: 300 * GB, total: 4000 * GB }; - assert!(s.note_disk_space(space)); - let alert = s.take_disk_space_alert().expect("the alert is handed out"); - assert_eq!(alert.space, space); - assert!(s.disk_space_alert_raised()); + // #4013: 76 GB free of 926 GB (8 %) warned that the drive was almost full; so did 300 GB of 4 TB + for space in [DiskSpace { available: 76 * GB, total: 926 * GB }, DiskSpace { available: 300 * GB, total: 4000 * GB }] { + assert!(!s.note_disk_space(space), "{space:?}"); + } + assert!(s.take_disk_space_alert().is_none()); + assert!(!s.disk_space_alert_raised()); } #[test] diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 190015338c..6dd5b5a7db 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -432,7 +432,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); a damaged settings file is kept as `.corrupt-