Merge branch 'main' into feat/ai-defringe

# Conflicts:
#	docs/parity-checklist.md
#	docs/whats-new.md
This commit is contained in:
FredApps committed 2026-11-28 05:42:01 +07:00
commit f329ac035d
43 files changed
+2564 -210

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+3 -2
View File
@@ -28,7 +28,7 @@ mod tone;
pub(crate) use colour::{PROFILE_PROXY, dng_colour, dng_tone_eligible};
#[cfg(test)]
use colour::{PROXY, starting_colour_with};
pub(crate) use colour::{file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
pub(crate) use colour::{correspondence_correction, file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
pub(crate) use hue_sat::HueSat;
#[cfg(test)]
use hue_sat::{MIN_LUMINANCE_KEPT, NO_LUMINANCE_KEPT, fit_hue_sat, hue_saturation, restore_weight};
@@ -94,7 +94,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// 26: a lens database's vignetting correction reaches the sensor proxy only in the share the camera JPEG shows
/// (`camera_vignetting_amount`, ranked within chromaticity classes), not whole: JPEGs that show less of it fitted looks too
/// dark, with skewed colour. The same for a DNG's tone fit; a CR3 proxy gets the gain where its framed pixels come from.
pub const LOOK_VERSION: u32 = 26;
/// 27: geometry-gated external lens and camera framing for JPEG calibration correspondences.
pub const LOOK_VERSION: u32 = 27;
#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
+30 -5
View File
@@ -126,6 +126,14 @@ pub(super) fn starting_colour_with(
(xy, t, look.or_else(|| dark(raw, &t)))
}
/// Additional profile resolution for this proposal's pooled/DNG routes; CR3 keeps Main's route.
pub(crate) fn correspondence_correction(raw: &RawImage, bytes: &[u8]) -> Option<lightcraft_develop::EmbeddedLens> {
if raw.format == RawFormat::Cr3 {
return None;
}
crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes))
}
/// The colour a raw starts from ([`starting_colour`]) as DNG colour tags, for a DNG of the raw's camera RGB (Photo
/// Merge, issue #965): without them a merge of CR2s, whose colour comes from a look fitted to their JPEG, rendered
/// green and dark. `None` when the file has colour matrices of its own (a DNG keeps them).
@@ -133,11 +141,31 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<C
if lightcraft_raw::color::has_matrix(&raw.color) {
return None;
}
let correction = correspondence_correction(raw, bytes);
starting_colour_tags_with_correction(raw, bytes, correction.as_ref())
}
/// Fit DNG colour in the stored sample space. Only a vignette owned by the file's
/// retained opcodes may enter the fit; external profile geometry still aligns the pairs.
pub(super) fn starting_colour_tags_with_correction(
raw: &mut RawImage,
bytes: &[u8],
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<ColorData> {
let correction = correction.filter(|_| raw.format != RawFormat::Cr3).map(|correction| lightcraft_develop::EmbeddedLens {
vignette: crate::files::embedded_lens(&raw.info()).and_then(|lens| lens.vignette),
..*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, None);
// 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.as_ref());
raw.opcodes.list3 = list3;
dng_colour(&raw.color, &white, &t, look.as_ref())
}
@@ -149,10 +177,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;
}
+10 -25
View File
@@ -1,7 +1,7 @@
use super::colour::{PROXY, file_local_look};
use super::mono::{fit_tone_only_with, monochrome};
use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered};
use super::proxy::{CLIP_TOLERANCE, Cr3Framing, LensGeometry, MIN_PREVIEW_FRACTION, extend_tone, framed_proxies, proxies, structure_agrees};
use super::proxy::{CLIP_TOLERANCE, Cr3Framing, LensGeometry, MIN_PREVIEW_FRACTION, extend_tone, proxies, structure_agrees};
use super::tone::{HighlightCheck, highlights};
use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020};
@@ -315,31 +315,12 @@ pub(super) fn look_proxies(
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {
// The file's own vignetting data is what its camera applied to the JPEG. A lens database profile describes the
// lens, not what this camera did: an ILCE-7M3 JPEG with an FE 28mm F2 at f/2 (maker note: vignetting correction
// Auto) shows none of lensfun's correction relative to its raw (the A7CR's shading Auto JPEGs show no consistent
// peripheral brightening either, docs/sony-lens-corrections.md). With the whole profile on the sensor that fit
// learned corners the JPEG doesn't have: 0.062 held-out RMS instead of 0.027, a darker, orange render. So the share
// of the profile the JPEG shows is measured. (Only without a lens warp: the gain goes on the returned proxy, and a
// warped one no longer has each pixel at its source position. A warp comes from the file's own opcodes, and a file
// with its own correction never gets a database profile, `lens_profiles::for_raw`.)
let database = embedded.filter(|e| e.source == lightcraft_develop::LensSource::Database && lens.is_none());
let Some(vignette) = database.and_then(|e| e.vignette) else {
return proxies(raw, bytes, transform, PROXY, 0.0, lens, embedded);
};
// A CR3's framing (`estimate_cr3_framing`) is estimated here on the uncorrected sensor, not the corrected one as
// before: it compares edge directions, which a smooth vignetting gain hardly moves. On the 22 corpus CR3s with a
// database profile it came out the same both ways (21 unmoved, the R50 V at scale 0.986).
let (mut sensor, reference, clipped, framing) = framed_proxies(raw, bytes, transform, PROXY, 0.0, lens, None)?;
// CR3 proxies come back oriented like the JPEG (their framing aligned to it), the others in sensor orientation
let orientation = if raw.format == lightcraft_raw::RawFormat::Cr3 { lightcraft_geom::Orientation::Normal } else { raw.orientation };
database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame { orientation, framing });
Some((sensor, reference, clipped))
proxies(raw, bytes, transform, PROXY, 0.0, lens, embedded)
}
/// Multiply `sensor` by the share of a lens database's `vignette` correction that the camera JPEG `reference` shows
/// ([`camera_vignetting_amount`]).
fn database_vignetting(
pub(super) fn database_vignetting(
sensor: &mut Rgb32f,
reference: &Rgb32f,
clipped: &[bool],
@@ -354,7 +335,7 @@ fn database_vignetting(
}
/// Where a sensor proxy's pixels sit in the oriented, cropped frame a lens's vignetting is in: `framing` (a CR3 proxy
/// moved to its camera JPEG's framing, [`framed_proxies`]) takes each pixel to the position it shows, and
/// moved to its camera JPEG's framing, [`super::proxy::framed_proxies`]) takes each pixel to the position it shows, and
/// `orientation` maps that position to the oriented frame.
#[derive(Clone, Copy, Debug)]
pub(super) struct ProxyFrame {
@@ -425,10 +406,14 @@ pub(super) fn camera_vignetting_amount(
vignette: &lightcraft_develop::EmbeddedVignette,
frame: ProxyFrame,
) -> f64 {
vignetting_amount_from_gains(sensor, reference, clipped, vignetting_gains(sensor, vignette, frame))
}
/// Estimate the share shown by the JPEG, with each gain evaluated at the sensor position that supplied its pixel.
pub(super) fn vignetting_amount_from_gains(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool], gains: impl IntoIterator<Item = f64>) -> f64 {
if sensor.data.len() != reference.data.len() {
return 1.0;
}
let gains = vignetting_gains(sensor, vignette, frame);
let usable = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()) && luminance_2020(*p) > 0.0;
let mut classes: Vec<Vec<(f64, [f64; 3], [f64; 3])>> = vec![Vec::new(); HUE_SECTORS + 1];
for (i, ((s, r), g)) in sensor.data.iter().zip(&reference.data).zip(gains).enumerate() {
@@ -486,7 +471,7 @@ pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::E
}
/// Multiply `sensor` by `amount` of `vignette`'s correction, as the Vignetting amount slider scales it.
fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame, amount: f64) {
pub(super) fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame, amount: f64) {
let gains = vignetting_gains(sensor, vignette, frame);
for (p, g) in sensor.data.iter_mut().zip(gains) {
let gain = (1.0 + (g - 1.0) * amount) as f32;
+199 -17
View File
@@ -1,6 +1,9 @@
use super::colour::{PROFILE_PROXY, PROXY, file_local_look};
use super::hue_sat::fit_hue_sat;
use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, correct_vignetting, without_clipped};
use super::look_fit::{
FIT_PREVIEW_MAX_PIXELS, ProxyFrame, SENSOR_CLIP, apply_vignetting, clip_mask, correct_vignetting, database_vignetting,
vignetting_amount_from_gains, without_clipped,
};
use super::mono::monochrome;
use super::pairs::{collect_pairs, fit_matrix, luma};
use super::tone::fit_tone;
@@ -144,7 +147,12 @@ pub(super) fn framed_proxies(
let mut sensor = sensor_proxy(raw, k, edge as usize)?;
let mut clipped = clip_mask(&sensor);
let mut framing = None;
correct_vignetting(&mut sensor, embedded, raw.orientation);
// A database describes the lens; only the share of its shading correction visible in the JPEG
// belongs in the fit. File-owned corrections describe what the camera applied to this image.
let database_vignette = embedded.filter(|e| e.source == lightcraft_develop::LensSource::Database && lens.is_none()).and_then(|e| e.vignette);
if database_vignette.is_none() {
correct_vignetting(&mut sensor, embedded, raw.orientation);
}
// The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 %
// zoom; other cameras when their correction setting is on): the sensor moved into that geometry is a candidate,
// kept below when it lines up with the JPEG better than the uncorrected one.
@@ -153,6 +161,28 @@ pub(super) fn framed_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 = embedded
.filter(|correction| {
raw.format != RawFormat::Cr3
&& file_local_look(raw.format)
&& transform.matrix_is_fallback
&& lens.is_none()
&& correction.source == lightcraft_develop::LensSource::Database
&& 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);
@@ -176,13 +206,22 @@ pub(super) fn framed_proxies(
// A proxy pixel is clipped when any sample it averages is (outside the CR3 framing the mask is
// 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<bool> = resize(&clipped, sensor.width, sensor.height, Filter::Box).data.iter().map(|p| p[0] > 0.0).collect();
if raw.format != RawFormat::Cr3 {
let clipped = clipped_pixels(&clipped, &sensor);
if raw.format != RawFormat::Cr3 && !external_applied {
sensor.map_in_place(to_working);
}
if let Some(vignette) = database_vignette.filter(|_| !external_applied) {
// CR3 is now in the JPEG’s oriented frame. Other proxies are still in sensor orientation.
let orientation = if raw.format == RawFormat::Cr3 { lightcraft_geom::Orientation::Normal } else { raw.orientation };
database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame { orientation, framing });
}
Some((sensor, reference, clipped, framing))
}
fn clipped_pixels(mask: &Rgb32f, sensor: &Rgb32f) -> Vec<bool> {
resize(mask, sensor.width, sensor.height, Filter::Box).data.iter().map(|p| p[0] > 0.0).collect()
}
/// The camera JPEG at exactly the sensor proxy's size, so the two pair pixel for pixel. Fitting it
/// into the proxy's box instead keeps its own aspect, which can round a pixel short: an ILCE-7RM4's
/// 1616×1080 preview, decoded at 384×257, fits a 192×128 proxy as 191×128, and `collect_pairs`
@@ -200,7 +239,7 @@ pub(super) struct Cr3Framing {
}
impl Cr3Framing {
const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] };
pub(super) const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] };
pub(super) fn source(self, x: f32, y: f32, w: usize, h: usize) -> (f32, f32) {
let (w, h) = (w as f32, h as f32);
@@ -213,9 +252,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<Cr3Framing> {
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: Option<&Rgb32f>) -> Option<Cr3Framing> {
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 {
@@ -225,7 +272,12 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if (reference.width, reference.height) != (w, h) {
return None;
}
let original = fit(original, PROXY, PROXY, Filter::Box);
if (original.width, original.height) != (w, h) || original.data.len() != sensor.data.len() {
return None;
}
let mut gradients = Rgb32f::new(w, h);
let mut original_gradients = Rgb32f::new(w, h);
let mut edges = Vec::new();
for y in 1..h - 1 {
for x in 1..w - 1 {
@@ -237,6 +289,8 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
};
let d = derivative(&sensor);
gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&original);
original_gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&reference);
let magnitude = d[0].hypot(d[1]);
let value = luminance_2020(reference.data[y * w + x]);
@@ -248,7 +302,7 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if edges.len() < 192 {
return None;
}
let score = |framing: Cr3Framing, held_out: bool| -> Option<f64> {
let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool, support: Option<(&Rgb32f, Cr3Framing)>| -> Option<f64> {
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 {
@@ -264,6 +318,19 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
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;
@@ -271,18 +338,29 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
}
(valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight)
};
let before = score(Cr3Framing::IDENTITY, false)?;
let mut best = (before, 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)))?;
if proposal && after < 0.9 {
return None;
}
let before = if proposal { score(&original_gradients, Cr3Framing::IDENTITY, false, Some((&gradients, framing)))? } else { before };
(!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));
// 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((before, value)) = training(framing)
&& value > best.0
{
best = (value, framing);
best = (value, framing, before);
}
}
}
@@ -298,24 +376,36 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
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(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(Cr3Framing::IDENTITY, true)?, score(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() {
eprintln!("[profile] CR3 JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {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)
}
/// 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<Cr3Framing> {
estimate_framing_against(candidate, reference, Some(original))
}
/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing, and that framing (`None`
/// when they stay as they are).
fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f, Option<Cr3Framing>) {
@@ -332,6 +422,93 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg
(apply(&sensor), apply(&clipped), Some(framing))
}
/// 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.
pub(super) 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 {
sample_correspondence(image, p.x as f32 - 0.5, p.y as f32 - 0.5)
} else {
[f32::NAN; 3]
};
}
out
}
/// Bilinear interpolation inside the image, with integer coordinates at pixel centres.
/// At an exact coordinate the two bounds coincide. An invalid neighbour with zero weight
/// must not turn a usable training pixel or its clip mask into NaN.
fn sample_correspondence(image: &Rgb32f, x: f32, y: f32) -> [f32; 3] {
let row = |y| -> [f32; 3] {
let left = image.get(x.floor() as usize, y);
let right = image.get(x.ceil() as usize, y);
std::array::from_fn(|i| left[i] + (right[i] - left[i]) * x.fract())
};
let top = row(y.floor() as usize);
let bottom = row(y.ceil() as usize);
std::array::from_fn(|i| top[i] + (bottom[i] - top[i]) * y.fract())
}
/// 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.
pub(super) 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, 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);
lightcraft_geom::Point::new(f64::from(x), f64::from(y))
};
let mask = resample_correspondence(&mask, frame);
let aligned = resample_correspondence(&candidate, frame);
let Some(vignette) = correction.vignette.filter(|_| correction.source == lightcraft_develop::LensSource::Database) else {
return Some((aligned, mask));
};
// Estimate shading only after the edges agree. Each gain belongs to the source position reached
// through both the JPEG framing and the lens warp, in the same sensor frame as the reoriented lens.
let small = fit(&aligned, PROXY, PROXY, Filter::Box);
let gains = (0..small.data.len()).map(|i| {
let x = ((i % small.width) as f64 + 0.5) * w / small.width as f64;
let y = ((i / small.width) as f64 + 0.5) * h / small.height as f64;
let framed = frame(x, y);
lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, source(framed.x, framed.y), w, h)
});
let amount = vignetting_amount_from_gains(&small, &reference_at(reference, &small), &clipped_pixels(&mask, &small), gains);
if amount == 0.0 {
return Some((aligned, mask));
}
// Apply the measured share before interpolation, exactly where the sensor samples came from.
let mut shaded = sensor.clone();
apply_vignetting(&mut shaded, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal), amount);
Some((resample_correspondence(&resample_correspondence(&shaded, source), frame), mask))
}
/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB.
pub(crate) struct ProfileSamples {
/// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020 (empty when the photo has too little colour).
@@ -344,12 +521,17 @@ pub(crate) struct ProfileSamples {
/// A raw's colour and tone samples for a pooled camera profile (`lightcraft-cli calibrate`): 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_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option<ProfileSamples> {
pub(crate) fn profile_samples(
raw: &RawImage,
bytes: &[u8],
lens: Option<&LensGeometry>,
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<ProfileSamples> {
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, None)?;
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);
+613
View File
@@ -1,3 +1,4 @@
use super::proxy::{align_profile_geometry, resample_correspondence};
use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity};
use super::*;
use lightcraft_raw::profile::{HsvTableApply, ProfileLookHueSat};
@@ -975,6 +976,527 @@ fn cr3_camera_framing_is_measured_independently_of_tone_and_rejects_unrelated_ed
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
}
#[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);
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})"
);
}
}
#[test]
fn correspondence_samples_use_only_neighbours_with_nonzero_weight() {
let valid = [0.25, 0.5, 1.0];
let mut image = Rgb32f::new(2, 2);
image.data.fill([f32::NAN; 3]);
image.set(0, 0, valid);
let sample = |image: &Rgb32f, x, y| resample_correspondence(image, |_, _| lightcraft_geom::Point::new(x, y)).get(0, 0);
assert_eq!(sample(&image, 0.5, 0.5), valid);
assert!(sample(&image, 1.0, 1.0).iter().all(|v| v.is_nan()));
for (x, y) in [(1, 0), (0, 1)] {
let mut axis = image.clone();
axis.set(x, y, valid.map(|v| 3.0 * v));
assert_eq!(sample(&axis, 0.5 + x as f64 * 0.5, 0.5 + y as f64 * 0.5), valid.map(|v| 2.0 * v));
}
}
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,
}),
source: lightcraft_develop::LensSource::Database,
..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;
}
}
}
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()
}
#[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}");
}
}
}
/// A demosaiced CR2 with a default crop inside its active area and no colour matrix.
fn profile_geometry_raw(scene: &Rgb32f, wb: [f32; 3]) -> RawImage {
use lightcraft_raw::{BlackLevel, RawData, Rect};
let (w, h) = (scene.width, scene.height);
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, w - 32, h - 32);
raw.linearized = true;
raw.wb_multipliers = Some(wb);
raw
}
fn profile_geometry_file(target: &Rgb32f, mut ifd: craft_tiff::IfdBuilder) -> Vec<u8> {
use craft_tiff::{TiffWriter, Value};
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<u8> = 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);
file
}
/// A file opcode with a centre outside the active area is ineligible for the file warp. The
/// same opcode returned by the render's lens lookup must not become a database proposal.
#[test]
fn rejected_file_warp_cannot_reenter_as_external_geometry() {
let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [1.0; 3]);
raw.opcodes.list3.push(lightcraft_raw::Opcode::WarpRectilinear { planes: vec![[1.0, -0.32, 0.08, 0.0, 0.0, 0.0]], center: [0.48, 1.01] });
let file_geometry = lens_geometry(&raw.opcodes.list3);
assert!(file_geometry.is_none());
// The file's correction is resolved before the colour fit strips lens opcodes from its sensor.
let file_lens = correspondence_correction(&raw, &[]).unwrap();
assert_eq!(file_lens.source, lightcraft_develop::LensSource::File);
assert!(file_lens.warp.is_some());
raw.opcodes.list3.clear();
let transform = lightcraft_raw::color::camera_transform(&raw, D65);
let mut sensor = sensor_proxy(&raw, 2, 384).unwrap();
sensor.map_in_place(|p| transform.matrix.apply_f32(p));
let target = profile_geometry_target(&sensor, &file_lens, Cr3Framing::IDENTITY);
let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new());
let samples = |correction: Option<&lightcraft_develop::EmbeddedLens>| {
let samples = profile_samples(&raw, &file, file_geometry.as_ref(), correction).unwrap();
(samples.colour, samples.tone)
};
let baseline = samples(None);
let database = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..file_lens };
assert!(samples(Some(&database)) != baseline, "this JPEG would accept the same radial proposal from a database");
assert!(samples(Some(&file_lens)) == baseline, "a rejected file warp cannot move pooled samples");
}
#[test]
fn configured_lens_geometry_reaches_pool_add_after_raw_decode() {
const DB: &str = r#"<lensdatabase>
<camera><maker>Nikon</maker><model>Uncalibrated</model><mount>T</mount><cropfactor>1.5</cropfactor></camera>
<lens><maker>Synthetic</maker><model>Synthetic 18mm</model><mount>T</mount><cropfactor>1.5</cropfactor>
<calibration><distortion model="poly5" focal="18" k1="-0.24" k2="0.08" /></calibration>
</lens></lensdatabase>"#;
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 craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags};
let (w, h) = (768, 512);
let scene = profile_geometry_scene(w, h);
let samples: Vec<u8> = 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 file = profile_geometry_file(&target, ifd);
let decoded = lightcraft_raw::decode(&file).unwrap();
let corrected = profile_samples(&decoded, &file, None, Some(&lens)).expect("corrected decoded NEF contributes samples");
let plain = profile_samples(&decoded, &file, None, None).unwrap();
assert!(corrected.colour != plain.colour && corrected.tone != plain.tone, "the distortion changes both sets of correspondences");
// Match the per-photo cap independently for colour and tone, then compare the actual public profile.
fn capped<T>(samples: Vec<T>) -> Vec<T> {
let step = samples.len().div_ceil(4000).max(1);
samples.into_iter().step_by(step).collect()
}
let colour = capped(corrected.colour);
let (matrix, hue_sat) = fit_profile(&colour).expect("synthetic scene spans enough colours for pooled calibration");
let tone = fit_profile_tone(&capped(corrected.tone), &matrix).expect("the camera JPEG supplies a pooled curve");
let expected = crate::camera_profiles::CameraProfile::new("Uncalibrated", 1, colour.len(), matrix, hue_sat).with_tone(Some(tone));
let mut pool = crate::camera_profiles::Pool::default();
assert_eq!(pool.add(&file).unwrap(), Some(crate::camera_profiles::Added { model: "Uncalibrated".into(), colour: true }));
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");
}
/// Exclude unsaved external shading while keeping the resolved DNG correspondence warp.
fn assert_external_dng_vignette_contract(raw: &RawImage, sensor: &Rgb32f, lens: &lightcraft_develop::EmbeddedLens, white: &crate::files::DngWhite) {
// The JPEG shows the shading correction. Opening the RAW can use it, while exporting a DNG
// keeps only the corrections represented by its opcodes.
let mut vignetted = *lens;
vignetted.vignette =
Some(lightcraft_develop::EmbeddedVignette { k: [0.5, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.45, 0.55), radius: 0.6 });
let mut corrected = sensor.clone();
correct_vignetting(&mut corrected, Some(&vignetted), raw.orientation);
let mut jpeg = profile_geometry_target(&corrected, lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] });
jpeg.map_in_place(|p| p.map(|v| v.powf(0.7)));
let file = profile_geometry_file(&jpeg, craft_tiff::IfdBuilder::new());
let tags = |correction| {
let mut opened = raw.clone();
let (_, transform, look) = starting_colour(&mut opened, &file, None, Some(correction));
dng_colour(&opened.color, white, &transform, look.as_ref()).unwrap()
};
let expected_tags = tags(lens);
assert_ne!(tags(&vignetted), expected_tags, "the JPEG makes external shading observable in the fitted colour");
let actual = super::colour::starting_colour_tags_with_correction(&mut raw.clone(), &file, Some(&vignetted)).unwrap();
assert_eq!(actual, expected_tags, "DNG colour fitting must exclude external vignette gains");
let mut converted = raw.clone();
converted.color = actual;
let options = lightcraft_raw::DngWriteOptions::default();
let saved = lightcraft_raw::write_dng(&converted, &options).unwrap();
converted.color = expected_tags;
assert_eq!(saved, lightcraft_raw::write_dng(&converted, &options).unwrap(), "saved DNG matches the warp-only colour contract");
assert!(lightcraft_raw::decode(&saved).unwrap().opcodes.list3.is_empty());
}
/// A DNG's own vignette is serialized and must remain in its fit and retained opcodes.
fn assert_file_owned_dng_vignette_contract(
raw: &mut RawImage,
file: &[u8],
lens: &lightcraft_develop::EmbeddedLens,
white: &crate::files::DngWhite,
expected_tags: &ColorData,
) {
// 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] });
raw.opcodes.list3.push(lightcraft_raw::Opcode::FixVignetteRadial { k: [0.3, 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_eq!(own.source, lightcraft_develop::LensSource::File);
assert!(own.vignette.is_some(), "file-owned shading must remain part of the DNG fit and opcodes");
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(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]
fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() {
const DB: &str = r#"<lensdatabase>
<camera><maker>Synthetic</maker><model>Uncalibrated</model><mount>T</mount><cropfactor>1.5</cropfactor></camera>
<lens><maker>Synthetic</maker><model>Synthetic 18mm</model><mount>T</mount><cropfactor>1.5</cropfactor>
<calibration><distortion model="poly5" focal="18" k1="-0.24" k2="0.08" /></calibration>
</lens></lensdatabase>"#;
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)
.env("LIGHTCRAFT_CONFIG_DIR", &dir)
.env("LIGHTCRAFT_CAMERA_PROFILES", &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;
}
let mut raw = profile_geometry_raw(&profile_geometry_scene(416, 288), [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 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)));
use craft_tiff::{IfdBuilder, 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);
let file = profile_geometry_file(&target, ifd);
// Standalone non-CR3 scope: a coherent profile must not alter Main's CR3 framing route.
let mut cr3 = raw.clone();
cr3.format = RawFormat::Cr3;
let baseline = proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap();
let proposed = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::<Vec<_>>();
assert_eq!(bits(&baseline.0), bits(&proposed.0), "CR3 sensor keeps Main framing");
assert_eq!(bits(&baseline.1), bits(&proposed.1), "CR3 reference is unchanged");
assert_eq!(baseline.2, proposed.2, "CR3 clipping is unchanged");
let cr3_samples = |correction: Option<&lightcraft_develop::EmbeddedLens>| {
let samples = profile_samples(&cr3, &file, None, correction).expect("CR3 colour and tone samples");
(samples.colour, samples.tone)
};
assert!(cr3_samples(None) == cr3_samples(Some(&lens)), "CR3 pooled samples preserve the original framing");
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::<f64>()).sum();
sum / pairs.len() as f64
};
let before = error(profile_samples(&raw, &file, None, None).unwrap().colour);
let after = error(profile_samples(&raw, &file, None, Some(&lens)).unwrap().colour);
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();
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);
assert_external_dng_vignette_contract(&raw, &sensor, &lens, &white);
assert_file_owned_dng_vignette_contract(&mut raw, &file, &lens, &white, &expected_tags);
// A real configured profile with nonzero vignetting must still be available to Main's
// per-file CR3 path, while this proposal's new Pool/DNG lookup stays excluded.
let vignetted_db =
DB.replace("</calibration>", r#"<vignetting model="pa" focal="18" aperture="3.5" distance="1000" k1="-0.4" k2="0" k3="0" /></calibration>"#);
let path = std::path::PathBuf::from(std::env::var_os(crate::lens_profiles::ENV).unwrap()).join("synthetic.xml");
std::fs::write(path, vignetted_db).unwrap();
crate::lens_profiles::reload();
let resolved = crate::lens_profiles::for_raw(&cr3.info(), || lightcraft_meta::extract(&file)).unwrap();
assert!(resolved.warp.is_some() && resolved.vignette.is_some(), "fixture resolves both corrections");
let mut main_lens = resolved;
main_lens.warp = None;
let main_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&main_lens)).unwrap();
let actual_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&resolved)).unwrap();
assert_eq!(bits(&main_proxy.0), bits(&actual_proxy.0), "CR3 keeps Main's vignetting and framing, ignoring the new radial proposal");
let (mut unshaded, reference, clipped, framing) = super::proxy::framed_proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap();
let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing };
let vignette = resolved.vignette.as_ref().unwrap();
let share = camera_vignetting_amount(&unshaded, &reference, &clipped, vignette, frame);
let gains = vignetting_gains(&unshaded, vignette, frame);
for (p, gain) in unshaded.data.iter_mut().zip(gains) {
*p = p.map(|v| v * (1.0 + (gain - 1.0) * share) as f32);
}
assert_eq!(bits(&unshaded), bits(&actual_proxy.0), "CR3 uses the share measured at the framed sensor positions");
assert_eq!(main_proxy.2, actual_proxy.2, "CR3 masks keep Main semantics");
assert!(cr3_samples(Some(&main_lens)) == cr3_samples(Some(&resolved)), "the database warp must not change pooled CR3 samples");
assert!(correspondence_correction(&cr3, &file).is_none(), "the actual shared Pool/DNG lookup excludes CR3");
let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None);
assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public DNG lookup keeps Main's CR3 route");
assert_eq!(
super::colour::starting_colour_tags_with_correction(&mut cr3, &file, Some(&resolved)),
expected,
"injected CR3 correction cannot bypass DNG scope"
);
}
#[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[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
/// download or an unfinished codec cannot make this test claim a successful RAW calibration.
#[test]
@@ -2893,6 +3415,97 @@ fn a_narrow_black_and_white_curve_that_darkens_the_bright_areas_is_refused() {
}
}
/// Build camera JPEGs that apply none, some, or all of an off-centre database vignette before distortion and
/// framing. Both the file look and the pooled colour and tone samples must follow the JPEG in the default crop.
#[test]
fn external_profile_vignetting_precedes_geometry_in_every_orientation() {
let mut scene = profile_geometry_scene(416, 288);
// Leave headroom for nonuniform WB and source-position vignetting in the generated JPEG.
scene.map_in_place(|p| p.map(|v| v * 0.3));
let mut raw = profile_geometry_raw(&scene, [1.25, 1.0, 0.8]);
let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
assert!(transform.wb.windows(2).any(|v| (v[0] - v[1]).abs() > 0.01), "the fixture must exercise nonuniform as-shot WB");
assert!(transform.matrix_is_fallback);
let mut sensor = sensor_proxy(&raw, 2, 384).unwrap();
assert_eq!((sensor.width, sensor.height), (384, 256));
let mut lens = synthetic_profile_lens();
let vignette =
lightcraft_develop::EmbeddedVignette { k: [1.15, 0.3, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.34, 0.62), radius: 0.6 };
lens.vignette = Some(vignette);
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 framing = Cr3Framing { scale: 0.95, offset: [0.006, -0.004] };
let shade = |image: &mut Rgb32f, share: f64| {
let (w, h) = (image.width, image.height);
for (i, p) in image.data.iter_mut().enumerate() {
let source = lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
let full = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, source, w as f64, h as f64);
*p = p.map(|v| v * (1.0 + share * (full - 1.0)) as f32);
}
};
for (share, orientations) in [(0.0, &[1, 6][..]), (0.45, &[2, 5, 7]), (1.0, &[3, 4, 8])] {
let mut shaded = sensor.clone();
shade(&mut shaded, share);
let expected = profile_geometry_target(&shaded, &lens, framing);
let mut target = expected.clone();
target.map_in_place(|p| p.map(|v| v.powf(0.7)));
let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz());
assert!(
target.data.iter().filter(|p| p.iter().all(|v| v.is_finite())).flat_map(|p| to_srgb.apply_f32(*p)).all(|v| (0.0..=1.0).contains(&v)),
"the synthetic JPEG must have headroom"
);
let file = profile_geometry_file(&target, craft_tiff::IfdBuilder::new());
let mut wrong_order = profile_geometry_target(&sensor, &lens, framing);
shade(&mut wrong_order, share);
for &exif in orientations {
let orientation = lightcraft_geom::Orientation::from_exif(exif);
raw.orientation = orientation;
let oriented_lens = lightcraft_pipeline::optics::reorient_lens(&lens, orientation, 384.0, 256.0);
let (aligned, reference, _) = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&oriented_lens)).unwrap();
let mut no_warp = oriented_lens;
no_warp.warp = None;
let (baseline, _, _) = super::look_fit::look_proxies(&raw, &file, &transform, None, Some(&no_warp)).unwrap();
assert!(
aligned.data.iter().flatten().zip(baseline.data.iter().flatten()).any(|(a, b)| a.to_bits() != b.to_bits()),
"orientation {exif}: profile geometry must be accepted with identical vignetting on both routes"
);
let mut displayed = aligned.clone();
displayed.map_in_place(|p| p.map(|v| v.powf(0.7)));
let rms = geometry_rms(&displayed, &reference);
assert!(rms < 0.009, "orientation {exif}: WB exactly once and matching frames: {rms}");
let truth = reference_at(&expected, &aligned);
let correct_error = geometry_rms(&aligned, &truth);
if share > 0.0 {
let wrong_error = geometry_rms(&aligned, &reference_at(&wrong_order, &aligned));
assert!(
correct_error < wrong_error,
"orientation {exif}, share {share}: source {correct_error} vs output-position gain {wrong_error}"
);
}
let samples = profile_samples(&raw, &file, None, Some(&oriented_lens)).expect("pooled samples with source-position vignetting");
assert!(samples.colour.len() >= 256 && samples.tone.len() >= 256);
let display = |camera| transform.matrix.apply(camera).map(|v| v.powf(0.7));
let colour_error = samples
.colour
.iter()
.map(|(camera, reference)| display(*camera).iter().zip(reference).map(|(v, r)| (v - r).powi(2)).sum::<f64>())
.sum::<f64>()
/ (3 * samples.colour.len()) as f64;
let tone_error =
samples.tone.iter().map(|(camera, reference)| (luma(display(*camera)) - reference).powi(2)).sum::<f64>() / samples.tone.len() as f64;
assert!(colour_error.sqrt() < 0.009, "orientation {exif}, share {share}: pooled colour RMS {}", colour_error.sqrt());
assert!(tone_error.sqrt() < 0.009, "orientation {exif}, share {share}: pooled tone RMS {}", tone_error.sqrt());
// Missing geometry must retain the existing unaligned correspondence path.
let (plain, plain_ref, plain_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
let (fallback, fallback_ref, fallback_clip) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&Default::default())).unwrap();
assert_eq!(plain.data, fallback.data);
assert_eq!(plain_ref.data, fallback_ref.data);
assert_eq!(plain_clip, fallback_clip);
}
}
}
/// A lens database's vignetting correction reaches the fit in the share the camera JPEG shows: a JPEG with none, part
/// or all of it is measured as such, and a JPEG without enough usable pixels keeps the whole correction.
#[test]
+88 -4
View File
@@ -184,6 +184,8 @@ fn cache() -> &'static Mutex<Cache> {
/// The profile for camera `model`: from [`dir`], else built in; read once per process.
pub fn get(model: &str) -> Option<Arc<CameraProfile>> {
// Capture the process fingerprint before a profile can enter the lookup cache.
stable_profile_key();
get_from(model, dir().as_deref())
}
@@ -223,7 +225,7 @@ fn get_from(model: &str, directory: Option<&Path>) -> Option<Arc<CameraProfile>>
let mut ranked: Vec<(u8, PathBuf)> = Vec::new();
for e in &entries {
let path = e.path();
if !path.extension().is_some_and(|x| x == "json") || !path.is_file() {
if path.extension().is_none_or(|x| x != "json") || !path.is_file() {
continue;
}
let rank = if path.file_stem().is_some_and(|s| normalize_for_local_match(&s.to_string_lossy()) == needle) { 1 } else { 2 };
@@ -243,13 +245,22 @@ fn get_from(model: &str, directory: Option<&Path>) -> Option<Arc<CameraProfile>>
profile
}
/// 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.
/// Identity of the camera-profile lookup cache and of the currently loaded lens database.
/// The camera profiles already loaded by this process outlive file changes on disk. A lens
/// reload changes only the lens part of the key used by thumbnails and rendered views.
pub fn cache_key() -> u64 {
cache_key_with_lens(stable_profile_key(), crate::lens_profiles::cache_key())
}
fn stable_profile_key() -> u64 {
static KEY: OnceLock<u64> = OnceLock::new();
*KEY.get_or_init(|| cache_key_for(dir().as_deref()))
}
fn cache_key_with_lens(profile_key: u64, lens_key: u64) -> u64 {
lightcraft_preview::Hasher128::new().str("camera-profiles-with-lens-v2").u64(profile_key).u64(lens_key).finish().0 as u64
}
fn cache_key_for(directory: Option<&Path>) -> u64 {
let entries = directory.and_then(|d| std::fs::read_dir(d).ok());
let mut files: Vec<(String, u64, std::time::Duration)> = entries
@@ -316,10 +327,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::camera_preview::correspondence_correction(&raw, 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(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) };
let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref(), correction.as_ref()) else { return Ok(None) };
let entry = self.models.entry(model.to_owned()).or_default();
let colour = !samples.colour.is_empty();
if colour {
@@ -375,6 +387,71 @@ 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#"<lensdatabase><lens><maker>Test</maker><model>18mm</model><mount>T</mount><cropfactor>1.5</cropfactor>
<calibration><distortion model="poly3" focal="18" k1="-0.03" /></calibration></lens></lensdatabase>"#,
)
.unwrap();
// The loaded snapshots and 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().unwrap();
let profile = profile();
save(&profile, &directory).unwrap();
assert_eq!(get(&profile.model).as_deref(), Some(&profile));
let profile_key = cache_key_for(Some(&directory));
let first = cache_key();
assert_eq!(first, cache_key_with_lens(profile_key, lens_key));
assert_ne!(first, cache_key_with_lens(profile_key, 0), "public camera key must forward the loaded lens key");
// The culling path now reuses rendered views before decoding. Their identity
// must follow the same loaded lens snapshot as camera fitting and thumbnails.
let mut session = crate::Session::with_demo();
let id = session.active().unwrap();
let view = session.loupe_job(id, 64, 64, true).unwrap();
let (views, view_key) = view.view_cache.as_ref().unwrap();
views.put_memory(*view_key, std::sync::Arc::new(lightcraft_raster::Rgba8::from_fn(64, 64, |_, _| [7, 19, 31, 255])));
assert!(session.loupe_job(id, 64, 64, true).unwrap().cached_view().is_some());
let mut replacement = profile.clone();
replacement.samples *= 100;
save(&replacement, &directory).unwrap();
assert_ne!(cache_key_for(Some(&directory)), profile_key, "a fresh process sees a different camera profile fingerprint");
assert_eq!(get(&profile.model).as_deref(), Some(&profile), "the loaded profile stays cached");
let file = directory.join("lens.xml");
let xml = std::fs::read_to_string(&file).unwrap();
std::fs::write(&file, xml.replace("-0.03", "-0.05")).unwrap();
assert_eq!(cache_key(), first, "unreloaded files do not change the loaded database");
crate::lens_profiles::replaced();
assert_ne!(cache_key(), first, "camera keys follow runtime lens replacements too");
let new_lens_key = crate::lens_profiles::cache_key();
assert_eq!(cache_key(), cache_key_with_lens(profile_key, new_lens_key));
assert!(session.loupe_job(id, 64, 64, true).unwrap().cached_view().is_none(), "a view from the old snapshot is not reused");
std::fs::write(&file, xml).unwrap();
crate::lens_profiles::reload();
assert_eq!(cache_key(), first, "restored semantic data restores the camera key");
assert!(session.loupe_job(id, 64, 64, true).unwrap().cached_view().is_some(), "restoring the snapshot restores its view identity");
}
#[test]
fn profiles_round_trip_and_reject_bad_files() {
let dir = std::env::temp_dir().join(format!("lc-camera-profiles-{}", std::process::id()));
@@ -471,6 +548,13 @@ mod tests {
// Staleness test uses fixed version 13 (tested in smart/tests.rs)
}
#[test]
fn lens_database_identity_invalidates_camera_render_cache() {
assert_ne!(cache_key_with_lens(1234, 0), cache_key_with_lens(1234, 123));
assert_ne!(cache_key_with_lens(1234, 123), cache_key_with_lens(1234, 456));
assert_eq!(cache_key_with_lens(1234, 123), cache_key_with_lens(1234, 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()));
+377 -10
View File
@@ -729,8 +729,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<crate::media::SourceRef> {
use crate::media::SourceRef;
@@ -740,6 +740,7 @@ fn original_only(source: crate::media::SourceRef) -> Option<crate::media::Source
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, outliers, reduced: None })
}
SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)),
source @ SourceRef::Demo { .. } => Some(source),
_ => None,
}
}
@@ -791,9 +792,12 @@ fn smart_run(
n.newer_kept += 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 };
// Capture provenance before decoding. A reload during that decode makes its
// pixels ambiguous; a later reload must leave the captured identity on the bytes.
let generation = crate::lens_profiles::generation();
let lens_key = crate::lens_profiles::cache_key();
// 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
@@ -801,8 +805,14 @@ 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());
}
if crate::lens_profiles::generation() != generation {
return Err("lens database changed while decoding the smart preview; retry the build".to_string());
}
let info = src.info_or(Default::default());
crate::smart::encode(&src.image, Some(&info))
crate::smart::encode_with_lens_key(&src.image, Some(&info), lens_key)
})
.and_then(|b| {
let parent = path.parent().ok_or_else(|| format!("{}: no parent folder", path.display()))?;
@@ -810,6 +820,7 @@ fn smart_run(
if !parent.is_dir() {
std::fs::create_dir(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
crate::smart::invalidate_look_check_for_write(dir, lens_key)?;
lightcraft_catalog::safe_file::write_atomic(&path, &b).map_err(|e| format!("{}: {e}", path.display()))
});
match r {
@@ -884,9 +895,9 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let path = crate::smart::sharded_file_path(&dir, &ph);
// (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor
// from a cached source developed with it)
let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview));
// Decode the original afresh, with the photo's hot-pixel setting. Cached sources may
// carry an imported profile or predate the lens database captured by smart_run.
let source = (!discard).then(|| s.media.origin_ref_of(&ph, crate::media::SourceLevel::Preview.max_edge()));
jobs.push((id, path, source, Ages::of(&ph)));
}
let custom = s.smart_previews_dir.is_some();
@@ -955,6 +966,11 @@ pub(crate) fn refresh_stale_smart_previews(s: &mut Session) -> Option<std::threa
/// The body of [`refresh_stale_smart_previews`]: rebuild the stale proxies among `jobs`.
#[cfg(not(target_arch = "wasm32"))]
fn refresh_stale(dir: &std::path::Path, jobs: Vec<SmartJob>) {
// Wait for any writer that decoded with the previous database before inspecting the files.
let (generation, lens_key) = {
let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
(crate::lens_profiles::generation(), crate::lens_profiles::cache_key())
};
let stale: Vec<SmartJob> = jobs
.into_iter()
.map(|(id, path, source, ages)| (id, crate::smart::existing_file_path(dir, path), source, ages))
@@ -975,7 +991,11 @@ fn refresh_stale(dir: &std::path::Path, jobs: Vec<SmartJob>) {
}
}
}
if let Err(e) = crate::smart::mark_look_checked(dir).and_then(|()| crate::smart::mark_source_checked(dir)) {
let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if crate::lens_profiles::generation() != generation {
return;
}
if let Err(e) = crate::smart::mark_look_checked_with_lens_key(dir, lens_key).and_then(|()| crate::smart::mark_source_checked(dir)) {
log::warn!("smart previews: {e}");
}
}
@@ -1224,3 +1244,350 @@ mod tests {
assert!(state.error().is_none());
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod smart_provenance_tests {
use super::{Ages, smart_run};
use crate::media::{SourceLevel, SourceRef};
use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source};
use std::sync::Arc;
fn temp(tag: &str) -> std::io::Result<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)?;
Ok(dir)
}
#[test]
fn damaged_shard_never_relabels_cached_legacy_fallback_and_repairs_from_online_original() {
let dir = temp("legacy-fallback").unwrap();
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), Ages::of(&photo))], 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), Ages::of(&photo))], 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").unwrap();
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), Ages { look: true, 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), Ages { look: true, 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);
}
#[test]
fn smart_command_reads_original_instead_of_cached_pixels() {
let dir = temp("fresh-original").unwrap();
let photo = Photo::new(
PhotoId(1),
Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() },
"original.arw",
"ARW",
32,
24,
"2026-11-04T00:00:00",
);
let path = crate::smart::sharded_file_path(&dir, &photo);
let mut session = crate::Session::new();
session.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(photo) }).unwrap();
session.media.smart_dir = Some(dir.clone());
session.media.insert(PhotoId(1), SourceLevel::Preview, Arc::new(lightcraft_raster::Rgb32f::new(32, 24)));
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = calls.clone();
// The new culling path can serve a prepared view without decoding. It must
// never become the source of a smart preview's linear original pixels.
let view = session.loupe_job(PhotoId(1), 32, 24, true).unwrap();
let (cache, key) = view.view_cache.as_ref().unwrap();
cache.put_memory(*key, Arc::new(lightcraft_raster::Rgba8::from_fn(32, 24, |_, _| [255, 0, 255, 255])));
let cached = view.run();
assert_eq!(cached.quick, Some(crate::media::QuickSource::Cached));
assert_eq!(cached.rendered.unwrap().image.data[0], [255, 0, 255, 255]);
session.media.file_loader = Some(Arc::new(move |_, _, with| {
assert!(with.dcp.is_none(), "smart previews keep the original camera colour");
counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut pixels = lightcraft_raster::Rgb32f::new(32, 24);
pixels.data.fill([0.4; 3]);
Ok((pixels, Default::default()))
}));
let result = session.execute("library.smartPreviews", &serde_json::json!({"ids": [1]})).unwrap();
assert_eq!(result["built"], 1, "{result}");
assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1, "the original must be decoded afresh");
let loaded = crate::smart::load(&path).unwrap();
assert!(loaded.image.data[0].iter().all(|v| *v > 0.3), "neither cached black sources nor prepared magenta views are original pixels");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn fresh_smart_build_and_refresh_keep_the_photos_hot_pixel_decode() {
for outliers in [false, true] {
let dir = temp(if outliers { "fresh-hot-on" } else { "fresh-hot-off" }).unwrap();
let mut photo = Photo::new(
PhotoId(1),
Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() },
"original.arw",
"ARW",
32,
24,
"2026-11-05T00:00:00",
);
photo.kind = lightcraft_catalog::MediaKind::Raw;
let mut settings = lightcraft_develop::DevelopSettings::for_raw(5200.0, 0.0);
settings.detail.nr_outliers = outliers;
photo.develop = Arc::new(settings);
let path = crate::smart::sharded_file_path(&dir, &photo);
let mut session = crate::Session::new();
session.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(photo) }).unwrap();
session.media.smart_dir = Some(dir.clone());
// A valid, matching raw decode in memory is still not a fresh original.
let cached = crate::media::DecodedSource {
outliers,
..crate::media::DecodedSource::new(
Arc::new(lightcraft_raster::Rgb32f::new(32, 24)),
Some(lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() }),
)
};
session.media.insert_source(PhotoId(1), SourceLevel::Preview, cached);
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let log = seen.clone();
session.media.file_loader = Some(Arc::new(move |_, _, with| {
assert!(with.dcp.is_none(), "smart pixels keep the original camera colour");
log.lock().unwrap().push(with.outliers);
let value = if with.outliers { 0.4 } else { 0.2 };
Ok((
lightcraft_raster::Rgb32f::from_fn(32, 24, |_, _| [value; 3]),
lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() },
))
}));
let result = session.execute("library.smartPreviews", &serde_json::json!({"ids": [1]})).unwrap();
assert_eq!(result["built"], 1, "{result}");
assert_eq!(*seen.lock().unwrap(), [outliers], "manual build decodes the original with the photo's option");
let check_pixels = || {
let proxy = crate::smart::load(&path).unwrap();
let expected = if outliers { 0.4 } else { 0.2 };
assert!(
proxy.image.data.iter().flatten().all(|v| (v - expected).abs() < 0.02),
"the loaded proxy carries the requested decode, not cached black pixels"
);
assert!(proxy.from_proxy && !proxy.outliers, "a proxy has no raw mosaic decode flag");
assert!(proxy.fits_outliers(false) && proxy.fits_outliers(true), "offline proxies retain the upstream no-mosaic contract");
};
check_pixels();
// Force a stale look without changing its pixels, then exercise the actual refresh worker.
let bytes = std::fs::read(&path).unwrap();
let start = b"LCSP1\n".len();
let nl = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap();
let mut header: serde_json::Value = serde_json::from_slice(&bytes[start..nl]).unwrap();
header["look_version"] = serde_json::json!(0);
let mut stale = bytes[..start].to_vec();
stale.extend_from_slice(header.to_string().as_bytes());
stale.extend_from_slice(&bytes[nl..]);
std::fs::write(&path, stale).unwrap();
assert!(crate::smart::is_stale_for(&path, true));
super::refresh_stale_smart_previews(&mut session).unwrap().join().unwrap();
assert_eq!(*seen.lock().unwrap(), [outliers, outliers], "refresh also decodes a fresh original with the photo's option");
assert!(!crate::smart::is_stale_for(&path, true));
check_pixels();
std::fs::remove_dir_all(dir).unwrap();
}
}
#[test]
fn runtime_lens_reload_during_smart_decode_preserves_destinations_and_scan_marker() {
const CHILD: &str = "LIGHTCRAFT_TEST_SMART_RELOAD_CHILD";
const DB: &str = r#"<lensdatabase><lens><maker>Test</maker><model>18mm</model><mount>T</mount>
<cropfactor>1.5</cropfactor><calibration><distortion model="poly3" focal="18" k1="-0.03" />
</calibration></lens></lensdatabase>"#;
if std::env::var_os(CHILD).is_none() {
let dir = temp("runtime-reload-child").unwrap();
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"cmd::previews::smart_provenance_tests::runtime_lens_reload_during_smart_decode_preserves_destinations_and_scan_marker",
"--nocapture",
])
.env(CHILD, "1")
.env(crate::lens_profiles::ENV, &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 dir = std::path::PathBuf::from(std::env::var_os(crate::lens_profiles::ENV).unwrap());
let database = dir.join("lens.xml");
let image = lightcraft_raster::Rgb32f::new(32, 24);
let old = crate::smart::encode_with_lens_key(&image, None, 0).unwrap();
for replace in [false, true] {
for existing in [None, Some(b"broken".to_vec()), Some(old.clone())] {
std::fs::write(&database, DB).unwrap();
crate::lens_profiles::reload();
let before = crate::lens_profiles::cache_key();
assert_ne!(before, 0);
let target = dir.join("target.lcsp");
if let Some(bytes) = &existing {
std::fs::write(&target, bytes).unwrap();
} else {
let _ = std::fs::remove_file(&target);
}
let db_path = database.clone();
let pixels = image.clone();
let mut session = crate::Session::new();
session.media.file_loader = Some(Arc::new(move |_, _, _| {
std::fs::write(&db_path, DB.replace("-0.03", "-0.05")).map_err(|e| e.to_string())?;
if replace {
crate::lens_profiles::replaced();
} else {
crate::lens_profiles::reload();
}
Ok((pixels.clone(), Default::default()))
}));
let origin = Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() };
let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge());
let counts =
smart_run(&dir, false, false, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })], None).unwrap();
assert_ne!(crate::lens_profiles::cache_key(), before);
if let Some(bytes) = &existing {
assert_eq!(std::fs::read(&target).unwrap(), *bytes, "a reload never replaces the previous destination");
} else {
assert!(!target.exists(), "a reload never creates a mislabeled proxy");
}
if existing.as_ref() == Some(&old) {
assert_eq!(counts.stale_kept, 1);
} else {
assert_eq!(counts.failed.len(), 1);
assert!(counts.failed[0][1].as_str().unwrap().contains("lens database changed"));
}
// The same change inside the actual background refresh cannot stamp the new DB checked.
std::fs::write(&database, DB).unwrap();
crate::lens_profiles::reload();
std::fs::write(&target, &old).unwrap();
let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge());
super::refresh_stale(&dir, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })]);
assert_eq!(std::fs::read(&target).unwrap(), old);
assert!(!crate::smart::look_checked(&dir));
// A subsequent stable decode writes B's identity and can complete the scan.
let pixels = image.clone();
session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((pixels.clone(), Default::default()))));
let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge());
super::refresh_stale(&dir, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })]);
assert!(!crate::smart::is_stale_for(&target, true));
assert!(crate::smart::look_checked(&dir));
// Reset the marker before the next race attempt.
crate::smart::mark_look_checked_with_lens_key(&dir, 0).unwrap();
}
}
// A reload between originals can leave some proxies written by B before the scan returns.
// Returning to A must scan those proxies even if A had already checked the folder.
std::fs::write(&database, DB).unwrap();
crate::lens_profiles::reload();
let key_a = crate::lens_profiles::cache_key();
crate::smart::mark_look_checked_with_lens_key(&dir, key_a).unwrap();
let (first, second) = (dir.join("first.lcsp"), dir.join("second.lcsp"));
let older = crate::smart::encode_with_lens_key(&image, None, 0).unwrap();
std::fs::write(&first, &older).unwrap();
std::fs::write(&second, &older).unwrap();
let src = |session: &mut crate::Session| session.media.origin_ref(&Source::File { path: "test.arw".into() }, SourceLevel::Preview.max_edge());
let (db_path, pixels) = (database.clone(), image.clone());
let mut session = crate::Session::new();
session.media.file_loader = Some(Arc::new(move |_, _, _| {
std::fs::write(&db_path, DB.replace("-0.03", "-0.05")).map_err(|e| e.to_string())?;
crate::lens_profiles::reload();
Ok((pixels.clone(), Default::default()))
}));
let first_source = src(&mut session);
session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((image.clone(), Default::default()))));
let second_source = src(&mut session);
let ages = Ages { look: true, source: true };
super::refresh_stale(
&dir,
vec![(PhotoId(1), first.clone(), Some(first_source), ages), (PhotoId(2), second.clone(), Some(second_source.clone()), ages)],
);
assert_eq!(std::fs::read(&first).unwrap(), older, "a reload during decode preserves the first proxy");
assert_ne!(crate::lens_profiles::cache_key(), key_a);
assert!(!crate::smart::is_stale_for(&second, true), "the next original was decoded with the new database");
std::fs::write(&database, DB).unwrap();
crate::lens_profiles::reload();
assert_eq!(crate::lens_profiles::cache_key(), key_a);
assert!(crate::smart::is_stale_for(&second, true));
assert!(!crate::smart::look_checked(&dir), "the aborted scan must invalidate A's old folder marker");
super::refresh_stale(&dir, vec![(PhotoId(2), second.clone(), Some(second_source), ages)]);
assert!(!crate::smart::is_stale_for(&second, true));
assert!(crate::smart::look_checked(&dir), "a stable scan makes the folder current again");
}
}
+13 -16
View File
@@ -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]
+210 -5
View File
@@ -156,8 +156,82 @@ pub fn profile_name(db: &LensDb, camera: &str, lens: &str) -> Option<String> {
Some(if model.to_lowercase().starts_with(&p.maker.to_lowercase()) || p.maker.is_empty() { model.clone() } else { format!("{} {model}", p.maker) })
}
/// 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: RwLock<Option<(Arc<LensDb>, u64)>> = RwLock::new(None);
let Some(db) = database() else { return 0 };
let mut key = KEY.write().unwrap_or_else(PoisonError::into_inner);
if let Some((snapshot, value)) = key.as_ref()
&& Arc::ptr_eq(snapshot, &db)
{
return *value;
}
let value = cache_key_for(Some(&db));
*key = Some((db, value));
value
}
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-v2").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.map(f64::to_bits).unwrap_or(0));
}
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.map(f64::to_bits).unwrap_or(0)).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`. `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<EmbeddedLens> {
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());
@@ -165,10 +239,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.and_then(|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 };
@@ -212,6 +303,85 @@ mod tests {
</calibration>
</lens></lensdatabase>"#;
#[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");
let first = cache_key();
let file = PathBuf::from(std::env::var_os(ENV).unwrap()).join("lens.xml");
std::fs::write(&file, DB.replace("-0.03", "-0.05")).unwrap();
assert_eq!(cache_key(), first, "files alone do not mutate the loaded snapshot");
replaced();
let replacement = cache_key();
assert_ne!(replacement, first, "a runtime replacement invalidates the fitted look");
assert_eq!(cache_key_for(Some(&loaded)), first, "the previous snapshot stays immutable");
std::fs::write(&file, DB).unwrap();
reload();
assert_eq!(cache_key(), first, "identical semantic data restores the same identity");
std::fs::remove_file(&file).unwrap();
reload();
assert_eq!(cache_key(), 0, "removing the database restores the no-database identity");
}
#[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("<camera>", "\n <camera> ")).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()),
@@ -235,6 +405,41 @@ mod tests {
assert!(line.contains("no lenses") && line.contains("downloaded") && line.contains("lenses 0, cameras"), "{line}");
}
#[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();
+2 -1
View File
@@ -1,12 +1,13 @@
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
/// 88: use eligible external lens profiles for camera-preview colour alignment (#2675).
/// 87: a lens database's vignetting correction reaches the look fit only in the share the camera JPEG shows
/// (#3943, which had reserved 83: taken after 86, so a later bump counting up from here can't meet an older cache).
/// 86: pushed shadows keep the camera profile's colour and tone (#2092).
/// 85: raw decoding keeps negative channels (#2278).
/// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328).
pub const RENDER_CACHE_VERSION: u64 = 87;
pub const RENDER_CACHE_VERSION: u64 = 88;
/// 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];
+73 -14
View File
@@ -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
@@ -157,6 +160,12 @@ fn stored_facts(head: &serde_json::Value, bytes: &[u8]) -> Option<(SmartFacts, M
/// Encode a source image and its decoder facts (the camera tone curve and the [`SourceInfo`] the
/// render interprets settings against, if given) as a smart preview.
pub fn encode(img: &Rgb32f, info: Option<&SourceInfo>) -> Result<Vec<u8>, String> {
encode_with_lens_key(img, info, crate::lens_profiles::cache_key())
}
/// Encode pixels with the database identity captured by their producer, rather than a later
/// database that may have replaced it while the image was decoded or encoded.
pub(crate) fn encode_with_lens_key(img: &Rgb32f, info: Option<&SourceInfo>, lens_key: u64) -> Result<Vec<u8>, String> {
// scale so all but the brightest 0.05 % fit into 0..1
let mut lum: Vec<f32> = img.data.iter().map(|c| c[0].max(c[1]).max(c[2])).filter(|v| v.is_finite()).collect();
let scale = if lum.is_empty() {
@@ -189,6 +198,7 @@ pub fn encode(img: &Rgb32f, info: Option<&SourceInfo>) -> Result<Vec<u8>, String
"h": img.height,
"scale": scale,
LOOK_FIELD: crate::camera_preview::LOOK_VERSION,
LENS_FIELD: lens_key,
ENC_FIELD: ENCODE_VERSION,
SOURCE_FIELD: SOURCE_VERSION,
});
@@ -472,7 +482,8 @@ fn complete_header(path: &Path) -> Option<serde_json::Value> {
/// 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 {
@@ -487,9 +498,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::<serde_json::Value>(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::<serde_json::Value>(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.
@@ -523,9 +546,12 @@ pub fn source_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";
/// A proxy was written with another LensDB after the recorded folder scan.
const LOOK_PENDING: &str = "look-scan-pending";
/// The marker file in a smart previews folder: the [`SOURCE_VERSION`] its raws' proxies were last checked at.
const SOURCE_MARKER: &str = "source-version";
@@ -543,21 +569,29 @@ fn marker(dir: &Path, name: &str) -> Vec<u64> {
/// Record `versions` in the marker `name` in `dir`, each kept at the one recorded there if that is newer (a newer
/// build checked the folder: no version in a marker goes back); versions after them that it records stay too.
fn mark(dir: &Path, name: &str, versions: &[u64]) -> Result<(), String> {
fn mark(dir: &Path, name: &str, versions: &[u64], lens_key: Option<u64>) -> Result<(), String> {
let old = marker(dir, name);
let kept = versions.iter().enumerate().map(|(i, &v)| old.get(i).map_or(v, |&o| o.max(v))).chain(old.iter().skip(versions.len()).copied());
// The lens key identifies the decoder that did the scan; it is not an ordered version.
// Keep a newer build's identity with its versions, even when our scan advances one of them.
let lens_key = lens_key.filter(|_| !old.iter().zip(versions).any(|(old, current)| old > current));
let tail = old.iter().skip(versions.len() + usize::from(lens_key.is_some())).copied();
let kept = versions.iter().enumerate().map(|(i, &v)| old.get(i).map_or(v, |&o| o.max(v))).chain(lens_key).chain(tail);
let text = kept.map(|v| v.to_string()).collect::<Vec<_>>().join(" ");
let path = dir.join(name);
lightcraft_catalog::safe_file::write_atomic(&path, format!("{text}\n").as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
}
/// 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.
/// camera-look fit version and encode version (or newer ones), and at the loaded lens database
/// identity. A proxy written with a different database after the scan also forces another scan.
pub fn look_checked(dir: &Path) -> bool {
matches!(marker(dir, LOOK_MARKER)[..], [look, enc, ..] if look >= u64::from(crate::camera_preview::LOOK_VERSION) && enc >= ENCODE_VERSION)
!dir.join(LOOK_PENDING).try_exists().unwrap_or(true) && marker_is_current(&marker(dir, LOOK_MARKER), crate::lens_profiles::cache_key())
}
fn marker_is_current(versions: &[u64], lens_key: u64) -> bool {
let [look, enc, ..] = *versions else { return false };
let current_fit = u64::from(crate::camera_preview::LOOK_VERSION);
look >= current_fit && enc >= ENCODE_VERSION && versions.get(2) == Some(&lens_key)
}
/// Whether the smart previews folder `dir` has been checked for raws' proxies from an older raw decode at this
@@ -569,12 +603,37 @@ pub fn source_checked(dir: &Path) -> bool {
/// Record that the proxies in `dir` were checked at this build's camera-look fit version and encode
/// version (newer ones recorded stay).
pub fn mark_look_checked(dir: &Path) -> Result<(), String> {
mark(dir, LOOK_MARKER, &[u64::from(crate::camera_preview::LOOK_VERSION), ENCODE_VERSION])
mark_look_checked_with_lens_key(dir, crate::lens_profiles::cache_key())
}
/// Stamp the identity captured before scanning, so a later database is never marked checked.
pub(crate) fn mark_look_checked_with_lens_key(dir: &Path, lens_key: u64) -> Result<(), String> {
mark(dir, LOOK_MARKER, &[u64::from(crate::camera_preview::LOOK_VERSION), ENCODE_VERSION], Some(lens_key))?;
if marker_is_current(&marker(dir, LOOK_MARKER), lens_key) {
let pending = dir.join(LOOK_PENDING);
match std::fs::remove_file(&pending) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("{}: {e}", pending.display())),
}
}
Ok(())
}
/// Invalidate an earlier LensDB scan before replacing a proxy, under the preview writer's lock.
/// Keep the recorded versions and identity for newer builds. Only a stable scan can clear the flag.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn invalidate_look_check_for_write(dir: &Path, lens_key: u64) -> Result<(), String> {
let pending = dir.join(LOOK_PENDING);
if !pending.exists() && marker(dir, LOOK_MARKER).get(2) != Some(&lens_key) {
lightcraft_catalog::safe_file::write_atomic(&pending, b"").map_err(|e| format!("{}: {e}", pending.display()))?;
}
Ok(())
}
/// Record that the raws' proxies in `dir` were checked at this build's [`SOURCE_VERSION`] (a newer one recorded stays).
pub fn mark_source_checked(dir: &Path) -> Result<(), String> {
mark(dir, SOURCE_MARKER, &[u64::from(SOURCE_VERSION)])
mark(dir, SOURCE_MARKER, &[u64::from(SOURCE_VERSION)], None)
}
/// Load the proxy at `path`.
+106 -9
View File
@@ -344,15 +344,19 @@ fn a_proxy_from_the_previous_look_version_is_stale() {
let path = dir.join("p.lcsp");
std::fs::write(&path, &bytes).unwrap();
assert!(!is_stale(&path), "this build's own proxy is up to date");
// a proxy fitted at the previous look version, with no profile for the camera, is rebuilt
let mut older = head.as_object().cloned().unwrap_or_default();
older.insert(LOOK_FIELD.to_owned(), serde_json::json!(13));
let mut old = MAGIC.to_vec();
old.extend_from_slice(serde_json::Value::Object(older).to_string().as_bytes());
old.extend_from_slice(&bytes[nl..]);
std::fs::write(&path, &old).unwrap();
assert!(is_valid(&path), "the previous look version keeps the file readable");
assert!(is_stale(&path), "a proxy from the previous look version is rebuilt");
// Both the pre-Nikon look and the previous integration's look remain readable offline
// and are rebuilt when the original is available. Keep the lens provenance current.
for version in [13, 14] {
let mut older = head.clone();
older[LOOK_FIELD] = serde_json::json!(version);
let mut old = MAGIC.to_vec();
old.extend_from_slice(older.to_string().as_bytes());
old.extend_from_slice(&bytes[nl..]);
std::fs::write(&path, &old).unwrap();
assert!(is_valid(&path), "look {version} remains readable");
assert!(is_stale(&path), "look {version} is rebuilt");
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
@@ -384,3 +388,96 @@ 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(&[fit, ENCODE_VERSION, 123], next_db), "the folder must be scanned again");
}
assert!(marker_is_current(&[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(&[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(&[fit + 1, ENCODE_VERSION, 456], 123));
assert!(marker_is_current(&[fit + 1, ENCODE_VERSION, 456], 456));
assert!(!marker_is_current(&[fit, ENCODE_VERSION + 1, 456], 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!(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 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);
}
#[test]
fn explicit_lens_identity_is_kept_by_encoder_and_scan_marker() {
let dir = temp("captured-lens");
let image = Rgb32f::new(16, 16);
let captured = crate::lens_profiles::cache_key().wrapping_add(1);
let bytes = encode_with_lens_key(&image, None, captured).unwrap();
let start = MAGIC.len();
let end = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap();
let head: serde_json::Value = serde_json::from_slice(&bytes[start..end]).unwrap();
assert_eq!(head[LENS_FIELD], serde_json::json!(captured), "encoding must not read a later identity");
mark_look_checked_with_lens_key(&dir, captured).unwrap();
assert!(marker_is_current(&marker(&dir, LOOK_MARKER), captured));
assert!(!look_checked(&dir), "a captured older identity does not mark the current database checked");
let future_fit = u64::from(crate::camera_preview::LOOK_VERSION) + 1;
std::fs::write(dir.join(LOOK_MARKER), format!("{future_fit} {ENCODE_VERSION} 42 99\n")).unwrap();
mark_look_checked_with_lens_key(&dir, captured).unwrap();
assert_eq!(marker(&dir, LOOK_MARKER), [future_fit, ENCODE_VERSION, 42, 99]);
assert!(!look_checked(&dir), "a newer version cannot cover the current lens identity");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() {
let dir = temp("lens-marker-pending");
let fit = u64::from(crate::camera_preview::LOOK_VERSION);
let key = crate::lens_profiles::cache_key();
let other_key = key.wrapping_add(1);
std::fs::write(dir.join(LOOK_MARKER), format!("{} {ENCODE_VERSION} {key} 71", fit + 1)).unwrap();
assert!(look_checked(&dir));
invalidate_look_check_for_write(&dir, other_key).unwrap();
mark_look_checked_with_lens_key(&dir, other_key).unwrap();
assert_eq!(marker(&dir, LOOK_MARKER), [fit + 1, ENCODE_VERSION, key, 71]);
assert!(!look_checked(&dir), "newer provenance for this key cannot cover a later write under a different key");
mark_look_checked_with_lens_key(&dir, key).unwrap();
assert!(look_checked(&dir), "a stable scan with the recorded key clears pending");
std::fs::remove_dir_all(dir).unwrap();
}
+7 -3
View File
@@ -86,6 +86,9 @@ fn model_files(dir: &Path, id: &str) -> PathBuf {
fn model_installation_keeps_the_frame_pump_responsive_and_reuses_the_loaded_model() {
use std::sync::{Mutex, mpsc};
use std::time::Duration;
// How long either side waits for the other: an upper bound only (a passing run takes milliseconds), long
// enough for the install thread to be scheduled on a machine running every test binary at once (#4502)
const WAIT: Duration = Duration::from_secs(30);
let mut x = setup("background-install", false);
let path = model_files(&x.dir, "stand-in");
let (entered_tx, entered_rx) = mpsc::channel();
@@ -97,7 +100,7 @@ fn model_installation_keeps_the_frame_pump_responsive_and_reuses_the_loaded_mode
x.s.denoise.loader = Arc::new(move |_, _| {
worker_loads.fetch_add(1, Ordering::Relaxed);
entered_tx.send(()).map_err(|e| e.to_string())?;
release_rx.lock().unwrap().recv_timeout(Duration::from_secs(3)).map_err(|e| e.to_string())?;
release_rx.lock().unwrap().recv_timeout(WAIT).map_err(|e| e.to_string())?;
Ok(Arc::new(Dim { runs: runs.clone() }))
});
let info = x.s.execute("denoise.models.inspect", &json!({"path": path})).unwrap();
@@ -105,7 +108,7 @@ fn model_installation_keeps_the_frame_pump_responsive_and_reuses_the_loaded_mode
assert_eq!(loads.load(Ordering::Relaxed), 0, "showing terms never executes the model");
let r = x.s.execute("denoise.models.install", &json!({"path": path, "acknowledged": true, "background": true})).unwrap();
assert_eq!(r["started"], "local-install");
entered_rx.recv_timeout(Duration::from_secs(3)).unwrap();
entered_rx.recv_timeout(WAIT).unwrap();
// The loader is blocked: the frame pump must still return, reporting installation in progress.
let state = x.s.execute("denoise.models.downloads", &json!({})).unwrap();
assert_eq!(state["downloads"][0]["state"], "installing");
@@ -113,7 +116,8 @@ fn model_installation_keeps_the_frame_pump_responsive_and_reuses_the_loaded_mode
assert_eq!(x.s.execute("denoise.status", &json!({})).unwrap()["model"]["id"], "builtin");
assert!(x.s.execute("denoise.models.install", &json!({"path": path, "acknowledged": true, "background": true})).is_err());
release_tx.send(()).unwrap();
for _ in 0..600 {
let deadline = std::time::Instant::now() + WAIT;
while std::time::Instant::now() < deadline {
let v = x.s.execute("denoise.models.downloads", &json!({})).unwrap();
if v["downloads"][0]["state"] == "installed" {
break;
+13 -3
View File
@@ -3257,7 +3257,13 @@ fn a_stale_refresh_never_rebuilds_a_proxy_from_itself() {
let pixels = lightcraft_raster::Rgb32f::from_fn(48, 32, |x, y| [0.02 + (x % 9) as f32 * 0.05, 0.03 + (y % 7) as f32 * 0.04, 0.06]);
let info = lightcraft_pipeline::SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 6.0, ..Default::default() };
let (p, i) = (pixels.clone(), info.clone());
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone()))));
s.media.file_loader = Some(std::sync::Arc::new(move |path, _max_edge, _| {
// Like the production loader, this fixture cannot decode an offline original.
if !std::path::Path::new(path).is_file() {
return Err("original is offline".into());
}
Ok((p.clone(), i.clone()))
}));
s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap();
let id = s.active().unwrap();
// a raw that takes the per-file camera look, so an older fit makes its proxy stale
@@ -3573,6 +3579,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),
@@ -3584,8 +3591,11 @@ 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!(" {} {}\n", cur + 1, enc + 1), 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), false),
(format!(" {} {} {lens}\n", cur + 1, enc + 1), true),
] {
std::fs::write(dir.join("look-version"), &text).unwrap();
assert_eq!(crate::smart::look_checked(&dir), checked, "{text:?}");
+38 -4
View File
@@ -328,6 +328,19 @@ impl Drop for Tracked {
}
}
/// Whether an uncaptured error on the renderer's device stops the GPU renderer. The renderer's own
/// work runs inside error scopes, so on the window's device ([`Gpu::adopt`]) an uncaptured
/// `Surface::configure` error is the window's swapchain. One of them passes: a resize or a desktop
/// switch can time out waiting for the GPU to come idle (wgpu-core's `GpuWaitTimeout`) with the
/// device fine, and eframe configures it again. That is logged, not a reason to render on the CPU for
/// the rest of the session (#4029). Every other configure error (a format, usage or size the surface
/// can't take) fails the same way again, so it stops the renderer as before; a device that is really
/// gone is reported by the device-lost callback.
pub(crate) fn stops_renderer(window: bool, error: &str) -> bool {
const GPU_WAIT_TIMEOUT: &str = "Failed to wait for GPU to come idle before reconfiguring the Surface";
!(window && error.contains("Surface::configure") && error.contains(GPU_WAIT_TIMEOUT))
}
#[cfg(test)]
thread_local! {
/// Polls on this thread panic as wgpu's do once a Vulkan or DX12 device is lost (#1858).
@@ -531,10 +544,16 @@ impl Gpu {
// Only a device the renderer keeps gets these: a window's device declined above keeps the
// window's own handler, so a later error of the window's can't stop the renderer's device
// (review of PR #1065).
// Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU.
device.on_uncaptured_error(std::sync::Arc::new(|e| {
log::error!("gpu: {e}");
crate::mark_broken(&format!("device error: {e}"));
// Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU,
// unless it is the window's own surface failing on the window's device (#4029).
device.on_uncaptured_error(std::sync::Arc::new(move |e| {
let text = e.to_string();
if stops_renderer(window, &text) {
log::error!("gpu: {text}");
crate::mark_broken(&format!("device error: {text}"));
} else {
log::warn!("gpu: the window's surface: {text}");
}
}));
// wgpu reports a lost device (driver reset, GPU hang, watchdog) only here — never as an
// error — so without this callback a lost device went unnoticed.
@@ -1158,6 +1177,21 @@ pub fn groups1(n: usize) -> [u32; 3] {
#[cfg(test)]
mod tests {
/// #4029: on the window's device, the window's surface failing to configure is logged, not a reason to stop
/// the GPU renderer; any other uncaptured error still stops it, and on a device of the renderer's own every one does.
#[test]
fn only_the_window_surface_failing_leaves_the_renderer_on_the_gpu() {
let surface =
"Validation Error\n\nCaused by:\n In Surface::configure\n Failed to wait for GPU to come idle before reconfiguring the Surface";
assert!(!super::stops_renderer(true, surface), "the window's surface on the window's device");
assert!(super::stops_renderer(false, surface), "on a device of the renderer's own every error counts");
let other = "Validation Error\n\nCaused by:\n In Queue::submit\n Buffer is destroyed";
assert!(super::stops_renderer(true, other), "anything else on the window's device still stops it");
// a configure error that retrying the same configuration can't mend still stops it (review of #4032)
let format = "Validation Error\n\nCaused by:\n In Surface::configure\n Requested format Rgba16Float is not in list of supported formats: [Bgra8Unorm]";
assert!(super::stops_renderer(true, format), "an unsupported format is not passed over");
}
/// Every kernel module, as it is handed to the device (the generated constants, the bindings, `common.wgsl`, the
/// module), parses and validates without a GPU.
#[test]
+29
View File
@@ -602,3 +602,32 @@ fn render_and_screenshot_pngs_go_through_a_private_folder() {
folders.push(dir);
}
}
/// Issue #4496: the Gemini API takes only string `enum`s in a tool's parameters and refuses the whole tool list
/// (400) for one integer enum, so no helper tool declares one.
#[test]
fn every_enum_in_the_helper_tools_is_a_list_of_strings() {
fn check(at: &str, v: &Value, bad: &mut Vec<String>) {
match v {
Value::Object(m) => {
if let Some(e) = m.get("enum")
&& !e.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(Value::is_string))
{
bad.push(format!("{at}: {e}"));
}
for (k, x) in m {
check(&format!("{at}.{k}"), x, bad);
}
}
Value::Array(a) => a.iter().enumerate().for_each(|(i, x)| check(&format!("{at}[{i}]"), x, bad)),
_ => {}
}
}
let mut bad = Vec::new();
for has_ui in [false, true] {
for t in crate::tools::helper_tools(has_ui) {
check(t["name"].as_str().unwrap_or("?"), &t["inputSchema"], &mut bad);
}
}
assert!(bad.is_empty(), "non-string enums: {bad:?}");
}
+2 -1
View File
@@ -263,7 +263,8 @@ pub fn helper_tools(has_ui: bool) -> Vec<Value> {
"metadata": {"type": "string", "enum": ["all", "allExceptCamera", "copyright", "none"]},
"removeLocation": {"type": "boolean"},
"colorSpace": {"type": "string", "enum": ["srgb", "displayP3", "adobeRgb", "proPhoto", "rec2020"], "description": "Output colour space (default sRGB; AVIF is always sRGB; lossy JPEG XL writes adobeRgb/proPhoto as rec2020). adobeRgb = Adobe RGB (1998) compatible; the embedded ICC profile is generated from the published primaries"},
"bitDepth": {"type": "integer", "enum": [8, 10, 16, 32], "description": "Bits per channel: PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"},
// the values in words, not an `enum`: the Gemini API refuses a tool list with a non-string enum (issue #4496)
"bitDepth": {"type": "integer", "description": "Bits per channel (8, 10, 16 or 32): PNG 8|16 (default 8), TIFF 8|16|32 (default 16; 32 = linear float with a linear profile), PSD 8|16 (default 16), AVIF 8|10, JPEG XL 8|16; JPEG/WebP are 8-bit"},
"hdr": {"type": "boolean", "description": "HDR output for photos edited in HDR (develop.hdr): JPEG as an ISO 21496-1 gain map JPEG, AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ, 32-bit TIFF with highlights above 1; other formats and SDR edits export as usual"},
"hdrTransfer": {"type": "string", "enum": ["pq", "hlg"], "description": "Transfer curve of HDR AVIF output (default pq): pq = SMPTE ST 2084, hlg = ITU-R BT.2100 hybrid log-gamma"},
"addToPhotos": {"type": "boolean", "description": "macOS: after writing the files, add them to Apple Photos (Apple Events to Photos' import; the first time, macOS asks the user to allow LightCraft to control Photos). The outcome is `applePhotos` in the result, the import job: {job, running, requested, album, imported?, ids?, warning?, error?}; headless waits for Photos, the desktop app returns the running job (outcome: command export.photosImports {job}). The files are written either way. An error before exporting on other platforms, or while another import is reserved or running"},
+20 -2
View File
@@ -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<ColorData> + 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]
+32 -19
View File
@@ -25,8 +25,8 @@ use export::{
};
pub use frame::{ConfirmStyle, confirm_style, list_height, prompt};
use frame::{
DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, choice_grid, choices, clicked_backdrop, dialog_body, dialog_field, field,
just_opened, num, only_shows, return_confirms, trailing_button_row,
DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, choice_combo, choice_grid, choice_menu, choices, clicked_backdrop, dialog_body,
dialog_field, field, just_opened, num, only_shows, return_confirms, trailing_button_row,
};
pub(crate) use rename::rename_preview;
use rename::{RENAME_PREVIEW_ROWS, person_rename_plan};
@@ -1403,9 +1403,15 @@ fn contact_sheet_summary(n: usize, pages: usize) -> String {
crate::i18n::tr_format!("{n} selected photo{} · {pages} page{}", crate::i18n::plural_s(n), crate::i18n::plural_s(pages), n = n, pages = pages)
}
/// The width of the Export dialog's options.
const EXPORT_BODY_W: f32 = 581.0;
/// The body of the Export dialog.
fn export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
let Dialog::Export { opts, full_size, resize, preset_name, limit_kb, dir } = dlg else { return };
// as wide as when Format was a row of buttons: its dropdowns would leave the sliders, the
// watermark preview and the folder path narrow
ui.set_min_width(EXPORT_BODY_W);
let n = app.session.selection.ids.len().max(1);
ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim));
export_preset_row(app, ui, opts, full_size, resize, limit_kb);
@@ -1472,20 +1478,20 @@ fn export_format_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions) {
let before = opts.format;
// "Rendered DNG" is a DNG option (below), not a format of its own in this list
let mut shown = if opts.format == F::RenderedDng { F::Dng } else { opts.format };
choices(
choice_menu(
ui,
"Format",
"exportFormat",
&[
(F::Jpeg, "JPEG"),
(F::Png, "PNG"),
(F::Tiff, "TIFF"),
(F::Psd, "PSD"),
(F::Webp, "WebP"),
(F::Avif, "AVIF"),
(F::Jxl, "JPEG XL"),
(F::Dng, "DNG"),
(F::Original, "Original files"),
(F::Jpeg, "JPEG", "jpeg"),
(F::Png, "PNG", "png"),
(F::Tiff, "TIFF", "tiff"),
(F::Psd, "PSD", "psd"),
(F::Webp, "WebP", "webp"),
(F::Avif, "AVIF", "avif"),
(F::Jxl, "JPEG XL", "jxl"),
(F::Dng, "DNG", "dng"),
(F::Original, "Original files", "original"),
],
&mut shown,
);
@@ -1550,11 +1556,17 @@ fn export_color_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOptions) {
ui.label(egui::RichText::new(crate::i18n::tr("Color space: sRGB (AVIF)")).color(t.text_dim));
} else {
use lightcraft_engine::export::OutputSpace as C;
choices(
choice_combo(
ui,
"Color space",
"exportColorSpace",
&[(C::Srgb, "sRGB"), (C::DisplayP3, "P3"), (C::AdobeRgb, "Adobe RGB"), (C::ProPhoto, "ProPhoto"), (C::Rec2020, "Rec.2020")],
&[
(C::Srgb, "sRGB", "srgb"),
(C::DisplayP3, "P3", "p3"),
(C::AdobeRgb, "Adobe RGB", "adobeRgb"),
(C::ProPhoto, "ProPhoto", "proPhoto"),
(C::Rec2020, "Rec.2020", "rec2020"),
],
&mut opts.color_space,
);
if opts.effective_space() != opts.color_space {
@@ -1594,21 +1606,22 @@ fn export_quality_rows(ui: &mut egui::Ui, opts: &mut ExportOptions, limit_kb: &m
/// Export dialog: sharpening, metadata and the watermark of a rendered photo.
fn export_output_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut ExportOptions, full_size: bool, resize: Resize) {
use lightcraft_engine::export::{MetadataPolicy as M, SharpenAmount as A, SharpenFor as S};
choices(
choice_combo(
ui,
"Sharpen",
"exportSharpen",
&[(S::None, "None"), (S::Screen, "Screen"), (S::Matte, "Matte"), (S::Glossy, "Glossy")],
&[(S::None, "None", "none"), (S::Screen, "Screen", "screen"), (S::Matte, "Matte", "matte"), (S::Glossy, "Glossy", "glossy")],
&mut opts.sharpen,
);
if opts.sharpen != S::None {
choices(ui, "Amount", "exportSharpenAmount", &[(A::Low, "Low"), (A::Standard, "Standard"), (A::High, "High")], &mut opts.sharpen_amount);
let amounts = [(A::Low, "Low", "low"), (A::Standard, "Standard", "standard"), (A::High, "High", "high")];
choice_menu(ui, "Amount", "exportSharpenAmount", &amounts, &mut opts.sharpen_amount);
}
choices(
choice_menu(
ui,
"Metadata",
"exportMetadata",
&[(M::All, "All"), (M::AllExceptCamera, "No camera"), (M::Copyright, "Copyright"), (M::None, "None")],
&[(M::All, "All", "all"), (M::AllExceptCamera, "No camera", "noCamera"), (M::Copyright, "Copyright", "copyright"), (M::None, "None", "none")],
&mut opts.metadata,
);
if !matches!(opts.metadata, M::None | M::Copyright) {
+22 -32
View File
@@ -1,4 +1,4 @@
use super::frame::{field, num};
use super::frame::{choice_combo, num};
use super::{ControlSpec, LightcraftApp, Section, SettingsGroup, Tokens, Track};
/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever
@@ -220,42 +220,32 @@ const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240
/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi.
pub(super) fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) {
use lightcraft_engine::export::ResizeMode as R;
const MODES: [(R, &str); 8] = [
(R::LongEdge, "Long Edge"),
(R::ShortEdge, "Short Edge"),
(R::Width, "Width"),
(R::Height, "Height"),
(R::WidthHeight, "Width & Height"),
(R::Dimensions, "Dimensions"),
(R::Megapixels, "Megapixels"),
(R::Percent, "Percentage"),
const MODES: [(R, &str, &str); 8] = [
(R::LongEdge, "Long Edge", "longEdge"),
(R::ShortEdge, "Short Edge", "shortEdge"),
(R::Width, "Width", "width"),
(R::Height, "Height", "height"),
(R::WidthHeight, "Width & Height", "widthHeight"),
(R::Dimensions, "Dimensions", "dimensions"),
(R::Megapixels, "Megapixels", "megapixels"),
(R::Percent, "Percentage", "percent"),
];
let r_full = ui.checkbox(full, crate::i18n::tr("Full size"));
crate::widgets::register(ui, "check:exportFullSize", r_full.rect);
if !*full {
field(ui, "Resize to", |ui| {
let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1);
let before = r.mode;
let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {
for (m, l) in MODES {
ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l));
}
});
crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize"));
crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect);
if r.mode != before {
// a sensible value for the new unit
r.value = match r.mode {
R::Megapixels => 12.0,
R::Percent => 50.0,
_ if matches!(before, R::Megapixels | R::Percent) => 2048.0,
_ => r.value,
};
if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 {
r.height = r.value as u32;
}
let before = r.mode;
if choice_combo(ui, "Resize to", "exportResizeMode", &MODES, &mut r.mode) {
// a sensible value for the new unit
r.value = match r.mode {
R::Megapixels => 12.0,
R::Percent => 50.0,
_ if matches!(before, R::Megapixels | R::Percent) => 2048.0,
_ => r.value,
};
if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 {
r.height = r.value as u32;
}
});
}
let mut v = r.value as f64;
let spec = match r.mode {
R::Megapixels => &SIZE_MP,
+40
View File
@@ -146,6 +146,46 @@ pub(super) fn choices<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &
});
}
/// A labelled row with a borderless dropdown ([`crate::widgets::menu_dropdown`]) for one of
/// `options` (value, label, key): `dropdown:{id}`, items `{id}:{key}`.
pub(super) fn choice_menu<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str, &str)], value: &mut V) {
field(ui, label, |ui| {
if let Some(v) = crate::widgets::menu_dropdown(ui, id, label, "", options, *value) {
*value = v;
}
});
}
/// A labelled row with a boxed dropdown (as Resize to has) for one of `options` (value, label,
/// key): `combo:{id}`, items `{id}:{key}`. True when the value changed.
pub(super) fn choice_combo<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str, &str)], value: &mut V) -> bool {
let before = *value;
field(ui, label, |ui| {
let shown = options.iter().find(|o| o.0 == *value).or(options.first()).map_or("", |o| crate::i18n::tr(o.1));
let mut picked = false;
let c = crate::widgets::combo_box(id).width(150.0).selected_text(shown).show_ui(ui, |ui| {
for (v, l, key) in options {
let item = ui.selectable_label(*value == *v, crate::i18n::tr(l));
crate::widgets::register(ui, format!("{id}:{key}"), item.rect);
if item.clicked() {
*value = *v;
picked = true;
ui.close();
}
}
});
if picked {
// as `widgets::picked`: the menu closed, the focus goes back to the combo box
c.response.request_focus();
}
crate::widgets::name_combo(&c.response, crate::i18n::tr(label));
let open = craft_ui::ComboBox::is_open(ui.ctx(), c.response.id);
ui.ctx().accesskit_node_builder(c.response.id, |node| node.set_expanded(open));
crate::widgets::register(ui, format!("combo:{id}"), c.response.rect);
});
*value != before
}
/// [`choices`] laid out as a grid of `cols` columns, row by row (ids `button:{id}-{index}`).
pub(super) fn choice_grid<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], cols: usize, value: &mut V) {
field(ui, label, |ui| {
+12
View File
@@ -877,6 +877,18 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>>
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| {
+53
View File
@@ -358,6 +358,59 @@ 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);
}
/// #3311: an exact-rating row is labelled apart from the "and higher" row for the same stars, through
/// the translatable "{} only" key (its translations follow in storytold/craft-i18n).
#[test]
fn select_by_exact_rating_rows_are_labelled_apart_from_and_higher() {
fn label_of(nodes: &[MenuNode], want: &serde_json::Value) -> Option<String> {
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();
let bar = menu_bar(&app);
let edit = &bar.iter().find(|(t, _)| t == "Edit").unwrap().1;
let only = label_of(edit, &json!({"rating": 3, "ratingOp": "eq"})).expect("the three-star-only row");
let higher = label_of(edit, &json!({"rating": 3})).expect("the three-star-and-higher row");
assert_eq!(only, crate::i18n::tr_format!("{} only", "★★★"));
assert_ne!(only, higher);
}
#[test]
fn help_opens_the_docs_and_merge_last_needs_photos() {
let mut app = app();
+9 -2
View File
@@ -47,7 +47,7 @@ pub(super) fn crop_overlay(
};
let quad = frame_crop_quad(d, frame);
let pts: Vec<Pos2> = quad.iter().map(|q| map.screen(*q)).collect();
let p = ui.painter();
let p = loupe_painter(app, ui);
// darken outside the crop (the box's corners in screen order: a flipped photo shows its
// top-left corner elsewhere)
let quad = flipped_corners(&pts, frame.flip_h, frame.flip_v);
@@ -272,6 +272,13 @@ pub(crate) fn readout_rect(at: Pos2, size: egui::Vec2, bounds: Rect) -> Rect {
}
/// On top of everything (the tooltip layer), so neither the photo nor a panel covers it.
/// A painter clipped to the loupe: zoomed in, the crop box reaches past it, and the filmstrip
/// below shares this `ui` (#3966: the box and its handles were painted over the filmstrip).
fn loupe_painter(app: &LightcraftApp, ui: &egui::Ui) -> egui::Painter {
let clip = app.canvas_rect.map_or(ui.clip_rect(), |c| c.intersect(ui.clip_rect()));
ui.painter().with_clip_rect(clip)
}
fn top_painter(ui: &egui::Ui, name: &'static str) -> egui::Painter {
ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique(name)))
}
@@ -569,7 +576,7 @@ fn straighten_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::R
}
let Some(Gesture::StraightenLine { a }) = app.gesture.clone() else { return };
let Some(b) = resp.interact_pointer_pos().or(resp.hover_pos()) else { return };
let p = ui.painter();
let p = loupe_painter(app, ui);
p.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140)));
p.line_segment([a, b], Stroke::new(1.5, Color32::WHITE));
if resp.drag_stopped() {
+45 -2
View File
@@ -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<Vec<String>> {
use crate::state::InfoOverlay;
@@ -533,6 +544,38 @@ 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}");
// 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");
}
/// #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() {
+10
View File
@@ -99,6 +99,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,
@@ -125,6 +131,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}));
+15 -7
View File
@@ -578,7 +578,7 @@ fn fire_command(app: &mut LightcraftApp, ctx: &egui::Context, f: &str, rotate_fi
let _ = app.run(if f == "library.next" { "slideshow.next" } else { "slideshow.previous" }, json!({}));
return;
}
if fire_rating_key(app, ctx, f) || fire_grid_key(app, f) || fire_flag_key(app, ctx, f) {
if fire_rating_key(app, ctx, f) || fire_grid_key(app, ctx, f) || fire_flag_key(app, ctx, f) {
return;
}
// in the full-screen preview (no panels) I cycles the info overlay instead
@@ -631,7 +631,7 @@ fn fire_rating_key(app: &mut LightcraftApp, ctx: &egui::Context, f: &str) -> boo
}
/// The keys of a grid or of Compare / Survey that move the active photo or the selection; whether `f` was one.
fn fire_grid_key(app: &mut LightcraftApp, f: &str) -> bool {
fn fire_grid_key(app: &mut LightcraftApp, ctx: &egui::Context, f: &str) -> bool {
use crate::panels::compare;
if f == "panel.presets" && library_grid(app) {
// Classic's Shift+P picks and advances in Library; keep the Presets binding elsewhere.
@@ -648,8 +648,12 @@ 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::<i64>().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") || (matches!(f, "library.down" | "library.up") && !over_slider(app, ctx)))
{
// ↑ / ↓ 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;
@@ -804,11 +808,15 @@ fn context_key_skipped(app: &mut LightcraftApp, f: &str, rotate_fires: bool) ->
}
}
/// Whether the pointer is over a slider: there the arrows nudge it (`widgets::slider` takes the key), in
/// the grids and in Survey and Compare alike.
fn over_slider(app: &LightcraftApp, ctx: &egui::Context) -> bool {
ctx.pointer_hover_pos().is_some_and(|p| app.widgets.iter().any(|(id, r)| id.starts_with("slider:") && r.contains(p)))
}
/// Up / Down in the grids go to the cell above / below (the filmstrip steps one photo).
fn up_down_key(app: &mut LightcraftApp, ctx: &egui::Context, f: &str) {
// over a slider the arrows nudge it (widgets::slider takes the key)
let over_slider = ctx.pointer_hover_pos().is_some_and(|p| app.widgets.iter().any(|(id, r)| id.starts_with("slider:") && r.contains(p)));
if over_slider {
if over_slider(app, ctx) {
return;
}
match crate::panels::grid::row_distance(app, f == "library.down") {
+1
View File
@@ -49,6 +49,7 @@ mod drop_import;
mod edit_layout;
mod empty_library;
mod error_kinds;
mod export_dropdowns;
mod filmstrip;
mod filmstrip_drag;
mod find_similar;
+84
View File
@@ -633,3 +633,87 @@ fn survey_command_click_on_the_active_photo_activates_the_last_one() {
let sel: Vec<u64> = 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::<Vec<u64>>();
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);
}
/// 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<u64> = 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);
}
/// 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<u64> = 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<_>>(), 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);
}
/// With the pointer over a slider, ↑ / ↓ nudge the slider in Survey and Compare too, and don't step to another
/// photo first: the nudge would then edit a photo the user didn't pick (review of #3648).
#[test]
fn up_and_down_over_a_slider_stay_on_the_photo_in_survey() {
let mut h = demo();
let [_, b, _] = survey_of_three(&mut h);
let active = |h: &Headless| h.app.session.selection.active.map(|p| p.0);
assert_eq!(active(&h), Some(b));
let slider = h.app.widgets.iter().find(|(id, _)| id.starts_with("slider:")).map(|(id, r)| (id.clone(), r.center()));
let Some((id, at)) = slider else { panic!("a slider in Survey: {:?}", h.app.widgets.iter().map(|(w, _)| w).collect::<Vec<_>>()) };
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.settle(SETTLE);
for key in ["down", "up"] {
let r = h.request("ui.key", json!({"key": key}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(SETTLE);
assert_eq!(active(&h), Some(b), "{key} over {id} stays on the photo");
}
}
+34
View File
@@ -95,3 +95,37 @@ fn x_in_the_crop_tool_swaps_the_aspect_once() {
h.settle(SETTLE);
assert_eq!(crop(&h), (true, Some((400, 300))), "X again turns it back");
}
/// Zoomed in, the crop box reaches past the bottom of the loupe: its frame, guides and handles
/// stop at the loupe and are not painted over the filmstrip below it (#3966).
#[test]
fn the_crop_box_is_not_painted_over_the_filmstrip() {
let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() });
let mut h = Headless::new(app, [1400.0, 900.0], 1.0);
let id = h.app.session.visible_cloned()[1];
h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [id.0], "active": id.0}}), T);
h.app.ui.view = ViewMode::Detail;
h.app.ui.filmstrip = true;
let r = h.request("engine.execute", json!({"command": "panel.crop"}), T);
assert_eq!(r["ok"], true, "{r}");
h.app.ui.zoom = crate::state::Zoom::Percent(400.0);
h.app.ui.pan = (0.5, 0.5);
h.settle(SETTLE);
let canvas = h.app.canvas_rect.expect("the loupe is drawn");
assert!(canvas.bottom() < 900.0 - 20.0, "the filmstrip shows below the loupe ({canvas:?})");
// the crop box's frame: a closed white line through its four corners
let white = egui::epaint::ColorMode::Solid(egui::Color32::WHITE);
let frames: Vec<_> = h
.view
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::epaint::Shape::Path(p) if p.closed && p.points.len() == 4 && p.stroke.width == 1.0 && p.stroke.color == white => Some((c, p)),
_ => None,
})
.collect();
assert_eq!(frames.len(), 1, "the crop box is drawn once");
let (c, p) = frames[0];
assert!(p.points.iter().any(|q| q.y > canvas.bottom() + 50.0), "zoomed in, the box reaches past the loupe ({:?}, loupe {canvas:?})", p.points);
assert!(c.clip_rect.bottom() <= canvas.bottom() + 0.5, "the box is clipped to the loupe, not {:?} (loupe {canvas:?})", c.clip_rect);
}
@@ -0,0 +1,113 @@
//! Headless tests of the Export dialog's dropdowns: Format, Amount and Metadata are a borderless
//! dropdown, Color space, Sharpen and Resize to a boxed one, instead of rows of buttons.
use std::time::Duration;
use serde_json::json;
use crate::headless::Headless;
use crate::state::Dialog;
use crate::{LightcraftApp, Services};
use lightcraft_engine::export::{
ExportFormat as F, ExportOptions, MetadataPolicy as M, OutputSpace as C, ResizeMode as R, SharpenAmount as A, SharpenFor as S,
};
const T: Duration = Duration::from_secs(20);
/// The demo library with the Export dialog open.
fn export_dialog() -> Headless {
let services = Services { png: None, ..Default::default() };
let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services);
let mut h = Headless::new(app, [1600.0, 1200.0], 1.0);
let r = h.request("engine.execute", json!({"command": "dialog.export", "params": {}}), T);
assert_eq!(r["ok"], true, "{r}");
if let Some(Dialog::Export { full_size, .. }) = &mut h.app.ui.dialog {
*full_size = false;
}
h.step();
h
}
fn opts(h: &Headless) -> &ExportOptions {
match &h.app.ui.dialog {
Some(Dialog::Export { opts, .. }) => opts,
_ => panic!("the Export dialog is open"),
}
}
fn has_widget(h: &Headless, prefix: &str) -> bool {
h.app.widgets.iter().any(|(id, _)| id.starts_with(prefix))
}
fn click(h: &mut Headless, id: &str) {
let r = h.request("ui.clickWidget", json!({"id": id}), T);
assert_eq!(r["ok"], true, "{id}: {r}");
}
/// Open the dropdown `opener` (`dropdown:{id}` or `combo:{id}`) and choose its item `key`.
fn choose(h: &mut Headless, opener: &str, id: &str, key: &str) {
click(h, &format!("{opener}:{id}"));
h.step();
click(h, &format!("{id}:{key}"));
h.step();
assert!(!has_widget(h, &format!("{id}:{key}")), "{id}: the menu closed");
}
/// Each row is a dropdown, with no row of buttons left, and choosing an item sets the option the
/// button did; Amount shows only while Sharpen is on, as before.
#[test]
fn export_choices_are_dropdowns() {
let mut h = export_dialog();
for (opener, id) in [
("dropdown", "exportFormat"),
("combo", "exportColorSpace"),
("combo", "exportResizeMode"),
("combo", "exportSharpen"),
("dropdown", "exportMetadata"),
] {
assert!(has_widget(&h, &format!("{opener}:{id}")), "{opener}:{id}");
assert!(!has_widget(&h, &format!("button:{id}-")), "no row of {id} buttons");
}
choose(&mut h, "dropdown", "exportFormat", "tiff");
assert_eq!(opts(&h).format, F::Tiff);
choose(&mut h, "combo", "exportColorSpace", "adobeRgb");
assert_eq!(opts(&h).color_space, C::AdobeRgb);
choose(&mut h, "combo", "exportSharpen", "none");
assert_eq!(opts(&h).sharpen, S::None);
assert!(!has_widget(&h, "dropdown:exportSharpenAmount"), "no Amount without sharpening");
choose(&mut h, "combo", "exportSharpen", "matte");
assert_eq!(opts(&h).sharpen, S::Matte);
choose(&mut h, "dropdown", "exportSharpenAmount", "high");
assert_eq!(opts(&h).sharpen_amount, A::High);
choose(&mut h, "dropdown", "exportMetadata", "copyright");
assert_eq!(opts(&h).metadata, M::Copyright);
choose(&mut h, "dropdown", "exportFormat", "original");
assert_eq!(opts(&h).format, F::Original);
assert!(!has_widget(&h, "combo:exportSharpen"), "original files have no output options");
}
/// Rendered DNG is a DNG option, so the Format dropdown says DNG for it, and choosing DNG again
/// keeps the rendered kind.
#[test]
fn rendered_dng_shows_as_dng() {
let mut h = export_dialog();
choose(&mut h, "dropdown", "exportFormat", "dng");
click(&mut h, "button:exportDngKind-1");
h.step();
assert_eq!(opts(&h).format, F::RenderedDng);
choose(&mut h, "dropdown", "exportFormat", "dng");
assert_eq!(opts(&h).format, F::RenderedDng, "DNG again keeps Rendered photo");
}
/// Resize to, now built on the shared boxed dropdown, still gives a new unit a sensible value.
#[test]
fn resize_mode_still_resets_the_value_for_a_new_unit() {
let mut h = export_dialog();
choose(&mut h, "combo", "exportResizeMode", "percent");
let Some(Dialog::Export { resize, .. }) = &h.app.ui.dialog else { panic!("dialog") };
assert_eq!(resize.mode, R::Percent);
assert!(resize.value <= 100.0, "a percentage, not a pixel count: {}", resize.value);
choose(&mut h, "combo", "exportResizeMode", "longEdge");
let Some(Dialog::Export { resize, .. }) = &h.app.ui.dialog else { panic!("dialog") };
assert!(resize.value > 100.0, "back to pixels: {}", resize.value);
}
+3
View File
@@ -173,6 +173,9 @@ fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() {
assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast);
assert_eq!(drive.reads.load(Ordering::SeqCst), 1);
// Frames may decode detail/thumbnail sources independently of search signatures.
// Isolate the signature-cache/read-count check from those decoded pixels.
h.app.session.media.clear_sources();
let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap();
assert_eq!(r["count"], PHOTOS - 1, "what was read isn't read again");
until_done(&mut h);
+33
View File
@@ -357,3 +357,36 @@ fn the_title_bar_handle_stays_below_a_dropdown_open_in_the_dialog() {
assert!(h.app.ui.dialog.is_some(), "and leaves the dialog");
assert!(handle_at(&mut h), "the handle is back");
}
// 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:?}");
}
+39 -21
View File
@@ -1079,33 +1079,51 @@ pub fn dropdown_within(ui: &mut Ui, id: &str, text: &str, font: egui::FontId, co
/// as `{id}:{key}`. Returns the value chosen this frame.
pub fn labeled_dropdown<T: Copy + PartialEq>(ui: &mut Ui, id: &str, label: &str, hint: &str, items: &[(T, &str, &str)], current: T) -> Option<T> {
let t = Tokens::get(ui.ctx());
let active = items.iter().position(|(v, _, _)| *v == current).unwrap_or(0);
let mut chosen = None;
ui.horizontal(|ui| {
let name = crate::i18n::tr(label);
ui.label(egui::RichText::new(name).color(t.text_dim));
let shown = items.get(active).map_or("", |(_, l, _)| crate::i18n::tr(l));
let mut r = dropdown(ui, id, shown, t.font(12.5), t.text_label);
if !hint.is_empty() {
r = r.on_hover_text(crate::i18n::tr(hint));
}
ui.ctx().accesskit_node_builder(r.id, |node| {
node.set_label(name.to_string());
node.set_value(shown.to_string());
});
egui::Popup::menu(&r).show(|ui| {
for (i, (v, l, key)) in items.iter().enumerate() {
let item = ui.selectable_label(i == active, crate::i18n::tr(l));
register(ui, format!("{id}:{key}"), item.rect);
if item.clicked() {
chosen = Some(*v);
}
ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text_dim));
menu_dropdown(ui, id, label, hint, items, current)
})
.inner
}
/// The dropdown of [`labeled_dropdown`] without its label, for a row that draws the label itself
/// (a dialog's label column): screen readers still hear `label` as its name.
pub fn menu_dropdown<T: Copy + PartialEq>(ui: &mut Ui, id: &str, label: &str, hint: &str, items: &[(T, &str, &str)], current: T) -> Option<T> {
let t = Tokens::get(ui.ctx());
let active = items.iter().position(|(v, _, _)| *v == current).unwrap_or(0);
let shown = items.get(active).map_or("", |(_, l, _)| crate::i18n::tr(l));
let mut r = dropdown(ui, id, shown, t.font(12.5), t.text_label);
if !hint.is_empty() {
r = r.on_hover_text(crate::i18n::tr(hint));
}
let mut chosen = None;
egui::Popup::menu(&r).show(|ui| {
for (i, (v, l, key)) in items.iter().enumerate() {
let item = ui.selectable_label(i == active, crate::i18n::tr(l));
register(ui, format!("{id}:{key}"), item.rect);
if item.clicked() {
chosen = Some(*v);
picked(ui, r.id);
}
});
}
});
let open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&r));
ui.ctx().accesskit_node_builder(r.id, |node| {
node.set_label(crate::i18n::tr(label).to_string());
node.set_value(shown.to_string());
node.set_expanded(open);
});
chosen
}
/// After an item of a dropdown's menu is chosen: close the menu and give the focus back to the
/// dropdown `trigger`. egui closes a menu by itself only on a pointer click, so a choice made with
/// Enter or Space would otherwise leave it open, with the focus on an item that is going away.
pub fn picked(ui: &Ui, trigger: egui::Id) {
ui.close();
ui.memory_mut(|m| m.request_focus(trigger));
}
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,84 @@
//! The Export dialog's dropdowns by keyboard: Enter on a menu item chooses it, closes the menu
//! and gives the focus back to the dropdown, and screen readers hear whether its menu is open.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::{Harness, kittest::NodeT};
use lightcraft_engine::export::{ExportFormat, SharpenFor};
use lightcraft_ui_egui::{LightcraftApp, Services, state::Dialog};
fn export_dialog() -> Harness<'static, LightcraftApp> {
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() });
// a headless host never gains the first-run tour: its modal would take the focus under test
app.headless_host = true;
let mut builder = Harness::builder().with_size(vec2(1500.0, 1100.0));
if lightcraft_engine::CRAFT_FONTS.is_empty() {
builder = builder.allow_missing_glyphs();
}
let mut h = builder.build_ui_state(
|ui, app: &mut LightcraftApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h.state_mut().run("dialog.export", serde_json::json!({})).expect("the Export dialog opens");
h.run_steps(6);
h
}
/// The dropdown named `name`: whether its menu is open, and whether it has the focus.
fn dropdown(h: &Harness<'_, LightcraftApp>, name: &str) -> (bool, bool) {
let n = h
.root()
.children_recursive()
.find(|n| n.accesskit_node().role() == Role::ComboBox && n.accesskit_node().label().as_deref() == Some(name))
.unwrap_or_else(|| panic!("no dropdown {name}"));
(n.accesskit_node().data().is_expanded() == Some(true), n.is_focused())
}
/// Whether a node other than a dropdown is named `name` (an item of an open menu).
fn item_shows(h: &Harness<'_, LightcraftApp>, name: &str) -> bool {
h.root().children_recursive().any(|n| n.accesskit_node().role() != Role::ComboBox && n.accesskit_node().label().as_deref() == Some(name))
}
/// Focus the dropdown `name`, open it with Enter, focus its item `item` and choose it with Enter.
fn choose_by_keyboard(h: &mut Harness<'_, LightcraftApp>, name: &str, item: &str) {
h.root()
.children_recursive()
.find(|n| n.accesskit_node().role() == Role::ComboBox && n.accesskit_node().label().as_deref() == Some(name))
.unwrap_or_else(|| panic!("no dropdown {name}"))
.focus();
h.run_steps(2);
assert_eq!(dropdown(h, name), (false, true), "{name}: closed and focused");
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert!(dropdown(h, name).0, "{name}: screen readers hear the open menu as expanded");
h.root()
.children_recursive()
.find(|n| n.accesskit_node().role() != Role::ComboBox && n.accesskit_node().label().as_deref() == Some(item))
.unwrap_or_else(|| panic!("{name}: no menu item {item}"))
.focus();
h.run_steps(2);
h.key_press(egui::Key::Enter);
h.run_steps(4);
assert_eq!(dropdown(h, name), (false, true), "{name}: Enter on {item} closes the menu and the focus is back on the dropdown");
assert!(!item_shows(h, item), "{name}: the menu is gone");
}
fn options(h: &Harness<'_, LightcraftApp>) -> lightcraft_engine::export::ExportOptions {
match &h.state().ui.dialog {
Some(Dialog::Export { opts, .. }) => opts.clone(),
_ => panic!("the Export dialog is open"),
}
}
/// Format (a borderless dropdown) and Sharpen (a boxed one) by keyboard alone.
#[test]
fn export_dropdowns_close_on_a_keyboard_choice() {
let mut h = export_dialog();
choose_by_keyboard(&mut h, "Format", "TIFF");
assert_eq!(options(&h).format, ExportFormat::Tiff);
choose_by_keyboard(&mut h, "Sharpen", "Matte");
assert_eq!(options(&h).sharpen, SharpenFor::Matte);
}
+1
View File
@@ -4,6 +4,7 @@
mod accessibility;
mod dialog_role;
mod docking_workflows;
mod export_dropdown_keys;
mod grid_names;
mod landmarks;
mod local_places;
+37 -1
View File
@@ -2,6 +2,10 @@
ARW, NEF, RW2, RAF, CR3, CR2, CRW, PEF, SRW, ORF, ERF and MRW decoding supply sensor data and camera white-balance multipliers (CRW only on the D60/10D/300D; on the other CRW bodies the fitted matrix absorbs the white balance), but currently no measured camera colour matrix — with one exception: the Canon EOS D60, whose matrices we measured on a ColorChecker (`crates/raw/src/chart_table.rs`). They give a D60 CRW its colour when its JPEG look cannot be fitted, and its white balance in Kelvin (below); an accepted fit still wins. 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
Historical pre-rebase validation on five private Canon PowerShot G7 X Mark II photographs showed that native fixed-mount lookup plus the gated profile/framing correspondence path reproduced the validated local correction. Four full-resolution renders removed the large pink sky regions and substantially reduced skin posterization. Four other RAWs (Sony A7 III, Canon 5D, 6D and 7D) and four JPEGs stayed pixel-identical at 1600 px; without a configured matching profile the tested G7 X II frame stayed unchanged. CPU and Metal differed 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. 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.
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.
@@ -278,6 +288,10 @@ is recorded here yet. Whether they should come before the file-local fit for the
A smart preview keeps the result of the fit twice: the colour matrix is baked into its pixels and the tone and chroma curves are stored in its header. When the fit changes, a preview built earlier keeps the old look until it is rebuilt, and the render cache version does not reach it (renders are keyed on the library's files, proxies are files of their own).
This independent proposal applies directly to upstream main; it requires no prior merge of the separate CR3 proposal #3138. CR3 retains upstream framing and its existing per-file source-position vignetting. The newly added Pool/DNG profile lookup excludes CR3, including a resolved profile that carries both warp and nonzero vignetting.
The synchronized geometry-gated external-profile correspondence fit uses `LOOK_VERSION = 27` and `RENDER_CACHE_VERSION = 88`, after upstream versions 26 and 87, invalidating both stale smart-preview looks and rendered thumbnails. The private-file observations above were recorded on the original proposal.
The fit therefore has a version, `LOOK_VERSION` in `crates/engine/src/camera_preview.rs`, and every smart preview records the version that wrote it in its header line (`look_version`). **Bump the constant in any change that makes the fit give a different result for the same file**: the matrix, hue/saturation, tone or chroma fit, their gates and fallbacks, or how a camera profile feeds them. Changes that leave the fitted look alone don't need it. A header without the field (everything built before it existed) counts as version 0, and so does a value that is not a non-negative integer; a value from a newer build is left alone.
A proxy older than the constant is brought up to date by the existing Build Smart Previews path (`smart_run`), which also repairs damaged proxies:
@@ -372,3 +386,25 @@ 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)
Each loaded lens database snapshot is immutable. 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.
A reload with the same matching and calibration data preserves the identity and leaves current previews valid.
When that data changes, affected fitted smart previews become eligible for rebuilding once their originals are available.
Existing offline proxies remain readable. A missing legacy identity triggers a new check. Proxies from newer
fit or encoding versions retain their downgrade protection.
Smart-preview builds decode the original afresh and capture its database identity before decoding. A reload
or replacement during decoding rejects that write; a later change during encoding leaves the captured identity
on the proxy so it can still be recognized as stale. A scan interrupted by a database change does not mark the
new database as checked. Existing destinations remain untouched when a build is rejected.
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.
The DNG colour fit retains only file-owned vignette gains: an external database vignette is not
stored with those sensor samples. External correspondence geometry remains available; normal
photo and pooled fits keep their existing vignetting. 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.
+4
View File
@@ -199,3 +199,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| 2026-10-20 | minor | Opt-in Windows DirectComposition preference added; VRR hardware verification pending; parity counts unchanged |
| 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged |
| 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) |
## Proposed external-profile correspondence geometry
Camera colour calibration remains open. 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.
+9 -1
View File
@@ -70,6 +70,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 `<model>24-70mm f/2.8</model>` 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 |
@@ -104,4 +112,4 @@ match score still wins even when its crop is unknown.
- The focus distance is not read from maker notes yet: vignetting uses the farthest calibrated distance.
- No manual make / model picker and no choice between sources (in the file, lens database, an own calibration)
yet; matching is automatic, the file's own correction wins.
- Not yet validated against real photos and another renderer; the tests use synthetic profiles and grids.
- Automated tests use synthetic profiles and grids. Historical validation of the fixed-mount fallback and its use for colour correspondences covered five private G7 X II photographs; it was not rerun on the subsequently synchronized source and does not establish geometric accuracy across other cameras or profiles.
+12 -4
View File
@@ -243,7 +243,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); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; 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, `Line truncated
| 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); the Canon EOS D60 (CRW) has DNG-style matrices of our own, fitted to ColorChecker Classic shots under a tungsten bulb and direct sun (`crates/raw/src/chart_table.rs`, `clean-room/crw/10-chart-calibration.md`; CIEDE2000 on the chart mean 2.4 / 1.7, 2.7 / 2.0 leaving each patch out), which give its white balance a Kelvin scale (the camera's own presets read Tungsten 3,264 K, Daylight 5,603 K, Cloudy 6,612 K) while its look stays the JPEG fit; 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, `Line truncated
| 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 |
@@ -437,7 +437,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; a filter above the tabs lists the sections of any tab that have every word typed (`field:settingsFilter`, `settingsFound:<tab>:<section>`); 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); Startup View: an image passed at launch honors explicit Detail; Grid and Last use Photo Grid; populated-library launches without image arguments retain their saved view; a damaged settings file is kept as `.corrupt-<time>` and reported, an unreadable one is not overwritten that session (`library.info` → `settingsWarnings`); quitting with unsaved changes retries, then asks |
| LR-PREF-LOCALSTORAGE | Storage & cache | P1 | ✅ | `cmd:library.preferences`, `cmd:library.clearPreviews`, `cmd:library.compact` | thumbnail cache size + clear in Settings → Performance; library location + Open Library… in General; the automatic size has no ceiling, so once per session (library open, then every few minutes) a notice says when the drive holding the cache has under 10 % or under 20 GB free, with its free space and the cache's size, and opens Settings → Performance (`crates/engine/src/disk_space.rs`, `library.info` → `lowDiskSpace`, `button:noticeSettings`) |
| LR-PREF-LOCALSTORAGE | Storage & cache | P1 | ✅ | `cmd:library.preferences`, `cmd:library.clearPreviews`, `cmd:library.compact` | thumbnail cache size + clear in Settings → Performance; library location + Open Library… in General; the automatic size has no ceiling, so once per session (library open, then every few minutes) a notice says when the drive holding the cache has under 20 GB free (not a share of the drive: 8 % of a 926 GB drive is 76 GB, #4013), with its free space and the cache's size, and opens Settings → Performance (`crates/engine/src/disk_space.rs`, `library.info` → `lowDiskSpace`, `button:noticeSettings`) |
| LR-PREF-ACCOUNT | Account | OOS | 🚫 | | |
| LR-PREF-INTERFACE | Interface options | P1 | ✅ | `cmd:app.settings`, `cmd:view.appearance`, `cmd:view.theme` | Appearance Mode (Sync with System / Dark / Light; the top bar button cycles Auto, Light, Dark) with separate dark (Charcoal, Midnight) and light (Silver, Paper) themes previewed in cards; hover stars persist favorite themes, the appearance button context menu opens Interface settings and lists light favorites before dark favorites; filmstrip names/badges, grid badges (Ratings & flags: Stars on hover, the default, formerly "When rated or hovered": flags and colour labels always, stars and the edited mark on hover and selection; Always; Never), square-grid names, navigator, info overlay |
| LR-PREF-DISPLAY | Monitor (display) colour management | P1 | 🟡 | `cmd:app.displayProfile`, `crates/codecs/src/display.rs`, `crates/engine/src/display.rs`, `crates/ui-egui/src/dialogs/settings.rs`, `apps/lightcraft/src/screen_profile.rs`, `apps/lightcraft/src/colord.rs`, `apps/lightcraft/src/win_screen_profile.rs`, `crates/wincolor/src/lib.rs`, `docs/display-profiles.md` | Settings ▸ Display: a monitor ICC profile (matrix/TRC exactly, LUT-based through the CMS) chosen by hand, or on macOS the profile of the screen showing the window (followed across screens, #787), on Linux the profile the desktop assigns in colord (read off the UI thread every 3 s; used with one display, or several sharing one profile), on Windows the profile Windows Color System assigns to the monitor showing the window (per-user or system, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop itself: HDR or Auto Color Management; verified on Windows 11 with a Display P3 profile set and unset while the app ran); the loupe, Before, Compare, hover previews and the second window render into the display's primaries (its full gamut, CPU and GPU), thumbnails and stand-ins are converted from sRGB; histogram, preview caches and exports stay sRGB; soft proofing's display gamut warning uses the display's gamut. Missing: X11 `_ICC_PROFILE`, per-monitor profiles on Linux (eframe doesn't say which monitor the window is on) |
@@ -492,7 +492,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). While a dialog is open the bar is not dimmed, so it stays level with the window buttons AppKit draws over it (as under a macOS sheet): its controls are inactive, a click on it does not close the dialog, and its empty space still moves the window; not on a window with its native title bar, nor in full screen. 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). While a dialog is open the bar is not dimmed, so it stays level with the window buttons AppKit draws over it (as under a macOS sheet): its controls are inactive, a click on it does not close the dialog, and its empty space still moves the window; not on a window with its native title bar, nor in full screen. 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-WINDOW | Window size and maximized state remembered | P2 | 🟡 | `crates/ui-egui/src/window_place.rs`, `apps/lightcraft/src/prefs.rs`, `apps/lightcraft/src/main.rs` | the window opens at the size it was left at, zoomed / maximized if it was; full screen and the place on the desktop are not remembered; Windows: a maximized window is built at its size and maximized once it shows (built maximized it could cover half the screen while Windows took it for maximized), and restored and maximized again once if it only says so; a window remembered larger than its screen is fitted to it. Not verified on several monitors with different scales on hardware |
## Y. Menus
@@ -533,7 +533,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; Paste Settings from Previous (⌥⌘V) follows it |
| MENU-EDIT-SELECTALL | Select All | P0 | ✅ | `cmd:library.selectAll` | |
| MENU-EDIT-SELECTNONE | Select None | P0 | ✅ | `cmd:library.selectNone` | Select Only Active Photo (⇧⌘D) follows it |
| 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` | |
@@ -809,13 +809,17 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| Date | Change | Summary |
|---|---|---|
| 2026-11-19 | minor | LR-EDIT-OPTICS-DEFRINGE: AI Defringe (beyond Lightroom), a user-installed defringe network with a cached per-photo correction; no model ships; status unchanged |
| 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-11-15 | patch | LR-PRE-AMOUNT: Amount blends tone curves, fades in the strength of a profile/LUT or switched-on group a preset changes, and takes white balance on another scale whole (#2669); the step at half amount for switches and choices stays (#2207); status unchanged (✅) |
| 2026-11-09 | minor | LR-PREF-LOCALSTORAGE: the low-disk notice warns under 20 GB free, no longer under 10 % of the drive (76 GB free of a 926 GB drive warned, #4013); status unchanged |
| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. |
| 2026-11-23 | minor | LR-BEHAV-RENDER-FIDELITY, LR-EDIT-LIGHT-SHADOWS, LR-EDIT-EFFECTS-TEXTURE, LR-EDIT-COLOR-GRADING, LRC-DEV-PROCESS: process V13 eases global Shadows off at large amounts, negative Texture and the Global grading wheel act less, fitted to Lightroom exports of real edits (#523); statuses and counts unchanged |
| 2026-11-24 | minor | LR-REM-HEAL, LR-REM-CLONE, LRC-DEV-PROCESS: process V14 pins Heal and Remove spots to the photo on the spot's edge (membrane fill of the log ratio), matches the source's grain to its surroundings and reads every spot's source at whole pixels; statuses and counts unchanged |
| 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged |
| 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur |
| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). |
| 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-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) |
| 2026-11-07 | minor | LR-EDIT-EFFECTS-GRAIN, LRC-DEV-PROCESS: process V7 takes film grain to crystal layers ([grain.md](grain.md)); V1 to V6 keep value noise |
| 2026-11-06 | minor | LR-EDIT-DETAIL-CNR, LRC-DEV-PROCESS: process V6 takes colour noise reduction to the joint method on linear R−Y / B−Y (issue #815); status unchanged |
@@ -1107,3 +1111,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-17 | minor | LR-BEHAV-DRAGDROP: Esc gives up a photo drag (and only the drag); album rows say how many photos a drop adds or that they are there already (a no-op drop changes nothing); smart albums, album folders and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason; the Keyword List says how many photos get a keyword and refuses a keyword dropped inside itself; LR-LIB-ALBUM and LRC-LIB-KEYWORDS text updated; status unchanged (✅) |
| 2026-10-27 | patch | MENU-HELP-FEEDBACK: on macOS the Help menu no longer shows the system's `Send <app> Feedback` row beside Send Feedback… |
| 2026-10-17 | minor | LR-LIB-SMARTALBUM, LR-LIB-PEOPLE, LR-VIEW-FOCUSPOINT, LR-VIEW-BEFOREAFTER, LR-VIEW-SLIDESHOW, LR-BEHAV-SIDEBAR-HIDE, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-SIDEBARSECTIONS, KEY-MASKCOLOR, LRC-LIB-METADATA, LRC-MAP-TRACKLOG, LRC-SS-PLAYBACK, LRC-SS-EXPORT, LRC-DEV-VIEWOPTIONS: menu bar reorganised; the rows now cite the new paths (View ▸ Loupe Overlay, Before/After, Mask Overlay, Slideshow, Sort; Window for panel toggles; Photo ▸ Metadata); no command changed and no status changed |
## Proposed external-profile correspondence geometry
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.
+1
View File
@@ -178,6 +178,7 @@ establish OS keyboard delivery or cross-platform acceptance.
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | patch | Export dialog: Format, Amount and Metadata are a dropdown beside their label, and Color space and Sharpen a boxed dropdown as Resize to is, instead of rows of buttons; the dialog keeps its width |
| 2026-11-08 | patch | Crop panel Overlay and Perspective Correction, and the Remove panel's mode, are a label with a dropdown beside it (as White Balance is) instead of rows of buttons |
| 2026-10-28 | minor | Shortcuts: in the Masking panel H toggles the mask pins (the same switch as View → Show Mask Pins) instead of opening Remove; only an unmodified H toggles and it yields only to an explicit assignment of H itself, a Remove key reassigned in Help → Keyboard Shortcuts still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default) |
| 2026-10-24 | minor | KEYC-METADATA: ⌘⌥K / Ctrl+Alt+K (Photo ▸ Enable Painting) paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel |
+18
View File
@@ -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).
## Unreleased
### AI Defringe
@@ -9,6 +16,12 @@
kept, so switching it off and on or moving Amount is instant, and an export makes it if it is missing. See
[AI Defringe](ai-defringe.md).
### 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).
### Export subfolder variables
- The Export dialog's Subfolder field now supports `{album}` (active album name sanitized for filesystem safety, empty outside an album view), `{date}` (batch export date in `YYYYMMDD`, local time), and `{hour}` (batch export time in `HHMM`, local time). An **Insert…** dropdown next to the field inserts tokens at the cursor. Tokens are stored in presets and expanded at export time, so the same preset produces dated subfolders on every use.
### Heal meets its surroundings (process 14)
@@ -192,6 +205,11 @@
Photo Grid. Populated-library launches without image arguments keep their saved view. (#3028)
## 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).
### Lightroom catalogs with a print inside a collection import their collections
- Lightroom Classic can keep a saved print, book, slideshow or web gallery inside a plain collection, but a
LightCraft album sits only inside a folder. Importing such a catalog stopped at the end with "parent must be an