Merge main (fc10a3faa6) into mac-menu-appkit-help

Re-merged main after today's merges. Conflicts: docs/parity-checklist.md  Re-merged main after 2092/2204/2418 landed: only docs/parity-checklist.md conflicted (rows from both sides kept, summary regenerated); no code change since the last merge.   Docs/locale conflicts are resolved by keeping both sides. Also folds in two fixes for main so the gate passes: crates/engine/src/import/job.rs gets rustfmt (the #1995 merge left it unformatted, so every gate failed at fmt), and the Windows-only folders test joins each path component.
This commit is contained in:
FredApps committed 2026-11-26 22:34:09 +07:00
commit d31f84ffa7
52 files changed
+2808 -219

No files matched your search

+1
View File
@@ -132,6 +132,7 @@ impl WireJob {
proof: None,
window: self.window.map(|[x, y, w, h]| lightcraft_engine::pipeline::PixelWindow { x, y, w, h }),
display: None,
downscale: lightcraft_engine::pipeline::Downscale::Smooth,
}
}
+39 -1
View File
@@ -247,7 +247,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R
let opts = *opts;
// The reason a format can't be decoded lives in one place, `Format::not_decodable`.
let unsupported = || Err(Error::Unsupported(format, format.not_decodable().unwrap_or("not decodable in this build")));
match format {
let d = match format {
Format::Jpeg => jpeg::decode(bytes, &opts),
Format::Png => png_codec::decode(bytes, &opts),
Format::Tiff => tiff_codec::decode(bytes, &opts),
@@ -261,7 +261,20 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R
Format::Heif => heif::decode(bytes, &opts),
Format::Avif => avif_decode::decode(bytes, &opts),
Format::RawTiffLike | Format::RawOther => unsupported(),
}?;
check_has_pixels(format, &d.image)?;
Ok(d)
}
/// An image with no pixels (a malformed header claiming zero width or height, a `w × h` that
/// overflows, or a buffer shorter than its size) is refused, so nothing downstream sees an empty
/// image.
fn check_has_pixels(format: Format, image: &Rgb32f) -> Result<()> {
let (w, h) = (image.width, image.height);
if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| image.data.len() < n) {
return Err(Error::Malformed(format, "image has no pixels".into()));
}
Ok(())
}
/// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space.
@@ -381,4 +394,29 @@ mod checked_arithmetic_tests {
// 300 Mpx RGBA is within the default pixel limit, so it must not be refused by sample count.
assert_eq!(checked_sample_buf_len(20_000, 15_000, 4), Some(1_200_000_000));
}
#[test]
fn checked_sample_buf_len_does_not_wrap_like_32_bit_usize() {
// 65535 × 21846 × 3 = 4_295_032_830, which a 32-bit `usize` product wraps to 65_534
assert_eq!(checked_sample_buf_len(65_535, 21_846, 3), Some(4_295_032_830));
assert!(checked_sample_buf_len(65_535, 21_846, 3).is_some_and(|n| n > 65_534));
}
fn image(width: usize, height: usize, len: usize) -> Rgb32f {
Rgb32f { width, height, data: vec![[0.0; 3]; len] }
}
#[test]
fn decoded_image_without_pixels_is_refused() {
for (w, h, len) in [(0, 4, 0), (4, 0, 0), (usize::MAX, 2, 1), (4, 4, 15)] {
let r = check_has_pixels(Format::Png, &image(w, h, len));
assert!(matches!(r, Err(Error::Malformed(Format::Png, _))), "{w}x{h} with {len} pixels");
}
}
#[test]
fn decoded_image_with_all_pixels_is_accepted() {
assert!(check_has_pixels(Format::Png, &image(4, 4, 16)).is_ok());
assert!(check_has_pixels(Format::Png, &image(1, 1, 1)).is_ok());
}
}
+37
View File
@@ -291,6 +291,43 @@ fn thumbnail_respects_configured_source_pixel_limit() {
assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1);
}
/// A header claiming zero width or height is an error, never a decoded image with no pixels
/// (downstream filters index into it).
#[test]
// End-to-end no-panic check: headers claiming a zero dimension are errors. The JPEG and PNG
// readers already refuse these; `decode_unguarded`'s own final-output guard is tested directly in
// the crate's unit tests.
fn zero_size_headers_are_refused() {
let jpeg = seeds()[0].clone();
let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();
for at in [sof + 5, sof + 7] {
let mut j = jpeg.clone();
j[at..at + 2].copy_from_slice(&[0, 0]);
assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err());
}
let png = seeds()[1].clone();
for at in [16, 20] {
let mut p = png.clone();
p[at..at + 4].copy_from_slice(&[0; 4]);
// repair the IHDR CRC so the dimension, not the checksum, is what gets refused
let crc = crc32(&p[12..29]);
p[29..33].copy_from_slice(&crc.to_be_bytes());
assert!(decode_unguarded(&p, Format::Png, &small_opts()).is_err());
}
}
/// CRC-32 (IEEE), as PNG chunks use.
fn crc32(bytes: &[u8]) -> u32 {
let mut c = !0u32;
for &b in bytes {
c ^= u32::from(b);
for _ in 0..8 {
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
fn seeds() -> &'static Vec<Vec<u8>> {
static S: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
S.get_or_init(|| {
+43
View File
@@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option<usize>) {
match op {
Op::Conv(c) => (c.src, c.src2),
Op::ConvT2(c) => (c.src, None),
Op::Add { src, src2 } => (*src, Some(*src2)),
Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => (*src, None),
}
}
@@ -108,6 +109,7 @@ impl NetRunner {
(a.channels, a.side / 2)
}
Op::DepthToSpace2 { .. } => (a.channels / 4, a.side.checked_mul(2).ok_or_else(|| bad("size overflow"))?),
Op::Add { .. } => (a.channels, a.side),
};
let n = count(channels, side)?;
let slot = busy
@@ -215,6 +217,7 @@ impl NetRunner {
&mut w.lower,
&mut w.product,
)?,
Op::Add { .. } => add(a, b.ok_or_else(|| bad("Add needs two inputs"))?, shape.side, dest)?,
Op::MaxPool2 { .. } => pool(a, shape.side, dest)?,
Op::DepthToSpace2 { .. } => shuffle(a, shape.side, dest)?,
}
@@ -381,6 +384,46 @@ fn shuffle(a: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
}
Ok(())
}
fn add(a: &[f32], b: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
let pixels = side * side;
let channels = a.len() / pixels;
let need = channels.checked_mul(pixels).ok_or_else(|| bad("Add size overflows"))?;
if a.len() < need || b.len() < need || dest.len() < need {
return Err(bad("Add inputs and output are not the same size"));
}
for c in 0..channels {
let a_plane = &a[c * pixels..(c + 1) * pixels];
let b_plane = &b[c * pixels..(c + 1) * pixels];
let d_plane = &mut dest[c * pixels..(c + 1) * pixels];
for (d, (&av, &bv)) in d_plane.iter_mut().zip(a_plane.iter().zip(b_plane)) {
*d = av + bv;
}
}
Ok(())
}
#[cfg(test)]
#[test]
fn add_op_produces_elementwise_sum() {
use crate::net::{Conv, Net, Op, TensorId};
fn conv(src: TensorId, cin: usize, cout: usize) -> Op {
Op::Conv(Conv { src, src2: None, cin, cout, k: 1, weight: vec![0.1; cout * cin], bias: vec![0.0; cout], leaky: None })
}
let tile = 8usize;
let ops = vec![conv(0, 4, 12), Op::Add { src: 1, src2: 1 }, Op::DepthToSpace2 { src: 2 }];
let net = Net::new(4, ops).unwrap();
let runner = NetRunner::new(&net, tile).unwrap();
let pixels = tile * tile;
let input: Vec<f32> = vec![1.0; 4 * pixels];
let output = runner.run(&input).unwrap();
assert_eq!(output.len(), 3 * (2 * tile) * (2 * tile));
for &v in &output {
assert!((v - 0.8).abs() < 1e-4, "expected 0.8, got {v}");
}
}
#[cfg(test)]
mod tests;
+19
View File
@@ -63,6 +63,11 @@ pub struct ConvT2 {
pub enum Op {
Conv(Conv),
ConvT2(ConvT2),
/// Elementwise addition of two same-shape tensors.
Add {
src: TensorId,
src2: TensorId,
},
/// 2 × 2 maximum, stride 2.
MaxPool2 {
src: TensorId,
@@ -146,6 +151,20 @@ impl Net {
check_weights(i, &c.weight, c.cin.checked_mul(c.cout).and_then(|n| n.checked_mul(4)), &c.bias, c.cout, c.leaky, &mut weights)?;
Shape { channels: c.cout, level: a.level - 1 }
}
Op::Add { src, src2 } => {
let a = shape_of(*src)?;
let b = shape_of(*src2)?;
if a.channels != b.channels || a.level != b.level {
return invalid(format!("layer {i}: add of tensors of different shapes"));
}
if a.channels == 0 {
return invalid(format!("layer {i}: add with zero channels"));
}
if a.channels > MAX_CHANNELS {
return invalid(format!("layer {i}: add with more than {} channels", MAX_CHANNELS));
}
Shape { channels: a.channels, level: a.level }
}
Op::MaxPool2 { src } => {
let a = shape_of(*src)?;
Shape { channels: a.channels, level: a.level + 1 }
+469 -23
View File
@@ -2,16 +2,18 @@
//!
//! Only what the denoise U-Nets are made of is understood: `Conv` (3 × 3 "same" or 1 × 1, stride 1, no groups, no
//! dilation) optionally followed by `LeakyRelu`, `ConvTranspose` (2 × 2, stride 2) likewise, `MaxPool` (2 × 2, stride 2),
//! a two-input `Concat` on the channels that feeds a convolution, and a final `DepthToSpace` (2, `CRD`). Any other
//! a two-input `Concat` on the channels that feeds a convolution, an `Add` of two same-shape tensors (elementwise addition),
//! a standalone `LeakyRelu` (as a 1 × 1 identity convolution with the
//! activation, when its source has more than one reader), and a final `DepthToSpace` (2, `CRD`). Any other
//! operator or attribute is [`NetError::Unsupported`], which is reported to the user by both runners.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use crate::onnx_proto::{self, AttributeProto, NodeProto, TensorProto, ValueInfoProto};
use std::io::Read;
use crate::net::{Conv, ConvT2, MAX_WEIGHTS, Net, NetError, Op, TensorId};
use crate::net::{Conv, ConvT2, MAX_CHANNELS, MAX_OPS, MAX_WEIGHTS, Net, NetError, Op, TensorId};
fn unsupported<T>(why: impl Into<String>) -> Result<T, NetError> {
Err(NetError::Unsupported(why.into()))
@@ -62,11 +64,23 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
// a Concat is not a layer of its own: the convolution that reads it takes both sources
let mut joins: HashMap<String, (TensorId, TensorId)> = HashMap::new();
let mut ops: Vec<Op> = Vec::new();
let mut shapes: Vec<(usize, i32)> = vec![(in_channels, 0)];
let mut weights_total = 0usize;
let nodes = &graph.node;
let mut i = 0;
let mut fused_indices = HashSet::new();
while i < nodes.len() {
// Skip nodes that were fused as LeakyRelu activations
while i < nodes.len() && fused_indices.contains(&i) {
i += 1;
}
if i >= nodes.len() {
break;
}
if ops.len() >= MAX_OPS {
return invalid("the network has too many layers");
}
let Some(node) = nodes.get(i) else { break };
i += 1;
if node.output.len() != 1 || node.output.first().is_none_or(|n| n.is_empty() || ids.contains_key(n) || joins.contains_key(n)) {
@@ -77,6 +91,8 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
"ConvTranspose" => &["kernel_shape", "pads", "strides", "dilations", "group", "output_padding", "auto_pad"],
"MaxPool" => &["kernel_shape", "pads", "strides", "dilations", "ceil_mode", "storage_order", "auto_pad"],
"Concat" => &["axis"],
"Add" => &[],
"LeakyRelu" => &["alpha"],
"DepthToSpace" => &["blocksize", "mode"],
_ => &[],
};
@@ -87,25 +103,37 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
let lookup = |name: &str| -> Result<TensorId, NetError> {
ids.get(name).copied().ok_or_else(|| NetError::Invalid(format!("`{}` reads `{name}`, which nothing makes", node.op_type)))
};
// a LeakyRelu straight after this layer, which nothing else reads, is part of it
let mut fuse_leaky = |out: &str| -> Result<(Option<f32>, String), NetError> {
if let Some(next) = nodes.get(i)
&& next.op_type == "LeakyRelu"
&& next.input.first().map(String::as_str) == Some(out)
&& readers.get(out).copied() == Some(1)
{
if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") {
return invalid("malformed LeakyRelu");
// a LeakyRelu consuming this output, which nothing else reads, is part of it
let mut fuse_leaky = |out: &str, joins: &HashMap<String, (TensorId, TensorId)>| -> Result<(Option<f32>, String), NetError> {
// Search forward for a LeakyRelu consuming this output
for j in i..nodes.len() {
if fused_indices.contains(&j) {
continue;
}
let next = &nodes[j];
if next.op_type == "LeakyRelu" && next.input.first().map(String::as_str) == Some(out) && readers.get(out).copied() == Some(1) {
if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") {
return invalid("malformed LeakyRelu");
}
// only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0
let alpha = match next.attribute.as_slice() {
[] => 0.01,
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
_ => return invalid("LeakyRelu alpha is not a single float"),
};
let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
if name.is_empty() || ids.contains_key(&name) || joins.contains_key(&name) {
continue;
}
// Fusing gives the LeakyRelu's output the id of this op. If that output is the graph
// output it must stay the last tensor, so decline the fusion when another node after
// this one emits an operation: it would push the graph output before a later tensor.
if name == output.name.as_str() && nodes[i..].iter().enumerate().any(|(k, n)| i + k != j && emits_op(n.op_type.as_str())) {
continue;
}
fused_indices.insert(j);
return Ok((Some(alpha), name));
}
// only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0
let alpha = match next.attribute.as_slice() {
[] => 0.01,
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
_ => return invalid("LeakyRelu alpha is not a single float"),
};
i += 1;
let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
return Ok((Some(alpha), name));
}
Ok((None, out.to_string()))
};
@@ -147,8 +175,9 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
None => (lookup(src_name)?, None),
};
let out = node.output.first().ok_or_else(|| NetError::Invalid("Conv without an output".into()))?;
let (leaky, out_name) = fuse_leaky(out)?;
let (leaky, out_name) = fuse_leaky(out, &joins)?;
ids.insert(out_name, this);
shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1)));
ops.push(Op::Conv(Conv { src, src2, cin, cout, k: kh, weight: w.1, bias: b, leaky }));
}
"ConvTranspose" => {
@@ -172,8 +201,9 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
}
let src = lookup(node.input.first().map_or("", String::as_str))?;
let out = node.output.first().ok_or_else(|| NetError::Invalid("ConvTranspose without an output".into()))?;
let (leaky, out_name) = fuse_leaky(out)?;
let (leaky, out_name) = fuse_leaky(out, &joins)?;
ids.insert(out_name, this);
shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1) - 1));
ops.push(Op::ConvT2(ConvT2 { src, cin, cout, weight: w.1, bias: b, leaky }));
}
"MaxPool" => {
@@ -190,8 +220,72 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
let src = lookup(node.input.first().map_or("", String::as_str))?;
let out = node.output.first().ok_or_else(|| NetError::Invalid("MaxPool without an output".into()))?;
ids.insert(out.clone(), this);
shapes.push(shapes.get(src).copied().map_or((in_channels, 1), |(c, l)| (c, l + 1)));
ops.push(Op::MaxPool2 { src });
}
"Add" => {
let [a, b] = node.input.as_slice() else { return unsupported("Add of other than two tensors") };
if joins.contains_key(a) || joins.contains_key(b) {
return unsupported("Add reading a Concat output");
}
if initialisers.contains_key(a.as_str()) || initialisers.contains_key(b.as_str()) {
return unsupported("Add with an initializer operand");
}
let src = lookup(a)?;
let src2 = lookup(b)?;
let out = node.output.first().ok_or_else(|| NetError::Invalid("Add without an output".into()))?;
let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
let (cb, lb) = shapes.get(src2).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
if ca != cb || la != lb {
return unsupported("Add of tensors of different shapes");
}
if ca == 0 {
return invalid("Add with zero channels");
}
if ca > MAX_CHANNELS {
return unsupported("Add with more than 4096 channels");
}
ids.insert(out.clone(), this);
shapes.push((ca, la));
ops.push(Op::Add { src, src2 });
}
"LeakyRelu" => {
let [a] = node.input.as_slice() else { return invalid("malformed LeakyRelu") };
if joins.contains_key(a) {
return unsupported("LeakyRelu reading a Concat output");
}
if initialisers.contains_key(a.as_str()) {
return unsupported("LeakyRelu with an initializer operand");
}
let src = lookup(a)?;
let out = node.output.first().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("LeakyRelu reads a tensor with no shape".into()))?;
if ca == 0 {
return invalid("LeakyRelu with zero channels");
}
if ca > MAX_CHANNELS {
return unsupported("LeakyRelu with more than 4096 channels");
}
let alpha = match node.attribute.as_slice() {
[] => 0.01,
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
_ => return invalid("LeakyRelu alpha is not a single float"),
};
let nn = ca.checked_mul(ca).ok_or_else(|| NetError::Invalid("LeakyRelu channel count overflows".into()))?;
weights_total = weights_total.saturating_add(nn).saturating_add(ca);
if weights_total > MAX_WEIGHTS {
return invalid("the network has too many weights");
}
let mut weight = vec![0.0f32; nn];
for c in 0..ca {
if let Some(w) = weight.get_mut(c * ca + c) {
*w = 1.0;
}
}
ids.insert(out.clone(), this);
shapes.push((ca, la));
ops.push(Op::Conv(Conv { src, src2: None, cin: ca, cout: ca, k: 1, weight, bias: vec![0.0; ca], leaky: Some(alpha) }));
}
"DepthToSpace" => {
if attr(node, "blocksize").map(|a| a.i) != Some(2) || attr(node, "mode").map(|a| a.s.as_slice()) != Some(&b"CRD"[..]) {
return unsupported("depth-to-space other than block size 2 in CRD order");
@@ -199,6 +293,7 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
let src = lookup(node.input.first().map_or("", String::as_str))?;
let out = node.output.first().ok_or_else(|| NetError::Invalid("DepthToSpace without an output".into()))?;
ids.insert(out.clone(), this);
shapes.push(shapes.get(src).copied().map_or((in_channels / 4, -1), |(c, l)| (c / 4, l - 1)));
ops.push(Op::DepthToSpace2 { src });
}
other => return unsupported(format!("the `{other}` operator")),
@@ -222,6 +317,12 @@ fn ints_or(n: &NodeProto, name: &str, default: &[i64]) -> Vec<i64> {
attr(n, name).map_or_else(|| default.to_vec(), |a| a.ints.clone())
}
/// Whether an ONNX operator node emits a denoise-layer operation. `Concat` does not: it only
/// records a join for the convolution that follows it.
fn emits_op(op_type: &str) -> bool {
matches!(op_type, "Conv" | "ConvTranspose" | "MaxPool" | "Add" | "LeakyRelu" | "DepthToSpace")
}
fn four(dims: &[i64]) -> Result<(usize, usize, usize, usize), NetError> {
match dims {
[a, b, c, d] if dims.iter().all(|&v| v > 0 && v <= 1 << 20) => Ok((*a as usize, *b as usize, *c as usize, *d as usize)),
@@ -297,6 +398,7 @@ fn channel_dim(v: &ValueInfoProto) -> Option<usize> {
mod tests {
use super::*;
use crate::synthetic::unet_onnx;
use crate::synthetic_proto::{len_field, value_info_bytes, varint_field};
fn temp_model(name: &str, bytes: &[u8]) -> std::path::PathBuf {
let p = std::env::temp_dir().join(format!("lc-denoise-onnx-{name}-{}.onnx", std::process::id()));
@@ -304,6 +406,109 @@ mod tests {
p
}
fn node(op: &str, inputs: &[&str], output: &str, ints: &[(&str, i64)]) -> Vec<u8> {
let mut n = Vec::new();
for i in inputs {
len_field(1, i.as_bytes(), &mut n);
}
len_field(2, output.as_bytes(), &mut n);
len_field(4, op.as_bytes(), &mut n);
for (name, value) in ints {
let mut a = Vec::new();
len_field(1, name.as_bytes(), &mut a);
varint_field(3, *value as u64, &mut a);
varint_field(20, 2, &mut a);
len_field(5, &a, &mut n);
}
n
}
fn tensor(name: &str, dims: &[u64], values: &[f32]) -> Vec<u8> {
let mut t = Vec::new();
for d in dims {
varint_field(1, *d, &mut t);
}
varint_field(2, 1, &mut t);
len_field(8, name.as_bytes(), &mut t);
let raw: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
len_field(9, &raw, &mut t);
t
}
fn model(nodes: &[Vec<u8>], in_channels: u64, out: &str) -> Vec<u8> {
let mut graph = Vec::new();
for n in nodes {
len_field(1, n, &mut graph);
}
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(in_channels), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes(out, 1, &[Ok(1), Ok(3), Ok(8), Ok(8)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
model
}
fn varint(mut v: u64, out: &mut Vec<u8>) {
loop {
let b = (v & 0x7f) as u8;
v >>= 7;
if v == 0 {
out.push(b);
return;
}
out.push(b | 0x80);
}
}
fn node_with_ints(op: &str, inputs: &[&str], output: &str, ints: &[(&str, &[i64])]) -> Vec<u8> {
let mut n = Vec::new();
for i in inputs {
len_field(1, i.as_bytes(), &mut n);
}
len_field(2, output.as_bytes(), &mut n);
len_field(4, op.as_bytes(), &mut n);
for &(name, values) in ints {
let mut a = Vec::new();
len_field(1, name.as_bytes(), &mut a);
// field 8: INTS (wire type 2) - varint-encoded list
varint(8 << 3 | 2, &mut a);
// length of the list in bytes (we'll compute after writing values)
let mut vals = Vec::new();
for &v in values {
varint(v as u64, &mut vals);
}
varint(vals.len() as u64, &mut a);
a.extend_from_slice(&vals);
// field 20: type = 7 (INTS)
varint_field(20, 7, &mut a);
len_field(5, &a, &mut n);
}
n
}
fn leaky_relu_node(inputs: &[&str], output: &str, alpha: f32) -> Vec<u8> {
let mut n = Vec::new();
for i in inputs {
len_field(1, i.as_bytes(), &mut n);
}
len_field(2, output.as_bytes(), &mut n);
len_field(4, b"LeakyRelu", &mut n);
// alpha attribute: field 1=name, field 2=float value (wire type 5), field 20=type=1 (FLOAT)
let mut a = Vec::new();
len_field(1, b"alpha", &mut a);
// field 2 with wire type 5 (fixed 4-byte float)
varint(2 << 3 | 5, &mut a);
a.extend_from_slice(&alpha.to_le_bytes());
// field 20: type = 1 (FLOAT)
varint_field(20, 1, &mut a);
len_field(5, &a, &mut n);
n
}
#[test]
fn a_u_net_is_read_with_its_layers_fused() {
let (tile, depth) = (32usize, 2usize);
@@ -324,6 +529,38 @@ mod tests {
let _ = std::fs::remove_file(p);
}
#[test]
fn add_operator_model_is_accepted() {
// the convolution output added back to the input, as a residual block does
let mut graph = Vec::new();
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph);
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
let mut mode = Vec::new();
len_field(1, b"mode", &mut mode);
len_field(4, b"CRD", &mut mode);
varint_field(20, 3, &mut mode);
len_field(5, &mode, &mut depth_to_space);
len_field(1, &depth_to_space, &mut graph);
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
let net = read_bytes(&model);
assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err());
let net = net.unwrap();
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
}
#[test]
fn a_leaky_relu_alpha_that_is_not_a_float_is_rejected() {
let good = unet_onnx(4, 3, 1, 7);
@@ -390,4 +627,213 @@ mod tests {
// a missing file
assert!(read(Path::new("/does/not/exist.onnx")).is_err());
}
#[test]
fn add_reading_concat_and_oversized_channels_are_unsupported() {
let concat_model =
model(&[node("Concat", &["data", "data"], "joined", &[("axis", 1)]), node("Add", &["joined", "data"], "a1", &[])], 4, "a1");
assert!(matches!(read_bytes(&concat_model), Err(NetError::Unsupported(_))));
let oversized_model = model(&[node("Add", &["data", "data"], "a1", &[])], 4097, "a1");
assert!(matches!(read_bytes(&oversized_model), Err(NetError::Unsupported(_))));
let mut depth = node("DepthToSpace", &["data"], "d", &[("blocksize", 2)]);
let mut mode = Vec::new();
len_field(1, b"mode", &mut mode);
len_field(4, b"CRD", &mut mode);
varint_field(20, 3, &mut mode);
len_field(5, &mode, &mut depth);
let zero_model = model(&[depth, node("Add", &["d", "d"], "a1", &[])], 3, "a1");
assert!(matches!(read_bytes(&zero_model), Err(NetError::Invalid(_))));
}
#[test]
fn many_adds_on_a_wide_input_are_accepted_up_to_max_ops() {
// 32 Add nodes on 4096 channels should be accepted (32 < MAX_OPS=512, no weight allocation)
let mut nodes = Vec::new();
let mut prev = "data".to_string();
for i in 0..32 {
let out = format!("a{i}");
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
prev = out;
}
let wide_model = model(&nodes, 4096, &prev);
assert!(read_bytes(&wide_model).is_ok(), "many Add nodes on wide input should be accepted");
// But exceeding MAX_OPS should still be rejected
let mut nodes = Vec::new();
let mut prev = "data".to_string();
for i in 0..=MAX_OPS {
let out = format!("a{i}");
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
prev = out;
}
let too_many_model = model(&nodes, 1, &prev);
assert!(matches!(read_bytes(&too_many_model), Err(NetError::Invalid(_))));
}
#[test]
fn leaky_relu_with_an_add_residual_branch_is_accepted() {
// the convolution output is read by both the LeakyRelu and the Add residual branch
let mut graph = Vec::new();
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
len_field(1, &node("LeakyRelu", &["c1"], "l1", &[]), &mut graph);
len_field(1, &node("Add", &["c1", "l1"], "a1", &[]), &mut graph);
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
let mut mode = Vec::new();
len_field(1, b"mode", &mut mode);
len_field(4, b"CRD", &mut mode);
varint_field(20, 3, &mut mode);
len_field(5, &mode, &mut depth_to_space);
len_field(1, &depth_to_space, &mut graph);
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
let net = read_bytes(&model);
assert!(net.is_ok(), "a LeakyRelu residual model was rejected: {:?}", net.err());
let net = net.unwrap();
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
}
#[test]
fn leaky_relu_fuses_across_interleaved_nodes() {
// Conv produces "c1", then an unrelated MaxPool (reading "data") comes between,
// then a LeakyRelu consumes "c1". The fusion should still happen.
let mut graph = Vec::new();
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
// Valid MaxPool: 2x2 kernel, stride 2, no padding, no dilation
len_field(
1,
&node_with_ints(
"MaxPool",
&["data"],
"mp1",
&[("kernel_shape", &[2, 2]), ("strides", &[2, 2]), ("pads", &[0, 0, 0, 0]), ("dilations", &[1, 1])],
),
&mut graph,
);
len_field(1, &leaky_relu_node(&["c1"], "l1", 0.2), &mut graph); // alpha=0.2
let mut depth_to_space = node("DepthToSpace", &["l1"], "rgb", &[("blocksize", 2)]);
let mut mode = Vec::new();
len_field(1, b"mode", &mut mode);
len_field(4, b"CRD", &mut mode);
varint_field(20, 3, &mut mode);
len_field(5, &mode, &mut depth_to_space);
len_field(1, &depth_to_space, &mut graph);
len_field(5, &tensor("w1", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
let net = read_bytes(&model);
assert!(net.is_ok(), "LeakyRelu across interleaved nodes was rejected: {:?}", net.err());
let net = net.unwrap();
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
// The Conv should have the leaky ReLU fused with alpha=0.2
let ops = net.ops();
assert_eq!(ops.len(), 3); // Conv (fused), MaxPool, DepthToSpace
match &ops[0] {
crate::net::Op::Conv(c) => {
assert_eq!(c.leaky, Some(0.2), "LeakyRelu alpha should be fused into Conv");
}
_ => panic!("first op should be fused Conv"),
}
assert!(matches!(ops[1], crate::net::Op::MaxPool2 { .. }));
assert!(matches!(ops[2], crate::net::Op::DepthToSpace2 { .. }));
}
#[test]
fn add_with_initializer_operand_is_unsupported() {
let mut graph = Vec::new();
len_field(1, &node("Add", &["data", "w1"], "a1", &[]), &mut graph);
len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("a1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_))));
}
#[test]
fn leaky_relu_with_initializer_operand_is_unsupported() {
let mut graph = Vec::new();
len_field(1, &node("LeakyRelu", &["w1"], "l1", &[]), &mut graph);
len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("l1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_))));
}
#[test]
fn more_than_max_ops_small_adds_are_rejected_as_too_many_layers() {
let mut nodes = Vec::new();
let mut prev = "data".to_string();
for i in 0..=MAX_OPS {
let out = format!("a{i}");
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
prev = out;
}
let many_model = model(&nodes, 1, &prev);
assert!(matches!(read_bytes(&many_model), Err(NetError::Invalid(_))));
}
#[test]
fn add_operator_model_is_accepted_review_regression_1() {
// An Add residual block: the convolution output is added back to the input.
let mut graph = Vec::new();
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph);
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
let mut mode = Vec::new();
len_field(1, b"mode", &mut mode);
len_field(4, b"CRD", &mut mode);
varint_field(20, 3, &mut mode);
len_field(5, &mode, &mut depth_to_space);
len_field(1, &depth_to_space, &mut graph);
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
let mut ops = Vec::new();
len_field(1, b"", &mut ops);
varint_field(2, 13, &mut ops);
let mut model = Vec::new();
varint_field(1, 8, &mut model);
len_field(7, &graph, &mut model);
len_field(8, &ops, &mut model);
let net = read_bytes(&model);
assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err());
}
}
+10
View File
@@ -104,6 +104,16 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
}
T { channels: c.cout, side: out_side, data }
}
Op::Add { src, src2 } => {
let a = get(&tensors, *src)?;
let b = get(&tensors, *src2)?;
let (channels, side) = (tensors[a].channels, tensors[a].side);
let mut data = tensor(channels, side, &mut total)?;
for (d, (&av, &bv)) in data.iter_mut().zip(tensors[a].data.iter().zip(&tensors[b].data)) {
*d = av + bv;
}
T { channels, side, data }
}
Op::MaxPool2 { src } => {
let a = get(&tensors, *src)?;
let (channels, side) = (tensors[a].channels, tensors[a].side / 2);
+373 -45
View File
@@ -5,8 +5,12 @@
//! computed from the photo's *original* state (its import settings, when known) and the preset's
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
//! current settings as before.
//! value; a point curve (a tone curve) moves between the two curves as rendered. Switches and choices
//! (a profile or LUT id, a style, a flag) take the original's value below half amount and the
//! preset's from half amount up, and the strength of a choice the preset changes fades in from 0
//! there; white balance on another scale is taken whole (see [`interpolate_object`]).
//! Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the current
//! settings as before.
//!
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
@@ -159,42 +163,34 @@ pub fn deep_merge(base: &mut Value, patch: &Value) {
}
}
/// Interpolate numbers in `patch` towards/away from `base` by `t` (1 = patch as-is); non-numeric
/// values are taken from the patch when `t >= 0.5`.
fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
match (base, patch) {
(Value::Object(b), Value::Object(p)) => {
let mut out = Map::new();
for (k, pv) in p {
let bv = b.get(k).unwrap_or(&Value::Null);
out.insert(k.clone(), scale_patch(bv, pv, t));
}
Value::Object(out)
}
// Integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would
// not deserialize as an integer, and the whole preset would silently not apply.
(Value::Number(b), Value::Number(p)) if b.is_f64() || p.is_f64() => {
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number).unwrap_or(Value::Null)
}
(b, p) => {
if t >= 0.5 {
p.clone()
} else {
b.clone()
}
}
}
}
/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped
/// through the control specs, as every merge does ([`DevelopSettings::merged`]).
/// Apply a partial settings object with an amount (1.0 = 100 %): each setting it names is blended
/// from `s`'s value by the same rules as a preset ([`interpolate_object`]). Out-of-range values are
/// clamped through the control specs, as every merge does ([`DevelopSettings::merged`]). At 0 %
/// (or less) nothing changes; at 100 % the partial is merged as it is.
pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings {
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) };
if amount.is_nan() || amount <= 0.0 {
return s.clone();
}
let patch = if (amount - 1.0).abs() < 1e-9 {
Cow::Borrowed(partial)
} else {
let base = blend_base(s);
Cow::Owned(Value::Object(partial.as_object().map(|p| interpolate_object(base.as_object(), p, amount)).unwrap_or_default()))
};
// (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`)
s.merged(&patch).unwrap_or_else(|_| s.clone())
}
/// `s` as the base an amount blends from: every group written out, also the ones serialization
/// leaves out while at their defaults (HDR), so their numbers blend from `s`'s values too.
fn blend_base(s: &DevelopSettings) -> Value {
let mut v = s.to_json_for_merge();
if let (Some(o), Ok(hdr)) = (v.as_object_mut(), serde_json::to_value(s.hdr)) {
o.entry("hdr").or_insert(hdr);
}
v
}
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
/// a preset without them leaves the photo's alone.
@@ -212,7 +208,7 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings
return current.merged(settings).unwrap_or_else(|_| current.clone());
}
let cur = current.to_json();
let mut base = original.to_json();
let mut base = blend_base(original);
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
for k in REPAIR_KEYS {
if let Some(v) = c.get(k) {
@@ -229,12 +225,38 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings
}
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
/// `base` ([`interpolate_leaf`]). A leaf the amount does not reach is left out, so the photo keeps
/// its own value there. Two rules look at an object as a whole (issue #2669):
///
/// - **The `amount` beside a choice.** When the preset changes a choice here (a string such as the
/// profile or LUT id or a style, or the object's `enabled` switch), its `amount` is the strength of
/// that choice, not of the base's: from half amount up, where the preset's choice applies, the
/// amount fades in from 0 (a new profile at 50 % has half the preset's strength, and a profile at
/// 0 % is no look at all); below half amount the base's choice keeps its own amount.
/// - **White balance on another scale.** `temp` / `tint` on a different [`crate::WbScale`] than the
/// base's (Kelvin against the older relative scale; a partial that names no scale is on the
/// relative one, as [`DevelopSettings::merged`] reads it) are in other units and are never
/// blended: below half amount the base's numbers and scale apply, from half amount up the
/// preset's, as for any other choice.
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
let get = |k: &str| base.and_then(|b| b.get(k));
let choice_changed = patch.iter().any(|(k, pv)| (pv.is_string() || (k == "enabled" && pv.is_boolean())) && get(k) != Some(pv));
let scale_of = |o: Option<&Map<String, Value>>| o.and_then(|o| o.get("scale")).and_then(Value::as_str).unwrap_or("legacy").to_string();
let other_scale = (patch.contains_key("temp") || patch.contains_key("tint")) && scale_of(Some(patch)) != scale_of(base);
let mut out = Map::new();
for (k, pv) in patch {
let bv = base.and_then(|b| b.get(k));
if other_scale && matches!(k.as_str(), "temp" | "tint" | "scale") {
continue;
}
let bv = get(k);
let v = match pv {
Value::Number(_) if choice_changed && k == "amount" => {
if t >= 0.5 {
interpolate_leaf(Some(&Value::from(0.0)), pv, t)
} else {
bv.cloned()
}
}
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
_ => interpolate_leaf(bv, pv, t),
};
@@ -242,18 +264,38 @@ fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Val
out.insert(k.clone(), v);
}
}
if other_scale {
// the numbers and their scale come together from one side, never a mix of the two
let side = if t >= 0.5 { Some(patch) } else { base };
for k in ["temp", "tint"] {
if let Some(v) = patch.get(k).and(side.and_then(|o| o.get(k))) {
out.insert(k.to_string(), v.clone());
}
}
out.insert("scale".to_string(), Value::from(scale_of(side)));
}
out
}
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
/// clear an option field such as a crop aspect).
/// One leaf at `t`. Numbers move from `base` towards `patch`. Point curves (lists of `{x, y}`
/// points, the tone curves; empty is the identity) move as curves: both are evaluated as the
/// renderer does (monotone cubic) at every control point of either, and the points blend like
/// numbers, `y` kept in `0..1`. Other values switch to the preset's at half amount and up, and
/// below it take the base's value. A null in the base is the baseline value the import state
/// recorded (a cleared option, such as a free crop aspect): below half amount it applies and
/// clears the photo's value, as the amount contract promises. A null the preset writes is a value
/// like any other, so it applies at half amount and up (a preset can clear an option field such as
/// a crop aspect).
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
if t > 0.0
&& let (Some(bc), Some(pc)) = (base.and_then(point_curve), point_curve(patch))
&& !(bc.is_empty() && pc.is_empty())
{
return Some(blend_curves(&bc, &pc, t));
}
match (base, patch) {
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
// integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would
// not deserialize as an integer, and the whole preset would silently not apply
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
@@ -263,6 +305,34 @@ fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value
}
}
/// `v` as a point curve: a list whose items all are `{x, y}` numbers (empty: the identity).
fn point_curve(v: &Value) -> Option<Vec<(f64, f64)>> {
v.as_array()?
.iter()
.map(|q| {
let o = q.as_object().filter(|o| o.len() == 2)?;
Some((o.get("x")?.as_f64()?, o.get("y")?.as_f64()?))
})
.collect()
}
/// Two point curves blended by `t` at the control points of both (see [`interpolate_leaf`]).
fn blend_curves(base: &[(f64, f64)], patch: &[(f64, f64)], t: f64) -> Value {
use lightcraft_color::spline::MonotoneCurve;
let (bc, pc) = (MonotoneCurve::new(base), MonotoneCurve::new(patch));
let mut xs: Vec<f64> = bc.points().into_iter().chain(pc.points()).map(|(x, _)| x.clamp(0.0, 1.0)).collect();
xs.sort_by(f64::total_cmp);
xs.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let points = xs
.into_iter()
.map(|x| {
let (yb, yp) = (bc.eval(x), pc.eval(x));
serde_json::json!({"x": x, "y": (yb + (yp - yb) * t).clamp(0.0, 1.0)})
})
.collect();
Value::Array(points)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub id: String,
@@ -285,6 +355,11 @@ impl Preset {
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
/// their effect scaled by the amount.
///
/// This knows nothing about the photo's source. A preset that names only one white balance
/// number needs the photo prepared against its as-shot white first, and the result put back on
/// the scale the photo is edited on: callers on a real photo go through the engine's
/// `apply_preset_to_photo`, which does that.
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
self.apply_on(s, s, amount)
}
@@ -295,8 +370,15 @@ impl Preset {
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
/// by the amount. A second preset therefore restores what the first one changed in the
/// settings it names (issue #2159), and nothing it leaves out.
/// settings it names (issue #2159), and nothing it leaves out. At 0 % (or less) the settings it
/// names take `original`'s values, so with `current` as the original nothing changes, and its
/// masks are not added (a mask at no strength would only block applying the preset later); a
/// NaN `amount` changes nothing.
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
if amount.is_nan() {
return current.clone();
}
let amount = amount.max(0.0);
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
return compose_named(current, original, &self.settings, amount);
};
@@ -305,7 +387,9 @@ impl Preset {
o.remove("masks");
}
let mut out = compose_named(current, original, &rest, amount);
add_masks(&mut out, masks, amount);
if amount > 0.0 {
add_masks(&mut out, masks, amount);
}
out
}
}
@@ -391,6 +475,250 @@ mod tests {
}
}
fn pts(v: &[(f64, f64)]) -> Vec<lightcraft_geom::Point> {
v.iter().map(|&(x, y)| lightcraft_geom::Point::new(x, y)).collect()
}
fn eval(c: &[lightcraft_geom::Point], x: f64) -> f64 {
lightcraft_color::spline::MonotoneCurve::new(&c.iter().map(|p| (p.x, p.y)).collect::<Vec<_>>()).eval(x)
}
fn preset(settings: Value) -> Preset {
Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings, favorite: false, builtin: false }
}
/// Issue #2669: a preset's tone curve did nothing below 50 % and all of it from 50 % up.
#[test]
fn amount_blends_point_curves() {
let curve = [(0.0, 0.0), (0.25, 0.15), (0.75, 0.85), (1.0, 1.0)];
let partial = json!({"curve": {"master": pts(&curve)}});
let base = DevelopSettings::default();
let mut last = 0.25;
for i in 1..=10 {
let t = f64::from(i) / 10.0;
let out = apply_partial(&base, &partial, t);
let y = eval(&out.curve.master, 0.25);
assert!((y - (0.25 - 0.10 * t)).abs() < 1e-9, "{t}: y(0.25) = {y}");
assert!(y < last + 1e-12, "{t}: the curve moves steadily towards the preset's");
last = y;
}
assert!(apply_partial(&base, &partial, 0.0).curve.master.is_empty(), "0 % keeps the photo's curve");
// 200 % goes twice as far, kept in 0..1
let more = apply_partial(&base, &partial, 2.0);
assert!((eval(&more.curve.master, 0.25) - 0.05).abs() < 1e-9);
assert!(more.curve.master.iter().all(|p| (0.0..=1.0).contains(&p.y)));
// a photo whose original has its own curves (other points): at every control point of either
// curve the result is the blend of the original's curve and the preset's as rendered, whatever
// the photo's current curve is
let mut original = DevelopSettings::default();
original.curve.master = pts(&[(0.0, 0.05), (0.5, 0.6), (1.0, 0.95)]);
original.curve.red = pts(&[(0.0, 0.0), (0.4, 0.5), (1.0, 1.0)]);
let mut current = DevelopSettings::default();
current.curve.master = pts(&[(0.0, 0.2), (1.0, 0.8)]);
let p = preset(json!({"curve": {"master": pts(&curve), "red": []}}));
let out = p.apply_on(&current, &original, 0.4);
for x in [0.0, 0.25, 0.5, 0.75, 1.0] {
let want = eval(&original.curve.master, x) * 0.6 + eval(&pts(&curve), x) * 0.4;
assert!((eval(&out.curve.master, x) - want).abs() < 1e-9, "x {x}");
}
// towards the identity (an empty curve) too
assert!((eval(&out.curve.red, 0.4) - (0.5 * 0.6 + 0.4 * 0.4)).abs() < 1e-9);
}
/// The profile (and LUT) choice steps to the preset's at half amount, as every choice does
/// (#2207); from there its strength fades in from 0 %, so the look shows in proportion to the
/// amount. The same profile blends its amount from the original's, not the photo's current one.
#[test]
fn amount_fades_in_a_new_profile() {
let p = preset(json!({"profile": {"id": "lc.vivid", "amount": 150.0}}));
let base = DevelopSettings::default();
for (t, id, amount) in [(0.3, "lc.color", 100.0), (0.5, "lc.vivid", 75.0), (0.8, "lc.vivid", 120.0), (1.0, "lc.vivid", 150.0)] {
let out = p.apply_on(&base, &base, t);
assert_eq!(out.profile.id, id, "{t}");
assert!((out.profile.amount - amount).abs() < 1e-9, "{t}: amount {}", out.profile.amount);
}
assert_eq!(p.apply_on(&base, &base, 0.0), base, "0 % changes nothing");
// the same profile: its amount blends from the original's (60 → 150 at 50 % is 105), not
// from the photo's current 20
let mut original = DevelopSettings::default();
original.profile.id = "lc.vivid".into();
original.profile.amount = 60.0;
let mut current = original.clone();
current.profile.amount = 20.0;
for t in [0.3, 0.5] {
let out = p.apply_on(&current, &original, t);
assert_eq!(out.profile.id, "lc.vivid");
assert!((out.profile.amount - (60.0 + 90.0 * t)).abs() < 1e-9, "{t}: {}", out.profile.amount);
}
}
/// Switches and choices keep the original's value below half amount and take the preset's from
/// half amount up; an `enabled` switch or a style the preset changes brings its amount in from 0
/// there, and below half amount leaves the original's amount as it is.
#[test]
fn amount_steps_switches_and_choices_at_half_and_fades_in_their_amount() {
let mut original = DevelopSettings::default();
original.lens_blur.amount = 50.0;
original.optics.lens_profile = true;
let style = serde_json::to_value(crate::VignetteStyle::ColorPriority).unwrap();
let p = preset(json!({
"lens_blur": {"enabled": true, "amount": 80.0},
"treatment": "bw",
"optics": {"lens_profile": false},
"vignette": {"style": style, "amount": -40.0},
}));
let mut current = original.clone();
current.light.exposure = 1.0;
let low = p.apply_on(&current, &original, 0.25);
assert!(!low.lens_blur.enabled);
assert_eq!(low.lens_blur.amount, 50.0, "below half the original's own amount");
assert_eq!(low.treatment, original.treatment);
assert!(low.optics.lens_profile);
assert_eq!((low.vignette.style, low.vignette.amount), (original.vignette.style, original.vignette.amount));
assert_eq!(low.light.exposure, 1.0, "a setting the preset doesn't name keeps the photo's value");
let half = p.apply_on(&current, &original, 0.5);
assert!(half.lens_blur.enabled);
assert!((half.lens_blur.amount - 40.0).abs() < 1e-9, "{}", half.lens_blur.amount);
assert_eq!(half.treatment, crate::Treatment::Bw);
assert!(!half.optics.lens_profile);
assert_eq!(half.vignette.style, crate::VignetteStyle::ColorPriority);
assert!((half.vignette.amount + 20.0).abs() < 1e-9, "{}", half.vignette.amount);
assert_eq!(p.apply_on(&current, &original, 0.0), current, "0 % changes nothing");
}
/// HDR is left out of the JSON while at its defaults; its numbers still blend from the original's.
#[test]
fn amount_blends_groups_left_out_at_their_defaults() {
let p = preset(json!({"hdr": {"enabled": true, "sdr_contrast": 40.0}}));
let base = DevelopSettings::default();
let out = p.apply_on(&base, &base, 0.5);
assert!(out.hdr.enabled);
assert!((out.hdr.sdr_contrast - 20.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast);
let out = apply_partial(&base, &p.settings, 0.3);
assert!(!out.hdr.enabled);
assert!((out.hdr.sdr_contrast - 12.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast);
}
/// White balance on another scale (Kelvin against the older relative one) is in other units:
/// the original's below half amount and the preset's from half amount up, each whole with its
/// scale, never a blend of the two.
#[test]
fn amount_takes_white_balance_on_another_scale_whole() {
let kelvin = preset(json!({"wb": {"mode": "custom", "temp": 4200.0, "tint": 8.0, "scale": "kelvin"}}));
let photo = DevelopSettings::default(); // relative scale, 6500 / 0 = as shot
for t in [0.01, 0.3, 0.49] {
assert_eq!(kelvin.apply_on(&photo, &photo, t).wb, photo.wb, "{t}");
}
for t in [0.5, 0.7, 1.5] {
let out = kelvin.apply_on(&photo, &photo, t);
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4200.0, 8.0), "{t}");
}
let wb = crate::WhiteBalance { mode: crate::WbMode::Custom, temp: 5000.0, tint: 0.0, scale: crate::WbScale::Kelvin };
let photo = DevelopSettings { wb, ..DevelopSettings::default() };
// a partial without a scale is on the relative scale
let relative = preset(json!({"wb": {"temp": 7000.0, "tint": 10.0}}));
assert_eq!(relative.apply_on(&photo, &photo, 0.3).wb, photo.wb);
let out = relative.apply_on(&photo, &photo, 0.6);
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Legacy, 7000.0, 10.0));
// the same scale blends
let out = kelvin.apply_on(&photo, &photo, 0.5);
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4600.0, 4.0));
}
#[test]
fn zero_amount_mask_preset_leaves_settings_unchanged_and_can_be_applied_later() {
let photo = DevelopSettings { masks: vec![crate::Mask { id: 9, name: "Existing".into(), ..Default::default() }], ..Default::default() };
let p = preset(json!({"light": {"exposure": 1.0}, "masks": [{"name": "New", "adjust": {"amount": 80.0}}]}));
for amount in [0.0, -0.5, f64::NAN] {
let unchanged = p.apply_on(&photo, &photo, amount);
assert_eq!(unchanged, photo);
let out = p.apply(&unchanged, 1.0);
assert_eq!(out.light.exposure, 1.0);
assert_eq!(out.masks.len(), 2);
assert_eq!(out.masks[0], photo.masks[0]);
assert_eq!(out.masks[1].name, "New");
assert_eq!(out.masks[1].adjust.amount, 80.0);
}
// with an import state, 0 % is that state for the settings the preset names (#2207), and still
// adds no mask
let mut current = photo.clone();
current.light.exposure = 2.0;
current.curve.master = pts(&[(0.0, 0.1), (1.0, 0.9)]);
let original = DevelopSettings { light: crate::Light { exposure: -0.5, ..Default::default() }, ..Default::default() };
let q =
preset(json!({"light": {"exposure": 1.0}, "curve": {"master": pts(&[(0.0, 0.0), (0.5, 0.7), (1.0, 1.0)])}, "masks": [{"name": "New"}]}));
let out = q.apply_on(&current, &original, 0.0);
assert_eq!(out.light.exposure, -0.5);
assert!(out.curve.master.is_empty(), "the original's curve, point for point");
assert_eq!(out.masks, current.masks);
}
/// Every leaf of `v` that is not a number (and every list's length), by path.
fn non_numbers(v: &Value, path: &str, out: &mut Vec<(String, Value)>) {
match v {
Value::Object(o) => o.iter().for_each(|(k, v)| non_numbers(v, &format!("{path}/{k}"), out)),
Value::Array(a) => {
out.push((format!("{path}#len"), Value::from(a.len())));
a.iter().enumerate().for_each(|(i, v)| non_numbers(v, &format!("{path}/{i}"), out));
}
Value::Number(_) => {}
v => out.push((path.to_string(), v.clone())),
}
}
/// Across the whole Amount range a preset has one step, at half amount (#2207): below it the
/// switches, choices and lists stay as at 1 %, from it as at 50 %; the numbers and tone curves
/// move in proportion to the amount throughout, and the strength of a changed choice fades in
/// from 0 once the choice is the preset's.
#[test]
fn amount_has_one_step_at_half_and_blends_the_rest() {
let mut a = DevelopSettings::default();
a.profile.id = "lc.vivid".into();
a.profile.amount = 140.0;
a.treatment = crate::Treatment::Bw;
a.light.exposure = 0.8;
a.curve.master = pts(&[(0.0, 0.0), (0.3, 0.2), (0.7, 0.8), (1.0, 1.0)]);
a.curve.green = pts(&[(0.0, 0.05), (1.0, 0.9)]);
a.grain.amount = 30.0;
a.grain.seed = 777;
a.vignette.style = crate::VignetteStyle::ColorPriority;
a.vignette.amount = -25.0;
a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0, ..Default::default() };
a.optics.remove_ca = true;
let p = Preset::from_settings("p", "P", "User", &a, &SettingsGroup::default_copy());
let mut original = DevelopSettings::default();
original.curve.master = pts(&[(0.0, 0.1), (0.5, 0.45), (1.0, 1.0)]);
original.light.exposure = -0.4;
let mut current = original.clone();
current.light.exposure = 2.0;
let leaves = |t: f64| {
let mut v = Vec::new();
non_numbers(&p.apply_on(&current, &original, t).to_json(), "", &mut v);
v
};
let (below, above) = (leaves(0.01), leaves(0.5));
assert_ne!(below, above, "the choices step at half amount");
let y0 = eval(&original.curve.master, 0.3);
for i in 2..=200 {
let t = f64::from(i) / 100.0;
let out = p.apply_on(&current, &original, t);
if i != 100 {
// (at exactly 100 % the preset is merged as it is: its own curve points)
assert_eq!(leaves(t), if t < 0.5 { below.clone() } else { above.clone() }, "{t}: a switch, choice or list moved off its side");
}
let want = (-0.4 + 1.2 * t).min(5.0);
assert!((out.light.exposure - want).abs() < 1e-9, "{t}: exposure {}", out.light.exposure);
let (profile, blur) =
if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), (60.0 * t).min(100.0)) };
assert!((out.profile.amount - profile).abs() < 1e-9, "{t}: profile amount {}", out.profile.amount);
assert!((out.lens_blur.amount - blur).abs() < 1e-9, "{t}: lens blur amount {}", out.lens_blur.amount);
let y = eval(&out.curve.master, 0.3);
let want = (y0 + (0.2 - y0) * t).clamp(0.0, 1.0);
assert!((y - want).abs() < 1e-9, "{t}: curve y(0.3) {y}, want {want}");
}
}
/// A preset changes only the settings it names: a setting in a group it styles but does not
/// name keeps the photo's value, and so does a whole group it leaves out.
#[test]
+1
View File
@@ -14,6 +14,7 @@ pub mod curves;
pub mod dcp_profiles;
pub(crate) mod denoise;
mod develop;
pub(crate) use develop::{prepare_photo_for_wb_partial, wb_partial_names_one_field};
mod edit;
mod export;
pub(crate) mod face_detect;
+13 -23
View File
@@ -120,13 +120,11 @@ fn wb_mode_ignores_its_numbers(mode: WbMode, info: &lightcraft_pipeline::SourceI
/// numbers, neither, or a mode of its own. [`merge_settings_for_photo`] and `preset.apply` both start here, and
/// both finish with `normalize_wb` so the photo ends on the scale it is edited on.
pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, info: &lightcraft_pipeline::SourceInfo) -> Option<DevelopSettings> {
let mut d = (*d).clone();
let wb = partial.get("wb").and_then(Value::as_object);
// the partial names one of the two numbers, and not both or neither
let one_field = wb.is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint"));
if !one_field {
if !wb_partial_names_one_field(partial) {
return None;
}
let mut d = (*d).clone();
let wb = partial.get("wb").and_then(Value::as_object);
// a photo whose source is edited in Kelvin is the one with two scales to trip over
let kelvin_source = info.raw && !info.relative_wb;
// the scale the partial's numbers are written on: an unmentioned scale means the relative scale, as `merged` reads it
@@ -154,6 +152,12 @@ pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value,
Some(d)
}
/// Whether `partial`'s white balance names one of the two numbers, and not both or neither: the partials
/// [`prepare_photo_for_wb_partial`] prepares the photo for.
pub(crate) fn wb_partial_names_one_field(partial: &Value) -> bool {
partial.get("wb").and_then(Value::as_object).is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint"))
}
/// Merge a partial settings JSON into a photo's settings (issue #2910). `DevelopSettings::merged` keeps a white
/// balance that names no scale on the relative scale; on a photo edited in Kelvin the field the partial does not
/// name (a partial with only `temp`, or only `tint`) would then be read on the other scale, giving a white neither
@@ -1323,24 +1327,10 @@ pub fn specs() -> Vec<CommandSpec> {
let ops = ids
.iter()
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
.filter_map(|(id, d)| {
// a hand-written preset may name one white balance number only, and then it means the same as
// a partial: bring the photo onto that scale first, with its own as-shot white, and put the
// result back on the scale the photo is edited on (issue #2910) — the merge `develop.merge` uses
let info = s.source_info(id);
let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info);
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d);
// Amount is measured from the import look only when the photo has one.
// Otherwise the current settings (on the partial's WB scale) are its baseline.
let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults());
let prepared_import =
imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone()));
let original = prepared_import.as_ref().unwrap_or(base);
let mut next = preset.apply_on(base, original, amount);
if on_kelvin_scale {
lightcraft_pipeline::local::normalize_wb(&mut next, &info);
}
.filter_map(|(id, _)| {
// the same composition, white balance preparation and final scale as previews and import
// (`Session::preset_applied`, issues #2159 and #2910)
let next = s.preset_applied(id, &preset, amount)?;
s.develop_op(id, next, &format!("Preset: {}", preset.name))
})
.collect::<Vec<_>>();
+59 -33
View File
@@ -6,7 +6,7 @@ use super::{
};
use std::borrow::Cow;
/// Unsharp mask on an 8-bit image (separable box-blur approximation of a small Gaussian).
/// Output sharpening of an 8-bit image: an unsharp mask on its luma ([`unsharp`]).
pub fn output_sharpen(img: &mut Rgba8, target: SharpenFor, amount: SharpenAmount) {
if !sharpens(img.width, img.height, target) {
return;
@@ -37,7 +37,8 @@ pub fn output_sharpen_deep(img: &mut DeepImage, target: SharpenFor, amount: Shar
}
}
DeepSamples::F32(v) => {
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect();
// A NaN or infinite sample would poison its neighbours' blur and local range; treat it as black.
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]].map(|x| if x.is_finite() { x } else { 0.0 })).collect();
if let Some(out) = unsharp(w, h, &src, target, amount) {
for (d, s) in v.iter_mut().zip(out.as_flattened()) {
*d = s.max(0.0);
@@ -52,47 +53,72 @@ fn sharpens(w: usize, h: usize, target: SharpenFor) -> bool {
target != SharpenFor::None && w >= 3 && h >= 3
}
/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done.
/// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share
/// of their difference: enough for crisp edges, too little for the light and dark rims (halos)
/// a plain unsharp mask draws along strong edges.
const SHARPEN_OVERSHOOT: f32 = 0.1;
/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done: an unsharp mask
/// at the output's own pixel scale (a Gaussian of radius `sigma` output pixels), on luma only (no
/// colour fringes), with its overshoot past the local range limited ([`SHARPEN_OVERSHOOT`]). Print
/// media blur more than a screen and get a wider, stronger mask. The values may be on any scale.
fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: SharpenAmount) -> Option<Vec<[f32; 3]>> {
let (radius, base) = match target {
let (sigma, base) = match target {
SharpenFor::None => return None,
SharpenFor::Screen => (1usize, 0.35f32),
SharpenFor::Matte => (2, 0.6),
SharpenFor::Glossy => (1, 0.5),
SharpenFor::Screen => (0.7f32, 0.65f32),
SharpenFor::Glossy => (0.8, 0.85),
SharpenFor::Matte => (1.0, 1.05),
};
let k = base
* match amount {
SharpenAmount::Low => 0.6,
SharpenAmount::Low => 0.5,
SharpenAmount::Standard => 1.0,
SharpenAmount::High => 1.5,
SharpenAmount::High => 1.6,
};
if w < 3 || h < 3 {
return None;
}
let r = radius as isize;
let box_pass = |inp: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> {
let mut out = vec![[0.0; 3]; inp.len()];
// rows in parallel: each output pixel is computed on its own, so the bits don't depend on the split
lightcraft_raster::par_rows(&mut out, w, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
let mut acc = [0.0f32; 3];
for d in -r..=r {
let (sx, sy) = if horizontal {
((x as isize + d).clamp(0, w as isize - 1) as usize, y)
} else {
(x, (y as isize + d).clamp(0, h as isize - 1) as usize)
};
let p = inp[sy * w + sx];
acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]];
}
let n = (2 * r + 1) as f32;
*o = acc.map(|v| v / n);
}
});
out
};
let blur = box_pass(&box_pass(src, true), false);
Some(src.iter().zip(&blur).map(|(s, b)| std::array::from_fn(|c| s[c] + (s[c] - b[c]) * k)).collect())
let luma: Vec<f32> = src.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect();
let r = (3.0 * sigma).ceil() as isize;
let taps: Vec<f32> = (-r..=r).map(|d| (-((d * d) as f32) / (2.0 * sigma * sigma)).exp()).collect();
let norm: f32 = taps.iter().sum();
let taps: Vec<f32> = taps.iter().map(|t| t / norm).collect();
let gauss = |acc: f32, d: isize, v: f32| acc + v * taps[(d + r) as usize];
let blur = separable(&separable(&luma, w, h, r, true, 0.0, gauss), w, h, r, false, 0.0, gauss);
let lo = |acc: f32, _: isize, v: f32| acc.min(v);
let hi = |acc: f32, _: isize, v: f32| acc.max(v);
let lo = separable(&separable(&luma, w, h, 1, true, f32::INFINITY, lo), w, h, 1, false, f32::INFINITY, lo);
let hi = separable(&separable(&luma, w, h, 1, true, f32::NEG_INFINITY, hi), w, h, 1, false, f32::NEG_INFINITY, hi);
Some(
src.iter()
.enumerate()
.map(|(i, p)| {
let (y, margin) = (luma[i], (hi[i] - lo[i]) * SHARPEN_OVERSHOOT);
// max/min rather than clamp: never panics, even on bounds a non-finite input left inverted or NaN.
let sharp = (y + (y - blur[i]) * k).max(lo[i] - margin).min(hi[i] + margin);
p.map(|v| v + sharp - y)
})
.collect(),
)
}
/// One pass of a separable filter over a `w × h` plane: each value folds (`f(acc, offset, value)`,
/// from `init`) its neighbours up to `reach` away along a row (`horizontal`) or a column, edges repeated.
fn separable(inp: &[f32], w: usize, h: usize, reach: isize, horizontal: bool, init: f32, f: impl Fn(f32, isize, f32) -> f32 + Sync) -> Vec<f32> {
let mut out = vec![0.0; inp.len()];
lightcraft_raster::par_rows(&mut out, w, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
*o = (-reach..=reach).fold(init, |acc, d| {
let i = if horizontal {
y * w + (x as isize + d).clamp(0, w as isize - 1) as usize
} else {
(y as isize + d).clamp(0, h as isize - 1) as usize * w + x
};
f(acc, d, inp[i])
});
}
});
out
}
/// Encode a rendered display-referred image according to `o` (its pixels must already be in
+59 -10
View File
@@ -209,7 +209,7 @@ fn sharpen_increases_edge_contrast() {
assert!(img.data[3][0] < 80 && img.data[4][0] > 170);
}
/// Output sharpening's pixels for every target and amount, pinned (its box blurs run row-parallel, which must not
/// Output sharpening's pixels for every target and amount, pinned (its separable passes run row-parallel, which must not
/// change a bit), on 8- and 16-bit images; with no target the image is left as it is.
#[test]
fn sharpened_pixels_are_pinned() {
@@ -234,17 +234,66 @@ fn sharpened_pixels_are_pinned() {
assert_eq!(img, test_image());
}
const SHARPENED: [u64; 9] = [
0x1494_273e_0bdc_a61c,
0x3fbb_40c4_74f4_b0c3,
0xa27f_8ff5_82a0_99f9,
0x6550_6571_a38d_4d9f,
0x5e28_f4f3_fc8a_9685,
0xdc2b_6f65_9138_3b1d,
0x8ce6_f0b8_d8ed_8026,
0x92d8_12e7_4b2e_81fe,
0x139f_6d78_b1f2_a910,
0x1a04_82d5_edaa_37c8,
0xcb78_18b7_938e_beda,
0x0490_bb9e_2b64_3d00,
0x1662_0293_b8a2_2538,
0xa3f7_7957_1af3_1b39,
0x30b0_919c_7c6a_705b,
0x27ef_4e5b_42e6_d1ed,
0x1dc3_3b96_b2f9_c1b6,
0xdab7_1280_a47a_ffeb,
];
/// Output sharpening (#2970): each step crisper than the one before, Screen / Standard roughly a
/// typical web export's, and no wide light or dark rim along a strong edge (overshoot stays
/// within a tenth of the edge's contrast). Colour is left alone: a grey edge stays grey.
#[test]
fn sharpen_steps_are_crisper_without_halos() {
let edge = || {
let mut img = Rgba8::new(32, 8);
for (i, p) in img.data.iter_mut().enumerate() {
let v = if i % 32 < 16 { 40 } else { 220 };
*p = [v, v, v, 255];
}
img
};
let mut last = 0u8;
for amount in [SharpenAmount::Low, SharpenAmount::Standard, SharpenAmount::High] {
let mut img = edge();
output_sharpen(&mut img, SharpenFor::Screen, amount);
let (dark, light) = (img.data[15], img.data[16]);
let spread = (40 - dark[0]).max(light[0] - 220);
assert!(spread >= last && spread > 0, "{amount:?}: {dark:?} {light:?}");
assert!(dark[0] >= 40 - 18 && light[0] <= 220 + 18, "{amount:?}: {dark:?} {light:?}");
assert!(dark[0] == dark[1] && dark[1] == dark[2] && light[0] == light[2], "grey stays grey");
assert_eq!(img.data[0][0], 40, "{amount:?}: flat areas untouched");
last = spread;
}
let mut none = edge();
output_sharpen(&mut none, SharpenFor::None, SharpenAmount::High);
assert_eq!(none.data, edge().data);
}
/// Output sharpening of a float image with NaN and infinite samples does not panic (#2970 review):
/// they are sharpened as black and every result is finite.
#[test]
fn sharpen_deep_survives_non_finite_samples() {
let (nan, inf) = (f32::NAN, f32::INFINITY);
let mut samples = vec![0.5f32; 27];
samples[..9].copy_from_slice(&[nan, nan, nan, inf, inf, inf, -inf, nan, inf]);
samples[12] = nan;
samples[20] = inf;
for target in [SharpenFor::Screen, SharpenFor::Glossy, SharpenFor::Matte] {
let mut img = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(samples.clone()) };
output_sharpen_deep(&mut img, target, SharpenAmount::High);
let DeepSamples::F32(out) = &img.samples else { panic!("expected F32 samples") };
assert!(out.iter().all(|v| v.is_finite() && *v >= 0.0), "{target:?}: {out:?}");
}
let mut all_nan = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(vec![nan; 27]) };
output_sharpen_deep(&mut all_nan, SharpenFor::Screen, SharpenAmount::Standard);
}
/// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject`
/// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of
/// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`.
+21 -3
View File
@@ -121,6 +121,23 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option<lightcraft_develop
Some(lightcraft_pipeline::optics::reorient_lens(&lens, raw.orientation, cw, ch))
}
fn xmp_has_rating(x: &str) -> bool {
lightcraft_meta::parse_xmp(x).ok().and_then(|d| d.metadata.rating).is_some()
}
fn embedded_or_exif_xmp(bytes: &[u8], m: &lightcraft_meta::Metadata) -> Option<String> {
match lightcraft_meta::embedded(bytes).xmp {
Some(x) if !xmp_has_rating(&x) && m.rating.is_some() => {
let fresh = lightcraft_meta::write_xmp(m, None);
lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() })
.ok()
.or(Some(x))
}
Some(x) => Some(x),
None => m.rating.map(|_| lightcraft_meta::write_xmp(m, None)),
}
}
fn ext_upper(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default()
}
@@ -133,6 +150,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string());
let m = lightcraft_meta::extract(bytes);
let (meta, captured) = meta_of(&m);
let xmp = embedded_or_exif_xmp(bytes, &m);
if lightcraft_raw::probe(bytes).is_some() {
let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) {
Ok(r) => r,
@@ -149,7 +167,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
meta,
as_shot_wb: None,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
xmp,
orientation: m.orientation,
preview_only: Some(why),
..Default::default()
@@ -184,7 +202,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
meta,
as_shot_wb,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
xmp,
orientation: Some(raw.orientation),
preview_only: None,
});
@@ -230,7 +248,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
as_shot_wb: None,
content_hash,
embedded_lens: None,
xmp: None,
xmp,
orientation: m.orientation,
preview_only: None,
})
+1 -1
View File
@@ -296,7 +296,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
}
}
if let Some(preset) = &opts.preset {
let d = std::sync::Arc::new(preset.apply(&p.develop, 1.0));
let d = std::sync::Arc::new(crate::presets::apply_preset_to_photo(preset, &p.develop, None, 1.0, &crate::media::source_info(&p)));
let label = format!("Preset: {}", preset.name);
p.develop = d.clone();
p.edited = Some(now.clone());
+1 -1
View File
@@ -87,7 +87,7 @@ pub fn apply_import_defaults(s: &Session, p: &mut Photo) {
let preset = s.import_defaults.preset_for(raw, &p.meta.camera).and_then(|id| s.presets.iter().find(|x| x.id == id));
match preset {
Some(pr) => {
let look = std::sync::Arc::new(pr.apply(&base, 1.0));
let look = std::sync::Arc::new(crate::presets::apply_preset_to_photo(pr, &base, None, 1.0, &crate::media::source_info(p)));
p.develop = look.clone();
p.import_look = (*look != base).then_some(look);
}
+40 -10
View File
@@ -372,22 +372,49 @@ impl ImportJob {
// when the import makes a record of it, once it is read as a file import reads it)
let duplicate_of =
info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing)));
// the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files
// the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files
// and names the copy when the file itself has none (a skipped duplicate needs only that time)
let raw = info.kind == MediaKind::Raw;
let packet = if duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates {
let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP");
let skip_sidecar = duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates;
let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
let mut embedded_sidecar = if skip_sidecar {
None
} else {
found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw))
info.xmp.as_deref().filter(|_| has_embedded_xmp).and_then(|x| match crate::sidecar::parse_sidecar(x, target) {
Ok(sc) => Some(sc),
Err(e) => {
log::warn!("import {path}: embedded XMP: {e}");
None
}
})
};
let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
Ok(sc) => Some(sc),
Err(e) => {
log::warn!("import {path}: XMP: {e}");
None
// Embedded XMP on a rendered file (JPEG, TIFF, PNG, WebP) has develop adjustments
// already baked into the pixels; only raws/DNGs keep foreign develop settings from embedded XMP.
if !raw && let Some(sc) = &mut embedded_sidecar {
sc.develop = None;
sc.warnings.clear();
}
let external_sidecar = if skip_sidecar {
None
} else {
found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
Ok(sc) => Some(sc),
Err(e) => {
log::warn!("import {path}: XMP: {e}");
None
}
})
};
let sidecar = match (embedded_sidecar, external_sidecar) {
(Some(mut embedded), Some(external)) => {
embedded.override_with(external);
Some(embedded)
}
});
(Some(embedded), None) => Some(embedded),
(None, Some(external)) => Some(external),
(None, None) => None,
};
if info.captured.is_none() {
info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone());
}
@@ -416,6 +443,9 @@ impl ImportJob {
let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now);
q.captured = info.captured.clone();
q.meta = info.meta.clone();
if let Some(sc) = &sidecar {
crate::sidecar::merge_into(&mut q, sc, &self.now);
}
let name = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) {
let Some(seq) = self.seq else {
self.done.fetch_add(1, Relaxed);
+4 -1
View File
@@ -601,7 +601,10 @@ impl crate::Session {
}
job.request.space = space;
job.request.depth = depth;
job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db);
// an export shrinks with a sharp filter: a preview's soft one leaves a small export blurred (#2970)
job.request.downscale = lightcraft_pipeline::Downscale::Sharp;
job.key ^=
(space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db) ^ 0x9e37_79b9_7f4a_7c15;
Ok(job)
}
+59 -15
View File
@@ -430,29 +430,72 @@ impl Session {
/// apply Auto Settings / the auto crop. Returns `{id, path, …info}`.
pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result<Value> {
let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1;
// a new file under a free name (never replacing one), complete and synced before it appears
let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng)
.map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))?
.to_string_lossy()
.to_string();
let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?;
let id = report
.imported
.first()
.copied()
.map(PhotoId)
.ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?;
if job.finish.stack {
let output_hash = lightcraft_preview::hash_bytes(&out.dng).to_string();
// Import deduplicates by content. Reuse an existing merge only while its live source has
// matching bytes; stale, missing or deleted rows fail before another file is published.
let candidates: Vec<(PhotoId, String, bool)> = self
.catalog
.photos()
.filter_map(|p| {
if p.content_hash.as_deref() != Some(output_hash.as_str()) {
return None;
}
let Source::File { path } = &p.source else { return None };
Some((p.id, path.clone(), p.deleted))
})
.collect();
let valid_existing = candidates
.iter()
.find(|(_, path, deleted)| {
if *deleted {
return false;
}
let bytes = match &self.media.file_bytes {
Some(read) => read(path).ok(),
None => std::fs::read(path).ok(),
};
bytes.is_some_and(|bytes| lightcraft_preview::hash_bytes(&bytes).to_string() == output_hash)
})
.cloned();
let (id, path, reused) = if let Some((id, path, _)) = valid_existing {
(id, path, true)
} else if let Some((id, path, deleted)) = candidates.first() {
let state = if *deleted { "deleted" } else { "missing or changed" };
return Err(EngineError::Other(format!(
"existing merge result {id:?} has a {state} source at {path}; relink or remove it before repeating the merge"
)));
} else {
// A new file under a free name (never replacing one), complete and synced before it appears.
let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng)
.map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))?
.to_string_lossy()
.to_string();
let report = match crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add) {
Ok(report) => report,
Err(e) => {
let _ = std::fs::remove_file(&path);
return Err(e);
}
};
if let Some(id) = report.imported.first().copied().map(PhotoId) {
(id, path, false)
} else {
let _ = std::fs::remove_file(&path);
return Err(EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)));
}
};
if !reused && job.finish.stack {
let sources: Vec<PhotoId> = job.sources.iter().map(|(p, _)| *p).collect();
if let Some(op) = self.catalog.stack_with_ops(id, &sources) {
self.commit("Stack with Sources", op)?;
}
}
self.selection = crate::Selection::single(id);
if job.finish.auto_settings {
if !reused && job.finish.auto_settings {
self.execute("develop.auto", &json!({}))?;
}
if let Some(c) = out.crop
if !reused
&& let Some(c) = out.crop
&& let Some(d) = self.develop_of(id)
{
let mut d = (*d).clone();
@@ -463,6 +506,7 @@ impl Session {
info["id"] = json!(id.0);
info["path"] = json!(path);
info["bytes"] = json!(out.dng.len());
info["reused"] = json!(reused);
Ok(info)
}
+42 -10
View File
@@ -178,21 +178,18 @@ impl Session {
/// from an XMP sidecar or a catalog import, which record none) composes them on its current
/// settings instead, since the camera defaults are not its import state. Either way, the
/// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply`
/// command and the UI's hover previews share this, so hovering shows exactly what a click commits.
/// command and the UI's hover previews and thumbnails share this, so hovering shows exactly what
/// a click commits, white balance preparation included ([`apply_preset_to_photo`]).
pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option<DevelopSettings> {
let current = self.develop_of(id)?;
let photo = self.catalog.photo(id)?;
// The original is read only below 100 %: the panel asks for every visible row at 100 % on
// every frame, and then neither the import state nor a copy of the photo's settings is built.
let look;
let original: &DevelopSettings = match &photo.import_look {
Some(_) if (amount - 1.0).abs() >= 1e-9 => {
look = photo.import_defaults();
&look
}
_ => &current,
};
Some(preset.apply_on(&current, original, amount))
let original = photo.import_look.as_ref().filter(|_| (amount - 1.0).abs() >= 1e-9).map(|_| photo.import_defaults());
// the photo's source is read only for a preset that needs it (one white balance number):
// the panel asks for every visible row on every frame
let info = if crate::cmd::wb_partial_names_one_field(&preset.settings) { self.source_info(id) } else { Default::default() };
Some(apply_preset_to_photo(preset, &current, original.as_ref(), amount, &info))
}
/// Add imported presets. Identical presets (same name, group and settings) already present are
@@ -634,6 +631,41 @@ impl Session {
}
}
/// Apply `preset` to a photo's settings `current` at `amount` (1.0 = 100 %), composing on
/// `original` (the photo's import state; `None`: `current` itself, see [`Preset::apply_on`]): the
/// one path every caller that puts a preset on a photo takes (the `preset.apply` command,
/// thumbnails and hover previews through [`Session::preset_applied`], importing with a preset,
/// import defaults), so all of them show and store the same result.
///
/// `info` is the photo's source: a hand-written preset may name one white balance number only, and
/// then it means what a one-field partial means (`prepare_photo_for_wb_partial`, shared with
/// `develop.merge`, issue #2910): the photo (and its original) are brought onto the preset's scale
/// with the photo's own as-shot white first, and the result is put back on the scale the photo is
/// edited on. Without an import state a zero (or negative) `amount` returns `current` exactly as it
/// was, before any preparation, so a preview at nothing never turns As Shot into Custom; with one,
/// 0 % is the import state's value for each setting the preset names ([`Preset::apply_on`]). A NaN
/// `amount` changes nothing.
pub fn apply_preset_to_photo(
preset: &Preset,
current: &DevelopSettings,
original: Option<&DevelopSettings>,
amount: f64,
info: &lightcraft_pipeline::SourceInfo,
) -> DevelopSettings {
if amount.is_nan() || (amount <= 0.0 && original.is_none()) {
return current.clone();
}
let prepared = crate::cmd::prepare_photo_for_wb_partial(current, &preset.settings, info);
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
let base = prepared.as_ref().unwrap_or(current);
let prepared_original = original.map(|o| crate::cmd::prepare_photo_for_wb_partial(o, &preset.settings, info).unwrap_or_else(|| o.clone()));
let mut next = preset.apply_on(base, prepared_original.as_ref().unwrap_or(base), amount);
if on_kelvin_scale {
lightcraft_pipeline::local::normalize_wb(&mut next, info);
}
next
}
#[cfg(test)]
mod tests {
use super::*;
+72
View File
@@ -379,6 +379,78 @@ impl SidecarData {
self
}
/// Overlay fields supplied by `other` onto `self`: any field present in `other`
/// replaces the one in `self`.
pub fn override_with(&mut self, other: SidecarData) {
if other.rating.is_some() {
self.rating = other.rating;
if self.flag == Some(Flag::Reject) && other.flag.is_none() {
self.flag = Some(Flag::None);
}
}
if other.flag.is_some() {
self.flag = other.flag;
}
if other.label.is_some() {
self.label = other.label;
self.label_text = other.label_text;
}
if other.title.is_some() {
self.title = other.title;
}
if other.caption.is_some() {
self.caption = other.caption;
}
if other.copyright.is_some() {
self.copyright = other.copyright;
}
if other.copyright_marked.is_some() {
self.copyright_marked = other.copyright_marked;
}
if other.usage_terms.is_some() {
self.usage_terms = other.usage_terms;
}
if other.copyright_url.is_some() {
self.copyright_url = other.copyright_url;
}
if other.creator.is_some() {
self.creator = other.creator;
}
if other.location.is_some() {
self.location = other.location;
}
if other.city.is_some() {
self.city = other.city;
}
if other.state.is_some() {
self.state = other.state;
}
if other.country.is_some() {
self.country = other.country;
}
if other.alt_text.is_some() {
self.alt_text = other.alt_text;
}
if other.extended_description.is_some() {
self.extended_description = other.extended_description;
}
if other.keywords.is_some() {
self.keywords = other.keywords;
}
if other.regions.is_some() {
self.regions = other.regions;
}
if other.captured.is_some() {
self.captured = other.captured;
}
if other.develop.is_some() {
self.develop = other.develop;
self.warnings = other.warnings;
} else {
self.warnings.extend(other.warnings);
}
}
/// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet
/// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]).
/// Only then is the file read ([`file_orientation`]).
+113
View File
@@ -470,3 +470,116 @@ fn one_field_wb_preset_apply_keeps_the_other_field_on_its_scale() {
let back = (*s.develop_of(kelvin).unwrap()).clone();
assert_eq!(back.wb, look.wb, "a preset made from the photo puts its whole white balance back: {:?} vs {:?}", back.wb, look.wb);
}
/// A preset applied to a photo goes through one function whether it is the `preset.apply` command, a thumbnail or
/// hover preview, or an import: a hand-written preset naming one white balance number (either one, on either
/// scale) gives the same settings in all three, on a photo edited in Kelvin and on one edited relative to its
/// as-shot white. Before, the previews (`Session::preset_applied`) and import called the source-free
/// `Preset::apply_on` / `Preset::apply` directly, which stored the number without the photo's as-shot white.
#[test]
fn one_field_wb_preset_gives_the_same_result_in_command_preview_and_import() {
use lightcraft_catalog::{MediaKind, Op, Photo, Source};
use lightcraft_develop::{Preset, WbMode, WbScale};
let as_shot = (4986.0, -2.0);
let photo = |camera: &str| {
let mut p = Photo::new(
lightcraft_catalog::PhotoId(1),
Source::File { path: "/photos/one-field.arw".into() },
"one-field.arw",
"ARW",
64,
64,
"2026-01-01T00:00:00",
);
p.kind = MediaKind::Raw;
p.meta.camera = camera.into();
p.as_shot_wb = Some(as_shot);
p.develop = std::sync::Arc::new(p.camera_defaults());
p
};
let one_field = |name: &str, wb: serde_json::Value| Preset {
id: format!("user.{name}"),
name: name.into(),
group: "User".into(),
settings: json!({ "wb": wb }),
favorite: false,
builtin: false,
};
let presets = [
one_field("temp-only", json!({"temp": 5800.0})),
one_field("tint-only", json!({"tint": 9.0})),
// the reverse scale: numbers written in Kelvin on a photo edited relative to as shot, and the relative
// scale named outright on a photo edited in Kelvin
one_field("kelvin-temp", json!({"scale": "kelvin", "temp": 6500.0})),
one_field("kelvin-tint", json!({"scale": "kelvin", "tint": 6.0})),
one_field("relative-temp", json!({"scale": "legacy", "temp": 6800.0})),
];
for (camera, kelvin_photo) in [("SONY ILCE-7M3", true), ("Nobody X1", false)] {
assert_eq!(photo(camera).relative_wb(), !kelvin_photo, "{camera}");
for preset in &presets {
let mut s = Session::new();
let p = photo(camera);
let id = p.id;
s.catalog.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
s.presets.push(preset.clone());
let why = format!("{camera}, {}", preset.name);
let before = (*s.develop_of(id).unwrap()).clone();
assert_eq!(before.wb.mode, WbMode::AsShot, "{why}");
// preview / hover
let preview = s.preset_applied(id, preset, 1.0).unwrap();
// command
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap();
s.execute("preset.apply", &json!({"id": preset.id})).unwrap();
let command = (*s.develop_of(id).unwrap()).clone();
// import (the photo is not in a catalog yet)
let mut imported = p;
s.import_defaults.raw_preset = Some(preset.id.clone());
crate::import::apply_import_defaults(&s, &mut imported);
assert_eq!(preview, command, "{why}: preview and command");
assert_eq!(*imported.develop, command, "{why}: import and command");
assert_eq!(command.wb.mode, WbMode::Custom, "{why}: the preset's number replaces As Shot: {:?}", command.wb);
// a photo edited in Kelvin ends there; a relative one keeps the scale the preset names (as `develop.merge` does)
let want_scale = if kelvin_photo || preset.name.starts_with("kelvin") { WbScale::Kelvin } else { WbScale::Legacy };
assert_eq!(command.wb.scale, want_scale, "{why}: the photo stays on the scale it is edited on: {:?}", command.wb);
assert_ne!(command.wb, before.wb, "{why}");
}
}
}
/// Zero Amount changes nothing, and not by being applied and undone: the photo keeps As Shot mode and every
/// setting, through the command and the preview, even for a preset whose preparation would write Custom values.
#[test]
fn zero_amount_preset_keeps_as_shot_mode_and_settings() {
use lightcraft_catalog::{MediaKind, Op, Photo, Source};
use lightcraft_develop::{Preset, WbMode};
let mut s = Session::new();
let id = s.catalog.alloc_photo_id();
let mut p = Photo::new(id, Source::File { path: "/photos/zero.arw".into() }, "zero.arw", "ARW", 64, 64, "2026-01-01T00:00:00");
p.kind = MediaKind::Raw;
p.meta.camera = "SONY ILCE-7M3".into();
p.as_shot_wb = Some((4986.0, -2.0));
p.develop = std::sync::Arc::new(p.camera_defaults());
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
let preset = Preset {
id: "user.zero".into(),
name: "Zero".into(),
group: "User".into(),
settings: json!({"wb": {"temp": 5800.0}, "light": {"exposure": 1.0}}),
favorite: false,
builtin: false,
};
s.presets.push(preset.clone());
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap();
let before = (*s.develop_of(id).unwrap()).clone();
assert_eq!(before.wb.mode, WbMode::AsShot);
for amount in [0.0, -1.0, f64::NAN] {
assert_eq!(crate::presets::apply_preset_to_photo(&preset, &before, None, amount, &s.source_info(id)), before, "preview at {amount}");
assert_eq!(s.preset_applied(id, &preset, amount).unwrap(), before, "panel preview at {amount}");
}
s.execute("preset.apply", &json!({"id": preset.id, "amount": 0})).unwrap();
let after = (*s.develop_of(id).unwrap()).clone();
assert_eq!(after, before);
assert_eq!(after.wb.mode, WbMode::AsShot);
}
+1 -1
View File
@@ -728,7 +728,7 @@ fn a_date_folder_inside_the_library_can_be_renamed_but_the_librarys_own_folders_
assert_eq!(r["relinked"], 1, "the photo inside is relinked");
assert!(lib.join("Originals/Beach").is_dir(), "the imported date folder is renamed");
assert!(!Path::new(&day).exists());
let moved = lib.join("Originals/Beach/a.jpg");
let moved = lib.join("Originals").join("Beach").join("a.jpg");
assert_eq!(paths(&s), [moved.to_string_lossy().to_string()], "the catalog follows the photo");
assert!(moved.is_file());
s.execute("edit.undo", &json!({})).unwrap();
+289
View File
@@ -3519,6 +3519,295 @@ fn presets_apply_the_imported_profile_they_name() {
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_preserves_embedded_xmp_rating_and_label() {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-xmp-rating-test");
let px = [128u8; 40 * 30 * 3];
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="5" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("photo.jpg"), &bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 1);
let p = s.catalog.photos().next().unwrap();
assert_eq!(p.rating, 5);
assert_eq!(p.flag, lightcraft_catalog::Flag::None);
assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue));
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_preserves_embedded_exif_rating() {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-exif-rating-test");
let px = [128u8; 40 * 30 * 3];
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() });
let meta = EncodeMeta { exif: Some(&exif), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("exif_rating.jpg"), &bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.join("exif_rating.jpg").to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 1);
let p = s.catalog.photos().next().unwrap();
assert_eq!(p.rating, 3);
assert_eq!(p.flag, lightcraft_catalog::Flag::None);
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_preserves_embedded_rejected_rating() {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-rejected-rating-test");
let px = [128u8; 40 * 30 * 3];
// Case 1: EXIF rating -1
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(-1), ..Default::default() });
let meta = EncodeMeta { exif: Some(&exif), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("exif_rejected.jpg"), &bytes).unwrap();
// Case 2: XMP rating -1
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="-1"/></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("xmp_rejected.jpg"), &bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 2);
let exif_p = s.catalog.photos().find(|p| p.file_name == "exif_rejected.jpg").unwrap();
assert_eq!(exif_p.rating, 0);
assert_eq!(exif_p.flag, lightcraft_catalog::Flag::Reject);
let xmp_p = s.catalog.photos().find(|p| p.file_name == "xmp_rejected.jpg").unwrap();
assert_eq!(xmp_p.rating, 0);
assert_eq!(xmp_p.flag, lightcraft_catalog::Flag::Reject);
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_preserves_embedded_xmp_png_and_webp() {
use lightcraft_catalog::ColorLabel;
use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png, encode_webp_lossless};
let src = temp_dir("embedded-xmp-png-webp-test");
let px = [128u8; 40 * 30 * 3];
// PNG with embedded XMP rating and label
let png_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
let png_meta = EncodeMeta { xmp: Some(png_xmp), ..Default::default() };
let png_bytes = encode_png(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &png_meta).unwrap();
std::fs::write(src.join("embedded.png"), &png_bytes).unwrap();
// WebP with embedded XMP rating and label
let webp_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="2" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
let webp_meta = EncodeMeta { xmp: Some(webp_xmp), ..Default::default() };
let webp_bytes = encode_webp_lossless(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &webp_meta).unwrap();
std::fs::write(src.join("embedded.webp"), &webp_bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 2);
let png_photo = s.catalog.photos().find(|p| p.file_name == "embedded.png").unwrap();
assert_eq!(png_photo.rating, 4);
assert_eq!(png_photo.label, Some(ColorLabel::Red));
let webp_photo = s.catalog.photos().find(|p| p.file_name == "embedded.webp").unwrap();
assert_eq!(webp_photo.rating, 2);
assert_eq!(webp_photo.label, Some(ColorLabel::Blue));
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("exif-rating-unrelated-xmp-test");
let px = [128u8; 40 * 30 * 3];
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(5), ..Default::default() });
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/"><exif:ISOSpeedRatings><rdf:Seq><rdf:li>100</rdf:li></rdf:Seq></exif:ISOSpeedRatings><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Rating guide mentioning xmp:Rating</rdf:li></rdf:Alt></dc:description></rdf:Description></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("iso_and_desc_rating.jpg"), &bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.join("iso_and_desc_rating.jpg").to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 1);
let p = s.catalog.photos().next().unwrap();
assert_eq!(p.rating, 5);
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_rendered_file_ignores_embedded_develop_settings() {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-rendered-develop-test");
let px = [128u8; 40 * 30 * 3];
// A JPEG with embedded XMP containing rating and crs:Exposure2012="+1.00"
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="3" crs:Exposure2012="+1.00"/></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("rendered_with_crs.jpg"), &bytes).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.join("rendered_with_crs.jpg").to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 1);
let p = s.catalog.photos().next().unwrap();
// Rating is imported from embedded XMP
assert_eq!(p.rating, 3);
// Develop settings from embedded XMP are ignored for rendered files (already baked into pixels)
assert_eq!(p.develop.light.exposure, 0.0);
assert_eq!(p.develop, std::sync::Arc::new(p.camera_defaults()));
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_embedded_metadata_and_field_specific_sidecar_precedence() {
use lightcraft_catalog::ColorLabel;
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-sidecar-precedence-test");
let px = [128u8; 40 * 30 * 3];
// Case 1: JPEG with embedded Rating 4 and Label Blue, external sidecar with only Label Red
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
let bytes1 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("partial.jpg"), &bytes1).unwrap();
let partial_sidecar = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
std::fs::write(src.join("partial.xmp"), partial_sidecar).unwrap();
// Case 2: JPEG with embedded Rating 4 and Label Blue, without sidecar
let px2 = [129u8; 40 * 30 * 3];
let bytes2 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px2)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("no_sidecar.jpg"), &bytes2).unwrap();
// Case 3: JPEG with embedded Rating 4 and Label Blue, complete sidecar override with Rating 1 and Label Red
let px3 = [130u8; 40 * 30 * 3];
let bytes3 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px3)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("complete.jpg"), &bytes3).unwrap();
let complete_sidecar = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="1" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
std::fs::write(src.join("complete.xmp"), complete_sidecar).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 3);
let partial_p = s.catalog.photos().find(|p| p.file_name == "partial.jpg").unwrap();
assert_eq!(partial_p.rating, 4);
assert_eq!(partial_p.label, Some(ColorLabel::Red));
let no_sidecar_p = s.catalog.photos().find(|p| p.file_name == "no_sidecar.jpg").unwrap();
assert_eq!(no_sidecar_p.rating, 4);
assert_eq!(no_sidecar_p.label, Some(ColorLabel::Blue));
let complete_p = s.catalog.photos().find(|p| p.file_name == "complete.jpg").unwrap();
assert_eq!(complete_p.rating, 1);
assert_eq!(complete_p.label, Some(ColorLabel::Red));
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_partial_sidecar_override_with_rendered_develop() {
use lightcraft_catalog::ColorLabel;
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let src = temp_dir("embedded-sidecar-rendered-develop-test");
let px = [128u8; 40 * 30 * 3];
// JPEG with embedded Rating 4, Label Blue, and crs:Exposure2012="+2.00"
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="4" xmp:Label="Blue" crs:Exposure2012="+2.00"/></rdf:RDF></x:xmpmeta>"#;
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
std::fs::write(src.join("photo.jpg"), &bytes).unwrap();
// Sidecar overriding Label to Red and explicitly setting Exposure to +1.00 (no rating tag)
let sidecar_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Label="Red" crs:Exposure2012="+1.00"/></rdf:RDF></x:xmpmeta>"#;
std::fs::write(src.join("photo.xmp"), sidecar_xmp).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 1);
let p = s.catalog.photos().next().unwrap();
// Rating 4 from embedded is kept
assert_eq!(p.rating, 4);
// Label Red from sidecar overrides Blue
assert_eq!(p.label, Some(ColorLabel::Red));
// External sidecar's develop settings apply; embedded exposure +2 stays suppressed
assert_eq!(p.develop.light.exposure, 1.0);
let _ = std::fs::remove_dir_all(&src);
}
#[test]
fn import_raw_with_embedded_develop_and_partial_sidecar() {
use lightcraft_catalog::ColorLabel;
let src = temp_dir("raw-embedded-develop-sidecar-test");
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="2" xmp:Label="Blue" crs:Exposure2012="+1.50"/></rdf:RDF></x:xmpmeta>"#;
// Case 1: Raw with embedded develop + rating + label, external sidecar has only Label Red
write_raw_with_xmp(&src.join("raw1.NEF"), xmp, 1);
let sidecar1 = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
std::fs::write(src.join("raw1.xmp"), sidecar1).unwrap();
// Case 2: Raw with embedded develop, external sidecar overrides develop settings to Exposure +0.50 and Rating 5
write_raw_with_xmp(&src.join("raw2.NEF"), xmp, 2);
let sidecar2 = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="5" crs:Exposure2012="+0.50"/></rdf:RDF></x:xmpmeta>"#;
std::fs::write(src.join("raw2.xmp"), sidecar2).unwrap();
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
assert_eq!(ids(&r, "imported"), 2);
let p1 = s.catalog.photos().find(|p| p.file_name == "raw1.NEF").unwrap();
assert_eq!(p1.rating, 2, "rating from embedded XMP is preserved");
assert_eq!(p1.label, Some(ColorLabel::Red), "label is overridden by external sidecar");
assert_eq!(p1.develop.light.exposure, 1.5, "raw keeps embedded develop when sidecar provides none");
let p2 = s.catalog.photos().find(|p| p.file_name == "raw2.NEF").unwrap();
assert_eq!(p2.rating, 5, "rating is overridden by external sidecar");
assert_eq!(p2.label, Some(ColorLabel::Blue), "label from embedded XMP is preserved");
assert_eq!(p2.develop.light.exposure, 0.5, "external sidecar develop overrides embedded develop");
let _ = std::fs::remove_dir_all(&src);
}
/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one,
/// optionally with an embedded XMP packet in tag 700.
fn write_raw_with_xmp(path: &Path, xmp: &str, seed: u8) {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let px: Vec<u8> = (0..48 * 32).flat_map(|i| [(i % 251) as u8, 91, seed]).collect();
let j = encode_jpeg(&EncodeImage::new(48, 32, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let xmp_bytes = xmp.as_bytes();
let xmp_off = 8 + 2 + 36 + 4;
let jpeg_off = xmp_off + xmp_bytes.len();
let mut f = b"II*\0\x08\0\0\0\x03\0".to_vec();
for (tag, v) in [(513u16, jpeg_off as u32), (514, j.len() as u32)] {
f.extend_from_slice(&tag.to_le_bytes());
f.extend_from_slice(&[4, 0, 1, 0, 0, 0]);
f.extend_from_slice(&v.to_le_bytes());
}
f.extend_from_slice(&700u16.to_le_bytes());
f.extend_from_slice(&[1, 0]);
f.extend_from_slice(&(xmp_bytes.len() as u32).to_le_bytes());
f.extend_from_slice(&(xmp_off as u32).to_le_bytes());
f.extend_from_slice(&[0, 0, 0, 0]);
f.extend_from_slice(xmp_bytes);
f.extend_from_slice(&j);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, f).unwrap();
}
/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one.
fn write_raw(path: &Path) {
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
+66 -6
View File
@@ -40,6 +40,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() {
let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap();
let path = r["path"].as_str().unwrap();
assert!(path.ends_with("IMG_0-HDR.dng"), "{path}");
assert_eq!(r["reused"].as_bool(), Some(false));
let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap());
let p = s.catalog.photo(id).unwrap().clone();
assert_eq!((p.width, p.height), (480, 320));
@@ -55,15 +56,25 @@ fn hdr_merge_command_creates_and_imports_a_dng() {
assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::<Vec<_>>(), ids);
assert!(st.collapsed);
assert_eq!(s.visible_cloned(), vec![id]);
// the second merge doesn't overwrite the first
let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap();
assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng"));
let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap());
assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option");
// A repeated deterministic merge reuses the existing content instead of publishing an
// unimported uniquely named orphan.
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap();
let edited = s.develop_of(id).unwrap().as_ref().clone();
let stack_before = s.catalog.stack_of(id).unwrap().clone();
let undo_before = s.undo.len();
let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap();
assert_eq!(r2["id"].as_u64(), Some(id.0));
assert_eq!(r2["reused"].as_bool(), Some(true));
assert_eq!(r2["path"].as_str(), Some(path));
assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan");
assert_eq!(s.catalog.photos().count(), 4);
assert_eq!(s.undo.len(), undo_before, "reusing merge content added an undo step");
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "reusing merge content changed edits");
assert_eq!(s.catalog.stack_of(id), Some(&stack_before), "reusing merge content changed stack");
// the type filter finds merge results (and only them)
s.execute("library.filter", &json!({"merged": "hdr"})).unwrap();
let found: std::collections::HashSet<_> = s.catalog.query(&s.filter, &Default::default()).into_iter().collect();
assert_eq!(found, [id, id2].into_iter().collect());
assert_eq!(found, [id].into_iter().collect());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -143,6 +154,55 @@ fn a_merge_of_raws_without_colour_matrices_keeps_their_colour() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hdr_merge_refuses_stale_result_before_writing() {
let dir = temp_dir("hdr-stale");
let mut paths = Vec::new();
for (i, b) in lightcraft_merge::synth::bracket_dngs(240, 160, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() {
let p = dir.join(format!("IMG_{i}.dng"));
std::fs::write(&p, b).unwrap();
paths.push(p.to_string_lossy().to_string());
}
let mut s = Session::new().with_fs();
let ids = import(&mut s, paths.clone());
let first = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap();
let id = lightcraft_catalog::PhotoId(first["id"].as_u64().unwrap());
let path = first["path"].as_str().unwrap().to_string();
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap();
let edited = s.develop_of(id).unwrap().as_ref().clone();
let stack_before = s.catalog.stack_of(id).cloned();
std::fs::remove_file(&path).unwrap();
let undo_before = s.undo.len();
let missing = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true}));
assert!(missing.as_ref().unwrap_err().to_string().contains("missing or changed"));
assert!(!std::path::Path::new(&path).exists());
assert!(!dir.join("IMG_0-HDR-2.dng").exists());
assert_eq!(s.undo.len(), undo_before);
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "repair changed edits");
assert_eq!(s.catalog.stack_of(id).cloned(), stack_before);
std::fs::write(&path, std::fs::read(&paths[0]).unwrap()).unwrap();
let changed_bytes = std::fs::read(&path).unwrap();
let changed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true}));
assert!(changed.as_ref().unwrap_err().to_string().contains("missing or changed"));
assert_eq!(std::fs::read(&path).unwrap(), changed_bytes);
assert!(!dir.join("IMG_0-HDR-2.dng").exists());
assert_eq!(s.undo.len(), undo_before);
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "changed-source repair changed edits");
assert_eq!(s.catalog.stack_of(id).cloned(), stack_before);
s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap();
let deleted_bytes = std::fs::read(&path).unwrap();
let undo_after_delete = s.undo.len();
let failed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false}));
assert!(failed.as_ref().unwrap_err().to_string().contains("deleted"));
assert_eq!(std::fs::read(&path).unwrap(), deleted_bytes);
assert!(!dir.join("IMG_0-HDR-3.dng").exists(), "failed import left an orphan");
assert_eq!(s.undo.len(), undo_after_delete);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn panorama_command_with_auto_crop() {
let dir = temp_dir("pano");
+2
View File
@@ -255,6 +255,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec<Layer>)
let reads: Vec<usize> = match op {
Op::Conv(c) => std::iter::once(c.src).chain(c.src2).collect(),
Op::ConvT2(c) => vec![c.src],
Op::Add { src, src2 } => vec![*src, *src2],
Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => vec![*src],
};
for t in reads {
@@ -448,6 +449,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec<Layer>)
}
// run as part of the 1 × 1 convolution before it
Op::DepthToSpace2 { .. } => {}
Op::Add { .. } => return unsupported("an elementwise add is not supported on the GPU"),
}
// buffers whose last reader was this layer are free for the next layer's result
for t in 0..=i {
+1 -1
View File
@@ -609,7 +609,7 @@ fn sample(cx: &mut Cx<'_>, src: &Arc<Rgb32f>, src_buf: Arc<Buf>, plan: &Plan<'_>
Arc::new(out)
};
let (base, (bw, bh)) = match sp.prefilter {
Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, Filter::Mitchell)), d),
Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, fr.downscale)), d),
None => (oriented, (sp.ow, sp.oh)),
};
let mut affine = |xf: &lightcraft_geom::Affine| {
+9 -3
View File
@@ -59,10 +59,16 @@ const PATCH_K: usize = 3 * PATCH * PATCH;
/// Longest wait for one forward pass before the device is given up on.
const TIMEOUT: Duration = Duration::from_secs(120);
/// Workgroup memory the attention kernel needs: its key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats).
/// Conservative workgroup memory for key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats).
const ATTENTION_BYTES: u32 = 2 * ATTENTION_KEYS * HEAD_DIM as u32 * 4;
/// Keys per step of the attention kernel.
/// The maximum keys per step; also used to bound the required workgroup memory.
const ATTENTION_KEYS: u32 = 32;
/// On DX12, creating the fully unrolled 32-key shader can be very slow on some drivers. Smaller
/// tiles shorten initialization; the existing 32-key limits remain conservative for every backend.
fn attention_keys(backend: wgpu::Backend) -> u32 {
if backend == wgpu::Backend::Dx12 { 8 } else { ATTENTION_KEYS }
}
/// The matrix product's blocking.
const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 };
@@ -255,7 +261,7 @@ fn make_device(backends: wgpu::Backends) -> Result<Dev, String> {
let k = Kernels {
matmul: Matmul { pipeline: pipe("sam3 matmul", &matmul_source(TILE, false), "main"), tile: TILE },
matmul16: OnceLock::new(),
attention: pipe("sam3 attention", &attention_source(ATTENTION_KEYS), "main"),
attention: pipe("sam3 attention", &attention_source(attention_keys(info.backend)), "main"),
layernorm: pipe("sam3 ops", ops, "layernorm"),
rope: pipe("sam3 ops", ops, "rope"),
im2col: pipe("sam3 ops", ops, "im2col"),
+2 -2
View File
@@ -30,7 +30,7 @@ const MLP: usize = 2048;
const LAYERS: usize = 6;
/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`).
const EPS: f32 = 1e-5;
/// Keys per step of the attention kernel (the prompt's 32 tokens are one step).
/// Required key-count alignment, kept at 32 even when the DX12 kernel uses smaller tiles.
const KEYS: u32 = 32;
/// `p.gelu` of the matrix product: ReLU.
const RELU: u32 = 2;
@@ -49,7 +49,7 @@ pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> {
KERNELS
.get_or_init(|| {
let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation);
let source = attention_source(KEYS);
let source = attention_source(super::attention_keys(dev.info.backend));
let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry);
let k = Kernels { attention: pipe("attention"), add: pipe("add") };
match pollster::block_on(validation.pop()) {
+2
View File
@@ -83,6 +83,8 @@ fn the_kernel_source_is_written_out() {
assert!(!src.contains("{{"), "a mark is left");
assert!(src.contains("let s31 = ") && !src.contains("let s32 = "));
assert!(src.contains("let q7 = ") && !src.contains("let q8 = "));
let dx12 = attention_source(super::super::attention_keys(wgpu::Backend::Dx12));
assert!(dx12.contains("let s7 = ") && !dx12.contains("let s8 = "));
}
#[test]
+9
View File
@@ -456,3 +456,12 @@ fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() {
assert_eq!(short.len(), 1, "{short:?}");
assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}");
}
/// DX12 pipeline creation can take minutes for the fully unrolled attention shader; other backends keep the larger tile.
#[test]
fn attention_tiles_are_smaller_on_dx12() {
assert_eq!(attention_keys(wgpu::Backend::Dx12), 8);
assert_eq!(attention_keys(wgpu::Backend::Vulkan), ATTENTION_KEYS);
let src = attention_source(attention_keys(wgpu::Backend::Dx12));
assert!(src.contains("let s7 = ") && !src.contains("let s8 = "));
}
+5
View File
@@ -68,6 +68,7 @@ mod write_tests {
focal_length: Some(35.0),
lens_model: Some("35mm F2".into()),
gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }),
rating: Some(4),
..Default::default()
};
let back = read_exif(&write_exif(&m));
@@ -80,8 +81,12 @@ mod write_tests {
assert!((back.f_number.unwrap() - 2.8).abs() < 1e-6);
assert!((back.exposure_time.unwrap() - 0.004).abs() < 1e-9);
assert_eq!(back.lens_model, m.lens_model);
assert_eq!(back.rating, Some(4));
let g = back.gps.unwrap();
assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{g:?}");
let rejected = read_exif(&write_exif(&Metadata { rating: Some(-1), ..Default::default() }));
assert_eq!(rejected.rating, Some(-1));
}
#[test]
+31 -5
View File
@@ -37,6 +37,9 @@ pub struct Frame {
/// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this
/// frame's transformed image, like spots and the crop.
pub masks_on_photo: bool,
/// Filter of the area downscale ahead of the bilinear resample ([`Frame::sample`]); see
/// [`crate::Downscale`].
pub downscale: Filter,
}
/// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's
@@ -82,6 +85,7 @@ impl Frame {
warp: (!warp.is_identity()).then_some(warp),
view: None,
masks_on_photo: false,
downscale: Filter::Mitchell,
};
if apply_crop {
f.constrain_to_image(s.geometry.constrain_crop);
@@ -312,8 +316,12 @@ impl Frame {
pub fn sample_plan(&self, src_w: usize, src_h: usize, w: usize, h: usize) -> SamplePlan {
let (ow, oh) = if self.orient.swaps_axes() { (src_h, src_w) } else { (src_w, src_h) };
let crop_px = self.crop.rect_px(self.ow, self.oh);
let k = crop_px.width() / w as f64;
let prefilter = (k > 1.25).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1)));
// the larger of the two axes' reductions: the prefilter then takes every axis at least as small
// as its output needs, so the bilinear pass after it never minifies (and aliases) either one
let k = (crop_px.width() / w as f64).max(crop_px.height() / h as f64);
// Sharp exports use their selected filter for every downscale; keep smooth previews' threshold.
let threshold = if self.downscale == Filter::Lanczos3 { 1.0 } else { 1.25 };
let prefilter = (k > threshold).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1)));
let (bw, bh) = prefilter.unwrap_or((ow, oh));
let (sx, sy) = (bw as f64 / ow as f64, bh as f64 / oh as f64);
let mode = if self.warp.is_some() {
@@ -333,7 +341,7 @@ impl Frame {
let o = oriented.as_ref().unwrap_or(src);
let plan = self.sample_plan(src.width, src.height, w, h);
let base = match plan.prefilter {
Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)),
Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, self.downscale)),
None => std::borrow::Cow::Borrowed(o),
};
self.sample_base(base, plan, w, h)
@@ -355,7 +363,7 @@ impl Frame {
let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new();
for dims in plans.iter().filter_map(|p| p.1.prefilter) {
if !bases.iter().any(|b| b.0 == dims) {
bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell)));
bases.push((dims, resize(o, dims.0, dims.1, self.downscale)));
}
}
plans
@@ -443,7 +451,7 @@ pub struct SamplePlan {
/// Oriented source size.
pub ow: usize,
pub oh: usize,
/// Size of the Mitchell prefilter (area downscale before the bilinear resample), if any.
/// Size of the prefilter ([`Frame::downscale`]: area downscale before the bilinear resample), if any.
pub prefilter: Option<(usize, usize)>,
/// Oriented-source px → prefiltered px.
pub sx: f64,
@@ -529,6 +537,24 @@ mod tests {
assert!((f.px_per_long(300) - 300.0).abs() < 1e-9);
}
#[test]
fn sharp_downscale_filters_mild_reductions_and_native_size_stays_identical() {
let src = Rgb32f::from_fn(100, 100, |x, y| [((x + y) % 2) as f32; 3]);
for filter in [Filter::Mitchell, Filter::Lanczos3] {
let mut f = Frame::new(100, 100, &DevelopSettings::default(), true);
f.downscale = filter;
let edge = if filter == Filter::Lanczos3 { 90 } else { 70 };
assert_eq!(f.sample_plan(100, 100, edge, edge).prefilter, Some((edge, edge)));
assert_eq!(f.sample(&src, edge, edge).data, resize(&src, edge, edge, filter).data);
if filter == Filter::Mitchell {
assert_eq!(f.sample_plan(100, 100, 90, 90).prefilter, None);
}
assert_eq!(f.sample_plan(100, 100, 100, 100).prefilter, None);
assert_eq!(f.sample(&src, 100, 100).data, src.data);
assert_eq!(f.sample_plan(100, 100, 110, 110).prefilter, None);
}
}
#[test]
fn rotation_swaps_aspect() {
let s = DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() };
+25 -1
View File
@@ -129,6 +129,26 @@ impl Default for SourceInfo {
}
}
/// How a render shrinks its source to the output size.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Downscale {
/// Mitchell–Netravali: soft, no visible ringing. Previews and thumbnails.
#[default]
Smooth,
/// Lanczos-3: keeps the detail a smaller output can hold, as a dedicated downscale does
/// (exports, #2970). Its slight overshoot at hard edges stays below the output sharpening's.
Sharp,
}
impl Downscale {
pub fn filter(self) -> lightcraft_raster::resample::Filter {
match self {
Downscale::Smooth => lightcraft_raster::resample::Filter::Mitchell,
Downscale::Sharp => lightcraft_raster::resample::Filter::Lanczos3,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Quality {
/// Interactive drags: skips the most expensive refinements.
@@ -162,6 +182,8 @@ pub struct RenderRequest {
/// Previews for a monitor with a display profile: render 8-bit into its primaries instead of
/// `space` (see [`DisplaySpace`]; ignored by deep renders).
pub display: Option<DisplaySpace>,
/// Filter of the downscale to the output size.
pub downscale: Downscale,
}
/// A window of the (virtual) full output, in its pixels: what a zoomed view needs, rendered
@@ -236,6 +258,7 @@ impl RenderRequest {
proof: None,
window: None,
display: None,
downscale: Downscale::Smooth,
}
}
@@ -491,7 +514,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
}
}
let s = &*settings;
let frame = frame_for(src, info, s, req.apply_crop);
let mut frame = frame_for(src, info, s, req.apply_crop);
frame.downscale = req.downscale.filter();
let (full_w, full_h) = req.size(&frame);
// sizes and scale are those of the whole output; a window only narrows what is drawn
let px_per_long = frame.px_per_long(full_w);
+21
View File
@@ -107,6 +107,27 @@ fn dehaze_does_not_crush_dark_regions_next_to_bright_ones() {
}
}
/// An export's sharp downscale (#2970) keeps more of the fine detail a smaller output can hold
/// than a preview's smooth one, and changes nothing when the output is the source's own size.
#[test]
fn sharp_downscale_keeps_detail() {
use crate::Downscale;
// fine stripes: a period of 5 source pixels, 3 output pixels at 600 → 360
let src = Rgb32f::from_fn(600, 400, |x, _| [0.18 * (1.0 + 0.8 * (x as f32 * std::f32::consts::TAU / 5.0).sin()); 3]);
let swing = |down: Downscale, edge: usize| {
let r =
render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest { downscale: down, ..RenderRequest::fit(edge, edge) });
let row: Vec<f32> = (40..r.image.width - 40).map(|x| r.image.data[(r.image.height / 2) * r.image.width + x][1] as f32).collect();
let m = row.iter().sum::<f32>() / row.len() as f32;
(row.iter().map(|v| (v - m).abs()).sum::<f32>() / row.len() as f32, r.image)
};
let ((smooth, _), (sharp, _)) = (swing(Downscale::Smooth, 360), swing(Downscale::Sharp, 360));
assert!(sharp > smooth * 1.25, "sharp {sharp} vs smooth {smooth}");
let ((_, a), (_, b)) = (swing(Downscale::Smooth, 600), swing(Downscale::Sharp, 600));
assert_eq!((b.width, b.height), (600, 400));
assert_eq!(a.data, b.data, "no resize, no difference");
}
#[test]
fn resolution_independence_of_local_contrast() {
// Clarity at two preview sizes should give similar results after downscaling.
+42
View File
@@ -0,0 +1,42 @@
//! A pure above-Nyquist carrier must be suppressed rather than folded into a smaller export.
use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::geometry::Frame;
use lightcraft_raster::{Rgb32f, resample::Filter};
#[test]
fn mild_sharp_reductions_suppress_above_target_nyquist_aliases() {
// 0.49 cycles/source pixel is above the 90% and 80% outputs' Nyquist limits.
let source = Rgb32f::from_fn(1000, 100, |x, _| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * x as f32).sin(); 3]);
let power = |image: &Rgb32f| {
let values: Vec<f64> = (12..image.width - 12).map(|x| f64::from(image.get(x, image.height / 2)[0])).collect();
let mean = values.iter().sum::<f64>() / values.len() as f64;
values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64
};
let mut frame = Frame::new(1000, 100, &DevelopSettings::default(), true);
frame.downscale = Filter::Lanczos3;
for (w, h) in [(900, 90), (800, 80)] {
let k = 1000.0 / w as f64;
let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(((x as f64 + 0.5) * k) as f32, ((y as f64 + 0.5) * k) as f32));
let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered));
assert!(sharp < bilinear * 0.95, "{w}: residual alias power {sharp} vs unfiltered {bilinear}");
}
}
#[test]
fn a_height_only_reduction_is_prefiltered_too() {
// the width stays 1:1, the height shrinks 1000 → 900: the vertical carrier must not fold in
let source = Rgb32f::from_fn(100, 1000, |_, y| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * y as f32).sin(); 3]);
let power = |image: &Rgb32f| {
let values: Vec<f64> = (12..image.height - 12).map(|y| f64::from(image.get(image.width / 2, y)[0])).collect();
let mean = values.iter().sum::<f64>() / values.len() as f64;
values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64
};
let mut frame = Frame::new(100, 1000, &DevelopSettings::default(), true);
frame.downscale = Filter::Lanczos3;
let (w, h) = (100, 900);
assert!(frame.sample_plan(100, 1000, w, h).prefilter.is_some(), "a reduction on either axis is prefiltered");
let k = 1000.0 / h as f64;
let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(x as f32 + 0.5, ((y as f64 + 0.5) * k) as f32));
let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered));
assert!(sharp < bilinear * 0.95, "residual alias power {sharp} vs unfiltered {bilinear}");
}
+117 -9
View File
@@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};
const CONTROL_LIMIT: usize = 16 * 1024;
const RESPONSE_LIMIT: usize = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(9 * 60);
const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100);
pub const ENV: &str = "LIGHTCRAFT_SAM3_REMOTE";
#[derive(Serialize, Deserialize)]
@@ -194,6 +195,30 @@ fn serve_client(stream: &mut TcpStream, dir: &Path, device: candle_core::Device)
}
}
fn serve_connections<I, C, H, S>(incoming: I, mut handle_client: H, mut retry_sleep: S)
where
I: IntoIterator<Item = io::Result<C>>,
H: FnMut(&mut C) -> Result<(), String>,
S: FnMut(Duration),
{
for connection in incoming {
let mut stream = match connection {
Ok(stream) => stream,
Err(error) => {
eprintln!("SAM3 accept failed: {error}");
retry_sleep(ACCEPT_RETRY_DELAY);
continue;
}
};
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_client(&mut stream)));
match result {
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
Err(_) => eprintln!("SAM3 session panicked; model released"),
Ok(Ok(())) => {}
}
}
}
pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Result<(), String> {
if !address.ip().is_loopback() || !device.is_metal() {
return Err("SAM worker requires a loopback address and a Metal device".into());
@@ -203,14 +228,97 @@ pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Re
}
let listener = TcpListener::bind(address).map_err(|e| e.to_string())?;
eprintln!("SAM3 worker listening on {address}; device=Metal; idle unload=600s");
for stream in listener.incoming() {
let mut stream = stream.map_err(|e| e.to_string())?;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| serve_client(&mut stream, dir, device.clone())));
match result {
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
Err(_) => eprintln!("SAM3 session panicked; model released"),
Ok(Ok(())) => {}
}
}
serve_connections(listener.incoming(), |stream| serve_client(stream, dir, device.clone()), std::thread::sleep);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn accept_error<T>() -> io::Result<T> {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, "injected accept failure"))
}
#[test]
fn sam_accept_error_before_client_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[accept_error(), Ok(1_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|_| {},
);
assert_eq!(handled, [1]);
}
#[test]
fn sam_accept_error_between_clients_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[Ok(1_u8), accept_error(), Ok(2_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|_| {},
);
assert_eq!(handled, [1, 2]);
}
#[test]
fn sam_accept_repeated_errors_back_off() {
let mut handled = Vec::new();
let mut delays = Vec::new();
serve_connections(
[accept_error(), accept_error(), Ok(1_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|delay| delays.push(delay),
);
assert_eq!(handled, [1]);
assert_eq!(delays, [Duration::from_millis(100), Duration::from_millis(100)]);
}
#[test]
fn sam_accept_client_failure_keeps_serving() {
let mut handled = Vec::new();
let mut delays = Vec::new();
serve_connections(
[Ok(1_u8), Ok(2_u8)],
|stream| {
handled.push(*stream);
if *stream == 1 { Err("injected client failure".into()) } else { Ok(()) }
},
|delay| delays.push(delay),
);
assert_eq!(handled, [1, 2]);
assert!(delays.is_empty());
}
#[test]
fn sam_accept_client_panic_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[Ok(1_u8), Ok(2_u8)],
|stream| {
handled.push(*stream);
if *stream == 1 {
std::panic::resume_unwind(Box::new("injected client panic"));
}
Ok(())
},
|_| {},
);
assert_eq!(handled, [1, 2]);
}
}
+3
View File
@@ -213,6 +213,9 @@ impl LightcraftApp {
// UI passes still counts as changed)
self.selection_changes();
let r = self.run_command(id, params);
// the panel a command left on show is noted now, not at the next frame, success or not: the next command
// of the same frame (a script, queued shortcuts) sees it (Close Panel, B, Done = the column stays hidden)
self.ui.note_right();
self.selection_changes();
r
}
+2
View File
@@ -437,6 +437,8 @@ impl LightcraftApp {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.library_changed(&ctx);
// (a tool panel opened some other way still remembers the panel it took the place of)
self.ui.note_right();
// panels set it again this frame while the pointer rests on a preset or profile
self.hover_preview = None;
self.end_drags(&ctx);
+11
View File
@@ -422,10 +422,21 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest
}
u.collapsed_sidebar.clear();
u.toast = app.ui.toast.clone();
// the panel a tool panel took the place of, to put back when it closes, survives a ui.set
u.tool_return = app.ui.tool_return;
u.right_seen = app.ui.right_seen;
// (and what a panel toggle replaced, so pressing its key again still puts that back)
u.toggle_return = app.ui.toggle_return.clone();
u.right_shown_by_f8 = app.ui.right_shown_by_f8;
u.dialog = app.ui.dialog.clone();
u.status = app.ui.status.clone();
let right_changed = u.right != app.ui.right;
crate::docking::cancel_replaced_gesture(app, u.docking.as_ref());
app.ui = u;
if right_changed {
// noted now, as a command does: the next request may open a tool before a frame is drawn
app.ui.note_right();
}
crate::i18n::set_language(app.ui.language);
ctx.request_repaint();
ok(serde_json::to_value(&app.ui).unwrap_or_default())
+19 -6
View File
@@ -3,19 +3,25 @@ use super::ui_commands::{UI_COMMANDS, language_from_command};
use super::{BeforeAfter, Dialog, LightcraftApp, PickRequest, Picked, RightPanel, Value, ViewMode, Zoom, json, thumb_size_view};
fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) {
if app.ui.right == p && crate::docking::exposed(app, crate::docking::Panel::Tools) {
app.ui.right = RightPanel::None;
// toggled off: back to exactly what the right column showed before (in the same frame: no flash, no jump),
// closed when it was closed (note 21)
let exposed = crate::docking::exposed(app, crate::docking::Panel::Tools);
let tool_before = app.ui.tool.clone();
let on = app.ui.toggle_panel(p, exposed);
// toggled off: the panel put back brings its own tool back (Masking's Brush, Remove's Heal or Clone)
let tool_restored = !on && app.ui.tool != tool_before;
if !on {
app.toast(ctx, crate::i18n::tr_format!("{name} Off", name = crate::i18n::tr(name)));
} else {
app.ui.right = p;
app.toast(ctx, crate::i18n::tr_format!("{name} On", name = crate::i18n::tr(name)));
if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) {
app.ui.view = ViewMode::Detail;
}
}
if p != RightPanel::Masking && app.ui.tool != "wbPicker" {
if !tool_restored && p != RightPanel::Masking && app.ui.tool != "wbPicker" {
app.ui.tool.clear();
}
app.ui.note_right();
let _ = app.session.end_interaction();
}
@@ -643,6 +649,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va
if app.ui.right != RightPanel::None && crate::docking::exposed(app, crate::docking::Panel::Tools) {
app.ui.right_hidden = app.ui.right;
app.ui.right = RightPanel::None;
// noted now, not at the frame's end: a command after it in the same frame (a batch of control
// requests) opens a tool on the hidden column, not on the panel F8 hid
app.ui.note_right();
if app.ui.tool != "wbPicker" {
app.ui.tool.clear();
}
@@ -653,6 +662,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va
p => p,
};
app.ui.right = p;
// (a tool shown again this way still closes to the panel before it; noted now, as for hiding)
app.ui.right_shown_by_f8 = Some(p);
app.ui.note_right();
if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) {
app.ui.view = ViewMode::Detail;
}
@@ -1050,7 +1062,7 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val
Ok(Value::Null)
}
"tool.done" => {
// Return commits a tool panel (crop, remove, red eye, masking): back to Edit
// Return commits a tool panel (crop, remove, red eye, masking): back to the panel before it
use RightPanel::*;
if app.ui.dialog.is_none() && matches!(app.ui.right, Crop | Remove | RedEye | Masking) {
if app.ui.right == Crop {
@@ -1058,7 +1070,8 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val
}
let _ = app.session.end_interaction();
app.ui.tool.clear();
app.ui.right = Edit;
// back to the panel shown before the tool (hidden if it was)
app.ui.right = app.ui.leave_tool();
}
Ok(Value::Null)
}
+9 -2
View File
@@ -29,6 +29,12 @@ pub(crate) use info::mixed_meta;
pub(crate) use keywords::forget_stale_enter_keywords;
use keywords::keywords;
/// The right column's scroll area for `panel`: one per panel, the same with or without a selected photo (the
/// Keywords panel shows its list either way).
fn scroll_salt(panel: RightPanel) -> (&'static str, RightPanel) {
("right-scroll", panel)
}
pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider));
@@ -45,7 +51,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
if app.ui.right == RightPanel::Keywords {
// (without a selection there is no Add keyword box for Add Keywords to put the cursor in)
app.ui.focus_keywords = None;
egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]).show(ui, |ui| {
egui::ScrollArea::vertical().id_salt(scroll_salt(RightPanel::Keywords)).auto_shrink([false, false]).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
if fold_header(app, ui, "keywording", "Keywords") {
padded(ui, |ui| {
@@ -70,7 +76,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
ui.spacing_mut().item_spacing.y = 0.0;
super::edit::histogram(app, ui, id);
}
let mut area = egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]);
// each panel keeps its own scroll position: Edit is where it was after Masking or Crop
let mut area = egui::ScrollArea::vertical().id_salt(scroll_salt(app.ui.right)).auto_shrink([false, false]);
if let Some(offset) = held {
area = area.vertical_scroll_offset(offset);
}
+58
View File
@@ -30,3 +30,61 @@ fn short_times() {
assert_eq!(super::short_time("2026-09-30T12:00:05"), "Sep 30, 2026, 12:00 PM");
assert_eq!(super::short_time("2026-01-02"), "Jan 2, 2026");
}
// Feature: the Keywords panel keeps its scroll position when a photo is selected (CodeRabbit on #3031: the
// no-selection list scrolled under another id)
#[test]
fn the_keywords_panel_scrolls_under_one_id_with_or_without_a_selection() {
use crate::state::RightPanel;
// (`show` names the no-selection list's scroll area by `scroll_salt(RightPanel::Keywords)`, as it names the
// panel's with a selection by `scroll_salt(app.ui.right)`)
assert_eq!(super::scroll_salt(RightPanel::Keywords), ("right-scroll", RightPanel::Keywords));
assert_ne!(super::scroll_salt(RightPanel::Keywords), super::scroll_salt(RightPanel::Edit), "each panel keeps its own");
}
// The Keywords panel scrolled with no photo selected is the same scroll area as with one: the offset it was left at
// is there when a photo is selected (CodeRabbit on #3031)
#[test]
fn the_keywords_panel_keeps_its_offset_from_no_selection_to_a_selection() {
use crate::headless::Headless;
use serde_json::json;
use std::time::Duration;
const T: Duration = Duration::from_secs(20);
let services = crate::Services { png: None, ..Default::default() };
let mut h = Headless::new(crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 420.0], 1.0);
// a Keyword List longer than the panel
for i in 0..80 {
h.app.session.execute("keyword.create", &json!({"name": format!("keyword {i:02}")})).unwrap();
}
let r = h.request("ui.set", json!({"view": "detail", "right": "keywords"}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(Duration::from_secs(120));
// with a selection: the panel's scroll area (as the panel records it)
let area = h.view.ctx.data(|d| d.get_temp::<egui::Id>(egui::Id::unique(super::AREA))).expect("the panel's scroll area");
let offset = |h: &Headless| egui::scroll_area::State::load(&h.view.ctx, area).map_or(0.0, |s| s.clamped_offset().y);
assert_eq!(offset(&h), 0.0);
// no selection: the list scrolled down
let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": []}}), T);
assert_eq!(r["ok"], true, "{r}");
for _ in 0..4 {
h.step();
}
assert!(h.app.session.active().is_none());
let panel = h.app.widgets.iter().find(|(w, _)| w == "panel:right_panel").map(|(_, r)| *r).expect("the right panel");
h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T);
let r = h.request("ui.scroll", json!({"dy": -300.0}), T);
assert_eq!(r["ok"], true, "{r}");
for _ in 0..60 {
h.step();
}
let scrolled = offset(&h);
assert!(scrolled > 50.0, "the no-selection list scrolls the panel's own area: {scrolled}");
// a photo selected: the area keeps the offset (moved down only by the Keywords box put above the list)
let id = h.app.session.visible_cloned()[0];
let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [id.0]}}), T);
assert_eq!(r["ok"], true, "{r}");
for _ in 0..10 {
h.step();
}
assert!(offset(&h) >= scrolled - 0.5, "the offset is kept: {} after {scrolled}", offset(&h));
}
+130
View File
@@ -47,6 +47,26 @@ pub struct UiState {
/// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again.
#[serde(skip)]
pub right_hidden: RightPanel,
/// The panel F8 just showed again, until [`UiState::note_right`] sees it: a tool coming back this way still closes
/// to the panel before it, while a tool opened any other way on a hidden column closes to the hidden column.
#[serde(skip)]
pub right_shown_by_f8: Option<RightPanel>,
/// The panel on show before a tool panel ([`RightPanel::is_tool`]) took its place, put back
/// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden).
#[serde(skip)]
pub tool_return: Option<RightPanel>,
/// The panels toggles (a panel key or button: I, M, R, Q…) opened, each with what the right column showed before
/// it and that one's [`UiState::tool_return`], the latest last: toggling the panel on show off puts back exactly
/// that, closed included (test notes 2026-10-24 note 21), and the one below it is then on show with its own
/// record (Edit → I → K → K → I = Edit). Forgotten once another panel is shown (not when F8 hides the panel and
/// shows it again). At most [`TOGGLE_HISTORY`] deep.
#[serde(skip)]
/// Each record also holds the on-canvas tool of the panel it replaced (Masking's Brush, Remove's Heal or Clone),
/// put back with that panel (`None`: a tool opened by a command, which leaves the tool as it is).
pub toggle_return: Vec<(RightPanel, RightPanel, Option<RightPanel>, Option<String>)>,
/// The panel [`UiState::note_right`] last saw.
#[serde(skip)]
pub right_seen: RightPanel,
/// Widths of the left sidebar and of the right panel in points (dragging their inner edge
/// resizes them; within [`LEFT_WIDTH`] / [`RIGHT_WIDTH`]).
pub left_width: f32,
@@ -387,6 +407,112 @@ pub struct UiState {
pub print: crate::print_view::PrintUi,
}
/// How many panel toggles [`UiState::toggle_return`] remembers (pressing I and K in turn would grow it without end).
pub const TOGGLE_HISTORY: usize = 16;
impl UiState {
/// Notes the panel on show: a tool panel opened from another panel (or from none) remembers
/// that one, to put it back when the tool closes; any other panel forgets it.
pub fn note_right(&mut self) {
self.note_right_from(None);
}
/// [`UiState::note_right`], told which panel a toggle ([`UiState::toggle_panel`]) just opened (its record is
/// on the history already).
fn note_right_from(&mut self, toggled: Option<RightPanel>) {
let shown_by_f8 = self.right_shown_by_f8.take();
if self.right == self.right_seen {
return;
}
// F8 showing a tool it hid: the panel before that tool still holds (`None` is F8's hidden column, not
// what the tool came from). A tool opened another way on the hidden column came from the hidden column.
let back_from_f8 = self.right_seen == RightPanel::None && shown_by_f8 == Some(self.right);
// A tool opened by a command, not a toggle (B, a mask tool from Crop…), is recorded like a toggle: closing
// it shows exactly what the column showed before (Info → Crop → B → Done = Crop), and the records below it
// stay (Crop closed = Info, I = Edit). That holds when the history already ends with this tool: F8 hiding it
// kept its record, and opening it again by a command on the hidden column (Info → Remove → F8 → Visualize
// Spots) closes it back to the hidden column, not to Info.
let opened_directly = self.right.is_tool() && !back_from_f8 && toggled != Some(self.right);
if opened_directly {
if self.toggle_return.len() >= TOGGLE_HISTORY {
self.toggle_return.remove(0);
}
self.toggle_return.push((self.right, self.right_seen, self.tool_return, None));
}
// F8 hiding the panel a toggle opened keeps its record, for F8 showing it again
let f8_hid = |opened: RightPanel| self.right == RightPanel::None && self.right_hidden == opened;
if !opened_directly && self.toggle_return.last().is_some_and(|&(opened, ..)| opened != self.right && !f8_hid(opened)) {
self.toggle_return.clear();
}
if self.right.is_tool() {
if !self.right_seen.is_tool() && !back_from_f8 {
self.tool_return = Some(self.right_seen);
}
} else if !(self.right == RightPanel::None && self.right_seen.is_tool() && self.right_hidden == self.right_seen) {
// any panel but F8 hiding the tool on show forgets it
self.tool_return = None;
}
self.right_seen = self.right;
}
/// The panel to show when the tool panel on show closes: the one shown before it, or none
/// when the panel was hidden (Edit when nothing is known).
pub fn leave_tool(&mut self) -> RightPanel {
self.note_right();
if let Some(back) = self.untoggle() {
return back;
}
let back = self.tool_return.take().unwrap_or(RightPanel::Edit);
if back.is_tool() { RightPanel::Edit } else { back }
}
/// A panel toggle (`panel.info`, `panel.masking`…) for `p`: when `p` is on show (`exposed`: not hidden behind
/// another dock tab) it goes and the right column shows exactly what it showed before the toggle opened it, or
/// stays closed when it was (note 21); otherwise `p` comes up and what was there is remembered. Returns whether
/// `p` is now on.
pub fn toggle_panel(&mut self, p: RightPanel, exposed: bool) -> bool {
self.note_right();
if self.right == p && exposed {
self.right = match self.untoggle() {
Some(back) => back,
None if p.is_tool() => self.leave_tool(),
None => RightPanel::None,
};
self.note_right();
false
} else {
// (a column hidden behind another dock tab comes back hidden, with no on-canvas tool: what it held
// wasn't on show)
let saved =
if exposed { (p, self.right, self.tool_return, Some(self.tool.clone())) } else { (p, RightPanel::None, self.tool_return, None) };
if self.toggle_return.len() >= TOGGLE_HISTORY {
self.toggle_return.remove(0);
}
// (on the history before `note_right` sees `p`: the panel it replaced keeps its own record below it)
self.toggle_return.push(saved);
self.right = p;
self.note_right_from(Some(p));
true
}
}
/// What the toggle that opened the panel on show replaced (see [`UiState::toggle_panel`]), with its own tool
/// memory and on-canvas tool put back, or `None` when that panel wasn't opened by a toggle.
fn untoggle(&mut self) -> Option<RightPanel> {
let &(opened, before, tool_return, _) = self.toggle_return.last()?;
if opened != self.right {
return None;
}
if let Some((.., Some(tool))) = self.toggle_return.pop() {
self.tool = tool;
}
self.tool_return = tool_return;
// seen already: `note_right` must not take the panel being left for the one this came back from
self.right_seen = before;
Some(before)
}
}
impl Default for UiState {
/// Initialize the library and import review sizes as independent app preferences.
fn default() -> Self {
@@ -404,6 +530,10 @@ impl Default for UiState {
right_width: RIGHT_WIDTH.default,
right: RightPanel::Edit,
right_hidden: RightPanel::None,
tool_return: None,
toggle_return: Vec::new(),
right_shown_by_f8: None,
right_seen: RightPanel::Edit,
presets: false,
preset_thumbs: false,
filmstrip: true,
+7 -1
View File
@@ -19,7 +19,7 @@ pub enum ViewMode {
}
/// The right-hand tool/panel shown next to the tool strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RightPanel {
#[default]
@@ -40,6 +40,12 @@ pub enum RightPanel {
}
impl RightPanel {
/// A tool that takes the panel's place while it is used (Crop, Remove, Masking, Red Eye): on
/// closing, the panel shown before it comes back ([`UiState::leave_tool`]).
pub fn is_tool(self) -> bool {
matches!(self, RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye)
}
pub fn is_edit_tool(self) -> bool {
matches!(self, RightPanel::Edit | RightPanel::Profiles | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye)
}
+1
View File
@@ -86,6 +86,7 @@ mod mode_dropdowns;
mod move_folder;
mod offline;
mod open_lightroom;
mod panel_restore;
pub(super) mod panels;
mod preset_favorites;
mod preset_import;
@@ -198,6 +198,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() {
let mut h = app();
h.app.run("app.setShortcut", json!({"id":"panel.crop","shortcut":"K"})).unwrap();
dock(&mut h, json!({"operation":"move","panel":"tools","target":"library","zone":"center"}));
let before = h.app.ui.right;
h.app.run("panel.crop", json!({})).unwrap();
h.step();
// The test chooses the renderer's actual registered tab, rather than an arbitrary focus owner.
@@ -207,7 +208,9 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() {
key(&mut h, egui::Key::Enter);
assert_eq!(h.app.ui.right, RightPanel::Crop, "Enter activates the tab without tool.done");
key(&mut h, egui::Key::K);
assert_eq!(h.app.ui.right, RightPanel::None, "the global crop toggle is reachable from tab focus");
// toggled off, Crop gives back the panel it took the place of (KEY-INFO / UiState::toggle_panel)
assert_eq!(h.app.ui.right, before, "the global crop toggle is reachable from tab focus");
assert_ne!(before, RightPanel::Crop);
}
#[test]
+393
View File
@@ -0,0 +1,393 @@
//! The panel a tool takes the place of comes back when the tool closes (item 12 of the evening
//! retest): open Edit → Masking (or Crop) → close it → Edit again, at the same width and scroll
//! position, with the photo where it was; a hidden panel stays hidden.
use std::time::Duration;
use serde_json::json;
use crate::headless::Headless;
use crate::state::RightPanel;
use crate::{LightcraftApp, Services};
const T: Duration = Duration::from_secs(20);
const SETTLE: Duration = Duration::from_secs(120);
fn detail() -> Headless {
let services = Services { png: None, ..Default::default() };
let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services);
let mut h = Headless::new(app, [1400.0, 900.0], 1.0);
let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(SETTLE);
h
}
fn exec(h: &mut Headless, command: &str) {
let r = h.request("engine.execute", json!({"command": command, "params": {}}), T);
assert_eq!(r["ok"], true, "{command}: {r}");
h.step();
h.step();
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
/// The Edit panel's first slider on show (its id and where it is: it moves when the panel scrolls).
fn first_slider(h: &Headless) -> (String, egui::Rect) {
let panel = widget(h, "panel:right_panel").expect("the right panel");
h.app
.widgets
.iter()
.filter(|(w, r)| w.starts_with("slider:") && panel.contains_rect(*r))
.min_by(|a, b| a.1.top().total_cmp(&b.1.top()))
.map(|(w, r)| (w.clone(), *r))
.expect("a slider in the Edit panel")
}
#[test]
fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() {
let mut h = detail();
// scroll the Edit panel down a little (the wheel scrolls what the pointer is over)
let panel = widget(&h, "panel:right_panel").expect("the right panel");
h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T);
let r = h.request("ui.scroll", json!({"dy": -300.0}), T);
assert_eq!(r["ok"], true, "{r}");
for _ in 0..60 {
h.step();
}
let (slider, at) = first_slider(&h);
let photo = widget(&h, "canvas:image").expect("the photo");
for tool in ["panel.masking", "panel.crop", "panel.remove", "panel.redeye"] {
exec(&mut h, tool);
assert!(h.app.ui.right.is_tool(), "{tool}: {:?}", h.app.ui.right);
assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: the panel keeps its place and width");
// the same button again closes the tool: Edit is back, as it was
exec(&mut h, tool);
assert_eq!(h.app.ui.right, RightPanel::Edit, "{tool}: the Edit panel comes back");
assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: same place and width");
assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo didn't move");
assert_eq!(widget(&h, &slider), Some(at), "{tool}: Edit kept its scroll position");
}
// Masking, then Crop from it, then Crop closed: exactly what was there before, Masking (note 21); then Edit
exec(&mut h, "panel.masking");
exec(&mut h, "panel.crop");
exec(&mut h, "panel.crop");
assert_eq!(h.app.ui.right, RightPanel::Masking);
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Edit);
// Return (Done) in a tool also goes back
exec(&mut h, "panel.masking");
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::Edit);
}
#[test]
fn a_hidden_panel_stays_hidden_after_a_tool() {
let mut h = detail();
exec(&mut h, "panel.close");
assert_eq!(h.app.ui.right, RightPanel::None);
let photo = widget(&h, "canvas:image").expect("the photo");
for tool in ["panel.masking", "panel.crop"] {
exec(&mut h, tool);
assert!(h.app.ui.right.is_tool(), "{tool} shows");
exec(&mut h, tool);
assert_eq!(h.app.ui.right, RightPanel::None, "{tool}: nothing shows again");
h.settle(SETTLE);
assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo is where it was");
}
exec(&mut h, "panel.masking");
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::None, "Done: hidden as before");
// a panel picked meanwhile is what comes back: Info → Masking → closed = Info
exec(&mut h, "panel.info");
exec(&mut h, "panel.masking");
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Info);
}
/// "I" toggles the Info panel; pressing it again brings back exactly what the right column showed before, closed
/// included (test notes 2026-10-24 note 21: the Edit sliders stayed gone).
#[test]
fn info_toggled_off_brings_back_exactly_what_was_there() {
let mut h = detail();
assert_eq!(h.app.ui.right, RightPanel::Edit);
// the key, as the user pressed it
let key = |h: &mut Headless| {
let r = h.request("ui.key", json!({"key": "I"}), T);
assert_eq!(r["ok"], true, "{r}");
h.step();
h.step();
};
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::Info);
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → I = Edit");
exec(&mut h, "panel.masking");
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::Info);
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks");
// and Masks still closes back to Edit
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Edit);
for panel in ["panel.keywords", "panel.versions", "panel.activity"] {
exec(&mut h, panel);
exec(&mut h, panel);
assert_eq!(h.app.ui.right, RightPanel::Edit, "{panel} toggled off: Edit again");
}
exec(&mut h, "panel.close");
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::Info);
key(&mut h);
assert_eq!(h.app.ui.right, RightPanel::None, "closed → I → I = closed");
}
/// A `ui.set` that changes something else (here the panel width) keeps a pending toggle: I still puts Edit back
/// (CodeRabbit on #3031).
#[test]
fn a_ui_set_between_the_two_presses_keeps_the_toggle() {
let mut h = detail();
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Info);
let r = h.request("ui.set", json!({"rightWidth": 320.0}), T);
assert_eq!(r["ok"], true, "{r}");
h.step();
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → ui.set → I = Edit");
}
/// A tool panel restored from the saved UI state (the panel before it unknown) closes to Edit, not to a hidden column.
#[test]
fn a_tool_restored_from_saved_state_closes_to_edit() {
let mut ui: crate::state::UiState = serde_json::from_str(r#"{"right": "crop"}"#).unwrap();
assert_eq!(ui.right, RightPanel::Crop);
ui.note_right();
assert_eq!(ui.leave_tool(), RightPanel::Edit);
}
/// F8 hiding a tool and F8 showing it again keeps what the tool closes to: Info → Crop → F8 → F8 → Done = Info, not a
/// hidden column (CodeRabbit on #3031).
#[test]
fn a_tool_hidden_and_shown_by_f8_still_closes_to_the_panel_before_it() {
let mut h = detail();
for close in ["tool.done", "panel.crop"] {
exec(&mut h, "panel.close");
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Info);
exec(&mut h, "panel.crop");
assert_eq!(h.app.ui.right, RightPanel::Crop);
exec(&mut h, "view.rightPanel");
assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop");
exec(&mut h, "view.rightPanel");
assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again");
exec(&mut h, close);
assert_eq!(h.app.ui.right, RightPanel::Info, "{close}: Info → Crop → F8 → F8 → closed = Info");
}
// a panel picked while the tool was hidden is not undone: Crop → F8 → Masking → closed = closed, as before
exec(&mut h, "panel.close");
exec(&mut h, "panel.crop");
exec(&mut h, "view.rightPanel");
exec(&mut h, "panel.info");
exec(&mut h, "panel.masking");
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Info, "a panel picked after F8 is what comes back");
}
/// A tool opened another way on the column F8 hid is not F8 showing a tool again: Info → Crop → F8 → Brush → Done
/// leaves the column hidden, as it was when the brush was picked (CodeRabbit on #3031).
#[test]
fn a_tool_opened_on_the_column_f8_hid_closes_to_the_hidden_column() {
let mut h = detail();
exec(&mut h, "panel.close");
exec(&mut h, "panel.info");
exec(&mut h, "panel.crop");
exec(&mut h, "view.rightPanel");
assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop");
exec(&mut h, "tool.brush");
assert_eq!(h.app.ui.right, RightPanel::Masking);
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::None, "Info → Crop → F8 → Brush → Done = hidden");
}
/// A tool opened from another tool keeps where it closes to across F8: Masking → Crop → F8 → F8 → closed = Masking,
/// and Masking then closes to Edit (CodeRabbit on #3031).
#[test]
fn a_nested_tool_hidden_and_shown_by_f8_still_closes_to_the_tool_before_it() {
let mut h = detail();
for close in ["tool.done", "panel.crop"] {
exec(&mut h, "panel.masking");
exec(&mut h, "panel.crop");
assert_eq!(h.app.ui.right, RightPanel::Crop);
exec(&mut h, "view.rightPanel");
assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop");
exec(&mut h, "view.rightPanel");
assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again");
exec(&mut h, close);
assert_eq!(h.app.ui.right, RightPanel::Masking, "{close}: Masking → Crop → F8 → F8 → closed = Masking");
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Edit, "{close}: then Masking closes to Edit");
}
}
/// Toggles nest: Edit → I → K → K → I = Edit, each press taking back exactly the one before it (CodeRabbit on #3031).
#[test]
fn nested_panel_toggles_come_back_one_at_a_time() {
let mut h = detail();
exec(&mut h, "panel.info");
exec(&mut h, "panel.keywords");
assert_eq!(h.app.ui.right, RightPanel::Keywords);
exec(&mut h, "panel.keywords");
assert_eq!(h.app.ui.right, RightPanel::Info, "Keywords toggled off: Info again");
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Edit, "Info toggled off: Edit again");
// pressing two keys in turn many times keeps a bounded history and still unwinds to a panel
for _ in 0..crate::state::TOGGLE_HISTORY {
exec(&mut h, "panel.info");
exec(&mut h, "panel.keywords");
}
assert!(h.app.ui.toggle_return.len() <= crate::state::TOGGLE_HISTORY);
exec(&mut h, "panel.keywords");
assert_eq!(h.app.ui.right, RightPanel::Info);
}
/// A tool opened by a command from another tool closes back to that tool, and the panels before it still come back
/// in turn: Info → Crop → B → Done = Crop, Crop closed = Info, I = Edit (CodeRabbit on #3031).
#[test]
fn a_tool_opened_from_another_tool_closes_back_to_it() {
let mut h = detail();
exec(&mut h, "panel.info");
exec(&mut h, "panel.crop");
exec(&mut h, "tool.brush");
assert_eq!(h.app.ui.right, RightPanel::Masking);
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::Crop, "Info → Crop → B → Done = Crop");
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::Info, "then Crop closes to Info");
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Edit, "and I gives back Edit");
// a tool opened by a command from a panel closes to that panel
exec(&mut h, "tool.brush");
exec(&mut h, "tool.done");
assert_eq!(h.app.ui.right, RightPanel::Edit);
}
/// Commands run back to back with no frame between them (a batch of control requests) see F8's hide at once:
/// Info → Crop → F8 → Brush → Done leaves the column hidden (CodeRabbit on #3031).
#[test]
fn f8_is_noted_before_the_next_command_of_the_same_frame() {
let mut h = detail();
exec(&mut h, "panel.close");
for command in ["panel.info", "panel.crop", "view.rightPanel", "tool.brush", "tool.done"] {
h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}"));
}
assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column");
}
/// Info → Remove → F8 → A (Visualize Spots opens Remove again on the hidden column) → Done leaves the column
/// hidden: F8 kept Remove's record, but this opening is a new one, from the hidden column (CodeRabbit on #3031).
#[test]
fn a_tool_hidden_by_f8_and_opened_again_by_a_command_closes_to_the_hidden_column() {
let mut h = detail();
for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots"] {
h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}"));
}
assert_eq!(h.app.ui.right, RightPanel::Remove);
h.app.run("tool.done", json!({})).unwrap_or_else(|e| panic!("tool.done: {e}"));
assert_eq!(h.app.ui.right, RightPanel::None, "Remove was opened again on the hidden column");
// the same steps a frame apart
let mut h = detail();
for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots", "tool.done"] {
exec(&mut h, command);
}
assert_eq!(h.app.ui.right, RightPanel::None, "frame by frame");
}
/// Commands run in one frame (a script, queued shortcuts) each see the panel the one before left: Close Panel →
/// B → Done keeps the column hidden, and B → A → Done goes back to Masking (CodeRabbit on #3031).
#[test]
fn every_command_notes_the_panel_it_leaves_on_show() {
let mut h = detail();
for command in ["panel.close", "tool.brush", "tool.done"] {
h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}"));
}
assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column");
let mut h = detail();
for command in ["tool.brush", "view.visualizeSpots", "tool.done"] {
h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}"));
}
assert_eq!(h.app.ui.right, RightPanel::Masking, "Remove was opened from Masking");
}
/// `ui.set` changing the panel notes it at once: a tool opened before the next frame closes back to that panel
/// (CodeRabbit on #3031).
#[test]
fn a_panel_set_by_ui_set_is_noted_before_the_next_command() {
let mut h = detail();
let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"right": "info"}));
let ctx = h.view.ctx.clone();
let _ = crate::control::handle(&mut h.app, &ctx, &req);
assert_eq!(h.app.ui.right, RightPanel::Info);
for command in ["tool.brush", "tool.done"] {
h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}"));
}
assert_eq!(h.app.ui.right, RightPanel::Info, "the brush was opened from Info");
}
/// A tool panel put back by a toggle brings its own on-canvas tool back: Masking's Brush, Remove's Heal or Clone
/// (CodeRabbit on #3031). The panels come back as before (Edit → I → K → K → I = Edit).
#[test]
fn a_panel_put_back_by_a_toggle_keeps_its_tool() {
let mut h = detail();
exec(&mut h, "panel.masking");
h.app.ui.tool = "brush".into();
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Info);
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks");
assert_eq!(h.app.ui.tool, "brush", "Masks → I → I keeps the Brush");
exec(&mut h, "panel.masking");
assert_eq!(h.app.ui.right, RightPanel::Edit);
assert_eq!(h.app.ui.tool, "", "Edit comes back with no tool");
exec(&mut h, "panel.remove");
assert_eq!(h.app.ui.right, RightPanel::Remove);
for mode in ["heal", "clone"] {
h.app.ui.tool = mode.into();
exec(&mut h, "panel.info");
exec(&mut h, "panel.info");
assert_eq!(h.app.ui.right, RightPanel::Remove);
assert_eq!(h.app.ui.tool, mode, "Remove → I → I keeps {mode}");
}
exec(&mut h, "panel.remove");
assert_eq!(h.app.ui.right, RightPanel::Edit);
// the panels themselves come back as before
for (command, right) in [
("panel.info", RightPanel::Info),
("panel.keywords", RightPanel::Keywords),
("panel.keywords", RightPanel::Info),
("panel.info", RightPanel::Edit),
] {
exec(&mut h, command);
assert_eq!(h.app.ui.right, right, "Edit → I → K → K → I, after {command}");
}
}
/// A toggle that opens a panel while the Tools column is behind another dock tab remembers the
/// column as hidden: toggled off, it doesn't come back with the panel or the on-canvas tool it held
/// out of sight (CodeRabbit on #3031: Remove in Heal behind another tab came back with Heal armed).
#[test]
fn a_toggle_over_a_hidden_tools_column_puts_back_a_hidden_column() {
let mut ui = crate::state::UiState { right: RightPanel::Remove, tool: "heal".into(), ..Default::default() };
assert!(ui.toggle_panel(RightPanel::Info, false), "Info comes up");
assert_eq!(ui.right, RightPanel::Info);
assert!(!ui.toggle_panel(RightPanel::Info, true), "and goes");
assert_eq!(ui.right, RightPanel::None, "the column was out of sight: it stays out of sight");
assert_eq!(ui.tool, "heal", "no tool put back (the command clears it)");
let mut ui = crate::state::UiState { right: RightPanel::Edit, ..Default::default() };
ui.toggle_panel(RightPanel::Info, false);
ui.toggle_panel(RightPanel::Info, true);
assert_eq!(ui.right, RightPanel::None, "Edit behind another tab isn't brought forward either");
}
+2
View File
@@ -164,6 +164,8 @@ stay in the local library, so later adjustments and exports work without the con
The worker requires Metal and accepts one editing connection at a time. It loads weights
on demand and releases them when the client disconnects or remains idle for ten minutes.
If the listener reports an accept error, the worker logs it, waits 100 ms, and retries; startup
validation and bind errors still stop the worker.
Both endpoints require loopback addresses: SSH provides authentication and encryption.
The listener has no independent authentication; do not expose it through a public proxy. Any
process of any user on the worker Mac can connect to it, and on the editing computer a local
+1
View File
@@ -100,6 +100,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed |
| 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed |
| 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed |
| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker logs and retries listener accept errors after 100 ms; startup and bind failures remain errors; gap ranking and readiness unchanged |
| 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain |
| 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) |
| 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes |
+8 -5
View File
@@ -300,7 +300,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) |
| LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) |
| LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) |
| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) |
| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle; the remote worker retries listener accept errors after 100 ms (#2574), isolating client failures; it is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) |
| LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic |
| LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty |
| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt |
@@ -329,7 +329,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails); a preset changes only the settings it names: each is computed on the photo's import state (or on its current settings when no default preset recorded one), and every setting it does not name keeps the photo's value, so a second preset restores what an earlier one changed in the settings it names (issue #2159) |
| LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`) | name, group and a checklist of settings groups (crop, masks, remove, red eye off by default; All / None) |
| LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests/preset_favorites.rs`); no hiding of groups |
| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded |
| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded; sliders and tone-curve points blend with the amount, switches and choices (profile/LUT, treatment, styles) take the preset's value from half amount, and the strength of a profile or `enabled` group the preset changes fades in from 0 there; white balance on another scale (Kelvin vs relative) is never blended (`interpolate_object`, `crates/develop/src/presets.rs`, issue #2669) |
| LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | |
| LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) |
| LR-PRE-RECOMMENDED | Community recommendations | OOS | 🚫 | | |
@@ -481,7 +481,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menus/menubar.rs`, `crates/ui-egui/src/tests/panels.rs` | View ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:<id>`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden |
| LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests/panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before: <section>\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another |
| LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests/panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:<id>`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:<id>`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:<id>`, with View ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button |
| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests/panels.rs` | drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed |
| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/src/tests/panel_restore.rs` | closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it in the same frame, at the same width and scroll position, or leaves it hidden if it was (`UiState::leave_tool`); drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed |
| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests/empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. Files dragged over the window dim it and a card says what dropping will do; a drop of photos or folders opens the same import review as File ▸ Import |
| LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | |
| LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu |
@@ -612,7 +612,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained
| KEY-FULLSCREEN | Full-screen preview — F | P1 | ✅ | `cmd:view.fullScreenPreview` | |
| KEY-LIGHTSOUT | Lights Out — Shift+L (Classic's L is Linear Gradient here) | P2 | ✅ | `cmd:view.lightsOut` | On → Dim (80 %) → Off; Esc turns the lights on |
| KEY-GRID | Grid — G | P0 | ✅ | `cmd:view.gridToggle`, `cmd:view.photoGrid` | G toggles Photo Grid ↔ Square Grid; both View menu rows show its live shortcut (including remapping/unbinding), with direct grid bindings taking priority; menu clicks still choose the named grid (#2500) |
| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info` | |
| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info`, `crates/ui-egui/src/tests/panel_restore.rs` | pressing I again brings back exactly what the right column showed before (Edit, Masks…; closed stays closed); every panel key and button does the same (`UiState::toggle_panel`) |
| KEY-KEYWORDS | Keywords — K | P0 | ✅ | `cmd:panel.keywords` | |
| KEY-CLIPBOARD | Copy / paste edit settings — ⌘C / ⌘V | P0 | ✅ | `cmd:develop.copy`, `cmd:develop.paste`, `crates/ui-egui/src/shortcuts.rs` (`matches`) | ⌘X has nothing to cut outside text fields; on Windows and Linux, where the windowing layer sends Ctrl+C / Ctrl+V as clipboard events rather than key presses, those run the shortcuts too (⇧Insert pastes plainly); there Ctrl+V only arrives while the system clipboard holds text (egui-winit drops it otherwise), so with an empty clipboard Paste Settings needs the menu |
| KEY-UNDOREDO | Undo / redo — ⌘Z / ⇧⌘Z | P0 | ✅ | `cmd:edit.undo`, `cmd:edit.redo` | |
@@ -688,7 +688,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained
| KEY-HELP | Help — F1 | P2 | ✅ | `cmd:app.help` | |
| KEY-VIDEO-PLAY | Play/pause video — Space | P1 | ⬜ | | |
| KEY-ESC | Leave tool / view — Esc | P0 | ✅ | `cmd:view.back`, `crates/ui-egui/src/icons.rs` (`navigation_arrowheads_have_both_halves`), `crates/ui-egui/src/tests/crop_tool.rs` | top-bar navigation arrowheads render both halves at 1× and 2× scale; in the crop tool Esc closes the tool first (the crop stays), the next Esc goes back to the grid; Esc that ends an edit in a text field does nothing else |
| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking back to Edit (edits apply live, as in Lightroom) |
| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking and goes back to the panel shown before the tool, the right column hidden again if it was (edits apply live, as in Lightroom) |
| KEY-DELETE-PIN | Delete selected pin — ⌫ | P0 | ✅ | `cmd:mask.delete`, `cmd:spot.delete` | ⌫ deletes the active mask (Masking) or the selected spot (Remove), never the photo while retouching |
| KEY-HIDEPINS | Hide pins — H | P2 | 🟡 | `cmd:view.toolOverlay`, `cmd:view.maskPins`, `cmd:panel.remove`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/tests/tool_overlay.rs`, `crates/ui-egui/src/tests/keymap.rs` (`h_toggles_the_mask_pins_while_masking`, `h_while_masking_does_not_open_remove`, `h_opens_remove_when_another_panel_is_active`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`, `h_keeps_its_binding_in_the_full_screen_preview`, `h_keeps_its_binding_when_the_masking_panel_is_not_exposed`) | ⇧H cycles the Tool Overlay (Auto → Always → Selected → Never) for spot and mask pins; also View ▸ Tool Overlay and the Remove / Masking panels (#224). In the visible Masking panel an unmodified H itself toggles the mask pins (the same switch as View ▸ Show Mask Pins) and does not open Remove; the toggle yields only to an explicit assignment of H itself, and a Remove key reassigned to anything else still opens Remove there. Outside Masking — and wherever no panel shows (the full-screen preview, a minimized or hidden panel) — H keeps its own binding (Remove, by default). Remove's spot pins have no H hide toggle (⇧H only), so the row is partial |
@@ -807,6 +807,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| Date | Change | Summary |
|---|---|---|
| 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-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 |
@@ -824,7 +825,9 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-27 | minor | LRC-LIB-PREVIEWS: the loupe shows built and prepared previews instead of rendering again, builds skip what is there and Build Previews with one photo open builds the view; LRC-PERF-PREP new (🟡): preparing photos in the background per mode |
| 2026-10-27 | minor | Culling speed: LR-IMP-LOCAL browsing shows the first photos within a second; LR-IMP-PREVIEW-READ a CR3's smallest covering JPEG, plain sRGB JPEGs straight to 8-bit, camera-JPEG thumbnails kept; LR-VIEW-DETAIL camera previews made ahead of the step, “Camera preview” label, camera JPEG first at 100 %; statuses unchanged |
| 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped |
| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker retries transient listener accept errors after 100 ms; client failures remain isolated; feature counts unchanged |
| 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) |
| 2026-10-26 | minor | LR-BEHAV-PANEL-RESIZE, KEY-INFO: closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it, hidden if it was hidden, at the same width and scroll position; a panel key or button (I, M, C, H…) pressed again puts back exactly what the right column showed before it (Edit → I → I = Edit, closed → I → I = closed); status unchanged (✅) |
| 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca |
| 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged |
| 2026-10-25 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K / Ctrl+Alt+Shift+K (`dialog.keywordShortcut`, Set Keyword Shortcut) and ⇧K (`keyword.toggleShortcut`) add and remove the keyword shortcut's keywords; Keyword Shortcut leaves LRC-LIB-KEYWORDS' Not yet list; status counts unchanged (KEYC-METADATA stays 🟡) |
+48
View File
@@ -0,0 +1,48 @@
# Sharp downscale threshold measurement
Compare the Sharp export resizer with prefilter thresholds k > 1.0 and k > 1.25, where k is source width / output width. Smooth previews retain their existing threshold. These numbers measure the resize operation; they do not establish perceptual quality, halo visibility, or behavior under every geometric warp.
Six existing CC0-1.0 RAW corpus records were verified against their manifest SHA-256 before decoding through the engine. The native sensor decode was required (not the embedded JPEG). Numeric linear Rec.2020 luminance uses weights 0.2627, 0.6780, 0.0593.
## Method
- Five fixed 500 x 500 source tiles per file, at 20%/80% corners and center of the available tile-origin range. No content-based tile selection.
- Export scales 0.9, 0.8, 0.7; actual Frame::sample with Lanczos3. The old path at k <= 1.25 is reproduced with its bilinear mapping; at 0.7 both thresholds use the same Lanczos path, providing an unchanged control.
- Alias proxy: mirror-pad each source tile by 250 pixels; FFT-isolate frequencies outside the target Nyquist square (either axis greater than scale/2 cycles/source pixel), inverse transform, crop to the original tile, then resize that signed high-band component through each path. Measure mean-square output energy, excluding 12 output pixels on each border. This measures folded energy from the removed source band rather than calling all output high frequencies aliases.
- Edge acutance proxy: mean of the strongest 5% Sobel gradient magnitudes in the resized ordinary tile, divided by its 95th-minus-5th-percentile luminance contrast; same border exclusion. Average five tiles per file. Percent changes compare threshold 1.0 against 1.25.
## Results across six files
- Scale 0.9: alias energy -25.48% (range -26.39% to -20.30%); edge acutance +4.62% (range +3.15% to +8.37%).
- Scale 0.8: alias energy -65.59% (range -66.07% to -62.74%); edge acutance +3.59% (range +2.39% to +6.03%).
- Scale 0.7: alias energy +0.00% (range +0.00% to +0.00%); edge acutance +0.00% (range +0.00% to +0.00%).
## Per-file changes
- Canon EOS 7D, 0.9: alias energy -25.70%; edge acutance +8.37%.
- Canon EOS 7D, 0.8: alias energy -64.35%; edge acutance +6.03%.
- Canon EOS 7D, 0.7: alias energy +0.00%; edge acutance +0.00%.
- Sony ILCE-7M3, 0.9: alias energy -24.27%; edge acutance +6.70%.
- Sony ILCE-7M3, 0.8: alias energy -62.74%; edge acutance +5.93%.
- Sony ILCE-7M3, 0.7: alias energy +0.00%; edge acutance +0.00%.
- Nikon D7000, 0.9: alias energy -26.02%; edge acutance +3.63%.
- Nikon D7000, 0.8: alias energy -65.91%; edge acutance +3.17%.
- Nikon D7000, 0.7: alias energy +0.00%; edge acutance +0.00%.
- Panasonic DMC-GF6, 0.9: alias energy -25.25%; edge acutance +4.42%.
- Panasonic DMC-GF6, 0.8: alias energy -65.70%; edge acutance +3.94%.
- Panasonic DMC-GF6, 0.7: alias energy +0.00%; edge acutance +0.00%.
- Pentax K-5, 0.9: alias energy -26.39%; edge acutance +3.15%.
- Pentax K-5, 0.8: alias energy -66.07%; edge acutance +2.39%.
- Pentax K-5, 0.7: alias energy +0.00%; edge acutance +0.00%.
- Fujifilm X-T3, 0.9: alias energy -20.30%; edge acutance +4.83%.
- Fujifilm X-T3, 0.8: alias energy -65.48%; edge acutance +3.23%.
- Fujifilm X-T3, 0.7: alias energy +0.00%; edge acutance +0.00%.
## Source records
- [Canon EOS 7D, record 131](https://raw.pixls.us/getfile.php/131/nice/Canon%20-%20EOS%207D%20-%20RAW%20%283:2%29.CR2), CC0-1.0; SHA-256 `b5e47c5fcf7332ac03e0134926f17a338a42e68c1fd7f83e16f45f4b767544e8`.
- [Sony ILCE-7M3, record 2414](https://raw.pixls.us/getfile.php/2414/nice/Sony%20-%20ILCE-7M3%20-%2014bit%2014bit%20compressed%20%283:2%29.ARW), CC0-1.0; SHA-256 `250784580ea527442c09004417bb0eead484f2bf3ee8f9121a776ac65bb50d0f`.
- [Nikon D7000, record 958](https://raw.pixls.us/getfile.php/958/nice/Nikon%20-%20D7000%20-%2014bit%2014bit%20compressed%20%28Lossless%29%20%283:2%29.NEF), CC0-1.0; SHA-256 `639945753240005d80488c0462c01e73a7ab82c96d3d1cdb6661f02e1b3c1319`.
- [Panasonic DMC-GF6, record 739](https://raw.pixls.us/getfile.php/739/nice/Panasonic%20-%20DMC-GF6%20-%204:3.RW2), CC0-1.0; SHA-256 `dace6b3818f00a5d4f7cc1cfc29744d15dcf7dd8684c882bea4a81c6ef670ad0`.
- [Pentax K-5, record 1479](https://raw.pixls.us/getfile.php/1479/nice/Pentax%20-%20K-5%20-%2014bit%20%283:2%29.DNG), CC0-1.0; SHA-256 `6f6419209340d07d597ccca66dc367d64cff3308ef2694c8f90c6259f3a5c431`.
- [Fujifilm X-T3, record 2783](https://raw.pixls.us/getfile.php/2783/nice/Fujifilm%20-%20X-T3%20-%2014bit%2014bit%20compressed%20%283:2%29.RAF), CC0-1.0; SHA-256 `95b33021160b239ceb1a09d46a1b29cb60cb7dd47581feb126b337c219091754`.
+14
View File
@@ -171,6 +171,12 @@
- Importing a backup of a catalog you already imported no longer adds every collection a second time: collections
are matched by the catalog's own id, which its backups keep, instead of by the catalog file's path.
## 2026-11-04
### Remote SAM worker recovers from accept errors
- A transient connection-accept error is logged and retried after a short pause, so one failed accept no longer
stops the remote Metal worker (#2574). Startup validation and bind failures still report an error.
### Reference View's empty state paints on every platform
- Its instruction now uses the supported menu arrow symbol, avoiding a missing-glyph panic while the view is drawn.
## 2026-10-30
### Lightroom catalogs with a print inside a collection import their collections
@@ -405,6 +411,14 @@
on macOS 15 and later, and Minimize All, Zoom All and Arrange in Front while Option is held.
## 2026-10-26
### Panels come back as they were
- Close Masking, Crop, Remove or Red Eye and the panel you came from is there again, at the same width and scroll
position, and the photo doesn't move; if the panel was hidden, it stays hidden. Pressing a panel key a second time
(I for Info, M for Masking, C for Crop, H for Remove) or its tool-strip button puts back exactly what the right
column showed before: Edit → I → I is Edit again, Masks → I → I is Masks, and a closed panel stays closed.
## 2026-10-25
### A one-field white balance edit no longer shifts the other one