From 357b16b8d81b69bff6677b85860947177f4ab679 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:03:03 +0200 Subject: [PATCH 001/247] M12: SAM 3 on the CPU ~3x faster: encode ~37 -> ~11 s, a description ~6 -> ~2 s On the CPU, candle runs elementwise ops and layout copies on one thread, batched matmuls one batch element after another (each spread over all threads) and transposed convolutions one output channel at a time. In the 32-layer ViT that was more than half of the ~37 s encode on a 12-core Ryzen 9 3900X; a text prompt spent most of its ~6 s in the DETR encoder's attention over 5184 tokens. crates/segment/src/cpu.rs, used on the CPU only (Metal keeps the tensor ops): - fused parallel kernels for the bias adds with GELU / ReLU / residual add, the ViT's window partition + head split + RoPE (with the 1/8 score scale moved to q, exact for a power of two) and head merge, the detector's box relative-position bias and the pixel decoder's GroupNorm + ReLU: the same float operations in the same order, bit-identical results; - sdpa as one rayon task per (batch, head, block of query rows), with 256 KB score blocks that stay in the core's cache (4 MB blocks were 3x slower for the detector's 8 heads of 32); - the necks' 2x2 stride-2 transposed convolutions as one matmul plus a reordering. The last two change how gemm blocks its sums, so results move by float rounding only, as between two CPUs (gemm picks its blocking from the cache sizes). Against the unchanged code on a real photo: backbone 1.1e-5 relative, click mask 1e-5 with no pixel changing side, text masks <= 7e-4 with at most 6 of 16.6M pixels changing side, the same kept instances. Ryzen 9 3900X, 24 threads: encode ~37 -> ~11 s, preparing clicks ~2.3 -> ~0.9 s, a description ~6 -> ~2.1 s (the first one on a photo also builds the detector's features: ~8.8 -> ~2.9 s). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/segment/Cargo.toml | 2 + crates/segment/src/clip.rs | 2 +- crates/segment/src/cpu.rs | 551 +++++++++++++++++++++++++++++++++ crates/segment/src/detector.rs | 21 +- crates/segment/src/lib.rs | 2 + crates/segment/src/neck.rs | 5 +- crates/segment/src/nn.rs | 50 ++- crates/segment/src/vit.rs | 113 ++++++- docs/ai-masks.md | 26 +- 10 files changed, 741 insertions(+), 32 deletions(-) create mode 100644 crates/segment/src/cpu.rs diff --git a/Cargo.lock b/Cargo.lock index 4b6d54289f..f94a68a2ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3465,6 +3465,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/src/clip.rs b/crates/segment/src/clip.rs index b69c148a4f..18a82b3dd0 100644 --- a/crates/segment/src/clip.rs +++ b/crates/segment/src/clip.rs @@ -74,7 +74,7 @@ impl TextEncoder { let h = l.ln1.forward(&x)?; x = (&x + l.attn.forward(&h, &h, &h, Some(&bias))?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } Ok(self.final_ln.forward(&x)?) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..ffbd0bde6c --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,551 @@ +//! Fused CPU kernels for the model's elementwise work, attention and upsampling. +//! +//! On the CPU, candle runs bias adds, activations, the rotary encoding and layout copies (window +//! partitioning, splitting and merging heads) one element at a time on one thread, batched matrix +//! products one pair at a time and transposed convolutions one output channel at a time: in the +//! 32-layer ViT that was more than half of the encode time on a 12-core CPU, and most of a text +//! prompt went to attention over 5184 tokens. The elementwise kernels do the same arithmetic in +//! the same order (bit-identical results), fused into fewer passes over memory and spread over +//! the rayon pool that candle's matrix products use. Attention in cache-sized blocks and the +//! transposed convolutions as one product change how gemm blocks its sums: those results move +//! by float rounding (as they do between two CPUs, gemm picking its blocking from the caches). + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp1, CustomOp2, CustomOp3, D, IndexOp, Layout, Shape, Tensor, bail}; +use candle_nn::{ConvTranspose2d, Linear}; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// A `b × h × w` token grid (row-major, `heads × head_dim` channels) attended in non-overlapping +/// `win × win` windows, or as a whole when `win` is 0. +#[derive(Clone, Copy, Debug)] +pub struct Grid { + pub b: usize, + pub h: usize, + pub w: usize, + pub win: usize, + pub heads: usize, + pub head_dim: usize, +} + +impl Grid { + /// Window height and width. + fn window(&self) -> (usize, usize) { + if self.win == 0 { (self.h, self.w) } else { (self.win, self.win) } + } + + /// Windows per image (down, across). + fn per_image(&self) -> (usize, usize) { + let (wh, ww) = self.window(); + (self.h / wh, self.w / ww) + } + + fn windows(&self) -> usize { + let (nh, nw) = self.per_image(); + self.b * nh * nw + } + + fn tokens(&self) -> usize { + let (wh, ww) = self.window(); + wh * ww + } + + fn channels(&self) -> usize { + self.heads * self.head_dim + } + + fn check(&self) -> candle_core::Result<()> { + let (wh, ww) = self.window(); + if wh == 0 || ww == 0 || !self.h.is_multiple_of(wh) || !self.w.is_multiple_of(ww) || !self.head_dim.is_multiple_of(2) { + bail!("grid {self:?}: windows must tile the grid"); + } + Ok(()) + } + + /// The grid row (token index in row-major order) of token `t` of window `win`. + fn row(&self, win: usize, t: usize) -> usize { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (win / (nh * nw), win % (nh * nw)); + let (y, x) = (i / nw * wh + t / ww, i % nw * ww + t % ww); + (b * self.h + y) * self.w + x + } + + /// The window and the token within it of grid row `row`. + fn window_of(&self, row: usize) -> (usize, usize) { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (row / (self.h * self.w), row % (self.h * self.w)); + let (y, x) = (i / self.w, i % self.w); + ((b * nh + y / wh) * nw + x / ww, y % wh * ww + x % ww) + } +} + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// `residual + (x · Wᵀ + b)`, shaped like `residual`. +pub fn linear_add(x: &Tensor, l: &Linear, residual: &Tensor) -> Result { + Ok(product(x, l)?.apply_op3_no_bwd(bias(l)?, &residual.contiguous()?, &BiasAdd)?) +} + +/// The projection `x · Wᵀ + b` of the grid's tokens (`x`: `[b, h, w, C]`), split into heads per +/// window: `[windows, heads, tokens, head_dim]`, with the rotary encoding (`cos`, `sin`: +/// `[tokens, head_dim]`) applied when given, then multiplied by `scale`. +pub fn heads(x: &Tensor, l: &Linear, grid: Grid, rope: Option<(&[f32], &[f32])>, scale: f32) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &Heads { grid, rope, scale })?) +} + +/// Attention scores computed per task (elements): a block of query rows against all keys, +/// small enough (256 KB) to stay in a core's L2 cache between the two products and the softmax. +/// 4 MB blocks were 3× slower for the detector's 5184-token attention (8 heads of 32). +const SCORE_TILE: usize = 1 << 16; + +/// `nn::sdpa` on `[B, H, L, d]` tensors (`bias` `[B or 1, H or 1, Lq or 1, Lk]`): the same +/// operations (scores × `scale` unless it is 1, plus the bias, softmax, × v), but candle +/// multiplies batched matrices one pair after another, each spread over all threads, which is +/// slow for 9 windows × 16 heads of 576 tokens or 8 heads of 5184; here every (batch, head, +/// block of query rows) is a task of its own. +pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + let (b, h, lq, _) = q.dims4()?; + let (lk, dv) = (k.dim(2)?, v.dim(3)?); + let bias = match bias { + Some(t) => Some((t, t.dims4()?)), + None => None, + }; + let rows = (SCORE_TILE / lk.max(1)).clamp(1, lq.max(1)); + let tasks: Vec<(usize, usize, usize)> = (0..b * h).flat_map(|i| (0..lq).step_by(rows).map(move |r| (i / h, i % h, r))).collect(); + let out = tasks + .par_iter() + .map(|&(bi, hi, r)| -> Result { + let n = rows.min(lq - r); + let mut att = q.i((bi, hi))?.narrow(0, r, n)?.matmul(&k.i((bi, hi))?.t()?)?; + if scale != 1.0 { + att = (att * scale)?; + } + if let Some((t, (tb, th, tq, _))) = bias { + let t = t.i((if tb == 1 { 0 } else { bi }, if th == 1 { 0 } else { hi }))?; + att = att.broadcast_add(&if tq == 1 { t } else { t.narrow(0, r, n)? })?; + } + Ok(candle_nn::ops::softmax_last_dim(&att)?.matmul(&v.i((bi, hi))?)?) + }) + .collect::>>()?; + Ok(Tensor::cat(&out, 0)?.reshape((b, h, lq, dv))?) +} + +/// Attention over `q`, `k`, `v` from [`heads`] (`q` already scaled), merged back to the grid: +/// `[b, h, w, C]`. +pub fn attention(q: &Tensor, k: &Tensor, v: &Tensor, grid: Grid) -> Result { + Ok(sdpa(q, k, v, None, 1.0)?.apply_op1_no_bwd(&Merge { grid })?) +} + +/// `ConvTranspose2d` with a 2 × 2 kernel and stride 2 (the neck's upsampling) on `x` +/// `[1, Cin, H, W]`, then GELU when `gelu`: `[1, Cout, 2H, 2W]`. The kernel windows don't overlap, +/// so this is one product `[H·W, Cin] × [Cin, Cout·4]` and a reordering with the bias; candle +/// computes it one output channel at a time (~50 GFLOP/s here). +pub fn upsample2(x: &Tensor, ct: &ConvTranspose2d, gelu: bool) -> Result { + let (b, cin, h, w) = x.dims4()?; + let (wi, cout, kh, kw) = ct.weight().dims4()?; + let c = ct.config(); + if b != 1 || wi != cin || (kh, kw, c.stride, c.padding, c.output_padding, c.dilation) != (2, 2, 2, 0, 0, 1) { + return Err(Error::Model(format!("upsample2: {:?} with a {:?} kernel", x.dims(), ct.weight().dims()))); + } + let y = x.reshape((cin, h * w))?.t()?.matmul(&ct.weight().reshape((cin, cout * 4))?)?; + let bias = match ct.bias() { + Some(b) => b.clone(), + None => Tensor::zeros(cout, candle_core::DType::F32, x.device())?, + }; + Ok(y.apply_op2_no_bwd(&bias, &Unpatch { h, w, gelu })?) +} + +/// `relu(group_norm(x))` over `[B, C, …]` with `groups` groups and per-channel `weight`, `bias`. +/// candle's `GroupNorm` makes eight single-threaded passes over the 288² pixel decoder maps. +pub fn group_norm_relu(x: &Tensor, weight: &Tensor, bias: &Tensor, groups: usize, eps: f64) -> Result { + Ok(x.contiguous()?.apply_op3_no_bwd(weight, bias, &GroupNormRelu { groups, eps })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BiasAdd; + +impl CustomOp3 for BiasAdd { + fn name(&self) -> &'static str { + "bias-residual-add" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b, r) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let n = rows(x, b)?; + if r.len() != x.len() { + bail!("residual of {} for {} values", r.len(), x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).zip(r.par_chunks(n)).for_each(|((o, x), r)| { + for (((o, x), b), r) in o.iter_mut().zip(x).zip(b).zip(r) { + *o = r + (x + b); + } + }); + Ok((CpuStorage::F32(out), l3.shape().clone())) + } +} + +struct Heads<'a> { + grid: Grid, + rope: Option<(&'a [f32], &'a [f32])>, + scale: f32, +} + +impl CustomOp2 for Heads<'_> { + fn name(&self) -> &'static str { + "split-heads-rope" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let (x, bias) = (values(s1, l1)?, values(s2, l2)?); + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if bias.len() != c || x.len() != g.b * g.h * g.w * c { + bail!("heads: {} values with a bias of {} for {g:?}", x.len(), bias.len()); + } + if let Some((cos, sin)) = self.rope + && (cos.len() != n * d || sin.len() != n * d) + { + bail!("rotary tables of {} and {} for {n} tokens", cos.len(), sin.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n * d).enumerate().for_each(|(i, o)| { + let (win, head) = (i / g.heads, i % g.heads); + let bias = &bias[head * d..][..d]; + for (t, o) in o.chunks_exact_mut(d).enumerate() { + let x = &x[g.row(win, t) * c + head * d..][..d]; + for ((o, x), b) in o.iter_mut().zip(x).zip(bias) { + *o = x + b; + } + if let Some((cos, sin)) = self.rope { + // x·cos + rotate_pairwise(x)·sin, rotate_pairwise mapping (a, b) to (−b, a) + let (cos, sin) = (&cos[t * d..][..d], &sin[t * d..][..d]); + for ((o, cos), sin) in o.as_chunks_mut::<2>().0.iter_mut().zip(cos.as_chunks::<2>().0).zip(sin.as_chunks::<2>().0) { + let [a, b] = *o; + *o = [a * cos[0] + -b * sin[0], b * cos[1] + a * sin[1]]; + } + } + for o in o.iter_mut() { + *o *= self.scale; + } + } + }); + let shape = Shape::from((g.windows(), g.heads, n, d)); + Ok((CpuStorage::F32(out), shape)) + } +} + +struct GroupNormRelu { + groups: usize, + eps: f64, +} + +impl CustomOp3 for GroupNormRelu { + fn name(&self) -> &'static str { + "group-norm-relu" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, w, b) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let dims = l1.shape().dims(); + let (batch, c) = match dims { + [batch, c, _, ..] => (*batch, *c), + _ => bail!("group norm of {dims:?}"), + }; + if c == 0 || self.groups == 0 || !c.is_multiple_of(self.groups) || w.len() != c || b.len() != c || x.is_empty() { + bail!("group norm: {dims:?} in {} groups, {} weights", self.groups, w.len()); + } + let hw = x.len() / (batch * c); + let per = c / self.groups * hw; + // mean and σ per (image, group), as candle computes them (f32 sums in order) + let n = (1.0 / per as f64) as f32; + let stats: Vec<(f32, f32)> = x + .par_chunks(per) + .map(|g| { + let mean = g.iter().fold(0f32, |s, v| s + v) * n; + let var = g.iter().fold(0f32, |s, v| s + (v - mean) * (v - mean)) * n; + (mean, (var + self.eps as f32).sqrt()) + }) + .collect(); + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(hw).zip(x.par_chunks(hw)).enumerate().for_each(|(row, (o, x))| { + let ch = row % c; + let (mean, sd) = stats[row / c * self.groups + ch / (c / self.groups)]; + for (o, x) in o.iter_mut().zip(x) { + *o = ((x - mean) / sd * w[ch] + b[ch]).max(0f32); + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +/// `[H·W, Cout·2·2]` patches (+ bias, then GELU) to `[1, Cout, 2H, 2W]`. +struct Unpatch { + h: usize, + w: usize, + gelu: bool, +} + +impl CustomOp2 for Unpatch { + fn name(&self) -> &'static str { + "unpatch-2x2" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (y, bias) = (values(s1, l1)?, values(s2, l2)?); + let (h, w, cout) = (self.h, self.w, bias.len()); + if y.len() != h * w * cout * 4 { + bail!("unpatch: {} values for {h} × {w} × {cout} × 4", y.len()); + } + let mut out = vec![0f32; y.len()]; + // one output row (channel c, row 2·r + i) at a time + out.par_chunks_mut(2 * w).enumerate().for_each(|(row, o)| { + let (c, r, i) = (row / (2 * h), row % (2 * h) / 2, row % 2); + for (x, o) in o.as_chunks_mut::<2>().0.iter_mut().enumerate() { + let p = &y[(r * w + x) * cout * 4 + c * 4 + i * 2..][..2]; + for (o, p) in o.iter_mut().zip(p) { + let v = p + bias[c]; + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v }; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, cout, 2 * h, 2 * w)))) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +struct Merge { + grid: Grid, +} + +impl CustomOp1 for Merge { + fn name(&self) -> &'static str { + "merge-heads" + } + + fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let x = values(s, l)?; + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if x.len() != g.windows() * g.heads * n * d { + bail!("merge: {} values for {g:?}", x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(c).enumerate().for_each(|(row, o)| { + let (win, t) = g.window_of(row); + for (head, o) in o.chunks_exact_mut(d).enumerate() { + o.copy_from_slice(&x[((win * g.heads + head) * n + t) * d..][..d]); + } + }); + Ok((CpuStorage::F32(out), Shape::from((g.b, g.h, g.w, c)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::{ConvTranspose2dConfig, Module}; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + /// The kernels against candle's tensor operations: equal up to float rounding (on x86-64 most + /// are bit-identical; the matrix products may block differently). + fn close(name: &str, got: &Tensor, want: &Tensor) { + assert_eq!(got.dims(), want.dims(), "{name}: shape"); + let (got, want): (Vec, Vec) = (got.flatten_all().unwrap().to_vec1().unwrap(), want.flatten_all().unwrap().to_vec1().unwrap()); + let scale = want.iter().fold(1e-6f32, |m, v| m.max(v.abs())); + let err = got.iter().zip(&want).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(err <= 1e-5 * scale, "{name}: max error {err} (scale {scale})"); + } + + #[test] + fn sdpa_matches_the_tensor_ops() { + // 1000 keys: blocks of 65 query rows, the last one short + let (q, k, v) = (randn(&[2, 3, 150, 8]), randn(&[2, 3, 1000, 8]), randn(&[2, 3, 1000, 5])); + let biases = + [None, Some(randn(&[1, 1, 1, 1000])), Some(randn(&[1, 3, 150, 1000])), Some(randn(&[2, 1, 150, 1000])), Some(randn(&[2, 3, 1, 1000]))]; + for (i, bias) in biases.iter().enumerate() { + for scale in [0.35, 1.0] { + let got = sdpa(&q, &k, &v, bias.as_ref(), scale).unwrap(); + let want = crate::nn::sdpa_tensors(&q, &k, &v, bias.as_ref(), scale).unwrap(); + close(&format!("bias {i}, scale {scale}"), &got, &want); + } + } + } + + #[test] + fn fused_linears_match_the_tensor_ops() { + let x = randn(&[3, 5, 7]); + let l = Linear::new(randn(&[6, 7]), Some(randn(&[6]))); + let y = l.forward(&x).unwrap().reshape((15, 6)).unwrap(); + close("gelu", &linear_act(&x, &l, true).unwrap(), &y.gelu_erf().unwrap()); + close("relu", &linear_act(&x, &l, false).unwrap(), &y.relu().unwrap()); + let r = randn(&[3, 5, 6]); + close("residual", &linear_add(&x, &l, &r).unwrap(), &(&r + l.forward(&x).unwrap()).unwrap()); + assert!(linear_act(&x, &Linear::new(randn(&[6, 7]), None), true).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + close("box bias", &box_bias(&ey, &ex).unwrap(), &want); + } + + #[test] + fn upsampling_matches_the_transposed_convolution() { + let x = randn(&[1, 6, 3, 4]); + let cfg = ConvTranspose2dConfig { stride: 2, ..Default::default() }; + let ct = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), Some(randn(&[5])), cfg); + let want = ct.forward(&x).unwrap(); + close("upsample", &upsample2(&x, &ct, false).unwrap(), &want); + close("upsample + gelu", &upsample2(&x, &ct, true).unwrap(), &want.gelu_erf().unwrap()); + let other = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), None, ConvTranspose2dConfig::default()); + assert!(upsample2(&x, &other, false).is_err()); + } + + #[test] + fn group_norm_matches_candle() { + let x = randn(&[2, 6, 4, 5]); + let (w, b) = (randn(&[6]), randn(&[6])); + let want = candle_nn::GroupNorm::new(w.clone(), b.clone(), 6, 3, 1e-5).unwrap().forward(&x).unwrap().relu().unwrap(); + close("group norm", &group_norm_relu(&x, &w, &b, 3, 1e-5).unwrap(), &want); + assert!(group_norm_relu(&x, &w, &b, 4, 1e-5).is_err()); + } + + #[test] + fn window_indexing_round_trips() { + for win in [0, 3] { + let g = Grid { b: 2, h: 6, w: 9, win, heads: 1, head_dim: 2 }; + g.check().unwrap(); + let mut seen = vec![false; g.b * g.h * g.w]; + for w in 0..g.windows() { + for t in 0..g.tokens() { + let row = g.row(w, t); + assert_eq!(g.window_of(row), (w, t)); + seen[row] = true; + } + } + assert!(seen.iter().all(|s| *s)); + } + assert!(Grid { b: 1, h: 6, w: 9, win: 4, heads: 1, head_dim: 2 }.check().is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index 7c4eccbd33..70c623570b 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -7,12 +7,14 @@ //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. use candle_core::{D, Device, IndexOp, Module, Tensor}; -use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; +use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; -use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::nn::{ + Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec, +}; +use crate::{Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; @@ -89,7 +91,7 @@ pub struct Detector { prompt_attn: Attention, prompt_ln: LayerNorm, pixel_convs: Vec, - pixel_norms: Vec, + pixel_norms: Vec, instance_proj: Conv2d, mask_embedder: Vec, } @@ -153,7 +155,7 @@ impl Detector { prompt_attn: Attention::new(HIDDEN, HIDDEN, HEADS, m.pp("prompt_cross_attn"))?, prompt_ln: ln(HIDDEN, TORCH_LN_EPS, m.pp("prompt_cross_attn_norm"))?, pixel_convs: (0..3).map(|i| Ok(candle_nn::conv2d(HIDDEN, HIDDEN, 3, conv3, p.pp(format!("conv_layers.{i}")))?)).collect::>()?, - pixel_norms: (0..3).map(|i| Ok(candle_nn::group_norm(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))?)).collect::>()?, + pixel_norms: (0..3).map(|i| GroupNormRelu::new(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))).collect::>()?, instance_proj: candle_nn::conv2d(HIDDEN, HIDDEN, 1, Conv2dConfig::default(), m.pp("instance_projection"))?, mask_embedder: (0..3).map(|i| linear(HIDDEN, HIDDEN, m.pp(format!("mask_embedder.layers.{i}")))).collect::>()?, }) @@ -183,6 +185,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -217,7 +222,7 @@ impl Detector { let h = l.ln2.forward(&x)?; x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; let h = l.ln3.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } let memory = x; @@ -236,7 +241,7 @@ impl Detector { h = l.text_ln.forward(&(&h + l.text_attn.forward(&q, &text, &text, Some(&text_bias))?)?)?; let q = (&h + &qpos)?; h = l.vision_ln.forward(&(&h + l.vision_attn.forward(&q, &key_pos, &memory, Some(&bias))?)?)?; - h = l.mlp_ln.forward(&(&h + l.mlp.forward(&h)?)?)?; + h = l.mlp_ln.forward(&l.mlp.forward_add(&h, &h)?)?; let qh = self.out_ln.forward(&h.narrow(1, 1, QUERIES)?)?; boxes = candle_nn::ops::sigmoid(&(self.box_head.forward(&qh)? + inverse_sigmoid(&boxes)?)?)?; let p = self.presence_head.forward(&self.presence_ln.forward(&h.narrow(1, 0, 1)?)?)?; @@ -265,7 +270,7 @@ impl Detector { let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { return Err(Error::Model("pixel decoder".into())); }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + prev = norm.forward(&conv.forward(&prev)?)?; } let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] let (_, c, mh, mw) = inst.dims4()?; diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6d488a919a..61cac2e63b 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -29,6 +29,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; diff --git a/crates/segment/src/neck.rs b/crates/segment/src/neck.rs index c4f716dd6f..46cbebf1e5 100644 --- a/crates/segment/src/neck.rs +++ b/crates/segment/src/neck.rs @@ -8,8 +8,8 @@ use candle_core::{Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, ConvTranspose2d, ConvTranspose2dConfig, VarBuilder}; -use crate::Result; use crate::vit::HIDDEN; +use crate::{Result, cpu}; pub const FPN: usize = 256; @@ -64,8 +64,11 @@ impl Neck { pub fn forward(&self, x: &Tensor, n: usize) -> Result> { let mut out = Vec::with_capacity(n); for l in self.levels.iter().take(n) { + let cpu = x.device().is_cpu(); let y = match &l.scale { + Scale::Up4(a, b) if cpu => cpu::upsample2(&cpu::upsample2(x, a, true)?, b, false)?, Scale::Up4(a, b) => b.forward(&a.forward(x)?.gelu_erf()?)?, + Scale::Up2(a) if cpu => cpu::upsample2(x, a, false)?, Scale::Up2(a) => a.forward(x)?, Scale::Same => x.clone(), Scale::Down2 => x.max_pool2d(2)?, diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..0749d9c72a 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -25,8 +25,17 @@ pub fn linear(i: usize, o: usize, vb: VarBuilder) -> Result { const SCORE_BLOCK: usize = 64 << 20; /// Scaled dot-product attention on `[B, H, L, d]` tensors, with an optional additive bias -/// broadcastable to `[B, H, Lq, Lk]`. Heads are processed in groups to bound memory. +/// broadcastable to `[B, H, Lq, Lk]` (on the CPU: [`cpu::sdpa`]). pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + if q.device().is_cpu() && bias.is_none_or(|t| t.rank() == 4) { + return cpu::sdpa(q, k, v, bias, scale); + } + sdpa_tensors(q, k, v, bias, scale) +} + +/// [`sdpa`] with candle's tensor operations (any device). Heads are processed in groups to bound +/// memory. +pub fn sdpa_tensors(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { let (b, h, lq, _) = q.dims4()?; let lk = k.dim(2)?; let per_head = b.saturating_mul(lq).saturating_mul(lk).max(1); @@ -97,6 +106,11 @@ impl Attention { Ok(self.o.forward(x)?) } + /// The q, k, v and output projections. + pub fn projections(&self) -> [&Linear; 4] { + [&self.q, &self.k, &self.v, &self.o] + } + /// `q`, `k`, `v`: `[B, L, hidden]`; `bias` broadcastable to `[B, heads, Lq, Lk]`. pub fn forward(&self, q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>) -> Result { let (b, lq, _) = q.dims3()?; @@ -132,6 +146,14 @@ impl Mlp { let x = if self.gelu { x.gelu_erf()? } else { x.relu()? }; Ok(self.fc2.forward(&x)?) } + + /// `residual + forward(x)`; on the CPU with the bias adds, activation and residual add fused. + pub fn forward_add(&self, x: &Tensor, residual: &Tensor) -> Result { + if !x.device().is_cpu() { + return Ok((residual + self.forward(x)?)?); + } + cpu::linear_add(&cpu::linear_act(x, &self.fc1, self.gelu)?, &self.fc2, residual) + } } /// `Sam3DecoderMLP`: `layer1 … layerN` with ReLU between (2 or 3 layers). @@ -188,6 +210,30 @@ impl FeedForward { } } +/// `nn.GroupNorm` followed by ReLU (the pixel decoder's), fused on the CPU. +pub struct GroupNormRelu { + norm: candle_nn::GroupNorm, + weight: Tensor, + bias: Tensor, + groups: usize, + eps: f64, +} + +impl GroupNormRelu { + pub fn new(groups: usize, channels: usize, eps: f64, vb: VarBuilder) -> Result { + let (weight, bias) = (vb.get(channels, "weight")?, vb.get(channels, "bias")?); + let norm = candle_nn::GroupNorm::new(weight.clone(), bias.clone(), channels, groups, eps)?; + Ok(Self { norm, weight, bias, groups, eps }) + } + + pub fn forward(&self, x: &Tensor) -> Result { + if x.device().is_cpu() { + return cpu::group_norm_relu(x, &self.weight, &self.bias, self.groups, self.eps); + } + Ok(self.norm.forward(x)?.relu()?) + } +} + /// Layer norm over the channel axis of an NCHW tensor (`Sam3TrackerLayerNorm`, channels_first). pub fn ln_channels(x: &Tensor, norm: &LayerNorm) -> Result { let x = x.permute((0, 2, 3, 1))?; diff --git a/crates/segment/src/vit.rs b/crates/segment/src/vit.rs index 16b09a729b..1f356ad547 100644 --- a/crates/segment/src/vit.rs +++ b/crates/segment/src/vit.rs @@ -8,8 +8,8 @@ use candle_core::{D, Device, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, VarBuilder}; -use crate::nn::{Attention, Mlp, ln, sdpa}; -use crate::{Error, Result}; +use crate::nn::{Attention, Mlp, ln, sdpa_tensors}; +use crate::{Error, Result, cpu}; pub const IMAGE: usize = 1008; pub const PATCH: usize = 14; @@ -19,14 +19,26 @@ pub const HIDDEN: usize = 1024; const HEADS: usize = 16; const HEAD_DIM: usize = HIDDEN / HEADS; const LAYERS: usize = 32; +const INTERMEDIATE: usize = 4736; const WINDOW: usize = 24; const GLOBAL: [usize; 4] = [7, 15, 23, 31]; const PRETRAIN_GRID: usize = 336 / PATCH; const EPS: f64 = 1e-6; +/// The attention score scale, `HEAD_DIM^-0.5`. A power of two, so scaling the queries instead +/// of the scores (on the CPU) gives the same scores, bit for bit. +const SCALE: f32 = 0.125; +const _: () = assert!(HEAD_DIM == 64); + +/// Cosine and sine tables `[N, head_dim]`, also as plain values for the CPU kernels. +struct Rope { + cos: Tensor, + sin: Tensor, + values: (Vec, Vec), +} /// Cosine and sine tables `[N, head_dim]` for a `side × side` grid whose coordinates are scaled /// by `scale` (`Sam3ViTRotaryEmbedding`: x frequencies then y, each duplicated pairwise). -fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tensor)> { +fn rope_tables(side: usize, scale: f64, device: &Device) -> Result { let spatial = HEAD_DIM / 2; let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); let n = side * side; @@ -44,7 +56,7 @@ fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tens } } } - Ok((Tensor::from_vec(cos, (n, HEAD_DIM), device)?, Tensor::from_vec(sin, (n, HEAD_DIM), device)?)) + Ok(Rope { cos: Tensor::from_slice(&cos, (n, HEAD_DIM), device)?, sin: Tensor::from_slice(&sin, (n, HEAD_DIM), device)?, values: (cos, sin) }) } /// `x·cos + rotate_pairwise(x)·sin`, where rotate_pairwise maps (a, b) pairs to (−b, a). @@ -71,7 +83,12 @@ struct Layer { impl Layer { /// `x`: `[B, H, W, C]`. - fn forward(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn forward(&self, x: &Tensor, rope: &Rope) -> Result { + if x.device().is_cpu() { self.forward_cpu(x, rope) } else { self.forward_tensors(x, rope) } + } + + /// With candle's tensor operations (any device). + fn forward_tensors(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let y = self.ln1.forward(x)?; let y = match (h.checked_div(self.window), w.checked_div(self.window)) { @@ -90,21 +107,37 @@ impl Layer { Ok((x + y)?) } + /// [`Self::forward`] on the CPU: the same arithmetic, with the window partitioning, head + /// split, rotary encoding, bias adds, GELU and residual adds in fused parallel kernels. + fn forward_cpu(&self, x: &Tensor, rope: &Rope) -> Result { + let (b, h, w, _) = x.dims4()?; + let grid = cpu::Grid { b, h, w, win: self.window, heads: HEADS, head_dim: HEAD_DIM }; + let y = self.ln1.forward(x)?; + let [q, k, v, o] = self.attn.projections(); + let table = Some((rope.values.0.as_slice(), rope.values.1.as_slice())); + let q = cpu::heads(&y, q, grid, table, SCALE)?; + let k = cpu::heads(&y, k, grid, table, 1.0)?; + let v = cpu::heads(&y, v, grid, None, 1.0)?; + let att = cpu::attention(&q, &k, &v, grid)?; + let x = cpu::linear_add(&att, o, x)?; + self.mlp.forward_add(&self.ln2.forward(&x)?, &x) + } + /// RoPE self-attention over `[B, H, W, C]`. - fn attend(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attend(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let seq = x.reshape((b, h * w, c))?; Ok(self.attn_rope(&seq, rope)?.reshape((b, h, w, c))?) } - fn attn_rope(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attn_rope(&self, x: &Tensor, rope: &Rope) -> Result { let (b, n, _) = x.dims3()?; let split = |t: Tensor| -> Result { Ok(t.reshape((b, n, HEADS, HEAD_DIM))?.transpose(1, 2)?.contiguous()?) }; let (q, k, v) = self.attn.qkv(x)?; - let q = apply_rope(&split(q)?, &rope.0, &rope.1)?; - let k = apply_rope(&split(k)?, &rope.0, &rope.1)?; + let q = apply_rope(&split(q)?, &rope.cos, &rope.sin)?; + let k = apply_rope(&split(k)?, &rope.cos, &rope.sin)?; let v = split(v)?; - let o = sdpa(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; + let o = sdpa_tensors(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; let o = o.transpose(1, 2)?.reshape((b, n, HIDDEN))?; self.attn.out(&o) } @@ -115,8 +148,8 @@ pub struct Vit { pos: Tensor, ln_pre: LayerNorm, layers: Vec, - rope_window: (Tensor, Tensor), - rope_global: (Tensor, Tensor), + rope_window: Rope, + rope_global: Rope, } impl Vit { @@ -141,7 +174,7 @@ impl Vit { ln1: ln(HIDDEN, EPS, l.pp("layer_norm1"))?, attn: Attention::new(HIDDEN, HIDDEN, HEADS, l.pp("attention"))?, ln2: ln(HIDDEN, EPS, l.pp("layer_norm2"))?, - mlp: Mlp::new(HIDDEN, 4736, true, l.pp("mlp"))?, + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, l.pp("mlp"))?, window: if GLOBAL.contains(&i) { 0 } else { WINDOW }, }); } @@ -168,3 +201,57 @@ impl Vit { Ok(x.permute((0, 3, 1, 2))?.contiguous()?) } } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use candle_core::DType; + + use super::*; + + /// A layer with random weights. + fn layer(window: usize) -> Layer { + let d = Device::Cpu; + let mut t = HashMap::new(); + let mut add = |name: String, shape: &[usize], mean: f32| { + t.insert(name, Tensor::randn(mean, 0.05f32, shape, &d).unwrap()); + }; + for n in ["layer_norm1", "layer_norm2"] { + add(format!("{n}.weight"), &[HIDDEN], 1.0); + add(format!("{n}.bias"), &[HIDDEN], 0.0); + } + for n in ["q_proj", "k_proj", "v_proj", "o_proj"] { + add(format!("attention.{n}.weight"), &[HIDDEN, HIDDEN], 0.0); + add(format!("attention.{n}.bias"), &[HIDDEN], 0.0); + } + add("mlp.fc1.weight".into(), &[INTERMEDIATE, HIDDEN], 0.0); + add("mlp.fc1.bias".into(), &[INTERMEDIATE], 0.0); + add("mlp.fc2.weight".into(), &[HIDDEN, INTERMEDIATE], 0.0); + add("mlp.fc2.bias".into(), &[HIDDEN], 0.0); + let vb = VarBuilder::from_tensors(t, DType::F32, &d); + Layer { + ln1: ln(HIDDEN, EPS, vb.pp("layer_norm1")).unwrap(), + attn: Attention::new(HIDDEN, HIDDEN, HEADS, vb.pp("attention")).unwrap(), + ln2: ln(HIDDEN, EPS, vb.pp("layer_norm2")).unwrap(), + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, vb.pp("mlp")).unwrap(), + window, + } + } + + #[test] + fn cpu_kernels_match_the_tensor_ops() { + // two images each: 12 × 24 tokens in 6 × 6 windows, and 12 × 12 with global attention + for (window, (h, w), side, scale) in [(6, (12, 24), 6, 1.0), (0, (12, 12), 12, 0.5)] { + let x = Tensor::randn(0f32, 1.0, (2, h, w, HIDDEN), &Device::Cpu).unwrap(); + let (l, rope) = (layer(window), rope_tables(side, scale, &Device::Cpu).unwrap()); + let want = l.forward_tensors(&x, &rope).unwrap().flatten_all().unwrap().to_vec1::().unwrap(); + let got = l.forward_cpu(&x, &rope).unwrap(); + assert_eq!(got.dims(), x.dims()); + let got = got.flatten_all().unwrap().to_vec1::().unwrap(); + let err = want.iter().zip(&got).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + // the same arithmetic (one attention block per window here): equal on x86-64 + assert!(err <= 1e-5, "window {window}: max error {err}"); + } + } +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index b02912abc1..37cd9c1639 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -29,13 +29,13 @@ In the Masking panel (M): so small objects get 5–10× finer edges than one pass over the whole photo gives. The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and -look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the -model after launch). That starts in the background as soon as you pick Object; after it, each -click takes ~35 ms and each description ~0.6 s. Everything the model does runs on its own worker -thread: the window stays responsive, a click shows its dot at once and the selection follows -when it's computed ("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is -unloaded after 10 minutes without use (it takes several GB of memory) and loaded again when -needed. +look: ~3 s on an Apple M4 Pro, ~11 s on the CPU of a 12-core Ryzen 9 3900X, plus a one-time ~6 s +for compiling GPU kernels and loading the model after launch). That starts in the background as +soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s +and ~2 s on that CPU). Everything the model does runs on its own worker thread: the window stays +responsive, a click shows its dot at once and the selection follows when it's computed +("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is unloaded after 10 +minutes without use (it takes several GB of memory) and loaded again when needed. The result is stored with the mask: the model's 288 × 288 mask logits over the uncropped photo (quantized, compressed, ~10–30 KB). Renders and exports sample them at any resolution and never @@ -230,6 +230,18 @@ wait and return the result (when built with the `sam` feature; the default CLI h - Accuracy: `crates/segment/tests/reference.rs` compares every stage against the Python reference (`tools/sam3_reference.py`); on Metal the backbone matches to 7e-5 relative error and masks to ~5e-5. f16 was tried and rejected (overflow, ~7 % faster). +- Speed on the CPU: candle runs elementwise operations and layout copies on one thread, batched + matrix products one pair after another and transposed convolutions one output channel at a + time. `cpu.rs` fuses the bias adds, activations, rotary encoding, window partitioning, head + split/merge, the detector's box bias and the pixel decoder's GroupNorm into parallel kernels + (the same operations in the same order: bit-identical), runs attention as one task per batch, + head and block of query rows (256 KB of scores, so they stay in the core's cache), and the + necks' 2 × 2 transposed convolutions as one matrix product each. Those two change how gemm + blocks its sums, so results move by float rounding only, as they do between two CPUs (gemm + picks its blocking from the cache sizes): against the tensor operations the backbone differs + by 1e-5 relative and the masks by at most 7e-4, and fewer than 4e-7 of the mask pixels change + side. On a 12-core Ryzen 9 3900X: encode ~37 → ~11 s, a description ~6 → ~2 s, getting ready + for clicks ~2.3 → ~0.8 s. - The engine feature `sam` (on in the desktop app, off for web and CLI) gates the model; without it the commands report that the build has no AI masks. From edfcc2f1653b28dc4269c63d9a380674125e7229 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:10:53 +0300 Subject: [PATCH 002/247] Workspace: bump rust-version to 1.95 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index ac8cbeca13..cf83258614 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ members = ["crates/*", "apps/*", "xtask"] version = "0.8.0" edition = "2024" license = "MIT OR Apache-2.0" -rust-version = "1.90" +rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] From 0ef612f518c91add53e32316c7cc83b637268c9f Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:24:45 -0400 Subject: [PATCH 003/247] LR-PROF-CAMERACOLOR: raw decoding keeps negative channels Decoding clamped each linear Rec.2020 channel at zero after the colour matrix. Near black those values are sensor noise, and the clamp kept only the positive half of each channel's noise: through a saturating camera matrix red and blue have the widest noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV: sRGB (64, 28, 65) in its darkest 40%, (2, 4, 4) now). Negative channels now pass through to noise reduction and the output gamut mapping, which already moves colours toward their luminance until in range; only non-finite values are zeroed. Moving each negative colour toward its luminance at decode instead still left it pink ((34, 14, 22)). RENDER_CACHE_VERSION 66. --- crates/engine/src/files.rs | 49 ++++++++++++++++++++++++++++++++++++-- crates/engine/src/media.rs | 2 +- docs/parity-checklist.md | 3 ++- docs/whats-new.md | 8 +++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 31bb930fbf..9c6f02852b 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -280,7 +280,7 @@ impl CameraColourModel<'_> { } let out = hue_sat.apply_lanes(rgb); for (l, p) in chunk.iter_mut().enumerate() { - *p = [out[0][l], out[1][l], out[2][l]].map(|v| v.max(0.0)); + *p = finite([out[0][l], out[1][l], out[2][l]]); } } }); @@ -302,10 +302,22 @@ impl CameraColourModel<'_> { Some(tables) => tables.apply(rgb, gain), None => rgb.map(|v| v * gain), }; - self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0)) + finite(self.hue_sat.map_or(rgb, |h| h.apply(rgb))) } } +/// `rgb` (linear Rec.2020) as decoding leaves it for the stages after: negative channels kept, non-finite ones zero. +/// Near black, negative channels are sensor noise through the colour matrix, and keeping them keeps the noise zero-mean +/// until noise reduction and the output's gamut mapping (which moves a colour toward its luminance until it is in +/// range) deal with it. Clamping each channel at zero here kept only the positive half of every channel's noise: +/// through a saturating camera matrix (red row 3.5, −2.4, −0.1 on a NIKON D780 profile) red and blue have the widest +/// noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV rendered at sRGB (64, 28, 65) +/// in its darkest 40%, (2, 4, 4) without the clamp). Moving each such colour toward its luminance instead still left +/// it pink, at (34, 14, 22): any per-pixel rule that treats pixels by the sign of their noise biases the mean. +fn finite(rgb: [f32; 3]) -> [f32; 3] { + rgb.map(|v| if v.is_finite() { v } else { 0.0 }) +} + /// The white-balanced camera RGB that `model` (white-balanced camera RGB → linear Rec.2020) renders /// neutral, as bright as it renders `[1, 1, 1]`: what fully clipped highlights are rebuilt to, so they come out /// neutral whatever the colour model does to the camera's own neutral (a look fitted to the camera's JPEG or a @@ -1839,6 +1851,39 @@ pub(crate) mod tests { /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. + #[test] + fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { + assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); + assert_eq!(finite([f32::NAN, -0.1, f32::INFINITY]), [0.0, -0.1, 0.0]); + } + + /// Dark sensor noise through a saturating camera matrix (a NIKON D780 profile's) averages to a neutral colour: the + /// per-channel clamp at zero decoding had kept red's and blue's wider positive halves and turned it magenta. + #[test] + fn dark_noise_through_a_saturating_matrix_stays_neutral() { + let matrix = lightcraft_color::Mat3([[3.48, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]); + let colour = CameraColourModel { wb: [1.0; 3], matrix, gain: 1.0, tables: None, hue_sat: None }; + // a grey 0.002 above black with ±0.004 of noise per channel (a deterministic sequence) + let mut state = 12345u32; + let mut noise = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let mut img = Rgb32f::new(200, 200); + for p in img.data.iter_mut() { + *p = [0.002 + noise(), 0.002 + noise(), 0.002 + noise()]; + } + colour.apply(&mut img); + let mut mean = [0.0f64; 3]; + for p in &img.data { + for (m, v) in mean.iter_mut().zip(p) { + *m += f64::from(*v); + } + } + let (hi, lo) = (mean[0].max(mean[1]).max(mean[2]), mean[0].min(mean[1]).min(mean[2])); + assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); + } + #[test] fn camera_look_in_lanes_matches_pixel_by_pixel() { let data = (0..72 * 5 * 5).map(|i| [((i * 37) % 61) as f32 - 30.0, 0.6 + ((i * 11) % 13) as f32 / 13.0, 1.0]).collect(); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 22d76528d6..e6c438ad72 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 64; +pub const RENDER_CACHE_VERSION: u64 = 65; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4e05317933..18863969ad 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (LRC-PRINT-PAGE: Print Page Options) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** patch (LR-PROF-CAMERACOLOR: raw decoding keeps negative channels) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -801,6 +801,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-16 | patch | LR-PROF-CAMERACOLOR: raw decoding keeps negative channels (noise near black) instead of clipping each at zero, which turned pushed shadows magenta; status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); status unchanged (🟡) | | 2026-10-13 | minor | LR-MERGE-PANO: a panorama's DNG takes its `AsShotNeutral` from the median of its frames' vendor white-balance multipliers (CR2, NEF, ARW…) instead of the first frame's tags, and frames now carry the multipliers (issue #1144); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 2f02ffb91b..441b4889bc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,13 @@ # What's new in LightCraft +## 2026-10-16 + +### Pushed shadows of raws no longer turn magenta +- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour + matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas + pushed up came out purple or magenta (a lens-cap frame pushed 4 EV rendered magenta; it is now black). Shadows + pushed with Exposure or Shadows keep their real colour, most visibly with saturating camera profiles. + ## 2026-10-14 ### Model downloads time out on a name that doesn't resolve From 3886c765827587f4d76f8fde870cbf443e9dd9f2 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:31:39 +0200 Subject: [PATCH 004/247] LR-LIB-CULL: Assisted Culling can stack each burst, best photo on top (#2277) photo.analyze takes stackGroups (default false): every burst becomes one collapsed stack topped by its sharpest photo, in the same undo step as the analysis and flags. Photos already in a stack are left alone (like stack.auto); the rest of the burst is stacked when two or more remain. Duplicate ids are measured once. The dialog gets a "Stack each burst, best photo on top" checkbox, remembered for the session; German translation, parity row and revision history updated. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 55 ++++++++++++-- crates/engine/src/tests_import.rs | 110 +++++++++++++++++++++++++++ crates/ui-egui/locales/de.json | 1 + crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/panels/dialogs.rs | 9 ++- crates/ui-egui/src/state.rs | 9 ++- docs/parity-checklist.md | 5 +- 7 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 92a9c3b7cb..71db71c990 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -1,7 +1,7 @@ //! Assisted culling: score photos for focus and clipping, group similar shots taken close //! together (bursts) and mark the sharpest of each group; optionally reject blurry ones and pick -//! each group's best. Scores are kept on the photos (rules / smart albums: `sharpness`, -//! `bestOfGroup`). +//! each group's best, and stack each burst with its best photo on top. Scores are kept on the +//! photos (rules / smart albums: `sharpness`, `bestOfGroup`). use lightcraft_catalog::{Analysis, Flag, Op, PhotoId}; use serde_json::{Value, json}; @@ -22,10 +22,17 @@ fn secs(iso: &str) -> Option { } fn analyze(s: &mut Session, p: &Value) -> Result { - let ids: Vec = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + let mut ids: Vec = if p.get("ids").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + // a photo named twice is measured (and stacked) once + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); let (gap, same) = burst_params(p)?; + let stack_groups = match p.get("stackGroups") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + }; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -80,10 +87,48 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); } + let mut stacks = 0; + if stack_groups { + // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked + // from its other photos when two or more remain, with the sharpest of those on top. + let index = s.catalog.stack_index(); + let mut members: std::collections::BTreeMap> = Default::default(); + for (i, g) in group_of.iter().enumerate() { + if let (Some(g), Some(r)) = (g, rows.get(i)) + && !index.contains_key(&r.0) + && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) + { + members.entry(*g).or_default().push((r.0, r.2)); + } + } + for group in members.values() { + let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { + continue; + }; + let photos: Vec = group.iter().map(|m| m.0).collect(); + if photos.len() >= 2 + && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + { + ops.push(op); + stacks += 1; + } + } + } if !ops.is_empty() { s.commit("Assisted Culling", Op::Batch { ops })?; } - Ok(json!({"photos": out, "groups": best.len(), "rejected": rejected, "picked": picked, "failed": failed})) + if stacks > 0 { + // a photo now hidden inside a collapsed stack must not stay the active one + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection = crate::Selection::single(top); + } + } + Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -152,7 +197,7 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", always, analyze ), diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index f581f11dda..101fe43431 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -870,6 +870,116 @@ fn assisted_culling_burst_limits_are_adjustable() { let _ = std::fs::remove_dir_all(&dir); } +/// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its +/// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step, +/// and a second run neither makes another stack nor splits the existing one. +#[test] +fn assisted_culling_stacks_each_burst_best_on_top() { + let dir = temp_dir("cull-stack"); + let scene = lightcraft_scenes::demo_library()[0].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + let save = |img: &lightcraft_raster::Rgb32f, name: &str| { + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(name), png).unwrap(); + }; + save(&soften(&scene, 3), "a_soft.png"); + save(&scene, "b_sharp.png"); + save(&soften(&scene, 6), "c_softer.png"); + save(&lightcraft_scenes::demo_library()[7].render(480, 320), "d_other.png"); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).collect(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s, n); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s, "a_soft.png"), by_name(&s, "b_sharp.png"), by_name(&s, "c_softer.png"), by_name(&s, "d_other.png")); + // a photo named twice is measured and stacked once + let mut twice = ids.clone(); + twice.push(sharp.0); + let r = s.execute("photo.analyze", &json!({"ids": twice, "stackGroups": true})).unwrap(); + assert_eq!((r["stacks"].clone(), r["groups"].clone()), (json!(1), json!(1)), "{r}"); + let st = s.catalog.stack_of(sharp).unwrap().clone(); + assert!(st.collapsed && st.top() == sharp, "the sharpest photo tops the stack"); + let mut members = st.photos.clone(); + members.sort(); + let mut want = vec![soft, sharp, softer]; + want.sort(); + assert_eq!(members, want); + assert!(s.catalog.stack_of(other).is_none(), "the unrelated photo stays loose"); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some_and(|a| a.best)); + // one undo step removes the stack and the analysis together + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_none()); + // without `stackGroups` nothing is stacked + let r = s.execute("photo.analyze", &json!({"ids": ids})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert!(s.catalog.stacks().next().is_none()); + s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(s.catalog.stacks().count(), 1); + // a second run leaves the stack as it is + let before = s.catalog.stack_of(sharp).unwrap().clone(); + let commits = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert_eq!(s.catalog.stacks().count(), 1); + assert_eq!(s.catalog.stack_of(sharp).unwrap(), &before); + assert!(s.commits() > commits); + // a burst partly stacked already: the loose photos are stacked among themselves when two remain + let mut s2 = Session::new().with_fs(); + s2.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s2, n); + s2.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s2, "a_soft.png"), by_name(&s2, "b_sharp.png"), by_name(&s2, "c_softer.png"), by_name(&s2, "d_other.png")); + let ids: Vec = [soft, sharp, softer, other].iter().map(|p| p.0).collect(); + s2.execute("stack.group", &json!({"ids": [soft.0, other.0]})).unwrap(); + let r = s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 1, "{r}"); + assert!(s2.catalog.stack_of(soft).unwrap().photos.contains(&other), "the existing stack is untouched"); + let st = s2.catalog.stack_of(sharp).unwrap(); + assert!(st.top() == sharp && st.photos.len() == 2 && st.photos.contains(&softer)); + // a non-boolean value is refused before anything changes + let n = s2.commits(); + assert!(s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": "yes"})).is_err()); + assert_eq!(s2.commits(), n); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 9d2d756800..4d08cbd4a4 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1205,6 +1205,7 @@ "Refresh View": "Ansicht aktualisieren", "Reject": "Ablehnen", "Reject below focus": "Unter Schärfegrenzwert ablehnen", + "Stack each burst, best photo on top": "Jede Serie stapeln, bestes Foto oben", "Burst: shots at most this far apart": "Serie: Aufnahmen höchstens so weit auseinander", "Burst: how alike (loose … strict)": "Serie: wie ähnlich (locker … streng)", "Lower it when a panning or moving burst splits into several groups.": "Senken, wenn eine Mitzieher- oder Bewegungsserie in mehrere Gruppen zerfällt.", diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 229b34dc6a..41df245a78 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1444,7 +1444,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option open_original_in(app, &ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 26e198133a..575ba09cd3 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -336,7 +336,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); @@ -346,6 +346,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { ui.label(egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 { "Blurry photos below the score are flagged as rejects." } else { "0: nothing is rejected." })).color(t.text_dim)); let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); crate::widgets::register(ui.ctx(), "check:cullPick", r.rect); + let r = ui.checkbox(stack_groups, crate::i18n::tr("Stack each burst, best photo on top")); + crate::widgets::register(ui.ctx(), "check:cullStack", r.rect); ui.add_space(6.0); let r = ui.add( egui::Slider::new(burst_gap, 1.0..=600.0) @@ -1918,9 +1920,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); - let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity}); + app.ui.cull_stack = *stack_groups; + let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity}); if *reject_below > 0.0 { p["rejectBelow"] = json!(reject_below); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3388bad3b1..f97a4b44dd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -732,6 +732,9 @@ pub struct UiState { /// session; `None` until the dialog is first confirmed (then 10 s, 0.93). #[serde(skip)] pub cull_burst: Option<(f32, f32)>, + /// Whether Assisted Culling stacked its bursts the last time it was confirmed (this session). + #[serde(skip)] + pub cull_stack: bool, /// "More" faces the user hid with ×, for this session: (photo, region index). #[serde(skip)] pub dismissed_faces: std::collections::HashSet<(u64, usize)>, @@ -1093,11 +1096,12 @@ pub enum Dialog { /// Help ▸ What's New. WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best - /// of each burst; shots at most `burst_gap` seconds apart and at least `similarity` alike are - /// a burst. + /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Cull { reject_below: f32, pick_best: bool, + stack_groups: bool, burst_gap: f32, similarity: f32, }, @@ -1321,6 +1325,7 @@ impl Default for UiState { person_from: None, last_person: None, cull_burst: None, + cull_stack: false, dismissed_faces: Default::default(), unnamed_selected: Default::default(), unnamed_name: String::new(), diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9cce61b9a6..32488a4dda 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: adjustable burst limits) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts can be stacked, best on top) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -116,7 +116,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | From 76dfb0df11079a9b38e61f879bd38d8657cf3ea6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:47:17 +0200 Subject: [PATCH 005/247] LR-LIB-CULL: stacking bursts keeps the rest of the selection (#2277) When the active photo goes into a collapsed burst stack, the stack's top becomes active and the other selected photos stay selected, instead of the selection collapsing to one photo. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 9 +++++++-- crates/engine/src/tests_import.rs | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 71db71c990..4266790edd 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -118,14 +118,19 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one + // a photo now hidden inside a collapsed stack must not stay the active one: its stack's + // top takes over, and the rest of the selection (what was culled) stays selected let vis = s.visible_cloned(); if let Some(a) = s.selection.active && !vis.contains(&a) && let Some(st) = s.catalog.stack_of(a) { let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection = crate::Selection::single(top); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); } } Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 101fe43431..170a9d245d 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -928,8 +928,12 @@ fn assisted_culling_stacks_each_burst_best_on_top() { // a photo named twice is measured and stacked once let mut twice = ids.clone(); twice.push(sharp.0); + s.selection = crate::Selection { ids: vec![soft, sharp, softer, other], active: Some(soft) }; let r = s.execute("photo.analyze", &json!({"ids": twice, "stackGroups": true})).unwrap(); assert_eq!((r["stacks"].clone(), r["groups"].clone()), (json!(1), json!(1)), "{r}"); + // the active photo went into the collapsed stack: its top takes over, the loose photo stays selected + assert_eq!(s.selection.active, Some(sharp)); + assert!(s.selection.ids.contains(&other) && s.selection.ids.contains(&sharp) && !s.selection.ids.contains(&soft), "{:?}", s.selection.ids); let st = s.catalog.stack_of(sharp).unwrap().clone(); assert!(st.collapsed && st.top() == sharp, "the sharpest photo tops the stack"); let mut members = st.photos.clone(); From c61d946ef32e5227ec48d061fa723038b84b5261 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:38:22 +0200 Subject: [PATCH 006/247] LR-LIB-CULL: bursts keep an order set by hand (catalog format 10) `Analysis.rank` is a photo's place in its burst once the person arranged the burst by hand (0 = the pick). `Catalog::burst_index` / `burst` / `bursts_among` give each burst pick first, and `next_burst_id` a number no photo uses. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/bursts.rs | 118 +++++++++++++++++++++ crates/catalog/src/journal.rs | 3 +- crates/catalog/src/lib.rs | 1 + crates/catalog/src/model.rs | 14 +++ crates/catalog/src/tests_format_version.rs | 31 +++++- 5 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 crates/catalog/src/bursts.rs diff --git a/crates/catalog/src/bursts.rs b/crates/catalog/src/bursts.rs new file mode 100644 index 0000000000..a5b393780b --- /dev/null +++ b/crates/catalog/src/bursts.rs @@ -0,0 +1,118 @@ +//! Bursts: the look-alike shots Assisted Culling groups ([`crate::Analysis::group`]), in the +//! order they are shown and arranged — the pick first. +//! +//! A burst culling made is ordered by what culling found: its best photo, then the sharper +//! shots, then capture time. Once the person arranges a burst by hand every member carries its +//! place ([`crate::Analysis::rank`]), and that order is kept. + +use std::collections::{HashMap, HashSet}; + +use crate::{Catalog, Photo, PhotoId}; + +/// A photo's place in its burst: hand-placed ones by their place, then the best, the sharper, +/// the earlier, the lower id. +fn order_key(p: &Photo) -> (u32, bool, i64, &str, PhotoId) { + let a = p.analysis.unwrap_or_default(); + // sharpness is 0..100: a fixed-point key keeps the sort total + (a.rank.unwrap_or(u32::MAX), !a.best, -((a.sharpness * 1000.0) as i64), p.captured.as_deref().unwrap_or("~"), p.id) +} + +impl Catalog { + /// Every burst: its number → its photos (deleted ones left out), pick first. + pub fn burst_index(&self) -> HashMap> { + let mut by: HashMap> = HashMap::new(); + for p in self.photos.values().filter(|p| !p.deleted) { + if let Some(g) = p.analysis.and_then(|a| a.group) { + by.entry(g).or_default().push(&**p); + } + } + by.into_iter() + .map(|(g, mut photos)| { + photos.sort_by(|a, b| order_key(a).cmp(&order_key(b))); + (g, photos.into_iter().map(|p| p.id).collect()) + }) + .collect() + } + + /// The photos of burst `group`, pick first (empty when there is no such burst). + pub fn burst(&self, group: u32) -> Vec { + self.burst_index().remove(&group).unwrap_or_default() + } + + /// The bursts `ids` meet, in the order their first photo appears in `ids`, each pick first. + /// Only photos in `scope` count as members (the photos of a view and the hidden members of + /// its collapsed stacks, say); `None` takes every photo of the burst. + pub fn bursts_among(&self, ids: &[PhotoId], scope: Option<&HashSet>) -> Vec<(u32, Vec)> { + let mut index = self.burst_index(); + let mut out = Vec::new(); + for id in ids { + let Some(g) = self.photo(*id).and_then(|p| p.analysis).and_then(|a| a.group) else { continue }; + if let Some(mut photos) = index.remove(&g) { + if let Some(scope) = scope { + photos.retain(|p| scope.contains(p)); + } + if !photos.is_empty() { + out.push((g, photos)); + } + } + } + out + } + + /// A burst number no photo uses (deleted ones included, so Undo never brings back a clash). + pub fn next_burst_id(&self) -> u32 { + self.photos.values().filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1 + } +} + +#[cfg(test)] +mod tests { + use crate::{Analysis, Catalog, Op, Photo, PhotoId, Source}; + + fn add(c: &mut Catalog, when: &str, a: Option) -> PhotoId { + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/p/{}.jpg", id.0) }, "p.jpg", "JPEG", 4, 3, "2026-01-01"); + p.captured = Some(when.into()); + p.analysis = a; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + } + + fn shot(group: u32, sharpness: f32, best: bool, rank: Option) -> Option { + Some(Analysis { sharpness, group: Some(group), best, rank, ..Default::default() }) + } + + #[test] + fn a_culled_burst_shows_its_best_then_the_sharper_shots() { + let mut c = Catalog::new(); + let a = add(&mut c, "2026-05-01T10:00:00", shot(1, 20.0, false, None)); + let b = add(&mut c, "2026-05-01T10:00:01", shot(1, 80.0, true, None)); + let d = add(&mut c, "2026-05-01T10:00:02", shot(1, 50.0, false, None)); + let loose = add(&mut c, "2026-05-01T10:00:03", Some(Analysis::default())); + assert_eq!(c.burst(1), vec![b, d, a]); + assert!(c.burst(2).is_empty()); + assert_eq!(c.bursts_among(&[a, loose, d], None), vec![(1, vec![b, d, a])]); + assert_eq!(c.next_burst_id(), 2); + } + + #[test] + fn a_burst_arranged_by_hand_keeps_its_order() { + let mut c = Catalog::new(); + // the pick by hand is the softest shot + let a = add(&mut c, "2026-05-01T10:00:00", shot(3, 20.0, true, Some(0))); + let b = add(&mut c, "2026-05-01T10:00:01", shot(3, 80.0, false, Some(2))); + let d = add(&mut c, "2026-05-01T10:00:02", shot(3, 50.0, false, Some(1))); + let other = add(&mut c, "2026-05-01T11:00:00", shot(7, 50.0, true, None)); + let other2 = add(&mut c, "2026-05-01T11:00:01", shot(7, 40.0, false, None)); + assert_eq!(c.burst(3), vec![a, d, b]); + // in the order the view meets them; a scope keeps a burst's members within it + assert_eq!(c.bursts_among(&[other, b], None), vec![(7, vec![other, other2]), (3, vec![a, d, b])]); + let scope = [b, d, other].into_iter().collect(); + assert_eq!(c.bursts_among(&[b, other], Some(&scope)), vec![(3, vec![d, b]), (7, vec![other])]); + assert_eq!(c.next_burst_id(), 8); + // deleted photos are no member + c.apply(Op::SetDeleted { id: d, deleted: true }).unwrap(); + assert_eq!(c.burst(3), vec![a, b]); + assert_eq!(c.next_burst_id(), 8); + } +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index edcfae22ae..a3421661d4 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -52,6 +52,7 @@ //! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | //! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! | 10 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 9; +pub const VERSION: u32 = 10; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1..b3791a6d95 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -13,6 +13,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bursts; pub mod dates; pub mod folders; mod index; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ac3544ee7..1a3e03ea82 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -321,6 +321,20 @@ pub struct Analysis { pub group: Option, /// The best photo of its group. pub best: bool, + /// Set when the person arranged this photo's burst by hand (Window ▸ Bursts, or + /// `photo.moveToBurst`): its place in [`Analysis::group`], 0 being the pick, or `Some(0)` for + /// a photo taken out of every burst. Culling run again keeps such a photo's burst, place and + /// pick (unless asked to regroup). `None` while the burst is as culling made it; left out of the + /// catalog JSON then, so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rank: Option, +} + +impl Analysis { + /// Whether the person placed this photo by hand (see [`Analysis::rank`]). + pub fn by_hand(&self) -> bool { + self.rank.is_some() + } } /// Raw formats whose files carry vendor white-balance multipliers but no colour matrices: their starting diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c4..56ffc6e58d 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -192,6 +192,33 @@ fn bad_crc_is_still_a_torn_tail() { assert!(r.torn_bytes > 0 && r.damaged.is_none(), "{r:?}"); } +/// A v9 library (bursts as culling made them) reads every analysis as not arranged by hand and +/// is rewritten in the current format; a place set by hand survives the round trip, and none is +/// written for a photo left as culling placed it. +#[test] +fn v9_analysis_loads_unarranged_and_is_upgraded() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 160, 120, "2026-01-01"); + p.analysis = Some(Analysis { sharpness: 61.0, clipped: 0.01, group: Some(2), best: true, ..Default::default() }); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let snap = c.to_snapshot(); + assert!(!snap.contains("rank"), "nothing new is written for a burst culling made: {snap}"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":1,\"catalog\":{snap}}}\n").into_bytes()); + let (_, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + let a = loaded.photo(id).unwrap().analysis.unwrap(); + assert_eq!((a.group, a.best, a.rank, a.by_hand()), (Some(2), true, None, false)); + assert_eq!(r.upgraded_from, Some(9)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // a place set by hand round-trips + let mut c = loaded; + let b = Analysis { rank: Some(1), best: false, ..a }; + c.apply(Op::SetAnalysis { id, analysis: Some(b) }).unwrap(); + let again: Catalog = serde_json::from_str(&c.to_snapshot()).unwrap(); + assert_eq!(again.photo(id).unwrap().analysis, Some(b)); +} + /// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks /// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the /// variant here under the new version. A version that only adds serialized fields raises @@ -238,8 +265,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + /// v10: `Analysis.rank`. + const NEWEST_FIELDS: u32 = 10; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } From 96a18539b9637289bfe52f37b94cfa16a33063f9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:58:03 +0200 Subject: [PATCH 007/247] LR-LIB-CULL: photo.moveToBurst arranges bursts by hand; culling again keeps them `photo.moveToBurst {ids, burst?: n | "new" | null, index?}` moves photos within their burst, into another, into a new one or out of every burst. The first place is the pick: `best` (Best of Similar Shots), the Pick flag culling gave the old pick and the top of a stacked burst follow it. A burst a move leaves with one photo is no burst. One undo step. `photo.analyze` keeps the burst, place and pick of photos arranged by hand and only scores them again (`resetBursts` regroups them), and numbers new bursts after every burst that stays, so two runs on different photos no longer share burst numbers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 247 +++++++++++++++++++++++++---- crates/engine/src/lib.rs | 2 + crates/engine/src/tests_bursts.rs | 250 ++++++++++++++++++++++++++++++ 3 files changed, 473 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/tests_bursts.rs diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 4266790edd..76725a968c 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -29,10 +29,14 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); let (gap, same) = burst_params(p)?; - let stack_groups = match p.get("stackGroups") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + let flag_param = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", format!("`{key}` must be true or false"))), + } }; + let stack_groups = flag_param("stackGroups")?; + let reset = flag_param("resetBursts")?; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -48,17 +52,25 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } // bursts: consecutive (by capture time) look-alike shots rows.sort_by_key(|r| (r.1.unwrap_or(i64::MAX), r.0)); + // A photo whose burst was arranged by hand keeps it (burst, place, pick): only its scores + // are measured again. The others are grouped among themselves, in bursts numbered after + // every burst that stays (earlier runs on other photos, the ones arranged by hand). + let by_hand = |id: PhotoId| -> Option { s.catalog.photo(id).and_then(|p| p.analysis).filter(|a| !reset && a.by_hand()) }; + let kept: Vec> = rows.iter().map(|r| by_hand(r.0)).collect(); + let auto: Vec = (0..rows.len()).filter(|i| kept[*i].is_none()).collect(); + let regrouped: std::collections::HashSet = auto.iter().map(|i| rows[*i].0).collect(); + let mut next = s.catalog.photos().filter(|p| !regrouped.contains(&p.id)).filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1; let mut group_of: Vec> = vec![None; rows.len()]; - let mut next = 1u32; - for i in 1..rows.len() { - let (a, b) = (&rows[i - 1], &rows[i]); + for w in auto.windows(2) { + let (i, j) = (w[0], w[1]); + let (a, b) = (&rows[i], &rows[j]); let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap); if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same { - let g = *group_of[i - 1].get_or_insert_with(|| { + let g = *group_of[i].get_or_insert_with(|| { next += 1; next - 1 }); - group_of[i] = Some(g); + group_of[j] = Some(g); } } let mut best: std::collections::HashMap = Default::default(); @@ -74,9 +86,16 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let (mut rejected, mut picked) = (0, 0); let mut out = Vec::new(); for (i, (id, _, sharp, clip, _)) in rows.iter().enumerate() { - let g = group_of[i]; - let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); - ops.push(Op::SetAnalysis { id: *id, analysis: Some(Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best }) }); + let analysis = match kept[i] { + Some(k) => Analysis { sharpness: *sharp, clipped: *clip, ..k }, + None => { + let g = group_of[i]; + let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); + Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best, rank: None } + } + }; + let (g, is_best) = (analysis.group, analysis.best); + ops.push(Op::SetAnalysis { id: *id, analysis: Some(analysis) }); let flag = s.catalog.photo(*id).map(|p| p.flag).unwrap_or_default(); if reject_below.is_some_and(|t| *sharp < t) && flag != Flag::Reject { ops.push(Op::SetFlag { id: *id, flag: Flag::Reject }); @@ -85,7 +104,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result { ops.push(Op::SetFlag { id: *id, flag: Flag::Pick }); picked += 1; } - out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); + out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best, "byHand": kept[i].is_some()})); } let mut stacks = 0; if stack_groups { @@ -118,22 +137,189 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one: its stack's - // top takes over, and the rest of the selection (what was culled) stays selected - let vis = s.visible_cloned(); - if let Some(a) = s.selection.active - && !vis.contains(&a) - && let Some(st) = s.catalog.stack_of(a) - { - let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection.ids.retain(|id| vis.contains(id)); - if !s.selection.ids.contains(&top) { - s.selection.ids.push(top); + keep_active_shown(s); + } + let kept = kept.iter().filter(|k| k.is_some()).count(); + Ok(json!({"photos": out, "groups": best.len(), "kept": kept, "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) +} + +/// A photo now hidden inside a collapsed stack must not stay the active one: its stack's top +/// takes over, and the rest of the selection stays selected. +fn keep_active_shown(s: &mut Session) { + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); + } +} + +/// Where `photo.moveToBurst` puts the photos. +#[derive(Clone, Copy, PartialEq)] +enum Dest { + Burst(u32), + New, + Nowhere, +} + +/// Arrange bursts by hand: `ids` go into a burst at `index` (0 = the pick), into a new burst, or +/// out of every burst. Every burst touched is then arranged by hand ([`Analysis::rank`]), so +/// culling run again keeps it. What marks a burst's pick follows its first photo: `best` (the +/// Best of Similar Shots rule), the Pick flag when culling's pick had it, and the top of the +/// burst's stack when the burst is stacked. One undo step. +fn move_to_burst(s: &mut Session, p: &Value) -> Result { + use std::collections::{BTreeMap, HashMap}; + const C: &str = "photo.moveToBurst"; + let mut ids = s.targets(p)?; + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); + if ids.is_empty() { + return Err(super::bad(C, "no photos")); + } + for id in &ids { + match s.catalog.photo(*id) { + Some(ph) if ph.deleted => return Err(super::bad(C, format!("“{}” is deleted", ph.file_name))), + Some(ph) if ph.analysis.is_none() => { + return Err(super::bad(C, format!("“{}” has no culling scores yet: run Assisted Culling on it first", ph.file_name))); } - s.selection.active = Some(top); + Some(_) => {} + None => return Err(super::bad(C, format!("no photo {}", id.0))), } } - Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) + let group = |s: &Session, id: PhotoId| s.catalog.photo(id).and_then(|p| p.analysis).and_then(|a| a.group); + let index = s.catalog.burst_index(); + let into = match p.get("burst") { + None => Dest::Burst(group(s, ids[0]).ok_or_else(|| super::bad(C, "the photo isn't in a burst: say which `burst` it goes to"))?), + Some(Value::Null) => Dest::Nowhere, + Some(Value::String(n)) if n == "new" => Dest::New, + Some(v) => match v.as_u64().and_then(|n| u32::try_from(n).ok()) { + Some(n) if index.contains_key(&n) => Dest::Burst(n), + Some(n) => return Err(super::bad(C, format!("there is no burst {n}"))), + None => return Err(super::bad(C, "`burst` must be a burst number, \"new\" or null")), + }, + }; + let at = match p.get("index") { + None | Some(Value::Null) => usize::MAX, + Some(v) => v.as_u64().map(|n| n as usize).ok_or_else(|| super::bad(C, "`index` must be a place in the burst: 0 (the pick), 1, …"))?, + }; + // the bursts touched, before and after + let target = match into { + Dest::Burst(g) => Some(g), + Dest::New => Some(s.catalog.next_burst_id()), + Dest::Nowhere => None, + }; + let mut old: BTreeMap> = BTreeMap::new(); + for g in ids.iter().filter_map(|id| group(s, *id)).chain(target) { + old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default()); + } + let mut new = old.clone(); + for members in new.values_mut() { + members.retain(|m| !ids.contains(m)); + } + if let Some(g) = target { + let members = new.entry(g).or_default(); + let at = at.min(members.len()); + members.splice(at..at, ids.iter().copied()); + } + // each photo's burst, place and pick: a burst a move leaves with one photo is no burst (the + // burst moved into stays one, so a new burst may start with one photo for more to join) + let remains = |g: u32, members: &Vec| members.len() >= 2 || (target == Some(g) && !members.is_empty()); + let mut placed: HashMap, u32, bool)> = ids.iter().map(|id| (*id, (None, 0, false))).collect(); + for (g, members) in &new { + let stays = remains(*g, members); + for (i, m) in members.iter().enumerate() { + placed.insert(*m, if stays { (Some(*g), i as u32, i == 0) } else { (None, 0, false) }); + } + } + let mut ops = Vec::new(); + let mut by_id: Vec<_> = placed.iter().collect(); + by_id.sort_by_key(|(id, _)| **id); + for (id, (g, rank, best)) in by_id { + let Some(was) = s.catalog.photo(*id).and_then(|p| p.analysis) else { continue }; + let now = Analysis { group: *g, rank: Some(*rank), best: *best, ..was }; + if now != was { + ops.push(Op::SetAnalysis { id: *id, analysis: Some(now) }); + } + } + // what the target burst holds now + let members: Option> = target.and_then(|g| new.get(&g).filter(|m| remains(g, m))).map(|m| m.iter().map(|p| p.0).collect()); + let report = |changed: bool| json!({"burst": members.as_ref().and(target), "pick": members.as_ref().and_then(|m| m.first()), "photos": members, "changed": changed}); + if ops.is_empty() { + return Ok(report(false)); + } + // the Pick culling gave a burst's pick goes to its new pick + let is_pick = |id: PhotoId| placed.get(&id).is_some_and(|p| p.2); + let flag = |s: &Session, id: PhotoId| s.catalog.photo(id).map(|p| p.flag).unwrap_or_default(); + let mut flags: BTreeMap = BTreeMap::new(); + for (g, before) in &old { + let Some(old_pick) = before.iter().copied().find(|m| s.catalog.photo(*m).and_then(|p| p.analysis).is_some_and(|a| a.best)) else { continue }; + let new_pick = new.get(g).filter(|m| remains(*g, m)).and_then(|m| m.first()).copied(); + if flag(s, old_pick) != Flag::Pick || new_pick == Some(old_pick) { + continue; + } + if !is_pick(old_pick) { + flags.insert(old_pick, Flag::None); + } + if let Some(n) = new_pick + && flag(s, n) == Flag::None + { + flags.insert(n, Flag::Pick); + } + } + ops.extend(flags.into_iter().map(|(id, flag)| Op::SetFlag { id, flag })); + // a stacked burst (a stack of exactly its photos, as culling stacks them) follows it: its stack + // shrinks, grows or goes, in the burst's order. Shrinking first: a photo is in one stack at a time. + let (mut shrink, mut grow) = (Vec::new(), Vec::new()); + let mut grows_target = false; + let mut followed = std::collections::HashSet::new(); + for (g, before) in old.iter().filter(|(_, m)| m.len() >= 2) { + let Some(st) = s.catalog.stack_of(before[0]).filter(|st| st.photos.len() == before.len() && before.iter().all(|m| st.photos.contains(m))) + else { + continue; + }; + followed.insert(st.id); + let after = new.get(g).filter(|m| m.len() >= 2); + match after { + None => shrink.push(Op::RemoveStack { id: st.id }), + Some(after) if after == &st.photos => {} + Some(after) => { + let op = Op::SetStack { id: st.id, photos: after.clone(), collapsed: st.collapsed }; + if after.iter().all(|m| st.photos.contains(m)) { + shrink.push(op) + } else { + grows_target = true; + grow.push(op) + } + } + } + } + if grows_target { + // photos joining a stacked burst leave any other stack they are in + let strays: Vec = ids.iter().copied().filter(|id| s.catalog.stack_of(*id).is_some_and(|st| !followed.contains(&st.id))).collect(); + shrink.extend(s.catalog.remove_from_stacks_ops(&strays)); + } + let restacked = !shrink.is_empty() || !grow.is_empty(); + ops.extend(shrink); + ops.extend(grow); + let same = matches!(into, Dest::Burst(g) if ids.iter().all(|id| group(s, *id) == Some(g))); + let label = match into { + Dest::Burst(_) if same && at == 0 => "Choose Burst Pick", + Dest::Burst(_) if same => "Rearrange Burst", + Dest::Burst(_) => "Move to Burst", + Dest::New => "New Burst", + Dest::Nowhere => "Remove from Burst", + }; + s.commit(label, Op::Batch { ops })?; + if restacked { + keep_active_shown(s); + } + Ok(report(true)) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -202,9 +388,18 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93), resetBursts?: bool (false)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain). Photos whose burst was arranged by hand (`photo.moveToBurst`) keep their burst, place and pick and are only scored again, unless `resetBursts`; one undo step → {photos: [{id, sharpness, clipped, group, best, byHand}], groups, kept, stacks, rejected, picked, failed}", always, analyze ), + cmd!( + "photo.moveToBurst", + "Move to Burst", + [], + None, + "{ids?, burst?: number | \"new\" | null (default: the first photo's burst), index?: place (0 = the pick; default last)} — arrange Assisted Culling's bursts by hand (Window ▸ Bursts): the photos go into that burst at `index`, into a new burst, or (null) out of every burst; reordering within a burst is the same call. A burst left with one photo is no burst. The pick follows the first place: Best of Similar Shots, the Pick flag culling gave the old pick, and the top of the burst's stack. Every burst touched is kept as arranged when culling runs again (`photo.analyze` `resetBursts` forgets it). Photos must have been culled; one undo step → {burst, photos, pick, changed}", + always, + move_to_burst + ), ] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 25e6ef52f8..7fc3195fd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1247,6 +1247,8 @@ mod tests_album_remove; #[cfg(test)] mod tests_albums_local; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_color; #[cfg(test)] mod tests_crop_angle; diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs new file mode 100644 index 0000000000..f402fbffe8 --- /dev/null +++ b/crates/engine/src/tests_bursts.rs @@ -0,0 +1,250 @@ +//! Bursts arranged by hand (`photo.moveToBurst`): a photo moved within its burst, into another, +//! into a new one or out of every burst; the pick follows the first place, and with it the +//! Best of Similar Shots rule, the Pick flag culling set and the burst's stack. Culling run again +//! keeps what was arranged by hand. + +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source, Stack}; +use serde_json::{Value, json}; + +use crate::Session; + +/// A photo culled into `group` (`None`: culled, in no burst; `best`: its pick), or never culled. +fn add(s: &mut Session, name: &str, when: &str, culled: Option<(Option, f32, bool)>) -> PhotoId { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 40, 30, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(group, sharpness, best)| Analysis { sharpness, group, best, ..Default::default() }); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn an(s: &Session, id: PhotoId) -> Analysis { + s.catalog.photo(id).unwrap().analysis.unwrap() +} + +fn flag(s: &Session, id: PhotoId) -> Flag { + s.catalog.photo(id).unwrap().flag +} + +fn mv(s: &mut Session, p: Value) -> Value { + s.execute("photo.moveToBurst", &p).unwrap_or_else(|e| panic!("{p}: {e}")) +} + +/// Burst 1 (a best and picked, b, c), burst 2 (d best, e), x culled in no burst, y never culled. +fn library() -> (Session, [PhotoId; 7]) { + let mut s = Session::new(); + let a = add(&mut s, "a.jpg", "2026-05-01T10:00:00", Some((Some(1), 80.0, true))); + let b = add(&mut s, "b.jpg", "2026-05-01T10:00:01", Some((Some(1), 60.0, false))); + let c = add(&mut s, "c.jpg", "2026-05-01T10:00:02", Some((Some(1), 40.0, false))); + let d = add(&mut s, "d.jpg", "2026-05-01T11:00:00", Some((Some(2), 70.0, true))); + let e = add(&mut s, "e.jpg", "2026-05-01T11:00:01", Some((Some(2), 30.0, false))); + let x = add(&mut s, "x.jpg", "2026-05-01T12:00:00", Some((None, 50.0, false))); + let y = add(&mut s, "y.jpg", "2026-05-01T13:00:00", None); + s.catalog.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); + (s, [a, b, c, d, e, x, y]) +} + +#[test] +fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { + let (mut s, [a, b, c, ..]) = library(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + let commits = s.commits(); + // the softest shot is the one the person likes best + let r = mv(&mut s, json!({"ids": [c.0], "index": 0})); + assert_eq!((r["burst"].clone(), r["photos"].clone(), r["pick"].clone()), (json!(1), json!([c.0, a.0, b.0]), json!(c.0)), "{r}"); + assert_eq!(s.catalog.burst(1), vec![c, a, b]); + assert!(an(&s, c).best && !an(&s, a).best); + assert_eq!([an(&s, c).rank, an(&s, a).rank, an(&s, b).rank], [Some(0), Some(1), Some(2)], "the whole burst is now arranged by hand"); + // the Pick culling gave the old best goes with it + assert_eq!((flag(&s, c), flag(&s, a)), (Flag::Pick, Flag::None)); + // and so does Best of Similar Shots + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + let shown = s.visible_cloned(); + assert!(shown.contains(&c) && !shown.contains(&a), "{shown:?}"); + // one undo step + assert_eq!(s.commits(), commits + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + assert!(an(&s, a).best && an(&s, a).rank.is_none()); + assert_eq!((flag(&s, a), flag(&s, c)), (Flag::Pick, Flag::None)); + // reordering further back: the pick stays, the order is kept + mv(&mut s, json!({"ids": [b.0], "index": 2})); + assert_eq!(s.catalog.burst(1), vec![a, c, b]); + assert!(an(&s, a).best); + assert_eq!(flag(&s, a), Flag::Pick); + // placing a photo where it already is changes nothing and makes no undo step + let commits = s.commits(); + let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.commits(), commits); +} + +#[test] +fn photos_move_between_bursts_into_new_ones_and_out() { + let (mut s, [a, b, c, d, e, x, y]) = library(); + // e joins burst 1 in second place; burst 2 keeps only d, which is then in no burst + let r = mv(&mut s, json!({"ids": [e.0], "burst": 1, "index": 1})); + assert_eq!(r["photos"], json!([a.0, e.0, b.0, c.0]), "{r}"); + assert_eq!(an(&s, e).group, Some(1)); + assert!(s.catalog.burst(2).is_empty()); + assert_eq!((an(&s, d).group, an(&s, d).best, an(&s, d).by_hand()), (None, false, true)); + // without an index it goes last; a culled loose photo can join too + mv(&mut s, json!({"ids": [x.0], "burst": 1})); + assert_eq!(s.catalog.burst(1), vec![a, e, b, c, x]); + // two photos make a new burst, in the order named + let r = mv(&mut s, json!({"ids": [c.0, b.0], "burst": "new"})); + let new = r["burst"].as_u64().unwrap() as u32; + assert_ne!(new, 1, "a number no photo uses: {r}"); + assert_eq!(s.catalog.burst(new), vec![c, b]); + assert!(an(&s, c).best); + assert_eq!(s.catalog.burst(1), vec![a, e, x]); + // out of every burst: the photo left alone in its burst is out too + let r = mv(&mut s, json!({"ids": [b.0], "burst": null})); + assert_eq!(r["burst"], Value::Null, "{r}"); + assert!(s.catalog.burst(new).is_empty()); + assert!([b, c].iter().all(|p| an(&s, *p).group.is_none() && !an(&s, *p).best && an(&s, *p).by_hand())); + // a whole burst dropped on another merges them, the target's pick first + mv(&mut s, json!({"ids": [b.0, c.0], "burst": "new"})); + let merged = s.catalog.burst(1); + let theirs = s.catalog.bursts_among(&[b], None)[0].clone(); + mv(&mut s, json!({"ids": theirs.1.iter().map(|p| p.0).collect::>(), "burst": 1})); + assert_eq!(s.catalog.burst(1), [merged, theirs.1].concat()); + assert!(s.catalog.burst(theirs.0).is_empty()); + // refused, with nothing changed: a photo never culled, a burst that isn't there, a bad index + let commits = s.commits(); + for (p, why) in [ + (json!({"ids": [y.0], "burst": 1}), "Assisted Culling"), + (json!({"ids": [a.0], "burst": 99}), "no burst 99"), + (json!({"ids": [a.0], "index": -1}), "index"), + (json!({"ids": [a.0], "burst": "first"}), "burst"), + (json!({"ids": [d.0]}), "isn't in a burst"), + (json!({"ids": []}), "no photos"), + ] { + let err = s.execute("photo.moveToBurst", &p).expect_err(&p.to_string()).to_string(); + assert!(err.contains(why), "{p}: {err}"); + } + assert_eq!(s.commits(), commits); + // a new burst may start with one photo, for more to join + let r = mv(&mut s, json!({"ids": [d.0], "burst": "new"})); + let solo = r["burst"].as_u64().unwrap() as u32; + assert_eq!(s.catalog.burst(solo), vec![d]); + assert!(an(&s, d).best); + mv(&mut s, json!({"ids": [x.0], "burst": solo, "index": 0})); + assert_eq!(s.catalog.burst(solo), vec![x, d]); +} + +#[test] +fn a_stacked_burst_follows_its_pick_and_its_members() { + let (mut s, [a, b, c, d, e, ..]) = library(); + // as Assisted Culling with "Stack each burst" leaves them: collapsed, the best on top + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(1), photos: vec![a, b, c], collapsed: true } }).unwrap(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(2), photos: vec![d, e], collapsed: true } }).unwrap(); + mv(&mut s, json!({"ids": [c.0], "index": 0})); + let st = s.catalog.stack_of(c).unwrap(); + assert_eq!((st.photos.clone(), st.collapsed), (vec![c, a, b], true), "the new pick tops the stack"); + // d moves into burst 1: its stack (now just e) goes, burst 1's stack takes it in + s.selection = crate::Selection::single(d); + mv(&mut s, json!({"ids": [d.0], "burst": 1, "index": 1})); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, d, a, b]); + assert!(s.catalog.stack_of(e).is_none()); + // d is hidden in the collapsed stack now: the stack's top is the active photo + assert_eq!(s.selection.active, Some(c)); + // one undo brings both stacks back as they were + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![d, e]); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, a, b]); + // a photo stacked with something else than its burst keeps that stack when it goes to an unstacked burst + let (mut s, [a, b, c, _, e, x, _]) = library(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(5), photos: vec![x, e], collapsed: false } }).unwrap(); + mv(&mut s, json!({"ids": [e.0], "burst": 1})); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![x, e]); + assert_eq!(s.catalog.burst(1), vec![a, b, c, e]); +} + +/// Look-alike PNGs (a scene and two softer copies) for the culling runs below. +fn burst_files(tag: &str, scene: usize) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-bursts-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_scenes::demo_library()[scene].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + for (name, im) in [("1_sharp.png", img.clone()), ("2_soft.png", soften(&img, 3)), ("3_softer.png", soften(&img, 6))] { + let data: Vec<[u8; 4]> = im + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: im.width, height: im.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(format!("s{scene}_{name}")), png).unwrap(); + } + dir +} + +#[test] +fn culling_again_keeps_bursts_arranged_by_hand() { + let (one, two) = (burst_files("keep-1", 0), burst_files("keep-2", 7)); + let mut s = Session::new().with_fs(); + let import = |s: &mut Session, dir: &std::path::Path, hour: u32| -> Vec { + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let mut ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).map(PhotoId).collect(); + ids.sort_by_key(|id| s.catalog.photo(*id).unwrap().file_name.clone()); + for (i, id) in ids.iter().enumerate() { + s.commit("t", Op::SetCaptured { id: *id, captured: Some(format!("2026-05-01T{hour:02}:00:0{i}")) }).unwrap(); + } + ids + }; + let first = import(&mut s, &one, 10); + let second = import(&mut s, &two, 14); + let ids = |v: &[PhotoId]| v.iter().map(|p| p.0).collect::>(); + // two runs on different photos number their bursts apart + s.execute("photo.analyze", &json!({"ids": ids(&first), "pickBest": true})).unwrap(); + s.execute("photo.analyze", &json!({"ids": ids(&second)})).unwrap(); + let (g1, g2) = (an(&s, first[0]).group.unwrap(), an(&s, second[0]).group.unwrap()); + assert_ne!(g1, g2, "each run's bursts get numbers of their own"); + assert_eq!(s.catalog.burst(g1), first, "sharpest first"); + // the softest is the person's pick + let softest = first[2]; + mv(&mut s, json!({"ids": [softest.0], "index": 0})); + assert_eq!(flag(&s, softest), Flag::Pick); + // culling the whole view again keeps that burst as arranged, with fresh scores + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "pickBest": true})).unwrap(); + assert_eq!(r["kept"], 3, "{r}"); + assert_eq!(s.catalog.burst(g1), vec![first[2], first[0], first[1]]); + assert!(an(&s, softest).best && !an(&s, first[0]).best); + assert_eq!(flag(&s, first[0]), Flag::None, "pickBest picks the pick chosen by hand, not the sharpest"); + let g2_again = an(&s, second[0]).group.unwrap(); + assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); + assert_eq!(s.catalog.burst(g2_again), second); + // asked to regroup, culling forgets the order set by hand + s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); + let g = an(&s, first[0]).group.unwrap(); + assert_eq!(s.catalog.burst(g), first); + assert!(first.iter().all(|p| !an(&s, *p).by_hand())); + assert!(s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&one); + let _ = std::fs::remove_dir_all(&two); +} From 74ded5b14fbb6fb7697b81fce58c6c171c38a457 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 008/247] =?UTF-8?q?LR-LIB-CULL:=20Window=20=E2=96=B8=20Bur?= =?UTF-8?q?sts=20arranges=20bursts=20by=20drag=20and=20drop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-hand panel (`panel.bursts`) shows the bursts of the photos in view, with the hidden members of collapsed stacks, each a row of thumbnails with its pick first. Drag a photo to another place in its burst (first: it becomes the pick), into another burst, onto New burst or Not in a burst; drag a burst by its title onto another to merge them. Photos dragged from the grid drop here too. The drag is the grid's photo drag (its label says what a drop does); each drop is one `photo.moveToBurst`. Photos culling never scored are refused. The Assisted Culling dialog gets "Regroup bursts I arranged by hand" (`resetBursts`) and a hint pointing to Window ▸ Bursts. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menubar.rs | 2 + crates/ui-egui/src/menus.rs | 14 +- crates/ui-egui/src/panels/bursts.rs | 271 +++++++++++++++++++++++++++ crates/ui-egui/src/panels/dialogs.rs | 9 +- crates/ui-egui/src/panels/left.rs | 2 +- crates/ui-egui/src/panels/mod.rs | 1 + crates/ui-egui/src/panels/right.rs | 9 +- crates/ui-egui/src/state.rs | 7 +- crates/ui-egui/src/tests_bursts.rs | 207 ++++++++++++++++++++ 10 files changed, 518 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/panels/bursts.rs create mode 100644 crates/ui-egui/src/tests_bursts.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86e..4c43ec8a69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -60,6 +60,8 @@ mod tests_before_after; #[cfg(test)] mod tests_browse_active; #[cfg(test)] +mod tests_bursts; +#[cfg(test)] mod tests_button; #[cfg(test)] mod tests_canvas_keys; @@ -1625,6 +1627,8 @@ mod drop_tests { #[derive(Default)] pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, + /// The Bursts panel's bursts, by the view's generation. + bursts: Option<(u64, panels::bursts::Shown)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index c5e4e45c77..4c2a7e4b6e 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -236,6 +236,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "panel.activity", "panel.info", "panel.keywords", + "panel.bursts", "---", "@Edit Sections", "@Tools", @@ -367,6 +368,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "panel.activity" => panel(RightPanel::Activity), "panel.info" => panel(RightPanel::Info), "panel.keywords" => panel(RightPanel::Keywords), + "panel.bursts" => panel(RightPanel::Bursts), "panel.presets" => Some(u.presets), "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write), _ => None, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 41df245a78..01fbd49216 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -145,6 +145,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("panel.keywords", "Keywords", Some("K"), "Window"), ("panel.versions", "Versions", Some("Shift+V"), "Window"), ("panel.activity", "History", None, "Window"), + ("panel.bursts", "Bursts", None, "Window"), ("panel.close", "Close Panel", None, ""), // {solo?}: true opens just that section (⌥-click on its header); otherwise opens or closes it ("section.light", "Light", Some("Cmd+1"), "Window>Edit Sections"), @@ -1157,6 +1158,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { + panel(app, &ctx, RightPanel::Bursts, "Bursts"); + Ok(Value::Null) + } "panel.presets" => { app.ui.presets = !app.ui.presets || !crate::docking::exposed(app, crate::docking::Panel::Presets); if app.ui.presets && app.ui.view != ViewMode::Detail { @@ -1444,7 +1449,14 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option open_original_in(app, &ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { + reject_below: 0.0, + pick_best: true, + stack_groups: app.ui.cull_stack, + burst_gap, + similarity, + reset_bursts: false, + }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs new file mode 100644 index 0000000000..8a6d17fd9d --- /dev/null +++ b/crates/ui-egui/src/panels/bursts.rs @@ -0,0 +1,271 @@ +//! Window ▸ Bursts: Assisted Culling's bursts among the photos in view (with the hidden members of +//! their collapsed stacks), each a row of thumbnails with its pick first, to put right by hand. +//! +//! Drag a photo to another place in its burst (to the front, and it becomes the pick), into +//! another burst, onto *New burst* or onto *Not in a burst*; drag a burst by its title onto +//! another to merge them. Photos dragged from the grid drop here too. A drag is the grid's photo +//! drag ([`crate::state::UiState::dragging_photos`]: its label, Esc and release), and a drop is one +//! `photo.moveToBurst`, so one undo step. +//! +//! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, +//! `burst:new`, `burst:none`. + +use std::collections::HashSet; +use std::sync::Arc; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::theme::Tokens; +use crate::widgets::register; + +/// Thumbnail cells: side, gap, row inset. +const CELL: f32 = 68.0; +const GAP: f32 = 6.0; +const INSET: f32 = 20.0; +/// A burst's title row. +const TITLE_H: f32 = 30.0; + +/// The bursts shown, by the view's generation (which follows every catalog change). +pub type Shown = Arc)>>; + +/// The bursts among the photos in view and the hidden members of their stacks, in view order. +fn bursts(app: &mut LightcraftApp) -> Shown { + let (generation, ids) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.bursts + && *g == generation + { + return b.clone(); + } + let cat = &app.session.catalog; + let mut scope: HashSet = ids.iter().copied().collect(); + for id in ids.iter() { + if let Some(st) = cat.stack_of(*id) { + scope.extend(st.photos.iter().copied()); + } + } + let b: Shown = Arc::new(cat.bursts_among(&ids, Some(&scope))); + app.caches.bursts = Some((generation, b.clone())); + b +} + +/// Where a drop under the pointer would put the dragged photos. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Target { + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included). + Burst(u32, usize), + New, + Nowhere, +} + +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + egui::ScrollArea::vertical().id_salt("bursts-scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + super::left::drag_auto_scroll(app, ui); + super::right::header(ui, "Bursts"); + let shown = bursts(app); + let dragged: Option> = app.ui.dragging_photos.as_ref().map(|v| v.iter().copied().map(PhotoId).collect()); + let pointer = ui.input(|i| i.pointer.latest_pos()).filter(|p| ui.clip_rect().contains(*p)); + let mut target: Option<(Target, Option)> = None; + let width = ui.available_width(); + let explain = if shown.is_empty() { + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand." + } else { + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them." + }; + egui::Frame::NONE.inner_margin(egui::Margin { left: INSET as i8, right: INSET as i8, top: 0, bottom: 10 }).show(ui, |ui| { + ui.set_width(width - 2.0 * INSET); + ui.label(egui::RichText::new(crate::i18n::tr(explain)).color(t.text_dim).size(12.0)); + }); + let cols = (((width - 2.0 * INSET + GAP) / (CELL + GAP)).floor() as usize).max(1); + for (k, (g, photos)) in shown.iter().enumerate() { + // the title: a drop there puts the photos last; dragged, it takes the burst along + let (title, resp) = ui.allocate_exact_size(vec2(width, TITLE_H), Sense::click_and_drag()); + register(ui.ctx(), format!("burst:{g}"), title); + let p = ui.painter(); + let name = format!("{} {}", crate::i18n::tr("Burst"), k + 1); + p.text(pos2(title.left() + INSET, title.center().y), Align2::LEFT_CENTER, name, t.semibold(12.5), t.text); + let n = photos.len(); + let count = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); + p.text(pos2(title.right() - INSET, title.center().y), Align2::RIGHT_CENTER, count, t.font(11.5), t.text_dim); + if resp.hovered() && dragged.is_none() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(photos.iter().map(|p| p.0).collect()); + } + if pointer.is_some_and(|p| title.contains(p)) { + target = Some((Target::Burst(*g, n), None)); + } + // the photos, in rows + let rows = n.div_ceil(cols); + let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * (CELL + GAP) + GAP), Sense::hover()); + let cell_at = |i: usize| { + let (r, c) = (i / cols, i % cols); + Rect::from_min_size(pos2(area.left() + INSET + c as f32 * (CELL + GAP), area.top() + r as f32 * (CELL + GAP)), vec2(CELL, CELL)) + }; + for (i, id) in photos.iter().enumerate() { + let r = cell_at(i); + if let Some(badge) = photo_cell(app, ui, *id, r) { + register(ui.ctx(), format!("burstPick:{g}"), badge); + } + // a drop on a photo's left half goes before it, on its right half after it + if let Some(p) = pointer + && r.expand(GAP / 2.0).contains(p) + { + let slot = if p.x < r.center().x { i } else { i + 1 }; + let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; + target = Some((Target::Burst(*g, slot), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + } + } + if target.is_none() + && let Some(p) = pointer + && area.contains(p) + { + // the room after the last photo: last + let last = cell_at(n.saturating_sub(1)); + target = Some((Target::Burst(*g, n), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + } + if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { + ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); + } + } + // drop places for a new burst and for none: there while there are bursts, or a drag + if !shown.is_empty() || dragged.is_some() { + ui.add_space(8.0); + for (key, label, tgt) in [("burst:new", "New burst", Target::New), ("burst:none", "Not in a burst", Target::Nowhere)] { + let (row, _) = ui.allocate_exact_size(vec2(width, 40.0), Sense::hover()); + let zone = row.shrink2(vec2(INSET, 4.0)); + register(ui.ctx(), key, zone); + let over = dragged.is_some() && pointer.is_some_and(|p| zone.contains(p)); + let stroke = if over { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.divider) }; + ui.painter().rect_stroke(zone, 6.0, stroke, StrokeKind::Inside); + ui.painter().text(zone.center(), Align2::CENTER_CENTER, crate::i18n::tr(label), t.font(12.0), if over { t.text } else { t.text_dim }); + if over { + target = Some((tgt, None)); + } + } + } + if let Some(ids) = dragged + && let Some((tgt, mark)) = target + { + drop_on(app, ui, &shown, &ids, tgt, mark); + } + ui.add_space(12.0); + }); +} + +/// One photo of a burst: its thumbnail, the pick's badge (returned), the active photo's outline; +/// a click selects it, a drag takes it along. +fn photo_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect) -> Option { + let t = Tokens::get(ui.ctx()); + let photo = app.session.catalog.photo(id).cloned()?; + let pick = photo.analysis.is_some_and(|a| a.best); + let resp = ui.interact(r, egui::Id::new(("burst-photo", id.0)), Sense::click_and_drag()); + register(ui.ctx(), format!("burstPhoto:{}", id.0), r); + // Any thumbnail will do at this size: one is asked for only when there is none, so the grid's + // larger ones are never asked again at this size (and back) every frame. Above the grid's own + // priorities: a member hidden in a collapsed stack isn't in the grid, which evicts the rest. + if app.renderer.thumb(id).is_none() && !app.renderer.is_pending(crate::render::Slot::Thumb(id)) { + let px = (CELL * ui.ctx().pixels_per_point()).ceil() as usize; + super::grid::request_thumb(app, id, px, 12); + } + let p = ui.painter(); + p.rect_filled(r, 3.0, Color32::from_gray(30)); + let shown = match app.renderer.thumb(id) { + Some(tex) => { + let fit = super::detail::fit_texture_rect(r, tex.size); + p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + fit + } + None => r, + }; + if photo.flag == Flag::Reject { + p.rect_filled(shown, 0.0, Color32::from_black_alpha(110)); + } + let state = app.session.selection.state_of(id); + if state == lightcraft_engine::SelectionState::Active { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); + } else if state != lightcraft_engine::SelectionState::NotSelected { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::from_gray(170)), StrokeKind::Outside); + } + let badge = pick.then(|| { + let g = p.layout_no_wrap(crate::i18n::tr("Pick").into(), t.semibold(9.5), Color32::WHITE); + let badge = Rect::from_min_size(r.min + vec2(3.0, 3.0), vec2(g.size().x + 10.0, 14.0)); + p.rect_filled(badge, 7.0, t.accent); + p.galley(pos2(badge.left() + 5.0, badge.center().y - g.size().y / 2.0), g, Color32::WHITE); + badge + }); + if photo.flag == Flag::Pick { + crate::icons::paint( + p, + Rect::from_min_size(pos2(r.right() - 16.0, r.bottom() - 16.0), vec2(13.0, 13.0)), + crate::icons::Icon::FlagPick, + t.pick, + ); + } + let focus = photo.analysis.map(|a| a.sharpness.round() as i32).unwrap_or_default(); + let resp = resp.on_hover_text(format!("{} · {} {focus}", photo.file_name, crate::i18n::tr("Focus"))); + if resp.clicked() { + let _ = app.run("library.select", json!({"ids": [id.0]})); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(vec![id.0]); + } + badge +} + +/// Photos dragged over `tgt`: the mark where they would go, the label saying what a drop does, +/// and on release the move. +fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[PhotoId], tgt: Target, mark: Option) { + let t = Tokens::get(ui.ctx()); + let released = ui.input(|i| i.pointer.any_released()); + // only photos culling scored can be in a burst + if ids.iter().any(|id| app.session.catalog.photo(*id).is_none_or(|p| p.analysis.is_none())) { + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let why = if ids.len() == 1 { "Run Assisted Culling on it first" } else { "Run Assisted Culling on these photos first" }; + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(why).into()); + if released { + app.toast( + ui.ctx(), + crate::i18n::tr("Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first"), + ); + app.ui.dragging_photos = None; + } + return; + } + let (params, hint) = match tgt { + Target::Burst(g, slot) => { + let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); + // the place once the dragged photos have left theirs + let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); + let whole = shown.iter().any(|(n, m)| *n != g && m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let hint = if whole { + "Merge into this burst" + } else if index == 0 && slot < members.len() { + if ids.len() == 1 { "Make it the pick" } else { "Put first: the first is the pick" } + } else if ids.iter().all(|id| members.contains(id)) { + "Move here" + } else { + "Move to this burst" + }; + let index = if slot >= members.len() { Value::Null } else { json!(index) }; + (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) + } + Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), + Target::Nowhere => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": null}), "Take out of its burst"), + }; + if let Some(mark) = mark { + ui.painter().rect_filled(mark, 1.5, t.accent); + } + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(hint).into()); + if released { + if let Err(e) = app.run("photo.moveToBurst", params) { + app.toast(ui.ctx(), e); + } + app.ui.dragging_photos = None; + } +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index 575ba09cd3..d55e38e4ce 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -336,7 +336,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), ); } - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); @@ -360,6 +360,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let r = ui.add(egui::Slider::new(similarity, 0.70..=0.99).text(crate::i18n::tr("Burst: how alike (loose … strict)")).step_by(0.01).fixed_decimals(2)); crate::widgets::register(ui.ctx(), "field:cullSimilar", r.rect); ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); + let r = ui.checkbox(reset_bursts, crate::i18n::tr("Regroup bursts I arranged by hand")); + crate::widgets::register(ui.ctx(), "check:cullResetBursts", r.rect); + ui.label(egui::RichText::new(crate::i18n::tr("Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.")).color(t.text_dim)); ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); } Dialog::WhatsNew => { @@ -1920,10 +1923,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); app.ui.cull_stack = *stack_groups; - let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity}); + let mut p = json!({"pickBest": pick_best, "stackGroups": stack_groups, "burstGap": burst_gap, "similarity": similarity, "resetBursts": reset_bursts}); if *reject_below > 0.0 { p["rejectBelow"] = json!(reject_below); } diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 3bb8deba2e..1b83e709c4 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -1273,7 +1273,7 @@ pub fn auto_scroll_speed(y: f32, top: f32, bottom: f32) -> f32 { /// While an album, or photos from the grid, are dragged over the sidebar: scrolls it when the /// pointer is near its top or bottom edge, so rows beyond the visible part can be reached. Call /// inside the scroll area. -fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { +pub(crate) fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { if app.ui.dragging_album.is_none() && app.ui.dragging_photos.is_none() && app.ui.dragging_section.is_none() { return; } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 2fcb36663c..9b9eebc1c5 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -2,6 +2,7 @@ pub mod activity; pub mod bottombar; +pub mod bursts; pub mod chips; pub mod compare; pub mod crop_overlay; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 5373308102..b17d3dd8f1 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -1,5 +1,5 @@ //! The right-hand panel next to the tool strip: Edit, Crop, Remove, Masking, Red Eye, Info, -//! Keywords, Versions, Activity. +//! Keywords, Versions, Activity, Bursts. use egui::{Align2, Rect, Sense, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -15,6 +15,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); frame.show(ui, |ui| { + // the bursts are the view's, not a photo's: they are there without a selection + if app.ui.right == RightPanel::Bursts { + super::bursts::show(app, ui); + return; + } // (taken on every pass the panel is drawn; one from earlier than the pass before is forgotten) let held = held_offset(ui.ctx()); let Some(id) = app.session.active() else { @@ -66,7 +71,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::Keywords => keywords(app, ui, id), RightPanel::Versions => versions(app, ui, id), RightPanel::Activity => activity(app, ui, id), - RightPanel::None => {} + RightPanel::Bursts | RightPanel::None => {} } }); ui.data_mut(|d| d.insert_temp(egui::Id::new(AREA), scrolled.id)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f97a4b44dd..783ccd0b4f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -37,6 +37,8 @@ pub enum RightPanel { Info, /// The profile browser (part of Edit). Profiles, + /// Assisted Culling's bursts, to arrange by hand (Window ▸ Bursts). + Bursts, } impl RightPanel { @@ -1097,13 +1099,16 @@ pub enum Dialog { WhatsNew, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most - /// `burst_gap` seconds apart and at least `similarity` alike are a burst. + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Bursts arranged by + /// hand (Window ▸ Bursts) are kept unless `reset_bursts`. Cull { reject_below: f32, pick_best: bool, stack_groups: bool, burst_gap: f32, similarity: f32, + #[serde(default)] + reset_bursts: bool, }, /// Help ▸ System Info: (label, value) rows. DenoiseModel { diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs new file mode 100644 index 0000000000..e7ce2858ba --- /dev/null +++ b/crates/ui-egui/src/tests_bursts.rs @@ -0,0 +1,207 @@ +//! Window ▸ Bursts: Assisted Culling's bursts as rows of thumbnails, pick first. A photo dragged +//! to the front of its burst becomes the pick; dragged into another burst, onto New Burst or Not +//! in a Burst it moves there; a burst dragged by its title merges into another; photos dragged +//! from the grid drop here too. Each drop is one undo step. + +use egui::{Pos2, Rect, pos2}; +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +/// Burst 1: a (picked by culling), b, c; burst 2: d, e; f never culled. The grid, with the +/// Bursts panel open. +fn app() -> (Headless, [PhotoId; 6]) { + let mut session = lightcraft_engine::Session::new(); + let mut add = |name: &str, when: &str, culled: Option<(u32, f32, bool)>| { + let id = session.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 300, 200, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(g, sharpness, best)| Analysis { sharpness, group: Some(g), best, ..Default::default() }); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let ids = [ + add("a.jpg", "2026-05-01T10:00:00", Some((1, 80.0, true))), + add("b.jpg", "2026-05-01T10:00:01", Some((1, 60.0, false))), + add("c.jpg", "2026-05-01T10:00:02", Some((1, 40.0, false))), + add("d.jpg", "2026-05-01T11:00:00", Some((2, 70.0, true))), + add("e.jpg", "2026-05-01T11:00:01", Some((2, 30.0, false))), + add("f.jpg", "2026-05-01T12:00:00", None), + ]; + session.catalog.apply(Op::SetFlag { id: ids[0], flag: Flag::Pick }).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid"}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], true, "{r}"); + h.app.run("panel.bursts", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.app.ui.right, RightPanel::Bursts); + (h, ids) +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| { + panic!("no {id} in {:?}", h.app.widgets.iter().filter(|(w, _)| w.starts_with("burst")).map(|(w, _)| w).collect::>()) + }) +} + +fn cell(h: &Headless, id: PhotoId) -> Rect { + widget(h, &format!("burstPhoto:{}", id.0)) +} + +fn press(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.step(); +} + +fn glide(h: &mut Headless, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + // (synthetic input arrives a frame or two behind) + for _ in 0..3 { + h.step(); + } +} + +fn release(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + h.step(); +} + +fn drag(h: &mut Headless, from: Pos2, to: Pos2) { + press(h, from); + glide(h, from, to); +} + +fn hint(h: &Headless) -> Option { + h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::new("drag-photos-hint"))).map(|(_, text)| text) +} + +fn best(h: &Headless, id: PhotoId) -> bool { + h.app.session.catalog.photo(id).unwrap().analysis.unwrap().best +} + +#[test] +fn bursts_show_their_pick_first() { + let (h, [a, b, c, d, e, f]) = app(); + // a row per burst, its pick first + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.bottom() <= cell(&h, a).top() && cell(&h, e).top() >= two.bottom(), "each title above its photos"); + assert!(cell(&h, a).left() < cell(&h, b).left() && cell(&h, b).left() < cell(&h, c).left()); + assert!(cell(&h, d).left() < cell(&h, e).left()); + widget(&h, "burstPick:1"); + assert!(widget(&h, "burstPick:1").intersects(cell(&h, a)), "the pick is marked"); + // a photo culling never saw has no row; the drop places for a new burst and for none are there + assert!(!h.app.widgets.iter().any(|(w, _)| w == &format!("burstPhoto:{}", f.0))); + widget(&h, "burst:new"); + widget(&h, "burst:none"); +} + +#[test] +fn a_photo_dragged_to_the_front_becomes_the_pick() { + let (mut h, [a, b, c, ..]) = app(); + let to = pos2(cell(&h, a).left() + 4.0, cell(&h, a).center().y); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + assert_eq!(h.app.ui.dragging_photos, Some(vec![c.0])); + assert_eq!(hint(&h).as_deref(), Some("Make it the pick")); + release(&mut h, to); + assert!(h.app.ui.dragging_photos.is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![c, a, b]); + assert!(best(&h, c) && !best(&h, a)); + assert_eq!(h.app.session.catalog.photo(c).unwrap().flag, Flag::Pick, "culling's Pick follows the pick"); + // the panel shows the new order + h.step(); + assert!(cell(&h, c).left() < cell(&h, a).left()); + // one undo step + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c]); + assert!(best(&h, a)); +} + +#[test] +fn photos_move_between_bursts_and_bursts_merge() { + let (mut h, [a, b, c, d, e, _]) = app(); + let group = |h: &Headless, id: PhotoId| h.app.session.catalog.photo(id).unwrap().analysis.unwrap().group; + // e onto burst 1 between a and b; burst 2 is left with d alone: no burst any more + let to = pos2(cell(&h, b).left() + 4.0, cell(&h, b).center().y); + let from = cell(&h, e).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c]); + assert!(h.app.session.catalog.burst(2).is_empty() && group(&h, d).is_none()); + h.step(); + // d dragged from the grid onto burst 1's title goes last + let title = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", d.0)).center(); + drag(&mut h, from, title); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, title); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c, d]); + h.step(); + // b onto New Burst: a burst of its own, which c then joins by its title + let new = widget(&h, "burst:new").center(); + let from = cell(&h, b).center(); + drag(&mut h, from, new); + assert_eq!(hint(&h).as_deref(), Some("New burst")); + release(&mut h, new); + let g = group(&h, b).expect("a new burst"); + assert_eq!(h.app.session.catalog.burst(g), vec![b]); + h.step(); + let to = widget(&h, &format!("burst:{g}")).center(); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(g), vec![b, c]); + h.step(); + // e onto Not in a Burst + let out = widget(&h, "burst:none").center(); + let from = cell(&h, e).center(); + drag(&mut h, from, out); + assert_eq!(hint(&h).as_deref(), Some("Take out of its burst")); + release(&mut h, out); + assert!(group(&h, e).is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d]); + h.step(); + // a burst dragged by its title onto another merges into it + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("burst:{g}")).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c]); + assert!(h.app.session.catalog.burst(g).is_empty()); +} + +#[test] +fn a_photo_never_culled_is_refused() { + let (mut h, [_, _, _, _, _, f]) = app(); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", f.0)).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Run Assisted Culling on it first")); + let commits = h.app.session.commits(); + release(&mut h, to); + assert_eq!(h.app.session.commits(), commits); + let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); + assert!(toast.contains("Assisted Culling"), "{toast}"); +} From 507d4d344075f1705121ea767874886bf0c88610 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:04:54 +0200 Subject: [PATCH 009/247] LR-LIB-CULL: German strings and checklist for bursts arranged by hand Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 24 +++++++++++++++++++++++- docs/parity-checklist.md | 5 +++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 4d08cbd4a4..9a9f6eaed6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2345,5 +2345,27 @@ "Checking the GPU…": "GPU wird geprüft …", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", - "Checking the GPU for faces": "GPU für Gesichter wird geprüft" + "Checking the GPU for faces": "GPU für Gesichter wird geprüft", + "Bursts": "Serien", + "Burst": "Serie", + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand.": "Foto → Unterstützte Fotoauswahl… fasst ähnliche Aufnahmen zu Serien zusammen. Hier lassen sie sich von Hand korrigieren.", + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them.": "Ziehe ein Foto an seinen Platz: Das erste einer Serie ist ihre Auswahl. Ziehe ein Foto in eine andere Serie oder eine Serie an ihrem Titel auf eine andere, um sie zusammenzuführen.", + "New burst": "Neue Serie", + "Not in a burst": "In keiner Serie", + "Run Assisted Culling on it first": "Zuerst die unterstützte Fotoauswahl darauf anwenden", + "Run Assisted Culling on these photos first": "Zuerst die unterstützte Fotoauswahl auf diese Fotos anwenden", + "Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first": "Nur Fotos, die die unterstützte Fotoauswahl bewertet hat, können in einer Serie sein: Wende zuerst Foto → Unterstützte Fotoauswahl… darauf an", + "Merge into this burst": "Mit dieser Serie zusammenführen", + "Make it the pick": "Zur Auswahl machen", + "Put first: the first is the pick": "An den Anfang: Das erste ist die Auswahl", + "Move here": "Hierher verschieben", + "Move to this burst": "In diese Serie verschieben", + "Take out of its burst": "Aus der Serie nehmen", + "Regroup bursts I arranged by hand": "Von Hand geordnete Serien neu gruppieren", + "Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.": "Serien lassen sich unter Fenster → Serien per Ziehen korrigieren: Das erste Foto einer Serie ist ihre Auswahl, und eine erneute Fotoauswahl behält, was du geordnet hast.", + "Choose Burst Pick": "Auswahl der Serie wählen", + "Rearrange Burst": "Serie umordnen", + "Move to Burst": "In Serie verschieben", + "New Burst": "Neue Serie", + "Remove from Burst": "Aus Serie nehmen" } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 32488a4dda..5d8c4f26fb 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts can be stacked, best on top) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** patch (LR-LIB-CULL: bursts arranged by hand) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -116,7 +116,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs` | “Copy N” badge, stacked with the original, same albums, no XMP writes; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -797,6 +797,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-19 | patch | LR-LIB-CULL: bursts can be arranged by hand by drag and drop in Window ▸ Bursts; the first photo of a burst is its pick, and culling again keeps the arrangement (`photo.moveToBurst`, `panel.bursts`, `photo.analyze` `resetBursts`). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling's burst gap and similarity are adjustable (dialog, `photo.analyze` `burstGap` / `similarity`; #2275). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | From 663497fc71106584ca0d1fe974bbe36a805ea670 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:20:21 -0400 Subject: [PATCH 010/247] LR-PROF-CAMERACOLOR: negative channels render finite on CPU and GPU Raw decoding keeps negative channels since the previous commit. A noisy near-black frame through a saturating camera matrix, pushed 4 EV, renders finite with every slider at its ends, at every output depth with HDR on and off, and gives finite auto settings; the GPU matches the CPU on it across the equivalence cases. The camera-look lanes test gets its doc comment back, which the new tests had split from it. The previous commit's message says RENDER_CACHE_VERSION 66; it is 65. --- crates/engine/src/files.rs | 5 +-- crates/gpu/tests/equivalence.rs | 28 +++++++++++++++ crates/pipeline/src/tests.rs | 62 +++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 9c6f02852b..612e1d7458 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -1849,8 +1849,7 @@ pub(crate) mod tests { lightcraft_color::Mat3([[0.42, 0.548, 0.04], [0.246, 0.728, 0.033], [-0.247, 0.679, 0.447]]) } - /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the - /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. + /// Decoding passes finite values through, negative ones included, and zeroes NaN and infinities. #[test] fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); @@ -1884,6 +1883,8 @@ pub(crate) mod tests { assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); } + /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the + /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. #[test] fn camera_look_in_lanes_matches_pixel_by_pixel() { let data = (0..72 * 5 * 5).map(|i| [((i * 37) % 61) as f32 - 30.0, 0.6 + ((i * 11) % 13) as f32 / 13.0, 1.0]).collect(); diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/equivalence.rs index c877e3d9d8..aa37153ccc 100644 --- a/crates/gpu/tests/equivalence.rs +++ b/crates/gpu/tests/equivalence.rs @@ -877,3 +877,31 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { lightcraft_gpu::render(&src, &info, &s, &at(1000), Some(&after)).expect("gpu render"); assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } + +/// Raw decoding keeps negative channels (near-black sensor noise through a saturating camera matrix, a NIKON D780 +/// profile's): pushed and edited, the GPU renders them as the CPU does. +#[test] +fn negative_channels_match_cpu() { + if !gpu() { + return; + } + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let src = Arc::new(Rgb32f::from_fn(320, 240, |x, y| { + let g = 0.0005 * 1.02f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + })); + assert!(src.data.iter().flatten().any(|v| *v < 0.0)); + let info = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(320, 240); + for (name, edit) in cases() { + let mut s = DevelopSettings::default(); + edit(&mut s); + s.light.exposure += 4.0; + check(&format!("negatives +4 EV, {name}"), &src, &info, &s, &req); + } +} diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 910705497e..7b38f86e3e 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -790,3 +790,65 @@ fn sliver_crops_render_quickly_with_wide_stages_on() { assert!(r.image.width >= 1 && r.image.height >= 1, "{rect:?}"); } } + +/// A raw's linear Rec.2020 as decoding leaves it since it stopped clamping channels at zero: a dark ramp with +/// sensor noise through a saturating camera matrix (a NIKON D780 profile's), so near black many channels are +/// negative, and a few strongly out-of-gamut pixels. +fn negative_noise() -> Rgb32f { + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + // ±0.004 of noise per channel, a hash of the position + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + Rgb32f::from_fn(48, 32, |x, y| { + if (x + y) % 37 == 0 { + return [-0.05, 0.01, -0.02]; + } + let g = 0.0005 * 1.15f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + }) +} + +/// Negative channels from decoding reach every stage after it: every slider at its ends, at every output depth +/// (HDR on and off), and the auto settings give finite values only. +#[test] +fn negative_channels_render_finite_everywhere() { + use crate::{DeepSamples, OutputDepth, auto}; + let src = negative_noise(); + assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives"); + let info = SourceInfo { raw: true, ..Default::default() }; + let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| { + let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) }); + assert!(r.histogram.total > 0, "{what}"); + if let Some(DeepSamples::F32(v)) = r.deep.map(|d| d.samples) { + assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + } + }; + let mut pushed = DevelopSettings::default(); + pushed.light.exposure = 4.0; + pushed.light.shadows = 100.0; + pushed.light.blacks = 100.0; + for hdr in [false, true] { + let mut s = pushed.clone(); + s.hdr.enabled = hdr; + for depth in [OutputDepth::U8, OutputDepth::U16, OutputDepth::F32Linear, OutputDepth::F32Hdr] { + finite(&s, depth, &format!("pushed, hdr {hdr}")); + } + } + for c in controls::CONTROLS { + for v in [c.min, c.max] { + let mut s = pushed.clone(); + controls::set(&mut s, c.id, v); + finite(&s, OutputDepth::F32Linear, &format!("{} = {v}", c.id)); + } + } + let tone = auto::auto_tone(&src, &info, &pushed); + let t = [tone.exposure, tone.contrast, tone.highlights, tone.shadows, tone.whites, tone.blacks, tone.vibrance, tone.saturation]; + assert!(t.iter().all(|v| v.is_finite()), "auto tone {t:?}"); + assert!(auto::auto_bw_mix(&src, &info, &pushed).iter().all(|v| v.is_finite())); + let (t, k) = auto::auto_wb(&src, &info); + assert!(t.is_finite() && k.is_finite(), "auto WB {t} {k}"); + assert!(auto::scene_log_mean(&src, &info, &pushed).is_none_or(f64::is_finite)); +} From 31a243ca28f5903b74761c2de28139dea80bc286 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:13:51 +0200 Subject: [PATCH 011/247] LR-LIB-CULL: Stack each burst stacks hand-arranged bursts; the panel lists bursts hidden in stacks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - photo.analyze with stackGroups now stacks a burst arranged by hand too, in its order with its pick on top; before, only the bursts culling grouped were stacked. - Window ▸ Bursts lists a burst whose photos are all hidden in another burst's collapsed stack (anchored after that stack's top), so it can be arranged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 38 ++++++++++++++++++++++------- crates/engine/src/tests_bursts.rs | 6 +++++ crates/ui-egui/src/panels/bursts.rs | 10 +++++--- crates/ui-egui/src/tests_bursts.rs | 18 ++++++++++++++ 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 76725a968c..4f5b2c93b5 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -109,24 +109,44 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let mut stacks = 0; if stack_groups { // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked - // from its other photos when two or more remain, with the sharpest of those on top. + // from its other photos when two or more remain. A burst culling grouped has the sharpest + // of those on top; a burst arranged by hand keeps its order, its pick (place 0) on top. let index = s.catalog.stack_index(); let mut members: std::collections::BTreeMap> = Default::default(); - for (i, g) in group_of.iter().enumerate() { - if let (Some(g), Some(r)) = (g, rows.get(i)) - && !index.contains_key(&r.0) - && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) - { - members.entry(*g).or_default().push((r.0, r.2)); + let mut arranged: std::collections::BTreeMap> = Default::default(); + for (i, r) in rows.iter().enumerate() { + if index.contains_key(&r.0) || !s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) { + continue; + } + match kept[i] { + Some(k) => { + if let Some(g) = k.group { + arranged.entry(g).or_default().push((k.rank.unwrap_or(u32::MAX), r.0)); + } + } + None => { + if let Some(g) = group_of[i] { + members.entry(g).or_default().push((r.0, r.2)); + } + } } } + let mut orders: Vec> = Vec::new(); for group in members.values() { let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { continue; }; - let photos: Vec = group.iter().map(|m| m.0).collect(); + let mut photos = vec![top.0]; + photos.extend(group.iter().map(|m| m.0).filter(|p| *p != top.0)); + orders.push(photos); + } + for group in arranged.values_mut() { + group.sort(); + orders.push(group.iter().map(|m| m.1).collect()); + } + for photos in orders { if photos.len() >= 2 - && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + && let Some(op) = s.catalog.group_ops(photos[0], &photos, true) { ops.push(op); stacks += 1; diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs index f402fbffe8..ff7ba98c69 100644 --- a/crates/engine/src/tests_bursts.rs +++ b/crates/engine/src/tests_bursts.rs @@ -239,6 +239,12 @@ fn culling_again_keeps_bursts_arranged_by_hand() { let g2_again = an(&s, second[0]).group.unwrap(); assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); assert_eq!(s.catalog.burst(g2_again), second); + // stacking each burst stacks the one arranged by hand too, in its order, the pick on top + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 2, "{r}"); + let st = s.catalog.stack_of(softest).expect("the hand-arranged burst is stacked"); + assert_eq!(st.photos, vec![first[2], first[0], first[1]], "in the order set by hand, its pick on top"); + assert_eq!(s.catalog.stack_of(second[0]).map(|st| st.top()), Some(second[0]), "an automatic burst: the sharpest on top"); // asked to regroup, culling forgets the order set by hand s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); let g = an(&s, first[0]).group.unwrap(); diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index 8a6d17fd9d..f03240e104 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -40,13 +40,17 @@ fn bursts(app: &mut LightcraftApp) -> Shown { return b.clone(); } let cat = &app.session.catalog; - let mut scope: HashSet = ids.iter().copied().collect(); + // each photo in view, then the hidden members of its stack: a burst whose photos are all + // hidden in another burst's collapsed stack is listed too, after that stack's top + let mut anchors: Vec = Vec::with_capacity(ids.len()); for id in ids.iter() { + anchors.push(*id); if let Some(st) = cat.stack_of(*id) { - scope.extend(st.photos.iter().copied()); + anchors.extend(st.photos.iter().copied().filter(|p| p != id)); } } - let b: Shown = Arc::new(cat.bursts_among(&ids, Some(&scope))); + let scope: HashSet = anchors.iter().copied().collect(); + let b: Shown = Arc::new(cat.bursts_among(&anchors, Some(&scope))); app.caches.bursts = Some((generation, b.clone())); b } diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index e7ce2858ba..f9e0d0c64d 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -115,6 +115,24 @@ fn bursts_show_their_pick_first() { widget(&h, "burst:none"); } +/// A burst whose photos are all hidden in a collapsed stack of another burst's photo is still +/// listed, so it can be arranged. +#[test] +fn a_burst_hidden_in_another_bursts_stack_is_listed() { + let (mut h, [a, _, _, d, e, _]) = app(); + h.app.session.selection.ids = vec![a, d, e]; + h.app.session.selection.active = Some(a); + h.app.session.execute("stack.group", &json!({"collapsed": true})).unwrap(); + for _ in 0..4 { + h.step(); + } + let visible = h.app.session.visible_cloned(); + assert!(visible.contains(&a) && !visible.contains(&d) && !visible.contains(&e), "d and e are hidden under a: {visible:?}"); + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.top() < two.top(), "listed after the burst of the stack's top"); + assert!(cell(&h, d).top() >= two.bottom() && cell(&h, e).top() >= two.bottom(), "with its photos"); +} + #[test] fn a_photo_dragged_to_the_front_becomes_the_pick() { let (mut h, [a, b, c, ..]) = app(); From b1cd4b923aed6f16283af0e3eab2c73afa941a74 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:33:37 +0200 Subject: [PATCH 012/247] LR-LIB-CULL: a photo dragged to the front takes the Pick even over a Reject; a burst dragged by its title takes all its photos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - photo.moveToBurst: when the Pick moves to a new first photo, that photo takes it whatever its flag; it was chosen by hand, so a Reject (from Reject below, say) no longer leaves the burst without a pick flag. - Window ▸ Bursts: dragging a burst by its title drags every photo of the burst, not only those in view, so a merge leaves none behind; the "Merge into this burst" label compares with the whole burst too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cull.rs | 5 ++--- crates/engine/src/tests_bursts.rs | 6 ++++++ crates/ui-egui/src/panels/bursts.rs | 8 ++++++-- crates/ui-egui/src/tests_bursts.rs | 20 ++++++++++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 4f5b2c93b5..13687ac935 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -286,9 +286,8 @@ fn move_to_burst(s: &mut Session, p: &Value) -> Result { if !is_pick(old_pick) { flags.insert(old_pick, Flag::None); } - if let Some(n) = new_pick - && flag(s, n) == Flag::None - { + // the new pick was chosen by hand: it takes the Pick even over a Reject + if let Some(n) = new_pick { flags.insert(n, Flag::Pick); } } diff --git a/crates/engine/src/tests_bursts.rs b/crates/engine/src/tests_bursts.rs index ff7ba98c69..04f2706624 100644 --- a/crates/engine/src/tests_bursts.rs +++ b/crates/engine/src/tests_bursts.rs @@ -72,6 +72,12 @@ fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { assert_eq!(s.catalog.burst(1), vec![a, c, b]); assert!(an(&s, a).best); assert_eq!(flag(&s, a), Flag::Pick); + // a rejected shot dragged to the front was chosen by hand: it takes the Pick + s.catalog.apply(Op::SetFlag { id: b, flag: Flag::Reject }).unwrap(); + mv(&mut s, json!({"ids": [b.0], "index": 0})); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Pick, Flag::None)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Reject, Flag::Pick)); // placing a photo where it already is changes nothing and makes no undo step let commits = s.commits(); let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index f03240e104..060b8cda7f 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -98,8 +98,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if resp.hovered() && dragged.is_none() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } + // the whole burst, also its photos out of view if resp.drag_started() { - app.ui.dragging_photos = Some(photos.iter().map(|p| p.0).collect()); + app.ui.dragging_photos = Some(app.session.catalog.burst(*g).iter().map(|p| p.0).collect()); } if pointer.is_some_and(|p| title.contains(p)) { target = Some((Target::Burst(*g, n), None)); @@ -246,7 +247,10 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); // the place once the dragged photos have left theirs let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); - let whole = shown.iter().any(|(n, m)| *n != g && m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let whole = shown.iter().any(|(n, _)| { + let all = app.session.catalog.burst(*n); + *n != g && all.len() > 1 && all.len() == ids.len() && all.iter().all(|p| ids.contains(p)) + }); let hint = if whole { "Merge into this burst" } else if index == 0 && slot < members.len() { diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index f9e0d0c64d..03f44f57a3 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -223,3 +223,23 @@ fn a_photo_never_culled_is_refused() { let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); assert!(toast.contains("Assisted Culling"), "{toast}"); } + +/// A burst dragged by its title takes all its photos along, also those the view leaves out. +#[test] +fn a_burst_dragged_by_its_title_takes_its_photos_out_of_view() { + let (mut h, [a, b, c, d, e, _]) = app(); + // only the picks are in view: e (of burst 2) is left out + let r = h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + assert!(r.is_object(), "{r}"); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&e), "e is out of view"); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, "burst:2").center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c, d, e], "e came along"); + assert!(h.app.session.catalog.burst(2).is_empty()); +} From a2dd47d682ee55fbf6786b94b365d532114caab9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:44:03 +0200 Subject: [PATCH 013/247] LR-LIB-CULL: Bursts panel drops land in the whole burst; one burst index per catalog change - A photo dropped after a shown photo of a burst goes right after it in the whole burst, before the members the view leaves out; a drop on the title or after the last photo still goes last. - The burst index a drag compares with (the title drag, the merge label) is built once per view generation and cached, not once per burst on every frame of the drag. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 3 ++ crates/ui-egui/src/panels/bursts.rs | 59 +++++++++++++++++++++++------ crates/ui-egui/src/tests_bursts.rs | 18 +++++++++ 3 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8cfc5d8a95..4ee5ce4ae0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1637,6 +1637,9 @@ pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, /// The Bursts panel's bursts, by the view's generation. bursts: Option<(u64, panels::bursts::Shown)>, + /// Every burst of the library (pick first), by the view's generation: what a drag in the + /// Bursts panel compares with, so a frame of the drag builds no index of its own. + burst_index: Option<(u64, panels::bursts::All)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index 060b8cda7f..de5092fac5 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -10,7 +10,7 @@ //! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, //! `burst:new`, `burst:none`. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; @@ -55,10 +55,31 @@ fn bursts(app: &mut LightcraftApp) -> Shown { b } +/// Every burst of the library: its number → its photos, pick first. +pub type All = Arc>>; + +/// Every burst of the library, built once per view generation (it follows every catalog change). +fn all_bursts(app: &mut LightcraftApp) -> All { + let (generation, _) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.burst_index + && *g == generation + { + return b.clone(); + } + let b: All = Arc::new(app.session.catalog.burst_index()); + app.caches.burst_index = Some((generation, b.clone())); + b +} + +/// A [`Target::Burst`] slot after every photo of the burst: a drop on its title or after its +/// last photo. +const LAST: usize = usize::MAX; + /// Where a drop under the pointer would put the dragged photos. #[derive(Clone, Copy, PartialEq, Debug)] enum Target { - /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included). + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included; + /// [`LAST`]: after every photo of the burst, those out of view too). Burst(u32, usize), New, Nowhere, @@ -100,10 +121,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // the whole burst, also its photos out of view if resp.drag_started() { - app.ui.dragging_photos = Some(app.session.catalog.burst(*g).iter().map(|p| p.0).collect()); + app.ui.dragging_photos = Some(all_bursts(app).get(g).map(|m| m.iter().map(|p| p.0).collect()).unwrap_or_default()); } if pointer.is_some_and(|p| title.contains(p)) { - target = Some((Target::Burst(*g, n), None)); + target = Some((Target::Burst(*g, LAST), None)); } // the photos, in rows let rows = n.div_ceil(cols); @@ -132,7 +153,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { // the room after the last photo: last let last = cell_at(n.saturating_sub(1)); - target = Some((Target::Burst(*g, n), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + target = Some((Target::Burst(*g, LAST), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); } if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); @@ -244,13 +265,27 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho } let (params, hint) = match tgt { Target::Burst(g, slot) => { + let all = all_bursts(app); let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); - // the place once the dragged photos have left theirs - let index = members.iter().take(slot).filter(|m| !ids.contains(m)).count(); - let whole = shown.iter().any(|(n, _)| { - let all = app.session.catalog.burst(*n); - *n != g && all.len() > 1 && all.len() == ids.len() && all.iter().all(|p| ids.contains(p)) - }); + // the place in the whole burst (members the view leaves out included) once the dragged + // photos have left theirs: right after the last shown member before the slot + let rest: Vec = all.get(&g).map(|m| m.iter().copied().filter(|p| !ids.contains(p)).collect()).unwrap_or_default(); + let index = if slot == LAST { + rest.len() + } else { + members[..slot.min(members.len())] + .iter() + .rev() + .find(|m| !ids.contains(m)) + .and_then(|m| rest.iter().position(|p| p == m)) + .map_or(0, |i| i + 1) + }; + // the dragged photos are a whole other burst (one lookup: the first one's burst) + let from = ids.first().and_then(|id| app.session.catalog.photo(*id)).and_then(|p| p.analysis).and_then(|a| a.group); + let whole = from + .filter(|n| *n != g) + .and_then(|n| all.get(&n)) + .is_some_and(|m| m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); let hint = if whole { "Merge into this burst" } else if index == 0 && slot < members.len() { @@ -260,7 +295,7 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho } else { "Move to this burst" }; - let index = if slot >= members.len() { Value::Null } else { json!(index) }; + let index = if index >= rest.len() { Value::Null } else { json!(index) }; (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) } Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index 03f44f57a3..e6618152b5 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -243,3 +243,21 @@ fn a_burst_dragged_by_its_title_takes_its_photos_out_of_view() { assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c, d, e], "e came along"); assert!(h.app.session.catalog.burst(2).is_empty()); } + +/// A photo dropped after a shown member lands right after it in the whole burst, before the +/// members the view leaves out, not after them. +#[test] +fn a_drop_after_a_shown_photo_goes_before_the_photos_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // only the picks are in view: burst 1 shows a, its b and c are left out + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + let to = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a, before b and c"); +} From e1ab84a94503bc4b1bf42b4d7151d861e4dc8599 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:57:23 +0200 Subject: [PATCH 014/247] LR-LIB-CULL: a drop in the Bursts panel keeps its side of the photo it is on With a member out of view between two shown photos, a drop on the left half of the second one now goes right before it, and a drop on the right half of the first right after that one; they used to land in the same place. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/bursts.rs | 22 ++++++++++++++-------- crates/ui-egui/src/tests_bursts.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs index de5092fac5..305271d492 100644 --- a/crates/ui-egui/src/panels/bursts.rs +++ b/crates/ui-egui/src/panels/bursts.rs @@ -79,8 +79,9 @@ const LAST: usize = usize::MAX; #[derive(Clone, Copy, PartialEq, Debug)] enum Target { /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included; - /// [`LAST`]: after every photo of the burst, those out of view too). - Burst(u32, usize), + /// [`LAST`]: after every photo of the burst, those out of view too), dropped on the left half + /// of the photo at `slot` (`true`: right before it) or the right half of the one before. + Burst(u32, usize, bool), New, Nowhere, } @@ -124,7 +125,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.dragging_photos = Some(all_bursts(app).get(g).map(|m| m.iter().map(|p| p.0).collect()).unwrap_or_default()); } if pointer.is_some_and(|p| title.contains(p)) { - target = Some((Target::Burst(*g, LAST), None)); + target = Some((Target::Burst(*g, LAST, false), None)); } // the photos, in rows let rows = n.div_ceil(cols); @@ -144,7 +145,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { let slot = if p.x < r.center().x { i } else { i + 1 }; let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; - target = Some((Target::Burst(*g, slot), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + target = Some((Target::Burst(*g, slot, slot == i), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); } } if target.is_none() @@ -153,9 +154,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { { // the room after the last photo: last let last = cell_at(n.saturating_sub(1)); - target = Some((Target::Burst(*g, LAST), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); + target = Some((Target::Burst(*g, LAST, false), Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))))); } - if dragged.is_some() && matches!(target, Some((Target::Burst(tg, _), _)) if tg == *g) { + if dragged.is_some() && matches!(target, Some((Target::Burst(tg, ..), _)) if tg == *g) { ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); } } @@ -264,14 +265,19 @@ fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[Pho return; } let (params, hint) = match tgt { - Target::Burst(g, slot) => { + Target::Burst(g, slot, before) => { let all = all_bursts(app); let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); // the place in the whole burst (members the view leaves out included) once the dragged - // photos have left theirs: right after the last shown member before the slot + // photos have left theirs: right before the photo dropped on, or right after the one + // whose right half it was (members out of view between them stay on their side) let rest: Vec = all.get(&g).map(|m| m.iter().copied().filter(|p| !ids.contains(p)).collect()).unwrap_or_default(); + let at = |m: &PhotoId| rest.iter().position(|p| p == m); + let next = members.get(slot..).and_then(|after| after.iter().find(|m| !ids.contains(m))); let index = if slot == LAST { rest.len() + } else if let Some(i) = next.filter(|_| before).and_then(at) { + i } else { members[..slot.min(members.len())] .iter() diff --git a/crates/ui-egui/src/tests_bursts.rs b/crates/ui-egui/src/tests_bursts.rs index e6618152b5..429ce1eee7 100644 --- a/crates/ui-egui/src/tests_bursts.rs +++ b/crates/ui-egui/src/tests_bursts.rs @@ -261,3 +261,30 @@ fn a_drop_after_a_shown_photo_goes_before_the_photos_out_of_view() { release(&mut h, to); assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a, before b and c"); } + +/// Between two shown photos with one out of view between them, a drop on the left half of the +/// second goes right before it, a drop on the right half of the first right after that one. +#[test] +fn a_drop_keeps_its_side_of_a_photo_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // b is left out: burst 1 shows a, c + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "fileName", "op": "notContains", "value": "b.jpg"}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&b)); + let before_c = pos2(cell(&h, c).left() + 4.0, cell(&h, c).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, before_c); + release(&mut h, before_c); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, d, c], "right before c"); + h.app.run("edit.undo", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + let after_a = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, after_a); + release(&mut h, after_a); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a"); +} From 7eece8e81e904d53602257f8874a1bfed19e0b5c Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:51:55 +0200 Subject: [PATCH 015/247] LR-BEHAV-LOCALIZE: Hebrew file and folder names get glyphs (#1915) Hebrew folder and file names drew as boxes: no face in the UI fallback chain (Inter, egui's default faces, the craft-fonts faces) has Hebrew letters. theme::font_definitions already falls back on every craft-fonts face of a non-CJK script, so the glyphs come from Noto Sans Hebrew, added to craft-fonts in storytold/craft-fonts#12: - Pin craft-fonts to 1466a88, the head of that PR (release and FreeBSD workflows, flake.nix/flake.lock, local packaging scripts). Re-pin to its merge commit once it lands. - CRAFT_FONTS_REQUIRED rejects a font input without Noto Sans Hebrew Regular, so a release can't ship boxes with an older pin. - The web build embeds Noto Sans Hebrew Regular (~65 KiB) next to Noto Sans Thai, for Hebrew file and folder names in every UI language. - The Thai folder-name test becomes a helper; a Hebrew test (letters, final forms, maqaf, geresh, gershayim, niqqud) runs it through every UI family, and the engine checks that the shipped face draws Hebrew and the shekel sign. They fail with a craft-fonts input without Hebrew and skip without CRAFT_FONTS_DIR. The egui check leaves out the shekel sign: Inter and Hack draw it before the Hebrew face, and in monospace Hack also holds the replacement glyph, where egui 0.36's has_glyph answers false (resolve_face(c) == replacement face) although the sign draws. Reading direction, measured on the laid-out galley: egui 0.36 shapes each run of one face with harfrust, which orders a Hebrew run right to left, so each word reads correctly. Nothing reorders the runs, and the space between words comes from Inter, so a multi-word name shows its words in logical order, left to right (documented in docs/localization-parity.md and docs/web.md). Part of #1915. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/freebsd.yml | 2 +- .github/workflows/release.yml | 2 +- NOTICE | 6 +++--- assets/ATTRIBUTION.md | 2 +- crates/engine/build.rs | 12 +++++++++--- crates/engine/src/fonts.rs | 3 ++- crates/ui-egui/src/theme.rs | 31 +++++++++++++++++++++++-------- docs/localization-parity.md | 6 +++++- docs/releasing.md | 7 ++++--- docs/web.md | 6 ++++-- flake.lock | 8 ++++---- flake.nix | 2 +- packaging/fonts.sh | 2 +- packaging/windows/fonts.ps1 | 2 +- 14 files changed, 60 insertions(+), 31 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index d85332b235..62c14700dd 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -33,4 +33,4 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: require-craft-fonts: true - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc # Hebrew: repin once storytold/craft-fonts#12 is on main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b8fb013261..3e8bd635fb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: with: app-name: lightcraft app-title: LightCraft - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc # Hebrew: repin once storytold/craft-fonts#12 is on main web-craft-fonts: true version: ${{ inputs.version }} secrets: diff --git a/NOTICE b/NOTICE index 8b16eeba0f..2f1b2d04c5 100644 --- a/NOTICE +++ b/NOTICE @@ -51,9 +51,9 @@ no darktable, RawSpeed, LibRaw or other GPL decoder/runtime code is included. Builds made with craft-fonts (the optional CRAFT_FONTS_DIR build input; all official releases) also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md -(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic and Noto Sans -Thai), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic Regular and Noto -Sans Thai Regular, and loads Noto Sans CJK SC separately. Release packages include each font's +(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans +Thai and Noto Sans Hebrew), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic +Regular, Noto Sans Thai Regular and Noto Sans Hebrew Regular, and loads Noto Sans CJK SC separately. Release packages include each font's licence as OFL-.txt; Windows installers include their texts in FONT-LICENCES.txt. Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 30eea5654c..2cbc261b6c 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -29,7 +29,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `docs/images/*-blue-marble.jpg`, `docs/images/grid-pd.jpg` | "The Blue Marble" (AS17-148-22727) | NASA, Apollo 17 crew (1972) | https://commons.wikimedia.org/wiki/File:The_Earth_seen_from_Apollo_17.jpg | Public domain (NASA) | 2026-09-30 | developed in LightCraft; shown inside app screenshots | | `docs/images/*.jpg` (UI) | LightCraft application screenshots | LightCraft contributors | original work (captured with `docs/showcase/`) | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `docs/brand/` (artcraft-logo and artcraft-mark, SVG and PNG) | ArtCraft wordmark and mark | ArtCraft Team | original work (https://getartcraft.com/) | ArtCraft trademark, see `docs/brand/LICENSE-brand.txt` (not open source) | 2026-10-01 | none | -| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular | The Noto Project Authors (Arabic and Thai); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular and Noto Sans Thai Regular and ships Noto Sans CJK SC Regular as a separate font file | +| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular, Noto Sans Hebrew (Regular, Bold) | The Noto Project Authors (Arabic, Thai and Hebrew); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Hebrew Regular and ships Noto Sans CJK SC Regular as a separate font file | | `crates/ui-egui/locales/uk.json`, `crates/ui-egui/locales/uk-formats.json` | Ukrainian interface catalogs | @dmatviichuk with Codex; PhotoCraft, FilmCraft and VectorCraft translation contributors for reused labels | original translations from English source; 337 initial English-key matches reviewed from [PhotoCraft 69c41f3](https://github.com/storytold/photocraft/blob/69c41f3523e147eb215da8c7b4c29b18b35d1c63/crates/ui-egui/src/i18n/uk.tsv), [FilmCraft 4854c27](https://github.com/storytold/filmcraft/blob/4854c277536fe8118257362304b6a7d82d8e704b/crates/ui-egui/src/i18n/uk.tsv), [VectorCraft 4b44265](https://github.com/storytold/vectorcraft/blob/4b44265965fdd6ffedfd6182a892c1a6c360d344/crates/ui-egui/src/i18n/uk.tsv) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-09 | adapted to LightCraft photo-development context, completed catalogs, reviewed spelling and placeholders | | `crates/ui-egui/locales/cs.json`, `crates/ui-egui/locales/cs-formats.json` | Czech interface catalogs | @Losminek with AI assistance (Codex) | original work: translations of English source phrases, reviewed against the app UI conventions; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-11 | catalog coverage, Czech dates and count-neutral wording; independent scope/terminology review; native-speaker proofreading pending | | `crates/ui-egui/locales/it.json`, `crates/ui-egui/locales/it-formats.json` | Italian interface catalogs | @GabrielePecchioli with Claude Code; PhotoCraft, VectorCraft, PdfCraft and WordCraft translation contributors for reused labels | original translations from English source; 410 initial English-key matches reviewed from [PhotoCraft da3da09](https://github.com/storytold/photocraft/blob/da3da0942c14c1159f40c652afcf33584332c733/crates/ui-egui/src/i18n/it.tsv), [VectorCraft 5432821](https://github.com/storytold/vectorcraft/blob/543282148007bcb5633c493a5374cd26b0339c8d/crates/ui-egui/src/i18n/it.tsv), [PdfCraft e8e275c](https://github.com/storytold/pdfcraft/blob/e8e275cbd40ccd0dc6b56f82b16a575571043702/crates/ui-egui/src/i18n/it.tsv) and the Italian WordCraft catalog ([storytold/wordcraft#598](https://github.com/storytold/wordcraft/pull/598)); 46 of them retranslated where the sibling's meaning didn't fit a photo app | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-12 | adapted to LightCraft photo-development context, count-neutral labels for Italian plural agreement, reviewed placeholders | diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 7f5aa77776..f55c0a9ef0 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -3,8 +3,9 @@ //! Recipe from craft-fonts' docs/integration.md; craft-fonts is never a Cargo dependency, and this //! script only reads a local directory (no network). //! -//! wasm32 embeds BIZ UDPGothic Regular (~4.5 MB) and Noto Sans Thai (~214 KiB) and Noto Sans Georgian, to keep the -//! `.wasm` within the web size budget (Cloudflare serves at most 25 MiB per file); the export +//! wasm32 embeds BIZ UDPGothic Regular (~4.5 MB), Noto Sans Thai (~214 KiB), Noto Sans Georgian and +//! Noto Sans Hebrew Regular (~65 KiB, for Hebrew file and folder names), to keep the `.wasm` within the +//! web size budget (Cloudflare serves at most 25 MiB per file); the export //! watermark falls back to it there. Native builds embed every font. use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -70,6 +71,7 @@ fn craft_fonts(dir: &Path, required: bool) -> Result { let mut has_japanese_ui = false; let mut has_chinese_ui = false; let mut has_thai_ui = false; + let mut has_hebrew_ui = false; for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); let [family, style, file, scripts, ..] = f.as_slice() else { @@ -78,7 +80,8 @@ fn craft_fonts(dir: &Path, required: bool) -> Result { has_japanese_ui |= (*family, *style) == ("BIZ UDPGothic", "Regular"); has_chinese_ui |= (*family, *style) == ("Noto Sans CJK SC", "Regular") && scripts.split(',').any(|script| script.trim() == "Hans"); has_thai_ui |= (*family, *style) == ("Noto Sans Thai", "Regular") && scripts.split(',').any(|script| script.trim() == "Thai"); - if wasm && !matches!((*family, *style), ("BIZ UDPGothic" | "Noto Sans Thai" | "Noto Sans Georgian", "Regular")) { + has_hebrew_ui |= (*family, *style) == ("Noto Sans Hebrew", "Regular") && scripts.split(',').any(|script| script.trim() == "Hebr"); + if wasm && !matches!((*family, *style), ("BIZ UDPGothic" | "Noto Sans Thai" | "Noto Sans Georgian" | "Noto Sans Hebrew", "Regular")) { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; @@ -94,6 +97,9 @@ fn craft_fonts(dir: &Path, required: bool) -> Result { if required && !has_thai_ui { return Err("required Thai UI face Noto Sans Thai Regular (Thai) is missing from fonts/manifest.txt".into()); } + if required && !has_hebrew_ui { + return Err("required Hebrew UI face Noto Sans Hebrew Regular (Hebr) is missing from fonts/manifest.txt".into()); + } if required && !has_japanese_ui { return Err("required Japanese UI face BIZ UDPGothic Regular is missing from fonts/manifest.txt".into()); } diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index db9e658d07..ae23ba7746 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -105,7 +105,8 @@ mod tests { assert!(japanese(CRAFT_FONTS).next().is_some(), "craft-fonts carries Japanese faces"); // Every script face that ships is a UI fallback, and has the glyphs of its script (#736). use ab_glyph::Font; - for (script, text) in [("Thai", "ภาพถ่ายสวัสดี๑๒๓"), ("Arab", "صورة"), ("Geor", "ფოტო")] { + for (script, text) in [("Thai", "ภาพถ่ายสวัสดี๑๒๓"), ("Arab", "صورة"), ("Geor", "ფოტო"), ("Hebr", "תמונות טנזניה ךםןףץ־׳״ָׁ₪")] + { let Some(face) = ui_fallback(CRAFT_FONTS, "Latn", "Regular").into_iter().find(|f| f.covers(script)) else { continue }; let font = ab_glyph::FontRef::try_from_slice(face.bytes).expect("parses"); assert!(text.chars().all(|c| font.glyph_id(c).0 != 0), "{} draws {script}", face.family); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ee987d1d..4b401b5bee 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -470,20 +470,35 @@ mod tests { /// Exercise the Thai characters of the reported folder name through every egui family. #[test] fn thai_folder_name_has_glyphs_in_every_ui_family() { + folder_name_has_glyphs_in_every_ui_family("Thai", "Studio34 ถ่ายภาพงานแต่งงาน"); + } + + /// #1915: Hebrew folder names drew as boxes. The release input carries Noto Sans Hebrew, and + /// every egui family reaches it (letters, final forms, maqaf, geresh and gershayim, niqqud). + /// No ₪ here: Inter and Hack draw it before the Hebrew face, and Hack also holds monospace's + /// replacement glyph, where `has_glyph` answers false (the engine test checks ₪ in the face). + #[test] + fn hebrew_folder_name_has_glyphs_in_every_ui_family() { + folder_name_has_glyphs_in_every_ui_family("Hebr", "תמונות טנזניה 2024 ךםןףץ ־ ׳ ״ שָׁלוֹם"); + } + + /// The craft-fonts face for `script` is in every UI family and draws the non-ASCII + /// characters of `name` in each of them. + fn folder_name_has_glyphs_in_every_ui_family(script: &str, name: &str) { if lightcraft_engine::CRAFT_FONTS.is_empty() { lightcraft_testkit::skip!(Fonts, "built without CRAFT_FONTS_DIR: no craft-fonts to check"); return; } - let thai = lightcraft_engine::CRAFT_FONTS.iter().find(|f| f.covers("Thai")).expect("font input includes Thai"); + let face = lightcraft_engine::CRAFT_FONTS.iter().find(|f| f.covers(script)).unwrap_or_else(|| panic!("font input includes {script}")); set_language(Locale::En); let definitions = font_definitions(lightcraft_engine::CRAFT_FONTS); - let name = craft_font_name(thai); - assert!(definitions.font_data.contains_key(&name)); + let face_name = craft_font_name(face); + assert!(definitions.font_data.contains_key(&face_name)); // (The strong family has the face's heavier twin instead when it is a variable font.) - let strong = format!("{name} strong"); + let strong = format!("{face_name} strong"); for family in [FontFamily::Proportional, FontFamily::Name(FONT_SEMIBOLD.into()), FontFamily::Monospace] { let names = definitions.families.get(&family).expect("UI font family"); - assert!(names.contains(&name) || (family == semibold_family() && names.contains(&strong)), "{family:?} falls back on {name}"); + assert!(names.contains(&face_name) || (family == semibold_family() && names.contains(&strong)), "{family:?} falls back on {face_name}"); } let ctx = egui::Context::default(); ctx.set_fonts(definitions); @@ -492,10 +507,10 @@ mod tests { ctx.fonts_mut(|fonts| { for family in [FontFamily::Proportional, FontFamily::Name(FONT_SEMIBOLD.into()), FontFamily::Monospace] { let id = FontId::new(13.0, family); - // Check the Thai portion; egui 0.36's has_glyph reports false for characters + // Check the non-ASCII portion; egui 0.36's has_glyph reports false for characters // in the replacement glyph's own face (including normal monospace Latin). - for ch in "Studio34 ถ่ายภาพงานแต่งงาน".chars().filter(|ch| !ch.is_ascii()) { - assert!(fonts.has_glyph(&id, ch), "{id:?} has {ch}"); + for ch in name.chars().filter(|ch| !ch.is_ascii()) { + assert!(fonts.has_glyph(&id, ch), "{id:?} has {ch} (U+{:04X})", ch as u32); } } }); diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 41669e4b78..64c4a2b31a 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -35,7 +35,11 @@ go beyond the target. Script support is checked against the code: `language_table!` in `crates/ui-egui/src/i18n.rs` lists scripts `Latn`, `Cyrl`, `Hans`, `Hant`, `Jpan` only. The UI is egui, which has no bidirectional layout and no complex-script shaping, so Arabic (RTL, joining) and Devanagari (conjuncts, reordering) cannot -render correctly today. +render correctly today. File and folder names in other scripts get glyphs from the craft-fonts faces after +Inter (Arabic, Thai, Hebrew, CJK). egui 0.36 shapes each run of one face with harfrust, so a Hebrew +word reads right to left, but nothing reorders the runs: the space between words comes from Inter, +so the words of a right-to-left name, and mixed Hebrew and Latin text, stay in logical order, left +to right (#1915). Native-speaker review: no catalog has had a formal review. Several catalogs have edits from community contributors whose commits only touch that language (ja, zh-hans, zh-hant, fr, de, ru, uk, pt-br); diff --git a/docs/releasing.md b/docs/releasing.md index 914a7ad840..75cb9646f4 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -61,12 +61,13 @@ shipped language needs: a stale pin still builds, it just ships tofu (issue #319 from before Noto Sans CJK SC, so Simplified Chinese had no glyphs). Before a release, check the pin against craft-fonts' `fonts/manifest.txt` and run `CRAFT_FONTS_DIR=../craft-fonts cargo test -p lightcraft-ui-egui i18n`, whose glyph-coverage test checks the characters in available faces. `CRAFT_FONTS_REQUIRED=1` now also makes -the native build fail if the pinned manifest lacks Noto Sans CJK SC Regular (`Hans`) or BIZ UDPGothic Regular; -the web build requires BIZ UDPGothic Regular and packages Noto Sans CJK SC as a separate asset. +the native build fail if the pinned manifest lacks Noto Sans CJK SC Regular (`Hans`), BIZ UDPGothic Regular, +Noto Sans Thai Regular (`Thai`) or Noto Sans Hebrew Regular (`Hebr`); the web build requires all but the +Chinese face and packages Noto Sans CJK SC as a separate asset. Local macOS, Linux and Windows packaging scripts automatically use the sibling `../craft-fonts` checkout. If it is absent, they clone it at revision -`3d9ab3a132ed0eff457e424226a435a901da30d3` (keep the pins in `packaging/fonts.sh` and +`1466a883ae5ac0a7d76cfe7f9d56fe0240acb255` (keep the pins in `packaging/fonts.sh` and `packaging/windows/fonts.ps1` in sync with the release workflow). Existing checkouts are left untouched. Set `CRAFT_FONTS_DIR` to use another checkout; relative paths resolve from the workspace root. The script requires the Chinese and Japanese diff --git a/docs/web.md b/docs/web.md index 98d0dd91c4..de7b296c4f 100644 --- a/docs/web.md +++ b/docs/web.md @@ -55,8 +55,10 @@ gzip size (5.25 MB). `wasm-opt -Oz`, when installed, shrinks it further. **Fonts.** The browser has no system fonts to fall back on, so CJK text comes from [craft-fonts](https://github.com/storytold/craft-fonts), the optional `CRAFT_FONTS_DIR` build input (`CRAFT_FONTS_DIR=../craft-fonts cargo xtask web`; release builds always set it). On wasm32 -`crates/engine/build.rs` embeds BIZ UDPGothic Regular (UI and watermark fallback) and Noto Sans -Thai Regular (~214 KiB, for Thai file and folder names in every UI language). The web +`crates/engine/build.rs` embeds BIZ UDPGothic Regular (UI and watermark fallback), Noto Sans +Thai Regular (~214 KiB) and Noto Sans Hebrew Regular (~65 KiB), for Thai and Hebrew file and folder +names in every UI language (a Hebrew name's words stay in logical order, see +[localization-parity](localization-parity.md)). The web bundle also ships Noto Sans CJK SC Regular as `lightcraft_zh_hans.otf` and loads it before the UI starts. Keeping the 16 MB Chinese face separate leaves the module under Cloudflare's 25 MiB per-file limit (the older Japanese-only module measured 21.8 MB). Without `CRAFT_FONTS_DIR`, the diff --git a/flake.lock b/flake.lock index a9953fd126..7252a4ebb4 100644 --- a/flake.lock +++ b/flake.lock @@ -3,17 +3,17 @@ "craft-fonts": { "flake": false, "locked": { - "lastModified": 1791722036, - "narHash": "sha256-mNnDzBcOp1X10dzmiW0iBAkb74QjuzMO4slWudxXCTE=", + "lastModified": 1791798042, + "narHash": "sha256-kFLq0Lj0hAp0/7XhlzL1Dc9lV7/SiIXm3vN1+39X2Uk=", "owner": "storytold", "repo": "craft-fonts", - "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3", + "rev": "1466a883ae5ac0a7d76cfe7f9d56fe0240acb255", "type": "github" }, "original": { "owner": "storytold", "repo": "craft-fonts", - "rev": "3d9ab3a132ed0eff457e424226a435a901da30d3", + "rev": "1466a883ae5ac0a7d76cfe7f9d56fe0240acb255", "type": "github" } }, diff --git a/flake.nix b/flake.nix index 51dd933f9a..0b2b919226 100644 --- a/flake.nix +++ b/flake.nix @@ -12,7 +12,7 @@ # glyphs. Pinned to the revision the release workflow uses — bump deliberately # (`nix flake update craft-fonts`); craftrules standards/fonts.md. craft-fonts = { - url = "github:storytold/craft-fonts/3d9ab3a132ed0eff457e424226a435a901da30d3"; + url = "github:storytold/craft-fonts/1466a883ae5ac0a7d76cfe7f9d56fe0240acb255"; flake = false; }; }; diff --git a/packaging/fonts.sh b/packaging/fonts.sh index 70d9fe14ea..843a495eed 100644 --- a/packaging/fonts.sh +++ b/packaging/fonts.sh @@ -10,7 +10,7 @@ prepare_fonts() { if [ -z "${CRAFT_FONTS_DIR:-}" ] && [ ! -e "$font_dir" ]; then # Same revision as release.yml. Never update or reset an existing checkout. - local revision=3d9ab3a132ed0eff457e424226a435a901da30d3 + local revision=1466a883ae5ac0a7d76cfe7f9d56fe0240acb255 echo "==> downloading craft-fonts ($revision) to $font_dir" if ! git clone --no-checkout https://github.com/storytold/craft-fonts "$font_dir" || ! git -C "$font_dir" checkout --detach "$revision"; then diff --git a/packaging/windows/fonts.ps1 b/packaging/windows/fonts.ps1 index 74f383fd8b..eccf69f820 100644 --- a/packaging/windows/fonts.ps1 +++ b/packaging/windows/fonts.ps1 @@ -6,7 +6,7 @@ function Initialize-CraftFonts([string] $WorkspaceRoot) { if (-not $env:CRAFT_FONTS_DIR -and -not (Test-Path -LiteralPath $fontDir)) { # Same revision as release.yml and packaging/fonts.sh. Existing checkouts stay untouched. - $revision = '3d9ab3a132ed0eff457e424226a435a901da30d3' + $revision = '1466a883ae5ac0a7d76cfe7f9d56fe0240acb255' Write-Output "==> downloading craft-fonts ($revision) to $fontDir" & git clone --no-checkout https://github.com/storytold/craft-fonts $fontDir if ($LASTEXITCODE -ne 0) { throw 'Could not download craft-fonts; provide a complete checkout with CRAFT_FONTS_DIR' } From 24f1df428d2975eb5268e95a42a72a1b85553503 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:56:29 +0200 Subject: [PATCH 016/247] LR-BEHAV-LOCALIZE: wrap the NOTICE font paragraph and the build.rs note again Co-Authored-By: Claude Opus 5.5 --- NOTICE | 9 +++++---- crates/engine/build.rs | 8 ++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/NOTICE b/NOTICE index 2f1b2d04c5..3606daae66 100644 --- a/NOTICE +++ b/NOTICE @@ -51,10 +51,11 @@ no darktable, RawSpeed, LibRaw or other GPL decoder/runtime code is included. Builds made with craft-fonts (the optional CRAFT_FONTS_DIR build input; all official releases) also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md -(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans -Thai and Noto Sans Hebrew), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic -Regular, Noto Sans Thai Regular and Noto Sans Hebrew Regular, and loads Noto Sans CJK SC separately. Release packages include each font's -licence as OFL-.txt; Windows installers include their texts in FONT-LICENCES.txt. +(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai +and Noto Sans Hebrew), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic +Regular, Noto Sans Thai Regular and Noto Sans Hebrew Regular, and loads Noto Sans CJK SC +separately. Release packages include each font's licence as OFL-.txt; Windows installers +include their texts in FONT-LICENCES.txt. Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and are never distributed with it. On the user's request (Photo > Download Place Names) the app diff --git a/crates/engine/build.rs b/crates/engine/build.rs index f55c0a9ef0..d891f572fb 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -3,10 +3,10 @@ //! Recipe from craft-fonts' docs/integration.md; craft-fonts is never a Cargo dependency, and this //! script only reads a local directory (no network). //! -//! wasm32 embeds BIZ UDPGothic Regular (~4.5 MB), Noto Sans Thai (~214 KiB), Noto Sans Georgian and -//! Noto Sans Hebrew Regular (~65 KiB, for Hebrew file and folder names), to keep the `.wasm` within the -//! web size budget (Cloudflare serves at most 25 MiB per file); the export -//! watermark falls back to it there. Native builds embed every font. +//! wasm32 embeds BIZ UDPGothic Regular (~4.5 MB), Noto Sans Thai (~214 KiB), Noto Sans Georgian +//! and Noto Sans Hebrew Regular (~65 KiB, for Hebrew file and folder names), to keep the `.wasm` +//! within the web size budget (Cloudflare serves at most 25 MiB per file); the export watermark +//! falls back to it there. Native builds embed every font. use std::fmt::Write as _; use std::path::{Path, PathBuf}; From 98a64775c79f19e9f4c4cfff53c98281626ed67f Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:44:36 +0200 Subject: [PATCH 017/247] LR-BEHAV-LOCALIZE: web docs name CRAFT_FONTS_REQUIRED and the Thai and Hebrew gap Co-Authored-By: Claude Opus 5.5 --- docs/web.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/web.md b/docs/web.md index de7b296c4f..9d331d0c34 100644 --- a/docs/web.md +++ b/docs/web.md @@ -54,15 +54,16 @@ gzip size (5.25 MB). `wasm-opt -Oz`, when installed, shrinks it further. **Fonts.** The browser has no system fonts to fall back on, so CJK text comes from [craft-fonts](https://github.com/storytold/craft-fonts), the optional `CRAFT_FONTS_DIR` build -input (`CRAFT_FONTS_DIR=../craft-fonts cargo xtask web`; release builds always set it). On wasm32 -`crates/engine/build.rs` embeds BIZ UDPGothic Regular (UI and watermark fallback), Noto Sans -Thai Regular (~214 KiB) and Noto Sans Hebrew Regular (~65 KiB), for Thai and Hebrew file and folder -names in every UI language (a Hebrew name's words stay in logical order, see -[localization-parity](localization-parity.md)). The web -bundle also ships Noto Sans CJK SC Regular as `lightcraft_zh_hans.otf` and loads it before the UI -starts. Keeping the 16 MB Chinese face separate leaves the module under Cloudflare's 25 MiB -per-file limit (the older Japanese-only module measured 21.8 MB). Without `CRAFT_FONTS_DIR`, the -web build still works, but Chinese and Japanese text lack glyphs. +input (`CRAFT_FONTS_DIR=../craft-fonts CRAFT_FONTS_REQUIRED=1 cargo xtask web`; release builds +always set both, and without `CRAFT_FONTS_REQUIRED` a face missing from the manifest is only a +warning). On wasm32 `crates/engine/build.rs` embeds BIZ UDPGothic Regular (UI and watermark +fallback), Noto Sans Thai Regular (~214 KiB) and Noto Sans Hebrew Regular (~65 KiB), for Thai and +Hebrew file and folder names in every UI language (a Hebrew name's words stay in logical order, +see [localization-parity](localization-parity.md)). The web bundle also ships Noto Sans CJK SC +Regular as `lightcraft_zh_hans.otf` and loads it before the UI starts. Keeping the 16 MB Chinese +face separate leaves the module under Cloudflare's 25 MiB per-file limit (the older Japanese-only +module measured 21.8 MB). Without `CRAFT_FONTS_DIR`, the web build still works, but Chinese, +Japanese, Thai and Hebrew text lack glyphs. ## Deploying: headers From dee1032f0fc39d39c00d2d2f8098d997a10a990d Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:53:32 +0200 Subject: [PATCH 018/247] LR-BEHAV-LOCALIZE: web docs name the Georgian face wasm32 now embeds Co-Authored-By: Claude Opus 5.5 --- docs/web.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/web.md b/docs/web.md index 9d331d0c34..d9d41957de 100644 --- a/docs/web.md +++ b/docs/web.md @@ -59,11 +59,12 @@ always set both, and without `CRAFT_FONTS_REQUIRED` a face missing from the mani warning). On wasm32 `crates/engine/build.rs` embeds BIZ UDPGothic Regular (UI and watermark fallback), Noto Sans Thai Regular (~214 KiB) and Noto Sans Hebrew Regular (~65 KiB), for Thai and Hebrew file and folder names in every UI language (a Hebrew name's words stay in logical order, -see [localization-parity](localization-parity.md)). The web bundle also ships Noto Sans CJK SC -Regular as `lightcraft_zh_hans.otf` and loads it before the UI starts. Keeping the 16 MB Chinese -face separate leaves the module under Cloudflare's 25 MiB per-file limit (the older Japanese-only -module measured 21.8 MB). Without `CRAFT_FONTS_DIR`, the web build still works, but Chinese, -Japanese, Thai and Hebrew text lack glyphs. +see [localization-parity](localization-parity.md)), and Noto Sans Georgian Regular for the +Georgian interface. The web bundle also ships Noto Sans CJK SC Regular as `lightcraft_zh_hans.otf` +and loads it before the UI starts. Keeping the 16 MB Chinese face separate leaves the module under +Cloudflare's 25 MiB per-file limit (the older Japanese-only module measured 21.8 MB). Without +`CRAFT_FONTS_DIR`, the web build still works, but Chinese, Japanese, Thai, Georgian and Hebrew +text lack glyphs. ## Deploying: headers From c60e248471b912134217982c877589381cff08cc Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:19:44 -0400 Subject: [PATCH 019/247] LR-PROF-CAMERACOLOR: negative-channel test requires the deep samples each output depth asks for --- crates/pipeline/src/tests.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index c2388c36b7..0596eff719 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -840,8 +840,12 @@ fn negative_channels_render_finite_everywhere() { let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| { let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) }); assert!(r.histogram.total > 0, "{what}"); - if let Some(DeepSamples::F32(v)) = r.deep.map(|d| d.samples) { - assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + match (depth, r.deep.map(|d| d.samples)) { + (OutputDepth::U8, None) | (OutputDepth::U16, Some(DeepSamples::U16(_))) => {} + (OutputDepth::F32Linear | OutputDepth::F32Hdr, Some(DeepSamples::F32(v))) => { + assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + } + _ => panic!("{what} {depth:?}: missing or wrong deep samples"), } }; let mut pushed = DevelopSettings::default(); From 48a002e73af31fe837a21358ce3290e36e0fda37 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:38 +0200 Subject: [PATCH 020/247] M12: SAM 3 accelerator plumbing: backend choice, CPU fallback and the AI masks setting Part 1 of 5 of #2167. lightcraft-segment gets a BackboneAccel trait (backbone, plus optional necks, DETR encoder and mask decoder, asked only when runs_heads()), WeightReader and Sam3::load_accelerated. Whatever an accelerator returns is checked (length, finite values); an error, a wrong size or a NaN falls back to candle, logged once, with the reason kept for the status. The engine worker places the model (Metal on macOS, the CPU elsewhere, or the CPU when chosen or switched off), reloads it when a GPU switch or the setting changes, and reports where it ran in segment.model.status. Settings > Performance > AI masks gets Run on: Automatic / CPU. #2067's retry is kept: a job that fails on candle's GPU (Metal) runs once more on the CPU, which then serves the session (now a placement with the reason); LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off keep the model on the CPU on macOS too. #1963's semantic mask comes from the mask decoder as before (on an accelerator: one more row of its mask product). This build has no GPU backbone (GPU_BACKBONE is None), so the GPU path is off: outside macOS candle runs everything on the CPU, as on main. Also on the CPU: the text features of the last 16 prompts are cached per model, and the detector's box relative-position bias is one pass, with the decoder MLPs' bias and ReLU fused (bit-identical outputs). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/engine/src/cmd/masks.rs | 20 +- crates/engine/src/config.rs | 7 +- crates/engine/src/segment/mod.rs | 99 ++- crates/engine/src/segment/worker.rs | 685 ++++++++++++++++---- crates/engine/src/tests_segment.rs | 45 ++ crates/gpu/src/lib.rs | 7 +- crates/segment/Cargo.toml | 2 + crates/segment/examples/sam3_bench.rs | 56 +- crates/segment/src/cpu.rs | 147 +++++ crates/segment/src/detector.rs | 293 ++++++++- crates/segment/src/lib.rs | 633 ++++++++++++++++-- crates/segment/src/nn.rs | 48 +- crates/segment/tests/it/accel.rs | 58 ++ crates/segment/tests/it/main.rs | 2 + crates/segment/tests/it/prompts.rs | 63 ++ crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/cs.json | 10 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/de.json | 10 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/es.json | 10 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fi.json | 10 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/fr.json | 10 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/id.json | 10 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/it.json | 11 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ja.json | 10 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/ka.json | 10 + crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pl.json | 12 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/pt-br.json | 10 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/ru.json | 10 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/sv.json | 10 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/uk.json | 10 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/vi.json | 10 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hans.json | 10 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/locales/zh-hant.json | 10 +- crates/ui-egui/src/panels/settings.rs | 57 +- crates/ui-egui/src/tests_dialog_fit.rs | 37 ++ 52 files changed, 2219 insertions(+), 265 deletions(-) create mode 100644 crates/segment/src/cpu.rs create mode 100644 crates/segment/tests/it/accel.rs create mode 100644 crates/segment/tests/it/prompts.rs diff --git a/Cargo.lock b/Cargo.lock index 8b3985fc09..8c29f11536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3485,6 +3485,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index dc403df9b1..9c7c8bca8f 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -533,7 +533,7 @@ pub fn specs() -> Vec { "AI Mask Model Status", [], None, - "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, and the download's progress → {available, installed, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", + "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, where it runs and how long the last photo took, and the download's progress → {available, installed, dir, loaded, busy, analyzing, runOn (auto | cpu: segment.settings), backend: {device (what runs the backbone: a GPU's name, Metal GPU or CPU; null until loaded), runtime (wgpu|candle), heads (CPU|Metal GPU, and which of the parts after the backbone the GPU accelerator runs, e.g. `CPU; the necks on the GPU`), fallback (why the backbone is not on the GPU), encodeMs (last backbone run), analyzeMs (last photo's analysis before the first click)}, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", super::always, |s, _| { let g = &s.segmenter; @@ -545,6 +545,8 @@ pub fn specs() -> Vec { "loaded": g.loaded(), "busy": g.busy(), "analyzing": g.analyzing(), + "runOn": g.run_on().name(), + "backend": g.backend(), "sizeBytes": crate::segment::MODEL_BYTES, "license": crate::segment::LICENSE_NAME, "licenseUrl": crate::segment::LICENSE_URL, @@ -553,6 +555,22 @@ pub fn specs() -> Vec { })) } ), + cmd!( + query "segment.settings", + "AI Mask Settings", + [], + None, + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere candle on the CPU: this build has no wgpu kernels for SAM 3 yet), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + super::always, + |s, p| { + let c = "segment.settings"; + if let Some(v) = p.get("runOn") { + let run_on = v.as_str().and_then(crate::segment::RunOn::parse).ok_or_else(|| bad(c, "`runOn` must be auto or cpu"))?; + s.segmenter.set_run_on(run_on).map_err(ai_err)?; + } + Ok(json!({"runOn": s.segmenter.run_on().name()})) + } + ), cmd!( query "segment.model.download", "Download AI Mask Model", diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..839836b274 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -132,11 +132,14 @@ fn sam3_dir(var: Option, config: Option) -> Option< } impl Session { - /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), and for the user's - /// download mirrors in `/models/sam3-mirrors.txt`. + /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), for the user's + /// download mirrors in `/models/sam3-mirrors.txt` and for where it runs in + /// `/models/sam3-settings.json`. pub fn with_default_sam3_model(mut self) -> Self { self.segmenter.dir = default_sam3_dir(); self.segmenter.mirrors_file = config_dir().map(|d| d.join("models").join("sam3-mirrors.txt")); + self.segmenter.settings_file = config_dir().map(|d| d.join("models").join("sam3-settings.json")); + self.segmenter.load_settings(); self } diff --git a/crates/engine/src/segment/mod.rs b/crates/engine/src/segment/mod.rs index b69a6dca27..b4302d77f7 100644 --- a/crates/engine/src/segment/mod.rs +++ b/crates/engine/src/segment/mod.rs @@ -117,12 +117,57 @@ pub struct DownloadStatus { pub finished: bool, } +/// Where SAM 3 runs (Settings ▸ Performance ▸ AI masks; `segment.settings {runOn}`, kept in +/// [`Segmenter::settings_file`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RunOn { + /// The GPU when there is one: Metal on macOS, elsewhere the image encoder through wgpu unless + /// the GPU is switched off ("Use the GPU for rendering", `LIGHTCRAFT_GPU=0`, …). + #[default] + Auto, + /// The CPU for all of it, on every platform (on macOS candle's CPU device instead of Metal). + Cpu, +} + +impl RunOn { + pub fn parse(name: &str) -> Option { + match name { + "auto" => Some(RunOn::Auto), + "cpu" => Some(RunOn::Cpu), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + RunOn::Auto => "auto", + RunOn::Cpu => "cpu", + } + } +} + +/// Why the model runs on the CPU when [`RunOn::Cpu`] is chosen (`segment.model.status` → +/// `backend.fallback`). +pub const CPU_CHOSEN: &str = "the CPU is chosen in Settings (AI masks)"; + +/// The settings file's contents (`sam3-settings.json`). +#[derive(Default, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct Settings { + /// `auto` or `cpu` (`None` or anything else: `auto`). + run_on: Option, +} + /// The model (on its worker thread), the download, and AI mask requests in flight. pub struct Segmenter { /// Where the `facebook/sam3` files live (set by the app; `None`: no AI masks). pub dir: Option, /// The user's list of download mirrors (one base URL per line), if any. pub mirrors_file: Option, + /// Where [`Segmenter::run_on`] is kept (`/models/sam3-settings.json` in the app; `None`: + /// only for this session). + pub settings_file: Option, + run_on: RunOn, /// Run requests in the background and apply them in [`Session::segment_poll`] (the /// desktop app); otherwise commands wait for their result (CLI, MCP, tests). pub background: bool, @@ -143,6 +188,8 @@ impl Default for Segmenter { Segmenter { dir: None, mirrors_file: None, + settings_file: None, + run_on: RunOn::Auto, background: false, pending: None, messages: Vec::new(), @@ -160,6 +207,33 @@ impl Segmenter { /// Whether this build can compute AI masks at all. pub const AVAILABLE: bool = cfg!(feature = "sam"); + /// Where SAM 3 runs: the user's choice. + pub fn run_on(&self) -> RunOn { + self.run_on + } + + /// Read the choice of where SAM 3 runs from [`Segmenter::settings_file`] (a missing or damaged + /// file is [`RunOn::Auto`]). + pub fn load_settings(&mut self) { + let read = self.settings_file.as_deref().and_then(|f| crate::denoise::read_capped(f, 4096)); + let st: Settings = read.and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + self.run_on = st.run_on.as_deref().and_then(RunOn::parse).unwrap_or_default(); + } + + /// Choose where SAM 3 runs, and keep the choice in [`Segmenter::settings_file`]. A loaded model + /// moves at its next request (it loads again). + pub fn set_run_on(&mut self, run_on: RunOn) -> Result<(), String> { + if let Some(f) = &self.settings_file { + if let Some(parent) = f.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?; + } + let st = Settings { run_on: Some(run_on.name().to_string()) }; + crate::denoise::write_atomic(f, &serde_json::to_vec_pretty(&st).map_err(|e| e.to_string())?)?; + } + self.run_on = run_on; + Ok(()) + } + pub fn remote_endpoint(&self) -> Option { #[cfg(feature = "sam")] return lightcraft_segment::remote::configured(); @@ -192,6 +266,28 @@ impl Segmenter { false } + /// Where the model runs and how long the last photo took (`segment.model.status` → `backend`): + /// `{device, runtime, heads, fallback, encodeMs, analyzeMs}` (see `worker::Backend`; `device` + /// is `null` until the model first loads, and `fallback` then says whether the GPU is switched + /// off), or `null` in a build without AI masks. + pub fn backend(&self) -> serde_json::Value { + #[cfg(feature = "sam")] + { + let mut b = self.worker.backend(); + if b.device.is_none() { + b.fallback = match self.run_on { + RunOn::Cpu => Some(CPU_CHOSEN.into()), + // macOS: Metal, unless the environment switches the GPU off (the preference is wgpu's) + RunOn::Auto if cfg!(target_os = "macos") => lightcraft_gpu::env_off_reason().map(Into::into), + RunOn::Auto => lightcraft_gpu::switched_off(), + }; + } + serde_json::to_value(b).unwrap_or_default() + } + #[cfg(not(feature = "sam"))] + serde_json::Value::Null + } + /// Whether a zoomed-in detail pass is queued or running. pub fn detail_busy(&self) -> bool { #[cfg(feature = "sam")] @@ -431,7 +527,8 @@ impl Session { job } }; - Ok(worker::Job { dir, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) + let cpu = self.segmenter.run_on == RunOn::Cpu; + Ok(worker::Job { dir, cpu, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) } /// Send a request and wait for its result (CLI, MCP, tests; or when not in background mode). diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..6bae968924 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -8,24 +8,33 @@ //! counters are decremented by drop guards, so they can't stay stuck. The model is unloaded //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! -//! Where the model can run on the GPU (Metal on macOS), a job that fails there (a panic or an -//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the -//! model and runs once more on the CPU. When that works, the model stays on the CPU for the rest -//! of the session and the job's outcome says so; when it fails too, the GPU wasn't the cause and -//! the next job uses it again. `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` keep the model on -//! the CPU from the start. +//! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) can run on the GPU through an +//! accelerator ([`GPU_BACKBONE`]: none in this build yet, so it runs in candle as before), unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI +//! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. +//! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every +//! platform, and so do `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` (macOS included, as +//! for AI Denoise and the face models). +//! +//! Where candle runs the model on the GPU (Metal on macOS), a job that fails there (a panic or an +//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the model +//! and runs once more on the CPU. When that works, the model stays on the CPU for the rest of the +//! session and the job's outcome says so; when it fails too, the GPU wasn't the cause and the next +//! job uses it again. (The wgpu backbone elsewhere falls back to candle by itself, part by part.) +//! [`Backend`] tells the session where it ran and how long the last photo took. use std::collections::VecDeque; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::sync::Arc; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use lightcraft_develop::SegMask; use lightcraft_segment::{ - Encoded, Sam3, + BackboneAccel, Device, Encoded, Sam3, WeightReader, remote::{self, Operation, Request, text_logits}, }; @@ -62,6 +71,8 @@ pub enum Kind { pub struct Job { /// The model folder. pub dir: PathBuf, + /// The user chose the CPU for SAM 3 (Settings ▸ Performance ▸ AI masks). + pub cpu: bool, /// Which photo and look the request is about (the encode cache's key). pub key: u64, /// Renders the model input when the cache doesn't hold `key` (always for a detail pass). @@ -87,29 +98,6 @@ pub struct Outcome { pub const GPU_FAILED: &str = "The GPU couldn't run the AI mask model, so it runs on the CPU until LightCraft restarts (slower). Details are in the log."; -/// Where the model is loaded. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Placement { - /// On the GPU when there is one (Metal on macOS); a job that fails there is retried on the CPU. - Gpu, - /// On the CPU: this build has no GPU path, the environment switches the GPU off, or the model - /// failed on it. - Cpu, -} - -impl Placement { - fn initial() -> Self { - if !lightcraft_segment::GPU_BUILD { - return Placement::Cpu; - } - if let Some(why) = lightcraft_gpu::env_off_reason() { - log::info!("SAM 3 runs on the CPU ({why})"); - return Placement::Cpu; - } - Placement::Gpu - } -} - /// Why a job failed. #[derive(Debug)] enum Failure { @@ -156,6 +144,154 @@ pub struct Shared { pub loaded: AtomicBool, /// Loading the model or encoding a photo right now (the slow parts). pub encoding: AtomicBool, + /// Where the model runs and how long the last photo took. + pub backend: Mutex, +} + +/// Where the model runs, and how long the last photo took (`segment.model.status` → `backend`, +/// Settings ▸ Performance ▸ AI masks). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Backend { + /// What the backbone (the 32-layer ViT, most of the work) runs on: a GPU's name ("NVIDIA + /// GeForce RTX 5070 (Vulkan)"), "Metal GPU" or "CPU". `None` until the model first loads. + pub device: Option, + /// What runs the backbone: "wgpu" (LightCraft's GPU kernels) or "candle". + pub runtime: Option, + /// What runs the rest (the necks and the click and text heads): "CPU" or "Metal GPU", with the parts the GPU + /// accelerator runs ("CPU; the necks on the GPU"). + pub heads: Option, + /// Why the backbone runs on the CPU where it could use the GPU: the GPU is switched off, there + /// is no usable one, or it failed on a photo. + pub fallback: Option, + /// The last photo's backbone run, in milliseconds. + pub encode_ms: Option, + /// The last photo's whole analysis before the first click (backbone and click features), in + /// milliseconds. + pub analyze_ms: Option, +} + +/// Where the model runs on this machine. +#[derive(Clone, Debug, PartialEq)] +enum Placement { + /// All of it in candle on its best device (Metal on macOS). + Best, + /// The backbone on the GPU (wgpu), the rest in candle on the CPU. + GpuBackbone, + /// All of it in candle on the CPU: the CPU is chosen, or the GPU is switched off (why). + Cpu(String), +} + +/// Where the model runs, for candle's best device being the CPU (`best_is_cpu`), the GPU switched +/// off (`switched_off`: why) or not, and the CPU chosen in Settings (`cpu`) or not. The choice wins +/// on every platform; the GPU switches only govern the wgpu backbone (macOS keeps Metal). +fn placement(best_is_cpu: bool, switched_off: Option, cpu: bool) -> Placement { + match (cpu, best_is_cpu, switched_off) { + (true, _, _) => Placement::Cpu(super::CPU_CHOSEN.into()), + (false, false, _) => Placement::Best, + (false, true, None) => Placement::GpuBackbone, + (false, true, Some(why)) => Placement::Cpu(why), + } +} + +/// Where the model is to run now: [`placement`], unless candle's GPU failed on it this session (`failed`: why; +/// the CPU until LightCraft restarts) or the environment switches the GPU off (`LIGHTCRAFT_GPU=0`, +/// `LIGHTCRAFT_GPU_BACKEND=off`), which keeps it off Metal too. +fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { + if cpu { + return placement(best_is_cpu, None, true); + } + if let Some(why) = failed { + return Placement::Cpu(why.into()); + } + if let Some(why) = lightcraft_gpu::env_off_reason() { + return Placement::Cpu(why.into()); + } + match placement(best_is_cpu, lightcraft_gpu::switched_off(), false) { + // without a GPU backbone in this build, candle's best device runs it all + Placement::GpuBackbone if GPU_BACKBONE.is_none() => Placement::Best, + p => p, + } +} + +/// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device +/// being the CPU or not (`best_is_cpu`). Two reasons for the CPU are the same place, and so is candle's best device +/// when that is the CPU. +fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { + #[derive(PartialEq)] + enum Runs { + Cpu, + Metal, + Wgpu, + } + let runs = |p: &Placement| match p { + Placement::Best if best_is_cpu => Runs::Cpu, + Placement::Best => Runs::Metal, + Placement::GpuBackbone => Runs::Wgpu, + Placement::Cpu(_) => Runs::Cpu, + }; + runs(loaded) != runs(wanted) +} + +/// Builds the GPU backbone from the checkpoint (tests use fakes). +type MakeAccel = fn(&WeightReader) -> Result, String>; + +/// The GPU backbone of this build: none yet (its wgpu kernels come separately), so where candle has no GPU the +/// model runs in candle on the CPU, as before. +const GPU_BACKBONE: Option = None; + +fn no_accelerator(_: &WeightReader) -> Result, String> { + Err("this build has no GPU backbone".into()) +} + +/// Load the model in `dir` as `placement` says, on `best` (candle's best device). +fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { + match placement { + Placement::Best => Sam3::load_on(dir, best), + Placement::Cpu(_) => Sam3::load_on(dir, Device::Cpu), + Placement::GpuBackbone => Sam3::load_accelerated(dir, Device::Cpu, make), + } +} + +/// Note where the model `m`, just loaded for `placement`, runs. +fn note_loaded(shared: &Shared, m: &Sam3, placement: &Placement) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + *b = Backend { + device: Some(m.backbone_device()), + runtime: Some(if m.accelerated() { "wgpu" } else { "candle" }.into()), + heads: Some(m.heads_device()), + fallback: match placement { + Placement::Cpu(why) => Some(why.clone()), + _ => m.backbone_fallback(), + }, + encode_ms: None, + analyze_ms: None, + }; +} + +/// Note where the backbone ran a photo (it may have moved to the CPU on the way) and, when it +/// succeeded, how long it took (`encode`). +fn note_run(shared: &Shared, m: &Sam3, encode: Option) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + b.device = Some(m.backbone_device()); + b.runtime = Some(if m.accelerated() { "wgpu" } else { "candle" }.into()); + b.heads = Some(m.heads_device()); + if let Some(why) = m.backbone_fallback() { + b.fallback = Some(why); + } + if let Some(d) = encode { + b.encode_ms = Some(millis(d)); + } +} + +/// Note where the backbone ran a detail pass (a zoomed-in region): not how long it took, since the last photo's +/// times are its whole analysis and the backbone run in it. +fn note_detail(shared: &Shared, m: &Sam3) { + note_run(shared, m, None); +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// Decrements a counter when dropped (also when unwinding). @@ -218,6 +354,11 @@ impl Worker { !self.dead() && self.shared.loaded.load(Ordering::SeqCst) } + /// Where the model runs (ran, once unloaded) and how long the last photo took. + pub fn backend(&self) -> Backend { + self.shared.backend.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + /// Queue `job`; returns at once. pub fn submit(&mut self, job: Job) -> Result<(), String> { if self.dead() { @@ -237,7 +378,7 @@ impl Worker { // (re)start the thread let (tx, rx) = mpsc::channel(); let shared = self.shared.clone(); - match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, Placement::initial())) { + match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, lightcraft_segment::GPU_BUILD)) { Ok(t) => { self.thread = Some(t); self.tx = Some(tx.clone()); @@ -255,6 +396,8 @@ impl Worker { #[derive(Default)] struct State { model: Option<(PathBuf, Sam3)>, + /// Where the model was loaded to run, and whether candle's best device was the CPU then. + placement: Option<(Placement, bool)>, cache: Option<(u64, Encoded)>, remote: Option, } @@ -269,8 +412,12 @@ fn supersedes(later: &Job, job: &Job) -> bool { } } -fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: Placement) { +/// The worker's loop. `metal`: candle may run the model on a GPU here (macOS), so a job that fails is retried on +/// the CPU. +fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, metal: bool) { let mut state = State::default(); + // why the model runs on the CPU for the rest of the session: it failed on the GPU and works on the CPU + let mut gpu_failed: Option = None; let mut queue: VecDeque = VecDeque::new(); loop { if queue.is_empty() { @@ -300,24 +447,26 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: let _ = job.reply.send(Outcome { tag: job.tag, result: Ok(None), superseded: true, notice: None }); continue; } - // what a retry on the CPU needs (running the job takes them) - let retry = (placement == Placement::Gpu && remote::configured().is_none()).then(|| (job.kind.clone(), job.render.clone())); - let mut result = attempt(&mut state, shared, &mut job, placement); + // on candle's GPU: what a retry on the CPU needs (running the job takes them) + let on_gpu = metal && gpu_failed.is_none() && !job.cpu && lightcraft_gpu::env_off_reason().is_none() && remote::configured().is_none(); + let retry = on_gpu.then(|| (job.kind.clone(), job.render.clone())); + let mut result = attempt(&mut state, shared, &mut job, gpu_failed.as_deref()); let mut notice = None; - let gpu_failed = match &result { + let failed_why = match &result { Err(Failure::Model(why)) => Some(why.clone()), _ => None, }; - if let (Some(why), Some((kind, render))) = (gpu_failed, retry) { + if let (Some(why), Some((kind, render))) = (failed_why, retry) { // the GPU may be the cause (e.g. a kernel its compiler can't build, issue #1974): free // the model there and try once on the CPU log::warn!("SAM 3 failed on the GPU ({why}); trying the CPU"); state = State::default(); (job.kind, job.render) = (kind, render); - match attempt(&mut state, shared, &mut job, Placement::Cpu) { + let reason = format!("the GPU couldn't run it ({why}); the CPU until LightCraft restarts"); + match attempt(&mut state, shared, &mut job, Some(&reason)) { Ok(r) => { log::warn!("SAM 3 runs on the CPU from now on: it failed on the GPU and works on the CPU"); - placement = Placement::Cpu; + gpu_failed = Some(reason); notice = Some(GPU_FAILED.to_string()); result = Ok(r); } @@ -338,10 +487,10 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: } } -/// Run `job` with the model on `placement`. A panic is a [`Failure::Model`] and drops what the -/// model kept. -fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { - match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, placement))) { +/// Run `job`, on the CPU when `failed` says the GPU failed this session. A panic is a [`Failure::Model`] and drops +/// what the model kept. +fn attempt(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { + match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, failed))) { Ok(r) => r, Err(p) => { let why = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); @@ -353,19 +502,38 @@ fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme } } -/// The model for `dir`, loading it on `placement` when needed. -fn model<'a>(state: &'a mut State, shared: &Shared, dir: &std::path::Path, placement: Placement) -> Result<&'a mut Sam3, Failure> { - if state.model.as_ref().is_none_or(|(d, _)| d != dir) { +/// The model for `dir`, loading it when needed (and again when the GPU was switched on or off, or +/// the CPU chosen or not: `cpu`; `failed`: the GPU failed this session, see [`wanted`]). +fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, failed: Option<&str>) -> Result<&'a mut Sam3, Failure> { + let now = state.placement.as_ref().map(|(_, best_is_cpu)| wanted(*best_is_cpu, cpu, failed)); + let stale = state.placement.as_ref().zip(now.as_ref()).is_some_and(|((p, best_is_cpu), now)| moves(p, now, *best_is_cpu)); + if let (false, Some((p, _)), Some(now)) = (stale, state.placement.as_mut(), now) { + // the same device for another reason (the choice, a GPU switch): the model stays, the reason it shows changes + if *p != now { + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).fallback = match &now { + Placement::Cpu(why) => Some(why.clone()), + _ => None, + }; + *p = now; + } + } + if stale || state.model.as_ref().is_none_or(|(d, _)| d != dir) { state.model = None; + state.placement = None; state.cache = None; let _busy = Flag::raise(&shared.encoding); let t = web_time::Instant::now(); - let m = match placement { - Placement::Gpu => Sam3::load(dir)?, - Placement::Cpu => Sam3::load_cpu(dir)?, - }; - log::info!("SAM 3 loaded in {:?} ({})", t.elapsed(), if m.device().is_cpu() { "CPU" } else { "GPU" }); + // with the CPU chosen (or forced) candle's best device isn't asked for (on macOS that sets up Metal): + // it counts as Metal on macOS and the CPU elsewhere when the choice changes back + let skip = cpu || failed.is_some() || lightcraft_gpu::env_off_reason().is_some(); + let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; + let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; + let placement = wanted(best_is_cpu, cpu, failed); + let m = load(dir, best, &placement, GPU_BACKBONE.unwrap_or(no_accelerator))?; + log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); + note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); + state.placement = Some((placement, best_is_cpu)); shared.loaded.store(true, Ordering::SeqCst); } state.model.as_mut().map(|(_, m)| m).ok_or_else(|| "the model did not load".into()) @@ -390,17 +558,33 @@ fn render(job: &mut Job) -> Result { } /// The model and the encoded photo `job.key` (rendering and encoding it when needed). -fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { - model(state, shared, &job.dir, placement)?; +fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { + model(state, shared, &job.dir, job.cpu, failed)?; if state.cache.as_ref().is_none_or(|(k, _)| *k != job.key) { state.cache = None; let input = render(job)?; let _busy = Flag::raise(&shared.encoding); let m = state.model.as_mut().map(|(_, m)| m).ok_or("the model did not load")?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + let encode = t.elapsed(); + note_run(shared, m, None); + let mut enc = enc?; m.prepare_clicks(&mut enc)?; - log::info!("SAM 3 encoded {}×{} in {:?}", input.w, input.h, t.elapsed()); + let analyze = t.elapsed(); + // both times together, once the whole analysis worked: never one photo's encoder with another's total + { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + (b.encode_ms, b.analyze_ms) = (Some(millis(encode)), Some(millis(analyze))); + } + log::info!( + "SAM 3 analyzed {}×{} in {analyze:?}: backbone {encode:?} on the {}, click features {:?} on the {}", + input.w, + input.h, + m.backbone_device(), + analyze.saturating_sub(encode), + m.heads_device() + ); state.cache = Some((job.key, enc)); } let State { model, cache, .. } = state; @@ -457,7 +641,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str) })) } -fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { +fn run_job(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { if let Some(endpoint) = remote::configured() { let result = remote_job(state, shared, job, &endpoint); if result.is_err() { @@ -468,33 +652,38 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme let side = lightcraft_segment::MASK_SIDE; match std::mem::replace(&mut job.kind, Kind::Prepare) { Kind::Prepare => { - encoded(state, shared, job, placement)?; + encoded(state, shared, job, failed)?; Ok(None) } Kind::Clicks(clicks) => { - let (m, enc) = encoded(state, shared, job, placement)?; + let (m, enc) = encoded(state, shared, job, failed)?; let p = m.segment_clicks(enc, &clicks)?; Ok(Some(SegMask::from_logits(side, &p.logits))) } Kind::Text(text) => { - let (m, enc) = encoded(state, shared, job, placement)?; - Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l))) + let (m, enc) = encoded(state, shared, job, failed)?; + let logits = text_logits(m, enc, &text)?; + // the text heads may have moved to the CPU on the way (a failure on the GPU) + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device()); + Ok(logits.map(|l| SegMask::from_logits(side, &l))) } #[cfg(test)] #[allow(clippy::panic)] Kind::Panic => panic!("a test panic"), #[cfg(test)] #[allow(clippy::panic)] - Kind::FailOnGpu { panic } => match placement { - Placement::Gpu if panic => panic!("a test panic on the GPU"), - Placement::Gpu => Err(Failure::Model("a test error on the GPU".into())), - Placement::Cpu => Ok(None), + Kind::FailOnGpu { panic } => match failed.is_some() || job.cpu { + false if panic => panic!("a test panic on the GPU"), + false => Err(Failure::Model("a test error on the GPU".into())), + true => Ok(None), }, Kind::Detail { prompt, region } => { let input = render(job)?; - let m = model(state, shared, &job.dir, placement)?; + let m = model(state, shared, &job.dir, job.cpu, failed)?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + note_detail(shared, m); + let mut enc = enc?; let (rw, rh) = (region[2] - region[0], region[3] - region[1]); if !(rw > 0.0 && rh > 0.0) { return Ok(None); @@ -527,7 +716,7 @@ mod tests { fn job(tag: Tag, reply: &mpsc::Sender) -> Job { // an empty folder: loading fails with an error (no model files) let dir = std::env::temp_dir().join(format!("lc-sam3-worker-none-{}", std::process::id())); - Job { dir, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } + Job { dir, cpu: false, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } } #[test] @@ -560,7 +749,7 @@ mod tests { jtx.send(job(Tag::Wait, &tx)).unwrap(); shared.pending.store(2, Ordering::SeqCst); drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let first = rx.recv().unwrap(); assert!(first.result.unwrap_err().contains("failed unexpectedly")); let second = rx.recv().unwrap(); @@ -569,72 +758,6 @@ mod tests { assert!(!shared.encoding.load(Ordering::SeqCst)); } - /// Run `kinds` in turn on a worker that starts on `placement`; their outcomes. - fn run_kinds(placement: Placement, kinds: Vec) -> Vec { - let (tx, rx) = mpsc::channel(); - let (jtx, jrx) = mpsc::channel(); - let shared = Shared::default(); - shared.pending.store(kinds.len(), Ordering::SeqCst); - for kind in kinds { - let mut j = job(Tag::Wait, &tx); - j.kind = kind; - jtx.send(j).unwrap(); - } - drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), placement); - assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); - assert!(!shared.encoding.load(Ordering::SeqCst)); - rx.try_iter().collect() - } - - #[test] - fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { - // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); - assert_eq!(out.len(), 2); - assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); - assert_eq!(out[1].notice, None, "said once"); - } - - #[test] - fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: false }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); - assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly")); - assert_eq!(out[0].notice, None); - // not the GPU's fault: the next job tries the GPU first again - assert!(matches!(out[1].result, Ok(None))); - assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_worker_on_the_cpu_never_tries_the_gpu() { - // no GPU in this build, or LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off - let out = run_kinds(Placement::Cpu, vec![Kind::FailOnGpu { panic: true }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice, None); - if !lightcraft_segment::GPU_BUILD { - assert_eq!(Placement::initial(), Placement::Cpu); - } - } - - #[test] - fn missing_model_files_are_not_retried_on_the_cpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Prepare]); - assert!(out[0].result.as_ref().unwrap_err().contains("not found")); - assert_eq!(out[0].notice, None); - let missing = lightcraft_segment::Error::Missing(PathBuf::from("models")); - assert!(matches!(Failure::from(missing), Failure::Other(_))); - } - #[test] fn a_newer_request_for_the_same_selection_supersedes_a_queued_one() { let (tx, rx) = mpsc::channel(); @@ -652,10 +775,298 @@ mod tests { drop(jtx); let shared = Shared::default(); shared.pending.store(3, Ordering::SeqCst); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let out: Vec = rx.try_iter().collect(); assert_eq!(out.len(), 3); assert!(out[0].superseded && out[1].superseded && !out[2].superseded); assert_eq!(shared.pending.load(Ordering::SeqCst), 0); } + + /// A model folder whose checkpoint holds no tensors: it loads with an accelerator, never in candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-worker-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join(lightcraft_segment::WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// A GPU backbone that answers with zeros, or fails on every photo. + struct FakeGpu(bool); + + impl BackboneAccel for FakeGpu { + fn forward(&self, _: &[f32]) -> Result, String> { + if self.0 { Err("device lost".into()) } else { Ok(vec![0.0; 1024 * 72 * 72]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + fn fake_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(false))) + } + + fn failing_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(true))) + } + + fn no_gpu(_: &WeightReader) -> Result, String> { + Err("no GPU adapter".into()) + } + + #[allow(clippy::panic)] + fn never(_: &WeightReader) -> Result, String> { + panic!("the GPU backbone was built") + } + + #[allow(clippy::unwrap_used)] + fn backend(shared: &Shared) -> Backend { + shared.backend.lock().unwrap().clone() + } + + #[test] + fn the_backbone_goes_to_the_gpu_only_where_candle_has_none_and_the_gpu_is_on() { + // macOS: candle runs everything on Metal, as before (the GPU switches are wgpu's) + assert_eq!(placement(false, None, false), Placement::Best); + assert_eq!(placement(false, Some("disabled by LIGHTCRAFT_GPU=0".into()), false), Placement::Best); + // elsewhere: the backbone on the GPU unless it is switched off + assert_eq!(placement(true, None, false), Placement::GpuBackbone); + let off = "disabled by the GPU rendering preference (app.gpu)"; + assert_eq!(placement(true, Some(off.into()), false), Placement::Cpu(off.into())); + } + + #[test] + fn the_cpu_chosen_in_settings_wins_on_every_platform() { + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // macOS (Metal) and elsewhere, the GPU on or off + for best_is_cpu in [false, true] { + for off in [None, Some("disabled by LIGHTCRAFT_GPU=0".to_string())] { + assert_eq!(placement(best_is_cpu, off.clone(), true), chosen, "{best_is_cpu} {off:?}"); + } + } + assert_eq!(super::super::CPU_CHOSEN, "the CPU is chosen in Settings (AI masks)"); + } + + #[test] + fn switching_the_gpu_or_the_choice_reloads_only_a_model_it_moves() { + let cpu = |why: &str| Placement::Cpu(why.into()); + let chosen = || placement(true, None, true); + // the GPU switch: Metal stays; the wgpu backbone goes to the CPU and back + assert!(!moves(&Placement::Best, &placement(false, Some("off".into()), false), false)); + assert!(moves(&Placement::GpuBackbone, &placement(true, Some("off".into()), false), true)); + assert!(moves(&cpu("off"), &placement(true, None, false), true)); + // without a GPU backbone candle's best device is the CPU: the GPU switch moves nothing + assert!(!moves(&Placement::Best, &cpu("off"), true)); + assert!(!moves(&cpu("off"), &Placement::Best, true)); + // the choice: Metal (macOS) or the GPU backbone to the CPU and back + assert!(moves(&Placement::Best, &placement(false, None, true), false)); + assert!(moves(&placement(false, None, true), &placement(false, None, false), false)); + assert!(moves(&Placement::GpuBackbone, &chosen(), true)); + // the CPU for one reason or the other: it stays loaded + assert!(!moves(&cpu("disabled by LIGHTCRAFT_GPU=0"), &chosen(), true)); + assert!(!moves(&chosen(), &cpu("disabled by LIGHTCRAFT_GPU=0"), false)); + assert!(!moves(&Placement::GpuBackbone, &placement(true, None, false), true)); + } + + #[test] + fn with_the_cpu_chosen_the_gpu_backbone_is_never_built() { + let dir = empty_model("chosen"); + // candle loads on the CPU (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &placement(true, None, true), never).is_err()); + assert!(load(&dir, Device::Cpu, &placement(false, None, true), never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_gpu_backbone_loads_and_reports_where_it_runs() { + let dir = empty_model("gpu"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, fake_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + let b = backend(&shared); + assert_eq!( + (b.device.as_deref(), b.runtime.as_deref(), b.heads.as_deref(), b.fallback.as_deref()), + (Some("Fake GPU (Vulkan)"), Some("wgpu"), Some("CPU"), None) + ); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(812))); + assert_eq!(backend(&shared).encode_ms, Some(812)); + let json = serde_json::to_value(backend(&shared)).unwrap(); + assert_eq!(json["device"], "Fake GPU (Vulkan)"); + assert_eq!(json["encodeMs"], 812); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn with_the_gpu_switched_off_the_gpu_backbone_is_never_built() { + let dir = empty_model("off"); + let off = Placement::Cpu("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()); + // candle loads (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &off, never).is_err()); + assert!(load(&dir, Device::Cpu, &Placement::Best, never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_gpu_that_cannot_be_used_leaves_the_backbone_to_the_cpu() { + let dir = empty_model("nogpu"); + // without an adapter candle loads the backbone (failing here only for the empty checkpoint) + let e = load(&dir, Device::Cpu, &Placement::GpuBackbone, no_gpu).err().unwrap(); + assert!(!e.to_string().contains("no GPU adapter"), "{e}"); + // a GPU that fails on a photo: the CPU takes over, and the status says why + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + assert_eq!(backend(&shared).runtime.as_deref(), Some("wgpu")); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(1))); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_environment_switches_and_a_failed_gpu_keep_the_model_on_the_cpu_also_on_macos() { + // candle's GPU failed this session: the CPU, with the reason, wherever candle has a GPU or not + for best_is_cpu in [false, true] { + assert_eq!(wanted(best_is_cpu, false, Some("the GPU couldn't run it")), Placement::Cpu("the GPU couldn't run it".into())); + } + // the CPU chosen in Settings still says so + assert_eq!(wanted(false, true, Some("x")), Placement::Cpu(super::super::CPU_CHOSEN.into())); + // otherwise as `placement`, with the environment switches deciding for Metal too + let want = match lightcraft_gpu::env_off_reason() { + Some(why) => Placement::Cpu(why.into()), + None => Placement::Best, + }; + assert_eq!(wanted(false, false, None), want); + } + + /// Run `kinds` in turn on a worker where candle has a GPU (`metal`) or not, the CPU chosen or not; their outcomes. + fn run_kinds(metal: bool, cpu: bool, kinds: Vec) -> Vec { + let (tx, rx) = mpsc::channel(); + let (jtx, jrx) = mpsc::channel(); + let shared = Shared::default(); + shared.pending.store(kinds.len(), Ordering::SeqCst); + for kind in kinds { + let mut j = job(Tag::Wait, &tx); + j.kind = kind; + j.cpu = cpu; + jtx.send(j).unwrap(); + } + drop(jtx); + run(&jrx, &shared, Duration::from_secs(60), metal); + assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); + assert!(!shared.encoding.load(Ordering::SeqCst)); + rx.try_iter().collect() + } + + /// The tests of the CPU fallback assume the GPU isn't switched off in the environment (it never is tried then). + fn gpu_allowed() -> bool { + let ok = lightcraft_gpu::env_off_reason().is_none(); + if !ok { + lightcraft_testkit::skip!(Gpu, "the GPU is switched off in the environment"); + } + ok + } + + #[test] + fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { + if !gpu_allowed() { + return; + } + // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); + assert_eq!(out.len(), 2); + assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); + assert_eq!(out[1].notice, None, "said once"); + } + + #[test] + fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); + assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly"), "reported as before"); + assert_eq!(out[0].notice, None); + // the next job still starts on the GPU, fails there and works on the CPU + assert!(matches!(out[1].result, Ok(None))); + assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn missing_model_files_are_not_retried_on_the_cpu() { + let out = run_kinds(true, false, vec![Kind::Prepare]); + assert!(out[0].result.as_ref().unwrap_err().contains("not found")); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_worker_on_the_cpu_never_tries_the_gpu() { + // the CPU chosen in Settings, and a build where candle has no GPU + for (metal, cpu) in [(true, true), (false, true)] { + let out = run_kinds(metal, cpu, vec![Kind::FailOnGpu { panic: true }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice, None); + } + // no GPU path (not macOS): a failure is reported, not retried + let out = run_kinds(false, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(out[0].result.is_err()); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_cpu_model_kept_for_another_reason_shows_that_reason() { + let dir = empty_model("reason"); + let shared = Shared::default(); + let mut state = State::default(); + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // loaded with the CPU chosen (put there by hand: the empty checkpoint doesn't load) + state.placement = Some((chosen.clone(), true)); + shared.backend.lock().unwrap().fallback = Some(super::super::CPU_CHOSEN.into()); + // the choice goes back to Automatic while the CPU stays for another reason: the new reason shows (the reload + // that follows here is only because no model was in memory) + let why = "the GPU couldn't run it"; + let _ = model(&mut state, &shared, &dir, false, Some(why)); + assert_eq!(backend(&shared).fallback.as_deref(), Some(why)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_detail_pass_leaves_the_last_photos_times_alone() { + let dir = empty_model("detail"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + { + let mut b = shared.backend.lock().unwrap(); + (b.encode_ms, b.analyze_ms) = (Some(812), Some(900)); + } + // the zoomed-in region: the GPU fails on it, and the status says where the backbone runs now + let _ = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_detail(&shared, &m); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + assert_eq!((b.encode_ms, b.analyze_ms), (Some(812), Some(900)), "the last photo's times"); + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/crates/engine/src/tests_segment.rs b/crates/engine/src/tests_segment.rs index f4b9f4f484..f317ef8fd4 100644 --- a/crates/engine/src/tests_segment.rs +++ b/crates/engine/src/tests_segment.rs @@ -50,6 +50,17 @@ fn status_and_model_commands_without_the_model() { assert_eq!(st["installed"], false); assert_eq!(st["download"]["running"], false); assert!(st["license"].as_str().unwrap().contains("SAM License")); + // where it runs: nowhere yet (no model loaded), and nothing timed + if Segmenter::AVAILABLE { + let b = &st["backend"]; + assert!(b["device"].is_null() && b["encodeMs"].is_null() && b["analyzeMs"].is_null(), "{b}"); + // the GPU switches show before the model loads (macOS: Metal, which only the environment switches govern) + let off = if cfg!(target_os = "macos") { lightcraft_gpu::env_off_reason().map(str::to_string) } else { lightcraft_gpu::switched_off() }; + assert_eq!(b["fallback"].as_str(), off.as_deref(), "{b}"); + } else { + assert!(st["backend"].is_null()); + } + assert_eq!(st["runOn"], "auto"); // downloading needs the user's consent, and names the size and the licence let e = s.execute("segment.model.download", &json!({})).unwrap_err().to_string(); assert!(e.contains("acknowledged") && e.contains("SAM License") && e.contains("GB"), "{e}"); @@ -305,3 +316,37 @@ fn a_missing_model_is_model_missing_by_kind() { } } } + +/// Where SAM 3 runs is the user's choice (`segment.settings`), shown by `segment.model.status`, kept in the settings +/// file and read back by the next session; a bad value is refused and changes nothing. +#[test] +fn the_choice_of_where_ai_masks_run_is_kept() { + let dir = tmp("runon"); + let file = dir.join("models").join("sam3-settings.json"); + let mut s = Session::with_demo(); + s.segmenter.settings_file = Some(file.clone()); + assert_eq!(s.execute("segment.settings", &json!({})).unwrap()["runOn"], "auto"); + assert_eq!(s.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let st = s.execute("segment.model.status", &json!({})).unwrap(); + assert_eq!(st["runOn"], "cpu"); + if Segmenter::AVAILABLE { + assert_eq!(st["backend"]["fallback"], crate::segment::CPU_CHOSEN, "{st}"); + } + let e = s.execute("segment.settings", &json!({"runOn": "gpu"})).unwrap_err().to_string(); + assert!(e.contains("auto or cpu"), "{e}"); + assert_eq!(s.segmenter.run_on(), crate::segment::RunOn::Cpu); + let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved["runOn"], "cpu"); + // the next session reads it; a damaged file is Automatic + let mut again = Session::with_demo(); + again.segmenter.settings_file = Some(file.clone()); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Cpu); + std::fs::write(&file, b"{not json").unwrap(); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Auto); + // without a settings file the choice holds for the session + let mut memory = Session::with_demo(); + assert_eq!(memory.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7efae6a576..ec644df6e7 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -237,10 +237,11 @@ pub fn wait_idle(timeout: std::time::Duration) -> bool { } } -/// Why GPU compute that has a device of its own (denoise, faces) is switched off by the user's settings, or `None`: the -/// environment switches and the rendering preference, but not a render-device failure (the devices are separate). +/// Why GPU compute that has a device of its own (denoise, faces, SAM 3) is switched off by the user's settings, or +/// `None`: the environment switches and the rendering preference, but not a render-device failure (the devices are +/// separate). #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn switched_off() -> Option { +pub fn switched_off() -> Option { if let Some(why) = env_off_reason() { return Some(why.into()); } diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/examples/sam3_bench.rs b/crates/segment/examples/sam3_bench.rs index 982f482e96..a00ae556dd 100644 --- a/crates/segment/examples/sam3_bench.rs +++ b/crates/segment/examples/sam3_bench.rs @@ -1,25 +1,57 @@ //! Times SAM 3 on this machine (a synthetic gradient image; the first run includes compiling -//! the GPU kernels): `cargo run -p lightcraft-segment --release --example sam3_bench -- `. +//! the GPU kernels and loading the heads): `cargo run -p lightcraft-segment --release --example +//! sam3_bench -- `. Each run times the backbone, the click features (tracker neck), +//! a first and a further click, and a first and a second description of the same image (the +//! first one computes the detector's features). + +use std::time::{Duration, Instant}; + +fn ms(d: Duration) -> String { + format!("{:.0} ms", d.as_secs_f64() * 1e3) +} fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); - let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench ")?); - let t = std::time::Instant::now(); + let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench [runs]")?); + let runs: usize = args.next().map(|s| s.parse()).transpose()?.unwrap_or(3); + let t = Instant::now(); let mut model = lightcraft_segment::Sam3::load(&dir)?; - eprintln!("load: {:?} on {:?}", t.elapsed(), model.device()); + eprintln!("load: {} on {}", ms(t.elapsed()), model.backbone_device()); let (w, h) = (1200, 800); let rgb: Vec = (0..w * h * 3).map(|i| ((i / 3 % w) * 255 / w) as u8).collect(); - for run in 0..3 { - let t = std::time::Instant::now(); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs { + let t = Instant::now(); let mut enc = model.encode(&rgb, w, h)?; lightcraft_segment::sync(&model)?; - let e = t.elapsed(); - let t = std::time::Instant::now(); - let p = model.segment_clicks(&mut enc, &[lightcraft_segment::Click { x: 0.5, y: 0.5, positive: true }])?; - let c = t.elapsed(); - let t = std::time::Instant::now(); + let encode = t.elapsed(); + let t = Instant::now(); + model.prepare_clicks(&mut enc)?; + lightcraft_segment::sync(&model)?; + let features = t.elapsed(); + let t = Instant::now(); + let p = model.segment_clicks(&mut enc, &[click(0.5, 0.5)])?; + let click1 = t.elapsed(); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5), click(0.3, 0.6)])?; + let click2 = t.elapsed(); + let t = Instant::now(); let d = model.segment_text(&mut enc, "sky", 0.5)?; - eprintln!("run {run}: encode {e:?}, click {c:?} (score {:.2}), text {:?} ({})", p.score, t.elapsed(), d.is_some()); + let text1 = t.elapsed(); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5)?; + let text2 = t.elapsed(); + eprintln!( + "run {run}: encode {}, click features {}, click {} (score {:.2}), further click {}, first describe {} ({}), second describe {}", + ms(encode), + ms(features), + ms(click1), + p.score, + ms(click2), + ms(text1), + d.is_some(), + ms(text2) + ); } Ok(()) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..64827840ce --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,147 @@ +//! Fused CPU kernels for the model's elementwise work. +//! +//! On the CPU, candle runs bias adds, activations, broadcasts and layout copies one element at a +//! time on one thread. The kernels do the same arithmetic in the same order (bit-identical +//! results), fused into fewer passes over memory and spread over the rayon pool that candle's +//! matrix products use. + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp2, D, Layout, Shape, Tensor, bail}; +use candle_nn::Linear; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::Module; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + #[test] + fn linear_act_matches_the_tensor_ops() { + let x = randn(&[2, 7, 5]); + let l = Linear::new(randn(&[6, 5]), Some(randn(&[6]))); + for gelu in [false, true] { + let want = l.forward(&x).unwrap(); + let want = if gelu { want.gelu_erf() } else { want.relu() }.unwrap().reshape((14, 6)).unwrap(); + let got = linear_act(&x, &l, gelu).unwrap(); + assert_eq!(got.dims(), want.dims()); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } + assert!(linear_act(&x, &Linear::new(randn(&[6, 5]), None), false).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + let got = box_bias(&ey, &ex).unwrap(); + assert_eq!(got.dims(), want.dims()); + // the same additions: bit-identical + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + assert!(box_bias(&ey, &randn(&[4, 6, 3])).is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index c302aafe76..edb8557dff 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -6,18 +6,24 @@ //! the Python/PyTorch SAM 3 code of Hugging Face Transformers (`models/sam3/modeling_sam3.py`), Copyright The HuggingFace //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. +use std::collections::VecDeque; +use std::sync::{Mutex, OnceLock, PoisonError}; + use candle_core::{D, Device, IndexOp, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::{BackboneAccel, Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; const QUERIES: usize = 200; const LAYERS: usize = 6; +/// Prompts whose text features are kept: they don't depend on the image, and the same few come back (Subject's +/// "person" on every photo). 32 KB each. +const TEXT_CACHE: usize = 16; /// Detector image features, computed once per image. pub struct Features { @@ -44,6 +50,17 @@ pub struct Output { /// Semantic logits `[288, 288]` flattened: everything the prompt names, one mask without /// boundaries between instances. pub semantic: Vec, + /// The DETR encoder's memory `[1, 5184, 256]` (tests). + pub memory: Tensor, +} + +/// Where the DETR encoder and the mask decoder may run outside candle: the model's accelerator (if it still has one), +/// and why the encoder (`failed`) or the mask decoder (`masks_failed`) stopped running there (set on its first failure; +/// from then on candle runs it). +pub struct EncoderAccel<'a> { + pub accel: &'a Mutex>>, + pub failed: &'a OnceLock, + pub masks_failed: &'a OnceLock, } struct EncoderLayer { @@ -71,6 +88,8 @@ pub struct Detector { neck: Neck, text: TextEncoder, text_proj: Linear, + /// The latest prompts' token ids and valid marks with their features `[1, 32, 256]`, most recent last. + texts: Mutex, Vec, Tensor)>>, encoder: Vec, decoder: Vec, out_ln: LayerNorm, @@ -138,6 +157,7 @@ impl Detector { neck: Neck::new(vb.pp("vision_encoder.neck"))?, text: TextEncoder::new(vb.pp("text_encoder.text_model"))?, text_proj: linear(1024, HIDDEN, vb.pp("text_projection"))?, + texts: Mutex::new(VecDeque::with_capacity(TEXT_CACHE)), encoder, decoder, out_ln: ln(HIDDEN, TORCH_LN_EPS, d.pp("output_layer_norm"))?, @@ -164,9 +184,13 @@ impl Detector { }) } - /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`. - pub fn features(&self, backbone: &Tensor) -> Result { - let levels = self.neck.forward(backbone, 3)?; + /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`, or from its neck's three + /// levels when they were computed elsewhere (an accelerator). + pub fn features(&self, backbone: &Tensor, levels: Option>) -> Result { + let levels = match levels { + Some(levels) => levels, + None => self.neck.forward(backbone, 3)?, + }; let last = levels.last().ok_or_else(|| Error::Model("detector neck".into()))?; let (_, _, side, _) = last.dims4()?; let flat = last.flatten_from(2)?.transpose(1, 2)?.contiguous()?; @@ -174,6 +198,23 @@ impl Detector { Ok(Features { levels, flat, pos, side }) } + /// The prompt's features `[1, 32, 256]`: the CLIP text encoder and its projection, or the same tensor again + /// when the prompt was among the last [`TEXT_CACHE`]. + fn text_features(&self, ids: &[u32], valid: &[bool]) -> Result { + let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(seen) = texts.iter().position(|(i, v, _)| i == ids && v == valid).and_then(|at| texts.remove(at)) { + let text = seen.2.clone(); + texts.push_back(seen); + return Ok(text); + } + let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; + if texts.len() >= TEXT_CACHE { + texts.pop_front(); + } + texts.push_back((ids.to_vec(), valid.to_vec(), text.clone())); + Ok(text) + } + /// Box relative-position bias `[1, heads, 1 + 200, side²]` for reference boxes (cx, cy, w, h). fn rpb(&self, boxes: &Tensor, side: usize) -> Result { let xyxy = cxcywh_to_xyxy(boxes)?.squeeze(0)?; // [200, 4] @@ -188,6 +229,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -208,23 +252,143 @@ impl Detector { Ok(Tensor::cat(&[one(1)?, one(0)?, one(2)?, one(3)?], D::Minus1)?) } - /// Run the detector for one tokenized prompt. - pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool]) -> Result { - let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; // [1, 32, 256] - let text_bias = padding_bias(valid, &self.device)?; - - // DETR encoder: image tokens attend to themselves and to the prompt + /// The DETR encoder: image tokens attend to themselves and to the prompt. Returns the memory `[1, 5184, 256]`. + fn encode(&self, f: &Features, text: &Tensor, text_bias: &Tensor) -> Result { let mut x = f.flat.clone(); for l in &self.encoder { let h = l.ln1.forward(&x)?; let hp = (&h + &f.pos)?; x = (&x + l.self_attn.forward(&hp, &hp, &h, None)?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; + x = (&x + l.cross_attn.forward(&h, text, text, Some(text_bias))?)?; let h = l.ln3.forward(&x)?; x = (&x + l.mlp.forward(&h)?)?; } - let memory = x; + Ok(x) + } + + /// [`Detector::encode`] on the accelerator; `None` when there is none, or it doesn't run the encoder or fails (the + /// first failure is logged and noted in `accel.failed`, and the accelerator isn't asked again). `Err` when the app is + /// closing. + fn encode_accelerated(&self, f: &Features, text: &Tensor, valid: &[bool], accel: &EncoderAccel) -> Result> { + if accel.failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_detr_encoder()) else { return Ok(None) }; + let image = to_vec(&f.flat)?; + let want = image.len(); + // what the decoder can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.detr_encoder(&image, &to_vec(&f.pos)?, &to_vec(text)?, valid).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => Ok(Some(Tensor::from_vec(out, f.flat.dims(), &self.device)?)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 DETR encoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// The mask decoder in candle: the per-query mask logits `[200, 288, 288]` for the encoder memory and the mask + /// embeddings `e` `[1, 200, 256]`. + fn masks(&self, f: &Features, memory: &Tensor, text: &Tensor, text_bias: &Tensor, e: &Tensor) -> Result<(Tensor, Vec)> { + // the encoder memory attends to the prompt, then a pixel decoder up to 288² + let mem = (memory + self.prompt_attn.forward(&self.prompt_ln.forward(memory)?, text, text, Some(text_bias))?)?; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; + for (i, skip) in [l1, l0].into_iter().enumerate() { + let (_, _, sh, sw) = skip.dims4()?; + prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; + let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { + return Err(Error::Model("pixel decoder".into())); + }; + prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + } + let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] + let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; + let (_, c, mh, mw) = inst.dims4()?; + Ok((e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?, semantic)) + } + + /// [`Detector::masks`] on the accelerator (the semantic mask as one more row of the same product); `None` when there + /// is none, or it doesn't run the mask decoder or fails + /// (the first failure is logged and noted in `accel.masks_failed`, and the accelerator isn't asked again). `Err` when + /// the app is closing. + fn masks_accelerated( + &self, + f: &Features, + memory: &Tensor, + (text, valid): (&Tensor, &[bool]), + e: &Tensor, + accel: &EncoderAccel, + ) -> Result)>> { + if accel.masks_failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_mask_decoder()) else { return Ok(None) }; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let (_, _, mh, mw) = l0.dims4()?; + // the instance projection folded into the embeddings: e · (W x + b) = (e W) x + e b, one product per pixel + let e = e.squeeze(0)?; // [200, 256] + let rows = e.matmul(&self.instance_proj.weight().reshape((HIDDEN, HIDDEN))?)?; + let mut bias = match self.instance_proj.bias() { + Some(b) => to_vec(&e.matmul(&b.unsqueeze(1)?)?)?, + None => vec![0.0; QUERIES], + }; + // the semantic projection (1 × 1, 256 → 1) is one more row: the last mask is the semantic one + let rows = Tensor::cat(&[rows, self.semantic_proj.weight().reshape((1, HIDDEN))?], 0)?; + bias.push(match self.semantic_proj.bias() { + Some(b) => to_vec(b)?.first().copied().unwrap_or(0.0), + None => 0.0, + }); + let want = (QUERIES + 1) * mh * mw; + // what the masks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.mask_decoder(&to_vec(memory)?, &to_vec(text)?, valid, [&to_vec(l1)?, &to_vec(l0)?], &to_vec(&rows)?, &bias).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + // without short-cutting, so that it vectorizes (17 M values) + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(mut out) => { + let semantic = out.split_off(QUERIES * mh * mw); + Ok(Some((Tensor::from_vec(out, (QUERIES, mh, mw), &self.device)?, semantic))) + } + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 mask decoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.masks_failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// Run the detector for one tokenized prompt, the DETR encoder and the mask decoder on `accel` when it runs them. + pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool], accel: &EncoderAccel) -> Result { + let text = self.text_features(ids, valid)?; + let text_bias = padding_bias(valid, &self.device)?; + + let memory = match self.encode_accelerated(f, &text, valid, accel)? { + Some(memory) => memory, + None => self.encode(f, &text, &text_bias)?, + }; // DETR decoder: presence token + 200 queries with iterative box refinement let mut boxes = candle_nn::ops::sigmoid(&self.reference_points)?; @@ -260,21 +424,7 @@ impl Detector { let pq = self.score_query_proj.forward(&queries)?; // [1, 200, 256] let logits = (pq.matmul(&pt.unsqueeze(2)?)? / (HIDDEN as f64).sqrt())?.clamp(-12f32, 12f32)?; - // masks: the encoder memory attends to the prompt, then a pixel decoder up to 288² - let mem = (&memory + self.prompt_attn.forward(&self.prompt_ln.forward(&memory)?, &text, &text, Some(&text_bias))?)?; - let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; - let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; - for (i, skip) in [l1, l0].into_iter().enumerate() { - let (_, _, sh, sw) = skip.dims4()?; - prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; - let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { - return Err(Error::Model("pixel decoder".into())); - }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; - } - let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] - let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; - let (_, c, mh, mw) = inst.dims4()?; + // masks: each query's mask embedding against the mask decoder's per-pixel output let mut e = queries.clone(); for (i, l) in self.mask_embedder.iter().enumerate() { e = l.forward(&e)?; @@ -282,7 +432,10 @@ impl Detector { e = e.relu()?; } } - let masks = e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?; + let (masks, semantic) = match self.masks_accelerated(f, &memory, (&text, valid), &e, accel)? { + Some(masks) => masks, + None => self.masks(f, &memory, &text, &text_bias, &e)?, + }; let boxes = cxcywh_to_xyxy(&boxes)?; let bv = to_vec(&boxes)?; Ok(Output { @@ -292,6 +445,7 @@ impl Detector { boxes: bv.as_chunks::<4>().0.to_vec(), text, semantic, + memory, }) } } @@ -335,7 +489,89 @@ pub fn merge(out: &Output, threshold: f32) -> Option { #[cfg(test)] mod tests { + use std::path::PathBuf; + use super::*; + use crate::Sam3; + + /// The real checkpoint in `$LIGHTCRAFT_SAM3_DIR` (as the GPU tests), or `None` (the test skips) without it or when it + /// doesn't load. + fn model() -> Option { + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + if !crate::is_model_dir(&dir) { + return None; + } + match Sam3::load_on(&dir, Device::Cpu) { + Ok(m) => Some(m), + Err(e) => { + eprintln!("the model in {} doesn't load: {e}", dir.display()); + None + } + } + } + + fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() + } + + #[test] + fn the_box_bias_matches_the_tensor_ops_on_random_boxes() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, _, _) = m.detector_parts().unwrap(); + let side = 72; + for _ in 0..3 { + let centres = Tensor::rand(0f32, 1.0, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let sizes = Tensor::rand(0.01f32, 0.6, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let boxes = Tensor::cat(&[centres, sizes], 2).unwrap(); + let got = det.rpb(&boxes, side).unwrap(); + // what the other devices run, from the same row and column terms + let xyxy = cxcywh_to_xyxy(&boxes).unwrap().squeeze(0).unwrap(); + let coords = Tensor::arange(0u32, side as u32, &Device::Cpu).unwrap().to_dtype(candle_core::DType::F32).unwrap(); + let coords = coords.affine(1.0 / side as f64, 0.0).unwrap().reshape((1, side, 1)).unwrap(); + let term = |mlp: &DecoderMlp, a: usize, b: usize| { + let pick = Tensor::cat(&[xyxy.narrow(1, a, 1).unwrap(), xyxy.narrow(1, b, 1).unwrap()], 1).unwrap().unsqueeze(1).unwrap(); + let d = (coords.broadcast_sub(&pick).unwrap() * 8.0).unwrap(); + let d = d.sign().unwrap().mul(&((d.abs().unwrap() + 1.0).unwrap().log().unwrap() / 8f64.ln()).unwrap()).unwrap(); + mlp.forward(&d).unwrap() + }; + let (ey, ex) = (term(&det.rpb_y, 1, 3), term(&det.rpb_x, 0, 2)); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((QUERIES, side * side, HEADS)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap(); + assert_eq!(got.dims(), [1, HEADS, 1 + QUERIES, side * side]); + assert_eq!(values(&got), values(&want)); + } + } + + #[test] + fn prompt_features_are_kept_for_the_latest_prompts() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, tok, _) = m.detector_parts().unwrap(); + let prompts: Vec<(Vec, Vec)> = (0..=TEXT_CACHE).map(|i| tok.encode(&format!("{i} people"))).collect(); + let features = |i: usize| det.text_features(&prompts[i].0, &prompts[i].1).unwrap(); + let first = features(0); + let fresh = det.text_proj.forward(&det.text.forward(&prompts[0].0, &prompts[0].1).unwrap()).unwrap(); + assert_eq!(values(&first), values(&fresh)); + // the same tensor again, also after other prompts + assert_eq!(features(0).id(), first.id()); + let second = features(1); + for i in 2..TEXT_CACHE { + features(i); + } + assert_eq!(features(0).id(), first.id(), "prompt 0 is the latest one now"); + // one more prompt drops the least recently used, prompt 1, which is computed again + features(TEXT_CACHE); + assert_eq!(det.texts.lock().unwrap().len(), TEXT_CACHE); + assert_eq!(features(0).id(), first.id()); + let again = features(1); + assert_ne!(again.id(), second.id()); + assert_eq!(values(&again), values(&second)); + } /// Two people side by side on a row of cells, each only weakly sure of themself and both fading where /// they touch; the semantic mask is sure of both and runs across. Each takes the semantic logits where @@ -376,6 +612,7 @@ mod tests { boxes: vec![[0.0; 4]; 3], text: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), semantic: semantic.to_vec(), + memory: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), }; let semantic = [5.0, 6.0, 4.0, 6.0, 5.0]; let merged = merge(&output([4.0, 4.0, -6.0], &semantic), 0.5).unwrap(); diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6c24d0836f..959232edf4 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -8,9 +8,14 @@ //! The expensive part, the 32-layer ViT over the 1008 × 1008 input, runs once per image //! ([`Sam3::encode`]); each click or prompt then reuses the [`Encoded`] features. //! -//! On macOS the model runs on the GPU through Metal; elsewhere (for now) on the CPU. The -//! weights are not part of LightCraft: they are the `facebook/sam3` checkpoint (SAM License), -//! read from a directory the user downloads them to ([`Sam3::load`]). +//! On macOS the model runs on the GPU through Metal ([`Sam3::load`]). Elsewhere candle runs on +//! the CPU, and the backbone, most of the work, can run outside candle on an accelerator, with +//! the two necks after it ([`BackboneAccel`]: `lightcraft-gpu`'s wgpu kernels on Vulkan / DX12, loaded with +//! [`Sam3::load_accelerated`]); when that can't be built or fails on a photo, the candle backbone +//! takes over ([`Sam3::backbone_fallback`] says why; not while the app is closing: [`BackboneAccel::closing`]). +//! The accelerator can also run the text detector's DETR encoder (else, or once it fails, candle does: +//! [`Sam3::detr_fallback`]). The weights are not part of LightCraft: they are the `facebook/sam3` checkpoint +//! (SAM License), read from a directory the user downloads them to. //! //! Ported from the Hugging Face `transformers` implementation (Apache-2.0); see `NOTICE`. //! This crate is therefore licensed under the Apache License 2.0 only (not the MIT option of @@ -29,6 +34,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; @@ -49,13 +56,15 @@ mod weights; use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; #[cfg(not(target_arch = "wasm32"))] -use candle_core::{DType, Device, Tensor}; +use candle_core::{DType, Tensor}; #[cfg(not(target_arch = "wasm32"))] use candle_nn::VarBuilder; +#[cfg(not(target_arch = "wasm32"))] +pub use candle_core::Device; #[cfg(not(target_arch = "wasm32"))] pub use tracker::Click; @@ -103,12 +112,135 @@ pub fn best_device() -> Device { } #[cfg(not(target_arch = "wasm32"))] -/// A loaded model. The vision backbone loads with it; the point and text heads load on first use. +/// Where the backbone's weights are in the checkpoint. +pub const BACKBONE_PREFIX: &str = "detector_model.vision_encoder.backbone"; + +#[cfg(not(target_arch = "wasm32"))] +/// The vision backbone run outside candle (the wgpu compute kernels of `lightcraft-gpu` on +/// Vulkan / DX12 / Metal). It computes what the candle ViT computes, so everything after the +/// backbone (necks, heads) stays as it is. +pub trait BackboneAccel: Send + Sync { + /// `pixels`: `[3, 1008, 1008]` (CHW, normalized to −1..1). Returns the backbone output + /// `[1024, 72, 72]` (CHW), as the candle ViT's `[1, 1024, 72, 72]` without the batch. + fn forward(&self, pixels: &[f32]) -> std::result::Result, String>; + /// What it runs on, for logs and Settings (e.g. "NVIDIA GeForce RTX 5070 (Vulkan)"). + fn device(&self) -> String; + + /// Whether the app is closing, so that an `Err` from it is no failure of the accelerator: it stays in use, and the + /// work ends with that error instead of running in candle (no CPU inference while the app quits). + fn closing(&self) -> bool { + false + } + + /// Whether it runs the necks ([`BackboneAccel::neck`]); when not, they are never asked for and run in candle. + fn runs_necks(&self) -> bool { + false + } + + /// Whether it runs the text detector's DETR encoder ([`BackboneAccel::detr_encoder`]); when not, candle does. + fn runs_detr_encoder(&self) -> bool { + false + } + + /// Whether it runs the text detector's mask decoder ([`BackboneAccel::mask_decoder`]); when not, candle does. + fn runs_mask_decoder(&self) -> bool { + false + } + + /// The feature pyramid of the `which` neck for a backbone output `[1024, 72, 72]` (CHW): the + /// `n` finest levels, each `[256, s, s]` (CHW; s = 288, 144, 72, 36), as the candle `Neck::forward`. + /// `Err` when this accelerator doesn't run it (the candle neck runs instead). + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + let _ = (which, backbone, n); + Err("no neck on this accelerator".into()) + } + + /// The detector's DETR encoder (6 layers): the image tokens `[5184, 256]` with their sine + /// position encoding `pos` `[5184, 256]` attend to themselves and to the prompt `text` + /// `[32, 256]` (`valid` marks its real tokens). Returns the encoder memory `[5184, 256]`. + /// `Err` when this accelerator doesn't run it (the candle encoder runs instead). + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> std::result::Result, String> { + let _ = (image, pos, text, valid); + Err("no DETR encoder on this accelerator".into()) + } + + /// The detector's mask decoder: the encoder memory `[5184, 256]` attends to the prompt `text` `[32, 256]` (`valid` + /// marks its real tokens) and is added to it, the pixel decoder brings that up to 288² with the detector neck's + /// `levels` `[256, 144, 144]` and `[256, 288, 288]` (CHW), and each of the `rows` `[r, 256]` (1 ≤ r ≤ 256, with + /// `bias` `[r]`) is a 1 × 1 projection of its output. Returns `[r, 288, 288]` (the detector passes its mask + /// embeddings with the instance projection folded in: the per-query mask logits). `Err` when this accelerator + /// doesn't run it (the candle decoder runs instead). + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> std::result::Result, String> { + let _ = (memory, text, valid, levels, rows, bias); + Err("no mask decoder on this accelerator".into()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// The two feature pyramids of the checkpoint. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NeckKind { + /// `tracker_neck`: the click decoder's (3 levels). + Tracker, + /// `detector_model.vision_encoder.neck`: the text detector's (3 levels). + Detector, +} + +#[cfg(not(target_arch = "wasm32"))] +/// Read access to a checkpoint's tensors (for accelerators that upload weights themselves; +/// cloning shares the open file, so an accelerator can keep one and load more layers later). +#[derive(Clone)] +pub struct WeightReader(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl WeightReader { + /// The checkpoint in a model directory (see [`is_model_dir`]). + pub fn open(dir: &Path) -> Result { + if !is_model_dir(dir) { + return Err(Error::Missing(dir.to_path_buf())); + } + Ok(Self(weights::Weights::open(&dir.join(WEIGHTS_FILE))?)) + } + + /// The stored shape of `name`, without reading its data. + pub fn shape(&self, name: &str) -> Option> { + self.0.shape(name).map(<[usize]>::to_vec) + } + + /// Tensor `name`: its shape and its values (f32, row-major). + pub fn read(&self, name: &str) -> Result<(Vec, Vec)> { + let t = self.0.read(name)?; + Ok((t.dims().to_vec(), t.flatten_all()?.to_vec1::()?)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A loaded model. The vision backbone loads with it (unless an accelerator runs it); the point +/// and text heads load on first use. pub struct Sam3 { dir: PathBuf, device: Device, weights: Arc, - backbone: vit::Vit, + /// The candle backbone: loaded with the model, or only when an accelerator fails. + backbone: OnceLock, + accel: Mutex>>, + /// Why the accelerator `load_accelerated` was given is not (or no longer) used. + fallback: Mutex>, + /// Why the DETR encoder runs in candle although there is an accelerator (it failed there once). + detr_fallback: OnceLock, + /// The same for the text detector's mask decoder. + mask_fallback: OnceLock, + /// The necks the accelerator failed on: candle runs them from then on. + necks_off: Mutex>, + /// The candle tracker neck: loaded on first use, unless the accelerator runs it. tracker_neck: Option, tracker: Option, detector: Option, @@ -149,8 +281,123 @@ impl Sam3 { return Err(Error::Missing(dir.to_path_buf())); } let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?; - let backbone = vit::Vit::new(Self::vb(&weights, &device).pp("detector_model.vision_encoder.backbone"))?; - Ok(Self { dir: dir.to_path_buf(), device, weights, backbone, tracker_neck: None, tracker: None, detector: None, tokenizer: None }) + let model = Self::unloaded(dir, device, weights, None); + model.candle_backbone()?; + Ok(model) + } + + /// Load with the backbone on an accelerator `make` builds from the checkpoint, and the rest + /// on `device`. When `make` fails the candle backbone loads instead, and when the + /// accelerator fails later, [`Sam3::encode`] falls back to it (logged, not an error), unless the app is closing. + pub fn load_accelerated( + dir: &Path, + device: Device, + make: impl FnOnce(&WeightReader) -> std::result::Result, String>, + ) -> Result { + let reader = WeightReader::open(dir)?; + match make(&reader) { + Ok(accel) => { + log::info!("SAM 3 backbone on {}", accel.device()); + Ok(Self::unloaded(dir, device, reader.0, Some(accel))) + } + Err(e) => { + log::warn!("SAM 3 backbone accelerator unavailable ({e}); using the {}", device_name(&device)); + let model = Self::unloaded(dir, device, reader.0, None); + *model.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(e); + model.candle_backbone()?; + Ok(model) + } + } + } + + fn unloaded(dir: &Path, device: Device, weights: Arc, accel: Option>) -> Self { + Self { + dir: dir.to_path_buf(), + device, + weights, + backbone: OnceLock::new(), + accel: Mutex::new(accel), + fallback: Mutex::new(None), + detr_fallback: OnceLock::new(), + mask_fallback: OnceLock::new(), + necks_off: Mutex::new(Vec::new()), + tracker_neck: None, + tracker: None, + detector: None, + tokenizer: None, + } + } + + /// The candle backbone, loading it on first use. + fn candle_backbone(&self) -> Result<&vit::Vit> { + if let Some(b) = self.backbone.get() { + return Ok(b); + } + let b = vit::Vit::new(Self::vb(&self.weights, &self.device).pp(BACKBONE_PREFIX))?; + Ok(self.backbone.get_or_init(|| b)) + } + + /// What the backbone runs on: the accelerator's device, else the candle device ("CPU", "Metal GPU"). + pub fn backbone_device(&self) -> String { + match &*self.accel.lock().unwrap_or_else(PoisonError::into_inner) { + Some(a) => a.device(), + None => device_name(&self.device), + } + } + + /// Whether the backbone runs on the accelerator (rather than in candle). + pub fn accelerated(&self) -> bool { + self.accel.lock().unwrap_or_else(PoisonError::into_inner).is_some() + } + + /// Why the backbone runs in candle although an accelerator was offered: it could not be built, or it failed on + /// a photo (from then on the model stays in candle). `None` when there is no such reason. + pub fn backbone_fallback(&self) -> Option { + self.fallback.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + /// Why the text detector's DETR encoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn detr_fallback(&self) -> Option { + self.detr_fallback.get().cloned() + } + + /// Why the text detector's mask decoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn mask_fallback(&self) -> Option { + self.mask_fallback.get().cloned() + } + + /// What runs everything after the backbone: the model's device, and which of those parts the accelerator runs + /// (e.g. "CPU; the necks, the DETR encoder and the mask decoder on the GPU"). + pub fn heads_device(&self) -> String { + let base = device_name(&self.device); + // what the accelerator runs (none: there is none any more), less what failed on it + let (necks, detr, masks) = match self.accel.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { + Some(a) => (a.runs_necks(), a.runs_detr_encoder(), a.runs_mask_decoder()), + None => (false, false, false), + }; + let mut gpu = Vec::new(); + if necks { + let off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + match (off.contains(&NeckKind::Tracker), off.contains(&NeckKind::Detector)) { + (false, false) => gpu.push("the necks"), + (false, true) => gpu.push("the click neck"), + (true, false) => gpu.push("the text neck"), + (true, true) => {} + } + } + if detr && self.detr_fallback.get().is_none() { + gpu.push("the DETR encoder"); + } + if masks && self.mask_fallback.get().is_none() { + gpu.push("the mask decoder"); + } + match gpu.split_last() { + None => base, + Some((last, [])) => format!("{base}; {last} on the GPU"), + Some((last, rest)) => format!("{base}; {} and {last} on the GPU", rest.join(", ")), + } } fn vb<'a>(w: &Arc, device: &Device) -> VarBuilder<'a> { @@ -171,30 +418,133 @@ impl Sam3 { /// Run the backbone on preprocessed pixels `[1, 3, 1008, 1008]` (−1..1). pub fn encode_pixels(&self, pixels: &Tensor) -> Result { - Ok(Encoded { backbone: self.backbone.forward(&pixels.to_device(&self.device)?)?, tracker: None, detector: None }) + let side = vit::GRID; + { + let mut accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(a) = accel.as_ref() { + let px = pixels.to_device(&Device::Cpu)?.flatten_all()?.to_vec1::()?; + // what the necks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let want = vit::HIDDEN * side * side; + let checked = a.forward(&px).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => { + let backbone = Tensor::from_vec(out, (1, vit::HIDDEN, side, side), &self.device)?; + return Ok(Encoded { backbone, tracker: None, detector: None }); + } + Err(e) if a.closing() => return Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 backbone failed on {} ({e}); using the {} from now on", a.device(), device_name(&self.device)); + *self.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(format!("{} failed: {e}", a.device())); + *accel = None; + } + } + } + } + let backbone = self.candle_backbone()?.forward(&pixels.to_device(&self.device)?)?; + Ok(Encoded { backbone, tracker: None, detector: None }) } - fn tracker_parts(&mut self) -> Result<(&neck::Neck, &tracker::Tracker)> { - if self.tracker_neck.is_none() { - self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + /// The `n` finest levels of the `which` neck for `backbone`, computed by the accelerator and put on the model's + /// device; `None` when there is no accelerator, it doesn't run this neck or failed on it (logged once; candle + /// runs that neck from then on). `Err` when the app is closing. + fn accel_neck(&self, which: NeckKind, backbone: &Tensor, n: usize) -> Result>> { + let accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: the necks run in candle, and that is no failure + let Some(a) = accel.as_ref().filter(|a| a.runs_necks()) else { return Ok(None) }; + let mut off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + if off.contains(&which) { + return Ok(None); } + let run = || -> std::result::Result, String> { + let x = backbone.to_device(&Device::Cpu).and_then(|t| t.flatten_all()).and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let levels = a.neck(which, &x, n)?; + if levels.len() != n { + return Err(format!("it returned {} levels instead of {n}", levels.len())); + } + levels + .into_iter() + .enumerate() + .map(|(i, l)| { + // what the heads can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let side = tracker::LOW_RES >> i; + if l.len() != neck::FPN * side * side { + return Err(format!("it returned {} values for level {i} instead of {}", l.len(), neck::FPN * side * side)); + } + // without short-cutting, so that it vectorizes (28 M values) + if !l.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("it returned values that are not numbers".into()); + } + Tensor::from_vec(l, (1, neck::FPN, side, side), &self.device).map_err(|e| e.to_string()) + }) + .collect() + }; + match run() { + Ok(levels) => Ok(Some(levels)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + let name = match which { + NeckKind::Tracker => "tracker", + NeckKind::Detector => "detector", + }; + log::warn!("SAM 3 {name} neck failed on {} ({e}); using the {} for it from now on", a.device(), device_name(&self.device)); + off.push(which); + Ok(None) + } + } + } + + fn tracker(&mut self) -> Result<&tracker::Tracker> { if self.tracker.is_none() { self.tracker = Some(tracker::Tracker::new(Self::vb(&self.weights, &self.device).pp("tracker_model"))?); } - match (&self.tracker_neck, &self.tracker) { - (Some(n), Some(t)) => Ok((n, t)), - _ => Err(Error::Model("tracker failed to load".into())), + self.tracker.as_ref().ok_or_else(|| Error::Model("tracker failed to load".into())) + } + + /// The click decoder's features for `enc`, once: the tracker neck on the accelerator when it runs it, else in + /// candle. + fn tracker_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.tracker.is_some() { + return Ok(()); } + let levels = match self.accel_neck(NeckKind::Tracker, &enc.backbone, 3)? { + Some(levels) => levels, + None => { + if self.tracker_neck.is_none() { + self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + } + let neck = self.tracker_neck.as_ref().ok_or_else(|| Error::Model("tracker neck failed to load".into()))?; + neck.forward(&enc.backbone, 3)? + } + }; + enc.tracker = Some(self.tracker()?.features(&levels)?); + Ok(()) + } + + /// The `which` neck's three finest levels for `enc`, each `[1, 256, s, s]` (tests and tools): on the + /// accelerator when it runs it, else in candle. + pub fn neck_levels(&self, which: NeckKind, enc: &Encoded) -> Result> { + if let Some(levels) = self.accel_neck(which, &enc.backbone, 3)? { + return Ok(levels); + } + let prefix = match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + }; + neck::Neck::new(Self::vb(&self.weights, &self.device).pp(prefix))?.forward(&enc.backbone, 3) } /// Compute the click decoder's features for `enc` now (so the first click is fast). pub fn prepare_clicks(&mut self, enc: &mut Encoded) -> Result<()> { - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } - Ok(()) + self.tracker()?; + self.tracker_features(enc) } /// Segment one object from clicks (positions normalized to the image, 0..1). @@ -202,18 +552,15 @@ impl Sam3 { if clicks.is_empty() { return Err(Error::Model("no clicks".into())); } - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } + self.tracker_features(enc)?; + let tracker = self.tracker()?; let f = enc.tracker.as_ref().ok_or_else(|| Error::Model("tracker features".into()))?; // one click: SAM's three alternatives, best by predicted IoU; more: the single mask let p = tracker.predict(f, clicks, clicks.len() == 1)?; Ok(Prediction { logits: p.logits, score: p.iou * sigmoid(p.object_score) }) } - fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer)> { + fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer, detector::EncoderAccel<'_>)> { if self.detector.is_none() { self.detector = Some(detector::Detector::new(Self::vb(&self.weights, &self.device).pp("detector_model"))?); } @@ -221,34 +568,42 @@ impl Sam3 { self.tokenizer = Some(tokenizer::Tokenizer::load(&self.dir)?); } match (&self.detector, &self.tokenizer) { - (Some(d), Some(t)) => Ok((d, t)), + (Some(d), Some(t)) => { + Ok((d, t, detector::EncoderAccel { accel: &self.accel, failed: &self.detr_fallback, masks_failed: &self.mask_fallback })) + } _ => Err(Error::Model("detector failed to load".into())), } } + /// The detector's features for `enc`, once: its neck on the accelerator when it runs it, else in candle. + fn detector_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.detector.is_none() { + let levels = self.accel_neck(NeckKind::Detector, &enc.backbone, 3)?; + let (det, _, _) = self.detector_parts()?; + enc.detector = Some(det.features(&enc.backbone, levels)?); + } + Ok(()) + } + /// Segment every instance of the concept `text` names. Instances scoring above /// `threshold` (0..1, 0.5 is the reference default) are merged into one mask; `None` when /// nothing matches. pub fn segment_text(&mut self, enc: &mut Encoded, text: &str, threshold: f32) -> Result> { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - let out = det.predict(f, &ids, &valid)?; + let out = det.predict(f, &ids, &valid, &accel)?; Ok(detector::merge(&out, threshold)) } /// Raw detector outputs for `text` (tests and tools). pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - det.predict(f, &ids, &valid) + det.predict(f, &ids, &valid, &accel) } } @@ -260,6 +615,16 @@ impl Encoded { } } +#[cfg(not(target_arch = "wasm32"))] +/// A candle device as people call it ("CPU", "Metal GPU"). +pub fn device_name(device: &Device) -> String { + match device { + Device::Cpu => "CPU".into(), + Device::Metal(_) => "Metal GPU".into(), + Device::Cuda(_) => "CUDA GPU".into(), + } +} + #[cfg(not(target_arch = "wasm32"))] fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) @@ -273,3 +638,193 @@ pub use detector::Output as DetectorOutput; pub fn sync(model: &Sam3) -> Result<()> { Ok(model.device.synchronize()?) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A model folder whose checkpoint holds no tensors: enough to load with an accelerator, never to run candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join(WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// Answers with `values` backbone values, all `fill`, or fails. + struct Fake { + values: usize, + fill: f32, + fail: bool, + } + + impl BackboneAccel for Fake { + fn forward(&self, pixels: &[f32]) -> std::result::Result, String> { + assert_eq!(pixels.len(), 3 * INPUT * INPUT); + if self.fail { Err("device lost".into()) } else { Ok(vec![self.fill; self.values]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + const FULL: usize = vit::HIDDEN * vit::GRID * vit::GRID; + + fn with(fake: Fake) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(fake)) + } + + #[test] + fn the_backbone_runs_on_the_accelerator_without_loading_candle() { + let dir = empty_model("accel"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(Fake { values: FULL, fill: 0.25, fail: false })).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Fake GPU (Vulkan)"); + assert_eq!(m.backbone_fallback(), None); + // an accelerator for the backbone only: the rest is candle's + assert_eq!(m.heads_device(), "CPU"); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(enc.backbone().dims(), [1, vit::HIDDEN, vit::GRID, vit::GRID]); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_accelerator_that_cannot_be_built_leaves_the_backbone_to_candle() { + let dir = empty_model("nomake"); + // the empty checkpoint has no candle backbone: the load fails, but only after trying it + let r = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no adapter".into())); + assert!(r.is_err_and(|e| !e.to_string().contains("no adapter"))); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A backbone of `fill`, and neck levels of the right sizes (filled with their index) for the tracker; for the + /// detector the third level is cut short (`short`) or holds a NaN. + struct NeckFake { + calls: Arc, + short: bool, + } + + impl BackboneAccel for NeckFake { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + Ok(vec![0.5; FULL]) + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!((backbone.len(), backbone[0]), (FULL, 0.5)); + let mut levels: Vec> = (0..n).map(|i| vec![i as f32; neck::FPN * (tracker::LOW_RES >> i).pow(2)]).collect(); + if which == NeckKind::Detector { + if self.short { + levels[2].pop(); + } else { + levels[2][7] = f32::NAN; + } + } + Ok(levels) + } + } + + #[test] + fn neck_levels_come_from_the_accelerator_and_a_failing_neck_is_left_to_candle() { + for short in [true, false] { + let dir = empty_model(&format!("neck-{short}")); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let fake = NeckFake { calls: calls.clone(), short }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, move |_| Ok(Box::new(fake))).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + let levels = m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().unwrap(); + for (i, (l, side)) in levels.iter().zip([288, 144, 72]).enumerate() { + assert_eq!(l.dims(), [1, neck::FPN, side, side]); + assert_eq!(l.flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap(), i as f32); + } + // a wrong level: candle's neck from then on, without asking again + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(m.heads_device(), "CPU; the click neck on the GPU"); + // the other neck and the backbone stay on the accelerator + assert!(m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().is_some()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3); + assert!(m.accelerated()); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + /// Fails as the GPU does once the app is closing (the backbone or, with a backbone of zeros, a neck). + struct Closing { + backbone: bool, + } + + impl BackboneAccel for Closing { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + if self.backbone { Err("LightCraft is closing".into()) } else { Ok(vec![0.0; FULL]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn closing(&self) -> bool { + true + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, _: NeckKind, _: &[f32], _: usize) -> std::result::Result>, String> { + Err("LightCraft is closing".into()) + } + } + + #[test] + fn closing_is_no_accelerator_failure_and_nothing_runs_in_candle() { + let dir = empty_model("closing"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(true)).unwrap(); + let e = m.encode(&[128; 4 * 3 * 3], 4, 3).err().unwrap(); + assert!(e.to_string().contains("LightCraft is closing"), "{e}"); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + assert!(m.accelerated()); + assert_eq!((m.backbone_device().as_str(), m.backbone_fallback()), ("Fake GPU (Vulkan)", None)); + // a neck: the error, not candle's neck, and the accelerator keeps it + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(false)).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + for which in [NeckKind::Tracker, NeckKind::Detector] { + assert!(m.accel_neck(which, enc.backbone(), 3).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + assert!(m.neck_levels(which, &enc).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + } + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + std::fs::remove_dir_all(dir).unwrap(); + } + + fn with_closing(backbone: bool) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(Closing { backbone })) + } + + #[test] + fn a_failing_or_wrong_accelerator_is_dropped_for_candle() { + for (name, fake, why) in [ + ("fail", Fake { values: FULL, fill: 0.0, fail: true }, "device lost"), + ("short", Fake { values: 10, fill: 0.0, fail: false }, "returned 10 values"), + ("nan", Fake { values: FULL, fill: f32::NAN, fail: false }, "not numbers"), + ] { + let dir = empty_model(name); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(fake)).unwrap(); + // the candle backbone takes over (and fails here: the checkpoint is empty) + assert!(m.encode(&[128; 4 * 3 * 3], 4, 3).is_err(), "{name}"); + assert!(!m.accelerated(), "{name}"); + assert_eq!(m.backbone_device(), "CPU", "{name}"); + let fallback = m.backbone_fallback().unwrap(); + assert!(fallback.starts_with("Fake GPU (Vulkan) failed: ") && fallback.contains(why), "{name}: {fallback}"); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..3666d8c411 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -149,15 +149,25 @@ impl DecoderMlp { Ok(Self { layers }) } + /// On the CPU the hidden layers' bias add and ReLU are fused ([`cpu::linear_act`]: the box bias's MLPs have + /// 200 · 72 rows of 256). pub fn forward(&self, x: &Tensor) -> Result { + let mut dims = x.dims().to_vec(); let mut x = x.clone(); for (i, l) in self.layers.iter().enumerate() { - x = l.forward(&x)?; - if i + 1 < self.layers.len() { - x = x.relu()?; - } + x = if i + 1 == self.layers.len() { + l.forward(&x)? + } else if x.device().is_cpu() { + cpu::linear_act(&x, l, false)? + } else { + l.forward(&x)?.relu()? + }; } - Ok(x) + // the fused layers return rows + if let Some(last) = dims.last_mut() { + *last = x.dim(D::Minus1)?; + } + Ok(x.reshape(dims)?) } } @@ -240,3 +250,29 @@ pub fn cxcywh_to_xyxy(b: &Tensor) -> Result { pub fn to_vec(t: &Tensor) -> Result> { Ok(t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::()?) } + +#[cfg(test)] +mod tests { + use candle_core::{DType, Device}; + use candle_nn::VarMap; + + use super::*; + + #[test] + fn a_decoder_mlp_over_rows_matches_linear_per_batch() { + let vars = VarMap::new(); + let vb = VarBuilder::from_varmap(&vars, DType::F32, &Device::Cpu); + let mlp = DecoderMlp::new(2, 256, 8, 2, vb).unwrap(); + let x = Tensor::randn(0f32, 1.0, (200, 72, 2), &Device::Cpu).unwrap(); + let mut want = x.clone(); + for (i, l) in mlp.layers.iter().enumerate() { + want = l.forward(&want).unwrap(); + if i + 1 < mlp.layers.len() { + want = want.relu().unwrap(); + } + } + let got = mlp.forward(&x).unwrap(); + assert_eq!(got.dims(), [200, 72, 8]); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } +} diff --git a/crates/segment/tests/it/accel.rs b/crates/segment/tests/it/accel.rs new file mode 100644 index 0000000000..ad8dad3c11 --- /dev/null +++ b/crates/segment/tests/it/accel.rs @@ -0,0 +1,58 @@ +//! A backbone accelerator that fails leaves the work to candle, with the real checkpoint. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. Runs the candle backbone once on the CPU (about half a minute in release). + +use std::path::PathBuf; + +use lightcraft_segment::{BackboneAccel, Device, Sam3, WeightReader}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// Fails on every photo, as a GPU that lost its device would. +struct Lost; + +impl BackboneAccel for Lost { + fn forward(&self, _: &[f32]) -> Result, String> { + Err("device lost".into()) + } + fn device(&self) -> String { + "Lost GPU (Vulkan)".into() + } +} + +#[test] +fn an_accelerator_failing_on_a_photo_falls_back_to_candle() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_: &WeightReader| Ok(Box::new(Lost) as Box)).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Lost GPU (Vulkan)"); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let enc = m.encode(&rgb, w, h).unwrap(); + assert_eq!(enc.backbone().dims(), [1, 1024, 72, 72]); + let v = enc.backbone().flatten_all().unwrap().to_vec1::().unwrap(); + assert!(v.iter().all(|x| x.is_finite()) && v.iter().any(|x| *x != 0.0), "candle computed the features"); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("Lost GPU (Vulkan) failed: device lost")); +} + +#[test] +fn an_accelerator_that_cannot_be_built_loads_candles_backbone() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no GPU adapter".into())).unwrap(); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("no GPU adapter")); +} diff --git a/crates/segment/tests/it/main.rs b/crates/segment/tests/it/main.rs index 4dcb685916..629ae5f085 100644 --- a/crates/segment/tests/it/main.rs +++ b/crates/segment/tests/it/main.rs @@ -1,4 +1,6 @@ //! The integration tests, one module per file, linked into one test binary. +mod accel; +mod prompts; mod reference; mod remote; diff --git a/crates/segment/tests/it/prompts.rs b/crates/segment/tests/it/prompts.rs new file mode 100644 index 0000000000..1ff14679e8 --- /dev/null +++ b/crates/segment/tests/it/prompts.rs @@ -0,0 +1,63 @@ +//! A text prompt seen before reuses its features, with the same detector output as the first time. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. The backbone output is made up (no ViT run); the necks, the text encoder +//! and the detector are candle's on the CPU. + +use std::path::PathBuf; + +use candle_core::Tensor; +use lightcraft_segment::{BackboneAccel, DetectorOutput, Device, Sam3}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// A backbone output `[1024, 72, 72]` that varies over the channels and the grid. +struct Waves; + +impl BackboneAccel for Waves { + fn forward(&self, _: &[f32]) -> Result, String> { + Ok((0..1024 * 72 * 72).map(|i| (i as f32 * 0.37).sin() * 0.5).collect()) + } + fn device(&self) -> String { + "Waves (test)".into() + } +} + +fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() +} + +fn assert_same(a: &DetectorOutput, b: &DetectorOutput) { + assert_eq!(a.logits, b.logits); + assert_eq!(a.presence, b.presence); + assert_eq!(a.boxes, b.boxes); + assert_eq!(values(&a.text), values(&b.text)); + assert_eq!(values(&a.memory), values(&b.memory)); + assert_eq!(values(&a.masks), values(&b.masks)); +} + +#[test] +fn a_repeated_prompt_gives_the_same_output() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let mut m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Ok(Box::new(Waves) as Box)).unwrap(); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let mut enc = m.encode(&rgb, w, h).unwrap(); + let fresh = m.detect(&mut enc, "person").unwrap(); + m.detect(&mut enc, "sky").unwrap(); + let cached = m.detect(&mut enc, "person").unwrap(); + assert_eq!(cached.text.id(), fresh.text.id(), "the prompt's features were reused"); + assert_same(&cached, &fresh); + // and on the next photo + let mut next = m.encode(&rgb, w, h).unwrap(); + let again = m.detect(&mut next, "person").unwrap(); + assert_eq!(again.text.id(), fresh.text.id()); + assert_same(&again, &fresh); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8a50d38f10..822688011d 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index e3a98569fd..84a3efb7b2 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2394,5 +2394,13 @@ "End Slideshow": "Ukončit prezentaci", "Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…", "Manage Effect Presets…": "Spravovat přednastavení efektů…", - "Export Effect Presets…": "Exportovat přednastavení efektů…" + "Export Effect Presets…": "Exportovat přednastavení efektů…", + "AI masks": "AI masky", + "Device": "Zařízení", + "Last photo": "Poslední fotka", + "Remote worker": "Vzdálený proces", + "Run on": "Spouštět na", + "Automatic (GPU when available)": "Automaticky (GPU, je-li k dispozici)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masky Objekt a Popsat analyzují každou fotku jednou, na grafické kartě, pokud není zvoleno CPU nebo vypnuto „Použít GPU pro vykreslování“. Na procesoru to trvá mnohem déle.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaticky spouští model na grafické kartě Macu. Pokud tam AI masky selhávají, zvolte CPU; na procesoru trvají mnohem déle." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index af29f7134e..109126c4de 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", "Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 67a305ddf5..4184b529f5 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3422,5 +3422,13 @@ "favourites across restarts (issue #328).": "über Neustarts hinweg Favoriten (Issue #328).", "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-", "inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.", - "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference)." + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).", + "AI masks": "KI-Masken", + "Device": "Gerät", + "Last photo": "Letztes Foto", + "Remote worker": "Entfernter Worker", + "Run on": "Ausführen auf", + "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index fd15401693..55ac68506e 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", "Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 46965c7782..9a6ae2b299 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "Comprobando la GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.", - "Checking the GPU for faces": "Comprobando la GPU para las caras" + "Checking the GPU for faces": "Comprobando la GPU para las caras", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Proceso remoto", + "Run on": "Ejecutar en", + "Automatic (GPU when available)": "Automático (GPU si la hay)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Las máscaras Objeto y Describir analizan cada foto una sola vez, en la tarjeta gráfica salvo que se elija CPU o «Usar la GPU para renderizar» esté desactivado. En el procesador tarda mucho más.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático ejecuta el modelo en la tarjeta gráfica del Mac. Elige CPU si las máscaras de IA fallan allí; en el procesador tardan mucho más." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 698080e10d..78025df6b5 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "”{to}” on jo henkilö. Yhdistäminen tekee kahdesta yhden henkilön; Kumoa erottaa ne uudelleen.", "• {assumption}": "• {assumption}", "… and {more} more": "… ja {more} lisää", - "…and {more} more": "…ja {more} lisää" + "…and {more} more": "…ja {more} lisää", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff1707ac7a..aadff2f442 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2311,5 +2311,13 @@ "− harder border · + softer border": "− terävämpi reuna · + pehmeämpi reuna", "≤ at most": "≤ enintään", "≥ at least": "≥ vähintään", - "★ Favorites": "★ Suosikit" + "★ Favorites": "★ Suosikit", + "AI masks": "Tekoälymaskit", + "Device": "Laite", + "Last photo": "Viimeisin kuva", + "Remote worker": "Etätyöskentelijä", + "Run on": "Suorita", + "Automatic (GPU when available)": "Automaattinen (GPU, jos saatavilla)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Kohde- ja Kuvaile-maskit analysoivat jokaisen kuvan kerran, näytönohjaimella, ellei Suoritin ole valittuna tai ”Käytä GPU:ta renderöintiin” ole pois päältä. Suorittimella se kestää paljon kauemmin.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaattinen suorittaa mallin Macin näytönohjaimella. Valitse Suoritin, jos tekoälymaskit epäonnistuvat siellä; suorittimella ne kestävät paljon kauemmin." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ae2b778725..566a24c37b 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", "Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 2f22a70c1c..47f2f6025f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Vérification du GPU…", "CPU": "Processeur", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.", - "Checking the GPU for faces": "Vérification du GPU pour les visages" + "Checking the GPU for faces": "Vérification du GPU pour les visages", + "AI masks": "Masques IA", + "Device": "Appareil", + "Last photo": "Dernière photo", + "Remote worker": "Processus distant", + "Run on": "Exécuter sur", + "Automatic (GPU when available)": "Automatique (GPU si disponible)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Les masques Objet et Décrire analysent chaque photo une fois, sur la carte graphique sauf si Processeur est choisi ou si « Utiliser le GPU pour le rendu » est désactivé. Sur le processeur, c’est beaucoup plus long.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatique exécute le modèle sur la carte graphique du Mac. Choisissez Processeur si les masques IA y échouent ; sur le processeur, ils sont beaucoup plus longs." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index b3887f9174..0072148c1f 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -297,5 +297,6 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index aefe04417a..17d698afab 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2325,5 +2325,13 @@ "≤ at most": "≤ maksimal", "≥ at least": "≥ minimal", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Masker AI", + "Device": "Perangkat", + "Last photo": "Foto terakhir", + "Remote worker": "Worker jarak jauh", + "Run on": "Jalankan di", + "Automatic (GPU when available)": "Otomatis (GPU jika tersedia)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masker Objek dan Deskripsikan menganalisis setiap foto sekali, di kartu grafis kecuali CPU dipilih atau “Gunakan GPU untuk rendering” dimatikan. Di prosesor hal itu jauh lebih lama.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Otomatis menjalankan model di kartu grafis Mac. Pilih CPU jika masker AI gagal di sana; di prosesor prosesnya jauh lebih lama." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index ccd01e6a71..778c4568c9 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.", - "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}" + "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a638c14820..00035165d4 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2344,7 +2344,14 @@ "Loupe Info 1": "Info lente 1", "Loupe Info 2": "Info lente 2", "Use Defaults": "Usa predefiniti", - "Dimensions": "Dimensioni", "Camera & Lens": "Fotocamera e obiettivo", - "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2." + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", + "AI masks": "Maschere IA", + "Device": "Dispositivo", + "Last photo": "Ultima foto", + "Remote worker": "Processo remoto", + "Run on": "Esegui su", + "Automatic (GPU when available)": "Automatico (GPU se disponibile)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Le maschere Oggetto e Descrivi analizzano ogni foto una volta, sulla scheda grafica a meno che sia scelta la CPU o «Usa la GPU per il rendering» sia disattivato. Sul processore richiede molto più tempo.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatico esegue il modello sulla scheda grafica del Mac. Scegli CPU se lì le maschere IA non funzionano; sul processore richiedono molto più tempo." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index ce56500b5e..5f2e86b59b 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」はすでに別の人物です。まとめると1人になり、元に戻すと再び分かれます。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}合成を{mp}で追加しました:フルサイズ({full})にはこのコンピューターのメモリが足りません", "Listing folders — folders: {folders}, files: {files}": "フォルダーを一覧中 — フォルダー:{folders}、ファイル:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 4c55ee4947..794cc0539e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "GPU を確認中…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。", - "Checking the GPU for faces": "顔用の GPU を確認中" + "Checking the GPU for faces": "顔用の GPU を確認中", + "AI masks": "AIマスク", + "Device": "デバイス", + "Last photo": "直前の写真", + "Remote worker": "リモートワーカー", + "Run on": "実行先", + "Automatic (GPU when available)": "自動(GPUがあれば使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "オブジェクトと説明で選択のマスクは、写真ごとに一度だけ解析します。CPUを選んだ場合や「描画にGPUを使用」がオフの場合を除き、グラフィックカードで行います。処理装置ではかなり時間がかかります。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "自動ではMacのグラフィックカードでモデルを実行します。そこでAIマスクが失敗する場合はCPUを選んでください。処理装置ではかなり時間がかかります。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c3b48ef626..5c6ea7c16a 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 066f2ecd25..190df90630 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -86,6 +86,7 @@ "AI Denoise needs a model. Install one in Settings.": "AI ხმაურის მოცილებას მოდელი სჭირდება. დააინსტალირეთ პარამეტრებში.", "AI Mask Model Status": "AI ნიღბების მოდელის მდგომარეობა", "AI RAW denoise": "RAW-ის AI ხმაურის მოცილება", + "AI masks": "AI ნიღბები", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI ნიღბები SAM 3-ით (ობიექტი და აღწერა ნიღბვის პანელში): დაწკაპეთ ობიექტზე მის მოსანიშნად (⌥-დაწკაპუნება ტოვებს", "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ფოტოების გაერთიანება გაერთიანებულ DNG-ს აძლევს იმ ფერს, რომელიც თითო ფოტოს ცალკე გახსნისას აქვს (ხარვეზი #965). CR2-ების HDR გაერთიანება ადრე", "About": "პროგრამის შესახებ", @@ -229,7 +230,9 @@ "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან: GPS მდებარეობები თქვენი ფოტოებისთვის GPX მარშრუტის ჟურნალიდან, გადაღების დროის მიხედვით.", "Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…", "Automatic": "ავტომატური", + "Automatic (GPU when available)": "ავტომატური (GPU, თუ არის)", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "ავტომატური რეჟიმი დეტალურ ხედს ასახავს იმ ზომით, რომლითაც ის ჩანს, ფოტოს საკუთარ პიქსელებამდე. ზღვრისთვის აირჩიეთ ზომა: პატარა უფრო სწრაფია.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "ავტომატური რეჟიმი მოდელს Mac-ის ვიდეობარათზე უშვებს. აირჩიეთ CPU, თუ AI ნიღბები იქ ვერ მუშაობს; პროცესორზე ისინი გაცილებით დიდხანს გრძელდება.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "ავტომატური რეჟიმი იყენებს ვიდეობარათს, როცა ის პროცესორზე სწრაფია: ორივეს დრო ამ კომპიუტერზე იზომება, როცა ფოტო პირველად მზადდება.", "Automatically Write Changes into XMP": "ცვლილებების XMP-ში ავტომატურად ჩაწერა", "Automatically write changes into XMP sidecars": "ცვლილებების XMP თანმხლებ ფაილებში ავტომატურად ჩაწერა", @@ -296,6 +299,7 @@ "By day (YYYY/YYYY-MM-DD)": "დღის მიხედვით (YYYY/YYYY-MM-DD)", "By month (YYYY/YYYY-MM)": "თვის მიხედვით (YYYY/YYYY-MM)", "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "R7 C-RAW-ებისთვის ფოტო → დისკიდან ხელახლა ჩატვირთვა RAW მონაცემებს წაიკითხავს.", + "CPU": "CPU", "CPU threads": "CPU ნაკადები", "Cache": "ქეში", "Calibration": "კალიბრაცია", @@ -597,6 +601,7 @@ "Detect Faces": "სახეების ამოცნობა", "Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.", "Develop": "დამუშავება", + "Device": "მოწყობილობა", "Diagonal": "დიაგონალური", "Dialogs": "დიალოგები", "Dialogs fit the window": "დიალოგები ფანჯარაში ეტევა", @@ -1085,6 +1090,7 @@ "Last GPU fallback": "GPU-დან ბოლო გადართვა", "Last commit": "ბოლო კომიტი", "Last loupe render": "ლუპის ბოლო რენდერი", + "Last photo": "ბოლო ფოტო", "Last view": "ბოლო ხედი", "Lateral Chromatic Aberration": "განივი ქრომატული აბერაცია", "Layer": "შრე", @@ -1368,6 +1374,7 @@ "None": "არცერთი", "None (the display is treated as sRGB)": "არცერთი (ეკრანი sRGB-ად ითვლება)", "Not Now": "ახლა არა", + "Not loaded yet": "ჯერ არ ჩატვირთულა", "Not saved": "არ არის შენახული", "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "არაფერი უკვე დამუშავებული არ იცვლება: ძველ ფარდობით შკალაზე დაყენებული მორგებული თეთრის ბალანსი პიქსელ-პიქსელ ისევე რენდერდება, როგორც", "Nothing is fetched until you accept. The model is kept on this computer only; LightCraft never uploads or shares it.": "თქვენს თანხმობამდე არაფერი ჩამოიტვირთება. მოდელი მხოლოდ ამ კომპიუტერზე ინახება; LightCraft მას არასოდეს ატვირთავს და არავის უზიარებს.", @@ -1378,6 +1385,7 @@ "ONNX model": "ONNX მოდელი", "Object": "ობიექტი", "Object Mask": "ობიექტის ნიღაბი", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "ობიექტისა და აღწერის ნიღბები თითო ფოტოს ერთხელ აანალიზებს, ვიდეობარათზე, თუ CPU არ არის არჩეული და „რენდერირებისთვის GPU-ის გამოყენება“ გამორთული არ არის. პროცესორზე ეს გაცილებით დიდხანს გრძელდება.", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "ნიღბები „ობიექტი“ და „აღწერა“ იყენებს SAM 3-ს, Meta-ს სეგმენტაციის მოდელს. ის LightCraft-ის ნაწილი არ არის და ყველაფერი დანარჩენი მის გარეშეც მუშაობს.", "October 2026": "ოქტომბერი 2026", "Off": "გამორთული", @@ -1663,6 +1671,7 @@ "Relinked": "ხელახლა დაკავშირებულია", "Reload Changed Files": "შეცვლილი ფაილების ხელახლა ჩატვირთვა", "Reload from Disk": "დისკიდან ხელახლა ჩატვირთვა", + "Remote worker": "დისტანციური დამმუშავებელი", "Remove": "მოშორება", "Remove (H)": "მოშორება (H)", "Remove CA": "ქრომატული აბერაციის მოცილება", @@ -1766,6 +1775,7 @@ "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "წესების პრობლემები ნაჩვენებია თქვენს ენაზე და ველს ისე ასახელებს, როგორც მენიუ („დასახელება: საჭიროა საძიებო", "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "წესების მნიშვნელობები მოწმდება: შეფასება 9, თარიღი, როგორიცაა 2026-13 ან „banana“, „შორის“, რომლის თარიღებიც არასწორი", "Rules": "წესები", + "Run on": "გაშვება", "SAM 3 download stopped: it resumes where it left off next time.": "SAM 3-ის ჩამოტვირთვა შეწყდა: შემდეგ ჯერზე იქიდან გაგრძელდება, სადაც შეჩერდა.", "SDR": "SDR", "SDR Brightness": "SDR სიკაშკაშე", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e3ce316a0d..7791c4f840 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index aba88ef445..dad3624832 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2269,5 +2269,15 @@ "SDR Shadows": "Cienie SDR", "SDR Whites": "Biele SDR", "SDR Clarity": "Przejrzystość SDR", - "Face Models on the GPU": "Modele twarzy przetwarzane na GPU" + "Face Models on the GPU": "Modele twarzy przetwarzane na GPU", + "AI masks": "Maski AI", + "Device": "Urządzenie", + "Last photo": "Ostatnie zdjęcie", + "Remote worker": "Zdalny proces", + "Not loaded yet": "Jeszcze nie wczytano", + "Run on": "Uruchamiaj na", + "Automatic (GPU when available)": "Automatycznie (GPU, gdy jest)", + "CPU": "CPU", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Maski Obiekt i Opisz analizują każde zdjęcie raz, na karcie graficznej, chyba że wybrano CPU albo opcja „Użyj procesora graficznego do renderowania” jest wyłączona. Na procesorze trwa to znacznie dłużej.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatycznie uruchamia model na karcie graficznej Maca. Wybierz CPU, jeśli maski AI tam zawodzą; na procesorze trwa to znacznie dłużej." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index bab81a3688..facb052cb1 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” já é uma pessoa. Combiná-las deixa uma só; Desfazer as separa de novo.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} mesclagem adicionada em {mp}: o tamanho completo, {full}, precisa de mais memória do que este computador tem", "Listing folders — folders: {folders}, files: {files}": "Listando pastas — pastas: {folders}, arquivos: {files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 5b4ae44096..e6e41243ac 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2188,5 +2188,13 @@ "Color Overlay on B&W": "Sobreposição de cor em P&B", "Image on Black": "Imagem sobre preto", "Image on White": "Imagem sobre branco", - "White on Black": "Branco sobre preto" + "White on Black": "Branco sobre preto", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Processo remoto", + "Run on": "Executar em", + "Automatic (GPU when available)": "Automático (GPU quando houver)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "As máscaras Objeto e Descrever analisam cada foto uma vez, na placa de vídeo, a menos que CPU esteja escolhida ou “Usar a GPU para renderização” esteja desligado. No processador isso demora muito mais.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático executa o modelo na placa de vídeo do Mac. Escolha CPU se as máscaras de IA falharem nela; no processador elas demoram muito mais." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 1efc30268e..2299b498ad 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index bf191bb515..744bc0ce55 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2335,5 +2335,13 @@ "Checking the GPU…": "Проверка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.", - "Checking the GPU for faces": "Проверка ГП для лиц" + "Checking the GPU for faces": "Проверка ГП для лиц", + "AI masks": "ИИ-маски", + "Device": "Устройство", + "Last photo": "Последнее фото", + "Remote worker": "Удалённый обработчик", + "Run on": "Выполнять на", + "Automatic (GPU when available)": "Автоматически (GPU, если есть)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Объект» и «Описать» анализируют каждое фото один раз — на видеокарте, если не выбран ЦП и не выключено «Использовать GPU для рендеринга». На процессоре это намного дольше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматически» запускает модель на видеокарте Mac. Если ИИ-маски там не работают, выберите ЦП; на процессоре они намного дольше." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 50e3fa4be0..ca8350cc57 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -297,5 +297,6 @@ "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, bildkodare {encoder:.1} s" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76f08c2d38..00bcb9f599 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2414,5 +2414,13 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "AI-masker", + "Device": "Enhet", + "Last photo": "Senaste foto", + "Remote worker": "Fjärrarbetare", + "Run on": "Kör på", + "Automatic (GPU when available)": "Automatisk (GPU när den finns)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- och Beskriv-masker analyserar varje foto en gång, på grafikkortet om inte CPU är vald eller ”Använd GPU:n för rendering” är av. På processorn tar det mycket längre tid.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisk kör modellen på Macens grafikkort. Välj CPU om AI-masker misslyckas där; på processorn tar de mycket längre tid." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 0ada44e080..f960122d27 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 4dff39f784..0628803bcd 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Перевірка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.", - "Checking the GPU for faces": "Перевірка ГП для облич" + "Checking the GPU for faces": "Перевірка ГП для облич", + "AI masks": "ШІ-маски", + "Device": "Пристрій", + "Last photo": "Останнє фото", + "Remote worker": "Віддалений обробник", + "Run on": "Виконувати на", + "Automatic (GPU when available)": "Автоматично (ГП, якщо є)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Об’єкт» і «Описати» аналізують кожне фото один раз — на відеокарті, якщо не вибрано ЦП і не вимкнено «Використовувати ГП для рендерингу». На процесорі це значно довше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматично» запускає модель на відеокарті Mac. Якщо ШІ-маски там не працюють, виберіть ЦП; на процесорі вони значно довші." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 9ff8ed6b99..c627d80df2 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", "• {assumption}": "• {assumption}", "… and {more} more": "… và {more} nữa", - "…and {more} more": "…and {more} more" + "…and {more} more": "…và {more} nữa", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 6908be70e1..d752190a82 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2220,5 +2220,13 @@ "≥ at least": "≥ tối thiểu", "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Mặt nạ AI", + "Device": "Thiết bị", + "Last photo": "Ảnh gần nhất", + "Remote worker": "Worker từ xa", + "Run on": "Chạy trên", + "Automatic (GPU when available)": "Tự động (GPU nếu có)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Mặt nạ Đối tượng và Mô tả phân tích mỗi ảnh một lần, trên card đồ họa trừ khi chọn CPU hoặc tắt “Dùng GPU để kết xuất”. Trên bộ xử lý việc này lâu hơn nhiều.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Tự động chạy mô hình trên card đồ họa của máy Mac. Hãy chọn CPU nếu mặt nạ AI bị lỗi ở đó; trên bộ xử lý chúng chạy lâu hơn nhiều." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index a28b07d2c8..e6688a8fb7 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}”已经是另一个人。合并后成为一个人;撤销会再把他们分开。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已添加 {what} 合并({mp}):完整尺寸({full})所需的内存超出了这台电脑的内存", "Listing folders — folders: {folders}, files: {files}": "正在列出文件夹 — 文件夹:{folders},文件:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 4a2ebaa7b1..633147d336 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2186,5 +2186,13 @@ "Suggests who is in a photo from the faces you have named. Everything stays on your computer.": "根据你已命名的人脸,推测照片中的人物。所有数据仅保存在本机。", "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", "Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。", - "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)" + "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)", + "AI masks": "AI 蒙版", + "Device": "设备", + "Last photo": "上一张照片", + "Remote worker": "远程工作进程", + "Run on": "运行位置", + "Automatic (GPU when available)": "自动(有 GPU 时使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "“对象”和“描述”蒙版对每张照片只分析一次;除非选择了 CPU 或关闭了“使用 GPU 渲染”,否则在显卡上进行。在处理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "“自动”会在 Mac 的显卡上运行模型。如果 AI 蒙版在那里失败,请选择 CPU;在处理器上会慢得多。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1192722251..7eca03bbd6 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」已經是另一個人。合併後成為一個人;還原會再把他們分開。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已新增{what}合併照片({mp}):完整尺寸({full})所需的記憶體超過這台電腦的記憶體", "Listing folders — folders: {folders}, files: {files}": "正在列出資料夾 — 資料夾:{folders},檔案:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 78d8851285..961d83505e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2143,5 +2143,13 @@ "Checking the GPU…": "正在檢查 GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 GPU。", - "Checking the GPU for faces": "正在檢查用於臉孔的 GPU" + "Checking the GPU for faces": "正在檢查用於臉孔的 GPU", + "AI masks": "AI 遮色片", + "Device": "裝置", + "Last photo": "上一張照片", + "Remote worker": "遠端工作程序", + "Run on": "執行位置", + "Automatic (GPU when available)": "自動(有 GPU 時使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "「物件」和「描述」遮色片對每張照片只分析一次;除非選擇了 CPU 或關閉了「使用 GPU 算繪」,否則在顯示卡上進行。在處理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "「自動」會在 Mac 的顯示卡上執行模型。如果 AI 遮色片在那裡失敗,請選擇 CPU;在處理器上會慢得多。" } diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 2f844f4ae9..66df3e719b 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -1,5 +1,5 @@ -//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! The Settings dialog (⌘,): General, Import, Performance (incl. where AI masks run), Display, +//! Interface, Slideshow, Faces, AI Denoise. //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -485,6 +485,59 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); #[cfg(not(target_arch = "wasm32"))] smart_previews(app, ui, t); + ai_masks(app, ui, t); +} + +/// Where AI masks (SAM 3) run: the choice (`segment.settings {runOn}`), what they run on, why not on +/// the GPU, and how long the last photo took (`segment.model.status` → `backend`), as Settings ▸ +/// Faces shows its models' processor. The same lines whatever the state, so nothing moves when the +/// model loads. +fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + return; + } + heading(ui, t, crate::i18n::tr("AI masks")); + let current = app.session.segmenter.run_on().name(); + let mut run_on = current; + if row(ui, t, "Run on", |ui| choices(ui, "settingsAiMasksRunOn", &[("auto", "Automatic (GPU when available)"), ("cpu", "CPU")], &mut run_on)) + && let Err(e) = app.run("segment.settings", json!({"runOn": run_on})) + { + app.toast(ui.ctx(), e); + } + let g = &app.session.segmenter; + let b = g.backend(); + let device = if g.remote_endpoint().is_some() { + crate::i18n::tr("Remote worker").to_string() + } else { + b["device"].as_str().map_or_else(|| crate::i18n::tr("Not loaded yet").to_string(), str::to_string) + }; + let text = match b["fallback"].as_str() { + Some(why) if g.remote_endpoint().is_none() => format!("{device} ({why})"), + _ => device, + }; + row(ui, t, "Device", |ui| { + let r = ui.add(egui::Label::new(RichText::new(text.clone()).color(t.text)).truncate()).on_hover_text(text); + register(ui.ctx(), "settings:aiMasksDevice", r.rect); + }); + let took = match (b["analyzeMs"].as_u64().or(b["encodeMs"].as_u64()), b["encodeMs"].as_u64()) { + (Some(all), Some(encoder)) => { + crate::i18n::tr_format!("{all:.1} s, image encoder {encoder:.1} s", all = all as f64 / 1000.0, encoder = encoder as f64 / 1000.0) + } + _ => "—".to_string(), + }; + row(ui, t, "Last photo", |ui| { + let r = ui.label(RichText::new(took).color(t.text)); + register(ui.ctx(), "settings:aiMasksTime", r.rect); + }); + hint( + ui, + t, + crate::i18n::tr(if cfg!(target_os = "macos") { + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer." + } else { + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer." + }), + ); } /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rs index 52d4128294..3d11c260fa 100644 --- a/crates/ui-egui/src/tests_dialog_fit.rs +++ b/crates/ui-egui/src/tests_dialog_fit.rs @@ -158,3 +158,40 @@ fn gpu_status_never_moves_the_performance_controls() { let first = seen[0].1; assert!(seen.iter().all(|(_, r, _)| *r == first), "the memory buttons moved: {seen:?}"); } + +/// Settings ▸ Performance says where AI masks run and how long the last photo took (issue #932): before the model +/// loads, its two lines are there all the same, at the end of the tab, so nothing above them moves when it loads. +#[test] +fn performance_tab_shows_where_ai_masks_run() { + let mut h = demo([1300.0, 820.0]); + let r = h.request("ui.key", json!({"key": ",", "cmd": true}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsTab-performance"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let has = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + assert!(!has(&h, "settings:aiMasksDevice"), "a build without AI masks says nothing about them"); + return; + } + let (device, time) = (rect(&h, "settings:aiMasksDevice"), rect(&h, "settings:aiMasksTime")); + assert!(device.bottom() <= time.top() + 1.0, "the device line comes first: {device:?} {time:?}"); + let choice = rect(&h, "button:settingsAiMasksRunOn-1"); + assert!(choice.bottom() <= device.top() + 1.0, "the choice of where they run comes first: {choice:?} {device:?}"); + assert!(rect(&h, "button:settingsMemory-2").bottom() < choice.top(), "after the other performance settings"); + let b = h.app.session.segmenter.backend(); + assert!(b["device"].is_null() && b["encodeMs"].is_null(), "nothing loaded or timed yet: {b}"); + // CPU, then Automatic again: the choice applies at once, and nothing moves + use lightcraft_engine::segment::{CPU_CHOSEN, RunOn}; + for (button, want) in [("button:settingsAiMasksRunOn-1", RunOn::Cpu), ("button:settingsAiMasksRunOn-0", RunOn::Auto)] { + let r = h.request("ui.clickWidget", json!({"id": button}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert_eq!(h.app.session.segmenter.run_on(), want); + let fallback = h.app.session.segmenter.backend()["fallback"].clone(); + assert_eq!(fallback == CPU_CHOSEN, want == RunOn::Cpu, "{fallback}"); + // (its text says why it runs on the CPU now, so only its width changes) + assert_eq!(rect(&h, "settings:aiMasksDevice").min, device.min, "the device line stays put"); + } +} From d653132a250c9884d8209bbfec4d1615b9f45ae9 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:41 +0200 Subject: [PATCH 021/247] M12: SAM 3 image encoder on the GPU (wgpu): shared kernels and the 32-layer ViT Part 2 of 5 of #2167. lightcraft-gpu gets a `sam` feature with `sam3`: a device of its own (like denoise and faces, with the same switches, the crash sentinel and the shutdown gate), the shared kernels (tiled matrix products with bias / GELU / residual in the epilogue, flash-style attention, layer norm, RoPE, im2col, the final reorder) and the image encoder built from them. The engine now uses it as the GPU backbone where candle has no GPU (not macOS); the necks and the text detector's heads stay in candle. An adapter without the needed limits (98 MB storage buffers, 16 KB workgroup memory) or whose device can't be created gets no device; the backbone then runs in candle on the CPU and Settings shows why (sam3::tests::an_adapter_short_of_the_limits_is_refused_with_what_it_lacks). A pass that doesn't finish names its stage in the reason the device is given up with. The parity test prints the largest mask difference to the CPU next to the IoU. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + crates/engine/Cargo.toml | 2 +- crates/engine/src/cmd/masks.rs | 2 +- crates/engine/src/segment/worker.rs | 22 +- crates/gpu/Cargo.toml | 12 + crates/gpu/examples/sam3_backbone_bench.rs | 125 +++ crates/gpu/src/lib.rs | 2 + crates/gpu/src/sam3.rs | 1102 ++++++++++++++++++++ crates/gpu/src/sam3/tests.rs | 458 ++++++++ crates/gpu/src/wgsl/sam3_attention.wgsl | 75 ++ crates/gpu/src/wgsl/sam3_matmul.wgsl | 138 +++ crates/gpu/src/wgsl/sam3_ops.wgsl | 143 +++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_backbone.rs | 143 +++ xtask/src/layers.rs | 2 + xtask/src/main.rs | 8 +- 16 files changed, 2217 insertions(+), 21 deletions(-) create mode 100644 crates/gpu/examples/sam3_backbone_bench.rs create mode 100644 crates/gpu/src/sam3.rs create mode 100644 crates/gpu/src/sam3/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_attention.wgsl create mode 100644 crates/gpu/src/wgsl/sam3_matmul.wgsl create mode 100644 crates/gpu/src/wgsl/sam3_ops.wgsl create mode 100644 crates/gpu/tests/it/sam3_backbone.rs diff --git a/Cargo.lock b/Cargo.lock index 8c29f11536..fd65dd2931 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3320,6 +3320,7 @@ name = "lightcraft-gpu" version = "0.13.0" dependencies = [ "bytemuck", + "candle-core", "lightcraft-color", "lightcraft-denoise", "lightcraft-develop", @@ -3329,6 +3330,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-raw", "lightcraft-scenes", + "lightcraft-segment", "lightcraft-testkit", "log", "pollster 1.0.1", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9caa8cdb0e..1eccf72577 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -51,7 +51,7 @@ chrono = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. -sam = ["dep:lightcraft-segment"] +sam = ["dep:lightcraft-segment", "lightcraft-gpu/sam"] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime", "lightcraft-gpu/denoise"] rawnind-model = ["denoise", "lightcraft-denoise/rawnind-model", "lightcraft-denoise-core/rawnind-model"] diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 9c7c8bca8f..d00c685a3d 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -560,7 +560,7 @@ pub fn specs() -> Vec { "AI Mask Settings", [], None, - "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere candle on the CPU: this build has no wgpu kernels for SAM 3 yet), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere the parts LightCraft's wgpu kernels run, while GPU rendering is allowed, and the rest on the CPU: `segment.model.status` → `backend` says which), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", super::always, |s, p| { let c = "segment.settings"; diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index 6bae968924..d9f437a2d6 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -9,8 +9,8 @@ //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! //! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. -//! Elsewhere candle runs on the CPU, and the backbone (most of the work) can run on the GPU through an -//! accelerator ([`GPU_BACKBONE`]: none in this build yet, so it runs in candle as before), unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) on the GPU with +//! `lightcraft-gpu`'s wgpu kernels, unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, //! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI //! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. //! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every @@ -207,11 +207,7 @@ fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { if let Some(why) = lightcraft_gpu::env_off_reason() { return Placement::Cpu(why.into()); } - match placement(best_is_cpu, lightcraft_gpu::switched_off(), false) { - // without a GPU backbone in this build, candle's best device runs it all - Placement::GpuBackbone if GPU_BACKBONE.is_none() => Placement::Best, - p => p, - } + placement(best_is_cpu, lightcraft_gpu::switched_off(), false) } /// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device @@ -233,17 +229,9 @@ fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { runs(loaded) != runs(wanted) } -/// Builds the GPU backbone from the checkpoint (tests use fakes). +/// Builds the GPU backbone from the checkpoint (`lightcraft_gpu::sam3::backbone`; tests use fakes). type MakeAccel = fn(&WeightReader) -> Result, String>; -/// The GPU backbone of this build: none yet (its wgpu kernels come separately), so where candle has no GPU the -/// model runs in candle on the CPU, as before. -const GPU_BACKBONE: Option = None; - -fn no_accelerator(_: &WeightReader) -> Result, String> { - Err("this build has no GPU backbone".into()) -} - /// Load the model in `dir` as `placement` says, on `best` (candle's best device). fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { match placement { @@ -529,7 +517,7 @@ fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, faile let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; let placement = wanted(best_is_cpu, cpu, failed); - let m = load(dir, best, &placement, GPU_BACKBONE.unwrap_or(no_accelerator))?; + let m = load(dir, best, &placement, lightcraft_gpu::sam3::backbone)?; log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 02edcefd1b..689d0e64ed 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -24,13 +24,25 @@ log = { workspace = true } wgpu = { workspace = true } pollster = { workspace = true } bytemuck = { workspace = true } +# the SAM 3 backbone kernels (`sam` feature) implement `lightcraft_segment::BackboneAccel` +lightcraft-segment = { workspace = true, optional = true } [features] default = [] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"] +# SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on +sam = ["dep:lightcraft-segment"] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } lightcraft-scenes = { workspace = true } lightcraft-raw = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# the SAM 3 backbone test and benchmark compare against the candle backbone +candle-core = { workspace = true } + +[[example]] +name = "sam3_backbone_bench" +required-features = ["sam"] diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs new file mode 100644 index 0000000000..05a001308e --- /dev/null +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -0,0 +1,125 @@ +//! Times the SAM 3 backbone on the GPU (wgpu) against the candle backbone on the CPU, on a procedural photo. +//! +//! `cargo run --release -p lightcraft-gpu --features sam --example sam3_backbone_bench -- [--f16] [--runs N] [--no-cpu]` +//! +//! The model directory is `LIGHTCRAFT_SAM3_DIR`, else `~/.config/lightcraft/models/sam3`. Prints the device and +//! kernel creation, the weight upload, the first and the warm forward passes, the CPU forward pass and how far the +//! two outputs are apart. `--app` then times what the app does per photo, with the model loaded as the app loads it +//! (GPU backbone, the rest in candle on the CPU): encode, click features, first click, first and second Describe. + +use std::path::PathBuf; +use std::time::Instant; + +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, INPUT, Sam3}; + +fn model_dir() -> Option { + let dir = match std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()) { + Some(d) => PathBuf::from(d), + None => PathBuf::from(std::env::var_os("HOME")?).join(".config/lightcraft/models/sam3"), + }; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + let precision = if args.iter().any(|a| a == "--f16") { Precision::F16 } else { Precision::F32 }; + let runs: usize = match args.iter().position(|a| a == "--runs").map(|i| args.get(i + 1).and_then(|v| v.parse().ok())) { + None => 5, + Some(Some(n)) if n > 0 => n, + Some(_) => return Err("--runs needs a positive number".into()), + }; + let cpu = !args.iter().any(|a| a == "--no-cpu"); + let app = args.iter().any(|a| a == "--app"); + let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; + + let scene = &lightcraft_scenes::demo_library()[0]; + let img = scene.render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let pixels = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).map_err(|e| e.to_string())?; + + let t = Instant::now(); + let adapter = sam3::adapter()?; + println!("device + kernels: {:7.1} ms ({adapter})", t.elapsed().as_secs_f64() * 1e3); + let reader = lightcraft_segment::WeightReader::open(&dir).map_err(|e| e.to_string())?; + let t = Instant::now(); + let gpu = sam3::load(&reader, precision)?; + println!( + "weight upload: {:7.1} ms ({:.0} MB weights, {:.0} MB work buffers, {precision:?})", + t.elapsed().as_secs_f64() * 1e3, + gpu.weight_bytes() as f64 / 1e6, + gpu.work_bytes() as f64 / 1e6 + ); + let t = Instant::now(); + let out = gpu.forward(&pixels)?; + println!("first forward: {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let mut best = f64::MAX; + let mut sum = 0.0; + for _ in 0..runs { + let t = Instant::now(); + gpu.forward(&pixels)?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + println!("warm forward: {:7.1} ms (mean of {runs}: {:.1} ms)", best, sum / runs.max(1) as f64); + if cpu { + let model = Sam3::load_on(&dir, candle_core::Device::Cpu).map_err(|e| e.to_string())?; + let px = candle_core::Tensor::from_vec(pixels.clone(), (1, 3, INPUT, INPUT), &candle_core::Device::Cpu).map_err(|e| e.to_string())?; + let t = Instant::now(); + let enc = model.encode_pixels(&px).map_err(|e| e.to_string())?; + println!("CPU (candle): {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let want = enc.backbone().flatten_all().and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())); + let (mut max, mut sum) = (0f32, 0f64); + for (a, b) in out.iter().zip(&want) { + max = max.max((a - b).abs()); + sum += f64::from((a - b).abs()); + } + println!( + "GPU vs CPU: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {:.3e}", + max / scale.max(1e-6), + sum / want.len().max(1) as f64 + ); + } + drop(gpu); + if app { + as_the_app(&dir, &rgb, (img.width, img.height), runs)?; + } + // no GPU work in flight when the process ends (issue #620) + lightcraft_gpu::begin_shutdown(); + lightcraft_gpu::wait_idle(std::time::Duration::from_secs(5)); + Ok(()) +} + +fn ms(t: Instant) -> String { + format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) +} + +/// The model as the app loads it, timed per photo: encode, click features, a click, two Describes. +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize) -> Result<(), String> { + let t = Instant::now(); + let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, sam3::backbone).map_err(|e| e.to_string())?; + println!("app: load {} on {}", ms(t), model.backbone_device()); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs.max(1) { + let t = Instant::now(); + let mut enc = model.encode(rgb, w, h).map_err(|e| e.to_string())?; + let encode = ms(t); + let t = Instant::now(); + model.prepare_clicks(&mut enc).map_err(|e| e.to_string())?; + let features = ms(t); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5)]).map_err(|e| e.to_string())?; + let click1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "sky", 0.5).map_err(|e| e.to_string())?; + let text1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5).map_err(|e| e.to_string())?; + let text2 = ms(t); + println!("app run {run}: encode {encode}, click features {features}, click {click1}, first describe {text1}, second describe {text2}"); + } + println!("app: the rest on {}", model.heads_device()); + Ok(()) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ec644df6e7..125eddd2de 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -43,6 +43,8 @@ pub mod nn; mod params; #[cfg(not(target_arch = "wasm32"))] mod render; +#[cfg(all(feature = "sam", not(target_arch = "wasm32")))] +pub mod sam3; #[cfg(not(target_arch = "wasm32"))] pub use render::GpuStages; diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs new file mode 100644 index 0000000000..bf37f72454 --- /dev/null +++ b/crates/gpu/src/sam3.rs @@ -0,0 +1,1102 @@ +//! The SAM 3 vision backbone on the GPU: a [`lightcraft_segment::BackboneAccel`] that runs the 32-layer ViT of +//! `lightcraft-segment` (`vit.rs`, the reference) with WGSL compute kernels, so AI masks (Object, Subject, Describe) +//! need not wait ~40 s per photo for the CPU on machines without Metal. +//! +//! What runs (`docs/gpu-pipeline.md` → SAM 3 backbone): the patch embedding as im2col and a matrix product, the +//! 24 × 24 position table, `ln_pre`, then per layer layer norm → one q|k|v product → 2-D RoPE → attention (24 × 24 +//! windows, or all 5184 tokens in layers 7, 15, 23 and 31) → output projection and residual → layer norm → MLP +//! (GELU, erf form) and residual. The tokens stay in *window order* the whole way (window-major, row-major inside a +//! window): a window's tokens are then a contiguous range for attention, the position table repeats per window, and +//! the global layers don't care about order (their RoPE table is stored in the same order). Only the last step puts +//! them back on the 72 × 72 grid, channels-first. +//! +//! Kernels: `wgsl/sam3_matmul.wgsl` (tiled, register-blocked; bias, GELU and residual in its epilogue), +//! `wgsl/sam3_attention.wgsl` (flash style: online softmax, the 16 × 5184² scores of a global layer never exist), +//! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters +//! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer +//! per layer and reads the result back once. No subgroups or shader-f16 needed. The necks and the text detector's +//! heads stay in candle on the CPU. +//! +//! The device is its own (like denoise's and faces'): it respects the same switches as GPU rendering +//! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, `LIGHTCRAFT_GPU_ADAPTER`, the GPU preference), the crash sentinel +//! around device creation and the shutdown gate. A device error or loss stops its use for the process; every +//! failure is an `Err` (the caller then runs the candle backbone), never a panic. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; +use std::time::Duration; + +use bytemuck::Pod; +use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, WeightReader}; +use wgpu::util::DeviceExt; + +#[cfg(test)] +mod tests; + +/// Input side (pixels), patch size, patches per side. +const IMAGE: usize = 1008; +const PATCH: usize = 14; +const GRID: usize = IMAGE / PATCH; +const TOKENS: usize = GRID * GRID; +const HIDDEN: usize = 1024; +const HEADS: usize = 16; +const HEAD_DIM: usize = HIDDEN / HEADS; +const MLP: usize = 4736; +const LAYERS: usize = 32; +const WINDOW: usize = 24; +const GLOBAL: [usize; 4] = [7, 15, 23, 31]; +/// The pretraining grid of the position table (336 / 14), tiled over the 72 × 72 grid. +const POS_SIDE: usize = 24; +const EPS: f32 = 1e-6; +/// Numbers per patch (3 × 14 × 14): the patch embedding's K. +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). +const ATTENTION_BYTES: u32 = 2 * ATTENTION_KEYS * HEAD_DIM as u32 * 4; +/// Keys per step of the attention kernel. +const ATTENTION_KEYS: u32 = 32; +/// The matrix product's blocking. +const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 }; + +/// How the matrix-product kernel blocks its work: each of its 16 × 16 threads makes `rows × cols` outputs (so a +/// workgroup makes 16 · rows × 16 · cols), walking k in steps of `bk` (a multiple of 8). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Tile { + rows: u32, + cols: u32, + bk: u32, +} + +impl Tile { + fn bm(self) -> usize { + 16 * self.rows as usize + } + + fn bn(self) -> usize { + 16 * self.cols as usize + } + + /// Workgroup memory: both tiles, k-contiguous, each row padded by one vector. + fn workgroup_bytes(self) -> u32 { + (self.bm() + self.bn()) as u32 * (self.bk / 4 + 1) * 16 + } +} + +/// A matrix-product pipeline and its blocking. +struct Matmul { + pipeline: wgpu::ComputePipeline, + tile: Tile, +} + +// --------------------------------------------------------------------------------------------------------------------- +// the device + +struct Dev { + device: wgpu::Device, + queue: wgpu::Queue, + info: wgpu::AdapterInfo, + limits: wgpu::Limits, + layout: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + k: Kernels, + /// Bound where a kernel has fewer operands than bindings. + dummy: wgpu::Buffer, +} + +struct Kernels { + matmul: Matmul, + /// The same with f16 weights, compiled when first needed. + matmul16: OnceLock, + attention: wgpu::ComputePipeline, + layernorm: wgpu::ComputePipeline, + rope: wgpu::ComputePipeline, + im2col: wgpu::ComputePipeline, + to_chw: wgpu::ComputePipeline, +} + +static DEV: OnceLock> = OnceLock::new(); +static BROKEN: AtomicBool = AtomicBool::new(false); +static BROKEN_WHY: Mutex> = Mutex::new(None); + +fn mark_broken(why: &str) { + let mut w = BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner); + if w.is_none() { + *w = Some(why.to_string()); + } + BROKEN.store(true, Ordering::Relaxed); +} + +/// Why the GPU stopped being used for SAM 3 (a device error), if it did. +pub fn broken_reason() -> Option { + BROKEN.load(Ordering::Relaxed).then(|| BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner).clone().unwrap_or_else(|| "device error".into())) +} + +fn dev() -> Result<&'static Dev, String> { + if let Some(why) = broken_reason() { + return Err(format!("stopped after a GPU failure: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + // creating the device is GPU work too: not once the process is ending (issue #620) + let _work = match DEV.get() { + Some(_) => None, + None => Some(crate::exit::enter().ok_or("LightCraft is closing")?), + }; + DEV.get_or_init(create_device).as_ref().map_err(|e| e.clone()) +} + +fn create_device() -> Result { + let Some(backends) = crate::backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + crate::backend::with_init_marker(backends, || { + std::panic::catch_unwind(|| make_device(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) + }) +} + +fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, + count: None, + } +} + +/// The largest buffer the backbone binds: the MLP's hidden activations (5184 × 4736 floats, 98 MB). +const LARGEST_BUFFER: u64 = (TOKENS * MLP * 4) as u64; + +/// The limits the kernels need: the WebGPU downlevel defaults, with room for the largest buffer and the tiles. +fn needed_limits() -> wgpu::Limits { + wgpu::Limits { + max_storage_buffer_binding_size: LARGEST_BUFFER, + max_buffer_size: LARGEST_BUFFER, + max_compute_workgroup_storage_size: ATTENTION_BYTES.max(TILE.workgroup_bytes()), + max_compute_invocations_per_workgroup: 256, + max_compute_workgroup_size_x: 256, + ..wgpu::Limits::downlevel_defaults() + } +} + +/// The limits an adapter with `have` falls short of ([`needed_limits`]), as "name have < want"; empty when it has them all. +/// Such an adapter gets no device: SAM 3 then runs in candle on the CPU, and Settings says why. +fn short_limits(have: &wgpu::Limits) -> Vec { + let mut short = Vec::new(); + needed_limits().check_limits_with_fail_fn(have, false, |name, want, have| short.push(format!("{name} {have} < {want}"))); + short +} + +fn make_device(backends: wgpu::Backends) -> Result { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + desc.backend_options = crate::backend::backend_options(); + desc.flags = crate::backend::instance_flags_from_env(desc.flags); + let instance = wgpu::Instance::new(desc); + let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); + let adapter = match &wanted { + Some(w) => pollster::block_on(instance.enumerate_adapters(backends)) + .into_iter() + .find(|a| { + let i = a.get_info(); + i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) + }) + .ok_or_else(|| format!("no GPU adapter named like `{w}`"))?, + None => pollster::block_on( + instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), + ) + .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, + }; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); + } + let need = needed_limits(); + let short = short_limits(&adapter.limits()); + if !short.is_empty() { + return Err(format!("{} is too limited for the SAM 3 kernels ({})", info.name, short.join(", "))); + } + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("lightcraft-sam3"), + required_limits: need, + ..Default::default() + })) + .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + device.on_uncaptured_error(Arc::new(|e| { + log::error!("gpu (sam3): {e}"); + mark_broken(&format!("device error: {e}")); + })); + device.set_device_lost_callback(|reason, msg| { + log::error!("gpu (sam3): device lost ({reason:?}): {msg}"); + mark_broken(&format!("device lost ({reason:?}): {msg}")); + }); + // a kernel the driver or naga rejects fails the device here, not the first forward pass + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + use wgpu::BufferBindingType::{Storage, Uniform}; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sam3"), + entries: &[ + entry(0, Uniform), + entry(1, Storage { read_only: true }), + entry(2, Storage { read_only: true }), + entry(3, Storage { read_only: true }), + entry(4, Storage { read_only: false }), + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&device, &pl, label, source, entry); + let ops = include_str!("wgsl/sam3_ops.wgsl"); + 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"), + layernorm: pipe("sam3 ops", ops, "layernorm"), + rope: pipe("sam3 ops", ops, "rope"), + im2col: pipe("sam3 ops", ops, "im2col"), + to_chw: pipe("sam3 ops", ops, "to_chw"), + }; + let dummy = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 unused"), + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 kernels did not compile ({e})", info.name)); + } + let limits = device.limits(); + log::info!("gpu (sam3): {} ({:?})", info.name, info.backend); + Ok(Dev { device, queue, info, limits, layout, pipeline_layout: pl, k, dummy }) +} + +impl Dev { + fn matmul16(&self) -> &Matmul { + self.k.matmul16.get_or_init(|| Matmul { + pipeline: pipeline(&self.device, &self.pipeline_layout, "sam3 matmul f16", &matmul_source(TILE, true), "main"), + tile: TILE, + }) + } +} + +fn pipeline(device: &wgpu::Device, layout: &wgpu::PipelineLayout, label: &str, source: &str, entry: &str) -> wgpu::ComputePipeline { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(layout), + module: &module, + entry_point: Some(entry), + // every kernel writes its workgroup memory before reading it + compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }, + cache: None, + }) +} + +/// The matrix-product kernel for `tile` (`bk` 16 with `f16` weights), written out from `wgsl/sam3_matmul.wgsl`: one +/// variable per accumulator and per prefetched vector. +fn matmul_source(tile: Tile, f16: bool) -> String { + matmul_source_with(tile, f16, None) +} + +/// [`matmul_source`] with `load_a` (the A-tile loader) from `a_loader` instead of the dense one (the neck's 3 × 3 +/// convolution, `sam3/neck.rs`). +fn matmul_source_with(tile: Tile, f16: bool, a_loader: Option<&str>) -> String { + let Tile { rows, cols, bk } = tile; + use std::fmt::Write; + let mut src = String::new(); + // keep the B-tile loader of this weight type, and the A-tile loader asked for + let mut keep = true; + for line in include_str!("wgsl/sam3_matmul.wgsl").lines() { + match line.trim() { + "// #if f32" => keep = !f16, + "// #if f16" => keep = f16, + "// #if dense" => keep = a_loader.is_none(), + "// #endif" => keep = true, + _ if keep => { + src.push_str(line); + src.push('\n'); + } + _ => {} + } + } + src.push_str(a_loader.unwrap_or_default()); + let (bm, bn) = (16 * rows, 16 * cols); + let a_vecs = bm * bk / 4; + let b_vecs = if f16 { bn * bk / 8 } else { bn * bk / 4 }; + let (mut decl, mut load, mut next, mut store_tile, mut compute, mut store) = + (String::new(), String::new(), String::new(), String::new(), String::new(), String::new()); + let w = |s: &mut String, line: String| { + s.push_str(&line); + s.push('\n'); + }; + for i in 0..rows { + let row: Vec = (0..cols).map(|j| format!("var c{i}_{j} = 0.0;")).collect(); + w(&mut decl, format!(" {}", row.join(" "))); + } + let b_type = if f16 { "array, 2>" } else { "vec4" }; + let b_load = if f16 { "load_b16" } else { "load_b" }; + for (l, start) in (0..a_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pa{l}: vec4;")); + let guard = if start + 256 > a_vecs { format!("if (tid + {start}u < {a_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pa{l} = load_a(m0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pa{l} = load_a(m0, k0 + BK, tid + {start}u); }}")); + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; As[e / KV * KS + e % KV] = pa{l}; }}")); + } + for (l, start) in (0..b_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pb{l}: {b_type};")); + let guard = if start + 256 > b_vecs { format!("if (tid + {start}u < {b_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pb{l} = {b_load}(n0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pb{l} = {b_load}(n0, k0 + BK, tid + {start}u); }}")); + let put = if f16 { + format!("let r = e / (BK / 8u) * KS + 2u * (e % (BK / 8u)); Bs[r] = pb{l}[0]; Bs[r + 1u] = pb{l}[1];") + } else { + format!("Bs[e / KV * KS + e % KV] = pb{l};") + }; + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; {put} }}")); + } + for i in 0..rows { + w(&mut compute, format!(" let a{i} = As[(ty + {}u) * KS + kv];", 16 * i)); + } + for j in 0..cols { + w(&mut compute, format!(" let b{j} = Bs[(tx + {}u) * KS + kv];", 16 * j)); + } + for c in ["x", "y", "z", "w"] { + for i in 0..rows { + let mut line = String::from(" "); + for j in 0..cols { + // writing into a String cannot fail + let _ = write!(line, " c{i}_{j} = fma(a{i}.{c}, b{j}.{c}, c{i}_{j});"); + } + w(&mut compute, line); + } + } + for i in 0..rows { + w(&mut store, format!(" {{\n let m = m0 + ty + {}u;\n if (m < p.m) {{", 16 * i)); + for j in 0..cols { + w(&mut store, format!(" put(m, n0 + tx + {}u, c{i}_{j});", 16 * j)); + } + w(&mut store, " }\n }".into()); + } + src.replace("{{WEIGHT}}", if f16 { "vec4" } else { "vec4" }) + .replace("{{BM}}", &bm.to_string()) + .replace("{{BN}}", &bn.to_string()) + .replace("{{BK}}", &bk.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{LOAD}}", &load) + .replace("{{LOAD_NEXT}}", &next) + .replace("{{STORE_TILE}}", &store_tile) + .replace("{{COMPUTE}}", &compute) + .replace("{{STORE}}", &store) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_attention.wgsl`: one variable per q +/// and output vector and per score. +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qkv[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = d{j}.x + d{j}.y + d{j}.z + d{j}.w;\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("wgsl/sam3_attention.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// The adapter the SAM 3 backbone would use ("NVIDIA GeForce RTX 5070 (Vulkan)"), or why it cannot use one. Creates +/// the device on first use. +pub fn adapter() -> Result { + dev().map(|d| format!("{} ({:?})", d.info.name, d.info.backend)) +} + +// --------------------------------------------------------------------------------------------------------------------- +// steps: one dispatch each, recorded once + +/// One dispatch: a kernel, its parameters, its buffers (bindings 1–3 read, 4 written) and its workgroup counts. +struct Pending { + pipeline: &'static wgpu::ComputePipeline, + params: [u32; 8], + buffers: [wgpu::Buffer; 4], + groups: [u32; 3], +} + +/// A recorded dispatch, ready to replay. +struct Step { + pipeline: &'static wgpu::ComputePipeline, + bind: wgpu::BindGroup, + groups: [u32; 3], +} + +fn u32_of(v: usize) -> Result { + u32::try_from(v).ok().filter(|v| *v < (1 << 31)).ok_or_else(|| "a tensor too large for the SAM 3 kernels".to_string()) +} + +/// How the linear layers' weights are stored on the device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Precision { + /// As in the checkpoint. + F32, + /// Halves, two per u32 (along k): half the memory and weight traffic; the products still run in f32. + F16, +} + +/// Builds a list of dispatches. +struct Graph { + dev: &'static Dev, + steps: Vec, + /// Where command buffers end (indices into `steps`): one submission each. + cuts: Vec, +} + +impl Graph { + fn new(dev: &'static Dev) -> Graph { + Graph { dev, steps: Vec::new(), cuts: Vec::new() } + } + + /// Workgroups for `count` items of 256 (or `count` workgroups), and the row length the kernel reads back. + fn flat(&self, count: usize) -> Result<([u32; 3], u32), String> { + let limit = (self.dev.limits.max_compute_workgroups_per_dimension as usize).min(65_535); + let blocks = count.max(1); + let row = blocks.min(limit); + let rows = blocks.div_ceil(row); + if rows > limit { + return Err("a step too large for the SAM 3 kernels".into()); + } + Ok(([u32_of(row)?, u32_of(rows)?, 1], u32_of(row)?)) + } + + fn push(&mut self, pipeline: &'static wgpu::ComputePipeline, params: [u32; 8], buffers: [&wgpu::Buffer; 4], groups: [u32; 3]) { + let buffers = buffers.map(Clone::clone); + self.steps.push(Pending { pipeline, params, buffers, groups }); + } + + /// End a command buffer here. + fn cut(&mut self) { + if self.cuts.last() != Some(&self.steps.len()) { + self.cuts.push(self.steps.len()); + } + } + + /// `y = act(x · wᵀ + bias[row % bias_rows])` (or `y +=` with `residual`): x `[m, k]`, w `[n, k]` (f32, or f16 + /// pairs), bias `[bias_rows, n]`, y `[m, n]`. + #[allow(clippy::too_many_arguments)] + fn matmul( + &mut self, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + precision: Precision, + ) -> Result<(), String> { + let kernel = match precision { + Precision::F32 => &self.dev.k.matmul, + Precision::F16 => self.dev.matmul16(), + }; + self.matmul_with(kernel, precision, [x, w, bias, y], (m, n, k), bias_rows, gelu, residual) + } + + /// [`Graph::matmul`] with the pipeline `kernel` (benchmarks of other tiles). + #[allow(clippy::too_many_arguments)] + fn matmul_with( + &mut self, + kernel: &'static Matmul, + precision: Precision, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + ) -> Result<(), String> { + let step = match precision { + Precision::F32 => 4, + Precision::F16 => kernel.tile.bk as usize, + }; + if !k.is_multiple_of(step) || bias_rows == 0 { + return Err(format!("a {m}×{k}·{k}×{n} product the SAM 3 kernel cannot do")); + } + let params = [u32_of(m)?, u32_of(n)?, u32_of(k)?, u32_of(bias_rows)?, u32::from(gelu), u32::from(residual), 0, 0]; + let groups = [u32_of(n.div_ceil(kernel.tile.bn()))?, u32_of(m.div_ceil(kernel.tile.bm()))?, 1]; + self.push(&kernel.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// Layer norm of `rows` rows of `c` numbers: `y = (x − mean) / sqrt(var + eps) · gamma + beta`. + fn layernorm(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// RoPE on the q and k of `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) in place, from a table of + /// `table_rows` positions (token t uses row t % table_rows), and q scaled by `scale`. + fn rope( + &mut self, + qkv: &wgpu::Buffer, + table: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + table_rows: usize, + scale: f32, + ) -> Result<(), String> { + if hidden % HEAD_DIM != 0 || table_rows == 0 { + return Err("a RoPE the SAM 3 kernel cannot do".into()); + } + let count = tokens.checked_mul(hidden).ok_or("too many tokens")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(stride)?, u32_of(hidden)?, u32_of(table_rows)?, 0, scale.to_bits(), u32_of(count)?, row]; + self.push(&self.dev.k.rope, params, [dummy, table, dummy, qkv], g); + Ok(()) + } + + /// Attention of every head over `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) into `out` + /// (`[tokens, hidden]`), each query over the `span` tokens of its window. + fn attention( + &mut self, + qkv: &wgpu::Buffer, + out: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + span: usize, + ) -> Result<(), String> { + if span == 0 + || !span.is_multiple_of(64) + || !span.is_multiple_of(ATTENTION_KEYS as usize) + || !tokens.is_multiple_of(span) + || !hidden.is_multiple_of(HEAD_DIM) + || !stride.is_multiple_of(4) + { + return Err("an attention the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(span)?, u32_of(stride)?, u32_of(hidden)?, 0, 0, 0, 0]; + let groups = [u32_of(tokens / 64)?, u32_of(hidden / HEAD_DIM)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many tokens for the SAM 3 attention kernel".into()); + } + self.push(&self.dev.k.attention, params, [qkv, dummy, dummy, out], groups); + Ok(()) + } + + /// The patches of `pixels` (`[channels, side, side]`) as rows of `[tokens, channels · patch²]`, in window order. + fn im2col( + &mut self, + pixels: &wgpu::Buffer, + cols: &wgpu::Buffer, + (side, patch, channels): (usize, usize, usize), + window: usize, + ) -> Result<(), String> { + let grid = side / patch.max(1); + if patch == 0 || window == 0 || grid % window != 0 { + return Err("a patch embedding the SAM 3 kernel cannot do".into()); + } + let count = grid * grid * channels * patch * patch; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(side)?, u32_of(patch)?, u32_of(grid)?, u32_of(window)?, u32_of(channels)?, 0, u32_of(count)?, row]; + self.push(&self.dev.k.im2col, params, [pixels, dummy, dummy, cols], g); + Ok(()) + } + + /// Tokens `[grid², channels]` in window order to `[channels, grid, grid]`. + fn channels_first(&mut self, x: &wgpu::Buffer, out: &wgpu::Buffer, channels: usize, grid: usize, window: usize) -> Result<(), String> { + if window == 0 || !grid.is_multiple_of(window) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels * grid * grid; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&self.dev.k.to_chw, [u32_of(channels)?, u32_of(grid)?, u32_of(window)?, 0, 0, 0, u32_of(count)?, row], [x, dummy, dummy, out], g); + Ok(()) + } + + /// The bind groups, with every step's parameters in one uniform buffer. + fn record(self) -> Recorded { + let d = self.dev; + let align = (d.limits.min_uniform_buffer_offset_alignment as usize).max(32); + let mut blob = vec![0u8; self.steps.len().max(1) * align]; + for (chunk, s) in blob.chunks_mut(align).zip(&self.steps) { + if let Some(to) = chunk.get_mut(..32) { + to.copy_from_slice(bytemuck::cast_slice(&s.params)); + } + } + let uniform = d.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sam3 params"), + contents: &blob, + usage: wgpu::BufferUsages::UNIFORM, + }); + let steps = self + .steps + .iter() + .enumerate() + .map(|(i, s)| { + let [a, b, c, out] = &s.buffers; + let bind = d.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &d.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniform, + offset: (i * align) as u64, + size: wgpu::BufferSize::new(32), + }), + }, + wgpu::BindGroupEntry { binding: 1, resource: a.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: b.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: c.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: out.as_entire_binding() }, + ], + }); + Step { pipeline: s.pipeline, bind, groups: s.groups } + }) + .collect(); + let mut cuts = self.cuts; + if cuts.last() != Some(&self.steps.len()) { + cuts.push(self.steps.len()); + } + Recorded { steps, cuts } + } +} + +/// Dispatches ready to replay, with where each command buffer ends. +struct Recorded { + steps: Vec, + cuts: Vec, +} + +impl Recorded { + /// Submit every step (one command buffer per cut), copy `len` floats of `src` into `staging` after the last, + /// wait and read them back. + /// Run the recorded dispatches of `stage` (its name for the reason a hung device is given up on) and read `len` + /// floats of `src` back. + fn run(&self, stage: &str, dev: &Dev, src: &wgpu::Buffer, staging: &wgpu::Buffer, len: usize) -> Result, String> { + let bytes = len as u64 * 4; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let mut from = 0; + let mut last = None; + for (n, &to) in self.cuts.iter().enumerate() { + let mut enc = dev.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sam3") }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("sam3"), timestamp_writes: None }); + for s in self.steps.get(from..to).unwrap_or_default() { + pass.set_pipeline(s.pipeline); + pass.set_bind_group(0, &s.bind, &[]); + let [x, y, z] = s.groups; + pass.dispatch_workgroups(x, y, z); + } + } + if n + 1 == self.cuts.len() { + enc.copy_buffer_to_buffer(src, 0, staging, 0, bytes); + } + last = Some(dev.queue.submit([enc.finish()])); + from = to; + } + let slice = staging.slice(..bytes); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + let waited = dev.device.poll(wgpu::PollType::Wait { submission_index: last, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + // the read-back buffer must not stay mapped, whatever failed: the next pass copies into it + let mapped = if waited.is_ok() { rx.recv_timeout(Duration::from_secs(10)).map_err(|e| e.to_string()) } else { Err("not finished".into()) }; + let out = (|| { + if let Some(e) = oom { + return Err(format!("the GPU ran out of memory: {e}")); + } + if let Some(e) = validation { + mark_broken(&format!("device error: {e}")); + return Err(format!("the GPU reported an error: {e}")); + } + if let Err(e) = &waited { + mark_broken(&format!("the GPU did not finish {stage}: {e}")); + return Err(format!("the GPU did not finish: {e}")); + } + match &mapped { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("reading the result back failed: {e}")), + Err(e) => return Err(format!("reading the result back failed: {e}")), + } + let data = slice.get_mapped_range().map_err(|e| format!("reading the result back failed: {e:?}"))?; + Ok(data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect::>()) + })(); + if matches!(mapped, Ok(Ok(()))) { + staging.unmap(); + } + let out = out?; + if out.len() != len { + return Err("the GPU returned a short result".into()); + } + Ok(out) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the backbone + +/// Device buffers, each `len` floats (`STORAGE | COPY_DST | COPY_SRC`), or uploaded from `data`. +fn buffer(dev: &Dev, label: &str, len: usize) -> wgpu::Buffer { + dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (len.max(4) * 4) as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }) +} + +/// A buffer holding `data`. Written through the queue rather than mapped at creation: a buffer the device has no +/// memory for then raises an out-of-memory error (and the caller tries something smaller), not a failed mapping. +fn upload(dev: &Dev, label: &str, data: &[T]) -> wgpu::Buffer { + let bytes: &[u8] = bytemuck::cast_slice(data); + let b = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (bytes.len() as u64).next_multiple_of(4).max(16), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + // write_buffer wants whole 4-byte words + if bytes.len().is_multiple_of(4) && !bytes.is_empty() { + dev.queue.write_buffer(&b, 0, bytes); + } + b +} + +/// The nearest f16 to `v` (ties to even), as its bits. +fn f16_bits(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + let round = |value: u32, shift: u32| -> u32 { + let rest = value & ((1 << shift) - 1); + let half = 1 << (shift - 1); + let r = value >> shift; + if rest > half || (rest == half && r & 1 == 1) { r + 1 } else { r } + }; + if e <= 0 { + // a subnormal half, or zero + if e < -10 { + return sign; + } + return sign | round(man | 0x80_0000, (14 - e) as u32) as u16; + } + // a carry out of the mantissa correctly bumps the exponent (up to infinity) + sign | round(((e as u32) << 23) | man, 13) as u16 +} + +/// Weights `[n, k]` as f16 pairs (k even): u32 i holds k 2i (low half) and 2i + 1. +fn pack_f16(w: &[f32]) -> Vec { + w.chunks(2) + .map(|p| u32::from(f16_bits(p.first().copied().unwrap_or(0.0))) | (u32::from(f16_bits(p.get(1).copied().unwrap_or(0.0))) << 16)) + .collect() +} + +/// The RoPE table of `Sam3ViTRotaryEmbedding` as `vit::rope_tables` makes it, for the tokens of a `side × side` grid +/// listed in window order (`window` per side; `side` itself: plain row-major), coordinates scaled by `scale`: +/// `[tokens, 32]` pairs (cos, sin), pair i of a head rotating by x · f_i (i < 16) or y · f_(i − 16). +fn rope_table(side: usize, window: usize, scale: f64) -> Vec { + let spatial = HEAD_DIM / 2; + let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); + let mut out = Vec::with_capacity(side * side * HEAD_DIM); + for t in 0..side * side { + let (row, col) = window_cell(t, side, window); + let (x, y) = (col as f64 * scale, row as f64 * scale); + for pos in [x, y] { + for f in &inv { + let a = (pos * f) as f32 as f64; + out.extend([a.cos() as f32, a.sin() as f32]); + } + } + } + out +} + +/// The grid cell (row, col) of window-order token `t` on a `side × side` grid of `window × window` windows. +fn window_cell(t: usize, side: usize, window: usize) -> (usize, usize) { + let per_side = (side / window.max(1)).max(1); + let (w, l) = (t / (window * window).max(1), t % (window * window).max(1)); + (w / per_side * window + l / window.max(1), w % per_side * window + l % window.max(1)) +} + +/// One layer's weights on the device. +struct LayerWeights { + ln1: [wgpu::Buffer; 2], + qkv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the backbone's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + precision: Precision, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{BACKBONE_PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + Ok(data) + } + + /// A small tensor (a bias, a norm's scale…), always f32. + fn small(&mut self, name: &str, shape: &[usize]) -> Result { + let data = self.read(name, shape)?; + self.bytes += data.len() as u64 * 4; + Ok(upload(self.dev, name, &data)) + } + + /// A linear layer's weight `[n, k]` (concatenated along n when there are several) in the backbone's precision. + fn weight(&mut self, names: &[&str], n: usize, k: usize) -> Result { + let mut all = Vec::with_capacity(names.len() * n * k); + for name in names { + all.extend(self.read(name, &[n, k])?); + } + self.store(names.first().copied().unwrap_or("weight"), &all) + } + + fn store(&mut self, label: &str, data: &[f32]) -> Result { + Ok(match self.precision { + Precision::F32 => { + self.bytes += data.len() as u64 * 4; + upload(self.dev, label, data) + } + Precision::F16 => { + let packed = pack_f16(data); + self.bytes += packed.len() as u64 * 4; + upload(self.dev, label, &packed) + } + }) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.small(&format!("{name}.weight"), &[HIDDEN])?, self.small(&format!("{name}.bias"), &[HIDDEN])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let a = format!("{l}.attention"); + let qkv_names = [format!("{a}.q_proj.weight"), format!("{a}.k_proj.weight"), format!("{a}.v_proj.weight")]; + let qkv_names: Vec<&str> = qkv_names.iter().map(String::as_str).collect(); + let mut qkv_bias = Vec::with_capacity(3 * HIDDEN); + for p in ["q_proj", "k_proj", "v_proj"] { + qkv_bias.extend(self.read(&format!("{a}.{p}.bias"), &[HIDDEN])?); + } + self.bytes += qkv_bias.len() as u64 * 4; + Ok(LayerWeights { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + qkv: [self.weight(&qkv_names, HIDDEN, HIDDEN)?, upload(self.dev, "qkv bias", &qkv_bias)], + o: [self.weight(&[&format!("{a}.o_proj.weight")], HIDDEN, HIDDEN)?, self.small(&format!("{a}.o_proj.bias"), &[HIDDEN])?], + ln2: self.norm(&format!("{l}.layer_norm2"))?, + fc1: [self.weight(&[&format!("{l}.mlp.fc1.weight")], MLP, HIDDEN)?, self.small(&format!("{l}.mlp.fc1.bias"), &[MLP])?], + fc2: [self.weight(&[&format!("{l}.mlp.fc2.weight")], HIDDEN, MLP)?, self.small(&format!("{l}.mlp.fc2.bias"), &[HIDDEN])?], + }) + } +} + +/// The buffers of a forward pass. +struct Work { + pixels: wgpu::Buffer, + out: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The SAM 3 backbone on the GPU: weights, work buffers and every dispatch of a forward pass, made once. +pub struct Sam3Gpu { + dev: &'static Dev, + recorded: Recorded, + /// One forward pass at a time (they share the work buffers). + work: Mutex, + /// Bytes of weights on the device. + weight_bytes: u64, + /// Bytes of work buffers on the device. + work_bytes: u64, + precision: Precision, +} + +/// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, +/// broken, a software adapter, too small, or out of memory). The weights take 1.8 GB of device memory, or 0.9 GB as f16 +/// when the f32 ones do not fit. +pub fn backbone(weights: &WeightReader) -> Result, String> { + match load(weights, Precision::F32) { + Ok(b) => Ok(Box::new(b)), + // half the memory (0.9 GB of weights), a little less accurate (see `docs/gpu-pipeline.md`) + Err(e) if e.starts_with(NO_MEMORY) => { + log::info!("gpu (sam3): {e}; trying f16 weights"); + Ok(Box::new(load(weights, Precision::F16)?)) + } + Err(e) => Err(e), + } +} + +/// How a build that ran out of device memory fails. +const NO_MEMORY: &str = "not enough GPU memory for the SAM 3 backbone"; + +/// [`backbone`] with the linear layers' weights stored in `precision`. +pub fn load(weights: &WeightReader, precision: Precision) -> Result { + let dev = dev()?; + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 backbone", || build(dev, weights, precision)) +} + +fn build(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, weights, precision); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("{NO_MEMORY}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 backbone: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let mut ld = Loader { weights, dev, precision: Precision::F32, bytes: 0 }; + // the patch embedding (K = 588, not a multiple of the f16 tile) and its position table stay f32 + let patch = ld.read("embeddings.patch_embeddings.projection.weight", &[HIDDEN, 3, PATCH, PATCH])?; + let patch = ld.store("patch embedding", &patch)?; + let pos = ld.small("embeddings.position_embeddings", &[1, POS_SIDE * POS_SIDE, HIDDEN])?; + let ln_pre = ld.norm("layer_norm")?; + ld.precision = precision; + let mut layers = Vec::with_capacity(LAYERS); + for i in 0..LAYERS { + layers.push(ld.layer(i)?); + // hand the queued uploads (~55 MB a layer) to the device, so their staging memory is freed as they land + dev.queue.submit([]); + } + let rope_window = upload(dev, "rope window", &rope_table(WINDOW, WINDOW, 1.0)); + let rope_global = upload(dev, "rope global", &rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64)); + + let pixels = buffer(dev, "sam3 pixels", 3 * IMAGE * IMAGE); + let x = buffer(dev, "sam3 hidden", TOKENS * HIDDEN); + let y = buffer(dev, "sam3 normed", TOKENS * HIDDEN); + // im2col, then q|k|v, then the MLP's hidden activations + let big = buffer(dev, "sam3 wide", TOKENS * MLP.max(3 * HIDDEN).max(PATCH_K)); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 read-back"), + size: (TOKENS * HIDDEN * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((3 * IMAGE * IMAGE + 3 * TOKENS * HIDDEN + TOKENS * MLP) * 4) as u64; + + let mut g = Graph::new(dev); + g.im2col(&pixels, &big, (IMAGE, PATCH, 3), WINDOW)?; + g.matmul([&big, &patch, &pos, &y], (TOKENS, HIDDEN, PATCH_K), POS_SIDE * POS_SIDE, false, false, Precision::F32)?; + g.layernorm([&y, &ln_pre[0], &ln_pre[1], &x], TOKENS, HIDDEN)?; + g.cut(); + for (i, l) in layers.iter().enumerate() { + let global = GLOBAL.contains(&i); + g.layernorm([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.qkv[0], &l.qkv[1], &big], (TOKENS, 3 * HIDDEN, HIDDEN), 1, false, false, precision)?; + let (table, rows, span) = if global { (&rope_global, TOKENS, TOKENS) } else { (&rope_window, WINDOW * WINDOW, WINDOW * WINDOW) }; + g.rope(&big, table, (TOKENS, 3 * HIDDEN, HIDDEN), rows, 1.0 / (HEAD_DIM as f32).sqrt())?; + g.attention(&big, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span)?; + g.matmul([&y, &l.o[0], &l.o[1], &x], (TOKENS, HIDDEN, HIDDEN), 1, false, true, precision)?; + g.layernorm([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.fc1[0], &l.fc1[1], &big], (TOKENS, MLP, HIDDEN), 1, true, false, precision)?; + g.matmul([&big, &l.fc2[0], &l.fc2[1], &x], (TOKENS, HIDDEN, MLP), 1, false, true, precision)?; + g.cut(); + } + g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; + let recorded = g.record(); + Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision }) +} + +/// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). +fn guarded(stage: &str, f: impl FnOnce() -> Result) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| { + mark_broken(&format!("{stage} on the GPU panicked")); + Err("the GPU runner gave up".into()) + }) +} + +impl Sam3Gpu { + /// Bytes of device memory the weights take. + pub fn weight_bytes(&self) -> u64 { + self.weight_bytes + } + + /// Bytes of device memory the work buffers take (activations, input, read-back). + pub fn work_bytes(&self) -> u64 { + self.work_bytes + (TOKENS * HIDDEN * 4) as u64 + } + + fn run(&self, pixels: &[f32]) -> Result, String> { + if pixels.len() != 3 * IMAGE * IMAGE { + return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let work = self.work.lock().unwrap_or_else(PoisonError::into_inner); + self.dev.queue.write_buffer(&work.pixels, 0, bytemuck::cast_slice(pixels)); + let out = self.recorded.run("the SAM 3 backbone", self.dev, &work.out, &work.staging, TOKENS * HIDDEN)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU backbone produced non-finite values".into()); + } + Ok(out) + } +} + +impl BackboneAccel for Sam3Gpu { + fn forward(&self, pixels: &[f32]) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + guarded("the SAM 3 backbone", || self.run(pixels)) + } + + fn closing(&self) -> bool { + crate::shutting_down() + } + + fn device(&self) -> String { + let weights = match self.precision { + Precision::F32 => "", + Precision::F16 => ", f16 weights", + }; + format!("{} ({:?}{weights})", self.dev.info.name, self.dev.info.backend) + } +} diff --git a/crates/gpu/src/sam3/tests.rs b/crates/gpu/src/sam3/tests.rs new file mode 100644 index 0000000000..d9f6050fe4 --- /dev/null +++ b/crates/gpu/src/sam3/tests.rs @@ -0,0 +1,458 @@ +//! The SAM 3 kernels against plain loops on small shapes (tiles cut off at the edges, several windows). The whole +//! backbone against candle: `tests/it/sam3_backbone.rs`. + +use super::*; + +pub(super) fn gpu() -> Option<&'static Dev> { + match dev() { + Ok(d) => Some(d), + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + None + } + } +} + +/// Deterministic values in −scale..scale. +pub(super) fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +pub(super) fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +pub(super) fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// GELU, erf form (candle's `gelu_erf`), with a high-precision erf: the kernel's approximation is what is checked. +pub(super) fn gelu(v: f64) -> f64 { + 0.5 * v * (1.0 + erf(v / std::f64::consts::SQRT_2)) +} + +/// erf to ~1e-15 (Taylor series near 0, continued fraction of erfc further out). +fn erf(x: f64) -> f64 { + let a = x.abs(); + let r = if a < 2.5 { + let (mut term, mut sum, mut n) = (a, a, 0.0); + while term.abs() > 1e-17 * sum.abs() { + n += 1.0; + term *= -a * a / n; + sum += term / (2.0 * n + 1.0); + } + sum * 2.0 / std::f64::consts::PI.sqrt() + } else { + // erfc(a) = exp(−a²)/√π · 1/(a + 1/2/(a + 1/(a + 3/2/(a + 2/(a + …))))) + let mut f = a; + for k in (1..60).rev() { + f = a + (k as f64 / 2.0) / f; + } + 1.0 - (-a * a).exp() / std::f64::consts::PI.sqrt() / f + }; + if x < 0.0 { -r } else { r } +} + +#[test] +fn erf_reference_is_right() { + for (x, want) in [(0.5, 0.520_499_877_813_046_5), (1.0, 0.842_700_792_949_714_9), (2.0, 0.995_322_265_018_952_7), (3.0, 0.999_977_909_503_001_4)] + { + assert!((erf(x) - want).abs() < 1e-13, "erf({x}) = {}", erf(x)); + assert!((erf(-x) + want).abs() < 1e-13); + } +} + +/// `y = act(x · wᵀ + bias[row % rows])` (+ y0) in f64. +#[allow(clippy::too_many_arguments)] +fn matmul_ref(x: &[f32], w: &[f32], bias: &[f32], y0: Option<&[f32]>, (m, n, k): (usize, usize, usize), rows: usize, act: bool) -> Vec { + let mut out = vec![0f32; m * n]; + for i in 0..m { + for j in 0..n { + let mut v = bias[(i % rows) * n + j] as f64; + for t in 0..k { + v += x[i * k + t] as f64 * w[j * k + t] as f64; + } + if act { + v = gelu(v); + } + if let Some(y0) = y0 { + v += y0[i * n + j] as f64; + } + out[i * n + j] = v as f32; + } + } + out +} + +#[test] +fn the_matrix_product_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + // whole tiles, cut-off tiles in every direction, K not a multiple of the tile's 16, a position-style bias table + for (case, (m, n, k, rows, act, residual)) in [ + (256, 128, 64, 1, false, false), + (200, 136, 52, 1, false, false), + (130, 300, 588, 7, false, false), + (77, 260, 96, 1, true, false), + (150, 129, 132, 1, false, true), + (5, 3, 4, 1, true, true), + ] + .into_iter() + .enumerate() + { + let x = values(m * k, case as u64, 1.0); + let w = values(n * k, 100 + case as u64, 0.2); + let bias = values(rows * n, 200 + case as u64, 0.5); + let y0 = values(m * n, 300 + case as u64, 1.0); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + d.queue.write_buffer(&by, 0, bytemuck::cast_slice(&y0)); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), rows, act, residual, Precision::F32).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &w, &bias, residual.then_some(&y0[..]), (m, n, k), rows, act); + let err = worst(&got, &want); + assert!(err < 2e-5 * (k as f32).sqrt().max(1.0), "case {case} ({m}×{n}×{k}): off by {err}"); + } +} + +#[test] +fn the_f16_matrix_product_uses_the_rounded_weights() { + let Some(d) = gpu() else { return }; + let (m, n, k) = (140, 200, 96); + let x = values(m * k, 1, 1.0); + let w = values(n * k, 2, 0.2); + let bias = values(n, 3, 0.5); + let rounded: Vec = w.iter().map(|v| f16_value(f16_bits(*v))).collect(); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &pack_f16(&w)), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), 1, true, false, Precision::F16).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &rounded, &bias, None, (m, n, k), 1, true); + let err = worst(&got, &want); + assert!(err < 1e-4, "off by {err}"); + // K must be a multiple of the f16 tile + assert!(Graph::new(d).matmul([&bx, &bw, &bb, &by], (m, n, 40), 1, false, false, Precision::F16).is_err()); +} + +/// The value of half `h` (test reference). +fn f16_value(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let (e, m) = (((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + sign * match e { + 0 => m * 2f32.powi(-24), + 0x1f => { + if m == 0.0 { + f32::INFINITY + } else { + f32::NAN + } + } + _ => (1.0 + m / 1024.0) * 2f32.powi(e - 15), + } +} + +#[test] +fn halves_round_to_nearest_even() { + for (v, h) in [ + (0.0f32, 0x0000u16), + (-0.0, 0x8000), + (1.0, 0x3c00), + (-2.0, 0xc000), + (65504.0, 0x7bff), + (65520.0, 0x7c00), + (1e10, 0x7c00), + (f32::INFINITY, 0x7c00), + (6.103_515_6e-5, 0x0400), + (5.960_464_5e-8, 0x0001), + (2.0e-8, 0x0000), + (0.333_333_34, 0x3555), + // exactly between 1 and the next half up (1 + 2⁻¹¹): ties to even (down), just above: up + (1.000_488_3, 0x3c00), + (1.000_488_4, 0x3c01), + ] { + assert_eq!(f16_bits(v), h, "{v}"); + } + assert!(f16_value(f16_bits(f32::NAN)).is_nan()); + // every half survives the round trip + for h in (0u16..0x7c00).step_by(7) { + assert_eq!(f16_bits(f16_value(h)), h); + } +} + +#[test] +fn layer_norm_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + for (rows, c) in [(7, 1024), (3, 300), (2, 4)] { + let x: Vec = values(rows * c, c as u64, 3.0).iter().enumerate().map(|(i, v)| v + (i / c) as f32).collect(); + let (gamma, beta) = (values(c, 5, 1.0), values(c, 6, 0.5)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| *v as f64).sum::() / c as f64; + let var = row.iter().map(|v| (*v as f64 - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((row[i] as f64 - mean) / (var + EPS as f64).sqrt() * gamma[i] as f64 + beta[i] as f64) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 2e-5, "{rows}×{c}: off by {err}"); + } +} + +/// `vit::apply_rope` (x·cos + rotate_pairwise(x)·sin) with the tables of `vit::rope_tables` for token `t`. +fn rope_ref(x: &[f32], table: &[f32], t: usize) -> Vec { + // the candle tables: [head_dim] cos and sin, each pair's value duplicated + let (mut cos, mut sin) = (Vec::new(), Vec::new()); + for i in 0..32 { + let (c, s) = (table[(t * 32 + i) * 2], table[(t * 32 + i) * 2 + 1]); + cos.extend([c, c]); + sin.extend([s, s]); + } + let mut out = vec![0f32; x.len()]; + for (h, head) in x.chunks(HEAD_DIM).enumerate() { + for i in 0..HEAD_DIM { + let rot = if i % 2 == 0 { -head[i + 1] } else { head[i - 1] }; + out[h * HEAD_DIM + i] = head[i] * cos[i] + rot * sin[i]; + } + } + out +} + +#[test] +fn rope_tables_follow_the_candle_port() { + // window table: plain row-major 24 × 24 positions; the global one lists the 72 × 72 grid in window order + let win = rope_table(WINDOW, WINDOW, 1.0); + let global = rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64); + assert_eq!(win.len(), WINDOW * WINDOW * 64); + assert_eq!(global.len(), TOKENS * 64); + // token 25 of a window is at (1, 1): x frequency 0 rotates by 1, y frequency 0 by 1 + assert!((win[(25 * 32) * 2] - 1f32.cos()).abs() < 1e-7); + assert!((win[(25 * 32 + 16) * 2 + 1] - 1f32.sin()).abs() < 1e-7); + // window-order token 576 (the second window's first) is cell (0, 24): x = 24 · (24 / 72) = 8 + assert_eq!(window_cell(576, GRID, WINDOW), (0, 24)); + assert!((global[(576 * 32) * 2] - 8f32.cos()).abs() < 1e-6); + assert!((global[(576 * 32 + 16) * 2] - 1.0).abs() < 1e-7, "y = 0"); + // every cell exactly once + let mut seen = vec![false; TOKENS]; + for t in 0..TOKENS { + let (r, c) = window_cell(t, GRID, WINDOW); + assert!(!seen[r * GRID + c]); + seen[r * GRID + c] = true; + } +} + +#[test] +fn rope_rotates_q_and_k_and_scales_q() { + let Some(d) = gpu() else { return }; + let (tokens, hidden, rows) = (40, 128, 16); + let stride = 3 * hidden; + let qkv = values(tokens * stride, 9, 1.0); + let table = rope_table(4, 4, 1.0); + let (bq, bt) = (buffer(d, "qkv", tokens * stride), upload(d, "table", &table)); + d.queue.write_buffer(&bq, 0, bytemuck::cast_slice(&qkv)); + let mut g = Graph::new(d); + g.rope(&bq, &bt, (tokens, stride, hidden), rows, 0.125).unwrap(); + let got = read(d, g, &bq, tokens * stride); + let mut want = qkv.clone(); + for t in 0..tokens { + let row = &qkv[t * stride..(t + 1) * stride]; + let q: Vec = rope_ref(&row[..hidden], &table, t % rows).iter().map(|v| v * 0.125).collect(); + let k = rope_ref(&row[hidden..2 * hidden], &table, t % rows); + want[t * stride..t * stride + hidden].copy_from_slice(&q); + want[t * stride + hidden..t * stride + 2 * hidden].copy_from_slice(&k); + } + let err = worst(&got, &want); + assert!(err < 1e-6, "off by {err}"); +} + +/// Softmax attention of each query over its window's `span` keys (q already scaled), f64. +fn attention_ref(qkv: &[f32], (tokens, stride, hidden): (usize, usize, usize), span: usize) -> Vec { + let mut out = vec![0f32; tokens * hidden]; + for h in 0..hidden / HEAD_DIM { + for t in 0..tokens { + let first = t / span * span; + let q = &qkv[t * stride + h * HEAD_DIM..][..HEAD_DIM]; + let s: Vec = (first..first + span) + .map(|j| q.iter().zip(&qkv[j * stride + hidden + h * HEAD_DIM..][..HEAD_DIM]).map(|(a, b)| *a as f64 * *b as f64).sum()) + .collect(); + let top = s.iter().fold(f64::MIN, |m, v| m.max(*v)); + let e: Vec = s.iter().map(|v| (v - top).exp()).collect(); + let sum: f64 = e.iter().sum(); + for c in 0..HEAD_DIM { + let v: f64 = (first..first + span).zip(&e).map(|(j, w)| w * qkv[j * stride + 2 * hidden + h * HEAD_DIM + c] as f64).sum(); + out[t * hidden + h * HEAD_DIM + c] = (v / sum) as f32; + } + } + } + out +} + +#[test] +fn windowed_and_global_attention_give_the_softmax_of_the_definition() { + let Some(d) = gpu() else { return }; + let (tokens, hidden) = (384, 128); + let stride = 3 * hidden; + // large scores: the online maximum must keep exp() in range + let qkv = values(tokens * stride, 11, 2.5); + let bq = upload(d, "qkv", &qkv); + for span in [64, 128, 384] { + let out = buffer(d, "out", tokens * hidden); + let mut g = Graph::new(d); + g.attention(&bq, &out, (tokens, stride, hidden), span).unwrap(); + let got = read(d, g, &out, tokens * hidden); + let want = attention_ref(&qkv, (tokens, stride, hidden), span); + let err = worst(&got, &want); + // relative to the outputs' size: Metal's exp() is a little less exact than Vulkan's + // (span 128 is off by 2.04e-5 on an M4 Pro, 8e-6 of the largest output) + let scale = want.iter().fold(1f32, |m, v| m.max(v.abs())); + assert!(err < 2e-5 * scale, "span {span}: off by {err} (scale {scale})"); + } + // windows must hold whole workgroups of queries + assert!(Graph::new(d).attention(&bq, &bq, (tokens, stride, hidden), 96).is_err()); +} + +#[test] +fn patches_go_in_and_out_of_window_order() { + let Some(d) = gpu() else { return }; + // 3 × 56 × 56 pixels, 14-pixel patches: a 4 × 4 grid of 2 × 2 windows + let (side, patch, window) = (56, 14, 2); + let grid = side / patch; + let k = 3 * patch * patch; + let pixels = values(3 * side * side, 12, 1.0); + let bp = upload(d, "pixels", &pixels); + let cols = buffer(d, "cols", grid * grid * k); + let mut g = Graph::new(d); + g.im2col(&bp, &cols, (side, patch, 3), window).unwrap(); + let got = read(d, g, &cols, grid * grid * k); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..3 { + for ky in 0..patch { + for kx in 0..patch { + let want = pixels[(ch * side + row * patch + ky) * side + col * patch + kx]; + assert_eq!(got[t * k + (ch * patch + ky) * patch + kx], want, "token {t}"); + } + } + } + } + // and back: channels-first on the grid + let channels = 8; + let tokens = values(grid * grid * channels, 13, 1.0); + let bt = upload(d, "tokens", &tokens); + let out = buffer(d, "chw", grid * grid * channels); + let mut g = Graph::new(d); + g.channels_first(&bt, &out, channels, grid, window).unwrap(); + let got = read(d, g, &out, grid * grid * channels); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..channels { + assert_eq!(got[(ch * grid + row) * grid + col], tokens[t * channels + ch]); + } + } +} + +#[test] +fn the_kernel_source_is_written_out_for_both_weight_types() { + for f16 in [false, true] { + let src = matmul_source(TILE, f16); + assert!(!src.contains("{{"), "a mark left"); + assert_eq!(src.contains("fn load_b16"), f16); + assert_eq!(src.contains("fn load_b("), !f16); + assert_eq!(src.matches("= fma(").count() as u32, 4 * TILE.rows * TILE.cols); + } +} + +/// Kernel timings at the backbone's shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some(d) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * HIDDEN); + let b = buffer(d, "b", MLP); + let w16 = buffer(d, "w16", MLP * HIDDEN / 2); + for (n, k) in [(3 * HIDDEN, HIDDEN), (HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("matmul {TOKENS}x{n}x{k}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F32).unwrap()); + time(&format!("matmul f16 {TOKENS}x{n}x{k}"), flops, &|g| { + g.matmul([&x, &w16, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F16).unwrap() + }); + } + // other blockings (`LC_SAM3_TILES=rows,cols,bk;…`) + for t in std::env::var("LC_SAM3_TILES").unwrap_or_default().split(';').filter(|t| !t.is_empty()) { + let v: Vec = t.split(',').map(|v| v.trim().parse().unwrap()).collect(); + let tile = Tile { rows: v[0], cols: v[1], bk: v[2] }; + let kernel: &'static Matmul = + Box::leak(Box::new(Matmul { pipeline: pipeline(&d.device, &d.pipeline_layout, "variant", &matmul_source(tile, false), "main"), tile })); + for (n, k) in [(3 * HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("{tile:?} {n}x{k}"), flops, &|g| { + g.matmul_with(kernel, Precision::F32, [&x, &w, &b, &y], (TOKENS, n, k), 1, false, false).unwrap() + }); + } + } + time("matmul 5184x4736x1024 gelu", 2.0 * (TOKENS * MLP * HIDDEN) as f64, &|g| { + g.matmul([&x, &w, &b, &y], (TOKENS, MLP, HIDDEN), 1, true, false, Precision::F32).unwrap() + }); + for span in [WINDOW * WINDOW, TOKENS] { + let flops = 4.0 * (TOKENS * span * HIDDEN) as f64; + time(&format!("attention span {span}"), flops, &|g| g.attention(&x, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span).unwrap()); + } + time("layernorm", 0.0, &|g| g.layernorm([&x, &b, &b, &y], TOKENS, HIDDEN).unwrap()); + time("rope", 0.0, &|g| g.rope(&x, &w, (TOKENS, 3 * HIDDEN, HIDDEN), TOKENS, 0.125).unwrap()); +} + +/// An adapter without the storage-buffer size or the workgroup memory the kernels need gets no device (the model then +/// runs in candle on the CPU); the error names what it lacks. No GPU needed. +#[test] +fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() { + assert!(short_limits(&needed_limits()).is_empty()); + let short = short_limits(&wgpu::Limits { max_storage_buffer_binding_size: 64 << 20, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_storage_buffer_binding_size 67108864 <"), "{short:?}"); + let short = short_limits(&wgpu::Limits { max_compute_workgroup_storage_size: 8 << 10, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}"); +} diff --git a/crates/gpu/src/wgsl/sam3_attention.wgsl b/crates/gpu/src/wgsl/sam3_attention.wgsl new file mode 100644 index 0000000000..e9dca40da3 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_attention.wgsl @@ -0,0 +1,75 @@ +// Self-attention of the SAM 3 backbone (`sam3.rs`), flash style: the scores are never stored. Each query keeps a +// running maximum, softmax denominator and weighted sum of values while the keys stream past (online softmax), so a +// global layer (5184 tokens, 16 heads) needs no 16 x 5184² score matrix. +// +// qkv [tokens, stride]: per token q | k | v, each `hidden` wide (heads x 64), q and k already rotated (RoPE) +// and q already scaled by 1 / sqrt(64) +// out [tokens, hidden] +// +// Tokens are in window order, so a query's keys are the `span` tokens of its window: a contiguous range (span = all +// tokens for the global layers). A workgroup is 64 queries of one head (span is a multiple of 64, so they share +// their window), one query per thread with its q and its partial output in registers; keys and values pass through +// workgroup memory KB at a time, read by all 64 threads at once (a broadcast). The host writes out the per-thread +// work with one variable per vector and score (the DECL, SCORES, RESCALE, ACCUMULATE and STORE marks): arrays indexed +// in loops can end up in slow local memory. + +struct P { + tokens: u32, + span: u32, + stride: u32, + hidden: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qkv: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step +const D4: u32 = 16u; +const KB: u32 = {{KB}}u; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let qw = wg.x * 64u; + let tq = qw + lid; + let s4 = p.stride / 4u; + let h4 = p.hidden / 4u; + let first = qw / p.span * p.span; + // a whole workgroup returns together (tokens is a multiple of 64): the barriers below stay uniform + if (qw >= p.tokens) { + return; + } + let qa = tq * s4 + head * D4; + +{{DECL}} + var m = -3.0e38; + var l = 0.0; + + for (var k0 = 0u; k0 < p.span; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = first + k0 + e / D4; + let c = head * D4 + e % D4; + Ks[e] = qkv[t * s4 + h4 + c]; + Vs[e] = qkv[t * s4 + 2u * h4 + c]; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + let r = 1.0 / l; + let oa = tq * h4 + head * D4; +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_matmul.wgsl b/crates/gpu/src/wgsl/sam3_matmul.wgsl new file mode 100644 index 0000000000..7ccc17f7f1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_matmul.wgsl @@ -0,0 +1,138 @@ +// The linear layers of the SAM 3 backbone (`sam3.rs`): Y = act(X · Wᵀ + bias), or Y += X · Wᵀ + bias (a residual); +// act is none, GELU (gelu = 1) or ReLU (gelu = 2, the DETR encoder's MLP, `sam3/detr.rs`). +// +// X [M, K] row-major activations +// W [N, K] row-major: the checkpoint's own layout (f32; or, with the f16 variant, pairs of halves packed into +// u32s, k first) +// bias [bias_rows, N]: row m adds bias row m % bias_rows (1: an ordinary bias; 576: the patch embedding's +// 24 x 24 position table, which repeats over the windows) +// Y [M, N] +// +// K is a multiple of 4 (of BK for the f16 variant); M and N are anything. A workgroup of 256 threads (16 x 16) makes a +// BM x BN block of Y, TM x TN values per thread: rows ty + 16 i and columns tx + 16 j, so neighbouring threads write +// neighbouring numbers. K is walked in steps of BK through workgroup memory, where both tiles are kept k-contiguous +// as they are loaded (four k per vector), each row padded by one vector so that the eight threads of a 128-bit load +// phase read eight different bank groups. The next step's tiles are fetched into registers while the current one is +// multiplied. The host writes out the per-thread work with one variable per accumulator (the DECL, LOAD, STORE_TILE, +// COMPUTE and STORE marks): arrays indexed in loops can end up in slow local memory. + +struct P { + m: u32, + n: u32, + k: u32, + bias_rows: u32, + gelu: u32, + residual: u32, + // the image side of the 3 x 3 convolution's loader (`sam3_conv.wgsl`); unused here + side: u32, + pad: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var x: array>; +@group(0) @binding(2) var w: array<{{WEIGHT}}>; +@group(0) @binding(3) var bias: array; +@group(0) @binding(4) var y: array; + +const BM: u32 = {{BM}}u; +const BN: u32 = {{BN}}u; +const BK: u32 = {{BK}}u; +// vectors per tile row, and the padded row stride +const KV: u32 = BK / 4u; +const KS: u32 = KV + 1u; + +var As: array, BM * KS>; +var Bs: array, BN * KS>; + +// #if dense +// Vector e of the A tile at k0 (row e / KV); zero outside X. +fn load_a(m0: u32, k0: u32, e: u32) -> vec4 { + let m = m0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (m < p.m && kq < k4) { + return x[m * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f32 +// Vector e of the B tile at k0 (row e / KV of W); zero outside W. +fn load_b(n0: u32, k0: u32, e: u32) -> vec4 { + let n = n0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (n < p.n && kq < k4) { + return w[n * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f16 +// The f16 variant: packed vector e of the B tile at k0 (eight k of row e / (BK / 8)), as two f32 vectors. +fn load_b16(n0: u32, k0: u32, e: u32) -> array, 2> { + let n = n0 + e / (BK / 8u); + let kq = k0 / 8u + e % (BK / 8u); + let k8 = p.k / 8u; + var v = vec4(0u); + if (n < p.n && kq < k8) { + v = w[n * k8 + kq]; + } + return array, 2>(vec4(unpack2x16float(v.x), unpack2x16float(v.y)), vec4(unpack2x16float(v.z), unpack2x16float(v.w))); +} +// #endif + +fn erf(v: f32) -> f32 { + // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7) + let a = abs(v); + let t = 1.0 / (1.0 + 0.3275911 * a); + let poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))); + let r = 1.0 - poly * exp(-a * a); + return select(-r, r, v >= 0.0); +} + +fn put(m: u32, n: u32, acc: f32) { + if (n >= p.n) { + return; + } + var v = acc + bias[(m % p.bias_rows) * p.n + n]; + if (p.gelu == 1u) { + // GELU, exact (erf) form + v = 0.5 * v * (1.0 + erf(v * 0.7071067811865476)); + } else if (p.gelu == 2u) { + // ReLU (the DETR encoder's MLP) + v = max(v, 0.0); + } + let o = m * p.n + n; + if (p.residual != 0u) { + v += y[o]; + } + y[o] = v; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) tid: u32) { + let n0 = wg.x * BN; + let m0 = wg.y * BM; + let tx = tid % 16u; + let ty = tid / 16u; + +{{DECL}} + +{{LOAD}} + for (var k0 = 0u; k0 < p.k; k0 += BK) { +{{STORE_TILE}} + workgroupBarrier(); + if (k0 + BK < p.k) { +{{LOAD_NEXT}} + } + for (var kv = 0u; kv < KV; kv++) { +{{COMPUTE}} + } + workgroupBarrier(); + } + +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_ops.wgsl b/crates/gpu/src/wgsl/sam3_ops.wgsl new file mode 100644 index 0000000000..a46d3ccad1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_ops.wgsl @@ -0,0 +1,143 @@ +// The small steps of the SAM 3 backbone (`sam3.rs`) around its matrix products and attention: layer norm, rotary +// position encoding, the patch embedding's im2col and the final reordering to channels-first. +// +// Tokens are kept in window order: token t = window · win² + (row % win) · win + col % win, windows row-major over +// the grid (win = 24 on the 72 x 72 grid). The per-token steps don't care; `im2col` puts the patches in this order +// and `to_chw` takes them out of it. +// +// One uniform block of up to eight numbers per step (`P`); flat dispatches cover `count` items, 256 per workgroup, +// workgroups in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// The position in window order of grid cell (row, col). +fn window_token(row: u32, col: u32, grid: u32, win: u32) -> u32 { + let w = row / win * (grid / win) + col / win; + return w * win * win + row % win * win + col % win; +} + +var red: array; + +fn reduce(lid: u32, v: f32) -> f32 { + red[lid] = v; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (lid < s) { + red[lid] += red[lid + s]; + } + workgroupBarrier(); + } + let total = red[0]; + workgroupBarrier(); + return total; +} + +// LayerNorm over rows of `c` numbers (a: rows, b: c, e: eps bits): dst = (src − mean) / sqrt(var + eps) · aux + aux2. +// One workgroup per row. +@compute @workgroup_size(256) +fn layernorm(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let row = wg.y * p.row + wg.x; + if (row >= p.a) { + return; + } + let c = p.b; + let base = row * c; + var s = 0.0; + for (var i = lid; i < c; i += 256u) { + s += src[base + i]; + } + let mean = reduce(lid, s) / f32(c); + var q = 0.0; + for (var i = lid; i < c; i += 256u) { + let d = src[base + i] - mean; + q += d * d; + } + let rstd = inverseSqrt(reduce(lid, q) / f32(c) + bitcast(p.e)); + for (var i = lid; i < c; i += 256u) { + dst[base + i] = (src[base + i] - mean) * rstd * aux[i] + aux2[i]; + } +} + +// Rotary position encoding of q and k in place, and q scaled (a: tokens, b: row stride, c: hidden = heads · 64, +// d: rows of the table, f: q scale bits). One thread per pair (x, y) of neighbouring numbers of a head: +// (x cos − y sin, y cos + x sin), cos and sin from row t % d of `aux` ([rows, 32] pairs of cos, sin). +@compute @workgroup_size(256) +fn rope(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let half = p.c / 2u; + let t = g / p.c; + let r = g % p.c; + let which = r / half; + let pair = r % half; + let i = t * p.b + which * p.c + 2u * pair; + let at = ((t % p.d) * 32u + pair % 32u) * 2u; + let cs = aux[at]; + let sn = aux[at + 1u]; + let x = dst[i]; + let y = dst[i + 1u]; + let scale = select(1.0, bitcast(p.f), which == 0u); + dst[i] = (x * cs - y * sn) * scale; + dst[i + 1u] = (y * cs + x * sn) * scale; +} + +// The patches as rows, in window order (a: image side, b: patch, c: grid side, d: window, e: channels): +// dst[t, (ch · patch + ky) · patch + kx] = src[ch, row · patch + ky, col · patch + kx] for the cell (row, col) of t. +@compute @workgroup_size(256) +fn im2col(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let side = p.a; + let size = p.b; + let grid = p.c; + let k = p.e * size * size; + let t = g / k; + let r = g % k; + let ch = r / (size * size); + let ky = r / size % size; + let kx = r % size; + // the cell of window-order token t + let win = p.d; + let w = t / (win * win); + let l = t % (win * win); + let row = w / (grid / win) * win + l / win; + let col = w % (grid / win) * win + l % win; + dst[g] = src[(ch * side + row * size + ky) * side + col * size + kx]; +} + +// Tokens in window order to channels-first (a: channels, b: grid side, c: window): dst[ch, row, col] = src[t, ch]. +@compute @workgroup_size(256) +fn to_chw(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let n = p.b * p.b; + let ch = g / n; + let cell = g % n; + let t = window_token(cell / p.b, cell % p.b, p.b, p.c); + dst[g] = src[t * p.a + ch]; +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index d26d1efc94..184916cfb0 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -7,3 +7,5 @@ mod equivalence; mod fallback; #[cfg(not(target_arch = "wasm32"))] mod gpu_probe; +#[cfg(feature = "sam")] +mod sam3_backbone; diff --git a/crates/gpu/tests/it/sam3_backbone.rs b/crates/gpu/tests/it/sam3_backbone.rs new file mode 100644 index 0000000000..66741d6a3a --- /dev/null +++ b/crates/gpu/tests/it/sam3_backbone.rs @@ -0,0 +1,143 @@ +//! The SAM 3 backbone on the GPU against the candle backbone on the CPU (the reference), on one photo, and what the +//! difference does to the masks downstream (a click mask and a Describe mask). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_backbone:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`; then the backbone is also checked against +//! Hugging Face's). `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"); `LIGHTCRAFT_SAM3_GPU_F16=1` +//! stores the GPU weights as f16 (bounds as for f32 do not apply then: the errors are printed). Skipped without a +//! model or a GPU. + +use std::path::PathBuf; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, Click, INPUT, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!("{name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +/// The largest |Δ| between two masks' logits, and between the masks themselves (their sigmoid, 0..1). +fn mask_diff(a: &[f32], b: &[f32]) -> (f32, f32) { + let sigmoid = |v: f32| 1.0 / (1.0 + (-v).exp()); + a.iter().zip(b).fold((0f32, 0f32), |(l, m), (x, y)| (l.max((x - y).abs()), m.max((sigmoid(*x) - sigmoid(*y)).abs()))) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`, and the reference backbone (72 × 72 tokens of 1024) if there +/// is a reference file. +fn photo() -> (Tensor, Option) { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return (r.remove("pixel_values").unwrap(), r.remove("backbone")); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + (Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap(), None) +} + +#[test] +fn the_gpu_backbone_matches_the_cpu_backbone() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let (pixels, reference) = photo(); + let mut cpu = Sam3::load_on(&dir, Device::Cpu).unwrap(); + let want_f16 = std::env::var("LIGHTCRAFT_SAM3_GPU_F16").is_ok_and(|v| v == "1"); + let mut gpu = if want_f16 { + let make = |w: &WeightReader| -> Result, String> { Ok(Box::new(sam3::load(w, Precision::F16)?)) }; + Sam3::load_accelerated(&dir, Device::Cpu, make).unwrap() + } else { + Sam3::load_accelerated(&dir, Device::Cpu, sam3::backbone).unwrap() + }; + assert!(gpu.backbone_device().starts_with(&adapter[..adapter.len() - 1]), "the accelerator is in use"); + // f16 weights asked for, or the fallback `sam3::backbone` takes when the f32 ones don't fit: the f16 bounds apply + let f16 = want_f16 || gpu.backbone_device().contains("f16 weights"); + if f16 { + eprintln!("f16 weights: {}", gpu.backbone_device()); + } + + let t = std::time::Instant::now(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + eprintln!("CPU backbone: {:?}", t.elapsed()); + let t = std::time::Instant::now(); + let mut got = gpu.encode_pixels(&pixels).unwrap(); + eprintln!("GPU backbone (first run): {:?} on {adapter}", t.elapsed()); + // a GPU that failed on the photo leaves it to candle, which would compare the CPU with itself + assert!(gpu.accelerated(), "the GPU backbone ran (it fell back: {:?})", gpu.backbone_fallback()); + // the bounds of `docs/gpu-pipeline.md`: f16 weights are ~20 × further off (max rel 3.8e-3, mean abs 5.4e-4 measured) + let (rel_max, mean_max) = if f16 { (1e-2, 1e-3) } else { (2e-3, 1e-4) }; + let (a, b) = (values(got.backbone()), values(want.backbone())); + let (_, rel, mean) = errors("GPU vs CPU backbone", &a, &b); + assert!(rel < rel_max && mean < mean_max, "the GPU backbone is off"); + if let Some(r) = reference { + let hf = values(&r.reshape((1, 72, 72, 1024)).unwrap().permute((0, 3, 1, 2)).unwrap()); + let (_, cpu_rel, _) = errors("CPU vs Hugging Face", &b, &hf); + let (_, gpu_rel, _) = errors("GPU vs Hugging Face", &a, &hf); + assert!(gpu_rel < rel_max && cpu_rel < 2e-3); + } + + // a click mask (the tracker head) and a Describe mask (the detector head) from both + for click in [Click { x: 0.5, y: 0.6, positive: true }, Click { x: 0.3, y: 0.3, positive: true }] { + let (m_cpu, m_gpu) = (cpu.segment_clicks(&mut want, &[click]).unwrap(), gpu.segment_clicks(&mut got, &[click]).unwrap()); + let i = iou(&m_gpu.logits, &m_cpu.logits); + let (dl, dm) = mask_diff(&m_gpu.logits, &m_cpu.logits); + eprintln!( + "click ({}, {}): mask IoU {i:.5}, max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + click.x, click.y, m_gpu.score, m_cpu.score + ); + assert!(i > 0.99, "click mask IoU {i}"); + } + let prompt = std::env::var("LIGHTCRAFT_SAM3_PROMPT").unwrap_or_else(|_| "sky".into()); + let (d_cpu, d_gpu) = (cpu.segment_text(&mut want, &prompt, 0.5).unwrap(), gpu.segment_text(&mut got, &prompt, 0.5).unwrap()); + match (d_cpu, d_gpu) { + (Some(c), Some(g)) => { + let i = iou(&g.logits, &c.logits); + let (dl, dm) = mask_diff(&g.logits, &c.logits); + let cover = c.logits.iter().filter(|v| **v > 0.0).count() as f32 / c.logits.len() as f32; + eprintln!( + "describe {prompt:?}: mask IoU {i:.5} (covers {:.1} %), max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + cover * 100.0, + g.score, + c.score + ); + assert!(i > 0.98, "describe mask IoU {i}"); + } + (None, None) => eprintln!("describe {prompt:?}: nothing found by either"), + (c, g) => panic!("describe {prompt:?}: CPU found {}, GPU {}", c.is_some(), g.is_some()), + } +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index d5be5523f3..342f25fbb9 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -73,6 +73,7 @@ pub const TABLE: &[(&str, Class)] = &[ /// Explicit orderings *within* a layer (earlier may be used by later). /// L0: `raster` builds on `color` and `geom`; `color` uses `geom` for matrices. /// L1: `raw` and `codecs` read metadata through `meta`; `develop` uses `meta` for XMP. +/// L3: `gpu` runs the SAM 3 backbone of `segment` (its `sam` feature). pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["geom", "color", "raster"], &["tiff", "raster"], @@ -82,6 +83,7 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["meta", "develop"], &["develop", "scenes"], &["codecs", "raw"], + &["segment", "gpu"], ]; fn intra_layer_allowed(from: &str, to: &str) -> bool { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7ce3cb4234..339fa1669a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -358,7 +358,11 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { Box::new(|| { let mut c = cargo(); c.args(["clippy", "--workspace", "--all-targets", "--keep-going", "--", "-D", "warnings"]); - run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings") + run(c, "cargo clippy --workspace --all-targets --keep-going -- -D warnings")?; + // the GPU crate's optional parts (the SAM 3 kernels may be off in the workspace build) + let mut c = cargo(); + c.args(["clippy", "-p", "lightcraft-gpu", "--features", "denoise,sam", "--all-targets", "--keep-going", "--", "-D", "warnings"]); + run(c, "cargo clippy -p lightcraft-gpu --features denoise,sam --all-targets --keep-going -- -D warnings") }), ), ( @@ -397,7 +401,7 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut failed = Vec::new(); for (backend, adapter) in backends { let step = format!("gpu-{backend}"); - let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise"])); + let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise,sam"])); c.env("LIGHTCRAFT_GPU_BACKEND", &backend).env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, &step)); let t = std::time::Instant::now(); let ok = run(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} {what}")).is_ok(); From dbb754fe187d04effec94ffb36788e5f48d497a6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:08:51 +0200 Subject: [PATCH 022/247] i18n(de): the GPU hint for AI masks uses du, like the rest of the German UI Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 529cebe691..5599c06131 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3445,5 +3445,5 @@ "Run on": "Ausführen auf", "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", - "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wähle CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } From 7cc1bc6d12dcbd24e16c315c19cb4a46f470a46e Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:19:51 +0200 Subject: [PATCH 023/247] =?UTF-8?q?LR-BEHAV-LOCALIZE:=20menu=20paths=20wit?= =?UTF-8?q?h=20=E2=86=92,=20not=20the=20=E2=96=B8=20no=20UI=20font=20has?= =?UTF-8?q?=20(#1950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inter has no glyph for U+25B8 "▸", and neither has egui's proportional fallbacks or any craft-fonts face, so every UI string that used it as a menu-path separator painted a box, in English and in every language that falls back to English for the message. - 23 string literals in 17 files (ui-egui, engine, the desktop and web apps) use → instead, as all 14 catalogs already translate it and as the English text already did next to it ("then View → Reference View"). The 8 catalog keys whose source changed are renamed in every catalog, translations untouched. - What's New keeps ▸ like the other docs; the dialog shows it as → (dialogs::whats_new_line), and the notes' ✕ and full-width + as × and +. - The chips' "+N more" remove mark ✕ (in no installed face) is ×; the intersecting mask component's ∩ (borrowed from BIZ UDPGothic in release builds, a box without craft-fonts) is drawn. - i18n test source_strings_use_paintable_symbols: every symbol in the string literals of non-test code and in What's New as shown has a glyph in the fonts the build installs. string_literals, the small lexer it reads the sources with, has a test of its own. - docs/localization.md: write menu paths with →. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-web/src/web.rs | 4 +- apps/lightcraft/src/editors.rs | 2 +- apps/lightcraft/src/main.rs | 8 +- crates/engine/src/cmd/face_detect.rs | 2 +- crates/engine/src/cmd/face_models.rs | 2 +- crates/engine/src/cmd/geocode.rs | 2 +- crates/engine/src/denoise.rs | 2 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/segment/worker.rs | 2 +- crates/ui-egui/locales/cs-formats.json | 10 +- crates/ui-egui/locales/cs.json | 6 +- crates/ui-egui/locales/de-formats.json | 10 +- crates/ui-egui/locales/de.json | 6 +- crates/ui-egui/locales/es-formats.json | 10 +- crates/ui-egui/locales/es.json | 6 +- crates/ui-egui/locales/fr-formats.json | 10 +- crates/ui-egui/locales/fr.json | 6 +- crates/ui-egui/locales/it-formats.json | 10 +- crates/ui-egui/locales/it.json | 4 +- crates/ui-egui/locales/ja-formats.json | 10 +- crates/ui-egui/locales/ja.json | 6 +- crates/ui-egui/locales/ka-formats.json | 10 +- crates/ui-egui/locales/ka.json | 6 +- crates/ui-egui/locales/pl-formats.json | 10 +- crates/ui-egui/locales/pl.json | 4 +- crates/ui-egui/locales/pt-br-formats.json | 10 +- crates/ui-egui/locales/pt-br.json | 6 +- crates/ui-egui/locales/ru-formats.json | 10 +- crates/ui-egui/locales/ru.json | 6 +- crates/ui-egui/locales/uk-formats.json | 10 +- crates/ui-egui/locales/uk.json | 6 +- crates/ui-egui/locales/zh-hans-formats.json | 10 +- crates/ui-egui/locales/zh-hans.json | 6 +- crates/ui-egui/locales/zh-hant-formats.json | 10 +- crates/ui-egui/locales/zh-hant.json | 6 +- crates/ui-egui/src/i18n.rs | 206 ++++++++++++++++++++ crates/ui-egui/src/import.rs | 2 +- crates/ui-egui/src/menus.rs | 4 +- crates/ui-egui/src/panels/chips.rs | 2 +- crates/ui-egui/src/panels/compare.rs | 2 +- crates/ui-egui/src/panels/detail.rs | 2 +- crates/ui-egui/src/panels/dialogs.rs | 16 +- crates/ui-egui/src/panels/grid.rs | 2 +- crates/ui-egui/src/panels/keywording.rs | 2 +- crates/ui-egui/src/panels/mask_effects.rs | 2 +- crates/ui-egui/src/panels/masking.rs | 20 +- crates/ui-egui/src/panels/settings.rs | 4 +- docs/localization.md | 7 +- docs/whats-new.md | 6 + 49 files changed, 374 insertions(+), 133 deletions(-) diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 827b367f80..5b46283a64 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -359,7 +359,7 @@ async fn boot(opts: Options) -> Boot { if !granted { notice( "This browser may delete LightCraft's library when it runs short of space (persistent storage wasn't granted). \ - Keep your original photos elsewhere and use File ▸ Back Up Library… now and then.", + Keep your original photos elsewhere and use File → Back Up Library… now and then.", ); } }); @@ -460,7 +460,7 @@ impl WebApp { if backend.is_some() { notice( "LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \ - elsewhere and back up with File ▸ Back Up Library….", + elsewhere and back up with File → Back Up Library….", ); } // previews are large (≤ 2560 px, f32): keep few in a 32-bit address space diff --git a/apps/lightcraft/src/editors.rs b/apps/lightcraft/src/editors.rs index 3ca748f473..87f2cb6144 100644 --- a/apps/lightcraft/src/editors.rs +++ b/apps/lightcraft/src/editors.rs @@ -120,7 +120,7 @@ fn launcher(app: &str) -> Result { return Ok(if cfg!(target_os = "macos") { Launcher::MacApp(app.to_string()) } else { Launcher::Program(PathBuf::from(app)) }); } find_photocraft().ok_or_else(|| { - "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings ▸ External Editing.".to_string() + "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings → External Editing.".to_string() }) } diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 7d30e69cd4..f561f1cd43 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -162,7 +162,7 @@ fn gpu_crash_check_at(marker: Option, in_memory: bool) -> Op fn gpu_crash_notice(what: &str) -> String { format!( "LightCraft closed unexpectedly while starting the GPU last time ({what}), so GPU rendering is now off and photos render on the CPU. \ - To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; to try another graphics backend, start LightCraft with \ + To try the GPU again, turn on Settings → Performance → Use the GPU for rendering; to try another graphics backend, start LightCraft with \ LIGHTCRAFT_GPU_BACKEND=dx12, vulkan or off (see docs/gpu-pipeline.md → Troubleshooting)." ) } @@ -201,7 +201,7 @@ fn gpu_lost_check_at(marker: Option<&std::path::Path>, in_memory: bool) -> Optio } Some(format!( "LightCraft stopped last time after the graphics driver reset the GPU ({}) while photos rendered on it, so GPU rendering \ - is now off and photos render on the CPU. To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; \ + is now off and photos render on the CPU. To try the GPU again, turn on Settings → Performance → Use the GPU for rendering; \ an up-to-date graphics driver may help.", reason.trim() )) @@ -814,7 +814,7 @@ fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Optio Some(LaunchPath::Refused { path, why }) => { log::warn!("not importing {path} given at launch: {why}"); notices - .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File ▸ Import Photos…")); + .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File → Import Photos…")); } None => {} } @@ -1085,7 +1085,7 @@ fn stopped_text(error: &str, lost: Option<&str>) -> String { match lost { Some(reason) => format!( "{error}. The graphics driver reset the GPU ({reason}). LightCraft renders on the CPU from its next start; \ - Settings ▸ Performance ▸ Use the GPU for rendering turns the GPU back on" + Settings → Performance → Use the GPU for rendering turns the GPU back on" ), None => error.to_string(), } diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 711bebb102..611a841033 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -313,7 +313,7 @@ pub fn specs() -> Vec { "Face Models on the GPU", [], None, - "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings ▸ Faces), `false` checks the GPU again", + "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings → Faces), `false` checks the GPU again", always, gpu ), diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rs index 1ea39d04c1..dc7bbe0ee0 100644 --- a/crates/engine/src/cmd/face_models.rs +++ b/crates/engine/src/cmd/face_models.rs @@ -511,7 +511,7 @@ fn enable(s: &mut Session, p: &Value) -> Result { let usable = st.embedder.as_deref().is_some_and(|id| installed_models(&dir).iter().any(|i| i.manifest.id == id && i.manifest.role == Role::Embedder)); if on && !usable { - return Err(bad(C, "choose a recognition model first (Settings ▸ Faces ▸ Use)")); + return Err(bad(C, "choose a recognition model first (Settings → Faces → Use)")); } st.enabled = on; write_settings(&dir, &st)?; diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index feb9b033e9..9d924003b1 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -141,7 +141,7 @@ fn reverse(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "none of these photos has a GPS position")); } let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo ▸ Download Place Names)")))?; + let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Download Place Names)")))?; // a large selection shows in the activity stack and can be stopped let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes)); let mut ops = Vec::new(); diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index 8793b3a5bf..4c0d0df523 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -595,7 +595,7 @@ pub fn serving(dir: Option<&Path>, id: Option<&str>, run_on: RunOn) -> Result i.to_string(), None => read_settings(&dir).model.ok_or_else(|| { - format!("no denoise model is selected in {} (install one in Settings ▸ AI Denoise, or name it with --model)", dir.display()) + format!("no denoise model is selected in {} (install one in Settings → AI Denoise, or name it with --model)", dir.display()) })?, }; let installed = installed_models(&dir) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ff2b972c0a..13c68a88de 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -115,7 +115,7 @@ pub enum EngineError { /// The folder (or file) asked for is a Lightroom Classic catalog or part of one, not a /// LightCraft library (issue #891): nothing was created or opened. `catalog`: the `.lrcat` /// to import with `library.importLightroom`, when one was found. - #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File ▸ Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] + #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File → Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] LightroomCatalog { path: std::path::PathBuf, catalog: Option }, /// The work was cancelled (by the person, an agent or a newer request): not a failure. #[error("{0}")] diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..11914039e3 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -379,7 +379,7 @@ fn render(job: &mut Job) -> Result { Err(e) => { return Err(match &job.missing { Some(path) => format!( - "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library ▸ Find Missing Photos can relink it." + "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library → Find Missing Photos can relink it." ), None => format!("couldn't render the photo for AI masks: {e}"), }); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d..b3fcbd6aa4 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -35,7 +35,7 @@ "Added “{keyword}” to {n} photo{}": "K fotografiím přidáno „{keyword}“: {n}{:.0}", "Adding photos… {} of {}": "Přidávání fotografií… {} z {}", "All {n} selected photos move by the same amount.": "Všech {n} vybraných fotografií se posune o stejnou hodnotu.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", "Already in the library: {} photo{} selected in All Photos": "Již v knihovně: ve všech fotografiích vybráno: {}{:.0}", "Auto ({})": "Automaticky ({})", "Auto Import: added {} photo{}": "Automatický import: přidáno fotografií: {}{:.0}", @@ -80,7 +80,7 @@ "Imported {n} point curve preset{}": "Importovaná přednastavení bodové křivky: {n}{:.0}", "Imported {n} preset{}": "Importovaná přednastavení: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importovaná přednastavení: {n}{0:.0}, nečitelné soubory: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", "Imported {} photo{}": "Importováno fotografií: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Ve frontě na redukci šumu pomocí AI (před vámi: {ahead})…", "Insert at the cursor (also written {})": "Vložit na pozici kurzoru (také se zapisuje {})", @@ -206,7 +206,7 @@ "{n} photo{}": "fotografií: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Odpovídající fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", "{n} photo{} now · updates automatically as photos change": "Aktuální fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", + "{n} similar photo{} · View → Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", "{n} tasks are still running: {names}. Quitting stops them.": "Stále běží úlohy: {n}: {names}. Ukončení aplikace je zastaví.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -252,7 +252,7 @@ "Create the keyword “{name}”": "Vytvořit klíčové slovo „{name}“", "new, inside {parent}": "nové, pod {parent}", "Keywords of {n} selected photos": "Klíčová slova vybraných fotografií (počet: {n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", "Inside: {names}": "Uvnitř: {names}", " in {g} group{}": " ve skupinách: {g}{:.0}", " · kept, not applied: {}": " · zachováno, nepoužito: {}", @@ -263,7 +263,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Odstranit přednastavení efektů v počtu {n}{:.0}? Tuto akci nelze vrátit zpět.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Exportováno přednastavení efektů: {0}{1:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", "Update “{name}” with Current Settings": "Aktualizovat „{name}“ podle aktuálního nastavení", "{n} preset{}": "Přednastavení: {n}{:.0}", "{count} more warnings.": "Další varování: {count}.", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 16095a43eb..71ea24f13b 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1356,7 +1356,7 @@ "Photo Grid": "Mřížka fotografií", "Photo Grid (G)": "Mřížka fotografií (G)", "Photo Merge": "Sloučení fotografií", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Fotografie → Upravit v externím editoru (⇧⌘E) vykreslí 16bitovou kopii TIFF, přidá ji do sady s originálem a otevře v této aplikaci (název aplikace v macOS, jinde cesta k programu).", "PhotoCraft": "PhotoCraft", "Photos": "Fotografie", @@ -1541,7 +1541,7 @@ "Remove location info": "Odebrat informace o poloze", "Remove missing photos from the library": "Odebrat chybějící fotografie z knihovny", "Remove shortcut": "Odebrat zkratku", - "Remove this face box (undo with Edit ▸ Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", + "Remove this face box (undo with Edit → Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", "Remove this filter": "Odebrat tento filtr", "Remove this group": "Odebrat tuto skupinu", "Remove this rule": "Odebrat toto pravidlo", @@ -1627,7 +1627,7 @@ "Revert": "Vrátit změny", "Review": "Zkontrolovat", "Review Import": "Zkontrolovat import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", "Right-click a preset to delete it": "Přednastavení odstraníte kliknutím pravým tlačítkem", "Rights Usage Terms": "Podmínky použití práv", "Rotate": "Otočit", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f1364..b8ba3e3fef 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} zu {name} hinzugefügt", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", "Already in the library: {} photo{} selected in All Photos": "Bereits in der Bibliothek: {} Foto{} in „Alle Fotos“ ausgewählt", "Auto ({})": "Automatisch ({})", "Auto Import: added {} photo{}": "Automatischer Import: {} Foto{} hinzugefügt", @@ -72,7 +72,7 @@ "Imported {n} point curve preset{}": "Importierte Punktkurvenvorgaben: {n}{:.0}", "Imported {n} preset{}": "Importierte Vorgaben: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importierte Vorgaben: {n}{0:.0}, nicht lesbare Dateien: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", "Imported {} photo{}": "{} Foto{} importiert", "Insert at the cursor (also written {})": "An Cursorposition einfügen (auch als {} geschrieben)", "Label Set: {name}": "Farbmarkierungssatz: {name}", @@ -195,7 +195,7 @@ "… and {more} more": "… und {more} weitere", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft kann diese RAW-Variante noch nicht dekodieren ({}). Du bearbeitest die eingebettete JPEG-Vorschau der Kamera. Sie enthält bereits deren Bildstil (z. B. Monochrom) und Weißabgleich.", "Filtered: {label}": "Gefiltert: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", + "{n} similar photo{} · View → Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", "Moved; {} photo(s) relinked": "Verschoben; {} Foto(s) neu verknüpft", "{} label (click more labels to show any of them)": "Farbmarkierung {} (weitere Farbmarkierungen auswählen, um alle passenden Fotos zu zeigen)", ", {} star{}": ", Sterne: {}{:.0}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Stichwort „{name}“ erstellen", "new, inside {parent}": "neu, in {parent}", "Keywords of {n} selected photos": "Stichwörter von {n} ausgewählten Fotos", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", "1 task is still running: {names}. Quitting stops it.": "1 Aufgabe läuft noch: {names}. Beenden bricht sie ab.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} Aufgaben laufen noch: {names}. Beenden bricht sie ab.", "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "{n} Effektvorgabe(n) löschen?{:.0} Dies kann nicht rückgängig gemacht werden.", "Effect: {name}": "Effekt: {name}", "Exported {} effect preset{}": "Exportierte Effektvorgaben: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", "Update “{name}” with Current Settings": "„{name}“ mit aktuellen Einstellungen aktualisieren", "{n} preset{}": "{n} Vorgabe(n){:.0}", "{name} opened in the other editor": "{name} im anderen Editor geöffnet", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 679e3b00fd..83bedcb748 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1236,7 +1236,7 @@ "Remove from survey": "Aus Übersicht entfernen", "Remove location info": "Ortsinformationen entfernen", "Remove shortcut": "Tastenkürzel entfernen", - "Remove this face box (undo with Edit ▸ Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", + "Remove this face box (undo with Edit → Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", "Remove this filter": "Diesen Filter entfernen", "Remove this group": "Diese Gruppe entfernen", "Remove this rule": "Diese Regel entfernen", @@ -1292,7 +1292,7 @@ "Revert": "Zurück zum letzten Stand", "Review": "Überprüfung", "Review Import": "Import überprüfen", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", "Right-click a preset to delete it": "Rechtsklick auf eine Vorgabe, um sie zu löschen", "Rights Usage Terms": "Nutzungsbedingungen", "Rotate": "Drehen", @@ -2310,7 +2310,7 @@ "Same folder as original photo": "Im selben Ordner wie das Originalfoto", "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", "Zoom to Focus Point": "Auf Fokuspunkt zoomen", "Focus": "Fokus", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6..3b483ecb56 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} añadido a {name}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", "Already in the library: {} photo{} selected in All Photos": "Ya en la biblioteca: {0} foto{1} seleccionada{1} en Todas las fotos", "Auto ({})": "Automático ({})", "Auto Import: added {} photo{}": "Importación automática: {0} foto{1} añadida{1}", @@ -72,7 +72,7 @@ "Imported {n} point curve preset{}": "{n} ajuste{0} preestablecido{0} de curva de puntos importado{0}", "Imported {n} preset{}": "{n} ajuste{0} preestablecido{0} importado{0}", "Imported {n} preset{}, {f} file{} not readable": "{n} ajuste{0} preestablecido{0} importado{0}, {f} archivo{1} ilegible{1}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", "Imported {} photo{}": "{0} foto{1} importada{1}", "Insert at the cursor (also written {})": "Insertar en el cursor (también se escribe {})", "Label Set: {name}": "Conjunto de etiquetas: {name}", @@ -195,7 +195,7 @@ "… and {more} more": "… y {more} más", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft aún no puede decodificar esta variante RAW ({}). Se está editando la vista previa JPEG incrustada de la cámara, que ya incluye el estilo de imagen de la cámara (p. ej. Monocromo) y el balance de blancos.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) de nuevo", "{} label (click more labels to show any of them)": "Etiqueta {} (hacer clic en más etiquetas para mostrar cualquiera de ellas)", ", {} star{}": ", {} estrella{}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Crear la palabra clave “{name}”", "new, inside {parent}": "nueva, dentro de {parent}", "Keywords of {n} selected photos": "Palabras clave de {n} fotos seleccionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", "1 task is still running: {names}. Quitting stops it.": "1 tarea sigue en curso: {names}. Salir la detiene.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tareas siguen en curso: {names}. Salir las detiene.", "{what} merge cancelled": "Combinación {what} cancelada", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "¿Eliminar {n} ajuste(s) preestablecido(s) de efecto?{:.0} No se puede deshacer.", "Effect: {name}": "Efecto: {name}", "Exported {} effect preset{}": "Ajustes de efecto exportados: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", "Update “{name}” with Current Settings": "Actualizar «{name}» con los ajustes actuales", "{n} preset{}": "{n} ajuste(s){:.0}", "{name} opened in the other editor": "{name} abierto en el otro editor", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index af22570ef8..36f3d686bd 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1243,7 +1243,7 @@ "Remove from survey": "Quitar de Encuesta", "Remove location info": "Quitar información de ubicación", "Remove shortcut": "Quitar método abreviado", - "Remove this face box (undo with Edit ▸ Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", + "Remove this face box (undo with Edit → Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", "Remove this filter": "Quitar este filtro", "Remove this group": "Quitar este grupo", "Remove this rule": "Quitar esta regla", @@ -1299,7 +1299,7 @@ "Revert": "Revertir", "Review": "Revisión", "Review Import": "Revisar importación", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", "Right-click a preset to delete it": "Clic derecho en un ajuste preestablecido para eliminarlo", "Rights Usage Terms": "Condiciones de uso de los derechos", "Rotate": "Rotar", @@ -2313,7 +2313,7 @@ "Same folder as original photo": "Misma carpeta que la foto original", "Tidying the thumbnail cache": "Ordenando la caché de miniaturas", "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", "Focus Point": "Punto de enfoque", "Zoom to Focus Point": "Zoom al punto de enfoque", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e..8ea5098ccc 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what} ajouté à {name}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", "Already in the library: {} photo{} selected in All Photos": "Déjà dans la bibliothèque : {} photo{} sélectionnée(s) dans Toutes les photos", "Auto ({})": "Automatique ({})", "Auto Import: added {} photo{}": "Importation automatique : {} photo{} ajoutée(s)", @@ -65,7 +65,7 @@ "Imported {n} point curve preset{}": "{n} préréglage{} de courbe à points importé(s)", "Imported {n} preset{}": "{n} préréglage{} importé(s)", "Imported {n} preset{}, {f} file{} not readable": "{n} préréglage{} importé(s), {f} fichier{} illisible(s)", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Les fichiers annexes XMP de {n} photos n'ont pas pu être écrits (leur dossier est-il hors ligne ?). LightCraft continue d'essayer.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Le profil XMP « {profile} » n’a pas été appliqué à {path} ; les couleurs peuvent différer de Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La géométrie Lightroom de {path} n’a pas été conservée ; {mode} sera recalculé.", @@ -195,7 +195,7 @@ "… and {more} more": "… et {more} de plus", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ne peut pas encore décoder cette variante RAW ({}). Vous modifiez l’aperçu JPEG intégré de l’appareil photo, qui inclut déjà le style d’image (par ex. monochrome) et la balance des blancs de l’appareil.", "Filtered: {label}": "Filtré : {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", + "{n} similar photo{} · View → Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", "Moved; {} photo(s) relinked": "Déplacé ; {} photo(s) de nouveau associée(s)", "{} label (click more labels to show any of them)": "Étiquette {} (cliquez sur « autres étiquettes » pour afficher celles de votre choix)", ", {} star{}": ", {} étoile{}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Créer le mot-clé « {name} »", "new, inside {parent}": "nouveau, dans {parent}", "Keywords of {n} selected photos": "Mots-clés de {n} photos sélectionnées", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", "1 task is still running: {names}. Quitting stops it.": "1 tâche est encore en cours : {names}. Quitter l'arrête.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tâches sont encore en cours : {names}. Quitter les arrête.", "{what} merge cancelled": "Fusion {what} annulée", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Supprimer {n} paramètre(s) prédéfini(s) d’effet ?{:.0} Cette action est irréversible.", "Effect: {name}": "Effet : {name}", "Exported {} effect preset{}": "Paramètres d’effet exportés : {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", "Update “{name}” with Current Settings": "Mettre à jour « {name} » avec les réglages actuels", "{n} preset{}": "{n} paramètre(s){:.0}", "{name} opened in the other editor": "{name} ouvert dans l’autre éditeur", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 33a892ecf5..0cd4b699c5 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1177,7 +1177,7 @@ "Remove from survey": "Retirer de la vue multiple", "Remove location info": "Supprimer les informations de lieu", "Remove shortcut": "Supprimer le raccourci", - "Remove this face box (undo with Edit ▸ Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", + "Remove this face box (undo with Edit → Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", "Remove this filter": "Retirer ce filtre", "Remove this group": "Retirer ce groupe", "Remove this rule": "Retirer cette règle", @@ -1227,7 +1227,7 @@ "Revert": "Rétablir l'original", "Review": "Révision", "Review Import": "Vérifier l'importation", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", "Right-click a preset to delete it": "Clic droit sur un préréglage pour le supprimer", "Rights Usage Terms": "Conditions d'utilisation des droits", "Rotate": "Pivoter", @@ -2309,7 +2309,7 @@ "Same folder as original photo": "Même dossier que la photo d’origine", "Tidying the thumbnail cache": "Rangement du cache des miniatures", "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", "Focus Point": "Point de mise au point", "Zoom to Focus Point": "Zoomer sur le point de mise au point", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e94..649f2c811f 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Aggiunto a {name}: {what}", "Adding photos… {} of {}": "Aggiunta delle foto… {} di {}", "All {n} selected photos move by the same amount.": "Tutte le {n} foto selezionate si spostano della stessa quantità.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", "Already in the library: {} photo{} selected in All Photos": "Già nella libreria (selezionate in Tutte le foto): {}{:.0}", "Auto ({})": "Automatico ({})", "Auto Import: added {} photo{}": "Importazione automatica · foto aggiunte: {}{:.0}", @@ -70,7 +70,7 @@ "Imported {n} point curve preset{}": "Preset di curva a punti importati: {n}{:.0}", "Imported {n} preset{}": "Preset importati: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Preset importati: {n}{:.0}, file illeggibili: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", "Imported {} photo{}": "Foto importate: {}{:.0}", "Insert at the cursor (also written {})": "Inserisci al cursore (si scrive anche {})", "Label Set: {name}": "Set di etichette: {name}", @@ -192,7 +192,7 @@ "… and {more} more": "… e altre {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft non sa ancora decodificare questa variante raw ({}). Stai modificando l'anteprima JPEG incorporata dalla fotocamera, che contiene già lo stile immagine della fotocamera (ad es. Monocromatico) e il bilanciamento del bianco.", "Filtered: {label}": "Filtrate: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", + "{n} similar photo{} · View → Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", "Moved; {} photo(s) relinked": "Spostata; foto ricollegate: {}", "{} label (click more labels to show any of them)": "Etichetta {} (fai clic su altre etichette per mostrarne una qualsiasi)", ", {} star{}": ", stelle: {}{:.0}", @@ -264,7 +264,7 @@ "Keywords of {n} selected photos": "Parole chiave delle foto selezionate: {n}", "new, inside {parent}": "nuova, dentro {parent}", "Delete these {n} effect presets?": "Eliminare questi preset effetto ({n})?", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "{photos} catalog records processed; {collections} collections.": "Record del catalogo elaborati: {photos}; raccolte: {collections}.", "Skipped {problem}": "Saltato: {problem}", "Updated {name}": "{name} aggiornato", @@ -282,7 +282,7 @@ " · kept, not applied: {}": " · conservato, non applicato: {}", "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", "{n} raws can now be developed from their raw data": "Raw che ora si possono sviluppare dai loro dati raw: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "Al suo interno: {names}", "Template preview: {name}": "Anteprima del modello: {name}", "{n} photos in view · {slides} slides · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a75448fbb9..7ce5af6e9d 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1188,7 +1188,7 @@ "Remove from survey": "Rimuovi dalla panoramica", "Remove location info": "Rimuovi le informazioni sulla posizione", "Remove shortcut": "Rimuovi scorciatoia", - "Remove this face box (undo with Edit ▸ Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", + "Remove this face box (undo with Edit → Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", "Remove this filter": "Rimuovi questo filtro", "Remove this group": "Rimuovi questo gruppo", "Remove this rule": "Rimuovi questa regola", @@ -1263,7 +1263,7 @@ "Revert": "Ripristina", "Review": "Revisione", "Review Import": "Rivedi importazione", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", "Right-click a preset to delete it": "Clic destro su un preset per eliminarlo", "Rights Usage Terms": "Condizioni d'uso dei diritti", "Rotate": "Ruota", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16d..9e242f8b54 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "写真を追加中:{1}枚中{0}枚", " ({} in Recently Deleted)": "(うち{}枚は最近削除した写真)", "Already in the library: {} photo{} selected in All Photos": "ライブラリに登録済み:すべての写真で{}枚を選択しました{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", "Auto ({})": "自動 ({})", "Build 1:1 Previews ({scope})": "1:1プレビューを作成({scope})", "Build Smart Previews ({scope})": "スマートプレビューを作成({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。ガイド付き Upright の保存された変換はサポートされていません。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。保存された Upright の変換はサポートされていません。", "XMP adjustments were not imported for {path}: {fields}.": "{path} の XMP 調整は読み込まれませんでした:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", "Insert at the cursor (also written {})": "カーソル位置に挿入({}とも表記可)", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。フォント:{}(OFL)。アイコン:オリジナル", "Painting “{k}”: click photos to add or remove it · Esc stops": "「{k}」を適用中:写真をクリックして付け外し・Escで終了", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — この人物の写真を表示", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraftはこのRAWの形式({})をまだデコードできません。カメラの埋め込みJPEGプレビューを編集しています。このプレビューには、カメラのピクチャースタイル(モノクロなど)とホワイトバランスがすでに反映されています", "Filtered: {label}": "フィルター適用中:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", + "{n} similar photo{} · View → Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", "Moved; {} photo(s) relinked": "移動しました。{}枚の写真の参照先を更新しました", "{} label (click more labels to show any of them)": "{}ラベル(ほかのラベルもクリックすると、いずれかに一致する写真を表示)", ", {} star{}": "、星{}つ{:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "キーワード「{name}」を作成", "new, inside {parent}": "新規、{parent} の中", "Keywords of {n} selected photos": "選択した写真{n}枚のキーワード", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", "1 task is still running: {names}. Quitting stops it.": "1件のタスクが実行中です:{names}。終了すると停止します。", "{n} tasks are still running: {names}. Quitting stops them.": "{n}件のタスクが実行中です:{names}。終了すると停止します。", "{what} merge cancelled": "{what}合成をキャンセルしました", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "効果プリセット{n}件を削除しますか?{:.0}元に戻せません。", "Effect: {name}": "効果:{name}", "Exported {} effect preset{}": "効果プリセットを{}件書き出しました{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", + "Imported {e} mask effect{} (Masking → Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", "Update “{name}” with Current Settings": "「{name}」を現在の設定で更新", "{n} preset{}": "{n}件のプリセット{:.0}", "{name} opened in the other editor": "{name}を別のエディタで開きました", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index c3f11e6e56..3f5529988f 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -717,7 +717,7 @@ "Remove a filter above, or choose Clear all": "上のフィルターを解除するか、「すべて解除」を選択してください", "Remove from Target Album": "追加先アルバムから除去", "Remove shortcut": "ショートカットを削除", - "Remove this face box (undo with Edit ▸ Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", + "Remove this face box (undo with Edit → Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", "Rename Component": "構成要素の名前を変更", "Rename Folder": "フォルダ名を変更", "Rename Mask": "マスク名を変更", @@ -1177,7 +1177,7 @@ "Reverse the order": "逆順にする", "Review": "レビュー", "Review Import": "読み込み内容を確認", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", "Right-click a preset to delete it": "プリセットを右クリックして削除", "Rights Usage Terms": "利用条件", "Rotate": "回転", @@ -2311,7 +2311,7 @@ "Same folder as original photo": "元の写真と同じフォルダー", "Tidying the thumbnail cache": "サムネールキャッシュを整理中", "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", "Focus Point": "フォーカスポイント", "Zoom to Focus Point": "フォーカスポイントにズーム", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 4603682618..0c1e068134 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -35,7 +35,7 @@ "Added “{keyword}” to {n} photo{}": "„{keyword}“ დაემატა ფოტოს: {n}{:.0}", "Adding photos… {} of {}": "ფოტოების დამატება… {} / {}", "All {n} selected photos move by the same amount.": "მონიშნული ფოტოები ({n}) ერთი და იმავე სიდიდით გადაინაცვლებს.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", "Already in the library: {} photo{} selected in All Photos": "უკვე ბიბლიოთეკაშია: „ყველა ფოტოში“ მონიშნულია ფოტო: {}{:.0}", "Auto ({})": "ავტომატური ({})", "Auto Import: added {} photo{}": "ავტოიმპორტი: დაემატა ფოტო: {}{:.0}", @@ -80,7 +80,7 @@ "Imported {n} point curve preset{}": "იმპორტირებულია წერტილოვანი მრუდის პრესეტი: {n}{:.0}", "Imported {n} preset{}": "იმპორტირებულია პრესეტი: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "იმპორტირებულია პრესეტი: {n}{:.0}, ვერ იკითხება ფაილი: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", + "Imported {profiles} profile{} (Profile browser → their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", "Imported {} photo{}": "იმპორტირებულია ფოტო: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "AI ხმაურის მოცილების რიგში (წინ არის: {ahead})…", "Insert at the cursor (also written {})": "კურსორის ადგილას ჩასმა (ასევე იწერება როგორც {})", @@ -205,7 +205,7 @@ "{n} photo{}": "ფოტო: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "შესაბამისი ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", "{n} photo{} now · updates automatically as photos change": "ახლა ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", - "{n} similar photo{} · View ▸ Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", + "{n} similar photo{} · View → Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", "{n} tasks are still running: {names}. Quitting stops them.": "ჯერ კიდევ მიმდინარეობს ამოცანები ({n}): {names}. გასვლა მათ შეწყვეტს.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -262,12 +262,12 @@ "Effect: {name}": "Effect: {name}", "Exported to {path}": "Exported to {path}", "Exported {} effect preset{}": "Exported {} effect preset{}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", "Keywords of {n} selected photos": "Keywords of {n} selected photos", "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "შიგნით: {names}", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", "Saved template {name}": "Saved template {name}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 13fd48d3ce..26322e5a27 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1482,7 +1482,7 @@ "Photo Merge": "ფოტოების გაერთიანება", "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Canon CR2-ის (და სხვა RAW ფაილების, რომელთა ფერსაც LightCraft კამერის საკუთარი JPEG-იდან არგებს, როგორიცაა NEF და", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "„ფოტო“ მენიუში. კადრების ზოლსაც აქვს ფოტოს კონტექსტური მენიუ. ახლახან წაშლილში მყოფი ფაილის ხელახლა დამატება აღარ", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "ფოტო → რედაქტირება გარე რედაქტორში (⇧⌘E) ქმნის 16-ბიტიან TIFF ასლს, ორიგინალთან ერთად დასტაში აერთიანებს და აქ ხსნის (macOS-ზე აპის სახელი, სხვაგან — პროგრამის მისამართი).", "Photos": "ფოტოები", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "ფოტოები თქვენი მონიტორის ICC პროფილით ნაჩვენებია, ამიტომ ფერები სწორია ფართო ფერთა გამისა და დაკალიბრებულ ეკრანებზე, ხოლო დეტალური ხედი ეკრანის მთელ ფერთა გამას იყენებს. ჰისტოგრამაზე, წინასწარი ხედების ქეშებსა და ექსპორტზე ეს გავლენას არ ახდენს.", @@ -1686,7 +1686,7 @@ "Remove location info": "მდებარეობის ინფორმაციის წაშლა", "Remove missing photos from the library": "დაკარგული ფოტოების ბიბლიოთეკიდან ამოშლა", "Remove shortcut": "მალსახმობის წაშლა", - "Remove this face box (undo with Edit ▸ Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", + "Remove this face box (undo with Edit → Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", "Remove this filter": "ამ ფილტრის მოშორება", "Remove this group": "ამ ჯგუფის წაშლა", "Remove this rule": "ამ წესის წაშლა", @@ -1751,7 +1751,7 @@ "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "მარჯვენა დაწკაპუნება საქაღალდეზე (ან სასტარტოს გარდა სხვა დისკზე) გვერდითი ზოლის საქაღალდეების სექციაში → საქაღალდის", "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "მარჯვენა დაწკაპუნება საქაღალდეზე → ახალი → ალბომის შექმნა… / სმარტ-ალბომის შექმნა… / სმარტ-ალბომის შექმნა ფილტრიდან… / საქაღალდის შექმნა…", "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "მარჯვენა დაწკაპუნება ფოტოზე → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (ან ფოტო → რედაქტირება სხვა პროგრამაში, ⇧⌘E) არენდერებს ასლს თქვენი ცვლილებებით, ათავსებს მას", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", "Right-click a preset to delete it": "პრესეტის წასაშლელად დაწკაპეთ მასზე მარჯვენა ღილაკით", "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "მარჯვენა დაწკაპუნება → ახალი საკვანძო სიტყვების ამ საკვანძო სიტყვაში ჩასმა: + ღილაკით ან ზემოთ ველში აკრეფილი ახალი საკვანძო სიტყვები", "Rights Usage Terms": "უფლებების გამოყენების პირობები", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6..76fcc28a22 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Dodano {what} do {name}", "Adding photos… {} of {}": "Dodawanie zdjęć… {} z {}", "All {n} selected photos move by the same amount.": "Wszystkie {n} zaznaczone zdjęcia zostaną przesunięte o tę samą wartość.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", "Already in the library: {} photo{} selected in All Photos": "Już w bibliotece — zaznaczone zdjęcia we Wszystkich zdjęciach: {}{:.0}", "Auto ({})": "Automatycznie ({})", "Auto Import: added {} photo{}": "Automatyczny import — dodane zdjęcia: {}{:.0}", @@ -63,7 +63,7 @@ "Imported {n} point curve preset{}": "Zaimportowane ustawienia krzywej punktowej: {n}{:.0}", "Imported {n} preset{}": "Zaimportowane ustawienia wstępne: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Zaimportowane ustawienia wstępne: {n}{:.0}, nieczytelne pliki: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", "Imported {} photo{}": "Zaimportowane zdjęcia: {}{:.0}", "Insert at the cursor (also written {})": "Wstaw w miejscu kursora (zostanie też zapisane {})", "Label Set: {name}": "Zestaw etykiet: {name}", @@ -183,7 +183,7 @@ "… and {more} more": "… i jeszcze {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft nie obsługuje jeszcze tego wariantu RAW ({}). Edytujesz podgląd JPEG osadzony przez aparat, zawierający już styl obrazu aparatu (np. monochromatyczny) i balans bieli.", "Filtered: {label}": "Filtrowanie: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", + "{n} similar photo{} · View → Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", "Moved; {} photo(s) relinked": "Przeniesiono; ponownie powiązane zdjęcia: {}", "{} label (click more labels to show any of them)": "{} etykieta (kliknij kolejne etykiety, aby wyświetlić dowolną z nich)", ", {} star{}": ", gwiazdki: {}{:.0}", @@ -257,7 +257,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Usunąć ustawienia efektów ({n})?{:.0} Tej operacji nie można cofnąć.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Wyeksportowane ustawienia efektów: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", "Update “{name}” with Current Settings": "Zaktualizuj „{name}” bieżącymi ustawieniami", "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", @@ -284,7 +284,7 @@ "Create the keyword “{name}”": "Utwórz słowo kluczowe „{name}”", "new, inside {parent}": "nowe, w {parent}", "Keywords of {n} selected photos": "Słowa kluczowe zaznaczonych zdjęć ({n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft nieoczekiwanie zakończył działanie: {e}\n\nSzczegóły są w pliku dziennika: {path}", "LightCraft stopped unexpectedly: {e}": "LightCraft nieoczekiwanie zakończył działanie: {e}", "Renames {n} face{} across the library. The files are not changed.": "Zmienia nazwę twarzy w całej bibliotece (twarze: {n}).{:.0} Pliki nie są zmieniane.", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index f03a81762a..e243fd482f 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1149,7 +1149,7 @@ "Remove from survey": "Usuń z widoku przeglądu", "Remove location info": "Usuń informacje o lokalizacji", "Remove shortcut": "Usuń skrót klawiszowy", - "Remove this face box (undo with Edit ▸ Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", + "Remove this face box (undo with Edit → Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", "Remove this filter": "Usuń ten filtr", "Remove this group": "Usuń tę grupę", "Remove this rule": "Usuń tę regułę", @@ -1202,7 +1202,7 @@ "Revert": "Cofnij zmiany", "Review": "Przegląd", "Review Import": "Sprawdź import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", "Right-click a preset to delete it": "Kliknij ustawienie wstępne prawym przyciskiem, aby je usunąć", "Rights Usage Terms": "Warunki korzystania z praw", "Rotate": "Obróć", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4..70a5446654 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -15,7 +15,7 @@ "Added {n} photo{} to “{}”": "{n} foto{0} adicionada{0} a “{1}”", "Adding photos… {} of {}": "Adicionando fotos… {} de {}", "All {n} selected photos move by the same amount.": "Todas as {n} fotos selecionadas se movem pela mesma quantidade.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", "Already in the library: {} photo{} selected in All Photos": "Já na biblioteca: {0} foto{1} selecionada{1} em Todas as fotos", "Already in “{}”": "Já está em “{}”", "Auto ({})": "Automático ({})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright guiado não é compatível.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright não é compatível.", "XMP adjustments were not imported for {path}: {fields}.": "Os ajustes XMP não foram importados para {path}: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", "Insert at the cursor (also written {})": "Inserir no cursor (também escrito {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Fontes: {} (OFL). Ícones: originais.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Aplicando “{k}”: clique nas fotos para adicionar ou remover · Esc para", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — mostrar as fotos desta pessoa", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "O LightCraft ainda não consegue decodificar esta variante RAW ({}). Você está editando a prévia JPEG incorporada da câmera, que já inclui o estilo de imagem da câmera (p. ex. Monocromático) e o balanço de branco.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) novamente", "{} label (click more labels to show any of them)": "Rótulo {} (clique em mais rótulos para mostrar qualquer um deles)", ", {} star{}": ", {} estrela{}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "Criar a palavra-chave “{name}”", "new, inside {parent}": "nova, dentro de {parent}", "Keywords of {n} selected photos": "Palavras-chave de {n} fotos selecionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", "1 task is still running: {names}. Quitting stops it.": "1 tarefa ainda está em andamento: {names}. Sair a interrompe.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tarefas ainda estão em andamento: {names}. Sair as interrompe.", "{what} merge cancelled": "{what} mesclagem cancelada", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Excluir {n} predefinição(ões) de efeito?{:.0} Não é possível desfazer.", "Effect: {name}": "Efeito: {name}", "Exported {} effect preset{}": "Predefinições de efeito exportadas: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", "Update “{name}” with Current Settings": "Atualizar “{name}” com as configurações atuais", "{n} preset{}": "{n} predefinição(ões){:.0}", "{name} opened in the other editor": "{name} aberto no outro editor", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 88e955d263..665a6a0479 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1197,7 +1197,7 @@ "Remove from survey": "Remover da inspeção", "Remove location info": "Remover informações de local", "Remove shortcut": "Remover atalho", - "Remove this face box (undo with Edit ▸ Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", + "Remove this face box (undo with Edit → Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", "Remove this filter": "Remover este filtro", "Remove this group": "Remover este grupo", "Remove this rule": "Remover esta regra", @@ -1250,7 +1250,7 @@ "Revert": "Reverter", "Review": "Revisão", "Review Import": "Revisar importação", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", "Right-click a preset to delete it": "Clique com o botão direito em uma predefinição para excluí-la", "Rights Usage Terms": "Termos de uso dos direitos", "Rotate": "Girar", @@ -2151,7 +2151,7 @@ "Same folder as original photo": "Mesma pasta da foto original", "Tidying the thumbnail cache": "Organizando o cache de miniaturas", "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", "Focus Point": "Ponto de foco", "Zoom to Focus Point": "Zoom no ponto de foco", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af4276..48f3ce0ff6 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -27,7 +27,7 @@ "Added {what} to {name}": "{what}: добавлено в {name}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", "Already in the library: {} photo{} selected in All Photos": "Уже в библиотеке: выбрано фото в разделе «Все фото»: {}{:.0}", "Auto ({})": "Авто ({})", "Auto Import: added {} photo{}": "Автоимпорт: добавлено фото: {}{:.0}", @@ -75,7 +75,7 @@ "Imported {n} point curve preset{}": "Импортировано пресетов точечной кривой: {n}{:.0}", "Imported {n} preset{}": "Импортировано пресетов: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Импортировано пресетов: {n}{:.0}, не читается файлов: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", "Imported {} photo{}": "Импортировано фото: {}{:.0}", "Insert at the cursor (also written {})": "Вставить в позицию курсора (также пишется как {})", "Label Set: {name}": "Набор меток: {name}", @@ -169,7 +169,7 @@ "{n} photo{} match · updates automatically as photos change": "Подходящих фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} photo{} now · updates automatically as photos change": "Сейчас фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} selected photos · {pages} pages": "Выбрано фото: {n} · страниц: {pages}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", + "{n} similar photo{} · View → Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", "{pid} (missing)": "{pid} (отсутствует)", "{sel_n} selected · {counted}": "Выбрано: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Создать ключевое слово «{name}»", "new, inside {parent}": "новое, внутри {parent}", "Keywords of {n} selected photos": "Ключевые слова выбранных фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", "1 task is still running: {names}. Quitting stops it.": "Ещё выполняется задача: {names}. Выход прервёт её.", "{n} tasks are still running: {names}. Quitting stops them.": "Ещё выполняется задач: {n} — {names}. Выход прервёт их.", "{what} merge cancelled": "{what}: слияние отменено", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Удалить пресеты эффектов ({n})?{:.0} Это нельзя отменить.", "Effect: {name}": "Эффект: {name}", "Exported {} effect preset{}": "Экспортировано пресетов эффектов: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", + "Imported {e} mask effect{} (Masking → Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", "Update “{name}” with Current Settings": "Обновить «{name}» текущими настройками", "{n} preset{}": "Пресетов: {n}{:.0}", "{name} opened in the other editor": "{name} открыт в другом редакторе", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 5c8816c5ee..ec36bf878f 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1037,7 +1037,7 @@ "Retouch": "Ретушь", "Revert": "Вернуть", "Review Import": "Проверить импорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", "Right-click a preset to delete it": "Щёлкните пресет правой кнопкой, чтобы удалить его", "Rights Usage Terms": "Условия использования прав", "Rotate": "Повернуть", @@ -1972,7 +1972,7 @@ "Remove a filter above, or choose Clear all": "Уберите фильтр выше или выберите «Очистить всё»", "Remove from Library…": "Убрать из библиотеки…", "Remove from Target Album": "Убрать из целевого альбома", - "Remove this face box (undo with Edit ▸ Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", + "Remove this face box (undo with Edit → Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", "Rename Component": "Переименовать компонент", "Rename Folder… and Move Folder To… (Local) can be undone and redone (issue #97): the folder moves back on disk with": "Переименование папки… и перемещение папки в… («Локальное») можно отменить и повторить (проблема #97): папка возвращается на диске вместе с", "Rename Photos never overwrites another photo when only the letter case changes (issue #95): on case-sensitive": "Переименование фото никогда не перезаписывает другое фото, когда меняется только регистр букв (проблема #95): на томах с учётом регистра", @@ -2304,7 +2304,7 @@ "Same folder as original photo": "Та же папка, что и у оригинала", "Tidying the thumbnail cache": "Упорядочивание кэша миниатюр", "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", "Focus Point": "Точка фокусировки", "Zoom to Focus Point": "Увеличить по точке фокусировки", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a2..f937619cc6 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "{what}: додано до {name}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", "Already in the library: {} photo{} selected in All Photos": "Уже в бібліотеці: вибрано фото в усіх фото: {}{:.0}", "Auto ({})": "Автоматично ({})", "Auto Import: added {} photo{}": "Автоімпорт: додано фото: {}{:.0}", @@ -65,7 +65,7 @@ "Imported {n} point curve preset{}": "Імпортовано наборів налаштувань точкової кривої: {n}{:.0}", "Imported {n} preset{}": "Імпортовано наборів налаштувань: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Імпортовано наборів налаштувань: {n}{:.0}, файлів не читається: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не вдалося записати XMP-файли {n} фото (папка недоступна?). LightCraft продовжує спроби.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профіль XMP «{profile}» не застосовано до {path}; кольори можуть відрізнятися від Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Геометрію Lightroom для {path} не збережено; режим {mode} буде перераховано.", @@ -195,7 +195,7 @@ "… and {more} more": "… і ще {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ще не може декодувати цей варіант RAW ({}). Ви редагуєте вбудований JPEG-перегляд камери, який уже містить її стиль зображення (наприклад, монохромний) і баланс білого.", "Filtered: {label}": "Відфільтровано: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", + "{n} similar photo{} · View → Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", "Moved; {} photo(s) relinked": "Переміщено; повторно пов’язано фото: {}", "{} label (click more labels to show any of them)": "Мітка «{}» (клацніть інші мітки, щоб показати фото з будь-якою з них)", ", {} star{}": ", зірок: {}{:.0}", @@ -242,7 +242,7 @@ "Create the keyword “{name}”": "Створити ключове слово «{name}»", "new, inside {parent}": "нове, всередині {parent}", "Keywords of {n} selected photos": "Ключові слова вибраних фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", "1 task is still running: {names}. Quitting stops it.": "1 завдання ще виконується: {names}. Вихід зупинить його.", "{n} tasks are still running: {names}. Quitting stops them.": "Ще виконуються завдання ({n}): {names}. Вихід зупинить їх.", "{what} merge cancelled": "Об’єднання {what} скасовано", @@ -262,7 +262,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Видалити пресети ефектів ({n})?{:.0} Це не можна скасувати.", "Effect: {name}": "Ефект: {name}", "Exported {} effect preset{}": "Експортовано пресетів ефектів: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", + "Imported {e} mask effect{} (Masking → Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", "Update “{name}” with Current Settings": "Оновити «{name}» поточними налаштуваннями", "{n} preset{}": "Пресетів: {n}{:.0}", "{name} opened in the other editor": "{name} відкрито в іншому редакторі", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 39090c0b3e..8f54687b1a 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -927,7 +927,7 @@ "Remove a filter above, or choose Clear all": "Видаліть фільтр вище або виберіть «Очистити все»", "Remove from Target Album": "Вилучити з цільового альбому", "Remove shortcut": "Видалити скорочення", - "Remove this face box (undo with Edit ▸ Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", + "Remove this face box (undo with Edit → Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", "Rename Component": "Перейменувати компонент", "Rename Folder": "Перейменувати теку", "Rename Mask": "Перейменувати маску", @@ -1270,7 +1270,7 @@ "Restore them": "Відновити їх", "Retouch": "Ретушування", "Review Import": "Перевірити імпорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", "Right-click a preset to delete it": "Клацніть набір налаштувань правою кнопкою, щоб видалити його", "Rights Usage Terms": "Умови використання прав", "Rotate Crop": "Обертати кадрування", @@ -2309,7 +2309,7 @@ "Same folder as original photo": "Та сама папка, що й оригінал", "Tidying the thumbnail cache": "Упорядкування кешу мініатюр", "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", "Focus Point": "Точка фокусування", "Zoom to Focus Point": "Збільшити до точки фокусування", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b86..9950129cef 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "正在添加照片… 第 {0} 张,共 {1} 张", " ({} in Recently Deleted)": "(其中 {0} 张在“最近删除”中)", "Already in the library: {} photo{} selected in All Photos": "已在图库中:已在“所有照片”中选择 {0} 张照片{1:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", "Auto ({})": "自动({})", "Build 1:1 Previews ({scope})": "生成 1:1 预览({scope})", "Build Smart Previews ({scope})": "生成智能预览({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的引导 Upright 变换。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的 Upright 变换。", "XMP adjustments were not imported for {path}: {fields}.": "未导入 {path} 的 XMP 调整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", "Insert at the cursor (also written {})": "在光标处插入(也可写作 {0})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字体:{0}(OFL)。图标:原创。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在应用“{k}”:单击照片以添加或移除 · 按 Esc 停止", @@ -199,7 +199,7 @@ "{} — show their photos": "{0} — 显示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 暂时无法解码这种 RAW 变体({0})。你正在编辑相机内嵌的 JPEG 预览,其中已包含相机的照片风格(如单色)和白平衡。", "Filtered: {label}": "已筛选:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", "Moved; {} photo(s) relinked": "已移动;已重新链接 {0} 张照片", "{} label (click more labels to show any of them)": "{0}标签(单击更多标签可显示符合其中任一标签的照片)", ", {} star{}": ",{0} 星{1:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "创建关键字“{name}”", "new, inside {parent}": "新关键字,位于 {parent} 内", "Keywords of {n} selected photos": "所选 {n} 张照片的关键字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 个任务在运行:{names}。退出将停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 个任务在运行:{names}。退出将停止它们。", "{what} merge cancelled": "已取消 {what} 合并", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "删除 {n} 个效果预设?{:.0}此操作无法撤销。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已导出 {} 个效果预设{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", "Update “{name}” with Current Settings": "用当前设置更新“{name}”", "{n} preset{}": "{n} 个预设{:.0}", "{name} opened in the other editor": "已在其他编辑器中打开 {name}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 73caf6407e..df1560ac7b 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -661,7 +661,7 @@ "Remove a filter above, or choose Clear all": "请移除上方的某个筛选条件,或选择“全部清除”", "Remove from Target Album": "从目标相册中移除", "Remove shortcut": "移除快捷键", - "Remove this face box (undo with Edit ▸ Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", + "Remove this face box (undo with Edit → Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", "Rename Component": "重命名组件", "Reorder Masks": "重新排序蒙版", "Reset All": "全部重置", @@ -1234,7 +1234,7 @@ "Revert": "恢复", "Review": "审阅", "Review Import": "查看导入内容", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", "Right-click a preset to delete it": "右键单击预设即可将其删除", "Rights Usage Terms": "使用条款", "Rotate": "旋转", @@ -2144,7 +2144,7 @@ "Same folder as original photo": "与原始照片相同的文件夹", "Tidying the thumbnail cache": "正在整理缩略图缓存", "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", "Zoom to Focus Point": "缩放至对焦点", "Focus": "对焦", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a..85b252c516 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -141,7 +141,7 @@ "… and {more} more": "…以及另外 {more} 個", " ({} in Recently Deleted)": "(其中 {} 張在「最近刪除」中)", "Already in the library: {} photo{} selected in All Photos": "已在照片庫中:已在「所有照片」中選取 {} 張照片{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", "Remove “{name}” and its {count} photo{} from the library?": "要將「{name}」及其 {count} 張照片從照片庫移除嗎?{:.0}", " ({unsure} with several look-alike files: use Locate)": "(其中 {unsure} 張有多個相似檔案:請使用「尋找」)", " · {:.0}% clipped": " · {:.0}% 剪裁", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的引導 Upright 轉換。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的 Upright 轉換。", "XMP adjustments were not imported for {path}: {fields}.": "未匯入 {path} 的 XMP 調整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", "Insert at the cursor (also written {})": "在游標處插入(也可寫成 {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字型:{}(OFL)。圖示:原創。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在套用「{k}」:點擊照片即可加入或移除 · 按 Esc 停止", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — 顯示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 目前還無法解碼這種 RAW 變體({})。你正在編輯相機內嵌的 JPEG 預覽,其中已包含相機的相片風格(例如單色)與白平衡。", "Filtered: {label}": "已篩選:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", "Moved; {} photo(s) relinked": "已移動;已重新連結 {} 張照片", "{} label (click more labels to show any of them)": "{}標籤(點擊更多標籤可顯示符合其中任一標籤的照片)", ", {} star{}": ",{} 顆星{:.0}", @@ -246,7 +246,7 @@ "Create the keyword “{name}”": "建立關鍵字「{name}」", "new, inside {parent}": "新關鍵字,位於 {parent} 內", "Keywords of {n} selected photos": "選取的 {n} 張照片的關鍵字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 個工作在執行:{names}。結束將停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 個工作在執行:{names}。結束將停止它們。", "{what} merge cancelled": "已取消{what}合併", @@ -266,7 +266,7 @@ "Delete {n} effect preset{}? This can't be undone.": "刪除 {n} 個效果預設集?{:.0}此動作無法復原。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已匯出 {} 個效果預設集{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", "Update “{name}” with Current Settings": "以目前設定更新「{name}」", "{n} preset{}": "{n} 個預設集{:.0}", "{name} opened in the other editor": "已在其他編輯器中開啟 {name}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 72cc3ab7fb..5838de95ce 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -662,7 +662,7 @@ "Remove a filter above, or choose Clear all": "請移除上方的某個篩選條件,或選擇「全部清除」", "Remove from Target Album": "從目標相簿移除", "Remove shortcut": "移除快速鍵", - "Remove this face box (undo with Edit ▸ Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", + "Remove this face box (undo with Edit → Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", "Rename Component": "重新命名元件", "Reorder Masks": "重新排序遮色片", "Reset All": "全部重設", @@ -1235,7 +1235,7 @@ "Revert": "回復至上次儲存", "Review": "審閱", "Review Import": "檢視匯入", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", "Right-click a preset to delete it": "在預設集上按右鍵即可刪除", "Rights Usage Terms": "使用權利條款", "Rotate": "旋轉", @@ -2112,7 +2112,7 @@ "Same folder as original photo": "與原始照片相同的資料夾", "Tidying the thumbnail cache": "正在整理縮圖快取", "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", "Focus Point": "對焦點", "Zoom to Focus Point": "縮放至對焦點", diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 9ba1cd5afb..2f7f32993b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -907,6 +907,212 @@ mod tests { } } + /// The string literals of non-test code in `src`, with the line each starts on. Code under + /// `#[cfg(test)]` and comments are left out; escapes are decoded where they matter here (`\u{…}`, + /// line continuations). + fn string_literals(src: &str) -> Vec<(usize, String)> { + let chars: Vec = src.chars().collect(); + let at = |i: usize| chars.get(i).copied().unwrap_or('\0'); + let ident = |c: char| c.is_alphanumeric() || c == '_'; + let (mut out, mut i, mut line) = (Vec::new(), 0, 1); + let (mut depth, mut test_depth, mut pending_test) = (0usize, None, false); + while i < chars.len() { + let c = chars[i]; + let raw_start = if c == 'r' { + Some(i + 1) + } else if c == 'b' && at(i + 1) == 'r' { + Some(i + 2) + } else { + None + }; + let raw_hashes = raw_start.filter(|_| i == 0 || !ident(at(i - 1))).and_then(|start| { + let hashes = chars[start..].iter().take_while(|&&h| h == '#').count(); + (at(start + hashes) == '"').then_some((start, hashes)) + }); + if c == '\n' { + line += 1; + i += 1; + } else if c == '/' && at(i + 1) == '/' { + while i < chars.len() && chars[i] != '\n' { + i += 1; + } + } else if c == '/' && at(i + 1) == '*' { + let mut nested = 0; + while i < chars.len() { + if chars[i] == '/' && at(i + 1) == '*' { + nested += 1; + i += 2; + } else if chars[i] == '*' && at(i + 1) == '/' { + nested -= 1; + i += 2; + if nested == 0 { + break; + } + } else { + line += usize::from(chars[i] == '\n'); + i += 1; + } + } + } else if chars[i..].starts_with(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + pending_test = true; + i += 12; + } else if let Some((start, hashes)) = raw_hashes { + let (first, mut text) = (line, String::new()); + i = start + hashes + 1; + while i < chars.len() && !(chars[i] == '"' && chars[i + 1..].iter().take(hashes).filter(|&&h| h == '#').count() == hashes) { + line += usize::from(chars[i] == '\n'); + text.push(chars[i]); + i += 1; + } + i += 1 + hashes; + if test_depth.is_none() { + out.push((first, text)); + } + } else if c == '"' { + let (first, mut text) = (line, String::new()); + i += 1; + while i < chars.len() && chars[i] != '"' { + if chars[i] == '\\' { + match at(i + 1) { + '\n' => { + line += 1; + i += 2; + while at(i).is_whitespace() { + line += usize::from(at(i) == '\n'); + i += 1; + } + } + 'u' => { + let hex: String = chars[i + 3..].iter().take_while(|&&h| h != '}').collect(); + text.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + i += 4 + hex.len(); + } + escaped => { + text.push(escaped); + i += 2; + } + } + } else { + line += usize::from(chars[i] == '\n'); + text.push(chars[i]); + i += 1; + } + } + i += 1; + if test_depth.is_none() { + out.push((first, text)); + } + } else if c == '\'' { + // a char literal ('"', '\'', '{') or a lifetime ('a) + i += if at(i + 1) == '\\' { + chars[i + 3..].iter().position(|&q| q == '\'').map_or(1, |end| end + 4) + } else if at(i + 2) == '\'' { + 3 + } else { + 1 + }; + } else { + match c { + '{' => { + depth += 1; + if pending_test && test_depth.is_none() { + test_depth = Some(depth); + } + pending_test = false; + } + '}' => { + if test_depth == Some(depth) { + test_depth = None; + } + depth = depth.saturating_sub(1); + } + ';' => pending_test = false, + _ => {} + } + i += 1; + } + } + out + } + + #[test] + fn string_literals_skip_comments_tests_and_char_literals() { + let src = r##"// "a" +fn f() { let q = '"'; let e = '\''; let s = "one ▸ \"two\""; } +/* "b" */ const R: &str = r#"raw "x""#; +fn g<'a>(x: &'a str) -> &'a str { "long \ + line \u{2192}" } +#[cfg(test)] +mod tests { fn t() { "test"; } } +const Z: &str = "after";"##; + let found = string_literals(src); + let found: Vec<(usize, &str)> = found.iter().map(|(line, text)| (*line, text.as_str())).collect(); + assert_eq!(found, [(2, "one ▸ \"two\""), (3, "raw \"x\""), (4, "long line →"), (8, "after")]); + } + + /// Every symbol in the interface's own text has a glyph (issue #1950: ▸ showed as a box in the + /// English strings, which untranslated messages fall back to). Checked on the string literals of + /// the code, not just the catalogs, with the fonts the build installs: a build without craft-fonts + /// checks Inter and egui's own fonts alone, so a symbol can't lean on a CJK face. Letters and the + /// full-width forms only CJK text uses are `catalog_characters_are_paintable`'s business. + #[test] + fn source_strings_use_paintable_symbols() { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::font_definitions(lightcraft_engine::CRAFT_FONTS)); + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + let cjk_only = |ch: char| matches!(ch, '\u{3000}'..='\u{303f}' | '\u{ff00}'..='\u{ffef}'); + // noncharacters are sentinels (an IndexedDB key range's end), never shown + let text = |ch: char| u32::from(ch) & 0xfffe != 0xfffe && !matches!(ch, '\u{fdd0}'..='\u{fdef}') && !ch.is_control(); + let checked = |ch: &char| !ch.is_ascii() && !ch.is_whitespace() && !ch.is_alphanumeric() && !cjk_only(*ch) && text(*ch); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + for group in ["crates", "apps"] { + for krate in std::fs::read_dir(root.join(group)).unwrap() { + let mut dirs = vec![krate.unwrap().path().join("src")]; + while let Some(dir) = dirs.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries { + let path = entry.unwrap().path(); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("").to_string(); + if path.is_dir() { + if name != "tests" { + dirs.push(path); + } + } else if name.ends_with(".rs") && !name.starts_with("tests_") && !name.ends_with("_tests.rs") && name != "tests.rs" { + files.push(path); + } + } + } + } + } + assert!(files.len() > 100, "found the workspace's sources ({} files)", files.len()); + let mut texts: Vec<(String, String)> = Vec::new(); + for path in &files { + let src = std::fs::read_to_string(path).unwrap(); + let shown = path.strip_prefix(&root).unwrap_or(path).display().to_string(); + texts.extend(string_literals(&src).into_iter().map(|(line, text)| (format!("{shown}:{line}"), text))); + } + // What's New as the dialog shows it + for line in crate::panels::dialogs::WHATS_NEW.lines().map(str::trim) { + let line = line.strip_prefix("### ").or_else(|| line.strip_prefix("## ")).or_else(|| line.strip_prefix("- ")).unwrap_or(line); + texts.push(("docs/whats-new.md".into(), crate::panels::dialogs::whats_new_line(line))); + } + let font = egui::FontId::new(13.0, egui::FontFamily::Proportional); + let mut missing: Vec = Vec::new(); + ctx.fonts_mut(|fonts| { + for (place, text) in &texts { + for ch in text.chars().filter(checked) { + if !fonts.has_glyph(&font, ch) { + missing.push(format!("{place}: {ch:?} (U+{:04X})", u32::from(ch))); + } + } + } + }); + missing.dedup(); + assert!(missing.is_empty(), "symbols no UI font has (they paint as boxes):\n{}", missing.join("\n")); + } + /// The language menu covers every language, and a language's own command selects it. #[test] fn language_commands_cover_every_language() { diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index d62311c56c..969525a51b 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -1035,7 +1035,7 @@ fn show_existing(app: &mut LightcraftApp, ctx: &egui::Context, existing: &[u64]) crate::i18n::tr_format!("Already in the library: {} photo{} selected in All Photos", n, plural) } else { crate::i18n::tr_format!( - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh", n, plural ) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a162e6ca66..7572a3e2a2 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1916,7 +1916,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option 0 { parts.push(crate::i18n::tr_format!( - "Imported {profiles} profile{} (Profile browser ▸ their groups)", + "Imported {profiles} profile{} (Profile browser → their groups)", if profiles == 1 { "" } else { "s" }, profiles = profiles )); @@ -2335,7 +2335,7 @@ pub fn delete_in_album(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { let lightcraft_engine::LibrarySource::Album(aid) = app.session.source else { return false }; let Some(album) = app.session.catalog.album(aid) else { return false }; if album.is_smart() { - app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo")); + app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo → Delete Photo")); return true; } if app.session.selected().is_empty() { diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index e6945db013..3537cdb7ba 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -136,7 +136,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { egui::Popup::menu(&more).show(|ui| { for c in hidden { if ui - .button(format!("{} ✕", display_label(c, &app.session.filter, &app.session.catalog))) + .button(format!("{} ×", display_label(c, &app.session.filter, &app.session.catalog))) .on_hover_text(crate::i18n::tr("Remove this filter")) .clicked() { diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 70037a51a4..98d57cf182 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -601,7 +601,7 @@ pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) { let canvas = area_and_filmstrip(app, ui); let reference = app.ui.reference.map(PhotoId).filter(|r| live(app, *r)); let (Some(r), Some(active)) = (reference, app.session.active()) else { - super::empty_message(ui, canvas, "No reference photo", "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)"); + super::empty_message(ui, canvas, "No reference photo", "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)"); return; }; let area = canvas.shrink(18.0); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 444ef7e731..20ec69f184 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -1225,7 +1225,7 @@ fn region_overlay( let cross = Stroke::new(1.4, if resp.hovered() { Color32::WHITE } else { Color32::from_gray(210) }); p.line_segment([c - vec2(m, m), c + vec2(m, m)], cross); p.line_segment([c - vec2(m, -m), c + vec2(m, -m)], cross); - if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit ▸ Undo)")).clicked() { + if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit → Undo)")).clicked() { edit = Some(RegionEdit::Remove(index)); } } diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index f14d7338b8..66ce41cebf 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -178,6 +178,14 @@ pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", " /// Help ▸ What's New (docs/whats-new.md). pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md"); +/// A line of What's New as the dialog shows it, in the UI language. The notes are written like the +/// docs, with symbols Inter lacks (issue #1950): ▸ between menu items shows as → (as in the +/// translations), the activity stack's ✕ as ×, and the sidebar's full-width +, which only the CJK +/// faces have, as +. +pub(crate) fn whats_new_line(source: &str) -> String { + crate::i18n::tr(source).replace('`', "").replace('▸', "→").replace('✕', "×").replace('+', "+") +} + /// The import review and Settings keep window ids of their own, so the size each is given /// doesn't carry over to the other dialogs. fn window_id(dialog: &Dialog) -> egui::Id { @@ -391,15 +399,15 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let l = line.trim_end(); if let Some(h) = l.strip_prefix("### ") { ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(whats_new_line(h)).font(t.semibold(12.5)).color(t.text)); } else if let Some(h) = l.strip_prefix("## ") { ui.add_space(8.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); + ui.label(egui::RichText::new(whats_new_line(h)).font(t.semibold(14.0)).color(t.text)); } else if l.starts_with("# ") || l.is_empty() { } else if let Some(b) = l.strip_prefix("- ") { - ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label)); + ui.label(egui::RichText::new(format!("• {}", whats_new_line(b))).color(t.text_label)); } else { - ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label)); + ui.label(egui::RichText::new(whats_new_line(l.trim())).color(t.text_label)); } } }); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 883f47f8bc..e9457d4ba6 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1239,7 +1239,7 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { app.ui.view = crate::state::ViewMode::PhotoGrid; app.toast( ui.ctx(), - crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), + crate::i18n::tr_format!("{n} similar photo{} · View → Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n), ); } Err(e) => app.toast(ui.ctx(), e), diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index a6f53562da..f15dcc389a 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -134,7 +134,7 @@ fn remove(app: &mut LightcraftApp, ctx: &egui::Context, chip: &Chip) { let name = chip.path.replace('|', " › "); app.toast_for( ctx, - crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.", name = name, n = chip.have), + crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit → Undo puts it back.", name = name, n = chip.have), 6.0, ); } diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index ef17bfba07..64044c7a48 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -688,7 +688,7 @@ pub fn manage_body( pub fn import_toast(v: &Value) -> String { let rows: Vec<&Value> = v["effects"].as_array().or_else(|| v["imported"].as_array()).into_iter().flatten().collect(); let n = rows.len(); - let mut msg = crate::i18n::tr_format!("Imported {e} mask effect{} (Masking ▸ Effect)", if n == 1 { "" } else { "s" }, e = n); + let mut msg = crate::i18n::tr_format!("Imported {e} mask effect{} (Masking → Effect)", if n == 1 { "" } else { "s" }, e = n); let mut groups: Vec<&str> = rows.iter().filter_map(|r| r["group"].as_str()).filter(|g| !g.is_empty()).collect(); groups.sort_unstable(); groups.dedup(); diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 675e5da6fb..85d5acf5ec 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -318,7 +318,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let op = match c.op { lightcraft_develop::MaskOp::Add => "", lightcraft_develop::MaskOp::Subtract => "− ", - lightcraft_develop::MaskOp::Intersect => "∩ ", + lightcraft_develop::MaskOp::Intersect => { + // drawn: Inter has no ∩, only the CJK faces do (issue #1950) + let (r, _) = ui.allocate_exact_size(vec2(8.0, 16.0), Sense::hover()); + intersect_mark(ui.painter(), r, ui.visuals().text_color()); + "" + } }; if let Some((_, _, name)) = app.ui.renaming_component.as_mut().filter(|(mid, k, _)| *mid == m.id && *k == i) { // inline rename: Enter (or leaving the field) commits, Escape cancels @@ -919,6 +924,19 @@ fn brush_settings(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } +/// The ∩ in front of an intersecting mask component: two legs joined by a half circle, as tall as +/// a lowercase letter. +fn intersect_mark(painter: &egui::Painter, rect: Rect, color: egui::Color32) { + let (c, r) = (rect.center(), 3.0); + let mut points = vec![pos2(c.x - r, c.y + 4.0)]; + points.extend((0..=8).map(|i| { + let a = std::f32::consts::PI * (1.0 + i as f32 / 8.0); + pos2(c.x + r * a.cos(), c.y - 0.5 + r * a.sin()) + })); + points.push(pos2(c.x + r, c.y + 4.0)); + painter.add(egui::Shape::line(points, Stroke::new(1.2, color))); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index ef9ebf85df..7e013de7f6 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -319,7 +319,7 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ui, t, crate::i18n::tr( - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", ), ); row(ui, t, crate::i18n::tr("Other editor"), |ui| { @@ -1416,7 +1416,7 @@ pub fn new_library(app: &mut LightcraftApp, p: &Value) -> Result None => location, }; if lightcraft_engine::library::is_library(&dir) { - return Err(format!("{}: there is a library here already; open it with File ▸ Open Library…", dir.display())); + return Err(format!("{}: there is a library here already; open it with File → Open Library…", dir.display())); } if dir.is_file() { return Err(format!("{}: is a file; a library is a folder", dir.display())); diff --git a/docs/localization.md b/docs/localization.md index b878a5de28..045b5ebd38 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -50,7 +50,9 @@ are in [`localization-zh-hans.md`](localization-zh-hans.md), [`localization-zh-h Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never here; a missing face is added there, not worked around in this repository. Sentence-cased messages go through `i18n::upper_first`, which leaves Georgian lowercase (upper-casing Mkhedruli would make - Mtavruli). + Mtavruli). Menu paths in messages use → ("View → Clear Filters"), in English and in + translations: Inter has no ▸ or ▾, so those paint as boxes (issue #1950). + `source_strings_use_paintable_symbols` checks every symbol in the code's string literals. 4. Run `cargo xtask ci` (it includes `fmt`, `clippy`, the tests, `parity` and the wasm check). ## How a message is found @@ -119,4 +121,5 @@ Help ▸ What's New shows `docs/whats-new.md`, and each of its lines (a heading, bullet, without the `- ` or `### `) is looked up like any message, so a catalog can translate the notes line by line (German does). A line that is re-wrapped or edited no longer matches its translation and shows in English until the catalog is updated; the translation gaps report counts the untranslated -lines. +lines. The notes may write menu paths with ▸ like the other docs: the dialog shows it as → (and the +activity stack's ✕ as ×, the sidebar's + as +), since Inter has none of them. diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c2592003..3e779684c2 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -291,6 +291,12 @@ every photo of the view again: at about 180,000 photos a batch cost the window a tenth of a second, over and over for as long as the import ran. Changing one photo's capture time or crop is quicker too. +### Menu paths without boxes +- Messages that name a menu path, such as "View → Clear Filters to see all" or the External Editing help in + Settings, showed a box between the menu names: the interface font has no glyph for the small triangle used + there (issue #1950). They use → now, as the translations already did, and so do these notes. The remove + mark of each filter under "+N more" was a box too; it is an × now. + ## 2026-10-15 ### Photo Merge takes each photo once From 327b6904549317e435104567b85ba682a8229888 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:56:18 +0200 Subject: [PATCH 024/247] LR-BEHAV-LOCALIZE: drop a stale catalog key, wider cfg(test) handling in the symbol scan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The catalogs still carried "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy…", whose source string Edit in PhotoCraft replaced; it is removed from all 13 catalogs. The source scan's lexer now reads `#[cfg(test)]` with spaces and `#[cfg(all(test, …))]` as test code, and `#![cfg(test)]` as the rest of the file. `cfg(any(test, …))` code can ship, so it stays checked, as do strings in other attributes (`#[error("…")]`). The test comment says which files and items count as test code. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs.json | 1 - crates/ui-egui/locales/de.json | 1 - crates/ui-egui/locales/es.json | 1 - crates/ui-egui/locales/fr.json | 1 - crates/ui-egui/locales/it.json | 1 - crates/ui-egui/locales/ja.json | 1 - crates/ui-egui/locales/ka.json | 1 - crates/ui-egui/locales/pl.json | 1 - crates/ui-egui/locales/pt-br.json | 1 - crates/ui-egui/locales/ru.json | 1 - crates/ui-egui/locales/uk.json | 1 - crates/ui-egui/locales/zh-hans.json | 1 - crates/ui-egui/locales/zh-hant.json | 1 - crates/ui-egui/src/i18n.rs | 52 ++++++++++++++++++++++++++--- 14 files changed, 47 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 71ea24f13b..7c0bb66b81 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1357,7 +1357,6 @@ "Photo Grid (G)": "Mřížka fotografií (G)", "Photo Merge": "Sloučení fotografií", "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Fotografie → Upravit v externím editoru (⇧⌘E) vykreslí 16bitovou kopii TIFF, přidá ji do sady s originálem a otevře v této aplikaci (název aplikace v macOS, jinde cesta k programu).", "PhotoCraft": "PhotoCraft", "Photos": "Fotografie", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Fotografie upravené v HDR: JPEG s mapou zisku HDR (správné zobrazení všude, jasnější světla na displejích HDR), AVIF jako 10bitový, PNG a JPEG XL jako 16bitové Rec. 2020 PQ; TIFF vyžaduje 32bitová čísla s plovoucí řádovou čárkou", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 83bedcb748..5e9f898aa6 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1073,7 +1073,6 @@ "Photo Grid (G)": "Fotoraster (G)", "Photo Merge": "Fotos zusammenfügen", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "Fotomenü. Auch der Filmstreifen besitzt das Fotokontextmenü. Wird eine Datei erneut hinzugefügt, die unter „Zuletzt gelöscht“ liegt,", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → In externem Editor bearbeiten (⇧⌘E) rendert eine 16-Bit-TIFF-Kopie, stapelt sie mit dem Original und öffnet sie hier (App-Name unter macOS, sonst Programmpfad).", "Photos": "Fotos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "In HDR bearbeitete Fotos: JPEG mit HDR-Gain-Map (sieht überall richtig aus, hellere Lichter auf HDR-Bildschirmen), AVIF mit 10 Bit, PNG und JPEG XL mit 16 Bit Rec. 2020 PQ; TIFF braucht 32-Bit-Gleitkomma", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "Fotos unter „Zuletzt gelöscht“ können in der App wiederhergestellt werden: Rechtsklick → Wiederherstellen oder Endgültig löschen, auch im", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 36f3d686bd..7a35ff987a 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1080,7 +1080,6 @@ "Photo Grid": "Cuadrícula de fotos", "Photo Grid (G)": "Cuadrícula de fotos (G)", "Photo Merge": "Combinación de fotos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Editar en el editor externo (⇧⌘E) renderiza una copia TIFF de 16 bits, la apila con el original y la abre aquí (un nombre de aplicación en macOS, una ruta de programa en otros sistemas).", "Photos": "Fotos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Fotos editadas en HDR: JPEG con mapa de ganancia HDR (se ve bien en todas partes, con luces más brillantes en pantallas HDR), AVIF a 10 bits, PNG y JPEG XL a 16 bits Rec. 2020 PQ; TIFF necesita coma flotante de 32 bits", "Photos per bracket (0 = auto)": "Fotos por horquillado (0 = automático)", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 0cd4b699c5..9846596073 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1022,7 +1022,6 @@ "Photo Grid": "Grille de photos", "Photo Grid (G)": "Grille de photos (G)", "Photo Merge": "Fusion de photos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Photo → Modifier dans l'éditeur externe (⇧⌘E) génère une copie TIFF 16 bits, l'empile avec l'original et l'ouvre ici (un nom d'application sur macOS, un chemin de programme ailleurs).", "Photos": "Photos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Photos retouchées en HDR : JPEG avec carte de gain HDR (correct partout, hautes lumières plus vives sur les écrans HDR), AVIF en 10 bits, PNG et JPEG XL en 16 bits Rec. 2020 PQ ; le TIFF exige du 32 bits flottant", "Photos per bracket (0 = auto)": "Photos par bracketing (0 = auto)", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 7ce5af6e9d..47ff98d158 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1031,7 +1031,6 @@ "Photo Grid": "Griglia foto", "Photo Grid (G)": "Griglia foto (G)", "Photo Merge": "Unione di foto", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Modifica nell'editor esterno (⇧⌘E) genera una copia TIFF a 16 bit, la mette in pila con l'originale e la apre qui (il nome di un'app su macOS, il percorso di un programma altrove).", "Photos": "Foto", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Foto modificate in HDR: JPEG con gain map HDR (si vede bene ovunque, luci più brillanti sugli schermi HDR), AVIF a 10 bit, PNG e JPEG XL a 16 bit Rec. 2020 PQ; il TIFF richiede virgola mobile a 32 bit", "Photos per bracket (0 = auto)": "Foto per bracketing (0 = automatico)", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 3f5529988f..76ad97f612 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1046,7 +1046,6 @@ "Photo Grid": "写真グリッド", "Photo Grid (G)": "写真グリッド(G)", "Photo Merge": "写真を合成", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "「写真 → 外部エディターで編集」(⇧⌘E)で16ビットTIFFコピーを作成し、元画像とスタックにまとめて開きます。Macではアプリ名を指定してください", "Photos": "写真", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "ローカルで参照しただけの写真は、この期間フォルダを開いていなければカタログから外します。ファイルはディスクに残り、再びフォルダを開くと表示されます", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "このフォルダに転送された写真は、転送が完了すると自動で追加されます", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 26322e5a27..166728dba8 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1483,7 +1483,6 @@ "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Canon CR2-ის (და სხვა RAW ფაილების, რომელთა ფერსაც LightCraft კამერის საკუთარი JPEG-იდან არგებს, როგორიცაა NEF და", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "„ფოტო“ მენიუში. კადრების ზოლსაც აქვს ფოტოს კონტექსტური მენიუ. ახლახან წაშლილში მყოფი ფაილის ხელახლა დამატება აღარ", "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "ფოტო → რედაქტირება გარე რედაქტორში (⇧⌘E) ქმნის 16-ბიტიან TIFF ასლს, ორიგინალთან ერთად დასტაში აერთიანებს და აქ ხსნის (macOS-ზე აპის სახელი, სხვაგან — პროგრამის მისამართი).", "Photos": "ფოტოები", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "ფოტოები თქვენი მონიტორის ICC პროფილით ნაჩვენებია, ამიტომ ფერები სწორია ფართო ფერთა გამისა და დაკალიბრებულ ეკრანებზე, ხოლო დეტალური ხედი ეკრანის მთელ ფერთა გამას იყენებს. ჰისტოგრამაზე, წინასწარი ხედების ქეშებსა და ექსპორტზე ეს გავლენას არ ახდენს.", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "ახლახან წაშლილში მყოფი ფოტოების აღდგენა შეიძლება აპიდან: მარჯვენა დაწკაპუნება → აღდგენა (ან სამუდამოდ წაშლა), აგრეთვე", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index e243fd482f..3b5ea71d4e 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1922,7 +1922,6 @@ "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "Maski Obiekt i Opis korzystają z modelu segmentacji SAM 3 firmy Meta. Nie jest on częścią LightCraft; wszystkie pozostałe funkcje działają bez niego.", "Panasonic and Leica raws (RW2, RWL and the older RAW files, DMC-LX1 to DC-S1R II) develop from the raw data in": "Pliki RAW Panasonic i Leica (RW2, RWL i starsze RAW, od DMC-LX1 do DC-S1R II) są wywoływane z danych RAW w", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "menu Zdjęcie. Pasek zdjęć ma także menu kontekstowe. Ponowne dodanie pliku znajdującego się w Ostatnio usuniętych nie", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Zdjęcie → Edytuj w edytorze zewnętrznym (⇧⌘E) tworzy 16-bitową kopię TIFF, grupuje ją z oryginałem i otwiera w wybranym programie (nazwa aplikacji w macOS, ścieżka programu w pozostałych systemach).", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "Zdjęcia w Ostatnio usuniętych można przywrócić w aplikacji: kliknij prawym przyciskiem → Przywróć (lub Usuń trwale), również w", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Zdjęcia widoczne w widoku Lokalnie, lecz nigdy niedodane ani niezmienione, są usuwane z katalogu, jeśli ich folder nie był przeglądany przez określony czas (sprawdzane przy otwieraniu biblioteki). Pliki pozostają na dysku; ponowne przejrzenie folderu znów je pokazuje.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Zdjęcia pojawiające się w tym folderze (z aparatu podłączonego do komputera, skanera lub aplikacji synchronizującej) są dodawane od razu po ukończeniu zapisu.", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 665a6a0479..bdaa11261c 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1040,7 +1040,6 @@ "Photo Grid": "Grade de fotos", "Photo Grid (G)": "Grade de fotos (G)", "Photo Merge": "Mesclagem de fotos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Editar no editor externo (⇧⌘E) renderiza uma cópia TIFF de 16 bits, empilha-a com o original e a abre aqui (um nome de aplicativo no macOS, um caminho de programa em outros sistemas).", "Photos": "Fotos", "Photos per bracket (0 = auto)": "Fotos por bracketing (0 = automático)", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Fotos vistas em Local mas nunca adicionadas nem alteradas saem do catálogo quando sua pasta não é navegada por esse período (verificado ao abrir a biblioteca). Os arquivos permanecem no disco; navegar pela pasta as mostra novamente.", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index ec36bf878f..7a4ca80d08 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -866,7 +866,6 @@ "Photo Grid": "Сетка фото", "Photo Grid (G)": "Сетка фото (G)", "Photo Merge": "Слияние фото", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Фото → Править во внешнем редакторе (⇧⌘E) создаёт 16-битную TIFF-копию, помещает её в стопку с оригиналом и открывает здесь (имя приложения в macOS, путь к программе в других системах).", "Photos": "Фото", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Фото, которые видели в «Локальном», но ни разу не добавляли и не меняли, исключаются из каталога, если папку не открывали так долго (проверяется при открытии библиотеки). Файлы остаются на диске; при просмотре папки они появятся снова.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Фото, поступающие в эту папку (тетеринг, сканер, приложение синхронизации), добавляются, как только будут готовы.", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 8f54687b1a..20acb281b9 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1169,7 +1169,6 @@ "Photo Grid": "Сітка фото", "Photo Grid (G)": "Сітка фото (G)", "Photo Merge": "Об’єднання фото", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Фото → Редагувати в зовнішньому редакторі (⇧⌘E) створює 16-бітну копію TIFF, додає її до стосу з оригіналом і відкриває тут (назва застосунку в macOS, шлях до програми в інших системах).", "Photos": "Фото", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Фото, переглянуті в локальних, але ніколи не додані й не змінені, вилучаються з каталогу, якщо їхню теку не оглядали протягом цього часу (перевіряється під час відкриття бібліотеки). Файли залишаються на диску; огляд теки знову їх показує.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Фото, що надходять до цієї теки (камерне підключення, сканер, застосунок синхронізації), додаються одразу після завершення запису.", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index df1560ac7b..03d1d0face 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1080,7 +1080,6 @@ "Photo Grid": "照片网格", "Photo Grid (G)": "照片网格(G)", "Photo Merge": "照片合并", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "“照片 » 在外部编辑器中编辑”(⇧⌘E)会渲染一份 16 位 TIFF 副本,与原图堆叠并在此打开(macOS 上填应用名称,其他平台填程序路径)。", "Photos": "照片", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "仅在“本地”中查看过、从未添加或更改的照片,若其文件夹在此时长内未被浏览,将移出目录(打开图库时检查)。文件保留在磁盘上;浏览该文件夹即可再次显示。", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "进入此文件夹的照片(联机拍摄、扫描仪、同步应用)在传输完成后即被添加。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 5838de95ce..91984e7e2f 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1081,7 +1081,6 @@ "Photo Grid": "照片格狀檢視", "Photo Grid (G)": "照片格狀檢視(G)", "Photo Merge": "照片合併", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "「照片 → 在外部編輯器中編輯」(⇧⌘E)會算繪 16 位元 TIFF 副本,與原始照片堆疊後在此開啟(macOS 填應用程式名稱,其他平台填程式路徑)。", "Photos": "照片", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "曾在本機瀏覽、但未加入或變更的照片,在其資料夾超過此期間未瀏覽時會移出目錄(開啟照片庫時檢驗)。檔案仍保留在磁碟上,再次瀏覽資料夾即可重新顯示。", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "此資料夾中新出現的照片(連線拍攝、掃描器或同步程式)會在檔案完整後立即加入。", diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2f7f32993b..c4742da8c6 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -914,6 +914,19 @@ mod tests { let chars: Vec = src.chars().collect(); let at = |i: usize| chars.get(i).copied().unwrap_or('\0'); let ident = |c: char| c.is_alphanumeric() || c == '_'; + // where the inside of a `#[cfg…]` or `#![cfg…]` attribute starts; other attributes are read as + // code, so the strings in `#[error("…")]` are checked + let cfg_start = |i: usize| { + let open = if at(i) == '#' && at(i + 1) == '[' { + i + 2 + } else if at(i) == '#' && at(i + 1) == '!' && at(i + 2) == '[' { + i + 3 + } else { + return None; + }; + let name = (open..chars.len()).find(|&j| !chars[j].is_whitespace())?; + chars[name..].starts_with(&['c', 'f', 'g']).then_some(open) + }; let (mut out, mut i, mut line) = (Vec::new(), 0, 1); let (mut depth, mut test_depth, mut pending_test) = (0usize, None, false); while i < chars.len() { @@ -953,9 +966,29 @@ mod tests { i += 1; } } - } else if chars[i..].starts_with(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { - pending_test = true; - i += 12; + } else if let Some(start) = cfg_start(i) { + // `#[cfg(test)]` (spaces allowed) and `#[cfg(all(test, …))]` mark the next item as test + // code, `#![cfg(test)]` the rest of the file; `cfg(any(test, …))` code can ship, so it stays + let mut end = start; + let mut nested = 1; + while end < chars.len() && nested > 0 { + nested = match chars[end] { + '[' => nested + 1, + ']' => nested - 1, + _ => nested, + }; + line += usize::from(chars[end] == '\n'); + end += 1; + } + let attr: String = chars[start..end.saturating_sub(1)].iter().filter(|ch| !ch.is_whitespace()).collect(); + let all_test = attr.starts_with("cfg(all(") && !attr.contains("not(") && attr.split([',', '(', ')']).any(|t| t == "test"); + if attr == "cfg(test)" || all_test { + if c == '#' && at(i + 1) == '!' { + break; + } + pending_test = true; + } + i = end; } else if let Some((start, hashes)) = raw_hashes { let (first, mut text) = (line, String::new()); i = start + hashes + 1; @@ -1044,10 +1077,16 @@ fn g<'a>(x: &'a str) -> &'a str { "long \ line \u{2192}" } #[cfg(test)] mod tests { fn t() { "test"; } } -const Z: &str = "after";"##; +const Z: &str = "after"; +#[ cfg( test ) ] fn spaced() { "test"; } +#[cfg(all(unix, test))] fn both() { "test"; } +#[cfg(any(test, feature = "x"))] fn either() { "either"; } +#[error("shown")] struct E; +#![cfg(test)] +fn rest() { "test"; }"##; let found = string_literals(src); let found: Vec<(usize, &str)> = found.iter().map(|(line, text)| (*line, text.as_str())).collect(); - assert_eq!(found, [(2, "one ▸ \"two\""), (3, "raw \"x\""), (4, "long line →"), (8, "after")]); + assert_eq!(found, [(2, "one ▸ \"two\""), (3, "raw \"x\""), (4, "long line →"), (8, "after"), (11, "either"), (12, "shown")]); } /// Every symbol in the interface's own text has a glyph (issue #1950: ▸ showed as a box in the @@ -1055,6 +1094,9 @@ const Z: &str = "after";"##; /// the code, not just the catalogs, with the fonts the build installs: a build without craft-fonts /// checks Inter and egui's own fonts alone, so a symbol can't lean on a CJK face. Letters and the /// full-width forms only CJK text uses are `catalog_characters_are_paintable`'s business. + /// Test code is left out: `tests/` directories, files named `tests.rs`, `tests_*.rs` or + /// `*_tests.rs`, and items under `#[cfg(test)]` or `#[cfg(all(test, …))]`. A string only a test + /// uses belongs in one of those, or it is checked like interface text. #[test] fn source_strings_use_paintable_symbols() { let ctx = egui::Context::default(); From 406f5fae75f4cc02ac1f0a69eeaf853c0e17d87d Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:44:36 +0200 Subject: [PATCH 025/247] LR-BEHAV-LOCALIZE: an intersecting mask component says Intersect to screen readers Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/masking.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 85d5acf5ec..1a643cebd1 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -348,9 +348,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let room = (ui.available_width() - 30.0).max(0.0); let resp = ui.scope(|ui| { ui.set_max_width(room); - ui.add(egui::Label::new(text).truncate().sense(Sense::click())) + ui.add(egui::Label::new(text.clone()).truncate().sense(Sense::click())) }); let resp = resp.inner; + if matches!(c.op, lightcraft_develop::MaskOp::Intersect) { + // the drawn ∩ has no text: the row still names its mode to screen readers + let spoken = format!("{}: {text}", crate::i18n::tr("Intersect")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, spoken.clone())); + } register(ui.ctx(), format!("component:{i}"), resp.rect); if resp.double_clicked() { app.ui.renaming_component = Some((m.id, i, label.clone())); From 913b6ff1389b4ef9aa5fec69813a1cba450f9323 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:32:08 +0200 Subject: [PATCH 026/247] =?UTF-8?q?LR-BEHAV-LOCALIZE:=20=E2=86=92=20menu?= =?UTF-8?q?=20paths=20in=20the=20catalogs=20main=20added=20since=20(fi,=20?= =?UTF-8?q?id,=20sv,=20vi)=20and=20in=20keys=20it=20brought=20back?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Finnish, Indonesian, Swedish and Vietnamese catalogs and a few keys main re-added in cs and it still named the source strings with ▸. (it.json also had "Dimensions" twice with the same value; it is there once now.) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs.json | 2 +- crates/ui-egui/locales/fi-formats.json | 10 +++++----- crates/ui-egui/locales/fi.json | 8 ++++---- crates/ui-egui/locales/id-formats.json | 10 +++++----- crates/ui-egui/locales/id.json | 8 ++++---- crates/ui-egui/locales/it.json | 4 ++-- crates/ui-egui/locales/sv-formats.json | 10 +++++----- crates/ui-egui/locales/sv.json | 8 ++++---- crates/ui-egui/locales/vi-formats.json | 10 +++++----- crates/ui-egui/locales/vi.json | 6 +++--- 10 files changed, 38 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 7c0bb66b81..ed45cd6bb6 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1580,7 +1580,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Obnoví všechny křivky: bodové (všechny kanály) i parametrickou (dvojklik na kanál obnoví pouze tento kanál)", "Reset all edits": "Obnovit všechny úpravy", "Reset all edits (Cmd+Shift+R)": "Obnovit všechny úpravy (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", "LightCraft stopped": "LightCraft se neočekávaně ukončil", "Zoom to Focus Point": "Přiblížit na zaostřovací bod", "Focus": "Zaostření", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9..ff7a292083 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Avainsana ”{keyword}” lisätty kuviin: {n}{:.0}", "Adding photos… {} of {}": "Lisätään kuvia… {} / {}", "All {n} selected photos move by the same amount.": "Kaikkia valittuja kuvia ({n}) siirretään saman verran.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", "Already in the library: {} photo{} selected in All Photos": "Jo kirjastossa (Kaikki kuvat): valittuja kuvia {}{:.0}", "Already in “{}”": "Jo kohteessa ”{}”", "Applied {name}": "{name} käytetty", @@ -93,12 +93,12 @@ "Import cancelled · {} photo{} added": "Tuonti peruttu · lisättyjä kuvia: {}{:.0}", "Import failed: {e}": "Tuonti epäonnistui: {e}", "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", + "Imported {e} mask effect{} (Masking → Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", "Imported {n} point curve preset{}": "Tuotuja pistekäyrän esiasetuksia: {n}{:.0}", "Imported {n} preset{}": "Tuotuja esiasetuksia: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Tuotuja esiasetuksia: {n}{:.0}, ei luettavissa olevia tiedostoja: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", "Imported {} photo{}": "Tuotuja kuvia: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Jonossa tekoälykohinanpoistoon ({ahead} edellä)…", "Insert at the cursor (also written {})": "Lisää kohdistimen kohtaan (kirjoitetaan myös {})", @@ -157,7 +157,7 @@ "Remove “{}” from Favorites": "Poista ”{}” suosikeista", "Removed from {}": "Poistettu kohteesta {}", "Removed {what} from {name}": "{what} poistettu kohteesta {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", "Rename {n} Photos…": "Nimeä uudelleen {n} kuvaa…", "Rename “{name}”": "Nimeä uudelleen ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Nimeää uudelleen kasvoja koko kirjastossa: {n}{:.0}. Tiedostoja ei muuteta.", @@ -249,7 +249,7 @@ "{n} preset{}": "Esiasetuksia: {n}{:.0}", "{n} raws can now be developed from their raw data": "Raw-kuvia, jotka voidaan nyt kehittää raakadatastaan: {n}", "{n} selected photos · {pages} pages": "Valittuja kuvia: {n} · sivuja: {pages}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", + "{n} similar photo{} · View → Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", "{n} tasks are still running: {names}. Quitting stops them.": "Käynnissä olevia tehtäviä: {n}: {names}. Lopettaminen pysäyttää ne.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 6456a66241..a9dc8ab2e8 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1412,7 +1412,7 @@ "Photo Grid": "Kuvaruudukko", "Photo Grid (G)": "Kuvaruudukko (G)", "Photo Merge": "Kuvien yhdistäminen", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Kuva → Muokkaa ulkoisessa muokkausohjelmassa (⇧⌘E) renderöi 16-bittisen TIFF-kopion, pinoaa sen alkuperäisen kanssa ja avaa sen täällä (macOS:ssä sovelluksen nimi, muualla ohjelman polku).", "PhotoCraft": "PhotoCraft", "Photos": "Kuvat", @@ -1610,7 +1610,7 @@ "Remove missing photos from the library": "Poista puuttuvat kuvat kirjastosta", "Remove region": "Poista alue", "Remove shortcut": "Poista pikakuvake", - "Remove this face box (undo with Edit ▸ Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", + "Remove this face box (undo with Edit → Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", "Remove this filter": "Poista tämä suodatin", "Remove this group": "Poista tämä ryhmä", "Remove this rule": "Poista tämä sääntö", @@ -1674,7 +1674,7 @@ "Review": "Tarkistus", "Review Import": "Tarkista tuonti", "Right": "Oikea", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", "Right-click a preset to delete it": "Poista esiasetus napsauttamalla sitä hiiren kakkospainikkeella", "Rights Usage Terms": "Oikeuksien käyttöehdot", "Rotate": "Kierrä", @@ -1885,7 +1885,7 @@ "Smart Album Rule Fields": "Älyalbumin sääntökentät", "Smart Preview Status": "Älyesikatselun tila", "Smart Previews Location": "Älyesikatseluiden sijainti", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", "Smart preview available": "Älyesikatselu saatavilla", "Smart previews": "Älyesikatselut", "Smart previews folder changed": "Älyesikatseluiden kansio muuttui", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221..12d0d443e9 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -120,7 +120,7 @@ "Adding photos… {} of {}": "Menambahkan foto… {} dari {}", " ({} in Recently Deleted)": " ({} di Baru dihapus)", "Already in the library: {} photo{} selected in All Photos": "Sudah ada di pustaka: {} foto{:.0} dipilih di Semua foto", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", "Auto ({})": "Otomatis ({})", "Build 1:1 Previews ({scope})": "Buat pratinjau 1:1 ({scope})", "Build Smart Previews ({scope})": "Buat pratinjau pintar ({scope})", @@ -169,7 +169,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan terpandu yang tersimpan tidak didukung.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan yang tersimpan tidak didukung.", "XMP adjustments were not imported for {path}: {fields}.": "Penyesuaian XMP untuk {path} tidak diimpor: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", "Insert at the cursor (also written {})": "Sisipkan di posisi kursor (dapat juga ditulis {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Font: {} (OFL). Ikon: orisinal.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Menerapkan “{k}”: klik foto untuk menambahkan atau menghapusnya · Esc untuk berhenti", @@ -199,7 +199,7 @@ "{} — show their photos": "{} — tampilkan foto orang ini", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft belum dapat mendekode varian raw ini ({}). Anda sedang mengedit pratinjau JPEG bawaan kamera, yang sudah menyertakan gaya gambar kamera (mis. Monokrom) dan keseimbangan putihnya.", "Filtered: {label}": "Difilter: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", "Moved; {} photo(s) relinked": "Dipindahkan; {} foto ditautkan ulang", "{} label (click more labels to show any of them)": "Label {} (klik label lain untuk ikut menampilkan foto berlabel tersebut)", ", {} star{}": ", {} bintang{:.0}", @@ -245,7 +245,7 @@ "Create the keyword “{name}”": "Buat kata kunci “{name}”", "new, inside {parent}": "baru, di dalam {parent}", "Keywords of {n} selected photos": "Kata kunci {n} foto yang dipilih", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", "1 task is still running: {names}. Quitting stops it.": "1 tugas masih berjalan: {names}. Jika keluar sekarang, tugas ini akan dihentikan.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tugas masih berjalan: {names}. Jika keluar sekarang, semua tugas ini akan dihentikan.", "{what} merge cancelled": "Penggabungan {what} dibatalkan", @@ -265,7 +265,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Hapus {n} preset efek{:.0}? Tindakan ini tidak dapat diurungkan.", "Effect: {name}": "Efek: {name}", "Exported {} effect preset{}": "{} preset efek diekspor{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", "Update “{name}” with Current Settings": "Perbarui “{name}” dengan pengaturan saat ini", "{n} preset{}": "{n} preset{:.0}", "{name} opened in the other editor": "{name} dibuka di editor lain", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index abb6a732e4..536ae3532f 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1395,7 +1395,7 @@ "Photo Grid": "Grid foto", "Photo Grid (G)": "Grid foto (G)", "Photo Merge": "Gabung foto", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Edit di editor eksternal (⇧⌘E) membuat salinan TIFF 16-bit, menumpuknya dengan file asli, lalu membukanya dengan program yang diisi di sini (nama aplikasi di macOS, jalur program di sistem lain).", "PhotoCraft": "PhotoCraft", "Photos": "Foto", @@ -1598,7 +1598,7 @@ "Remove location info": "Hapus info lokasi", "Remove missing photos from the library": "Keluarkan foto yang hilang dari pustaka", "Remove shortcut": "Hapus pintasan", - "Remove this face box (undo with Edit ▸ Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", + "Remove this face box (undo with Edit → Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", "Remove this filter": "Hapus filter ini", "Remove this group": "Hapus grup ini", "Remove this rule": "Hapus aturan ini", @@ -1665,7 +1665,7 @@ "Review": "Tinjauan", "Review Import": "Tinjau impor", "Right": "Kanan", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", "Right-click a preset to delete it": "Klik kanan preset untuk menghapusnya", "Rights Usage Terms": "Ketentuan penggunaan", "Rotate": "Putar", @@ -1884,7 +1884,7 @@ "Smart Album Rule Fields": "Kolom aturan album pintar", "Smart Preview Status": "Status pratinjau pintar", "Smart Previews Location": "Lokasi pratinjau pintar", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", "Smart preview available": "Pratinjau pintar tersedia", "Smart previews": "Pratinjau pintar", "Smart previews folder changed": "Folder pratinjau pintar diubah", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 47ff98d158..a82a9e6721 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1224,7 +1224,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Reimposta tutte le curve: curve a punti (tutti i canali) e parametrica (doppio clic su un canale per reimpostare solo quello)", "Reset all edits": "Ripristina tutte le modifiche", "Reset all edits (Cmd+Shift+R)": "Reimposta tutte le modifiche (Cmd+Maiusc+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", "LightCraft stopped": "LightCraft si è chiuso", "Zoom to Focus Point": "Zoom sul punto di messa a fuoco", "Focus": "Messa a fuoco", @@ -1834,7 +1834,7 @@ "Monitor profile": "Profilo monitor", "None (the display is treated as sRGB)": "Nessuno (lo schermo viene trattato come sRGB)", "Other editor": "Altro editor", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", "PhotoCraft": "PhotoCraft", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Le foto vengono mostrate attraverso il profilo ICC del monitor, così i colori sono corretti su schermi calibrati e a gamut esteso, e la vista Dettaglio usa tutto il gamut dello schermo. Istogramma, cache delle anteprime ed esportazioni non cambiano.", "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Le foto restano in Tutte le foto. Eliminando una cartella si eliminano anche i suoi album. Puoi annullare l'operazione.", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c..dfc3b4779a 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Lade till ”{keyword}” på {n} foto{}", "Adding photos… {} of {}": "Lägger till foton… {} av {}", "All {n} selected photos move by the same amount.": "Alla {n} markerade foton flyttas lika mycket.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", "Already in the library: {} photo{} selected in All Photos": "Finns redan i biblioteket: {} foto{} markerade i Alla foton", "Applied {name}": "Tillämpade {name}", "Apply to “{mask}” on Selected Photos": "Använd på ”{mask}” i markerade foton", @@ -91,12 +91,12 @@ "Import cancelled · {} photo{} added": "Importen avbröts · {} foto{} tillagda", "Import failed: {e}": "Importen misslyckades: {e}", "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", "Imported {n} point curve preset{}": "Importerade {n} punktkurvförinställning{}", "Imported {n} preset{}": "Importerade {n} förinställning{}", "Imported {n} preset{}, {f} file{} not readable": "Importerade {n} förinställning{}, {f} fil{} kunde inte läsas", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", "Imported {} photo{}": "Importerade {} foto{}", "In line for AI Denoise ({ahead} ahead)…": "I kö för AI-brusreducering ({ahead} före)…", "Insert at the cursor (also written {})": "Infoga vid textmarkören (skrivs även {})", @@ -153,7 +153,7 @@ "Remove “{}” from Favorites": "Ta bort ”{}” från Favoriter", "Removed from {}": "Borttaget från {}", "Removed {what} from {name}": "Tog bort {what} från {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", "Rename {n} Photos…": "Byt namn på {n} foton…", "Rename “{name}”": "Byt namn på ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Byter namn på {n} ansikte{} i hela biblioteket. Filerna ändras inte.", @@ -241,7 +241,7 @@ "{n} photo{} now · updates automatically as photos change": "{n} foto{} just nu · uppdateras automatiskt när fotona ändras", "{n} preset{}": "{n} förinställning{}", "{n} raws can now be developed from their raw data": "{n} raw-filer kan nu framkallas från sina rådata", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", + "{n} similar photo{} · View → Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", "{n} tasks are still running: {names}. Quitting stops them.": "{n} uppgifter körs fortfarande: {names}. Om du avslutar stoppas de.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index d9af4b8e86..7b6875d97b 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1544,7 +1544,7 @@ "Photo Merge": "Fotosammanfogning", "photo waiting": "foto väntar", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Redigera i externt program (⇧⌘E) renderar en 16-bitars TIFF-kopia, staplar den med originalet och öppnar den här (ett appnamn på macOS, en programsökväg på andra system).", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", "PhotoCraft": "PhotoCraft", "Photos": "Foton", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Foton visas genom bildskärmens ICC-profil, så att färgerna blir rätt på kalibrerade skärmar och skärmar med brett färgomfång, och vyn Detalj använder skärmens hela färgomfång. Histogrammet, förhandsgranskningscacharna och exporter påverkas inte.", @@ -1754,7 +1754,7 @@ "Remove missing photos from the library": "Ta bort saknade foton från biblioteket", "Remove region": "Ta bort region", "Remove shortcut": "Ta bort kortkommando", - "Remove this face box (undo with Edit ▸ Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", + "Remove this face box (undo with Edit → Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", "Remove this filter": "Ta bort det här filtret", "Remove this group": "Ta bort den här gruppen", "Remove this rule": "Ta bort den här regeln", @@ -1823,7 +1823,7 @@ "Review": "Granskning", "Review Import": "Granska import", "Right": "Höger", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", "Right-click a preset to delete it": "Högerklicka på en förinställning för att radera den", "Rights Usage Terms": "Villkor för användningsrätt", "Rotate": "Rotera", @@ -2041,7 +2041,7 @@ "Smart Album Rule Fields": "Regelfält för smarta album", "smart album value|No": "Nej", "smart album value|Yes": "Ja", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", "Smart albums with a rule editor: match all / any / none, nested groups, 26 fields.": "Smarta album med regelredigerare: matcha alla/någon/ingen, nästlade grupper, 26 fält.", "Smart preview available": "Smart förhandsgranskning tillgänglig", "Smart Preview Status": "Status för smart förhandsgranskning", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff06..8ac30e33d7 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -39,7 +39,7 @@ "Added “{keyword}” to {n} photo{}": "Đã thêm «{keyword}» vào {n} ảnh{:.0}", "Adding photos… {} of {}": "Đang thêm ảnh… {} / {}", "All {n} selected photos move by the same amount.": "Tất cả {n} ảnh đã chọn dịch chuyển cùng một lượng.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", "Already in the library: {} photo{} selected in All Photos": "Đã có trong thư viện: đã chọn {} ảnh{:.0} trong Tất cả ảnh", "Already in “{}”": "Already in “{}”", "Applied {name}": "Applied {name}", @@ -93,12 +93,12 @@ "Import cancelled · {} photo{} added": "Đã hủy nhập · đã thêm {} ảnh{:.0}", "Import failed: {e}": "Nhập thất bại: {e}", "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", "Imported {n} point curve preset{}": "Đã nhập {n} thiết lập sẵn đường cong điểm{:.0}", "Imported {n} preset{}": "Đã nhập {n} thiết lập sẵn{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Đã nhập {n} thiết lập sẵn{:.0}, {f} tệp{:.0} không đọc được", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", "Imported {} photo{}": "Đã nhập {} ảnh{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Đang xếp hàng Khử nhiễu AI (trước bạn: {ahead})…", "Insert at the cursor (also written {})": "Chèn tại con trỏ (cũng ghi là {})", @@ -157,7 +157,7 @@ "Remove “{}” from Favorites": "Gỡ «{}» khỏi Yêu thích", "Removed from {}": "Đã gỡ khỏi {}", "Removed {what} from {name}": "Đã gỡ {what} khỏi {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Rename {n} Photos…": "Đổi tên {n} ảnh…", "Rename “{name}”": "Đổi tên «{name}»", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", @@ -249,7 +249,7 @@ "{n} preset{}": "{n} preset{}", "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", + "{n} similar photo{} · View → Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", "{n} tasks are still running: {names}. Quitting stops them.": "Còn {n} tác vụ đang chạy: {names}. Thoát sẽ dừng chúng.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 98adc91b84..9932449608 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1289,7 +1289,7 @@ "Photo Grid (G)": "Lưới ảnh (G)", "Photo Merge": "Ghép ảnh", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "Menu Ảnh. Dải phim cũng có menu ngữ cảnh ảnh. Thêm lại tệp đang ở Đã xóa gần đây không", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Ảnh → Chỉnh trong trình soạn ngoài (⇧⌘E) kết xuất bản sao TIFF 16 bit, xếp chồng với bản gốc và mở tại đây (tên app trên macOS, đường dẫn chương trình ở nơi khác).", "PhotoCraft": "PhotoCraft", "Photos": "Ảnh", @@ -1481,7 +1481,7 @@ "Remove location info": "Xóa thông tin vị trí", "Remove missing photos from the library": "Gỡ ảnh mất khỏi thư viện", "Remove shortcut": "Gỡ lối tắt", - "Remove this face box (undo with Edit ▸ Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", + "Remove this face box (undo with Edit → Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", "Remove this filter": "Gỡ bộ lọc này", "Remove this group": "Gỡ nhóm này", "Remove this rule": "Gỡ quy tắc này", @@ -1540,7 +1540,7 @@ "Revert": "Hoàn tác", "Review": "Xem lại", "Review Import": "Xem lại nhập", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", "Right-click a preset to delete it": "Nhấp phải thiết lập sẵn để xóa", "Rights Usage Terms": "Điều khoản sử dụng quyền", "Rotate": "Xoay", From 48d15847a496cdc77bd789e185fd3ac9e7d8988a Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 24 Oct 2026 04:50:32 +0200 Subject: [PATCH 027/247] LR-BEHAV-LOCALIZE: the source-string scanner reads cfg_attr, nested any(test) and body-less test items right MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cfg_start matched any attribute starting with cfg, so the strings in #[cfg_attr(…, error("…"))] were never checked; it now needs cfg(. #[cfg(all(…))] counts as test-only only when test is one of its top-level conditions, so all(unix, any(test, feature = "x")) is checked. Literals of a #[cfg(test)] item without a body, such as a const, are left out. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n.rs | 54 ++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c4742da8c6..05bb7166c2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -914,8 +914,8 @@ mod tests { let chars: Vec = src.chars().collect(); let at = |i: usize| chars.get(i).copied().unwrap_or('\0'); let ident = |c: char| c.is_alphanumeric() || c == '_'; - // where the inside of a `#[cfg…]` or `#![cfg…]` attribute starts; other attributes are read as - // code, so the strings in `#[error("…")]` are checked + // where the inside of a `#[cfg(…)]` or `#![cfg(…)]` attribute starts; other attributes are read + // as code, so the strings in `#[error("…")]` and `#[cfg_attr(…, error("…"))]` are checked let cfg_start = |i: usize| { let open = if at(i) == '#' && at(i + 1) == '[' { i + 2 @@ -925,7 +925,27 @@ mod tests { return None; }; let name = (open..chars.len()).find(|&j| !chars[j].is_whitespace())?; - chars[name..].starts_with(&['c', 'f', 'g']).then_some(open) + let paren = (name + 3..chars.len()).find(|&j| !chars[j].is_whitespace())?; + (chars[name..].starts_with(&['c', 'f', 'g']) && chars[paren] == '(').then_some(open) + }; + // whether `test` is one of the top-level conditions of an `all(…)`: `all(unix, any(test, …))` + // can ship without it + let all_has_test = |args: &str| { + let (mut level, mut from) = (0, 0); + for (k, ch) in args.char_indices().chain([(args.len(), ',')]) { + match ch { + '(' => level += 1, + ')' => level -= 1, + ',' if level == 0 => { + if &args[from..k] == "test" { + return true; + } + from = k + 1; + } + _ => {} + } + } + false }; let (mut out, mut i, mut line) = (Vec::new(), 0, 1); let (mut depth, mut test_depth, mut pending_test) = (0usize, None, false); @@ -968,7 +988,8 @@ mod tests { } } else if let Some(start) = cfg_start(i) { // `#[cfg(test)]` (spaces allowed) and `#[cfg(all(test, …))]` mark the next item as test - // code, `#![cfg(test)]` the rest of the file; `cfg(any(test, …))` code can ship, so it stays + // code up to its `;` or through its body, `#![cfg(test)]` the rest of the file; + // `cfg(any(test, …))` code can ship, so it stays let mut end = start; let mut nested = 1; while end < chars.len() && nested > 0 { @@ -981,7 +1002,7 @@ mod tests { end += 1; } let attr: String = chars[start..end.saturating_sub(1)].iter().filter(|ch| !ch.is_whitespace()).collect(); - let all_test = attr.starts_with("cfg(all(") && !attr.contains("not(") && attr.split([',', '(', ')']).any(|t| t == "test"); + let all_test = attr.strip_prefix("cfg(all(").and_then(|rest| rest.strip_suffix("))")).is_some_and(all_has_test); if attr == "cfg(test)" || all_test { if c == '#' && at(i + 1) == '!' { break; @@ -998,7 +1019,7 @@ mod tests { i += 1; } i += 1 + hashes; - if test_depth.is_none() { + if test_depth.is_none() && !pending_test { out.push((first, text)); } } else if c == '"' { @@ -1032,7 +1053,7 @@ mod tests { } } i += 1; - if test_depth.is_none() { + if test_depth.is_none() && !pending_test { out.push((first, text)); } } else if c == '\'' { @@ -1082,11 +1103,28 @@ const Z: &str = "after"; #[cfg(all(unix, test))] fn both() { "test"; } #[cfg(any(test, feature = "x"))] fn either() { "either"; } #[error("shown")] struct E; +#[cfg(all(unix, any(test, feature = "y")))] fn nested() { "nested"; } +#[cfg(all(test, not(feature = "y")))] fn negated() { "test"; } +#[cfg(test)] const SYMBOL: &str = "test"; +const KEPT: &str = "kept"; +#[cfg_attr(feature = "y", error("conditional"))] struct C; #![cfg(test)] fn rest() { "test"; }"##; let found = string_literals(src); let found: Vec<(usize, &str)> = found.iter().map(|(line, text)| (*line, text.as_str())).collect(); - assert_eq!(found, [(2, "one ▸ \"two\""), (3, "raw \"x\""), (4, "long line →"), (8, "after"), (11, "either"), (12, "shown")]); + let expected = [ + (2, "one ▸ \"two\""), + (3, "raw \"x\""), + (4, "long line →"), + (8, "after"), + (11, "either"), + (12, "shown"), + (13, "nested"), + (16, "kept"), + (17, "y"), + (17, "conditional"), + ]; + assert_eq!(found, expected); } /// Every symbol in the interface's own text has a glyph (issue #1950: ▸ showed as a box in the From 9c79f8b9a12e262cdea0fe1e74547e2ee0bdabb8 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:48:11 +0100 Subject: [PATCH 028/247] =?UTF-8?q?LR-BEHAV-LOCALIZE:=20the=20missing-file?= =?UTF-8?q?=20AI-mask=20message=20points=20to=20File=20=E2=86=92=20Find=20?= =?UTF-8?q?Missing=20Photos=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Find Missing Photos lives in the File menu, not Library. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/segment/worker.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index 11914039e3..4a4a8d3672 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -379,7 +379,7 @@ fn render(job: &mut Job) -> Result { Err(e) => { return Err(match &job.missing { Some(path) => format!( - "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library → Find Missing Photos can relink it." + "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. File → Find Missing Photos… can relink it." ), None => format!("couldn't render the photo for AI masks: {e}"), }); From 7a43d5c16f6c398074ee62b7a4422039f2926e20 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:41:37 +0200 Subject: [PATCH 029/247] #2359: Remove tool: one outline per brushed spot, strokes recorded at a spacing A brushed Remove / Heal / Clone spot stored a point on every frame the pointer was down and drew one ring per point (plus one more per point for the source), so a short stroke showed dozens of stacked rings and the paint preview a solid blob that hid the result. - Capture: a point is added only when the pointer is at least max(r/4, 2 px) from the last stored one, a held pointer adds nothing, and the release adds where the stroke ended if that is r/8 further on. A click is still one point. - `spot.add` drops points closer than size/4 (long-edge units, so the aspect ratio counts) and keeps the first and last, so API / MCP callers get the same. Saved spots are not rewritten. - The overlay draws a spot as the boundary of the union of its discs, over a dark under-stroke; the source the same way, dashed. The paint preview is the same outline, with no fills. `panels/spot_outline.rs` holds the geometry (the uncovered arcs of each circle, crossing to crossing, chained). - A spot can be grabbed by its pin and anywhere within r of its stroke (the selected spot's source likewise); the selected spot still wins, then the nearest. Tool Overlay modes and the keyboard handles are unchanged. Co-Authored-By: Claude Opus 5.5 # Conflicts: # crates/engine/src/tests_spots.rs # docs/parity-checklist.md # Conflicts: # docs/parity-checklist.md # Conflicts: # crates/ui-egui/src/panels/detail.rs --- crates/engine/src/cmd/develop.rs | 2 +- crates/engine/src/cmd/masks.rs | 69 ++++- crates/engine/src/tests_spots.rs | 36 +++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/detail.rs | 75 ++++-- crates/ui-egui/src/panels/mod.rs | 1 + crates/ui-egui/src/panels/spot_outline.rs | 297 ++++++++++++++++++++++ crates/ui-egui/src/tests_spot_stroke.rs | 89 +++++++ docs/parity-checklist.md | 3 +- 9 files changed, 547 insertions(+), 27 deletions(-) create mode 100644 crates/ui-egui/src/panels/spot_outline.rs create mode 100644 crates/ui-egui/src/tests_spot_stroke.rs diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index fbc3d4041a..6d89c51dbc 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -33,7 +33,7 @@ fn groups_param(p: &Value, c: &str) -> Result>> { } } -fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { +pub(super) fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { let p = s.catalog.photo(id); let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0)); let o = p.map(|p| p.develop.orientation).unwrap_or_default(); diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 2fd44d5665..b09d3a1d23 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -894,15 +894,16 @@ pub fn specs() -> Vec { return Err(bad("spot.add", "missing points")); } let d = Spot::default(); + let size = f64_or(p, "size", d.size).clamp(SPOT_SIZE.0, SPOT_SIZE.1); + let id = s.active().ok_or_else(|| bad("spot.add", "no active photo"))?; let mut spot = Spot { mode, - points: pts, - size: f64_or(p, "size", d.size).clamp(SPOT_SIZE.0, SPOT_SIZE.1), + points: thin_spot_points(&pts, size, super::develop::crop_dims(s, id)), + size, feather: f64_or(p, "feather", d.feather).clamp(0.0, 100.0), opacity: f64_or(p, "opacity", d.opacity).clamp(0.0, 100.0), source_offset: point(p, "source"), }; - let id = s.active().ok_or_else(|| bad("spot.add", "no active photo"))?; let mut dd = (*s.develop_of(id).unwrap_or_default()).clone(); if spot.source_offset.is_none() && spot.mode != SpotMode::Fill { // resolve the automatic source now: it gets a pin and stays put at every size @@ -1092,6 +1093,37 @@ fn spots_edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut Vec Vec { + let long = w.max(h).max(1e-9); + let (kx, ky) = (w / long, h / long); + let dist = |a: Point, b: Point| ((b.x - a.x) * kx).hypot((b.y - a.y) * ky); + let spacing = size / 4.0; + let mut out: Vec = Vec::with_capacity(pts.len().min(64)); + for &q in pts { + if out.last().is_none_or(|&last| dist(last, q) >= spacing) { + out.push(q); + } + } + // the stroke reaches where it ended: a last point closer than the spacing takes the place of the one + // before it (so a hold at the end doesn't leave a bump), unless it is at that one already + if let Some(&end) = pts.last() + && let Some(&last) = out.last() + && dist(last, end) > 0.0 + { + match out.len() { + 1 if dist(last, end) < spacing / 2.0 => {} + 1 => out.push(end), + n => out[n - 1] = end, + } + } + out +} + /// An automatic source for `spot` on photo `id` (a small proxy of the photo, framed by `d`). fn pick_source(s: &mut Session, id: crate::PhotoId, d: &lightcraft_develop::DevelopSettings, spot: &Spot, avoid: Option) -> Option { let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?; @@ -1168,3 +1200,34 @@ mod tests_color_range { assert_eq!(samples.len(), MAX_COLOR_RANGE_SAMPLES); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The thinning measures in long-edge units: on a portrait photo the y axis is the long one (issue #2359). + #[test] + fn spot_thinning_respects_the_aspect_ratio() { + let pts: Vec = (0..100).map(|i| Point::new(0.1, 0.1 + 0.002 * f64::from(i))).collect(); + // size 0.04: one point per 0.01 long-edge units, which is 0.01 of y on a portrait photo but 0.015 on a landscape one + let tall = thin_spot_points(&pts, 0.04, (2.0, 3.0)); + let wide = thin_spot_points(&pts, 0.04, (3.0, 2.0)); + assert!(tall.len() > wide.len(), "{} vs {}", tall.len(), wide.len()); + // 0.198 of y: 19.8 spacings of 0.01 (portrait), 13.2 of 0.015 (landscape), plus the first point + assert!((tall.len() as f64 - 21.0).abs() <= 2.0, "{}", tall.len()); + assert!((wide.len() as f64 - 14.0).abs() <= 2.0, "{}", wide.len()); + assert_eq!(tall.first(), pts.first()); + assert_eq!(tall.last(), pts.last()); + assert_eq!(wide.last(), pts.last()); + } + + #[test] + fn thinning_keeps_clicks_and_degenerate_input() { + let one = vec![Point::new(0.5, 0.5)]; + assert_eq!(thin_spot_points(&one, 0.05, (3.0, 2.0)), one); + assert_eq!(thin_spot_points(&[one[0], one[0], one[0]], 0.05, (3.0, 2.0)), one); + assert!(thin_spot_points(&[], 0.05, (3.0, 2.0)).is_empty()); + // a zero-sized photo doesn't divide by zero + assert_eq!(thin_spot_points(&[one[0], Point::new(0.6, 0.6)], 0.05, (0.0, 0.0)).len(), 1); + } +} diff --git a/crates/engine/src/tests_spots.rs b/crates/engine/src/tests_spots.rs index 28a9fca0b1..57d99a31e0 100644 --- a/crates/engine/src/tests_spots.rs +++ b/crates/engine/src/tests_spots.rs @@ -321,3 +321,39 @@ fn mask_and_spot_targets_preserve_explicit_defaults_and_selection_clearing() { s.execute("mask.brushStroke", &json!({"points": [[0.5, 0.5]]})).unwrap(); assert_eq!(s.develop_of(s.active().unwrap()).unwrap().masks.len(), 3); } + +/// A brushed stroke recorded a point per frame (issue #2359): stationary repeats and points closer than a +/// quarter of the size collapse, the ends stay, and a click is still one point. +#[test] +fn spot_add_thins_a_stroke_to_a_quarter_of_the_size() { + let mut s = Session::with_demo(); + let size = 0.04; + // 60 samples along x (a point every 0.001), with 5 stationary repeats at the start and end + let mut pts: Vec<[f64; 2]> = vec![[0.3, 0.5]; 5]; + pts.extend((0..60).map(|i| [0.3 + 0.001 * f64::from(i), 0.5])); + pts.extend(vec![[0.359, 0.5]; 5]); + s.execute("spot.add", &json!({"mode": "heal", "points": pts, "size": size, "source": [0.1, 0.0]})).unwrap(); + let p = spots(&s)[0].points.clone(); + // the demo photo's shape decides how far a quarter of the size is along x + let dims = { + let ph = s.catalog.photo(s.active().unwrap()).unwrap(); + let (w, h) = (f64::from(ph.width), f64::from(ph.height)); + if ph.develop.orientation.swaps_axes() { (h, w) } else { (w, h) } + }; + let long = dims.0.max(dims.1); + let steps = 0.059 * dims.0 / long / (size / 4.0); + assert!((p.len() as f64 - (steps + 1.0)).abs() <= 2.0, "a stroke of {steps:.1} spacings is about {} points, got {p:?}", steps + 1.0); + assert!(p.len() < 20, "60 samples and 10 repeats collapse: {}", p.len()); + assert_eq!((p[0].x, p[0].y), (0.3, 0.5), "first point kept"); + assert!((p.last().unwrap().x - 0.359).abs() < 1e-9, "last point kept: {p:?}"); + // the spacing counts in long-edge units, so no two neighbours are closer than size/4 (bar the last) + for w in p.windows(2).take(p.len().saturating_sub(2)) { + let d = ((w[1].x - w[0].x) * dims.0 / long).hypot((w[1].y - w[0].y) * dims.1 / long); + assert!(d >= size / 4.0 - 1e-12, "spacing {d} between {w:?}"); + } + // a click and a held click stay one point + s.execute("spot.add", &json!({"points": [[0.5, 0.5]], "size": size, "source": [0.1, 0.0]})).unwrap(); + assert_eq!(spots(&s)[1].points.len(), 1); + s.execute("spot.add", &json!({"points": [[0.5, 0.5], [0.5, 0.5], [0.5001, 0.5]], "size": size, "source": [0.1, 0.0]})).unwrap(); + assert_eq!(spots(&s)[2].points.len(), 1, "a jitter below the spacing is the same spot"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index be1a9e879f..b4e18a4361 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -197,6 +197,8 @@ mod tests_slideshow; #[cfg(test)] mod tests_solo_sections; #[cfg(test)] +mod tests_spot_stroke; +#[cfg(test)] mod tests_switch_library; #[cfg(test)] mod tests_sync; diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 5e610b098d..1271eef220 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -9,6 +9,7 @@ use lightcraft_pipeline::geometry::Frame; use serde_json::json; use crate::LightcraftApp; +use crate::panels::spot_outline; use crate::render::Slot; use crate::state::{BeforeAfter, RightPanel, ToolOverlay, Zoom}; use crate::theme::Tokens; @@ -2679,8 +2680,12 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo if painting { pins.set_invisible(); } - // (spot, is source, screen centre, radius) of everything that can be grabbed + // (spot, is source, screen centre, radius) of every pin: the keyboard handles let mut grips: Vec<(usize, bool, Pos2, f32)> = Vec::new(); + // (spot, is source, screen points of the stroke, radius) of everything that can be grabbed: the pin, and + // anywhere within the radius of the stroke's points (the source's, shifted by its offset, for the selected spot) + let mut bodies: Vec<(usize, bool, Vec, f32)> = Vec::new(); + let clip = p.clip_rect(); for (i, s) in d.spots.iter().enumerate() { let r = (s.size * long) as f32; let sel = Some(i) == active; @@ -2688,39 +2693,41 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo continue; } let p = &pins; - let col = Color32::from_white_alpha(if sel { 230 } else { 150 }); - for q in &s.points { - p.circle_stroke(map.screen(*q), r, Stroke::new(if sel { 1.5 } else { 1.0 }, col)); + let target: Vec = s.points.iter().map(|q| map.screen(*q)).collect(); + let light = if sel { Stroke::new(1.25, Color32::from_white_alpha(230)) } else { Stroke::new(1.0, Color32::from_white_alpha(120)) }; + if touches(&target, r, clip) { + draw_outline(p, &spot_outline::union_outline(&target, r), light, false); } - let Some(&t) = s.points.first() else { continue }; - let tq = map.screen(t); + let Some(&tq) = target.first() else { continue }; if let Some(o) = s.source_offset.filter(|_| sel) { - let sq = map.screen(Point::new(t.x + o.x, t.y + o.y)); - for q in &s.points { - p.circle_stroke(map.screen(Point::new(q.x + o.x, q.y + o.y)), r, Stroke::new(1.0, Color32::from_white_alpha(170))); + let source: Vec = s.points.iter().map(|q| map.screen(Point::new(q.x + o.x, q.y + o.y))).collect(); + if touches(&source, r, clip) { + draw_outline(p, &spot_outline::union_outline(&source, r), Stroke::new(1.0, Color32::from_white_alpha(150)), true); } + let sq = source[0]; let dir = (tq - sq).normalized(); - p.arrow(sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length()), Stroke::new(1.0, Color32::from_white_alpha(200))); + let (from, by) = (sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length())); + p.arrow(from, by, Stroke::new(2.5, Color32::from_black_alpha(110))); + p.arrow(from, by, Stroke::new(1.0, Color32::from_white_alpha(200))); register(ui, format!("spotSource:{i}"), Rect::from_center_size(sq, vec2(14.0, 14.0))); grips.push((i, true, sq, r)); + bodies.push((i, true, source, r)); } pin(p, tq, sel); register(ui, format!("spotPin:{i}"), Rect::from_center_size(tq, vec2(14.0, 14.0))); grips.push((i, false, tq, r)); + bodies.push((i, false, target, r)); } if spot_keys(app, ui, map, d, &grips) { return; } let r = (app.ui.remove_size as f64 * long) as f32; - // a target or source under `q`: the selected spot's first, then the nearest pin + // a target or source under `q` (its pin or anywhere along its stroke): the selected spot's first, then the nearest let hit = |q: Pos2| { - grips + bodies .iter() - .filter(|g| g.2.distance(q) < g.3.max(8.0)) - .min_by(|a, b| { - (Some(a.0) != active, a.2.distance(q)).partial_cmp(&(Some(b.0) != active, b.2.distance(q))).unwrap_or(std::cmp::Ordering::Equal) - }) - .copied() + .filter_map(|(spot, source, pts, r)| Some((*spot, *source, spot_outline::grab_distance(pts, q, r.max(8.0))?))) + .min_by(|a, b| (Some(a.0) != active, a.2).partial_cmp(&(Some(b.0) != active, b.2)).unwrap_or(std::cmp::Ordering::Equal)) }; let hover = resp.hover_pos().and_then(hit); if let Some(h) = resp.hover_pos() { @@ -2765,18 +2772,23 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo return; } if let Some(q) = resp.interact_pointer_pos() - && (resp.drag_started() || resp.dragged() || resp.clicked()) + && (resp.drag_started() || resp.dragged() || resp.clicked() || resp.drag_stopped()) { let n = map.norm(q); match &mut app.gesture { - Some(Gesture::Spot { points }) => points.push(n), + // a point every r/4 of movement; a held pointer stores nothing, and the release adds where it ended + Some(Gesture::Spot { points }) => { + let last = points.last().map(|l| map.screen(*l)); + if last.is_none_or(|l| spot_outline::adds_point(l, q, r, resp.drag_stopped())) { + points.push(n); + } + } _ => app.gesture = Some(Gesture::Spot { points: vec![n] }), } } if let Some(Gesture::Spot { points }) = &app.gesture { - for q in points { - p.circle_filled(map.screen(*q), r, Color32::from_white_alpha(60)); - } + let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); + draw_outline(&p, &spot_outline::union_outline(&screen, r), Stroke::new(1.25, Color32::from_white_alpha(230)), false); } if (resp.drag_stopped() || resp.clicked()) && let Some(Gesture::Spot { points }) = app.gesture.take() @@ -2795,6 +2807,25 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo } } +/// Whether the discs of radius `r` at `pts` can show in `clip`. +fn touches(pts: &[Pos2], r: f32, clip: Rect) -> bool { + pts.iter().any(|q| clip.expand(r).contains(*q)) +} + +/// A spot's outline in `light`, over a dark under-stroke so a thin line stays visible on light and dark areas alike. +fn draw_outline(p: &egui::Painter, lines: &[Vec], light: Stroke, dashed: bool) { + let dark = Stroke::new(light.width + 1.5, Color32::from_black_alpha(110)); + for stroke in [dark, light] { + for l in lines { + if dashed { + p.extend(egui::Shape::dashed_line(l, stroke, 6.0, 4.0)); + } else { + p.add(egui::Shape::line(l.clone(), stroke)); + } + } + } +} + /// Keyboard stand-ins for the Remove tool: each spot's target and source (an arrow press moves /// it a step, one undo step; Return selects the spot), and a placement point that the arrows move /// and Return turns into a new spot of the brush's size there. True when a spot was added. diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index e3300e04f1..934ef0da4c 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -37,6 +37,7 @@ pub mod slide_overlays; pub mod slide_templates; pub mod slide_titles; pub mod slideshow; +pub mod spot_outline; pub mod strip; pub mod topbar; pub mod unnamed; diff --git a/crates/ui-egui/src/panels/spot_outline.rs b/crates/ui-egui/src/panels/spot_outline.rs new file mode 100644 index 0000000000..2d3e3ac7b2 --- /dev/null +++ b/crates/ui-egui/src/panels/spot_outline.rs @@ -0,0 +1,297 @@ +//! The Remove tool's strokes on the photo (issue #2359): when a brush stroke records a point, the outline of +//! a stroke (the boundary of the union of its discs, not one ring per point) and what counts as grabbing it. +//! Pure geometry in screen points, so it is tested without a window. + +use std::collections::HashMap; +use std::f32::consts::TAU; + +use egui::Pos2; + +/// Fewest and most samples on one circle: scaled with the radius so a ring stays round at any zoom. +const SAMPLES: (f32, f32) = (24.0, 128.0); + +/// Whether a pointer at `q` adds a point to a stroke whose last stored point is `last`, in screen points, for a brush +/// of radius `r`. A point comes every `r / 4` (at least 2 points), like the mask brush's dabs, so a held or slowly +/// dragged pointer stores nothing more. On release (`end`) the stroke only has to reach `q` within `r / 8`. +pub fn adds_point(last: Pos2, q: Pos2, r: f32, end: bool) -> bool { + let d = last.distance(q); + let min = if end { r / 8.0 } else { (r / 4.0).max(2.0) }; + d.is_finite() && d > 0.0 && d >= min +} + +/// The distance from `q` to the nearest of `centres`, when it is within `r` (the stroke can be grabbed there). +pub fn grab_distance(centres: &[Pos2], q: Pos2, r: f32) -> Option { + let d = centres.iter().map(|c| c.distance(q)).filter(|d| d.is_finite()).min_by(f32::total_cmp)?; + (d < r).then_some(d) +} + +/// The boundary of the union of the discs of radius `r` at `centres`, as polylines of the arcs no other disc covers. +/// One disc, or many at the same place, gives one closed polyline (first point repeated at the end). Where discs +/// overlap, each circle contributes the arcs outside the others, from crossing to crossing, so the pieces meet and +/// are chained. Cost grows with the number of centres within `2r` of each other, so centres closer than `r / 16` to the +/// previous kept one (a held pointer in a stroke saved before points were spaced) don't count. +pub fn union_outline(centres: &[Pos2], r: f32) -> Vec> { + if !r.is_finite() || r <= 0.0 { + return Vec::new(); + } + let mut cs: Vec = Vec::new(); + for &c in centres { + if c.x.is_finite() && c.y.is_finite() && cs.last().is_none_or(|l| l.distance(c) >= r / 16.0) { + cs.push(c); + } + } + // a hostile stroke (thousands of points) is drawn from a subset: the outline stays within r/16 · stride of it + const MAX_CENTRES: usize = 1024; + if cs.len() > MAX_CENTRES { + let stride = cs.len().div_ceil(MAX_CENTRES); + cs = cs.into_iter().step_by(stride).collect(); + } + let same2 = (r * 0.01) * (r * 0.01); + // samples round a full circle: an arc gets the same angular step + let step = TAU / (r * 0.5).clamp(SAMPLES.0, SAMPLES.1).floor(); + let (mut out, mut arcs) = (Vec::new(), Vec::new()); + for (i, &c) in cs.iter().enumerate() { + let d2 = |o: &Pos2| (o.x - c.x).powi(2) + (o.y - c.y).powi(2); + // a circle on top of an earlier one adds nothing + if cs[..i].iter().any(|o| d2(o) <= same2) { + continue; + } + // the angles of this circle that another one covers: centred on the way to its centre, as wide as the + // chord where they cross (equal radii: acos(d / 2r)) + let mut covered: Vec<(f32, f32)> = Vec::new(); + for o in cs.iter().filter(|o| d2(o) > same2 && d2(o) < 4.0 * r * r) { + let (dx, dy) = (o.x - c.x, o.y - c.y); + let half = (dx.hypot(dy) / (2.0 * r)).clamp(0.0, 1.0).acos(); + let mid = dy.atan2(dx).rem_euclid(TAU); + let (lo, hi) = (mid - half, mid + half); + if lo < 0.0 { + covered.extend([(lo + TAU, TAU), (0.0, hi)]); + } else if hi > TAU { + covered.extend([(lo, TAU), (0.0, hi - TAU)]); + } else { + covered.push((lo, hi)); + } + } + covered.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut free: Vec<(f32, f32)> = Vec::new(); + let mut from = 0.0f32; + for (lo, hi) in covered { + if lo > from { + free.push((from, lo)); + } + from = from.max(hi); + } + if from < TAU { + free.push((from, TAU)); + } + // an arc that runs through angle 0 is one + if let (true, Some(&(_, end))) = (free.len() > 1 && free[0].0 == 0.0, free.last()) + && end == TAU + { + let (_, head) = free.remove(0); + if let Some(last) = free.last_mut() { + last.1 = TAU + head; + } + } + for (a, b) in free { + let m = (((b - a) / step).ceil() as usize).max(1); + let mut line: Vec = (0..=m) + .map(|k| { + let t = a + (b - a) * k as f32 / m as f32; + Pos2::new(c.x + r * t.cos(), c.y + r * t.sin()) + }) + .collect(); + // a circle nothing covers is a ring, not an arc + if b - a >= TAU { + line[m] = line[0]; + out.push(line); + } else if b - a > 1e-4 { + arcs.push(line); + } + } + } + out.extend(chain(arcs, (r * 0.01).max(0.25))); + out +} + +/// Arcs joined end to start wherever they meet within `tol`, so the outline is a few long polylines (one closed one +/// for a stroke) and not a piece per circle, with proper joins instead of butt ends at every crossing. +fn chain(arcs: Vec>, tol: f32) -> Vec> { + let cell = |p: Pos2| ((p.x / tol).floor() as i32, (p.y / tol).floor() as i32); + let first = |i: usize| arcs[i][0]; + let last = |i: usize| arcs[i][arcs[i].len() - 1]; + let grid = |at: &dyn Fn(usize) -> Pos2| { + let mut g: HashMap<(i32, i32), Vec> = HashMap::new(); + for i in 0..arcs.len() { + g.entry(cell(at(i))).or_default().push(i); + } + g + }; + // an arc whose start is within `tol` of p, `ok` to take + let find = |g: &HashMap<(i32, i32), Vec>, at: &dyn Fn(usize) -> Pos2, p: Pos2, ok: &dyn Fn(usize) -> bool| { + let (cx, cy) = cell(p); + (-1..=1) + .flat_map(|dx| (-1..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy)))) + .find_map(|c| g.get(&c)?.iter().copied().find(|&j| ok(j) && at(j).distance(p) <= tol)) + }; + let (by_start, by_end) = (grid(&first), grid(&last)); + // chains begin where no arc ends; whatever is left over is a cycle + let heads: Vec = (0..arcs.len()).filter(|&i| find(&by_end, &last, first(i), &|j| j != i).is_none()).collect(); + let mut used = vec![false; arcs.len()]; + let mut out = Vec::new(); + for i in heads.into_iter().chain(0..arcs.len()) { + if std::mem::replace(&mut used[i], true) { + continue; + } + let mut line = arcs[i].clone(); + while let Some(j) = line.last().and_then(|&end| find(&by_start, &first, end, &|j| !used[j])) { + used[j] = true; + line.extend(arcs[j].iter().skip(1)); + } + // a chain that came back to its start is closed + if let (Some(&a), Some(&b)) = (line.first(), line.last()) + && line.len() > 2 + && a.distance(b) <= tol + { + line.push(a); + } + out.push(line); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn length(lines: &[Vec]) -> f32 { + lines.iter().map(|l| l.windows(2).map(|w| w[0].distance(w[1])).sum::()).sum() + } + + fn outside_all(lines: &[Vec], centres: &[Pos2], r: f32) -> bool { + lines.iter().flatten().all(|p| centres.iter().all(|c| c.distance(*p) >= r * (1.0 - 1e-3))) + } + + #[test] + fn one_disc_is_one_closed_circle() { + let (c, r) = (Pos2::new(50.0, 40.0), 30.0); + let lines = union_outline(&[c], r); + assert_eq!(lines.len(), 1); + let l = &lines[0]; + assert_eq!(l.first(), l.last(), "closed"); + assert!(l.iter().all(|p| (p.distance(c) - r).abs() < 1e-3)); + assert!((length(&lines) - TAU * r).abs() < TAU * r * 0.01, "{}", length(&lines)); + } + + #[test] + fn many_identical_points_are_one_circle() { + let (c, r) = (Pos2::new(10.0, 10.0), 20.0); + let mut pts = vec![c; 40]; + pts.extend([Pos2::new(10.0, 10.0); 5]); + assert_eq!(union_outline(&pts, r), union_outline(&[c], r)); + // the same place reached again later in the stroke adds nothing either + let back = [c, Pos2::new(60.0, 10.0), c]; + assert_eq!(union_outline(&back, r).len(), 2, "two separate circles"); + } + + #[test] + fn two_overlapping_discs_leave_no_sample_inside_the_other() { + let r = 40.0; + let cs = [Pos2::new(0.0, 0.0), Pos2::new(r, 0.0)]; + let lines = union_outline(&cs, r); + assert_eq!(lines.len(), 1, "one closed outline, its two arcs joined at the crossings"); + assert!(lines[0][0].distance(lines[0][lines[0].len() - 1]) < 1e-3, "closed"); + assert!(outside_all(&lines, &cs, r)); + // each circle keeps 240° of its 360° when the centres are r apart + let want = 2.0 * TAU * r * (240.0 / 360.0); + assert!((length(&lines) - want).abs() < want * 0.02, "{} vs {want}", length(&lines)); + // the crossings of the two circles are on the outline + let h = r * 3f32.sqrt() / 2.0; + for y in [-h, h] { + assert!(lines[0].iter().any(|p| p.distance(Pos2::new(r / 2.0, y)) < 0.5), "crossing at y={y}"); + } + } + + #[test] + fn a_stroke_is_one_outline_around_its_path() { + let r = 30.0; + // a straight stroke at r/4 spacing + let cs: Vec = (0..40).map(|i| Pos2::new(i as f32 * r / 4.0, 0.0)).collect(); + let lines = union_outline(&cs, r); + assert!(outside_all(&lines, &cs, r)); + // a stadium: two straight sides of the stroke's length and the two caps + let want = 2.0 * 39.0 * r / 4.0 + TAU * r; + assert!((length(&lines) - want).abs() < want * 0.03, "{} vs {want}", length(&lines)); + assert_eq!(lines.len(), 1, "the arcs of all the circles are one closed line"); + // every outline point lies on a circle of the stroke + assert!(lines.iter().flatten().all(|p| cs.iter().any(|c| (c.distance(*p) - r).abs() < 1e-2))); + } + + /// A curved stroke's arcs are shorter than a sample step in places: the outline must still be one closed line. + #[test] + fn a_curved_stroke_is_one_closed_outline_without_gaps() { + for r in [6.0, 31.0, 80.0, 400.0] { + let cs: Vec = (0..70) + .map(|i| { + let t = i as f32 * r / 4.0; + Pos2::new(t * 0.9, r * 1.5 * (t / (6.0 * r)).sin() + t * 0.1) + }) + .collect(); + let lines = union_outline(&cs, r); + assert_eq!(lines.len(), 1, "r={r}: {} pieces", lines.len()); + let l = &lines[0]; + assert!(l[0].distance(l[l.len() - 1]) < 1e-3, "r={r}: closed"); + assert!(outside_all(&lines, &cs, r), "r={r}"); + // no step along the line is longer than a sample step of its circle (plus one crossing's worth of slack) + let step = TAU * r / (r * 0.5).clamp(SAMPLES.0, SAMPLES.1).floor(); + assert!(l.windows(2).all(|w| w[0].distance(w[1]) <= step * 1.01 + 0.5), "r={r}: gap in the outline"); + } + } + + #[test] + fn a_stationary_pointer_in_a_stroke_costs_nothing_extra() { + let r = 30.0; + let moving: Vec = (0..8).map(|i| Pos2::new(i as f32 * r / 4.0, 5.0)).collect(); + // every position held for 25 frames, as a stroke saved before points were spaced + let held: Vec = moving.iter().flat_map(|p| std::iter::repeat_n(*p, 25)).collect(); + assert_eq!(union_outline(&held, r), union_outline(&moving, r)); + } + + #[test] + fn hostile_input_gives_an_empty_or_finite_outline() { + for r in [0.0, -3.0, f32::NAN, f32::INFINITY] { + assert!(union_outline(&[Pos2::new(1.0, 1.0)], r).is_empty()); + } + assert!(union_outline(&[], 10.0).is_empty()); + let lines = union_outline(&[Pos2::new(f32::NAN, 0.0), Pos2::new(5.0, 5.0), Pos2::new(f32::INFINITY, 1.0)], 10.0); + assert_eq!(lines.len(), 1); + assert!(lines[0].iter().all(|p| p.x.is_finite() && p.y.is_finite())); + let many: Vec = (0..50_000).map(|i| Pos2::new(i as f32 * 0.7, (i % 7) as f32)).collect(); + assert!(!union_outline(&many, 40.0).is_empty()); + } + + #[test] + fn a_stroke_adds_points_a_quarter_radius_apart() { + let (last, r) = (Pos2::new(100.0, 100.0), 40.0); + let at = |dx: f32| Pos2::new(100.0 + dx, 100.0); + assert!(!adds_point(last, last, r, false), "stationary"); + assert!(!adds_point(last, at(9.0), r, false), "closer than r/4"); + assert!(adds_point(last, at(10.0), r, false)); + // a small brush still needs 2 points of movement + assert!(!adds_point(last, at(1.5), 4.0, false)); + assert!(adds_point(last, at(2.0), 4.0, false)); + // the release reaches where the pointer is once it moved r/8 + assert!(!adds_point(last, at(4.9), r, true)); + assert!(adds_point(last, at(5.0), r, true)); + assert!(!adds_point(last, last, r, true)); + assert!(!adds_point(last, Pos2::new(f32::NAN, 0.0), r, false)); + } + + #[test] + fn a_stroke_is_grabbed_anywhere_within_a_radius_of_its_points() { + let cs = [Pos2::new(0.0, 0.0), Pos2::new(20.0, 0.0), Pos2::new(40.0, 0.0)]; + assert_eq!(grab_distance(&cs, Pos2::new(40.0, 25.0), 30.0), Some(25.0)); + assert_eq!(grab_distance(&cs, Pos2::new(40.0, 30.0), 30.0), None); + assert_eq!(grab_distance(&[], Pos2::new(0.0, 0.0), 30.0), None); + } +} diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs new file mode 100644 index 0000000000..45b9369ab9 --- /dev/null +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -0,0 +1,89 @@ +//! Headless tests of the Remove tool's brush stroke (issue #2359): points are recorded at a spacing, not one per +//! frame, and a stroke can be grabbed anywhere along it. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn remove_tool() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for (req, params) in [("ui.set", json!({"view": "detail"})), ("engine.execute", json!({"command": "panel.remove"}))] { + let r = h.request(req, params, T); + assert_eq!(r["ok"], true, "{r}"); + } + // spots show and can be grabbed whatever the pointer does + let r = h.request("engine.execute", json!({"command": "view.toolOverlay", "params": {"mode": "always"}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.remove_size = 0.04; + h +} + +fn pointer(h: &mut Headless, kind: &str, x: f64, y: f64) { + let r = h.request("ui.pointer", json!({"events": [{"kind": kind, "x": x, "y": y}]}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); +} + +fn spots(h: &Headless) -> Vec { + h.app.session.develop_of(h.app.session.active().expect("active photo")).unwrap_or_default().spots.clone() +} + +#[test] +fn a_brushed_stroke_stores_points_at_a_spacing_and_ignores_a_held_pointer() { + let mut h = remove_tool(); + pointer(&mut h, "down", 0.3, 0.5); + // 40 frames of 0.002 of the photo's width each: about 1.4 px at this size, a point every r/4 = 8 px + for i in 1..=40 { + pointer(&mut h, "drag", 0.3 + 0.002 * f64::from(i), 0.5); + } + // held still for a while: no point per frame + for _ in 0..15 { + pointer(&mut h, "drag", 0.38, 0.5); + } + pointer(&mut h, "up", 0.38, 0.5); + let s = spots(&h); + assert_eq!(s.len(), 1, "one spot"); + let p = &s[0].points; + assert!((3..=12).contains(&p.len()), "a stroke of ~64 px with a point every ~8 px is a handful of points, got {}", p.len()); + assert!((p[0].x - 0.3).abs() < 0.02, "starts where the button went down: {:?}", p[0]); + let end = p[p.len() - 1]; + assert!((end.x - 0.38).abs() < 0.003 && (end.y - 0.5).abs() < 0.003, "reaches where the pointer was released: {end:?}"); +} + +#[test] +fn a_click_is_still_a_single_point_spot() { + let mut h = remove_tool(); + pointer(&mut h, "down", 0.6, 0.4); + pointer(&mut h, "up", 0.6, 0.4); + let s = spots(&h); + assert_eq!((s.len(), s[0].points.len()), (1, 1)); +} + +#[test] +fn a_stroke_is_grabbed_anywhere_along_it() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5], [0.34, 0.5], [0.38, 0.5], [0.42, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].points.len(), 4); + // the third point is 0.08 of the width (about 60 px) from the pin: grabbing there moves the spot, adds none + pointer(&mut h, "move", 0.38, 0.5); + pointer(&mut h, "down", 0.38, 0.5); + pointer(&mut h, "drag", 0.38, 0.55); + pointer(&mut h, "drag", 0.38, 0.6); + pointer(&mut h, "up", 0.38, 0.6); + let s = spots(&h); + assert_eq!(s.len(), 1, "grabbed the stroke instead of painting a new spot"); + assert!((s[0].points[0].y - 0.6).abs() < 0.03 && (s[0].points[0].x - 0.3).abs() < 0.01, "{:?}", s[0].points); + assert_eq!(s[0].points.len(), 4); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 080680b9ff..24d8e93569 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -270,7 +270,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-REM-GEN | Generative remove | OOS | 🚫 | | | | LR-REM-DETECT | Object detection for remove | P2 | ⬜ | | | | LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush) | -| LR-REM-SPOT-EDIT | Edit existing spots | P0 | ✅ | `cmd:spot.select`, `cmd:spot.update`, `cmd:spot.refreshSource`, `cmd:spot.delete`, `cmd:view.toolOverlay` | click a pin to select, drag target or source, ⌫ deletes the selected spot, `/` picks another source; automatic sources are resolved when the spot is added; Tool Overlay (Remove panel, View menu, ⇧H) shows the spots' pins Auto (pointer over the photo, hidden while painting) / Always / Selected / Never, and a hidden spot can't be grabbed (#224) | +| LR-REM-SPOT-EDIT | Edit existing spots | P0 | ✅ | `cmd:spot.select`, `cmd:spot.update`, `cmd:spot.refreshSource`, `cmd:spot.delete`, `cmd:view.toolOverlay` | click a pin to select, drag target or source, ⌫ deletes the selected spot, `/` picks another source; automatic sources are resolved when the spot is added; Tool Overlay (Remove panel, View menu, ⇧H) shows the spots' pins Auto (pointer over the photo, hidden while painting) / Always / Selected / Never, and a hidden spot can't be grabbed (#224); a brushed spot records a point every r/4 of movement (a held pointer adds none; `spot.add` thins the same way, #2359) and shows as one outline, the boundary of the union of its discs, with the source the same, dashed; its pin or anywhere within r of its stroke grabs it (`crates/ui-egui/src/panels/spot_outline.rs`) | | LR-REM-VISUALIZE | Visualize spots | P1 | ✅ | `cmd:view.visualizeSpots` | | | LR-REM-PEOPLE | Remove people (generative) | OOS | 🚫 | | | | LR-REM-REFLECT | Remove reflections | P2 | ⬜ | | | @@ -958,3 +958,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | +| 2026-10-20 | patch | LR-REM-SPOT-EDIT: a brushed Remove / Heal / Clone spot is one outline (union of its discs, dark under-stroke) instead of a ring per stored point, the paint preview is an outline too, the stroke records a point every r/4 and `spot.add` thins the same way, and a spot is grabbed anywhere along its stroke (#2359); status unchanged | From cd8a1f1d20cefe7afc3fd6057783cdfdebc923df Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:18:36 +0200 Subject: [PATCH 030/247] =?UTF-8?q?#2359:=20the=20mouse=20sizes=20and=20fe?= =?UTF-8?q?athers=20the=20brush=20(wheel,=20Shift+wheel,=20=E2=8C=83?= =?UTF-8?q?=E2=8C=A5-drag)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Over the photo with the Remove tool or the Masking brush, a mouse wheel notch resizes the brush (×1.1, up: larger) and Shift+wheel feathers it (±5), like `]` / `[` and ⇧`]` / ⇧`[`, the selected spot included. The wheel then doesn't zoom. A trackpad still pans, and pinch / ⌘-wheel still zoom. - ⌃⌥-drag (or ⌥-right-drag) sets both at once, as in Photoshop: across for the size, down for a softer edge. The circle and its values show where the drag started, and the drag is one undo step on a selected spot. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/panels/detail.rs | 105 +++++++++++++++++++++++- crates/ui-egui/src/tests_spot_stroke.rs | 22 +++++ docs/parity-checklist.md | 2 +- 4 files changed, 128 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 84ec8ae0c1..9e336a1cbb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -309,7 +309,7 @@ fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str /// `[` / `]` (size ×`k`) and ⇧`[` / ⇧`]` (feather +`df`) for the brush in use: the Remove tool's /// (and its selected spot's) or the Masking brush's. -fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { +pub(crate) fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { if app.ui.right == RightPanel::Remove { app.ui.remove_size = (app.ui.remove_size * k).clamp(0.001, 0.25); app.ui.remove_feather = (app.ui.remove_feather + df).clamp(0.0, 100.0); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 1271eef220..0d51db51ec 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -579,6 +579,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mut img_rect = animated_rect(ui.ctx(), &mut app.ui.zoom_anim, target_rect); let in_pane = |pane: Rect, image: Rect| image.translate(pane.center() - main_area.center()); let mut navigating = false; + brush_wheel(app, ui, &resp, right); for &view_area in &areas { let view_img = in_pane(view_area, img_rect); if navigate_gesture(app, ui, &resp, view_area, view_img, native) || middle_pan(app, ui, &resp, view_area, view_img) { @@ -954,7 +955,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) { general_cursor(app, ui, &resp, img_rect, main_area); } - if !navigating { + if !navigating && !brush_drag(app, ui, &resp, right, &map) { match right { RightPanel::Crop => crop_overlay(app, ui, &resp, &map, &frame, &d, id), RightPanel::Masking => mask_overlay(app, ui, &resp, &map, &d), @@ -2663,6 +2664,108 @@ fn pin(p: &egui::Painter, c: Pos2, sel: bool) { p.circle_stroke(c, 6.0, Stroke::new(1.5, Color32::WHITE)); } +// ------------------------------------------------------------------------ brush by mouse + +/// The brush the pointer paints with on the photo: the Remove tool's, or the Masking brush. +fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { + right == RightPanel::Remove || (right == RightPanel::Masking && app.ui.tool == "brush") +} + +/// The mouse wheel over the photo resizes the brush in use (up: larger, ×1.1 a notch) and +/// Shift+wheel feathers it (+5 a notch), as `]` / `[` and ⇧`]` / ⇧`[` do, the selected spot too. +/// The wheel then doesn't zoom; a trackpad still pans and pinch / ⌘-wheel still zoom. +fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { + let id = egui::Id::new("brush-wheel"); + if !brush_in_use(app, right) || !resp.hovered() { + ui.data_mut(|d| d.remove_temp::(id)); + return; + } + let ours = |e: &egui::Event| match e { + egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page, delta, modifiers, .. } if delta.is_finite() => { + if *modifiers == egui::Modifiers::NONE { + Some((delta.y, 0.0)) + } else if *modifiers == egui::Modifiers::SHIFT { + // some platforms turn Shift+wheel into a sideways scroll + Some((0.0, delta.y + delta.x)) + } else { + None + } + } + _ => None, + }; + let (size, feather) = ui.input(|i| i.events.iter().filter_map(ours).fold((0.0f32, 0.0f32), |a, b| (a.0 + b.0, a.1 + b.1))); + if size != 0.0 || feather != 0.0 { + ui.input_mut(|i| i.events.retain(|e| ours(e).is_none())); + ui.data_mut(|d| d.insert_temp(id, true)); + let _ = crate::menus::adjust_brush(app, 1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); + } + // egui glides a wheel's scroll over the next frames: none of it may pan or zoom the photo + if ui.data(|d| d.get_temp::(id)).unwrap_or(false) { + if ui.input(|i| i.smooth_scroll_delta == egui::Vec2::ZERO) { + ui.data_mut(|d| d.remove_temp::(id)); + } + ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); + } +} + +/// ⌃⌥-drag (or ⌥-right-drag) on the photo sets the brush in use the way Photoshop does: across for +/// the size, up and down for the feather (down: softer), shown on the circle where the drag +/// started. True while it owns the pointer (nothing is painted). +fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel, map: &CanvasMap) -> bool { + let id = egui::Id::new("brush-resize"); + if !brush_in_use(app, right) { + ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); + return false; + } + let remove = right == RightPanel::Remove; + let current = |app: &LightcraftApp| { + if remove { (app.ui.remove_size, app.ui.remove_feather) } else { (app.ui.brush_size, app.ui.brush_feather) } + }; + let (mods, secondary) = ui.input(|i| (i.modifiers, i.pointer.secondary_down())); + if resp.drag_started() + && ((mods.ctrl && mods.alt) || (mods.alt && secondary)) + && let Some(o) = ui.input(|i| i.pointer.press_origin()) + { + let (s0, f0) = current(app); + ui.data_mut(|d| d.insert_temp(id, (o, s0, f0))); + if remove && app.session.active_spot.is_some() { + let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); + } + } + let Some((o, s0, f0)) = ui.data(|d| d.get_temp::<(Pos2, f32, f32)>(id)) else { return false }; + if let Some(q) = ui.input(|i| i.pointer.latest_pos()) { + let dv = q - o; + let (s, f) = current(app); + let size = s0 * (dv.x / 200.0).exp(); + let feather = (f0 + dv.y * 0.3).clamp(0.0, 100.0); + if size != s || feather != f { + let _ = crate::menus::adjust_brush(app, size / s.max(1e-6), feather - f); + } + } + let (s, f) = current(app); + let long = map.rect.width().max(map.rect.height()); + let r = s * long; + let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect)); + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + for (rr, col) in [(r, Color32::WHITE), (r * (1.0 - f / 100.0).max(0.05), Color32::from_white_alpha(140))] { + p.circle_stroke(o, rr, Stroke::new(2.5, Color32::from_black_alpha(110))); + p.circle_stroke(o, rr, Stroke::new(1.0, col)); + } + let label = format!("{} {:.0} · {} {:.0}", crate::i18n::tr("Size"), s * 1000.0, crate::i18n::tr("Feather"), f); + let at = o + vec2(0.0, r + 14.0); + let galley = p.layout_no_wrap(label, egui::FontId::proportional(12.0), Color32::WHITE); + let rect = Rect::from_center_size(at, galley.size() + vec2(10.0, 4.0)); + p.rect_filled(rect, 4.0, Color32::from_black_alpha(160)); + p.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); + if !ui.input(|i| i.pointer.any_down()) { + ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); + if remove && app.session.interaction.is_some() { + let _ = app.run("develop.endInteraction", json!({})); + } + } + true +} + // ------------------------------------------------------------------------ remove /// The Remove tool on the photo: every spot's outline and pin (the selected one with its source), diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index 45b9369ab9..d2ca6ccd68 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -87,3 +87,25 @@ fn a_stroke_is_grabbed_anywhere_along_it() { assert!((s[0].points[0].y - 0.6).abs() < 0.03 && (s[0].points[0].x - 0.3).abs() < 0.01, "{:?}", s[0].points); assert_eq!(s[0].points.len(), 4); } + +fn wheel(h: &mut Headless, dy: f32, modifiers: egui::Modifiers) { + h.events.push(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers }); + h.step(); +} + +#[test] +fn the_wheel_over_the_photo_sizes_and_feathers_the_brush_instead_of_zooming() { + let mut h = remove_tool(); + let c = h.app.image_rect.expect("photo drawn").center(); + h.request("ui.move", json!({"x": c.x, "y": c.y}), T); + h.step(); + let (zoom, size, feather) = (h.app.ui.zoom, h.app.ui.remove_size, h.app.ui.remove_feather); + wheel(&mut h, 2.0, egui::Modifiers::NONE); + for _ in 0..30 { + h.step(); + } + assert!((h.app.ui.remove_size / size - 1.21).abs() < 0.01, "two notches up: ×1.1², got {} from {size}", h.app.ui.remove_size); + assert_eq!(h.app.ui.zoom, zoom, "the wheel doesn't zoom while the Remove tool is open"); + wheel(&mut h, -1.0, egui::Modifiers::SHIFT); + assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+wheel feathers"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 24d8e93569..e582de071e 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -269,7 +269,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-REM-CLONE | Clone | P0 | ✅ | `cmd:spot.add` (`mode: clone`), `crates/pipeline/src/spots.rs` | Hard-edge source copying and unchanged radius pixels regression-tested at two output sizes | | LR-REM-GEN | Generative remove | OOS | 🚫 | | | | LR-REM-DETECT | Object detection for remove | P2 | ⬜ | | | -| LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush) | +| LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush); the mouse wheel over the photo sizes the Remove / Masking brush and Shift+wheel feathers it, ⌃⌥-drag (⌥-right-drag) sets both at once, as in Photoshop (#2359) | | LR-REM-SPOT-EDIT | Edit existing spots | P0 | ✅ | `cmd:spot.select`, `cmd:spot.update`, `cmd:spot.refreshSource`, `cmd:spot.delete`, `cmd:view.toolOverlay` | click a pin to select, drag target or source, ⌫ deletes the selected spot, `/` picks another source; automatic sources are resolved when the spot is added; Tool Overlay (Remove panel, View menu, ⇧H) shows the spots' pins Auto (pointer over the photo, hidden while painting) / Always / Selected / Never, and a hidden spot can't be grabbed (#224); a brushed spot records a point every r/4 of movement (a held pointer adds none; `spot.add` thins the same way, #2359) and shows as one outline, the boundary of the union of its discs, with the source the same, dashed; its pin or anywhere within r of its stroke grabs it (`crates/ui-egui/src/panels/spot_outline.rs`) | | LR-REM-VISUALIZE | Visualize spots | P1 | ✅ | `cmd:view.visualizeSpots` | | | LR-REM-PEOPLE | Remove people (generative) | OOS | 🚫 | | | From f3a96aced3b63196e78a9c3ad3554eeeb408670f Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:03:38 +0200 Subject: [PATCH 031/247] #2359: smooth-scrolling mice size the brush; spot outlines run outside the feather and show it macOS reports a Magic Mouse, smooth-scrolling wheels and trackpads in points, which the wheel handler ignored, so it zoomed or panned. A line's worth of points is now a notch. A spot's outline sat on its outer radius, right over the seam being matched. It now runs 3 pt outside where the blend stops (past the radius for Fill, whose feather is outside), and the selected spot, a stroke being painted and the cursor show a faint dashed line where the blend is full, so the feather between the two is visible. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 70 +++++++++++++++++++------ crates/ui-egui/src/tests_spot_stroke.rs | 26 +++++++++ 2 files changed, 80 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 0d51db51ec..beae01d598 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -3,7 +3,7 @@ use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use lightcraft_catalog::PhotoId; -use lightcraft_develop::{DevelopSettings, MaskShape}; +use lightcraft_develop::{DevelopSettings, MaskShape, SpotMode}; use lightcraft_geom::{Affine, Point}; use lightcraft_pipeline::geometry::Frame; use serde_json::json; @@ -2673,20 +2673,24 @@ fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { /// The mouse wheel over the photo resizes the brush in use (up: larger, ×1.1 a notch) and /// Shift+wheel feathers it (+5 a notch), as `]` / `[` and ⇧`]` / ⇧`[` do, the selected spot too. -/// The wheel then doesn't zoom; a trackpad still pans and pinch / ⌘-wheel still zoom. +/// As in Lightroom, a smooth-scrolling mouse and a two-finger trackpad swipe do the same (a line's +/// worth of points a notch) instead of zooming or panning; pinch and ⌘-wheel still zoom. fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { let id = egui::Id::new("brush-wheel"); if !brush_in_use(app, right) || !resp.hovered() { ui.data_mut(|d| d.remove_temp::(id)); return; } + let line = ui.ctx().options(|o| o.input_options.line_scroll_speed).max(1.0); let ours = |e: &egui::Event| match e { - egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page, delta, modifiers, .. } if delta.is_finite() => { + egui::Event::MouseWheel { unit, delta, modifiers, .. } if delta.is_finite() => { + // macOS reports most mice in points (Magic Mouse, smooth-scrolling wheels), a notched wheel in lines + let notches = if *unit == egui::MouseWheelUnit::Point { *delta / line } else { *delta }; if *modifiers == egui::Modifiers::NONE { - Some((delta.y, 0.0)) + Some((notches.y, 0.0)) } else if *modifiers == egui::Modifiers::SHIFT { // some platforms turn Shift+wheel into a sideways scroll - Some((0.0, delta.y + delta.x)) + Some((0.0, notches.y + notches.x)) } else { None } @@ -2747,10 +2751,8 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, let r = s * long; let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect)); ui.ctx().set_cursor_icon(egui::CursorIcon::None); - for (rr, col) in [(r, Color32::WHITE), (r * (1.0 - f / 100.0).max(0.05), Color32::from_white_alpha(140))] { - p.circle_stroke(o, rr, Stroke::new(2.5, Color32::from_black_alpha(110))); - p.circle_stroke(o, rr, Stroke::new(1.0, col)); - } + let band = if remove { spot_band(feather_band(app.ui.tool == "fill", r, f)) } else { (r * (1.0 - f / 100.0), r) }; + brush_circles(&p, o, band); let label = format!("{} {:.0} · {} {:.0}", crate::i18n::tr("Size"), s * 1000.0, crate::i18n::tr("Feather"), f); let at = o + vec2(0.0, r + 14.0); let galley = p.layout_no_wrap(label, egui::FontId::proportional(12.0), Color32::WHITE); @@ -2790,7 +2792,8 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let mut bodies: Vec<(usize, bool, Vec, f32)> = Vec::new(); let clip = p.clip_rect(); for (i, s) in d.spots.iter().enumerate() { - let r = (s.size * long) as f32; + let band = feather_band(s.mode == SpotMode::Fill, (s.size * long) as f32, s.feather as f32); + let r = band.1 + OUTLINE_GAP; let sel = Some(i) == active; if !mode.shows(sel, live) { continue; @@ -2799,13 +2802,13 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let target: Vec = s.points.iter().map(|q| map.screen(*q)).collect(); let light = if sel { Stroke::new(1.25, Color32::from_white_alpha(230)) } else { Stroke::new(1.0, Color32::from_white_alpha(120)) }; if touches(&target, r, clip) { - draw_outline(p, &spot_outline::union_outline(&target, r), light, false); + draw_spot(p, &target, band, light, false, sel); } let Some(&tq) = target.first() else { continue }; if let Some(o) = s.source_offset.filter(|_| sel) { let source: Vec = s.points.iter().map(|q| map.screen(Point::new(q.x + o.x, q.y + o.y))).collect(); if touches(&source, r, clip) { - draw_outline(p, &spot_outline::union_outline(&source, r), Stroke::new(1.0, Color32::from_white_alpha(150)), true); + draw_spot(p, &source, band, Stroke::new(1.0, Color32::from_white_alpha(150)), true, false); } let sq = source[0]; let dir = (tq - sq).normalized(); @@ -2825,6 +2828,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo return; } let r = (app.ui.remove_size as f64 * long) as f32; + let band = feather_band(app.ui.tool == "fill", r, app.ui.remove_feather); // a target or source under `q` (its pin or anywhere along its stroke): the selected spot's first, then the nearest let hit = |q: Pos2| { bodies @@ -2838,8 +2842,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } else { ui.ctx().set_cursor_icon(egui::CursorIcon::None); - p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE)); - p.circle_stroke(h, r * (1.0 - app.ui.remove_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(110))); + brush_circles(&p, h, spot_band(band)); } } let press = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); @@ -2891,7 +2894,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo } if let Some(Gesture::Spot { points }) = &app.gesture { let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); - draw_outline(&p, &spot_outline::union_outline(&screen, r), Stroke::new(1.25, Color32::from_white_alpha(230)), false); + draw_spot(&p, &screen, band, Stroke::new(1.25, Color32::from_white_alpha(230)), false, true); } if (resp.drag_stopped() || resp.clicked()) && let Some(Gesture::Spot { points }) = app.gesture.take() @@ -2915,9 +2918,44 @@ fn touches(pts: &[Pos2], r: f32, clip: Rect) -> bool { pts.iter().any(|q| clip.expand(r).contains(*q)) } +/// Where a spot of radius `r` starts and stops blending into the photo, as `pipeline::spots` does it: Heal and +/// Clone feather inside the radius (over its outer 80 % at full feather), Fill replaces all of it and feathers +/// outside, up to 0.3 radii further. +fn feather_band(outside: bool, r: f32, feather: f32) -> (f32, f32) { + let f = (feather / 100.0).clamp(0.0, 1.0); + if outside { (r, r * (1.0 + 0.3 * f)) } else { (r * (1.0 - 0.8 * f), r) } +} + +/// How far outside the blend a spot's outline runs (screen points), so the line never covers the edge being matched. +const OUTLINE_GAP: f32 = 3.0; + +/// A spot over `pts` blending across `band`: its outline just outside the blend and, with `feather`, a faint +/// dashed line where the blend is full, so the feather between the two shows. +fn draw_spot(p: &egui::Painter, pts: &[Pos2], band: (f32, f32), light: Stroke, dashed: bool, feather: bool) { + draw_outline(p, &spot_outline::union_outline(pts, band.1 + OUTLINE_GAP), light, dashed); + if feather && band.1 - band.0 >= 3.0 && band.0 >= 2.0 { + for l in spot_outline::union_outline(pts, band.0) { + p.extend(egui::Shape::dashed_line(&l, Stroke::new(1.0, Color32::from_white_alpha(110)), 3.0, 3.0)); + } + } +} + +/// A Remove brush's `band` as its cursor shows it: the outer circle where a spot's outline will run. +fn spot_band(band: (f32, f32)) -> (f32, f32) { + (band.0, band.1 + OUTLINE_GAP) +} + +/// The brush cursor: a solid circle at the outer edge of `band`, a faint one at its inner edge (where the blend is full). +fn brush_circles(p: &egui::Painter, at: Pos2, band: (f32, f32)) { + for (rr, col) in [(band.1, Color32::WHITE), (band.0.max(1.0), Color32::from_white_alpha(140))] { + p.circle_stroke(at, rr, Stroke::new(2.0, Color32::from_black_alpha(90))); + p.circle_stroke(at, rr, Stroke::new(1.0, col)); + } +} + /// A spot's outline in `light`, over a dark under-stroke so a thin line stays visible on light and dark areas alike. fn draw_outline(p: &egui::Painter, lines: &[Vec], light: Stroke, dashed: bool) { - let dark = Stroke::new(light.width + 1.5, Color32::from_black_alpha(110)); + let dark = Stroke::new(light.width + 1.0, Color32::from_black_alpha(90)); for stroke in [dark, light] { for l in lines { if dashed { diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index d2ca6ccd68..da717590b3 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -109,3 +109,29 @@ fn the_wheel_over_the_photo_sizes_and_feathers_the_brush_instead_of_zooming() { wheel(&mut h, -1.0, egui::Modifiers::SHIFT); assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+wheel feathers"); } + +#[test] +fn a_smooth_scrolling_mouse_sizes_the_brush_too() { + // macOS reports a Magic Mouse, a smooth-scrolling wheel and a trackpad in points, not lines + let mut h = remove_tool(); + let c = h.app.image_rect.expect("photo drawn").center(); + h.request("ui.move", json!({"x": c.x, "y": c.y}), T); + h.step(); + let (zoom, pan, size, feather) = (h.app.ui.zoom, h.app.ui.pan, h.app.ui.remove_size, h.app.ui.remove_feather); + let line = h.view.ctx.options(|o| o.input_options.line_scroll_speed); + for (y, modifiers) in [(line, egui::Modifiers::NONE), (line, egui::Modifiers::NONE), (-line, egui::Modifiers::SHIFT)] { + h.events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, y), + phase: egui::TouchPhase::Move, + modifiers, + }); + h.step(); + } + for _ in 0..30 { + h.step(); + } + assert!((h.app.ui.remove_size / size - 1.21).abs() < 0.01, "two lines' worth of points: ×1.1², got {} from {size}", h.app.ui.remove_size); + assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+scroll feathers"); + assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "nor does it zoom or pan"); +} From 1e90a76ba44d5240bc50baf6cb12fc9ee9e24849 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:20:54 +0200 Subject: [PATCH 032/247] #2359: the wheel sizes the spot under the pointer, elsewhere the next stroke; a dragged spot's outline hides MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wheel used to resize the selected spot wherever the pointer was, so the stroke just painted changed instead of the brush for the next one. Over a spot (its pin or anywhere along its stroke) the wheel now resizes and feathers that spot, selecting it; elsewhere it lets go of the selected spot, whose settings the brush shows, and resizes the brush alone. ⌃⌥-drag likewise sets the brush for the next stroke. [ and ] are unchanged. While a spot's target or source is dragged, the target's outline hides, so the edge being matched shows. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 26 +++++---- crates/ui-egui/src/panels/detail.rs | 73 ++++++++++++++++++++----- crates/ui-egui/src/tests_spot_stroke.rs | 28 ++++++++++ 3 files changed, 103 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9e336a1cbb..f0d23b6ea7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -310,19 +310,25 @@ fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str /// `[` / `]` (size ×`k`) and ⇧`[` / ⇧`]` (feather +`df`) for the brush in use: the Remove tool's /// (and its selected spot's) or the Masking brush's. pub(crate) fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { + let v = resize_brush(app, k, df); + if app.ui.right == RightPanel::Remove && app.session.active_spot.is_some() { + let mut p = json!({}); + if k != 1.0 { + p["size"] = json!(app.ui.remove_size); + } + if df != 0.0 { + p["feather"] = json!(app.ui.remove_feather); + } + let _ = app.run("spot.update", p); + } + v +} + +/// The brush in use alone, size ×`k` and feather +`df`, for the next stroke: no spot changes. +pub(crate) fn resize_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { if app.ui.right == RightPanel::Remove { app.ui.remove_size = (app.ui.remove_size * k).clamp(0.001, 0.25); app.ui.remove_feather = (app.ui.remove_feather + df).clamp(0.0, 100.0); - if app.session.active_spot.is_some() { - let mut p = json!({}); - if k != 1.0 { - p["size"] = json!(app.ui.remove_size); - } - if df != 0.0 { - p["feather"] = json!(app.ui.remove_feather); - } - let _ = app.run("spot.update", p); - } json!({"size": app.ui.remove_size, "feather": app.ui.remove_feather}) } else { app.ui.brush_size = (app.ui.brush_size * k).clamp(0.002, 0.5); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index beae01d598..216877669d 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2671,8 +2671,10 @@ fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { right == RightPanel::Remove || (right == RightPanel::Masking && app.ui.tool == "brush") } -/// The mouse wheel over the photo resizes the brush in use (up: larger, ×1.1 a notch) and -/// Shift+wheel feathers it (+5 a notch), as `]` / `[` and ⇧`]` / ⇧`[` do, the selected spot too. +/// The mouse wheel over the photo resizes the brush in use for the next stroke (up: larger, ×1.1 a +/// notch) and Shift+wheel feathers it (+5 a notch). Over a Remove spot it resizes and feathers that +/// spot instead (selecting it), so a stroke just painted can still be adjusted; elsewhere it lets go +/// of the selected spot, whose settings the brush otherwise follows. /// As in Lightroom, a smooth-scrolling mouse and a two-finger trackpad swipe do the same (a line's /// worth of points a notch) instead of zooming or panning; pinch and ⌘-wheel still zoom. fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { @@ -2701,7 +2703,26 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response if size != 0.0 || feather != 0.0 { ui.input_mut(|i| i.events.retain(|e| ours(e).is_none())); ui.data_mut(|d| d.insert_temp(id, true)); - let _ = crate::menus::adjust_brush(app, 1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); + let (k, df) = (1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); + match ui.data(|d| d.get_temp::(egui::Id::new(HOVERED_SPOT))).filter(|_| right == RightPanel::Remove) { + Some(HoveredSpot { index, size, feather }) => { + if app.session.active_spot != Some(index) { + let _ = app.run("spot.select", json!({"index": index})); + } + let mut p = json!({"index": index}); + if k != 1.0 { + p["size"] = json!((size * k as f64).clamp(0.001, 0.25)); + } + if df != 0.0 { + p["feather"] = json!((feather + df as f64).clamp(0.0, 100.0)); + } + let _ = app.run("spot.update", p); + } + None => { + deselect_spot(app, right); + let _ = crate::menus::resize_brush(app, k, df); + } + } } // egui glides a wheel's scroll over the next frames: none of it may pan or zoom the photo if ui.data(|d| d.get_temp::(id)).unwrap_or(false) { @@ -2712,9 +2733,16 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response } } -/// ⌃⌥-drag (or ⌥-right-drag) on the photo sets the brush in use the way Photoshop does: across for -/// the size, up and down for the feather (down: softer), shown on the circle where the drag -/// started. True while it owns the pointer (nothing is painted). +/// Lets go of the selected Remove spot, so the brush (which shows a selected spot's settings) is the next stroke's alone. +fn deselect_spot(app: &mut LightcraftApp, right: RightPanel) { + if right == RightPanel::Remove && app.session.active_spot.is_some() { + let _ = app.run("spot.select", json!({"index": null})); + } +} + +/// ⌃⌥-drag (or ⌥-right-drag) on the photo sets the brush in use for the next stroke the way +/// Photoshop does: across for the size, up and down for the feather (down: softer), shown on the +/// circle where the drag started. True while it owns the pointer (nothing is painted). fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel, map: &CanvasMap) -> bool { let id = egui::Id::new("brush-resize"); if !brush_in_use(app, right) { @@ -2730,11 +2758,9 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, && ((mods.ctrl && mods.alt) || (mods.alt && secondary)) && let Some(o) = ui.input(|i| i.pointer.press_origin()) { + deselect_spot(app, right); let (s0, f0) = current(app); ui.data_mut(|d| d.insert_temp(id, (o, s0, f0))); - if remove && app.session.active_spot.is_some() { - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); - } } let Some((o, s0, f0)) = ui.data(|d| d.get_temp::<(Pos2, f32, f32)>(id)) else { return false }; if let Some(q) = ui.input(|i| i.pointer.latest_pos()) { @@ -2743,7 +2769,7 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, let size = s0 * (dv.x / 200.0).exp(); let feather = (f0 + dv.y * 0.3).clamp(0.0, 100.0); if size != s || feather != f { - let _ = crate::menus::adjust_brush(app, size / s.max(1e-6), feather - f); + let _ = crate::menus::resize_brush(app, size / s.max(1e-6), feather - f); } } let (s, f) = current(app); @@ -2761,15 +2787,21 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, p.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); if !ui.input(|i| i.pointer.any_down()) { ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); - if remove && app.session.interaction.is_some() { - let _ = app.run("develop.endInteraction", json!({})); - } } true } // ------------------------------------------------------------------------ remove +/// The Remove spot under the pointer as of the last frame, with its size and feather. +#[derive(Clone, Copy, Debug, Default)] +struct HoveredSpot { + index: usize, + size: f64, + feather: f64, +} +const HOVERED_SPOT: &str = "remove-hovered-spot"; + /// The Remove tool on the photo: every spot's outline and pin (the selected one with its source), /// click a pin to select its spot, drag a target or source to move it, paint elsewhere to add one. /// The Tool Overlay mode (Shift+H) says which spots show; a hidden spot can't be grabbed, so a @@ -2780,6 +2812,11 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let (mode, live) = (app.ui.tool_overlay, pins_live(app, resp, map)); // Auto also hides them while a new spot is painted let painting = mode == ToolOverlay::Auto && matches!(app.gesture, Some(Gesture::Spot { .. })); + // while a spot's target or source is dragged, its target's outline is hidden, so the edge being matched shows + let moving = match app.gesture { + Some(Gesture::SpotMove { spot, .. }) => Some(spot), + _ => None, + }; let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect)); let mut pins = p.clone(); if painting { @@ -2801,7 +2838,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let p = &pins; let target: Vec = s.points.iter().map(|q| map.screen(*q)).collect(); let light = if sel { Stroke::new(1.25, Color32::from_white_alpha(230)) } else { Stroke::new(1.0, Color32::from_white_alpha(120)) }; - if touches(&target, r, clip) { + if touches(&target, r, clip) && moving != Some(i) { draw_spot(p, &target, band, light, false, sel); } let Some(&tq) = target.first() else { continue }; @@ -2837,6 +2874,14 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo .min_by(|a, b| (Some(a.0) != active, a.2).partial_cmp(&(Some(b.0) != active, b.2)).unwrap_or(std::cmp::Ordering::Equal)) }; let hover = resp.hover_pos().and_then(hit); + // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) + let hovered = hover.and_then(|(index, ..)| d.spots.get(index).map(|s| HoveredSpot { index, size: s.size, feather: s.feather })); + ui.data_mut(|m| { + m.remove_temp::(egui::Id::new(HOVERED_SPOT)); + if let Some(h) = hovered { + m.insert_temp(egui::Id::new(HOVERED_SPOT), h); + } + }); if let Some(h) = resp.hover_pos() { if hover.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index da717590b3..bd0a35a1f9 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -135,3 +135,31 @@ fn a_smooth_scrolling_mouse_sizes_the_brush_too() { assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+scroll feathers"); assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "nor does it zoom or pan"); } + +#[test] +fn the_wheel_sizes_the_spot_under_the_pointer_and_elsewhere_the_next_stroke() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "feather": 40.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + // away from the spot just added (still selected): the brush changes, the spot doesn't + pointer(&mut h, "move", 0.7, 0.5); + let brush = h.app.ui.remove_size; + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!((h.app.ui.remove_size / brush - 1.1).abs() < 0.01, "the next stroke's brush grows"); + assert_eq!(spots(&h)[0].size, 0.04, "the selected spot keeps its size"); + assert_eq!(h.app.session.active_spot, None, "and is let go, so the brush no longer shows its settings"); + h.step(); + assert!((h.app.ui.remove_size / brush - 1.1).abs() < 0.01, "the brush keeps its new size"); + // over the spot: that spot changes (and is selected again) + pointer(&mut h, "move", 0.3, 0.5); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + wheel(&mut h, -1.0, egui::Modifiers::SHIFT); + let s = spots(&h); + assert!((s[0].size / 0.04 - 1.1).abs() < 0.01, "the spot under the pointer grows, got {}", s[0].size); + assert_eq!(s[0].feather, 35.0, "and Shift+wheel feathers it"); + assert_eq!(h.app.session.active_spot, Some(0)); +} From 61ab5881d5841679d4ea98e60e9151beefbb99e4 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:15:02 +0200 Subject: [PATCH 033/247] #2359: a wheel gesture on a spot is one undo step and counts every notch Each frame with wheel events sent its own spot.update, so a trackpad swipe added tens of Edit Spot undo steps; they are now one interaction, ended by a 0.5 s pause, the pointer leaving the spot, a button press or the tool closing. The wheel also scaled the size the overlay saw before the previous frame's edit, losing every other notch on consecutive frames; it now reads the spot from the session. (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 45 +++++++++++++++++++++---- crates/ui-egui/src/tests_spot_stroke.rs | 24 +++++++++++++ 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 216877669d..db7aa242d4 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2679,7 +2679,19 @@ fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { /// worth of points a notch) instead of zooming or panning; pinch and ⌘-wheel still zoom. fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { let id = egui::Id::new("brush-wheel"); - if !brush_in_use(app, right) || !resp.hovered() { + let now = ui.input(|i| i.time); + let hovered = ui.data(|d| d.get_temp::(egui::Id::new(HOVERED_SPOT))).filter(|_| right == RightPanel::Remove); + let in_use = brush_in_use(app, right) && resp.hovered(); + // one wheel gesture on a spot is one undo step: it ends after a pause, off that spot, or when the tool goes + if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) { + let pressed = ui.input(|i| i.pointer.any_down()); + if !in_use || pressed || hovered.map(|h| h.index) != Some(spot) || now - last > WHEEL_EDIT_PAUSE { + end_wheel_edit(app, ui); + } else { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); + } + } + if !in_use { ui.data_mut(|d| d.remove_temp::(id)); return; } @@ -2704,11 +2716,20 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response ui.input_mut(|i| i.events.retain(|e| ours(e).is_none())); ui.data_mut(|d| d.insert_temp(id, true)); let (k, df) = (1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); - match ui.data(|d| d.get_temp::(egui::Id::new(HOVERED_SPOT))).filter(|_| right == RightPanel::Remove) { - Some(HoveredSpot { index, size, feather }) => { + match hovered { + Some(HoveredSpot { index }) => { + // the spot as it is now: the overlay saw it before this frame's edits + let current = + app.session.active().and_then(|p| app.session.develop_of(p)).and_then(|d| d.spots.get(index).map(|s| (s.size, s.feather))); + let Some((size, feather)) = current else { return }; if app.session.active_spot != Some(index) { let _ = app.run("spot.select", json!({"index": index})); } + if ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_none() { + let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); + } + ui.data_mut(|d| d.insert_temp(egui::Id::new(WHEEL_EDIT), (index, now))); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); let mut p = json!({"index": index}); if k != 1.0 { p["size"] = json!((size * k as f64).clamp(0.001, 0.25)); @@ -2733,6 +2754,18 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response } } +/// The spot a wheel gesture is editing and when it last turned, as `(index, time)`; its edits are one undo step. +const WHEEL_EDIT: &str = "brush-wheel-edit"; +/// Seconds without a turn that end a wheel gesture. +const WHEEL_EDIT_PAUSE: f64 = 0.5; + +/// Commits a wheel gesture's spot edits as one undo step. +fn end_wheel_edit(app: &mut LightcraftApp, ui: &mut egui::Ui) { + if ui.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { + let _ = app.run("develop.endInteraction", json!({})); + } +} + /// Lets go of the selected Remove spot, so the brush (which shows a selected spot's settings) is the next stroke's alone. fn deselect_spot(app: &mut LightcraftApp, right: RightPanel) { if right == RightPanel::Remove && app.session.active_spot.is_some() { @@ -2793,12 +2826,10 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, // ------------------------------------------------------------------------ remove -/// The Remove spot under the pointer as of the last frame, with its size and feather. +/// The Remove spot under the pointer as of the last frame. #[derive(Clone, Copy, Debug, Default)] struct HoveredSpot { index: usize, - size: f64, - feather: f64, } const HOVERED_SPOT: &str = "remove-hovered-spot"; @@ -2875,7 +2906,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo }; let hover = resp.hover_pos().and_then(hit); // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) - let hovered = hover.and_then(|(index, ..)| d.spots.get(index).map(|s| HoveredSpot { index, size: s.size, feather: s.feather })); + let hovered = hover.map(|(index, ..)| HoveredSpot { index }); ui.data_mut(|m| { m.remove_temp::(egui::Id::new(HOVERED_SPOT)); if let Some(h) = hovered { diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index bd0a35a1f9..c64a93e1a8 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -163,3 +163,27 @@ fn the_wheel_sizes_the_spot_under_the_pointer_and_elsewhere_the_next_stroke() { assert_eq!(s[0].feather, 35.0, "and Shift+wheel feathers it"); assert_eq!(h.app.session.active_spot, Some(0)); } + +#[test] +fn notches_on_consecutive_frames_all_count_and_undo_as_one_step() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "feather": 40.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.3, 0.5); + // a spun wheel: a notch on each of four frames + for _ in 0..4 { + wheel(&mut h, 1.0, egui::Modifiers::NONE); + } + let grown = spots(&h)[0].size; + assert!((grown / 0.04 - 1.1f64.powi(4)).abs() < 0.01, "four notches: ×1.1⁴, got {grown}"); + // the gesture ends off the spot; one undo takes back all of it + pointer(&mut h, "move", 0.7, 0.5); + assert!(h.app.session.interaction.is_none(), "the wheel gesture is committed"); + let r = h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].size, 0.04, "one undo step for the whole gesture"); +} From 8dea7e923c0183ea6b03303b17b63b83645b5051 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:12:29 +0200 Subject: [PATCH 034/247] #2359: leaving the loupe ends a wheel gesture on a spot The wheel's Edit Spot interaction ended only from brush_wheel, which runs while the loupe draws: switching straight to a grid left it open, so later develop edits would preview inside it and commit as part of the wheel edit. Every frame now ends a gesture whose loupe or Remove tool is gone, or that has paused. (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels/detail.rs | 18 ++++++++++++++---- crates/ui-egui/src/tests_spot_stroke.rs | 22 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b4e18a4361..bdd5e06f2b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1976,6 +1976,7 @@ impl LightcraftApp { self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); + panels::detail::settle_wheel_edit(self, ctx); self.slideshow_tick(ctx, now); panels::denoise::pump_background(self, ctx, now); panels::faces::pump_background(self, ctx, now); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index db7aa242d4..f48ac97341 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -11,7 +11,7 @@ use serde_json::json; use crate::LightcraftApp; use crate::panels::spot_outline; use crate::render::Slot; -use crate::state::{BeforeAfter, RightPanel, ToolOverlay, Zoom}; +use crate::state::{BeforeAfter, RightPanel, ToolOverlay, ViewMode, Zoom}; use crate::theme::Tokens; use crate::widgets::{register, register_geometry}; @@ -2686,7 +2686,7 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) { let pressed = ui.input(|i| i.pointer.any_down()); if !in_use || pressed || hovered.map(|h| h.index) != Some(spot) || now - last > WHEEL_EDIT_PAUSE { - end_wheel_edit(app, ui); + end_wheel_edit(app, ui.ctx()); } else { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); } @@ -2760,12 +2760,22 @@ const WHEEL_EDIT: &str = "brush-wheel-edit"; const WHEEL_EDIT_PAUSE: f64 = 0.5; /// Commits a wheel gesture's spot edits as one undo step. -fn end_wheel_edit(app: &mut LightcraftApp, ui: &mut egui::Ui) { - if ui.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { +fn end_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { + if ctx.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { let _ = app.run("develop.endInteraction", json!({})); } } +/// Every frame, whatever is drawn: ends a wheel gesture whose loupe is gone (another view, another +/// tool), which `brush_wheel` no longer runs to end, or that has paused, so no later edit joins it. +pub(crate) fn settle_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some((_, last)) = ctx.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) else { return }; + let drawn = app.ui.view == ViewMode::Detail && app.ui.right == RightPanel::Remove && !app.ui.fullscreen; + if !drawn || ctx.input(|i| i.time) - last > WHEEL_EDIT_PAUSE { + end_wheel_edit(app, ctx); + } +} + /// Lets go of the selected Remove spot, so the brush (which shows a selected spot's settings) is the next stroke's alone. fn deselect_spot(app: &mut LightcraftApp, right: RightPanel) { if right == RightPanel::Remove && app.session.active_spot.is_some() { diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index c64a93e1a8..e2a9385c2b 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -187,3 +187,25 @@ fn notches_on_consecutive_frames_all_count_and_undo_as_one_step() { assert_eq!(r["ok"], true, "{r}"); assert_eq!(spots(&h)[0].size, 0.04, "one undo step for the whole gesture"); } + +#[test] +fn leaving_the_loupe_ends_a_wheel_gesture() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.3, 0.5); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!(h.app.session.interaction.is_some(), "the wheel gesture is open"); + // straight to the grid, where the loupe (and its wheel handling) no longer draws + let r = h.request("ui.set", json!({"view": "photoGrid"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.session.interaction.is_none(), "the wheel gesture is committed, so no later edit joins it"); + let r = h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].size, 0.04, "and is one undo step"); +} From 3e97448c8279ad8b3eab97958f7987a4ad95afba Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:29:41 +0200 Subject: [PATCH 035/247] #2359: the wheel finds the spot under the pointer where it is now brush_wheel runs before remove_overlay, so it used the spot the overlay found under last frame's pointer: moving onto another spot (or off all of them) and turning the wheel in the same frame resized the old one. The overlay now keeps what of each spot can be grabbed, and brush_wheel hit-tests it at the current pointer, with the hit test both share. (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 48 +++++++++++++------------ crates/ui-egui/src/tests_spot_stroke.rs | 22 ++++++++++++ 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index f48ac97341..b2504f593c 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2680,12 +2680,17 @@ fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { let id = egui::Id::new("brush-wheel"); let now = ui.input(|i| i.time); - let hovered = ui.data(|d| d.get_temp::(egui::Id::new(HOVERED_SPOT))).filter(|_| right == RightPanel::Remove); + // the spot under the pointer now (last frame's outlines, this frame's pointer: it may have moved with the wheel) + let hovered = ui + .data(|d| d.get_temp::(egui::Id::new(SPOT_BODIES))) + .filter(|_| right == RightPanel::Remove) + .and_then(|b| spot_under(&b.bodies, b.active, resp.hover_pos()?)) + .map(|(index, ..)| index); let in_use = brush_in_use(app, right) && resp.hovered(); // one wheel gesture on a spot is one undo step: it ends after a pause, off that spot, or when the tool goes if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) { let pressed = ui.input(|i| i.pointer.any_down()); - if !in_use || pressed || hovered.map(|h| h.index) != Some(spot) || now - last > WHEEL_EDIT_PAUSE { + if !in_use || pressed || hovered != Some(spot) || now - last > WHEEL_EDIT_PAUSE { end_wheel_edit(app, ui.ctx()); } else { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); @@ -2717,7 +2722,7 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response ui.data_mut(|d| d.insert_temp(id, true)); let (k, df) = (1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); match hovered { - Some(HoveredSpot { index }) => { + Some(index) => { // the spot as it is now: the overlay saw it before this frame's edits let current = app.session.active().and_then(|p| app.session.develop_of(p)).and_then(|d| d.spots.get(index).map(|s| (s.size, s.feather))); @@ -2836,12 +2841,23 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, // ------------------------------------------------------------------------ remove -/// The Remove spot under the pointer as of the last frame. -#[derive(Clone, Copy, Debug, Default)] -struct HoveredSpot { - index: usize, +/// What of each Remove spot can be grabbed, as last drawn: `(spot, is source, screen points of +/// its stroke, radius)`, and the selected spot. `brush_wheel` finds the spot under the pointer in it. +#[derive(Clone, Debug, Default)] +struct SpotBodies { + bodies: Vec<(usize, bool, Vec, f32)>, + active: Option, +} +const SPOT_BODIES: &str = "remove-spot-bodies"; + +/// The target or source among `bodies` under `q` (its pin or anywhere along its stroke) as `(spot, is +/// source, distance)`: the selected spot's first, then the nearest. +fn spot_under(bodies: &[(usize, bool, Vec, f32)], active: Option, q: Pos2) -> Option<(usize, bool, f32)> { + bodies + .iter() + .filter_map(|(spot, source, pts, r)| Some((*spot, *source, spot_outline::grab_distance(pts, q, r.max(8.0))?))) + .min_by(|a, b| (Some(a.0) != active, a.2).partial_cmp(&(Some(b.0) != active, b.2)).unwrap_or(std::cmp::Ordering::Equal)) } -const HOVERED_SPOT: &str = "remove-hovered-spot"; /// The Remove tool on the photo: every spot's outline and pin (the selected one with its source), /// click a pin to select its spot, drag a target or source to move it, paint elsewhere to add one. @@ -2907,22 +2923,10 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo } let r = (app.ui.remove_size as f64 * long) as f32; let band = feather_band(app.ui.tool == "fill", r, app.ui.remove_feather); - // a target or source under `q` (its pin or anywhere along its stroke): the selected spot's first, then the nearest - let hit = |q: Pos2| { - bodies - .iter() - .filter_map(|(spot, source, pts, r)| Some((*spot, *source, spot_outline::grab_distance(pts, q, r.max(8.0))?))) - .min_by(|a, b| (Some(a.0) != active, a.2).partial_cmp(&(Some(b.0) != active, b.2)).unwrap_or(std::cmp::Ordering::Equal)) - }; + let hit = |q: Pos2| spot_under(&bodies, active, q); let hover = resp.hover_pos().and_then(hit); // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) - let hovered = hover.map(|(index, ..)| HoveredSpot { index }); - ui.data_mut(|m| { - m.remove_temp::(egui::Id::new(HOVERED_SPOT)); - if let Some(h) = hovered { - m.insert_temp(egui::Id::new(HOVERED_SPOT), h); - } - }); + ui.data_mut(|m| m.insert_temp(egui::Id::new(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active })); if let Some(h) = resp.hover_pos() { if hover.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index e2a9385c2b..236d42a739 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -209,3 +209,25 @@ fn leaving_the_loupe_ends_a_wheel_gesture() { assert_eq!(r["ok"], true, "{r}"); assert_eq!(spots(&h)[0].size, 0.04, "and is one undo step"); } + +#[test] +fn the_wheel_sizes_the_spot_the_pointer_has_just_moved_onto() { + let mut h = remove_tool(); + for x in [0.3, 0.7] { + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[x, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + } + pointer(&mut h, "move", 0.3, 0.5); + // in one frame the pointer moves onto the other spot and the wheel turns + let img = h.app.image_rect.expect("photo drawn"); + let to = egui::pos2(img.min.x + 0.7 * img.width(), img.min.y + 0.5 * img.height()); + h.events.push(egui::Event::PointerMoved(to)); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + let s = spots(&h); + assert_eq!(s[0].size, 0.04, "the spot the pointer left keeps its size"); + assert!((s[1].size / 0.04 - 1.1).abs() < 0.01, "the spot under the pointer grows, got {}", s[1].size); +} From c0573dbc758a3759f45ba81f0ced36dd291354f2 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:30:15 +0200 Subject: [PATCH 036/247] #2359: the wheel's hit test uses each spot's radius as it is now The overlay keeps what can be grabbed from the settings it drew with, from before the frame's wheel edit, so a pointer inside a just-grown spot but outside its old outline missed it and resized the brush instead. brush_wheel now takes each spot's radius from the session (grab_radius, as the overlay draws it). (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 24 ++++++++++++++++++---- crates/ui-egui/src/tests_spot_stroke.rs | 27 +++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index b2504f593c..5978a3c206 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2681,10 +2681,19 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response let id = egui::Id::new("brush-wheel"); let now = ui.input(|i| i.time); // the spot under the pointer now (last frame's outlines, this frame's pointer: it may have moved with the wheel) + // with each spot's radius as it is now: the wheel may have just resized it let hovered = ui .data(|d| d.get_temp::(egui::Id::new(SPOT_BODIES))) .filter(|_| right == RightPanel::Remove) - .and_then(|b| spot_under(&b.bodies, b.active, resp.hover_pos()?)) + .and_then(|mut b| { + let spots = app.session.active().and_then(|p| app.session.develop_of(p)).map(|d| d.spots.clone()).unwrap_or_default(); + for (spot, _, _, r) in &mut b.bodies { + if let Some(s) = spots.get(*spot) { + *r = grab_radius(s, b.long); + } + } + spot_under(&b.bodies, b.active, resp.hover_pos()?) + }) .map(|(index, ..)| index); let in_use = brush_in_use(app, right) && resp.hovered(); // one wheel gesture on a spot is one undo step: it ends after a pause, off that spot, or when the tool goes @@ -2842,11 +2851,18 @@ fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, // ------------------------------------------------------------------------ remove /// What of each Remove spot can be grabbed, as last drawn: `(spot, is source, screen points of -/// its stroke, radius)`, and the selected spot. `brush_wheel` finds the spot under the pointer in it. +/// its stroke, radius)`, the selected spot and the photo's long edge on screen (for [`grab_radius`]). +/// `brush_wheel` finds the spot under the pointer in it. #[derive(Clone, Debug, Default)] struct SpotBodies { bodies: Vec<(usize, bool, Vec, f32)>, active: Option, + long: f64, +} + +/// How far from its stroke a spot is drawn (its outline) and can be grabbed, on a photo whose long edge is `long` on screen. +fn grab_radius(s: &lightcraft_develop::Spot, long: f64) -> f32 { + feather_band(s.mode == SpotMode::Fill, (s.size * long) as f32, s.feather as f32).1 + OUTLINE_GAP } const SPOT_BODIES: &str = "remove-spot-bodies"; @@ -2887,7 +2903,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let clip = p.clip_rect(); for (i, s) in d.spots.iter().enumerate() { let band = feather_band(s.mode == SpotMode::Fill, (s.size * long) as f32, s.feather as f32); - let r = band.1 + OUTLINE_GAP; + let r = grab_radius(s, long); let sel = Some(i) == active; if !mode.shows(sel, live) { continue; @@ -2926,7 +2942,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let hit = |q: Pos2| spot_under(&bodies, active, q); let hover = resp.hover_pos().and_then(hit); // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) - ui.data_mut(|m| m.insert_temp(egui::Id::new(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active })); + ui.data_mut(|m| m.insert_temp(egui::Id::new(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active, long })); if let Some(h) = resp.hover_pos() { if hover.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index 236d42a739..a49d1c829b 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -231,3 +231,30 @@ fn the_wheel_sizes_the_spot_the_pointer_has_just_moved_onto() { assert_eq!(s[0].size, 0.04, "the spot the pointer left keeps its size"); assert!((s[1].size / 0.04 - 1.1).abs() < 0.01, "the spot under the pointer grows, got {}", s[1].size); } + +#[test] +fn a_spot_the_wheel_has_grown_is_grabbed_out_to_its_new_edge() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.5, 0.5]], "size": 0.02, "feather": 0.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.5, 0.5); + // grow it to twice its size, then, in the next frame, move to where only the grown spot reaches and turn on + for _ in 0..8 { + wheel(&mut h, 1.0, egui::Modifiers::NONE); + } + let grown = spots(&h)[0].size; + assert!(grown > 0.04, "{grown}"); + let img = h.app.image_rect.expect("photo drawn"); + let long = img.width().max(img.height()); + // between the outline drawn before the last notch and the grown one (3 pt outside the radius, no feather) + let between = (grown / 1.1 + grown) as f32 / 2.0 * long + 3.0; + let to = egui::pos2(img.center().x + between, img.center().y); + h.events.push(egui::Event::PointerMoved(to)); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!((spots(&h)[0].size / grown - 1.1).abs() < 0.01, "the grown spot is still under the pointer: {}", spots(&h)[0].size); + assert_eq!(h.app.session.active_spot, Some(0), "and stays selected (the brush isn't resized instead)"); +} From 17d055ed137c00954377b66ece31e889824e1056 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:24:35 +0200 Subject: [PATCH 037/247] #2359: releasing a middle-button pan adds no spot The Remove stroke ends on the release so it reaches where the pointer stopped, but a middle drag pans the photo (#2689's LR-VIEW-ZOOM): only the left button's release counts, so letting go of the wheel no longer drops a spot. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 5978a3c206..6dabb04b13 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2984,14 +2984,15 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo return; } if let Some(q) = resp.interact_pointer_pos() - && (resp.drag_started() || resp.dragged() || resp.clicked() || resp.drag_stopped()) + // the release ends the stroke where it is, but only the left button's: a middle drag pans + && (resp.drag_started() || resp.dragged() || resp.clicked() || resp.drag_stopped_by(egui::PointerButton::Primary)) { let n = map.norm(q); match &mut app.gesture { // a point every r/4 of movement; a held pointer stores nothing, and the release adds where it ended Some(Gesture::Spot { points }) => { let last = points.last().map(|l| map.screen(*l)); - if last.is_none_or(|l| spot_outline::adds_point(l, q, r, resp.drag_stopped())) { + if last.is_none_or(|l| spot_outline::adds_point(l, q, r, resp.drag_stopped_by(egui::PointerButton::Primary))) { points.push(n); } } From 6ea72d8b1313767b0bdee6a8fa0dccfd863e206d Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:50:32 +0100 Subject: [PATCH 038/247] LR-BEHAV-LOCALIZE: the intersect row's spoken label uses egui 0.37's Role Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/masking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index 6f075c02e4..04e5ff6a57 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -354,7 +354,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if matches!(c.op, lightcraft_develop::MaskOp::Intersect) { // the drawn ∩ has no text: the row still names its mode to screen readers let spoken = format!("{}: {text}", crate::i18n::tr("Intersect")); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, spoken.clone())); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, spoken.clone())); } register(ui, format!("component:{i}"), resp.rect); if resp.double_clicked() { From eae7dcd2069cdddf38a60a400f9ccbc083134a83 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:22:30 +1100 Subject: [PATCH 039/247] LRC-LIB-LIBFOLDERS: a date folder inside the library can be renamed folder.rename / folder.move refused any folder below the library folder (`src.starts_with(&l.dir)`), so the date folders an import copies into `Originals/` could never be renamed. Only the library folder, its parents and its own top-level folders (`Originals`, `thumbs`) are refused now. A refused Rename Folder prompt also closed silently; it now shows why in a toast, as Move Photos does. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/browse.rs | 4 +++- crates/engine/src/tests_folders.rs | 24 ++++++++++++++++++++++++ crates/ui-egui/src/panels/dialogs.rs | 3 ++- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 6f3f889631..eace5943ad 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -513,7 +513,9 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: if !src.is_dir() { return Err(format!("{from} is not a folder")); } - if s.library.as_ref().is_some_and(|l| l.dir.starts_with(src) || src.starts_with(&l.dir)) { + // the library folder itself, and its own top-level folders (`Originals`, `thumbs`), stay where + // the library expects them; folders below those (an import's date folders) can be renamed + if s.library.as_ref().is_some_and(|l| l.dir.starts_with(src) || src.parent() == Some(l.dir.as_path())) { return Err("the library's own folders can't be moved here".into()); } // Repairs retain their exact old paths, including those on surviving history entries. diff --git a/crates/engine/src/tests_folders.rs b/crates/engine/src/tests_folders.rs index 34017fc977..739ccecd91 100644 --- a/crates/engine/src/tests_folders.rs +++ b/crates/engine/src/tests_folders.rs @@ -16,6 +16,7 @@ use lightcraft_catalog::{Op, Photo, Source}; use serde_json::json; +use std::path::Path; use crate::{LibrarySource, Session, filter_chips}; @@ -701,3 +702,26 @@ fn a_destination_without_write_permission_reports_an_error_and_keeps_everything( } std::fs::set_permissions(dir.0.join("ro"), std::fs::Permissions::from_mode(0o755)).unwrap(); } + +#[test] +fn a_date_folder_inside_the_library_can_be_renamed_but_the_librarys_own_folders_cannot() { + let dir = Scratch::new("in-library"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + add(&mut s, &day.join("a.jpg").to_string_lossy()); + let day = day.to_string_lossy().to_string(); + s.execute("folder.rename", &json!({"path": day, "name": "Beach"})).unwrap(); + assert!(lib.join("Originals/Beach").is_dir(), "the imported date folder is renamed"); + assert!(!Path::new(&day).exists()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(Path::new(&day).is_dir(), "undo names it back"); + for own in ["Originals", "thumbs"] { + std::fs::create_dir_all(lib.join(own)).unwrap(); + let path = lib.join(own).to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": path, "name": "x"})).is_err(), "{own} stays put"); + } + assert!(s.execute("folder.rename", &json!({"path": lib.to_string_lossy(), "name": "x"})).is_err(), "and so does the library"); +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index f26b433255..925d482269 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -1581,7 +1581,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { } close = true; } - Err(e) if matches!(dlg, Dialog::MovePhotos { .. }) => { + // a prompt (Rename Folder, …) that is refused closes and says why + Err(e) if matches!(dlg, Dialog::MovePhotos { .. } | Dialog::TextPrompt { .. }) => { app.toast(ctx, e); close = true; } From 3da201b8c55ed65d8b0b47c840acc712924a379d Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Sat, 10 Oct 2026 17:09:37 +1100 Subject: [PATCH 040/247] perf(catalog): box Photo::embedded_lens (about 240 bytes less a photo record) The DNG warp/vignette coefficients sat inline in every photo record (248 bytes) though few photos have them; boxed, a 1M-photo catalog holds about 240 MB less in memory. The serialized form is unchanged (new round-trip test). (cherry picked from commit 681cb0e183e1c3256c085ae8505cccd0fc93f48a) Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 2 +- crates/catalog/src/model.rs | 2 +- crates/catalog/src/tests.rs | 17 ++++++++++++++++- crates/engine/src/cmd/convert.rs | 6 +++--- crates/engine/src/files.rs | 2 +- crates/engine/src/import.rs | 4 ++-- crates/engine/src/lib.rs | 2 +- crates/engine/src/media.rs | 4 ++-- crates/engine/src/slide.rs | 2 +- crates/engine/src/tests_constrain_crop.rs | 2 +- crates/engine/src/tests_merge.rs | 4 ++-- crates/ui-egui/examples/thumb_request_bench.rs | 2 +- crates/ui-egui/src/panels/compare.rs | 2 +- crates/ui-egui/src/panels/detail.rs | 6 +++--- crates/ui-egui/src/panels/slideshow.rs | 2 +- 15 files changed, 37 insertions(+), 22 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a697..06266d782d 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -928,7 +928,7 @@ impl Catalog { } Op::SetEmbeddedLens { id, lens } => { let p = self.photo_mut(id)?; - Op::SetEmbeddedLens { id, lens: std::mem::replace(&mut p.embedded_lens, lens.map(|l| *l)).map(Box::new) } + Op::SetEmbeddedLens { id, lens: std::mem::replace(&mut p.embedded_lens, lens) } } Op::SetAsShotWb { id, wb } => { if wb.is_some_and(|(t, tint)| !(t.is_finite() && tint.is_finite())) { diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index b405e1db96..f26cc71cf5 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -276,7 +276,7 @@ pub struct Photo { /// Lens corrections embedded in the file (DNG `WarpRectilinear` / `FixVignetteRadial`), applied when /// "Enable Profile Corrections" is on. #[serde(default, skip_serializing_if = "Option::is_none")] - pub embedded_lens: Option, + pub embedded_lens: Option>, /// A virtual copy: the photo it was copied from (it shares that photo's file but has its own /// settings, metadata and history). #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 579175086e..ba38bd4ec0 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -568,7 +568,7 @@ fn set_embedded_lens_is_undoable_and_journaled() { let op = Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens)) }; let op: Op = serde_json::from_str(&serde_json::to_string(&op).unwrap()).unwrap(); let inv = c.apply(op).unwrap(); - assert_eq!(c.photo(a).unwrap().embedded_lens, Some(lens)); + assert_eq!(c.photo(a).unwrap().embedded_lens, Some(Box::new(lens))); let inv: Op = serde_json::from_str(&serde_json::to_string(&inv).unwrap()).unwrap(); c.apply(inv).unwrap(); assert_eq!(c.photo(a).unwrap().embedded_lens, None); @@ -1046,3 +1046,18 @@ fn a_batch_that_cannot_be_rolled_back_whole_makes_earlier_changes_unknown() { assert_eq!(c.touched_since(start), None, "so nothing is said of what changed"); assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again"); } + +/// `Photo::embedded_lens` is boxed to keep photo records small; the box doesn't change the serialized form: +/// a photo written with the lens reads back with it, and its JSON is the bare lens, as before the box. +#[test] +fn boxed_embedded_lens_serializes_like_the_bare_lens() { + let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default() }; + let mut p = Photo::new(PhotoId(1), Source::File { path: "/x.dng".into() }, "x.dng", "DNG", 4000, 3000, "2026-10-06T00:00:00"); + p.embedded_lens = Some(Box::new(lens)); + let json = serde_json::to_value(&p).unwrap(); + assert_eq!(json["embedded_lens"], serde_json::to_value(lens).unwrap()); + let back: Photo = serde_json::from_value(json).unwrap(); + assert_eq!(back.embedded_lens.as_deref(), Some(&lens)); + p.embedded_lens = None; + assert!(serde_json::to_value(&p).unwrap().get("embedded_lens").is_none(), "no lens, no field"); +} diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 0871e43528..bf9fa50c65 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -260,7 +260,7 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P /// what import gave it, the lens correction is turned on as import would; an edited photo keeps /// its settings. pub(crate) fn lens_ops(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Vec { - if info.embedded_lens == ph.embedded_lens { + if info.embedded_lens.as_ref() == ph.embedded_lens.as_deref() { return Vec::new(); } let mut ops = vec![Op::SetEmbeddedLens { id, lens: info.embedded_lens.map(Box::new) }]; @@ -486,7 +486,7 @@ mod tests { c.apply(op).unwrap(); } let after = c.photo(lightcraft_catalog::PhotoId(1)).unwrap(); - assert_eq!(after.embedded_lens, Some(lens())); + assert_eq!(after.embedded_lens, Some(Box::new(lens()))); assert!(!after.is_edited()); assert_eq!(*after.develop, after.camera_defaults()); assert!(lens_ops(after.id, after, &info).is_empty(), "nothing more to do the second time"); @@ -507,7 +507,7 @@ mod tests { #[test] fn reload_leaves_a_photo_whose_user_switched_the_correction_off_alone() { let mut ph = old_rw2(); - ph.embedded_lens = Some(lens()); + ph.embedded_lens = Some(Box::new(lens())); let mut d = ph.camera_defaults(); d.optics.lens_profile = false; ph.develop = std::sync::Arc::new(d); diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 82d4c57d60..b0a955b329 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -2881,7 +2881,7 @@ pub(crate) mod tests { let name = format!("x.{format}"); let mut p = Photo::new(PhotoId(1), Source::File { path: format!("/{name}") }, &name, format, 64, 48, ""); p.kind = MediaKind::Raw; - p.embedded_lens = embedded; + p.embedded_lens = embedded.map(Box::new); crate::import::apply_import_defaults(&s, &mut p); assert_eq!(p.develop.optics.lens_profile, embedded.is_some(), "{format} {embedded:?}"); } diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index bb81bd2407..20f350d3c8 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1470,7 +1470,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.meta = info.meta; p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; - p.embedded_lens = info.embedded_lens; + p.embedded_lens = info.embedded_lens.map(Box::new); p.set_preview_only(info.preview_only.clone()); apply_import_defaults(s, &mut p); if let Some(sc) = &sidecar { @@ -1593,7 +1593,7 @@ impl Session { p.kind = c.kind; if let Some(info) = self.import_probes.get(&c.path) { p.as_shot_wb = info.as_shot_wb; - p.embedded_lens = info.embedded_lens; + p.embedded_lens = info.embedded_lens.map(Box::new); p.preview_only = info.preview_only.clone(); } p.develop = std::sync::Arc::new(p.import_defaults()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ff2b972c0a..e9d66c1c0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -960,7 +960,7 @@ impl Session { photo.height.max(1) as usize, &d, true, - photo.embedded_lens.as_ref(), + photo.embedded_lens.as_deref(), ); d.crop.geometry.rect = frame.crop.rect; d diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index e76ef81691..dc101ae52c 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1238,7 +1238,7 @@ fn header_info(p: &Photo) -> SourceInfo { raw: true, as_shot_temp: temp, as_shot_tint: tint, - lens: p.embedded_lens, + lens: p.embedded_lens.as_deref().copied(), relative_wb: relative, // (a fitted-look raw edited in Kelvin: its camera's matrices give the scale, see `files::WbScaleOf`) legacy_relative_wb: p.fitted_look() && !relative, @@ -1525,7 +1525,7 @@ impl crate::Session { p.height.max(1) as usize, &job.settings, apply_crop, - p.embedded_lens.as_ref(), + p.embedded_lens.as_deref(), ); let ppl = frame.px_per_long(full_w); lightcraft_pipeline::spots::window_for_reads_checked(&job.settings, &frame, full_w, full_h, ppl, window.clamped(full_w, full_h))?; diff --git a/crates/engine/src/slide.rs b/crates/engine/src/slide.rs index 009a2e2ac3..4ddf6cca6e 100644 --- a/crates/engine/src/slide.rs +++ b/crates/engine/src/slide.rs @@ -87,7 +87,7 @@ impl crate::Session { p.height.max(1) as usize, &p.develop, true, - p.embedded_lens.as_ref(), + p.embedded_lens.as_deref(), ); let a = frame.aspect(); Some(if a.is_finite() && a > 0.0 { a } else { 1.5 }) diff --git a/crates/engine/src/tests_constrain_crop.rs b/crates/engine/src/tests_constrain_crop.rs index 9f01ed05d6..a07ad2fea7 100644 --- a/crates/engine/src/tests_constrain_crop.rs +++ b/crates/engine/src/tests_constrain_crop.rs @@ -17,7 +17,7 @@ fn fits(s: &Session) -> bool { let p = s.catalog.photo(s.active().unwrap()).unwrap(); let mut d = (*p.develop).clone(); d.geometry.constrain_crop = true; - let f = Frame::with_lens(p.width as usize, p.height as usize, &d, true, p.embedded_lens.as_ref()); + let f = Frame::with_lens(p.width as usize, p.height as usize, &d, true, p.embedded_lens.as_deref()); let (a, b) = (f.crop.rect, p.develop.crop.geometry.rect); [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-9) } diff --git a/crates/engine/src/tests_merge.rs b/crates/engine/src/tests_merge.rs index ed524ae3d2..432ad14ca1 100644 --- a/crates/engine/src/tests_merge.rs +++ b/crates/engine/src/tests_merge.rs @@ -100,8 +100,8 @@ fn hdr_merge_keeps_the_reference_frames_lens_corrections() { let reference = s.catalog.photo(lightcraft_catalog::PhotoId(ids[1])).unwrap().clone(); let expect = if orientation == Orientation::Normal { (452, 304) } else { (304, 452) }; assert_eq!(((merged.width, merged.height), (reference.width, reference.height)), (expect, expect)); - let a = reference.embedded_lens.expect("the source's correction"); - let b = merged.embedded_lens.expect("the merged DNG carries the reference frame's correction"); + let a = reference.embedded_lens.as_deref().copied().expect("the source's correction"); + let b = merged.embedded_lens.as_deref().copied().expect("the merged DNG carries the reference frame's correction"); let (wa, wb) = (a.warp.unwrap(), b.warp.unwrap()); let (va, vb) = (a.vignette.unwrap(), b.vignette.unwrap()); let (w, h) = (expect.0 as f64, expect.1 as f64); diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 166c0e9b62..d02b6501f3 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -195,7 +195,7 @@ fn real() { p.kind = probe.kind; p.meta = probe.meta; p.as_shot_wb = probe.as_shot_wb; - p.embedded_lens = probe.embedded_lens; + p.embedded_lens = probe.embedded_lens.map(Box::new); p.content_hash = probe.content_hash; p.preview_only = probe.preview_only; lightcraft_engine::import::apply_import_defaults(&session, &mut p); diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 829500da47..5c7644eb0a 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -212,7 +212,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo photo.height.max(1) as usize, &photo.develop, true, - photo.embedded_lens.as_ref(), + photo.embedded_lens.as_deref(), ); let aspect = frame.aspect() as f32; let native = super::detail::output_px(&frame); diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 5e610b098d..4f8fb66769 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -296,7 +296,7 @@ pub(crate) fn output_px(frame: &Frame) -> [usize; 2] { pub(crate) fn focus_box(photo: &lightcraft_catalog::Photo) -> Option { let f = photo.meta.focus.as_ref()?; let d = &photo.develop; - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, d, true, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, d, true, photo.embedded_lens.as_deref()); let [w, h] = output_px(&frame); let to_out = frame.out_to_norm(w, h).inverse()?; // stored on the upright photo: the user's Rotate / Flip on top, then the crop @@ -527,7 +527,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the full-screen preview shows the photo only: no tool overlays let right = if fullscreen { RightPanel::None } else { app.ui.right }; let crop_tool = right == RightPanel::Crop; - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &d, !crop_tool, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &d, !crop_tool, photo.embedded_lens.as_deref()); let aspect = frame.aspect() as f32; let ppp = ui.ctx().pixels_per_point(); let area = canvas.shrink(if fullscreen { @@ -701,7 +701,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { for (n, nid) in [next, prev].into_iter().enumerate() { let Some(nid) = nid else { continue }; let Some(np) = app.session.catalog.photo(nid).cloned() else { continue }; - let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, !crop_tool, np.embedded_lens.as_ref()); + let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, !crop_tool, np.embedded_lens.as_deref()); let na = nf.aspect() as f32; let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); let nw = diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index cfe0ce6e68..43b01c4503 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -194,7 +194,7 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { /// [`SlideSettings::is_plain`]: lightcraft_engine::slide::SlideSettings::is_plain fn slide_job(app: &mut LightcraftApp, id: PhotoId, area: Rect, ppp: f32, texture_side: usize) -> Option { let photo = app.session.catalog.photo(id)?.clone(); - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &photo.develop, true, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &photo.develop, true, photo.embedded_lens.as_deref()); let native = super::detail::output_px(&frame); if !app.session.slides_plain() { let (w, h) = slide_px(area, ppp, texture_side); From 90b3e0489b3684fdda3636ef2a91e4ba8fdda0fb Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:43:37 +1100 Subject: [PATCH 041/247] LRC-LIB-LIBFOLDERS: a folder path with '..' is refused before the library check Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/browse.rs | 4 ++++ crates/engine/src/tests_folders.rs | 3 +++ 2 files changed, 7 insertions(+) diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index eace5943ad..83478cbdb1 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -513,6 +513,10 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: if !src.is_dir() { return Err(format!("{from} is not a folder")); } + // `a/../b` names a folder without spelling it, which the checks below and the relink can't see + if src.components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return Err(format!("{from}: give the folder's path without '..'")); + } // the library folder itself, and its own top-level folders (`Originals`, `thumbs`), stay where // the library expects them; folders below those (an import's date folders) can be renamed if s.library.as_ref().is_some_and(|l| l.dir.starts_with(src) || src.parent() == Some(l.dir.as_path())) { diff --git a/crates/engine/src/tests_folders.rs b/crates/engine/src/tests_folders.rs index 739ccecd91..f2269443be 100644 --- a/crates/engine/src/tests_folders.rs +++ b/crates/engine/src/tests_folders.rs @@ -724,4 +724,7 @@ fn a_date_folder_inside_the_library_can_be_renamed_but_the_librarys_own_folders_ assert!(s.execute("folder.rename", &json!({"path": path, "name": "x"})).is_err(), "{own} stays put"); } assert!(s.execute("folder.rename", &json!({"path": lib.to_string_lossy(), "name": "x"})).is_err(), "and so does the library"); + let alias = lib.join("Originals").join("..").join("Originals").to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": alias, "name": "x"})).is_err(), "even named through '..'"); + assert!(lib.join("Originals").is_dir()); } From 4da22ff0c40f06b71706d033e1d18409bf5f8df8 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:46:41 +0100 Subject: [PATCH 042/247] #2359: the brush's wheel code and tests follow egui 0.37 egui 0.37 deprecates `Id::new`; the brush-wheel, brush-resize, wheel-edit and spot-body ids are global, so they move to `Id::unique` as the rest of the loupe already does. The wheel tests' synthetic `MouseWheel` events name their `source`, now a required field. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 18 +++++++++--------- crates/ui-egui/src/tests_spot_stroke.rs | 9 ++++++++- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 6dabb04b13..a1b045ae30 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -2678,12 +2678,12 @@ fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { /// As in Lightroom, a smooth-scrolling mouse and a two-finger trackpad swipe do the same (a line's /// worth of points a notch) instead of zooming or panning; pinch and ⌘-wheel still zoom. fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { - let id = egui::Id::new("brush-wheel"); + let id = egui::Id::unique("brush-wheel"); let now = ui.input(|i| i.time); // the spot under the pointer now (last frame's outlines, this frame's pointer: it may have moved with the wheel) // with each spot's radius as it is now: the wheel may have just resized it let hovered = ui - .data(|d| d.get_temp::(egui::Id::new(SPOT_BODIES))) + .data(|d| d.get_temp::(egui::Id::unique(SPOT_BODIES))) .filter(|_| right == RightPanel::Remove) .and_then(|mut b| { let spots = app.session.active().and_then(|p| app.session.develop_of(p)).map(|d| d.spots.clone()).unwrap_or_default(); @@ -2697,7 +2697,7 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response .map(|(index, ..)| index); let in_use = brush_in_use(app, right) && resp.hovered(); // one wheel gesture on a spot is one undo step: it ends after a pause, off that spot, or when the tool goes - if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) { + if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))) { let pressed = ui.input(|i| i.pointer.any_down()); if !in_use || pressed || hovered != Some(spot) || now - last > WHEEL_EDIT_PAUSE { end_wheel_edit(app, ui.ctx()); @@ -2739,10 +2739,10 @@ fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response if app.session.active_spot != Some(index) { let _ = app.run("spot.select", json!({"index": index})); } - if ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_none() { + if ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))).is_none() { let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); } - ui.data_mut(|d| d.insert_temp(egui::Id::new(WHEEL_EDIT), (index, now))); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(WHEEL_EDIT), (index, now))); ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); let mut p = json!({"index": index}); if k != 1.0 { @@ -2775,7 +2775,7 @@ const WHEEL_EDIT_PAUSE: f64 = 0.5; /// Commits a wheel gesture's spot edits as one undo step. fn end_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { - if ctx.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { + if ctx.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { let _ = app.run("develop.endInteraction", json!({})); } } @@ -2783,7 +2783,7 @@ fn end_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { /// Every frame, whatever is drawn: ends a wheel gesture whose loupe is gone (another view, another /// tool), which `brush_wheel` no longer runs to end, or that has paused, so no later edit joins it. pub(crate) fn settle_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { - let Some((_, last)) = ctx.data(|d| d.get_temp::<(usize, f64)>(egui::Id::new(WHEEL_EDIT))) else { return }; + let Some((_, last)) = ctx.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))) else { return }; let drawn = app.ui.view == ViewMode::Detail && app.ui.right == RightPanel::Remove && !app.ui.fullscreen; if !drawn || ctx.input(|i| i.time) - last > WHEEL_EDIT_PAUSE { end_wheel_edit(app, ctx); @@ -2801,7 +2801,7 @@ fn deselect_spot(app: &mut LightcraftApp, right: RightPanel) { /// Photoshop does: across for the size, up and down for the feather (down: softer), shown on the /// circle where the drag started. True while it owns the pointer (nothing is painted). fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel, map: &CanvasMap) -> bool { - let id = egui::Id::new("brush-resize"); + let id = egui::Id::unique("brush-resize"); if !brush_in_use(app, right) { ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); return false; @@ -2942,7 +2942,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let hit = |q: Pos2| spot_under(&bodies, active, q); let hover = resp.hover_pos().and_then(hit); // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) - ui.data_mut(|m| m.insert_temp(egui::Id::new(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active, long })); + ui.data_mut(|m| m.insert_temp(egui::Id::unique(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active, long })); if let Some(h) = resp.hover_pos() { if hover.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); diff --git a/crates/ui-egui/src/tests_spot_stroke.rs b/crates/ui-egui/src/tests_spot_stroke.rs index a49d1c829b..c331697fac 100644 --- a/crates/ui-egui/src/tests_spot_stroke.rs +++ b/crates/ui-egui/src/tests_spot_stroke.rs @@ -89,7 +89,13 @@ fn a_stroke_is_grabbed_anywhere_along_it() { } fn wheel(h: &mut Headless, dy: f32, modifiers: egui::Modifiers) { - h.events.push(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers }); + h.events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, dy), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers, + }); h.step(); } @@ -124,6 +130,7 @@ fn a_smooth_scrolling_mouse_sizes_the_brush_too() { unit: egui::MouseWheelUnit::Point, delta: egui::vec2(0.0, y), phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, modifiers, }); h.step(); From 031ba0375c25d1bd5a4684f8588d8f85550b7fc8 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:29:23 -0400 Subject: [PATCH 043/247] LR-PROF-CAMERACOLOR: negative channels bump the render cache; What's New entry dated 2026-10-26 --- crates/engine/src/media.rs | 2 +- docs/whats-new.md | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index e76ef81691..abdb058928 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 70; +pub const RENDER_CACHE_VERSION: u64 = 71; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/docs/whats-new.md b/docs/whats-new.md index b1e141ec8c..5bac5c14d4 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,15 @@ # What's new in LightCraft +## 2026-10-26 + +### Pushed shadows of raws no longer turn magenta +- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour + matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas + pushed up came out purple or magenta, most visibly with saturating camera profiles. In the fitted view, thumbnails + and other views smaller than the photo, where neighbouring pixels are averaged first, pushed shadows now keep their + real colour (a lens-cap frame pushed 4 EV rendered magenta; it is now black), and cached thumbnails are rendered + again. At 100% and in full-size exports white balance still clips each channel before noise reduction (#840). + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock @@ -279,12 +289,6 @@ ## 2026-10-16 -### Pushed shadows of raws no longer turn magenta -- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour - matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas - pushed up came out purple or magenta (a lens-cap frame pushed 4 EV rendered magenta; it is now black). Shadows - pushed with Exposure or Shadows keep their real colour, most visibly with saturating camera profiles. - ### Synchronize Folder shows that it is listing the folder - A folder with tens of thousands of photos, above all on a network share, can take minutes to list before Synchronize Folder checks a single photo. Its row in the activity stack used to sit at "0 of 64085" with an empty From d10a9af00b5b8a87a70c1d7e123295e68ee168ce Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 16 Oct 2026 08:25:22 -0400 Subject: [PATCH 044/247] LR-LIB-SMARTALBUM: creating or giving a keyword no longer freezes the window while albums are counted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In a large library with smart albums, the frame after an edit the album tally could not follow photo by photo counted every smart album over every photo on the UI thread: seconds, during which the window froze. Creating a keyword inside another one (and giving it to the selected photos) was such an edit, because Op::SetKeyword was classed as a broad op, so the view, the folder tree and the date groups were worked out again too. - The keyword list changes no photo and no rule, filter or sort reads it: Op::SetKeyword now records Aspects::KEYWORD_LIST instead of marking the catalog's change memory broad. The view and the albums' counts follow the edit from the photos it touched; only the keyword tree is made again. - A count of every photo that is still needed (an album's rules or photos changed, an edit to more than 256 photos, a new minute with an "in the last…" rule, a library opened) runs on a worker thread over a copy of the catalog. The sidebar keeps the counts it showed (none before the first count, and none of another library) and follows the edits made meanwhile once the count is in. AlbumTally::update only follows now; the caller decides where to count whole. Co-Authored-By: Claude --- crates/catalog/src/lib.rs | 21 +- crates/catalog/src/tally.rs | 19 +- crates/catalog/src/tests.rs | 6 + crates/engine/src/tests/view_follow.rs | 38 +++- crates/ui-egui/src/caches.rs | 242 ++++++++++++++++++++--- crates/ui-egui/src/headless.rs | 5 +- crates/ui-egui/src/lib.rs | 11 +- crates/ui-egui/src/panels/left/albums.rs | 6 +- docs/parity-checklist.md | 2 +- 9 files changed, 292 insertions(+), 58 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a697..3225284c5f 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -316,6 +316,9 @@ impl Aspects { pub const ANALYSIS: Aspects = Aspects(1 << 7); /// Whether it is in the library at all: added, removed, deleted, restored, taken in from Local. pub const PRESENCE: Aspects = Aspects(1 << 8); + /// The keyword list (keywords on their own and their attributes): of no photo, and read by no rule, filter or + /// sort, only by what lists keywords (the keyword tree, export names). + pub const KEYWORD_LIST: Aspects = Aspects(1 << 9); /// Everything: the photo may count differently for any tally. pub const ALL: Aspects = Aspects(u16::MAX); @@ -340,9 +343,11 @@ struct Changes { touched: std::collections::VecDeque<(u64, PhotoId, Aspects)>, /// What the op being applied changes of its photo. now: Aspects, - /// The latest revision made by an op that changed more than photos of its own (an album, a stack, a keyword of - /// the list…): what it changed for which photos is not known. + /// The latest revision made by an op that changed more than photos of its own (an album, a stack…): what it + /// changed for which photos is not known. broad: u64, + /// The latest revision made by an op that changed the keyword list ([`Aspects::KEYWORD_LIST`]). + keyword_list: u64, /// Changes up to this revision are no longer all in `touched`. floor: u64, /// The revision the last op recorded here made. When the catalog's revision is another, it was set from @@ -589,7 +594,8 @@ impl Catalog { if !self.remembers(revision) { return None; } - Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a))) + let photos = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a)); + Some(if self.changes.keyword_list > revision { photos.with(Aspects::KEYWORD_LIST) } else { photos }) } /// Whether every change since the catalog was at `revision` is remembered photo by photo. @@ -653,9 +659,9 @@ impl Catalog { } fn apply_inner(&mut self, op: Op) -> Result { - // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind - // can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's - // name. Listed kind by kind, so a new one has to be put on one side. + // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Most other kinds + // can change what any photo matches or where it sorts: an album's photos or rules, a stack. The keyword + // list changes only lists of keywords. Listed kind by kind, so a new one has to be put on one side. match &op { // (a photo that comes, goes, or changes what it is to the library counts for every tally; so do the // rare kinds whose reach nobody has to think about) @@ -695,8 +701,9 @@ impl Catalog { | Op::SetStack { .. } | Op::SetLabelName { .. } | Op::SetBrowsed { .. } - | Op::SetKeyword { .. } | Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1), + // (no photo matches, counts or sorts by it: only lists of keywords change) + Op::SetKeyword { .. } => self.changes.keyword_list = self.revision.saturating_add(1), } Ok(match op { Op::AddPhoto { photo } => { diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index e8fdc61979..c6cfef295a 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -3,8 +3,8 @@ //! A smart album's count asks every photo whether its rules hold. Asked again after every edit, that is a pass over //! the library for each smart album each time a keyword is given. [`AlbumTally`] remembers which photos each smart //! album holds, and after a small edit asks only the photos the edit touched ([`Catalog::touched_since`]). An op -//! that changes more than photos of its own (an album's rules or photos, a stack, the keyword list) has it counted -//! whole again, as before. +//! that changes more than photos of its own (an album's rules or photos, a stack) has to be counted whole again +//! ([`AlbumTally::of`]): the caller decides where (the app does it off the UI thread). use std::collections::{HashMap, HashSet}; @@ -168,27 +168,24 @@ impl AlbumTally { self.revision } - /// Bring the counts up to `cat` as it is now. `true` when that was done from the photos the ops since touched - /// (or nothing had changed), `false` when every photo was asked again. + /// Bring the counts up to `cat` as it is now from the photos the ops since touched. `true` when that was done (or + /// nothing had changed); `false` when it can't be, and every photo has to be asked again ([`AlbumTally::of`]): + /// the counts are then left as they were. /// /// `cat` has to be the catalog the counts were made of, further along. Another catalog is told apart only by - /// its revisions: a library that is loaded takes a range of its own (and then everything is counted again), but - /// two catalogs both counting from 0 look like one. + /// its revisions: a library that is loaded takes a range of its own (and then nothing is followed), but two + /// catalogs both counting from 0 look like one. pub fn update(&mut self, cat: &Catalog) -> bool { if self.revision == cat.revision { return true; } - let followed = match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { + match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { (Some(touched), Some(changed)) if touched.len() <= MAX_FOLLOWED => { self.follow(cat, &touched, changed); true } _ => false, - }; - if !followed { - *self = AlbumTally::of(cat); } - followed } /// The counts after ops that touched only `touched`: each smart album asks those photos again; an album of diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index bf67b24958..fa71eb69be 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -960,6 +960,12 @@ fn history_handles_loaded_revisions_failed_batches_and_retention() { let before = c.revision; c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap(); assert_eq!(c.touched_since(before), None); + // the keyword list changes no photo: what was touched stays known, and the list is said to have changed + let before = c.revision; + c.apply(Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }).unwrap(); + assert_eq!(c.touched_since(before), Some(vec![])); + assert_eq!(c.aspects_since(before), Some(Aspects::KEYWORD_LIST)); + assert_eq!(c.aspects_since(c.revision), Some(Aspects::NONE), "and from after it, not"); // more ops than are remembered: the oldest are answered with "anything" let long_ago = c.revision; for i in 0..9000u32 { diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index bc47d94c94..88e365d554 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -360,6 +360,35 @@ fn an_edit_to_many_photos_or_to_more_than_photos_is_worked_out_whole() { assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 2)); } +/// A keyword created in the keyword list, inside another and given to the selected photo at once, changes no photo +/// but that one: the view and the albums' counts follow it from that photo instead of asking every photo again. +#[test] +fn a_keyword_created_inside_another_and_given_to_a_photo_is_followed_from_that_photo() { + use lightcraft_catalog::{AlbumId, tally::AlbumTally}; + let (mut s, ids, _, smart) = library(600); + let _ = s.visible_cloned(); + let mut tally = AlbumTally::of(&s.catalog); + let (followed, whole) = (s.view_followed, s.view_worked_out); + // (the second photo has no keywords: it is in the smart album of those) + let bare = ids[1]; + assert!(s.catalog.photo(bare).is_some_and(|p| p.meta.keywords.is_empty())); + let unkeyworded = tally.counts()[&AlbumId(smart)]; + s.execute("library.select", &json!({"ids": [bare.0]})).unwrap(); + s.execute("keyword.create", &json!({"name": "Rome", "parent": "travel", "addToSelected": true})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole), "followed, not worked out whole"); + assert!(tally.update(&s.catalog), "the counts followed"); + assert_eq!(tally.counts()[&AlbumId(smart)], unkeyworded - 1, "the photo has a keyword now"); + // a keyword created on its own, for no photo: nothing else to follow + s.execute("keyword.create", &json!({"name": "Paris", "parent": "travel"})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 2, whole)); + assert!(tally.update(&s.catalog)); + // and what was followed is what every photo says + assert_eq!(s.visible_cloned(), s.visible_in_full()); + assert_eq!(tally.counts()[&AlbumId(smart)], s.catalog.album_count(AlbumId(smart))); +} + #[test] fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo() { use lightcraft_catalog::tally::AlbumTally; @@ -402,7 +431,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let moved = tally.revision() != s.catalog.revision; match (moved, tally.update(&s.catalog)) { (true, true) => followed += 1, - (true, false) => whole += 1, + (true, false) => { + tally = AlbumTally::of(&s.catalog); + whole += 1; + } // (an edit that was refused changed nothing: nothing to follow) (false, _) => {} } @@ -428,8 +460,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let many: Vec = if many.len() >= 300 { many } else { s.visible_cloned().iter().take(300).map(|id| id.0).collect() }; if many.len() > 256 { s.execute("library.select", &json!({"ids": many})).unwrap(); + let before = shown(&tally); s.execute("photo.rate", &json!({"rating": 5})).unwrap(); assert!(!tally.update(&s.catalog), "more photos than are followed one by one"); - assert_eq!(shown(&tally), fresh(&s)); + assert_eq!(shown(&tally), before, "not followed: left as they were, to be counted again"); + assert_eq!(shown(&AlbumTally::of(&s.catalog)), fresh(&s)); } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 93fe551847..13ab8031dd 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -8,6 +8,31 @@ pub struct LibraryCounts { pub deleted: usize, } +/// The albums' counts as the sidebar shows them ([`Caches::album_counts`]). +pub(crate) struct AlbumCounts { + /// The library they are of ([`lightcraft_engine::Session::library_generation`]). + library: u64, + /// The minute they are of while a smart album asks about "the last N days" (else empty). + minute: String, + /// What follows edits to a photo or a few. + tally: lightcraft_catalog::tally::AlbumTally, + /// The counts as the panels take them. + shown: std::sync::Arc>, +} + +/// A count of every photo on a worker thread ([`Caches::album_counts`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) struct AlbumRecount { + /// The library, minute and catalog revision it counts. + library: u64, + minute: String, + revision: u64, + /// The count, sent before the repaint is asked for, so the frame it wakes finds it. + done: std::sync::mpsc::Receiver>, + /// The thread, until it has let go of its copy of the catalog. + worker: std::thread::JoinHandle<()>, +} + /// The values the filter bar's pickers offer. #[derive(Clone, Debug, Default)] pub struct FilterValues { @@ -42,6 +67,9 @@ const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRE const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); +/// The keyword tree: the keywords photos carry, and the keyword list's own. +const READS_KEYWORDS: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::KEYWORD_LIST); + const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); @@ -62,7 +90,7 @@ impl Caches { } /// The library's keyword tree. pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); + let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_KEYWORDS)).map(|(_, t)| t); let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); self.keyword_tree = Some((cat.revision, t.clone())); t @@ -327,22 +355,32 @@ impl Caches { v } + /// How many photos each album of the library `library` ([`lightcraft_engine::Session::library_generation`]) + /// shows, `now` being the session clock ("in the last…" rules count back from it). + /// + /// An edit to a photo or a few is followed at once: a smart album asks only those photos again (a keyword + /// created and given to them too: the keyword list itself counts in no album). Anything more (an album's rules + /// or photos changed, a stack, an edit to many photos such as a keyword renamed across them, a new minute while + /// a smart album asks about "the last N days", another library) counts every photo again, seconds in a large + /// library. That count runs on a worker thread (natively) while the counts shown before stay (none the first + /// time, and none of another library); `ctx` repaints when it is done, and edits made meanwhile are followed + /// from it. pub fn album_counts( &mut self, cat: &lightcraft_catalog::Catalog, + library: u64, now: &str, + ctx: &egui::Context, ) -> std::sync::Arc> { let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - // the counts of this minute, if there are any: an edit to a photo or a few is followed from them, a smart - // album asking only those photos again; anything more, or a new minute, is counted from every photo - let kept = self.album_counts.take().filter(|(of, _, _)| of == minute); - if let Some((_, tally, shown)) = &kept - && tally.revision() == cat.revision - { - let shown = shown.clone(); - self.album_counts = kept; - return shown; + self.collect_album_recount(library); + // (album ids start again in every library: another one's counts would be shown on this one's albums) + if self.album_counts.as_ref().is_some_and(|c| c.library != library) { + self.album_counts = None; + } + if let Some(counts) = self.album_counts.as_ref().filter(|c| c.minute == minute && c.tally.revision() == cat.revision) { + return counts.shown.clone(); } if relative { // "in the last N days" counts back from the session clock, as in the grid. (Within a minute an edit asks @@ -350,21 +388,87 @@ impl Caches { // far out as the counts already were between edits, and the next minute counts them all again.) lightcraft_catalog::rules::set_now(Some(now.to_string())); } - let tally = match kept { - Some((_, mut tally, _)) => { - if !tally.update(cat) { - self.album_count_scans += 1; + if let Some(counts) = self.album_counts.as_mut().filter(|c| c.minute == minute) + && counts.tally.update(cat) + { + counts.shown = std::sync::Arc::new(counts.tally.counts().clone()); + return counts.shown.clone(); + } + self.recount_albums(cat, library, minute, now, relative, ctx); + self.album_counts.as_ref().map(|c| c.shown.clone()).unwrap_or_default() + } + + /// A count of every photo is running ([`Caches::album_counts`]). + pub fn album_recount_running(&self) -> bool { + self.album_recount.as_ref().is_some_and(|job| !job.worker.is_finished()) + } + + /// Count every photo for [`Caches::album_counts`]: on a worker thread when one can be started, else here. + fn recount_albums(&mut self, cat: &lightcraft_catalog::Catalog, library: u64, minute: &str, now: &str, relative: bool, ctx: &egui::Context) { + // one at a time: what it finds is followed up to the catalog as it is by then, or counted again + let failed = self.album_recount_failed.as_ref().is_some_and(|(l, r, m)| *l == library && *r == cat.revision && m == minute); + if self.album_recount.is_some() || failed { + return; + } + self.album_count_scans += 1; + #[cfg(not(target_arch = "wasm32"))] + { + // (cheap: the copy shares the photos) + let (copy, ctx, now) = (cat.clone(), ctx.clone(), relative.then(|| now.to_string())); + let (tx, done) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("lc-album-counts".into()).spawn(move || { + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || { + lightcraft_catalog::rules::set_now(now); + lightcraft_catalog::tally::AlbumTally::of(©) + }); + let _ = tx.send(counted); + ctx.request_repaint(); + }); + match spawned { + Ok(worker) => { + self.album_recount = Some(AlbumRecount { library, minute: minute.to_string(), revision: cat.revision, done, worker }); + return; } - tally + Err(e) => log::warn!("album counts: can't start a thread ({e}); counting them here"), } - None => { - self.album_count_scans += 1; - lightcraft_catalog::tally::AlbumTally::of(cat) + } + #[cfg(target_arch = "wasm32")] + let _ = (now, relative, ctx); + // (`album_counts` has set the clock on this thread) + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || lightcraft_catalog::tally::AlbumTally::of(cat)); + self.finish_album_recount(library, cat.revision, minute.to_string(), counted); + } + + /// Take the worker's count once it is done; a count of another library is let go (its thread ends on its own). + fn collect_album_recount(&mut self, library: u64) { + let Some(job) = &self.album_recount else { return }; + if job.library != library { + self.album_recount = None; + return; + } + let counted = match job.done.try_recv() { + Ok(counted) => counted, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + log::error!("album counts: the count stopped without an answer"); + Err("stopped without an answer".to_string()) } }; - let shown = std::sync::Arc::new(tally.counts().clone()); - self.album_counts = Some((minute.to_string(), tally, shown.clone())); - shown + let Some(job) = self.album_recount.take() else { return }; + self.finish_album_recount(job.library, job.revision, job.minute, counted); + } + + /// The counts a count of every photo made are the ones shown. One that failed (already logged) leaves those + /// shown before, and isn't tried again for the same library, catalog and minute. + fn finish_album_recount(&mut self, library: u64, revision: u64, minute: String, counted: Result) { + match counted { + Ok(tally) => { + self.album_recount_failed = None; + let shown = std::sync::Arc::new(tally.counts().clone()); + self.album_counts = Some(AlbumCounts { library, minute, tally, shown }); + } + Err(_) => self.album_recount_failed = Some((library, revision, minute)), + } } } @@ -386,6 +490,27 @@ mod cache_tests { Op::AddAlbum { album: a } } + type Counts = std::sync::Arc>; + + /// [`super::Caches::album_counts`] of library `library` once a count of every photo it started is done and + /// taken. + fn counted_in(c: &mut super::Caches, cat: &Catalog, library: u64, now: &str) -> Counts { + let ctx = egui::Context::default(); + let t0 = std::time::Instant::now(); + loop { + let shown = c.album_counts(cat, library, now, &ctx); + if c.album_recount.is_none() { + return shown; + } + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count is done"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + fn counted(c: &mut super::Caches, cat: &Catalog, now: &str) -> Counts { + counted_in(c, cat, 0, now) + } + /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for /// "in the last…" rules) the clock crossing into a new minute recompute them. #[test] @@ -398,23 +523,23 @@ mod cache_tests { cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); cat.apply(smart(11, serde_json::json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}))).unwrap(); let now = "2026-09-30T12:00:00"; - let n = c.album_counts(&cat, now); + let n = counted(&mut c, &cat, now); assert_eq!((n[&AlbumId(10)], n[&AlbumId(11)]), (1, 1)); assert_eq!(c.album_count_scans, 1); for _ in 0..10 { - c.album_counts(&cat, "2026-09-30T12:00:40"); + counted(&mut c, &cat, "2026-09-30T12:00:40"); } assert_eq!(c.album_count_scans, 1, "unchanged frames in the same minute don't rescan"); // a photo rated: followed from that photo, not counted from every one cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 2); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2); assert_eq!(c.album_count_scans, 1); // rule change let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 5}]})).unwrap(); cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 1); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); // an hour later the 11:59:30 photo has left "in the last hour", with no catalog change - assert_eq!(c.album_counts(&cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); + assert_eq!(counted(&mut c, &cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); assert_eq!(c.album_count_scans, 3, "new rules and a new minute are counted from every photo; the rating was not"); lightcraft_catalog::rules::set_now(None); } @@ -462,8 +587,69 @@ mod cache_tests { let mut c = super::Caches::default(); cat.apply(photo(1, "2026-09-30T11:59:30", 5)).unwrap(); cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); - c.album_counts(&cat, "2026-09-30T12:00:00"); - c.album_counts(&cat, "2027-01-01T00:00:00"); + counted(&mut c, &cat, "2026-09-30T12:00:00"); + counted(&mut c, &cat, "2027-01-01T00:00:00"); assert_eq!(c.album_count_scans, 1); } + + /// Counting every photo again (an album's rules changed, an edit to many photos) takes seconds in a large + /// library: it runs off the UI thread, and the sidebar keeps the counts it showed until the new ones are ready. + #[test] + fn a_count_of_every_photo_runs_in_the_background_and_the_counts_shown_stay_meanwhile() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 0..3u64 { + cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + let now = "2026-09-30T12:00:00"; + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); + // new rules: every photo is asked again + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + let ctx = egui::Context::default(); + assert_eq!(c.album_counts(&cat, 0, now, &ctx)[&AlbumId(10)], 1, "the frame after the change shows the counts it had"); + assert!(c.album_recount.is_some(), "and every photo is counted elsewhere"); + // done counting is said whether or not a frame has taken the count yet (a folded Albums section takes none) + let t0 = std::time::Instant::now(); + while c.album_recount_running() { + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count ends"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // a photo rated meanwhile: followed from what the count finds + cat.apply(Op::SetRating { id: PhotoId(3), rating: 0 }).unwrap(); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2, "three photos rated at least 1, then one not"); + assert_eq!(c.album_count_scans, 2, "counted whole once for the new rules; the rating was followed"); + // the first time there is nothing to show yet: no count, rather than a wrong one + let mut fresh = super::Caches::default(); + assert!(fresh.album_counts(&cat, 0, now, &ctx).get(&AlbumId(10)).is_none()); + assert_eq!(counted(&mut fresh, &cat, now)[&AlbumId(10)], 2); + } + + /// Album ids start again in every library: once another library is open, the albums of the one before never + /// lend it their counts, nor does a count of that library still running when it closed. + #[test] + fn another_library_never_shows_the_counts_of_the_one_before() { + let library = |rated: &[u8]| { + let mut cat = Catalog::default(); + for (i, r) in rated.iter().enumerate() { + cat.apply(photo(i as u64 + 1, "2026-09-30T11:00:00", *r)).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + cat + }; + let (mut first, second) = (library(&[5, 1, 1]), library(&[5, 5, 1])); + let (mut c, ctx, now) = (super::Caches::default(), egui::Context::default(), "2026-09-30T12:00:00"); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + assert!(c.album_counts(&second, 2, now, &ctx).get(&AlbumId(10)).is_none(), "nothing until its own are counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2); + // a count of the first library under way when the second opens is let go + let mut c = super::Caches::default(); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + first.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + assert_eq!(c.album_counts(&first, 1, now, &ctx)[&AlbumId(10)], 1); + assert!(c.album_recount.is_some(), "the first library is being counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2, "the second library's own count"); + } } diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index ab49563cbb..3e122129b1 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -388,11 +388,12 @@ impl Headless { } } - /// Is anything still in progress (renders, file-system checks the sidebar waits for, queued - /// input)? + /// Is anything still in progress (renders, file-system checks the sidebar waits for, the albums' counts, + /// queued input)? pub fn busy(&self) -> bool { self.app.renderer.in_flight() > 0 || crate::panels::left::fs_cached_running(&self.view.ctx) > 0 + || self.app.caches.album_recount_running() || self.app.merge.busy() || self.app.scan.is_some() || self.app.sync.is_some() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9db7035c1d..8a5528f332 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -78,6 +78,7 @@ mod services; #[cfg(test)] use app::{import_tick_allowed, sam_download_ended, shot_ready}; pub(crate) use caches::key_of; +use caches::{AlbumCounts, AlbumRecount}; pub use caches::{FilterValues, LibraryCounts, RulesView}; use clock::AppClock; pub use clock::{monotonic_ms, now_ms}; @@ -570,10 +571,12 @@ pub struct Caches { counts: Option<(u64, LibraryCounts)>, date_groups: Option<(u64, std::sync::Arc>)>, filter_values: Option<(u64, std::sync::Arc)>, - /// The albums' counts: the minute they are of (while a smart album asks about "the last N days"), the tally - /// that follows edits, and the counts as the panels take them. - album_counts: - Option<(String, lightcraft_catalog::tally::AlbumTally, std::sync::Arc>)>, + /// The albums' counts as the sidebar shows them, with the tally that follows edits. + album_counts: Option, + /// A count of every photo running off the UI thread; the counts above are shown until it is done. + album_recount: Option, + /// The library, catalog revision and minute a count of every photo failed at: not tried again until one changes. + album_recount_failed: Option<(u64, u64, String)>, /// How often the album counts were made from every photo (tests check that unchanged frames, and edits to a /// photo or a few, don't). pub album_count_scans: usize, diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 92498eb023..3c732508bf 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -63,9 +63,9 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare } else { let sel = app.session.source == LibrarySource::Album(a.id); let icon = if a.is_smart() { Icon::SmartAlbum } else { Icon::Album }; - // cached: a smart album's count scans the catalog + // cached: a smart album's count scans the catalog (in the background: no number until it is known) let now = (app.session.clock)(); - let n = app.caches.album_counts(&app.session.catalog, &now).get(&a.id).copied().unwrap_or(0); + let n = app.caches.album_counts(&app.session.catalog, app.session.library_generation(), &now, ui.ctx()).get(&a.id).copied(); // the album B adds to is marked "+" let target = app.session.target_album.filter(|t| app.session.catalog.album(*t).is_some()).or_else(|| app.session.catalog.quick_collection()); @@ -74,7 +74,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let problems = app.caches.smart_album_problems(&app.session.catalog).get(&a.id).cloned().unwrap_or_default(); let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let mut resp = Row::new(&format!("album:{}", a.id.0), icon, &label) - .count(Some(n)) + .count(n) .selected(sel) .indent(indent) .sense(Sense::click_and_drag()) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f6..abd021aab3 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -96,7 +96,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | | LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | +| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | From 83f068807bf155d774241cabf6b89291093bc39f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 03:29:32 -0400 Subject: [PATCH 045/247] catalog: a failed keyword op no longer marks the keyword list as changed --- crates/catalog/src/lib.rs | 2 ++ crates/catalog/src/tests.rs | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 3225284c5f..f9d37606cf 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -628,6 +628,7 @@ impl Catalog { self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } let broad = self.changes.broad; + let keyword_list = self.changes.keyword_list; self.changes.torn = false; let inv = match self.apply_inner(op) { Ok(inv) => inv, @@ -649,6 +650,7 @@ impl Catalog { self.changes.touched.pop_back(); } self.changes.broad = broad; + self.changes.keyword_list = keyword_list; } return Err(e); } diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index fa71eb69be..8f4dbbdb8f 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -1006,6 +1006,13 @@ fn an_op_that_fails_leaves_no_touched_photos_behind() { assert_eq!(c.revision, start); assert_eq!(c.touched_since(start), Some(vec![])); assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + // a keyword op that fails, alone or inside a batch that is rolled back, does not say the keyword list changed + assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(Default::default()) }).is_err()); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + let ok = Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }; + assert!(c.apply(Op::Batch { ops: vec![ok, Op::SetRating { id: missing, rating: 1 }] }).is_err()); + assert_eq!(c.revision, start); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); assert_eq!(c.photo(a).map(|p| p.rating), Some(0)); // a batch that ends in a failed removal of a photo that exists assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err()); From 9352be8811e83630413fab140a6bc3263d9aed20 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:02:54 +0100 Subject: [PATCH 046/247] i18n tests: split string_literals under the workspace cognitive_complexity limit Main now denies clippy::cognitive_complexity; the literal scanner reached 32/30. Its block-comment skip and quoted-literal decoding become helpers of their own. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/tests.rs | 107 ++++++++++++++++++------------- 1 file changed, 61 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b3eefe40d1..ce7cd81a07 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -405,22 +405,7 @@ fn string_literals(src: &str) -> Vec<(usize, String)> { i += 1; } } else if c == '/' && at(i + 1) == '*' { - let mut nested = 0; - while i < chars.len() { - if chars[i] == '/' && at(i + 1) == '*' { - nested += 1; - i += 2; - } else if chars[i] == '*' && at(i + 1) == '/' { - nested -= 1; - i += 2; - if nested == 0 { - break; - } - } else { - line += usize::from(chars[i] == '\n'); - i += 1; - } - } + skip_block_comment(&chars, &mut i, &mut line); } else if let Some(start) = cfg_start(i) { // `#[cfg(test)]` (spaces allowed) and `#[cfg(all(test, …))]` mark the next item as test // code up to its `;` or through its body, `#![cfg(test)]` the rest of the file; @@ -458,36 +443,8 @@ fn string_literals(src: &str) -> Vec<(usize, String)> { out.push((first, text)); } } else if c == '"' { - let (first, mut text) = (line, String::new()); - i += 1; - while i < chars.len() && chars[i] != '"' { - if chars[i] == '\\' { - match at(i + 1) { - '\n' => { - line += 1; - i += 2; - while at(i).is_whitespace() { - line += usize::from(at(i) == '\n'); - i += 1; - } - } - 'u' => { - let hex: String = chars[i + 3..].iter().take_while(|&&h| h != '}').collect(); - text.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); - i += 4 + hex.len(); - } - escaped => { - text.push(escaped); - i += 2; - } - } - } else { - line += usize::from(chars[i] == '\n'); - text.push(chars[i]); - i += 1; - } - } - i += 1; + let first = line; + let text = quoted_literal(&chars, &mut i, &mut line); if test_depth.is_none() && !pending_test { out.push((first, text)); } @@ -524,6 +481,64 @@ fn string_literals(src: &str) -> Vec<(usize, String)> { out } +/// Skips the block comment (nested ones too) that starts at `chars[*i]`, counting its lines. +fn skip_block_comment(chars: &[char], i: &mut usize, line: &mut usize) { + let at = |k: usize| chars.get(k).copied().unwrap_or('\0'); + let mut nested = 0; + while *i < chars.len() { + if chars[*i] == '/' && at(*i + 1) == '*' { + nested += 1; + *i += 2; + } else if chars[*i] == '*' && at(*i + 1) == '/' { + nested -= 1; + *i += 2; + if nested == 0 { + break; + } + } else { + *line += usize::from(chars[*i] == '\n'); + *i += 1; + } + } +} + +/// The text of the `"…"` literal that starts at `chars[*i]`, with `\u{…}`, line continuations and +/// other escapes decoded; `*i` ends past its closing quote. +fn quoted_literal(chars: &[char], i: &mut usize, line: &mut usize) -> String { + let at = |k: usize| chars.get(k).copied().unwrap_or('\0'); + let mut text = String::new(); + *i += 1; + while *i < chars.len() && chars[*i] != '"' { + if chars[*i] != '\\' { + *line += usize::from(chars[*i] == '\n'); + text.push(chars[*i]); + *i += 1; + continue; + } + match at(*i + 1) { + '\n' => { + *line += 1; + *i += 2; + while at(*i).is_whitespace() { + *line += usize::from(at(*i) == '\n'); + *i += 1; + } + } + 'u' => { + let hex: String = chars[*i + 3..].iter().take_while(|&&h| h != '}').collect(); + text.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + *i += 4 + hex.len(); + } + escaped => { + text.push(escaped); + *i += 2; + } + } + } + *i += 1; + text +} + #[test] fn string_literals_skip_comments_tests_and_char_literals() { let src = r##"// "a" From d031492f7a4b0ff1399ae1e33e80e66e35fbe59c Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 18:53:15 -0400 Subject: [PATCH 047/247] LR-LIB-DELETE: the catalog answers "which photos have a file in this folder / of this name" from an index Two lookups the Trash work asks once per photo, so a big library answers from a map instead of a pass over every photo: `photos_in_folder_any_case` and `photos_named_any_case`. Like the stack and album lookups they are never saved, built on first use and kept up to date by `AddPhoto`, `RemovePhoto`, `Relink` and `SetFile`. Nothing asks them yet, so nothing changes on screen. --- crates/catalog/src/index.rs | 134 ++++++++++++++++++++++- crates/catalog/src/lib.rs | 12 ++ crates/catalog/src/tests_folder_index.rs | 115 +++++++++++++++++++ 3 files changed, 256 insertions(+), 5 deletions(-) create mode 100644 crates/catalog/src/tests_folder_index.rs diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 2c347473bc..8510a743c8 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -1,17 +1,19 @@ //! Lookups derived from the catalog's own data, so questions asked once per photo of a big library -//! don't scan a list each time: which stack a photo is in, whether a regular album holds it. +//! don't scan a list each time: which stack a photo is in, whether a regular album holds it, which +//! photos have their file in a folder, which have a file of a given name. //! //! They are never saved (the on-disk format is unchanged). Each is built on first use from what //! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts //! without them and builds them when asked. Once built, [`crate::Catalog::apply`] keeps them up to //! date: the ops that change stacks or album photos (`AddStack`, `RemoveStack`, `SetStack`, -//! `AddAlbum`, `RemoveAlbum`, `SetAlbumPhotos`) update them as they apply, inverses and the -//! rollback of a failed batch included, as those are ops too. +//! `AddAlbum`, `RemoveAlbum`, `SetAlbumPhotos`) and those that add, remove or point a photo at +//! another file (`AddPhoto`, `RemovePhoto`, `Relink`, `SetFile`) update them as they apply, +//! inverses and the rollback of a failed batch included, as those are ops too. use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; -use crate::{AlbumId, Catalog, PhotoId, StackId}; +use crate::{AlbumId, Catalog, PhotoId, Source, StackId}; #[derive(Default)] pub(crate) struct Indexes { @@ -20,6 +22,13 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Folder (its [`photo_folder_index_key`], lower-cased) → the photos whose file is directly in + /// it, whatever their state (in the library, in Recently Deleted, browsed in Local). Demo + /// photos have none. + folders: OnceLock>>, + /// File name, lower-cased ([`file_name_index_key`]) → the photos whose file has it (same + /// states as `folders`). + names: OnceLock>>, } /// A copy builds its own when asked (copies are made to be saved, not queried). @@ -40,7 +49,12 @@ impl PartialEq for Indexes { impl std::fmt::Debug for Indexes { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let stacks = self.stacks.get().map(|m| m.as_ref().map(HashMap::len)); - f.debug_struct("Indexes").field("stacks", &stacks).field("albums", &self.albums.get().map(HashMap::len)).finish() + f.debug_struct("Indexes") + .field("stacks", &stacks) + .field("albums", &self.albums.get().map(HashMap::len)) + .field("folders", &self.folders.get().map(HashMap::len)) + .field("names", &self.names.get().map(HashMap::len)) + .finish() } } @@ -70,6 +84,86 @@ impl Indexes { } } } + + /// Photo `id`'s file was at `old` and is at `new` now (`None`: no file, or the photo was added + /// or is gone). + pub(crate) fn file_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option<&str>) { + if old == new { + return; + } + if let Some(m) = self.folders.get_mut() { + rekey(m, id, old.and_then(photo_folder_index_key), new.and_then(photo_folder_index_key)); + } + if let Some(m) = self.names.get_mut() { + rekey(m, id, old.and_then(file_name_index_key), new.and_then(file_name_index_key)); + } + } +} + +fn rekey(m: &mut HashMap>, id: PhotoId, old: Option, new: Option) { + if let Some(k) = old + && let Some(set) = m.get_mut(&k) + { + set.remove(&id); + if set.is_empty() { + m.remove(&k); + } + } + if let Some(k) = new { + m.entry(k).or_default().insert(id); + } +} + +/// Whether `path` is a plain POSIX path, its own identity under [`crate::query::folder_key`]: no +/// `\`, no repeated separator, no `.` or `..` part, no trailing separator. +fn plain_posix(path: &str) -> bool { + !cfg!(windows) + && path.starts_with('/') + && !path.contains('\\') + && !path.contains("//") + && !path.contains("/./") + && !path.contains("/../") + && !path.ends_with('/') + && !path.ends_with("/.") + && !path.ends_with("/..") +} + +/// The folder-index key of a file path: its folder as [`crate::folder_of`] spells it, lower-cased +/// (`None` for a bare relative name). A plain POSIX path is cut at its last `/` without building a +/// [`crate::query::folder_key`]. +pub fn photo_folder_index_key(path: &str) -> Option { + let cut = |key: &str| key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { dir.to_lowercase() }); + if plain_posix(path) { cut(path) } else { cut(&crate::query::folder_key(path)) } +} + +/// The folder-index key of a folder path (as [`photo_folder_index_key`] gives for the files in it). +pub fn folder_index_key(folder: &str) -> String { + let key = crate::query::folder_key(folder).to_lowercase(); + // a disk's or share's root key ends in `/` (`c:/`, `//srv/share/`); its files' folder key doesn't + match key.strip_suffix('/') { + Some(k) if !k.is_empty() => k.to_string(), + _ => key, + } +} + +/// The name-index key of a file path: its file name, lower-cased (`None`: it has none). +pub fn file_name_index_key(path: &str) -> Option { + // `/` and `\` both separate on every platform (a catalog can move between them), as for the folder key + path.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().filter(|n| !n.is_empty() && *n != "." && *n != "..").map(str::to_lowercase) +} + +/// The path of a photo's file (`None` for a demo scene). +pub(crate) fn file_path(s: &Source) -> Option<&str> { + match s { + Source::File { path } => Some(path), + Source::Demo { .. } => None, + } +} + +fn sorted(set: Option<&HashSet>) -> Vec { + let mut v: Vec = set.map(|s| s.iter().copied().collect()).unwrap_or_default(); + v.sort_unstable(); + v } impl Catalog { @@ -98,4 +192,34 @@ impl Catalog { let m = self.index.albums.get_or_init(|| self.albums.values().map(|a| (a.id, a.photos.iter().copied().collect())).collect()); m.get(&album).is_some_and(|s| s.contains(&photo)) } + + fn file_index(&self, which: &str, key: fn(&str) -> Option) -> HashMap> { + let t = web_time::Instant::now(); + let mut m: HashMap> = HashMap::new(); + for p in self.photos.values() { + if let Source::File { path } = &p.source + && let Some(k) = key(path) + { + m.entry(k).or_default().insert(p.id); + } + } + log::info!("catalog: {which} index built for {} photos in {:.1} ms", self.photos.len(), t.elapsed().as_secs_f64() * 1e3); + m + } + + /// The photos whose file is directly in the folder with key `folder_key` (from + /// [`photo_folder_index_key`] or [`folder_index_key`]), whatever their state, sorted by id. + /// The grouping ignores letter case: callers compare exact paths themselves. The first query + /// builds the index in one pass over the library; it costs about one set entry per photo. + pub fn photos_in_folder_any_case(&self, folder_key: &str) -> Vec { + sorted(self.index.folders.get_or_init(|| self.file_index("folder", photo_folder_index_key)).get(folder_key)) + } + + /// The photos whose file is named `name_lower` (lower-cased, as [`file_name_index_key`] gives), + /// whatever their state, sorted by id. The grouping ignores letter case: callers compare exact + /// names themselves. The first query builds the index in one pass over the library; it costs + /// about one set entry per photo. + pub fn photos_named_any_case(&self, name_lower: &str) -> Vec { + sorted(self.index.names.get_or_init(|| self.file_index("name", file_name_index_key)).get(name_lower)) + } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a697..03b1589bb4 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -33,6 +33,8 @@ use std::sync::Arc; pub use dates::{DateRun, GroupBy}; pub use folders::{FolderNode, FolderRecord}; +use index::file_path; +pub use index::{file_name_index_key, folder_index_key, photo_folder_index_key}; pub use journal::{Journal, LoadReport, PersistStats, SnapshotPolicy, SnapshotTiming}; pub use keywords::KeywordNode; use lightcraft_develop::DevelopSettings; @@ -705,11 +707,13 @@ impl Catalog { } let id = photo.id; self.next_photo = self.next_photo.max(id.0.saturating_add(1)); + self.index.file_changed(id, None, file_path(&photo.source)); self.photos.insert(id, Arc::new(*photo)); Op::RemovePhoto { id } } Op::RemovePhoto { id } => { let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?; + self.index.file_changed(id, file_path(&p.source), None); // album membership is restored by the batch the engine builds (see `delete_permanently`) Op::AddPhoto { photo: Box::new((*p).clone()) } } @@ -909,6 +913,9 @@ impl Catalog { Op::SetCaptured { id, captured: std::mem::replace(&mut p.captured, captured) } } Op::Relink { id, file_name, source, format } => { + if let Some(p) = self.photos.get(&id) { + self.index.file_changed(id, file_path(&p.source), file_path(&source)); + } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); let old_format = format.map(|f| std::mem::replace(&mut p.format, f)); @@ -941,6 +948,9 @@ impl Catalog { if file_name.trim().is_empty() { return Err(CatalogError::Invalid("empty file name".into())); } + if let Some(p) = self.photos.get(&id) { + self.index.file_changed(id, file_path(&p.source), file_path(&source)); + } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) } @@ -1193,6 +1203,8 @@ mod tests_album_order; #[cfg(test)] mod tests_background; #[cfg(test)] +mod tests_folder_index; +#[cfg(test)] mod tests_folder_records; #[cfg(test)] mod tests_folders; diff --git a/crates/catalog/src/tests_folder_index.rs b/crates/catalog/src/tests_folder_index.rs new file mode 100644 index 0000000000..2ccbc41d86 --- /dev/null +++ b/crates/catalog/src/tests_folder_index.rs @@ -0,0 +1,115 @@ +//! Which photos have their file in a folder, or a file of a given name, whatever the letter case +//! (see [`crate::index`]): asked once per photo moved to the Trash, so a big library answers from +//! an index instead of a pass over every photo. +//! +//! * Spellings of a folder that differ only in case are one folder; a folder inside it is another. +//! * The answers stay right as photos are added, removed, relinked or pointed at another file, and +//! when those are undone, or a batch fails and is rolled back. +//! * A plain path is read without building a folder key, and gives the same key. + +use crate::*; + +fn add(c: &mut Catalog, path: &str) -> PhotoId { + let id = c.alloc_photo_id(); + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let p = Photo::new(id, Source::File { path: path.into() }, name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +const FOLDERS: [&str; 6] = ["/a/b", "/a/b/sub", "/c", "/c/d", "/e", "/"]; +const NAMES: [&str; 5] = ["x.jpg", "y.jpg", "z.jpg", "w.jpg", "v.jpg"]; + +/// Every answer for the folders and names the tests use. +fn answers(c: &Catalog) -> Vec> { + let folders = FOLDERS.iter().map(|f| c.photos_in_folder_any_case(&folder_index_key(f))); + folders.chain(NAMES.iter().map(|n| c.photos_named_any_case(n))).collect() +} + +#[test] +fn spellings_that_differ_in_case_are_one_folder_and_one_name() { + let mut c = Catalog::new(); + let x = add(&mut c, "/A/b/x.jpg"); + let y = add(&mut c, "/a/B/y.jpg"); + let z = add(&mut c, "/a/b/sub/z.jpg"); + let big_x = add(&mut c, "/c/X.JPG"); + assert_eq!(c.photos_in_folder_any_case(&folder_index_key("/a/b")), vec![x, y]); + assert_eq!(c.photos_in_folder_any_case(&folder_index_key("/A/B/sub")), vec![z]); + assert_eq!(c.photos_named_any_case("x.jpg"), vec![x, big_x]); + assert!(c.photos_named_any_case("X.JPG").is_empty(), "the caller lower-cases the name"); +} + +#[test] +fn the_answers_follow_every_op_that_moves_a_file_and_its_undo() { + let mut c = Catalog::new(); + let x = add(&mut c, "/a/b/x.jpg"); + add(&mut c, "/a/b/sub/z.jpg"); + answers(&c); // built: from here on, the ops keep them + let check = |c: &Catalog, step: &str| assert_eq!(answers(c), answers(&c.clone()), "{step}"); + let id = c.alloc_photo_id(); + let added = Photo::new(id, Source::File { path: "/C/y.jpg".into() }, "y.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + let steps = [ + ("add", Op::AddPhoto { photo: Box::new(added) }), + ("set file", Op::SetFile { id: x, file_name: "W.jpg".into(), source: Source::File { path: "/e/W.jpg".into() } }), + ("relink", Op::Relink { id: x, file_name: "v.jpg".into(), source: Source::File { path: "/c/d/v.jpg".into() }, format: None }), + ("demo", Op::SetFile { id: x, file_name: "x.jpg".into(), source: Source::Demo { scene: 1 } }), + ("remove", Op::RemovePhoto { id }), + ]; + for (step, op) in steps { + let inverse = c.apply(op.clone()).unwrap(); + check(&c, step); + c.apply(inverse).unwrap(); + check(&c, &format!("{step} undone")); + c.apply(op).unwrap(); + check(&c, &format!("{step} again")); + } + assert!(c.photos_in_folder_any_case(&folder_index_key("/c")).is_empty(), "the added photo is gone"); +} + +#[test] +fn a_batch_rolled_back_leaves_the_answers_as_they_were() { + let mut c = Catalog::new(); + let x = add(&mut c, "/a/b/x.jpg"); + let before = answers(&c); + let failing = Op::Batch { + ops: vec![ + Op::SetFile { id: x, file_name: "y.jpg".into(), source: Source::File { path: "/c/y.jpg".into() } }, + Op::RemovePhoto { id: x }, + Op::SetRating { id: x, rating: 1 }, // the photo is gone: fails + ], + }; + assert!(c.apply(failing).is_err()); + assert_eq!(answers(&c), before); + assert_eq!(answers(&c), answers(&c.clone())); +} + +#[test] +fn a_plain_path_gives_the_same_folder_key_as_any_other_spelling() { + let slow = |path: &str| { + let key = crate::query::folder_key(path); + key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { dir.to_lowercase() }) + }; + for path in ["/a/b.jpg", "/b.jpg", "/a//b.jpg", "/a/./b.jpg", "/a/../b.jpg", "/a/b/", "/Volumes/X/[Stills]/0002/o.jpg", "a/b.jpg"] { + assert_eq!(photo_folder_index_key(path), slow(path), "{path}"); + } + assert_eq!(photo_folder_index_key("/Volumes/X/[Stills]/0002/o.jpg").as_deref(), Some("/volumes/x/[stills]/0002")); + assert_eq!(photo_folder_index_key("/a//b.jpg"), photo_folder_index_key("/a/b.jpg")); +} + +#[test] +fn a_folder_key_matches_its_files_key_at_a_drive_or_share_root_too() { + for (file, folder) in + [("C:\\x.jpg", "C:\\"), ("C:\\x.jpg", "C:"), ("\\\\nas\\share\\x.jpg", "\\\\nas\\share"), ("/x.jpg", "/"), ("/a/b/x.jpg", "/a/b/")] + { + assert_eq!(photo_folder_index_key(file), Some(folder_index_key(folder)), "{file} in {folder}"); + } +} + +#[test] +fn a_file_name_is_cut_at_either_separator() { + assert_eq!(file_name_index_key("/a/B.JPG").as_deref(), Some("b.jpg")); + assert_eq!(file_name_index_key("D:\\Photos\\IMG_1.JPG").as_deref(), Some("img_1.jpg")); + assert_eq!(file_name_index_key("/a/b/").as_deref(), Some("b")); + assert_eq!(file_name_index_key("/"), None); + assert_eq!(file_name_index_key("/a/.."), None); +} From 70b620b85ecf59bf83b65ea3ee16e389cd5b3d71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:57:16 -0700 Subject: [PATCH 048/247] LRC-LIB-KEYWORDS: the Keywording panel's Enter Keywords view edits keywords as text The Keywording box gets an Enter Keywords view (keywordView:enter) next to Keywords, & Containing and Will Export. It shows the selected photos' keywords as text, with commas between them and an asterisk after a keyword only some of the photos have. Return or leaving the box applies the edit to the photos selected when it began, as one photo.setMeta call and one undo step: a keyword left out comes off every one of them, a name typed goes to all of them, a marked keyword stays on the photos that have it, and without its asterisk it goes to all of them. Esc gives the edit up, and so does another selection. An asterisk after any other name is refused, and the text is kept. Containing keywords and synonyms stay out of the text. How mixed keywords are handled and when an edit applies are LightCraft's own rules; the help pages describe the view without saying either. --- crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/cs.json | 3 + crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/de.json | 3 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/es.json | 3 + crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fi.json | 3 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/fr.json | 3 + crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/id.json | 3 + crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/it.json | 3 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ja.json | 3 + crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/ka.json | 3 + crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pl.json | 3 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/pt-br.json | 3 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/ru.json | 3 + crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/sv.json | 3 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/uk.json | 3 + crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/vi.json | 3 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hans.json | 3 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/locales/zh-hant.json | 3 + crates/ui-egui/src/panels/keywording.rs | 138 +++++++++++++++++++- crates/ui-egui/src/panels/right/keywords.rs | 105 ++++++++++++++- crates/ui-egui/src/state/view.rs | 6 +- crates/ui-egui/src/tests/keywording.rs | 94 +++++++++++++ docs/parity-checklist.md | 2 +- 39 files changed, 400 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e0ec9f1baa..f012f37466 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -114,6 +114,7 @@ "New Folder in “{name}”": "Nová složka v „{name}“", "Created folder “{name}” in “{parent}”": "Vytvořena složka „{name}“ v „{parent}“", "On {have} of {of} selected photos": "Na {have} z {of} vybraných fotografií", + "A keyword name can't end with an asterisk: “{name}”": "Název klíčového slova nemůže končit hvězdičkou: „{name}“", "Painting “{k}”: click photos to add or remove it · Esc stops": "Nanášení „{k}“: kliknutím na fotografie přidáte nebo odeberete slovo · Esc ukončí režim", "Paste into {n} photo{} — only settings that were copied are pasted": "Vložit do fotografií: {n}{:.0} — vloží se pouze zkopírovaná nastavení", "Preset: {name}": "Přednastavení: {name}", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 6a056bbfb9..e0eaf629a8 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -5,6 +5,9 @@ " · in a burst": " · v sérii", "% of all commits": "% všech commitů", "& Containing": "& Obsahující", + "Enter Keywords": "Zadat klíčová slova", + "Keywords, separated by commas": "Klíčová slova oddělená čárkami", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Klávesou Return úpravu použijete na vybrané fotografie, klávesou Esc ji zrušíte. Hvězdička označuje klíčové slovo, které má jen část z nich.", "+ Group": "+ Skupina", "+ Rule": "+ Pravidlo", ", picked": ", vybráno", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 782886be84..ba5dc85ae8 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -232,6 +232,7 @@ "Added “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzugefügt", "Add Keyword “{keywords}”": "Stichwort „{keywords}“ hinzufügen", "On {have} of {of} selected photos": "Bei {have} von {of} ausgewählten Fotos", + "A keyword name can't end with an asterisk: “{name}”": "Ein Stichwortname darf nicht mit einem Sternchen enden: „{name}“", "Remove “{name}”": "„{name}“ entfernen", "There is a keyword set “{name}” already": "Es gibt bereits einen Stichwortsatz „{name}“", "Added {n} keyword{}": "Stichwörter hinzugefügt: {n}{:.0}", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 405c54a464..6b77f4726a 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2059,6 +2059,9 @@ "Will Export": "Wird exportiert", "No keywords are exported": "Es werden keine Stichwörter exportiert", "& Containing": "& Übergeordnete", + "Enter Keywords": "Stichwörter eingeben", + "Keywords, separated by commas": "Stichwörter, durch Kommas getrennt", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Die Eingabetaste wendet die Änderung auf die ausgewählten Fotos an, Esc verwirft sie. Ein Sternchen kennzeichnet ein Stichwort, das nur einige von ihnen haben.", "Edit Set…": "Satz bearbeiten…", "Edit Keyword Set": "Stichwortsatz bearbeiten", "Edit Keywords": "Stichwörter bearbeiten", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 41ae09d66e..f85c0c913f 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -233,6 +233,7 @@ "Added “{keyword}” to {n} photo{}": "Se añadió “{keyword}” a {n} foto{}", "Add Keyword “{keywords}”": "Añadir palabra clave “{keywords}”", "On {have} of {of} selected photos": "En {have} de {of} fotos seleccionadas", + "A keyword name can't end with an asterisk: “{name}”": "El nombre de una palabra clave no puede terminar en asterisco: «{name}»", "Remove “{name}”": "Quitar “{name}”", "There is a keyword set “{name}” already": "Ya hay un conjunto de palabras clave “{name}”", "Added {n} keyword{}": "Palabras clave añadidas: {n}{:.0}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index e43ae8c49b..178584c309 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2088,6 +2088,9 @@ "Will Export": "Se exportará", "No keywords are exported": "No se exporta ninguna palabra clave", "& Containing": "y contenedoras", + "Enter Keywords": "Introducir palabras clave", + "Keywords, separated by commas": "Palabras clave separadas por comas", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Intro aplica el cambio a las fotos seleccionadas; Esc lo descarta. Un asterisco marca una palabra clave que solo tienen algunas de ellas.", "Edit Set…": "Editar conjunto…", "Edit Keyword Set": "Editar conjunto de palabras clave", "Edit Keywords": "Editar palabras clave", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc..de04034e74 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -140,6 +140,7 @@ "New Folder in “{name}”": "Uusi kansio kohteessa ”{name}”", "Created folder “{name}” in “{parent}”": "Kansio ”{name}” luotu kohteeseen ”{parent}”", "On {have} of {of} selected photos": "{have} / {of} valitulla kuvalla", + "A keyword name can't end with an asterisk: “{name}”": "Avainsanan nimi ei voi päättyä tähteen: ”{name}”", "Painting “{k}”: click photos to add or remove it · Esc stops": "Maalataan ”{k}”: napsauta kuvia lisätäksesi tai poistaaksesi sen · Esc lopettaa", "Paste into {n} photo{} — only settings that were copied are pasted": "Liitä kuviin: {n}{:.0} — vain kopioidut asetukset liitetään", "Preset: {name}": "Esiasetus: {name}", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff7e03c066..d52eec6f93 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -5,6 +5,9 @@ " · in a burst": " · osa sarjaa", "% of all commits": "% kaikista commiteista", "& Containing": "& sisältää", + "Enter Keywords": "Kirjoita avainsanat", + "Keywords, separated by commas": "Avainsanat pilkuilla erotettuina", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Return tekee muutoksen valituille kuville, Esc peruu sen. Tähti merkitsee avainsanaa, joka on vain osalla niistä.", "(not in the library)": "(ei kirjastossa)", "+ Group": "+ Ryhmä", "+ Rule": "+ Sääntö", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index fc46d653c6..517e62fe48 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -233,6 +233,7 @@ "Added “{keyword}” to {n} photo{}": "« {keyword} » ajouté à {n} photo{}", "Add Keyword “{keywords}”": "Ajouter le mot-clé « {keywords} »", "On {have} of {of} selected photos": "Sur {have} des {of} photos sélectionnées", + "A keyword name can't end with an asterisk: “{name}”": "Un nom de mot-clé ne peut pas se terminer par un astérisque : « {name} »", "Remove “{name}”": "Retirer « {name} »", "There is a keyword set “{name}” already": "Un jeu de mots-clés « {name} » existe déjà", "Added {n} keyword{}": "Mots-clés ajoutés : {n}{:.0}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e032cf52f3..75d4bff648 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1895,6 +1895,9 @@ "Will Export": "Sera exporté", "No keywords are exported": "Aucun mot-clé n'est exporté", "& Containing": "et parents", + "Enter Keywords": "Saisir des mots-clés", + "Keywords, separated by commas": "Mots-clés séparés par des virgules", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Entrée applique la modification aux photos sélectionnées, Échap l'annule. Un astérisque marque un mot-clé que seules certaines d'entre elles ont.", "Edit Set…": "Modifier le jeu…", "Edit Keyword Set": "Modifier le jeu de mots-clés", "Edit Keywords": "Modifier les mots-clés", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3..62c20dfadf 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -236,6 +236,7 @@ "Added “{keyword}” to {n} photo{}": "“{keyword}” ditambahkan ke {n} foto{:.0}", "Add Keyword “{keywords}”": "Tambahkan kata kunci “{keywords}”", "On {have} of {of} selected photos": "Pada {have} dari {of} foto yang dipilih", + "A keyword name can't end with an asterisk: “{name}”": "Nama kata kunci tidak boleh diakhiri tanda bintang: “{name}”", "Remove “{name}”": "Hapus “{name}”", "There is a keyword set “{name}” already": "Set kata kunci “{name}” sudah ada", "Added {n} keyword{}": "{n} kata kunci ditambahkan{:.0}", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 1c70f26344..c8e964d592 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -6,6 +6,9 @@ "#106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its": "#106): DNG dicocokkan dengan data raw, ditulis ke file sementara, disinkronkan, lalu dibaca ulang sebelum diberi", "% of all commits": "% dari semua commit", "& Containing": "& kata kunci induk", + "Enter Keywords": "Masukkan kata kunci", + "Keywords, separated by commas": "Kata kunci, dipisahkan dengan koma", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Tekan Return untuk menerapkan perubahan ke foto yang dipilih, Esc untuk membatalkannya. Tanda bintang menandai kata kunci yang hanya dimiliki sebagian foto.", "(not in the library)": "(tidak ada di pustaka)", "+ Group": "+ Grup", "+ Rule": "+ Aturan", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 4437aa644d..5c91284e32 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -229,6 +229,7 @@ "Added “{keyword}” to {n} photo{}": "Aggiunta “{keyword}” a {n} foto{:.0}", "Add Keyword “{keywords}”": "Aggiungi parola chiave “{keywords}”", "On {have} of {of} selected photos": "Su {have} di {of} foto selezionate", + "A keyword name can't end with an asterisk: “{name}”": "Il nome di una parola chiave non può terminare con un asterisco: “{name}”", "Remove “{name}”": "Rimuovi “{name}”", "There is a keyword set “{name}” already": "Esiste già un set di parole chiave “{name}”", "Added {n} keyword{}": "Parole chiave aggiunte: {n}{:.0}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a0d39d0610..f638439b6a 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2014,6 +2014,9 @@ "Will Export": "Verrà esportata", "No keywords are exported": "Nessuna parola chiave viene esportata", "& Containing": "e contenenti", + "Enter Keywords": "Inserisci parole chiave", + "Keywords, separated by commas": "Parole chiave separate da virgole", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Invio applica la modifica alle foto selezionate, Esc la annulla. Un asterisco indica una parola chiave che hanno solo alcune di esse.", "Edit Set…": "Modifica set…", "Edit Keyword Set": "Modifica set di parole chiave", "Edit Keywords": "Modifica parole chiave", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 2fb625ff6a..b07df2d55f 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -237,6 +237,7 @@ "Added “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加しました{:.0}", "Add Keyword “{keywords}”": "キーワード「{keywords}」を追加", "On {have} of {of} selected photos": "選択した写真{of}枚のうち{have}枚", + "A keyword name can't end with an asterisk: “{name}”": "キーワード名の末尾にアスタリスクは使えません:「{name}」", "Remove “{name}”": "「{name}」を削除", "There is a keyword set “{name}” already": "キーワードセット「{name}」はすでにあります", "Added {n} keyword{}": "{n}件のキーワードを追加しました{:.0}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5f80d7896b..0fa1998178 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1908,6 +1908,9 @@ "Will Export": "書き出されるキーワード", "No keywords are exported": "書き出されるキーワードはありません", "& Containing": "と親キーワード", + "Enter Keywords": "キーワードを入力", + "Keywords, separated by commas": "キーワード (カンマ区切り)", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Return キーで選択した写真に変更を適用し、Esc キーで取り消します。アスタリスクは一部の写真だけにあるキーワードを示します。", "Edit Set…": "セットを編集…", "Edit Keyword Set": "キーワードセットを編集", "Edit Keywords": "キーワードを編集", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 329662ac1b..b76c111863 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -115,6 +115,7 @@ "New Folder in “{name}”": "ახალი საქაღალდე „{name}“-ში", "Created folder “{name}” in “{parent}”": "საქაღალდე „{name}“ შეიქმნა „{parent}“-ში", "On {have} of {of} selected photos": "{of} მონიშნული ფოტოდან {have}-ზე", + "A keyword name can't end with an asterisk: “{name}”": "საკვანძო სიტყვის სახელი ვარსკვლავით ვერ დასრულდება: „{name}“", "Painting “{k}”: click photos to add or remove it · Esc stops": "„{k}“-ის მინიჭება: დაწკაპეთ ფოტოებზე მის დასამატებლად ან მოსახსნელად · Esc ასრულებს", "Paste into {n} photo{} — only settings that were copied are pasted": "ჩასმა ფოტოებში: {n}{:.0} — ჩაისმება მხოლოდ კოპირებული პარამეტრები", "Preset: {name}": "პრესეტი: {name}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 0ea7d3d805..8c8a98af87 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -11,6 +11,9 @@ "#106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its": "#106): DNG მოწმდება RAW მონაცემებთან, იწერება დროებით ფაილში, სინქრონიზდება და ხელახლა იკითხება, სანამ მიიღებს", "% of all commits": "ყველა კომიტის %", "& Containing": "და შემცველი", + "Enter Keywords": "საკვანძო სიტყვების შეყვანა", + "Keywords, separated by commas": "საკვანძო სიტყვები, მძიმეებით გამოყოფილი", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Return ცვლილებას მონიშნულ ფოტოებს ანიჭებს, Esc კი აუქმებს. ვარსკვლავი აღნიშნავს საკვანძო სიტყვას, რომელიც მხოლოდ ზოგიერთ მათგანს აქვს.", "(\"Failed to associate portal window with parent window\" in the portal's log): tiling compositors put it beside the": "(„Failed to associate portal window with parent window“ პორტალის ჟურნალში): ფილისებრი კომპოზიტორები მას", "(Esc keeps the old angle; a decimal comma works too), or click the Straighten value; hovering any slider's value now says it can be typed.": "(Esc ძველ კუთხეს ტოვებს; ათწილადი მძიმეც მუშაობს), ან დაწკაპეთ გასწორების მნიშვნელობაზე; ნებისმიერი სლაიდერის მნიშვნელობაზე მიტანისას ახლა ჩანს, რომ მისი აკრეფა შეიძლება.", "(Space, G, X, ⌫) and ⌘ shortcuts were not affected.": "(Space, G, X, ⌫) და ⌘ მალსახმობებზე ეს გავლენას არ ახდენდა.", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 3f0fd43a22..570f8e47db 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -220,6 +220,7 @@ "Added “{keyword}” to {n} photo{}": "Dodano „{keyword}” do zdjęć: {n}{:.0}", "Add Keyword “{keywords}”": "Dodaj słowo kluczowe „{keywords}”", "On {have} of {of} selected photos": "Na {have} z {of} zaznaczonych zdjęć", + "A keyword name can't end with an asterisk: “{name}”": "Nazwa słowa kluczowego nie może kończyć się gwiazdką: „{name}”", "Remove “{name}”": "Usuń „{name}”", "There is a keyword set “{name}” already": "Istnieje już zestaw słów kluczowych „{name}”", "Added {n} keyword{}": "Dodane słowa kluczowe: {n}{:.0}", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index bb3729a5b6..6533701b00 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1847,6 +1847,9 @@ "Will Export": "Zostanie wyeksportowane", "No keywords are exported": "Nie zostaną wyeksportowane żadne słowa kluczowe", "& Containing": "i nadrzędne", + "Enter Keywords": "Wprowadź słowa kluczowe", + "Keywords, separated by commas": "Słowa kluczowe oddzielone przecinkami", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Return stosuje zmianę do zaznaczonych zdjęć, Esc ją odrzuca. Gwiazdka oznacza słowo kluczowe, które ma tylko część z nich.", "Edit Set…": "Edytuj zestaw…", "Edit Keyword Set": "Edytuj zestaw słów kluczowych", "Edit Keywords": "Edytuj słowa kluczowe", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index c26b2e281e..073aa982f7 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -237,6 +237,7 @@ "Added “{keyword}” to {n} photo{}": "“{keyword}” adicionada a {n} foto{}", "Add Keyword “{keywords}”": "Adicionar palavra-chave “{keywords}”", "On {have} of {of} selected photos": "Em {have} de {of} fotos selecionadas", + "A keyword name can't end with an asterisk: “{name}”": "O nome de uma palavra-chave não pode terminar com asterisco: “{name}”", "Remove “{name}”": "Remover “{name}”", "There is a keyword set “{name}” already": "Já existe um conjunto de palavras-chave “{name}”", "Added {n} keyword{}": "Palavras-chave adicionadas: {n}{:.0}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index a0884dc56a..1cd2c17859 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1906,6 +1906,9 @@ "Will Export": "Será exportado", "No keywords are exported": "Nenhuma palavra-chave é exportada", "& Containing": "e as que as contêm", + "Enter Keywords": "Inserir palavras-chave", + "Keywords, separated by commas": "Palavras-chave separadas por vírgulas", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Enter aplica a alteração às fotos selecionadas; Esc a descarta. Um asterisco marca uma palavra-chave que só algumas delas têm.", "Edit Set…": "Editar conjunto…", "Edit Keyword Set": "Editar conjunto de palavras-chave", "Edit Keywords": "Editar palavras-chave", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 4be240ec5b..c14902a200 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -233,6 +233,7 @@ "Added “{keyword}” to {n} photo{}": "«{keyword}» добавлено к фото ({n}){:.0}", "Add Keyword “{keywords}”": "Добавить ключевое слово «{keywords}»", "On {have} of {of} selected photos": "На {have} из {of} выбранных фото", + "A keyword name can't end with an asterisk: “{name}”": "Имя ключевого слова не может заканчиваться звёздочкой: «{name}»", "Remove “{name}”": "Убрать «{name}»", "There is a keyword set “{name}” already": "Набор ключевых слов «{name}» уже есть", "Added {n} keyword{}": "Добавлено ключевых слов: {n}{:.0}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 598893c3bc..ffe4906beb 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1832,6 +1832,9 @@ "Will Export": "Будет экспортировано", "No keywords are exported": "Ключевые слова не экспортируются", "& Containing": "и родительские", + "Enter Keywords": "Ввод ключевых слов", + "Keywords, separated by commas": "Ключевые слова через запятую", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Клавиша Enter применяет изменение к выбранным фото, Esc отменяет его. Звёздочка отмечает ключевое слово, которое есть только у некоторых из них.", "Edit Set…": "Изменить набор…", "Edit Keyword Set": "Изменить набор ключевых слов", "Edit Keywords": "Изменить ключевые слова", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..f3c6b4869a 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -136,6 +136,7 @@ "none (CPU rendering): {why}": "ingen (CPU-rendering): {why}", "not added to Apple Photos: {e}": "inte tillagt i Apple Photos: {e}", "On {have} of {of} selected photos": "På {have} av {of} markerade foton", + "A keyword name can't end with an asterisk: “{name}”": "Ett nyckelordsnamn kan inte sluta med en asterisk: ”{name}”", "Painting “{k}”: click photos to add or remove it · Esc stops": "Målar ”{k}”: klicka på foton för att lägga till eller ta bort det · Esc avslutar", "Paste into {n} photo{} — only settings that were copied are pasted": "Klistra in i {n} foto{} – endast inställningar som kopierades klistras in", "Preset: {name}": "Förinställning: {name}", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f229b9547c..4db541291f 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -7,6 +7,9 @@ "#106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its": "#106): en DNG kontrolleras mot rådata, skrivs till en temporär fil, synkas och läses tillbaka innan den får sitt", "% of all commits": "% av alla commits", "& Containing": "& innehåller", + "Enter Keywords": "Ange nyckelord", + "Keywords, separated by commas": "Nyckelord, åtskilda med kommatecken", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Retur tillämpar ändringen på de markerade fotona, Esc ångrar den. En asterisk markerar ett nyckelord som bara några av dem har.", "(`gpuReason`, `gpuFallback`), Help ▸ System Info and Settings ▸ Performance say why the GPU isn't": "(`gpuReason`, `gpuFallback`), Hjälp → Systeminfo och Inställningar → Prestanda anger varför GPU:n inte", "(e.g. D750, D780, D850, D7500, Z 50) no longer render nearly black or with crushed shadows: their black level was": "(t.ex. D750, D780, D850, D7500, Z 50) renderas inte längre nästan svarta eller med klippta skuggor: deras svartnivå var", "(issue #94): an HTTP request from a web page can no longer carry a command in its body. Lines are capped at": "(ärende #94): en HTTP-begäran från en webbsida kan inte längre bära ett kommando i sin brödtext. Rader begränsas till", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index e87bd03749..f60eecc06d 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -233,6 +233,7 @@ "Added “{keyword}” to {n} photo{}": "«{keyword}» додано до фото: {n}{:.0}", "Add Keyword “{keywords}”": "Додати ключове слово «{keywords}»", "On {have} of {of} selected photos": "На {have} з {of} вибраних фото", + "A keyword name can't end with an asterisk: “{name}”": "Назва ключового слова не може закінчуватися зірочкою: «{name}»", "Remove “{name}”": "Вилучити «{name}»", "There is a keyword set “{name}” already": "Набір ключових слів «{name}» уже існує", "Added {n} keyword{}": "Додано ключових слів: {n}{:.0}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a4efe34a60..333cbff27c 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2090,6 +2090,9 @@ "Will Export": "Буде експортовано", "No keywords are exported": "Ключові слова не експортуються", "& Containing": "і батьківські", + "Enter Keywords": "Введення ключових слів", + "Keywords, separated by commas": "Ключові слова через кому", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Клавіша Enter застосовує зміну до вибраних фото, Esc скасовує її. Зірочка позначає ключове слово, яке є лише в деяких із них.", "Edit Set…": "Редагувати набір…", "Edit Keyword Set": "Редагувати набір ключових слів", "Edit Keywords": "Редагувати ключові слова", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db5..bf04d55e00 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -140,6 +140,7 @@ "New Folder in “{name}”": "Thư mục mới trong «{name}»", "Created folder “{name}” in “{parent}”": "Đã tạo thư mục «{name}» trong «{parent}»", "On {have} of {of} selected photos": "Trên {have} / {of} ảnh đã chọn", + "A keyword name can't end with an asterisk: “{name}”": "Tên từ khóa không thể kết thúc bằng dấu sao: «{name}»", "Painting “{k}”: click photos to add or remove it · Esc stops": "Gán «{k}»: nhấp ảnh để thêm hoặc gỡ · Esc dừng", "Paste into {n} photo{} — only settings that were copied are pasted": "Dán vào {n} ảnh{:.0} — chỉ dán các thiết lập đã sao chép", "Preset: {name}": "Thiết lập sẵn: {name}", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c1610e428f..8b45b1edbf 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -7,6 +7,9 @@ "#106): a DNG is checked against the raw data, written to a temp file, synced and read back before it gets its": "#106): một DNG được đối chiếu với dữ liệu raw, ghi vào tệp tạm, đồng bộ và đọc lại trước khi nhận", "% of all commits": "% tất cả commit", "& Containing": "& Chứa", + "Enter Keywords": "Nhập từ khóa", + "Keywords, separated by commas": "Từ khóa, cách nhau bằng dấu phẩy", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "Nhấn Return để áp dụng thay đổi cho các ảnh đã chọn, Esc để bỏ. Dấu sao đánh dấu từ khóa chỉ một số ảnh có.", "(`gpuReason`, `gpuFallback`), Help ▸ System Info and Settings ▸ Performance say why the GPU isn't": "(`gpuReason`, `gpuFallback`), Trợ giúp → Thông tin hệ thống và Cài đặt → Hiệu năng giải thích vì sao GPU không", "(e.g. D750, D780, D850, D7500, Z 50) no longer render nearly black or with crushed shadows: their black level was": "(ví dụ D750, D780, D850, D7500, Z 50) không còn hiển thị gần như đen hoặc vùng tối bị nén: mức đen của chúng đã được", "(issue #94): an HTTP request from a web page can no longer carry a command in its body. Lines are capped at": "(issue #94): yêu cầu HTTP từ trang web không còn mang lệnh trong phần thân. Số dòng được giới hạn ở", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0a8b94115f..3b063058d1 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -237,6 +237,7 @@ "Added “{keyword}” to {n} photo{}": "已将“{keyword}”添加到 {n} 张照片{:.0}", "Add Keyword “{keywords}”": "添加关键字“{keywords}”", "On {have} of {of} selected photos": "所选 {of} 张照片中的 {have} 张", + "A keyword name can't end with an asterisk: “{name}”": "关键字名称不能以星号结尾:“{name}”", "Remove “{name}”": "移除“{name}”", "There is a keyword set “{name}” already": "已有关键字集“{name}”", "Added {n} keyword{}": "已添加 {n} 个关键字{:.0}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ea867f35e6..26b54d945f 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1900,6 +1900,9 @@ "Will Export": "将导出", "No keywords are exported": "没有要导出的关键字", "& Containing": "及上级", + "Enter Keywords": "输入关键字", + "Keywords, separated by commas": "关键字,用逗号分隔", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "按回车键将修改应用到所选照片,按 Esc 键放弃。星号表示只有部分照片带有的关键字。", "Edit Set…": "编辑关键字集…", "Edit Keyword Set": "编辑关键字集", "Edit Keywords": "编辑关键字", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 178cd55a03..ffbad3d8be 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -237,6 +237,7 @@ "Added “{keyword}” to {n} photo{}": "已將「{keyword}」加入 {n} 張照片{:.0}", "Add Keyword “{keywords}”": "加入關鍵字「{keywords}」", "On {have} of {of} selected photos": "選取的 {of} 張照片中的 {have} 張", + "A keyword name can't end with an asterisk: “{name}”": "關鍵字名稱不能以星號結尾:「{name}」", "Remove “{name}”": "移除「{name}」", "There is a keyword set “{name}” already": "已有關鍵字集「{name}」", "Added {n} keyword{}": "已加入 {n} 個關鍵字{:.0}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 90b3670ec3..d57149ce41 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1906,6 +1906,9 @@ "Will Export": "將匯出", "No keywords are exported": "沒有要匯出的關鍵字", "& Containing": "及上層", + "Enter Keywords": "輸入關鍵字", + "Keywords, separated by commas": "關鍵字,以逗號分隔", + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.": "按 Return 鍵將修改套用到選取的照片,按 Esc 鍵放棄。星號表示只有部分照片帶有的關鍵字。", "Edit Set…": "編輯關鍵字集…", "Edit Keyword Set": "編輯關鍵字集", "Edit Keywords": "編輯關鍵字", diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 4861d4c6fa..b77c2a6763 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -9,14 +9,17 @@ use crate::LightcraftApp; use crate::theme::Tokens; use crate::widgets::register; -/// The Keywording box's view: the keywords (chips), them with the keywords containing them, or -/// what exported files will carry. +/// The Keywording box's view: the keywords as text (Enter Keywords), the keywords (chips), them +/// with the keywords containing them, or what exported files will carry. pub fn view_switch(app: &mut LightcraftApp, ui: &mut egui::Ui) { use crate::state::KeywordingView as V; ui.horizontal_wrapped(|ui| { - for (view, id, label) in - [(V::Keywords, "keywords", "Keywords"), (V::Containing, "containing", "& Containing"), (V::WillExport, "willExport", "Will Export")] - { + for (view, id, label) in [ + (V::Enter, "enter", "Enter Keywords"), + (V::Keywords, "keywords", "Keywords"), + (V::Containing, "containing", "& Containing"), + (V::WillExport, "willExport", "Will Export"), + ] { let r = ui.selectable_label(app.ui.keywording_view == view, crate::i18n::tr(label)); register(ui, format!("keywordView:{id}"), r.rect); if r.clicked() { @@ -708,6 +711,62 @@ pub(crate) fn chips(catalog: &Catalog, photos: &[PhotoId]) -> Vec { have.into_values().map(|(k, n)| Chip { path: catalog.listed_path(&k).map(str::to_string).unwrap_or(k), have: n, of: photos.len() }).collect() } +/// The Enter Keywords text of the selection's keywords `chips`: each keyword's path, with commas +/// between them and an asterisk after a keyword only some of the selected photos have. +pub(crate) fn entered_text(chips: &[Chip]) -> String { + chips.iter().map(|c| if c.on_all() { c.path.clone() } else { format!("{}*", c.path) }).collect::>().join(", ") +} + +/// What an edit of the Enter Keywords text gives to and takes off the selected photos. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Entered { + /// Keywords for every selected photo. + pub add: Vec, + /// Keywords taken off every selected photo. + pub remove: Vec, +} + +impl Entered { + /// The edit changes no photo. + pub fn is_empty(&self) -> bool { + self.add.is_empty() && self.remove.is_empty() + } +} + +/// Reads the Enter Keywords `text` against `start`, the selection's keywords when the edit began. +/// Keywords are separated by commas or new lines. A keyword of `start` left out of the text is +/// taken off every selected photo. A name without an asterisk goes to every selected photo (a +/// keyword of `start` keeps its spelling, and a new name goes where `Catalog::typed_keyword` puts +/// it). A keyword only some photos have, still marked with its asterisk, stays on those photos +/// only. An asterisk after any other name is refused: the error is the name as typed. +pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result { + use lightcraft_catalog::keywords::{clean, same}; + let mut kept: Vec = Vec::new(); + let mut add: Vec = Vec::new(); + for token in text.split([',', '\n']).map(str::trim).filter(|t| !t.is_empty()) { + if let Some(marked) = token.strip_suffix('*') { + let name = clean(marked); + let partial = start.iter().find(|c| !c.on_all() && same(&c.path, &name)).ok_or_else(|| token.to_string())?; + kept.push(partial.path.clone()); + continue; + } + let typed = clean(token); + let (name, on_all) = match start.iter().find(|c| same(&c.path, &typed)) { + Some(c) => (c.path.clone(), c.on_all()), + None => (catalog.typed_keyword(token), false), + }; + if name.is_empty() { + continue; + } + if !on_all && !add.iter().any(|a| same(a, &name)) { + add.push(name.clone()); + } + kept.push(name); + } + let remove = start.iter().filter(|c| !kept.iter().any(|k| same(k, &c.path))).map(|c| c.path.clone()).collect(); + Ok(Entered { add, remove }) +} + #[cfg(test)] mod tests { use lightcraft_catalog::{Op, Photo, Source}; @@ -1007,4 +1066,73 @@ mod tests { let (c, ids) = library(&[&["travel|Italy|Rome", "travel|Spain"], &["travel|Italy"]]); assert_eq!(shown(&with_containing(&c, &ids)), [("Italy", 2, 2), ("Rome", 1, 2), ("Spain", 1, 2), ("travel", 2, 2)]); } + + fn edit(add: &[&str], remove: &[&str]) -> Entered { + Entered { add: add.iter().map(|s| s.to_string()).collect(), remove: remove.iter().map(|s| s.to_string()).collect() } + } + + /// The Enter Keywords text is the selection's keywords with their paths, commas between them, and + /// an asterisk after one only some of the selected photos have; left as it is, it changes nothing. + #[test] + fn the_entered_text_is_the_selections_keywords() { + let (c, ids) = library(&[&["Places|Lisbon", "beach"], &["beach"]]); + let start = chips(&c, &ids); + let text = entered_text(&start); + assert_eq!(text, "beach, Places|Lisbon*"); + assert_eq!(entered(&c, &start, &text), Ok(Entered::default())); + assert_eq!(entered(&c, &start, " beach ,\nPlaces | Lisbon * "), Ok(Entered::default()), "spaces and new lines"); + assert_eq!(entered(&c, &start, "BEACH, places|lisbon*"), Ok(Entered::default()), "another case is the same keyword"); + assert_eq!(entered_text(&[]), ""); + } + + /// A keyword left out of the text is taken off every selected photo; a name typed goes to every + /// one of them; a partial keyword without its asterisk goes to all of them. + #[test] + fn an_edit_adds_and_removes_for_every_selected_photo() { + let (c, ids) = library(&[&["Places|Lisbon", "beach"], &["beach", "sea"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, "Places|Lisbon*, sea*"), Ok(edit(&[], &["beach"]))); + assert_eq!(entered(&c, &start, "beach, Places|Lisbon*, sea*, harbour, Places|Porto"), Ok(edit(&["harbour", "Places|Porto"], &[]))); + assert_eq!(entered(&c, &start, "beach, Places|Lisbon, sea*"), Ok(edit(&["Places|Lisbon"], &[])), "made common"); + assert_eq!(entered(&c, &start, "beach, harbour, HARBOUR"), Ok(edit(&["harbour"], &["Places|Lisbon", "sea"])), "named once"); + assert_eq!(entered(&c, &start, ""), Ok(edit(&[], &["beach", "Places|Lisbon", "sea"])), "an empty box clears them"); + assert_eq!(entered(&c, &start, " , | ,"), Ok(edit(&[], &["beach", "Places|Lisbon", "sea"])), "nothing but separators"); + } + + /// Containing keywords and synonyms are not part of the text: they stay derived, and an edit + /// never assigns them. + #[test] + fn containing_keywords_and_synonyms_stay_out_of_the_text() { + use lightcraft_catalog::keywords::KeywordInfo; + let (mut c, ids) = library(&[&["Places|Lisbon"]]); + c.apply(Op::SetKeyword { + path: "Places|Lisbon".into(), + info: Some(KeywordInfo { synonyms: vec!["Lisboa".into()], ..KeywordInfo::default() }), + }) + .unwrap(); + let start = chips(&c, &ids); + assert_eq!(entered_text(&start), "Places|Lisbon"); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); + } + + /// An asterisk marks a keyword only some photos have; after any other name it is refused, and the + /// error names what was typed. + #[test] + fn an_asterisk_after_another_name_is_refused() { + let (c, ids) = library(&[&["beach", "sea"], &["beach"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, "beach*, sea*"), Err("beach*".to_string()), "every photo has beach"); + assert_eq!(entered(&c, &start, "beach, sea*, harbour*"), Err("harbour*".to_string()), "a new name"); + assert_eq!(entered(&c, &start, "beach, *"), Err("*".to_string())); + } + + /// A new name goes inside the default parent, as one typed in the Add keyword box does. + #[test] + fn a_new_name_goes_inside_the_default_parent() { + use lightcraft_catalog::keywords::KeywordInfo; + let (mut c, ids) = library(&[&["beach"]]); + c.apply(Op::SetKeyword { path: "Inbox".into(), info: Some(KeywordInfo { new_keywords_inside: true, ..KeywordInfo::default() }) }).unwrap(); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, "beach, harbour"), Ok(edit(&["Inbox|harbour"], &[]))); + } } diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index d202557c12..1b092f06ee 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -138,10 +138,10 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { crate::panels::keywording::view_switch(app, ui); ui.add_space(4.0); crate::panels::keywording::scope(app, ui, &selection); - if app.ui.keywording_view == crate::state::KeywordingView::Keywords { - crate::panels::keywording::chip_row(app, ui, &selection); - } else { - crate::panels::keywording::names_row(app, ui); + match app.ui.keywording_view { + crate::state::KeywordingView::Enter => enter_keywords(app, ui, &selection), + crate::state::KeywordingView::Keywords => crate::panels::keywording::chip_row(app, ui, &selection), + _ => crate::panels::keywording::names_row(app, ui), } ui.add_space(10.0); keyword_set(app, ui); @@ -198,6 +198,101 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { }); } +/// An edit of the Enter Keywords box: its text, and the selection it was started on. +#[derive(Clone)] +struct EnterEdit { + text: String, + /// The selection's keywords when the edit started. + start: Vec, + /// The photos the edit is for (`photo.setMeta` `ids`). + ids: Vec, + /// The selection the edit was started on (`key_of`). + selection: u64, + /// The last try to apply it was refused: the text stays to be put right. + refused: bool, +} + +impl EnterEdit { + fn new(chips: &[crate::panels::keywording::Chip], selection: &[PhotoId], key: u64) -> Self { + let mut seen = std::collections::HashSet::new(); + EnterEdit { + text: crate::panels::keywording::entered_text(chips), + start: chips.to_vec(), + ids: selection.iter().filter(|id| seen.insert(**id)).map(|id| id.0).collect(), + selection: key, + refused: false, + } + } +} + +/// Enter Keywords: the selection's keywords as text, separated by commas, one only some of the +/// photos have marked with an asterisk. Return or leaving the box applies the edit to the photos +/// selected when it started, as one undo step; Esc gives it up. Another selection while the box is +/// being edited gives the edit up too. A refused edit keeps its text and says why. +fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { + const FIELD: &str = "field:enterKeywords"; + let id = egui::Id::unique("kw-enter"); + let key = crate::key_of(selection); + let chips = app.caches.keyword_chips(&app.session.catalog, selection); + let fid = crate::text_field::id(FIELD); + let focused = ui.memory(|m| m.has_focus(fid)); + let kept: Option = ui.data(|d| d.get_temp(id)); + // (an edit of another selection is given up, never applied to this one) + if kept.as_ref().is_some_and(|e| e.selection != key) && focused { + ui.memory_mut(|m| m.surrender_focus(fid)); + } + let mut edit = kept.filter(|e| e.selection == key).unwrap_or_else(|| EnterEdit::new(&chips, selection, key)); + // Return applies the edit (Shift+Return or a pasted line break separates keywords as a comma does) + let returned = focused + && ui.input_mut(|i| { + let plain = + |e: &egui::Event| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, modifiers, .. } if modifiers.is_none()); + let found = i.events.iter().any(plain); + i.events.retain(|e| !plain(e)); + found + }); + let r = crate::text_field::TextField::multiline(FIELD, &mut edit.text) + .hint(crate::i18n::tr("Keywords, separated by commas")) + .label(crate::i18n::tr("Enter Keywords")) + .rows(2) + .width(f32::INFINITY) + .show(ui); + r.response.clone().on_hover_text(crate::i18n::tr( + "Return applies the edit to the selected photos; Esc gives it up. An asterisk marks a keyword only some of them have.", + )); + if r.cancelled() { + ui.data_mut(|d| d.remove::(id)); + return; + } + let mut done = false; + if returned || r.committed() { + let applied = match crate::panels::keywording::entered(&app.session.catalog, &edit.start, &edit.text) { + Ok(change) if change.is_empty() => true, + Ok(change) => match app.run("photo.setMeta", json!({"ids": edit.ids, "addKeywords": change.add, "removeKeywords": change.remove})) { + Ok(_) => true, + Err(e) => { + app.toast_error(ui.ctx(), e); + false + } + }, + Err(name) => { + app.toast_error(ui.ctx(), crate::i18n::tr_format!("A keyword name can't end with an asterisk: “{name}”", name = name)); + false + } + }; + edit.refused = !applied; + done = applied; + if applied && returned { + ui.memory_mut(|m| m.surrender_focus(fid)); + } + } + if !done && (r.editing || returned || edit.refused) { + ui.data_mut(|d| d.insert_temp(id, edit)); + } else { + ui.data_mut(|d| d.remove::(id)); + } +} + /// Keeps the Keyword List where it is on screen when the Keywords box above it (starting at /// `top`) grows or shrinks: a keyword ticked or unticked in the list, another selection. Without it /// a long tree slides away from under the pointer by a row of chips each time. It holds only while @@ -218,7 +313,7 @@ fn hold_list_in_place(ui: &mut egui::Ui, top: f32) { // (only the part of it in sight: the pointer on the top bar above a half-hidden box isn't on it) let old_box = Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + before).intersect(ui.clip_rect()); let on_box = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| old_box.contains(p)); - let typing = ui.memory(|m| m.has_focus(crate::text_field::id("field:keyword"))); + let typing = ui.memory(|m| ["field:keyword", "field:enterKeywords"].iter().any(|f| m.has_focus(crate::text_field::id(f)))); if on_box || typing { return; } diff --git a/crates/ui-egui/src/state/view.rs b/crates/ui-egui/src/state/view.rs index 6110026475..a1fdb3b7ce 100644 --- a/crates/ui-egui/src/state/view.rs +++ b/crates/ui-egui/src/state/view.rs @@ -367,11 +367,13 @@ pub const RIGHT_WIDTH: PanelWidth = PanelWidth { min: 250.0, default: 270.0, max /// The photo area the side panels always leave free (as far as their minimum widths allow). pub const MIN_PHOTO_WIDTH: f32 = 360.0; -/// What the Keywording box shows: the keywords (chips to edit), them with the keywords containing -/// them, or what exported files will carry (read only). +/// What the Keywording box shows: the keywords as text to edit (Enter Keywords), the keywords +/// (chips to edit), them with the keywords containing them, or what exported files will carry +/// (read only). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum KeywordingView { + Enter, #[default] Keywords, Containing, diff --git a/crates/ui-egui/src/tests/keywording.rs b/crates/ui-egui/src/tests/keywording.rs index 4e2908d10f..130af6ee3d 100644 --- a/crates/ui-egui/src/tests/keywording.rs +++ b/crates/ui-egui/src/tests/keywording.rs @@ -949,3 +949,97 @@ fn open_dialogs_count_once_per_library_change() { } assert_eq!(h.app.caches.dialog_count_scans, before + 3, "another dialog counts its own photos, once"); } + +/// Enter Keywords, with everything in its box replaced by `text`. +fn enter(h: &mut Headless, text: &str) { + ask(h, "ui.clickWidget", json!({"id": "keywordView:enter"})); + ask(h, "ui.clickWidget", json!({"id": "field:enterKeywords"})); + ask(h, "ui.key", json!({"key": "A", "cmd": true})); + ask(h, "ui.key", json!({"key": "Backspace"})); + if !text.is_empty() { + ask(h, "ui.text", json!({"text": text})); + } +} + +fn enter_focused(h: &Headless) -> bool { + h.view.ctx.memory(|m| m.has_focus(crate::text_field::id("field:enterKeywords"))) +} + +/// Given two selected photos, when Enter Keywords is chosen, then the box shows their keywords as +/// text in place of the chips; Return applies an edit to both photos as one undo step, and gives up +/// the cursor. +#[test] +fn enter_keywords_edits_the_selections_keywords_as_text() { + let (mut h, ids) = two_selected(); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:enter"})); + assert!(has(&h, "field:enterKeywords") && !has(&h, "keywordChip:beach"), "the text gives the chips way"); + enter(&mut h, "beach, Weddings*, harbour"); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(keywords_of(&h, ids[0]), ["beach", "Weddings", "harbour"]); + assert_eq!(keywords_of(&h, ids[1]), ["beach", "harbour"], "Weddings stays on the photo that had it"); + assert!(!enter_focused(&h), "Return gave up the cursor"); + ask(&mut h, "engine.execute", json!({"command": "edit.undo", "params": {}})); + assert_eq!(keywords_of(&h, ids[0]), ["beach", "Weddings"], "one undo takes the edit back"); + assert_eq!(keywords_of(&h, ids[1]), ["beach"]); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:keywords"})); + assert!(has(&h, "keywordChip:beach") && !has(&h, "field:enterKeywords"), "Keywords brings the chips back"); +} + +/// A keyword left out of the text is taken off every selected photo, a partial one keeps its photos +/// while its asterisk stays, and without its asterisk it goes to all of them. +#[test] +fn enter_keywords_removes_and_makes_a_partial_keyword_common() { + let (mut h, ids) = two_selected(); + enter(&mut h, "Weddings*"); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(keywords_of(&h, ids[0]), ["Weddings"]); + assert!(keywords_of(&h, ids[1]).is_empty(), "beach went from both"); + enter(&mut h, "Weddings"); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(keywords_of(&h, ids[1]), ["Weddings"], "without its asterisk it goes to both"); + enter(&mut h, ""); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(ids.iter().all(|id| keywords_of(&h, *id).is_empty()), "an empty box takes every keyword off"); +} + +/// Esc gives the edit up; leaving the box applies it, as Return does. +#[test] +fn enter_keywords_escape_gives_up_and_leaving_applies() { + let (mut h, ids) = two_selected(); + enter(&mut h, "sea"); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + assert_eq!(keywords_of(&h, ids[0]), ["beach", "Weddings"], "Esc changed nothing"); + assert_eq!(keywords_of(&h, ids[1]), ["beach"]); + enter(&mut h, "beach, Weddings*, sea"); + ask(&mut h, "ui.key", json!({"key": "Tab"})); + assert!(all_have(&h, &ids, "sea"), "leaving the box applied it"); +} + +/// An asterisk after a name that is not a keyword only some photos have is refused: the photos keep +/// their keywords, the box keeps the cursor and its text, and the refusal is said. +#[test] +fn enter_keywords_refuses_a_name_ending_in_an_asterisk() { + let (mut h, ids) = two_selected(); + enter(&mut h, "beach, Weddings*, sea*"); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(keywords_of(&h, ids[0]), ["beach", "Weddings"]); + assert_eq!(keywords_of(&h, ids[1]), ["beach"]); + assert!(enter_focused(&h), "the box keeps the cursor to put it right"); + assert!(h.app.ui.toast.as_ref().is_some_and(|(t, ..)| t.contains("asterisk") && t.contains("sea*")), "{:?}", h.app.ui.toast); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(all_have(&h, &ids, "sea"), "the text was kept and put right"); +} + +/// Another selection while the box is being edited gives the edit up: what was typed goes neither to +/// the photos it was typed for nor to the new selection. +#[test] +fn enter_keywords_gives_up_an_edit_when_the_selection_changes() { + let (mut h, ids) = two_selected(); + enter(&mut h, "beach, Weddings*, harbour"); + ask(&mut h, "engine.execute", json!({"command": "library.select", "params": {"ids": [ids[1]]}})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + let every: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + assert!(every.iter().all(|id| !keywords_of(&h, *id).contains(&"harbour".to_string())), "nobody got harbour"); + assert_eq!(keywords_of(&h, ids[0]), ["beach", "Weddings"]); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a9dd725236..ed019f08bf 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -711,7 +711,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-STACKS | Stacks (full) | P1 | ✅ | `crates/catalog/src/stacks.rs`, `cmd:stack.group`, `cmd:stack.split`, `cmd:stack.moveUp`, `cmd:stack.moveDown` | group / ungroup / toggle / set top / remove / auto by time / split / move up and down | | LRC-LIB-VC | Virtual copies | P1 | ✅ | `cmd:photo.virtualCopy` | ⌘' | | LRC-LIB-LABELS | Colour-label sets | P1 | ✅ | `cmd:label.sets`, `cmd:label.applySet`, `cmd:label.saveSet`, `cmd:label.deleteSet`, `cmd:label.setNames`, `crates/engine/src/cmd/manage.rs` | built-in Colors / Review sets + user sets (Photo ▸ Set Color Label, Edit Label Names… dialog); names written to and read from `xmp:Label` | -| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | +| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry); Enter Keywords (`keywordView:enter`, `field:enterKeywords`) shows the selection's keywords as text, commas between them and an asterisk after one only some selected photos have: Return or leaving the box applies the edit to the photos selected when it began as one undo step (a keyword left out comes off every one of them, a name typed goes to all of them, a marked keyword stays on the photos that have it and without its asterisk goes to all), Esc gives the edit up, another selection gives it up too, an asterisk after any other name is refused with the text kept, and containing keywords and synonyms stay out of the text (the rules for mixed keywords and for when an edit applies are LightCraft's own), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | | LRC-LIB-METADATA | Metadata panel & presets | P1 | ✅ | `cmd:photo.setMeta`, `cmd:metadata.savePreset`, `cmd:metadata.applyPreset`, `cmd:metadata.presets`, `cmd:metadata.deletePreset`, `cmd:dialog.captureTime` | IPTC core, accessibility, place, capture-time edit; copyright status (unknown / copyrighted / public domain), rights usage terms and copyright info URL (`photo.setMeta` `copyrightStatus`, `usageTerms`, `copyrightUrl`; XMP Rights Management fields, kept by "copyright only" exports, a smart-album rule); metadata presets (Photo → Metadata Preset, Save Metadata Preset… from the active photo; applied on import from Settings) | | LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step | | LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people From c5e15cdb1a2a551b55a76401721a8dbf436a7738 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:17:52 -0700 Subject: [PATCH 049/247] Keywords: Enter Keywords keeps names with commas or a final asterisk and applies on a view change A keyword whose name holds a comma is read back as one name, so an unchanged edit no longer splits it. A keyword on every selected photo whose name ends in an asterisk is kept instead of refused. Choosing another view while typing applies the edit, as leaving the box does; a refused edit comes back when Enter Keywords is chosen again. --- crates/ui-egui/src/panels/keywording.rs | 101 ++++++++++++++++++-- crates/ui-egui/src/panels/right/keywords.rs | 77 ++++++++++----- crates/ui-egui/src/tests/keywording.rs | 26 +++++ 3 files changed, 173 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index b77c2a6763..19a38a0816 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -733,21 +733,71 @@ impl Entered { } } +/// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except +/// where pieces of one line joined by their commas spell a keyword of `start` whose name holds a +/// comma (with or without its asterisk), which stays one name. +fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { + use lightcraft_catalog::keywords::{clean, same}; + let spells = |s: &str, c: &Chip| same(&clean(s), &c.path) || s.strip_suffix('*').is_some_and(|m| same(&clean(m), &c.path)); + let mut names = Vec::new(); + for line in text.split('\n') { + // each piece's byte range in the line + let mut pieces: Vec> = Vec::new(); + let mut from = 0; + for piece in line.split(',') { + pieces.push(from..from + piece.len()); + from += piece.len() + 1; + } + let mut i = 0; + while let Some(first) = pieces.get(i) { + // the most pieces that spell a keyword with commas + let joined = start + .iter() + .map(|c| c.path.matches(',').count()) + .filter(|&commas| commas > 0) + .filter_map(|commas| { + let last = pieces.get(i + commas)?; + let s = line.get(first.start..last.end)?.trim(); + start.iter().any(|c| spells(s, c)).then_some((commas, s)) + }) + .max_by_key(|&(commas, _)| commas); + let (commas, name) = joined.unwrap_or((0, line.get(first.clone()).unwrap_or_default().trim())); + if !name.is_empty() { + names.push(name); + } + i += commas + 1; + } + } + names +} + /// Reads the Enter Keywords `text` against `start`, the selection's keywords when the edit began. -/// Keywords are separated by commas or new lines. A keyword of `start` left out of the text is -/// taken off every selected photo. A name without an asterisk goes to every selected photo (a -/// keyword of `start` keeps its spelling, and a new name goes where `Catalog::typed_keyword` puts -/// it). A keyword only some photos have, still marked with its asterisk, stays on those photos -/// only. An asterisk after any other name is refused: the error is the name as typed. +/// Keywords are separated by commas or new lines; a keyword of `start` whose name holds a comma is +/// read as one name. A keyword of `start` left out of the text is taken off every selected photo. +/// A name without an asterisk goes to every selected photo (a keyword of `start` keeps its +/// spelling, and a new name goes where `Catalog::typed_keyword` puts it). A keyword only some +/// photos have, still marked with its asterisk, stays on those photos only. A keyword every photo +/// has whose own name ends in an asterisk is kept as it is. An asterisk after any other name is +/// refused: the error is the name as typed. pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result { use lightcraft_catalog::keywords::{clean, same}; let mut kept: Vec = Vec::new(); let mut add: Vec = Vec::new(); - for token in text.split([',', '\n']).map(str::trim).filter(|t| !t.is_empty()) { + for token in entered_names(start, text) { if let Some(marked) = token.strip_suffix('*') { - let name = clean(marked); - let partial = start.iter().find(|c| !c.on_all() && same(&c.path, &name)).ok_or_else(|| token.to_string())?; - kept.push(partial.path.clone()); + let (whole, name) = (clean(token), clean(marked)); + // a keyword on every photo named with the asterisk, or a partial one marked; one not + // named yet first, when the text could mean either + let on_all = |c: &Chip| c.on_all() && same(&c.path, &whole); + let partial = |c: &Chip| !c.on_all() && same(&c.path, &name); + let fresh = |c: &Chip| !kept.iter().any(|k| same(k, &c.path)); + let found = start + .iter() + .find(|c| fresh(c) && on_all(c)) + .or_else(|| start.iter().find(|c| fresh(c) && partial(c))) + .or_else(|| start.iter().find(|c| on_all(c) || partial(c))) + .ok_or_else(|| token.to_string())?; + kept.push(found.path.clone()); continue; } let typed = clean(token); @@ -1126,6 +1176,39 @@ mod tests { assert_eq!(entered(&c, &start, "beach, *"), Err("*".to_string())); } + /// A keyword whose name holds a comma is one name in the text: left as it is, it changes + /// nothing, and it can be marked, made common or taken off like any other. + #[test] + fn a_keyword_with_a_comma_is_one_name() { + let (c, ids) = library(&[&["Places|Paris, France", "beach", "Lyon, Rhône, France"], &["beach"]]); + let start = chips(&c, &ids); + let text = entered_text(&start); + assert_eq!(text, "beach, Lyon, Rhône, France*, Places|Paris, France*"); + assert_eq!(entered(&c, &start, &text), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "beach,\nPlaces | Paris, France * , Lyon, Rhône, France*"), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "beach, Places|Paris, France"), Ok(edit(&["Places|Paris, France"], &["Lyon, Rhône, France"]))); + assert_eq!(entered(&c, &start, "Paris, France"), Ok(edit(&["Paris", "France"], &["beach", "Lyon, Rhône, France", "Places|Paris, France"]))); + let (c, ids) = library(&[&["Paris, France"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default()), "on every photo"); + } + + /// A keyword on every photo whose own name ends in an asterisk is kept when the text is left as + /// it is; one only some photos have is marked with a second asterisk. + #[test] + fn a_keyword_ending_in_an_asterisk_is_kept() { + let (c, ids) = library(&[&["star*", "beach", "sea*"], &["star*", "beach"]]); + let start = chips(&c, &ids); + let text = entered_text(&start); + assert_eq!(text, "beach, sea**, star*"); + assert_eq!(entered(&c, &start, &text), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "beach, star*"), Ok(edit(&[], &["sea*"]))); + // a partial `star` beside a common `star*`: both read the same, each is kept once + let (c, ids) = library(&[&["star*", "star"], &["star*"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); + } + /// A new name goes inside the default parent, as one typed in the Add keyword box does. #[test] fn a_new_name_goes_inside_the_default_parent() { diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index 1b092f06ee..0be0f83b2b 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -135,7 +135,11 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { } ui.data_mut(|d| d.insert_temp(kid, text)); ui.add_space(8.0); + let view = app.ui.keywording_view; crate::panels::keywording::view_switch(app, ui); + if view == crate::state::KeywordingView::Enter && app.ui.keywording_view != view { + leave_enter_keywords(app, ui, &selection); + } ui.add_space(4.0); crate::panels::keywording::scope(app, ui, &selection); match app.ui.keywording_view { @@ -225,16 +229,58 @@ impl EnterEdit { } } +/// The Enter Keywords box's field. +const ENTER_FIELD: &str = "field:enterKeywords"; + +/// Where the Enter Keywords box keeps its edit between frames. +fn enter_id() -> egui::Id { + egui::Id::unique("kw-enter") +} + +/// Applies the Enter Keywords `edit` to the photos it was started on, as one undo step. Returns +/// whether it was applied (an edit that changes nothing is); a refusal is said. +fn apply_enter(app: &mut LightcraftApp, ctx: &egui::Context, edit: &EnterEdit) -> bool { + match crate::panels::keywording::entered(&app.session.catalog, &edit.start, &edit.text) { + Ok(change) if change.is_empty() => true, + Ok(change) => match app.run("photo.setMeta", json!({"ids": edit.ids, "addKeywords": change.add, "removeKeywords": change.remove})) { + Ok(_) => true, + Err(e) => { + app.toast_error(ctx, e); + false + } + }, + Err(name) => { + app.toast_error(ctx, crate::i18n::tr_format!("A keyword name can't end with an asterisk: “{name}”", name = name)); + false + } + } +} + +/// Another view chosen while the Enter Keywords box holds an edit: the edit is applied, as leaving +/// the box applies it, and the box gives up the cursor. An edit of another selection is given up. +/// A refused edit is kept, marked refused, and comes back when Enter Keywords is chosen again. +fn leave_enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { + let id = enter_id(); + ui.memory_mut(|m| m.surrender_focus(crate::text_field::id(ENTER_FIELD))); + let Some(mut edit) = ui.data(|d| d.get_temp::(id)) else { return }; + if edit.selection == crate::key_of(selection) && !apply_enter(app, ui.ctx(), &edit) { + edit.refused = true; + ui.data_mut(|d| d.insert_temp(id, edit)); + } else { + ui.data_mut(|d| d.remove::(id)); + } +} + /// Enter Keywords: the selection's keywords as text, separated by commas, one only some of the -/// photos have marked with an asterisk. Return or leaving the box applies the edit to the photos -/// selected when it started, as one undo step; Esc gives it up. Another selection while the box is -/// being edited gives the edit up too. A refused edit keeps its text and says why. +/// photos have marked with an asterisk. Return, leaving the box or choosing another view applies +/// the edit to the photos selected when it started, as one undo step; Esc gives it up. Another +/// selection while the box is being edited gives the edit up too. A refused edit keeps its text and +/// says why. fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { - const FIELD: &str = "field:enterKeywords"; - let id = egui::Id::unique("kw-enter"); + let id = enter_id(); let key = crate::key_of(selection); let chips = app.caches.keyword_chips(&app.session.catalog, selection); - let fid = crate::text_field::id(FIELD); + let fid = crate::text_field::id(ENTER_FIELD); let focused = ui.memory(|m| m.has_focus(fid)); let kept: Option = ui.data(|d| d.get_temp(id)); // (an edit of another selection is given up, never applied to this one) @@ -251,7 +297,7 @@ fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[Photo i.events.retain(|e| !plain(e)); found }); - let r = crate::text_field::TextField::multiline(FIELD, &mut edit.text) + let r = crate::text_field::TextField::multiline(ENTER_FIELD, &mut edit.text) .hint(crate::i18n::tr("Keywords, separated by commas")) .label(crate::i18n::tr("Enter Keywords")) .rows(2) @@ -266,20 +312,7 @@ fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[Photo } let mut done = false; if returned || r.committed() { - let applied = match crate::panels::keywording::entered(&app.session.catalog, &edit.start, &edit.text) { - Ok(change) if change.is_empty() => true, - Ok(change) => match app.run("photo.setMeta", json!({"ids": edit.ids, "addKeywords": change.add, "removeKeywords": change.remove})) { - Ok(_) => true, - Err(e) => { - app.toast_error(ui.ctx(), e); - false - } - }, - Err(name) => { - app.toast_error(ui.ctx(), crate::i18n::tr_format!("A keyword name can't end with an asterisk: “{name}”", name = name)); - false - } - }; + let applied = apply_enter(app, ui.ctx(), &edit); edit.refused = !applied; done = applied; if applied && returned { @@ -313,7 +346,7 @@ fn hold_list_in_place(ui: &mut egui::Ui, top: f32) { // (only the part of it in sight: the pointer on the top bar above a half-hidden box isn't on it) let old_box = Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + before).intersect(ui.clip_rect()); let on_box = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| old_box.contains(p)); - let typing = ui.memory(|m| ["field:keyword", "field:enterKeywords"].iter().any(|f| m.has_focus(crate::text_field::id(f)))); + let typing = ui.memory(|m| ["field:keyword", ENTER_FIELD].iter().any(|f| m.has_focus(crate::text_field::id(f)))); if on_box || typing { return; } diff --git a/crates/ui-egui/src/tests/keywording.rs b/crates/ui-egui/src/tests/keywording.rs index 130af6ee3d..0c9ba252e6 100644 --- a/crates/ui-egui/src/tests/keywording.rs +++ b/crates/ui-egui/src/tests/keywording.rs @@ -1015,6 +1015,32 @@ fn enter_keywords_escape_gives_up_and_leaving_applies() { assert!(all_have(&h, &ids, "sea"), "leaving the box applied it"); } +/// Choosing another view while typing applies the edit, as leaving the box does; Enter Keywords +/// chosen again shows the photos' keywords, not the old text. A refused edit comes back with it. +#[test] +fn enter_keywords_applies_an_edit_when_another_view_is_chosen() { + let (mut h, ids) = two_selected(); + enter(&mut h, "beach, Weddings*, sea"); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:containing"})); + assert!(all_have(&h, &ids, "sea"), "choosing another view applied it"); + assert!(!enter_focused(&h)); + ask(&mut h, "engine.execute", json!({"command": "photo.setMeta", "params": {"ids": [ids[1]], "removeKeywords": ["sea"]}})); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:enter"})); + ask(&mut h, "ui.clickWidget", json!({"id": "field:enterKeywords"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert_eq!(keywords_of(&h, ids[1]), ["beach"], "the old text did not come back to give sea again"); + enter(&mut h, "beach, harbour*"); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:keywords"})); + assert!(h.app.ui.toast.as_ref().is_some_and(|(t, ..)| t.contains("harbour*")), "{:?}", h.app.ui.toast); + assert!(none_has(&h, &ids, "harbour")); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordView:enter"})); + ask(&mut h, "ui.clickWidget", json!({"id": "field:enterKeywords"})); + ask(&mut h, "ui.key", json!({"key": "End", "cmd": true})); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(all_have(&h, &ids, "harbour"), "the refused text came back to be put right"); +} + /// An asterisk after a name that is not a keyword only some photos have is refused: the photos keep /// their keywords, the box keeps the cursor and its text, and the refusal is said. #[test] From 2af87a751023b9ad11a5100cb2572debf3bcf991 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:37:45 -0700 Subject: [PATCH 050/247] Keywords: Enter Keywords quotes a common name ending in an asterisk and joins a name with a comma once A keyword every selected photo has whose name ends in an asterisk is now written in double quotes, so it reads differently from a partial keyword of the same name marked with the asterisk, and either one can be taken off. A name in double quotes is read as written. Pieces of a line are joined into a keyword whose name holds a comma only while the text has not named that keyword yet, so reordering the text no longer drops the keywords its pieces spell. --- crates/ui-egui/src/panels/keywording.rs | 92 +++++++++++++++++++------ 1 file changed, 70 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 19a38a0816..08d5362378 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -712,9 +712,28 @@ pub(crate) fn chips(catalog: &Catalog, photos: &[PhotoId]) -> Vec { } /// The Enter Keywords text of the selection's keywords `chips`: each keyword's path, with commas -/// between them and an asterisk after a keyword only some of the selected photos have. +/// between them and an asterisk after a keyword only some of the selected photos have. A keyword +/// every photo has whose name ends in an asterisk, or is itself in double quotes, is written in +/// double quotes, so that it reads differently from a partial keyword marked with the asterisk. pub(crate) fn entered_text(chips: &[Chip]) -> String { - chips.iter().map(|c| if c.on_all() { c.path.clone() } else { format!("{}*", c.path) }).collect::>().join(", ") + chips + .iter() + .map(|c| { + if !c.on_all() { + format!("{}*", c.path) + } else if c.path.ends_with('*') || quoted(&c.path).is_some() { + format!("\"{}\"", c.path) + } else { + c.path.clone() + } + }) + .collect::>() + .join(", ") +} + +/// The name inside `token` when it is in double quotes. +fn quoted(token: &str) -> Option<&str> { + token.strip_prefix('"')?.strip_suffix('"') } /// What an edit of the Enter Keywords text gives to and takes off the selected photos. @@ -735,10 +754,14 @@ impl Entered { /// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except /// where pieces of one line joined by their commas spell a keyword of `start` whose name holds a -/// comma (with or without its asterisk), which stays one name. +/// comma (with or without its asterisk or its quotes) that the text has not named yet, which stays +/// one name. fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { use lightcraft_catalog::keywords::{clean, same}; - let spells = |s: &str, c: &Chip| same(&clean(s), &c.path) || s.strip_suffix('*').is_some_and(|m| same(&clean(m), &c.path)); + let spells = |s: &str, c: &Chip| [Some(s), s.strip_suffix('*'), quoted(s)].into_iter().flatten().any(|n| same(&clean(n), &c.path)); + // the keywords of `start` the text has named so far + let mut named = vec![false; start.len()]; + let unnamed = |s: &str, named: &[bool]| start.iter().zip(named).position(|(c, n)| !n && spells(s, c)); let mut names = Vec::new(); for line in text.split('\n') { // each piece's byte range in the line @@ -750,7 +773,7 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { } let mut i = 0; while let Some(first) = pieces.get(i) { - // the most pieces that spell a keyword with commas + // the most pieces that spell a keyword with commas not named yet let joined = start .iter() .map(|c| c.path.matches(',').count()) @@ -758,10 +781,13 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { .filter_map(|commas| { let last = pieces.get(i + commas)?; let s = line.get(first.start..last.end)?.trim(); - start.iter().any(|c| spells(s, c)).then_some((commas, s)) + unnamed(s, &named).map(|_| (commas, s)) }) .max_by_key(|&(commas, _)| commas); let (commas, name) = joined.unwrap_or((0, line.get(first.clone()).unwrap_or_default().trim())); + if let Some(n) = unnamed(name, &named) { + named[n] = true; + } if !name.is_empty() { names.push(name); } @@ -776,34 +802,39 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { /// read as one name. A keyword of `start` left out of the text is taken off every selected photo. /// A name without an asterisk goes to every selected photo (a keyword of `start` keeps its /// spelling, and a new name goes where `Catalog::typed_keyword` puts it). A keyword only some -/// photos have, still marked with its asterisk, stays on those photos only. A keyword every photo -/// has whose own name ends in an asterisk is kept as it is. An asterisk after any other name is -/// refused: the error is the name as typed. +/// photos have, still marked with its asterisk, stays on those photos only. A name in double +/// quotes is read as written, an asterisk at its end included. A keyword every photo has whose own +/// name ends in an asterisk is also kept when written without its quotes, unless a keyword only +/// some photos have reads the same. An asterisk after any other name is refused: the error is the +/// name as typed. pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result { use lightcraft_catalog::keywords::{clean, same}; let mut kept: Vec = Vec::new(); let mut add: Vec = Vec::new(); for token in entered_names(start, text) { - if let Some(marked) = token.strip_suffix('*') { + let literal = quoted(token); + if let Some(marked) = token.strip_suffix('*').filter(|_| literal.is_none()) { let (whole, name) = (clean(token), clean(marked)); - // a keyword on every photo named with the asterisk, or a partial one marked; one not - // named yet first, when the text could mean either + // a partial keyword marked, or else a keyword on every photo named with the asterisk; + // one not named yet first let on_all = |c: &Chip| c.on_all() && same(&c.path, &whole); let partial = |c: &Chip| !c.on_all() && same(&c.path, &name); let fresh = |c: &Chip| !kept.iter().any(|k| same(k, &c.path)); let found = start .iter() - .find(|c| fresh(c) && on_all(c)) - .or_else(|| start.iter().find(|c| fresh(c) && partial(c))) - .or_else(|| start.iter().find(|c| on_all(c) || partial(c))) + .find(|c| fresh(c) && partial(c)) + .or_else(|| start.iter().find(|c| fresh(c) && on_all(c))) + .or_else(|| start.iter().find(|c| partial(c) || on_all(c))) .ok_or_else(|| token.to_string())?; kept.push(found.path.clone()); continue; } - let typed = clean(token); + let written = literal.unwrap_or(token); + let typed = clean(written); let (name, on_all) = match start.iter().find(|c| same(&c.path, &typed)) { Some(c) => (c.path.clone(), c.on_all()), - None => (catalog.typed_keyword(token), false), + None if typed.ends_with('*') => return Err(token.to_string()), + None => (catalog.typed_keyword(written), false), }; if name.is_empty() { continue; @@ -1191,21 +1222,38 @@ mod tests { let (c, ids) = library(&[&["Paris, France"]]); let start = chips(&c, &ids); assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default()), "on every photo"); + // a name with a comma joins once; named again, its pieces are other keywords + let (c, ids) = library(&[&["a", "b", "a, b"]]); + let start = chips(&c, &ids); + assert_eq!(entered_text(&start), "a, a, b, b"); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "a, b, a, b"), Ok(Entered::default()), "reordered"); + assert_eq!(entered(&c, &start, "a, b, a"), Ok(edit(&[], &["b"]))); } - /// A keyword on every photo whose own name ends in an asterisk is kept when the text is left as - /// it is; one only some photos have is marked with a second asterisk. + /// A keyword on every photo whose own name ends in an asterisk is written in quotes and kept when + /// the text is left as it is; one only some photos have is marked with a second asterisk. #[test] fn a_keyword_ending_in_an_asterisk_is_kept() { let (c, ids) = library(&[&["star*", "beach", "sea*"], &["star*", "beach"]]); let start = chips(&c, &ids); let text = entered_text(&start); - assert_eq!(text, "beach, sea**, star*"); + assert_eq!(text, "beach, sea**, \"star*\""); assert_eq!(entered(&c, &start, &text), Ok(Entered::default())); - assert_eq!(entered(&c, &start, "beach, star*"), Ok(edit(&[], &["sea*"]))); - // a partial `star` beside a common `star*`: both read the same, each is kept once + assert_eq!(entered(&c, &start, "beach, star*"), Ok(edit(&[], &["sea*"])), "without its quotes"); + assert_eq!(entered(&c, &start, "beach, \"sea*\", \"star*\""), Ok(edit(&["sea*"], &[])), "a quoted partial goes to all"); + assert_eq!(entered(&c, &start, "beach, \"harbour*\""), Err("\"harbour*\"".to_string()), "a new name with an asterisk"); + // a partial `star` beside a common `star*`: each reads differently, and either can go let (c, ids) = library(&[&["star*", "star"], &["star*"]]); let start = chips(&c, &ids); + assert_eq!(entered_text(&start), "star*, \"star*\""); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "\"star*\""), Ok(edit(&[], &["star"]))); + assert_eq!(entered(&c, &start, "star*"), Ok(edit(&[], &["star*"]))); + // a keyword every photo has that is itself in quotes keeps them + let (c, ids) = library(&[&["\"quoted\""]]); + let start = chips(&c, &ids); + assert_eq!(entered_text(&start), "\"\"quoted\"\""); assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); } From 04d8efd0e0c2f91beeae0bf418c2fd7603c9fd43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:56:32 -0700 Subject: [PATCH 051/247] Keywords: Enter Keywords reads a keyword holding a line break as one name A keyword whose name holds a new line, such as one set through photo.setMeta or read from a sidecar, was split into its lines when the unchanged Enter Keywords text was applied: the keyword was removed and its pieces added. The text is now cut at commas and new lines alike, and pieces that spell a keyword of the selection holding that many separators stay one name, as a keyword holding a comma does. --- crates/ui-egui/src/panels/keywording.rs | 76 +++++++++++++++---------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 08d5362378..75504aee38 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -753,46 +753,45 @@ impl Entered { } /// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except -/// where pieces of one line joined by their commas spell a keyword of `start` whose name holds a -/// comma (with or without its asterisk or its quotes) that the text has not named yet, which stays -/// one name. +/// where pieces joined by their separators spell a keyword of `start` whose name holds a comma or a +/// new line (with or without its asterisk or its quotes) that the text has not named yet, which +/// stays one name. fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { use lightcraft_catalog::keywords::{clean, same}; + let is_separator = |ch: char| ch == ',' || ch == '\n'; let spells = |s: &str, c: &Chip| [Some(s), s.strip_suffix('*'), quoted(s)].into_iter().flatten().any(|n| same(&clean(n), &c.path)); // the keywords of `start` the text has named so far let mut named = vec![false; start.len()]; let unnamed = |s: &str, named: &[bool]| start.iter().zip(named).position(|(c, n)| !n && spells(s, c)); + // each piece's byte range in the text + let mut pieces: Vec> = Vec::new(); + let mut from = 0; + for piece in text.split(is_separator) { + pieces.push(from..from + piece.len()); + from += piece.len() + 1; + } let mut names = Vec::new(); - for line in text.split('\n') { - // each piece's byte range in the line - let mut pieces: Vec> = Vec::new(); - let mut from = 0; - for piece in line.split(',') { - pieces.push(from..from + piece.len()); - from += piece.len() + 1; + let mut i = 0; + while let Some(first) = pieces.get(i) { + // the most pieces that spell a keyword with separators not named yet + let joined = start + .iter() + .map(|c| c.path.matches(is_separator).count()) + .filter(|&separators| separators > 0) + .filter_map(|separators| { + let last = pieces.get(i + separators)?; + let s = text.get(first.start..last.end)?.trim(); + unnamed(s, &named).map(|_| (separators, s)) + }) + .max_by_key(|&(separators, _)| separators); + let (separators, name) = joined.unwrap_or((0, text.get(first.clone()).unwrap_or_default().trim())); + if let Some(n) = unnamed(name, &named) { + named[n] = true; } - let mut i = 0; - while let Some(first) = pieces.get(i) { - // the most pieces that spell a keyword with commas not named yet - let joined = start - .iter() - .map(|c| c.path.matches(',').count()) - .filter(|&commas| commas > 0) - .filter_map(|commas| { - let last = pieces.get(i + commas)?; - let s = line.get(first.start..last.end)?.trim(); - unnamed(s, &named).map(|_| (commas, s)) - }) - .max_by_key(|&(commas, _)| commas); - let (commas, name) = joined.unwrap_or((0, line.get(first.clone()).unwrap_or_default().trim())); - if let Some(n) = unnamed(name, &named) { - named[n] = true; - } - if !name.is_empty() { - names.push(name); - } - i += commas + 1; + if !name.is_empty() { + names.push(name); } + i += separators + 1; } names } @@ -1231,6 +1230,21 @@ mod tests { assert_eq!(entered(&c, &start, "a, b, a"), Ok(edit(&[], &["b"]))); } + /// A keyword whose name holds a new line is read as one name, as one holding a comma is. + #[test] + fn a_keyword_with_a_line_break_is_one_name() { + let (c, ids) = library(&[&["a\nb", "beach", "x,\ny"], &["beach"]]); + let start = chips(&c, &ids); + let text = entered_text(&start); + assert_eq!(text, "a\nb*, beach, x,\ny*"); + assert_eq!(entered(&c, &start, &text), Ok(Entered::default())); + assert_eq!(entered(&c, &start, "beach, a\nb"), Ok(edit(&["a\nb"], &["x,\ny"]))); + assert_eq!(entered(&c, &start, "beach\na"), Ok(edit(&["a"], &["a\nb", "x,\ny"]))); + let (c, ids) = library(&[&["a\nb"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default()), "on every photo"); + } + /// A keyword on every photo whose own name ends in an asterisk is written in quotes and kept when /// the text is left as it is; one only some photos have is marked with a second asterisk. #[test] From 660be841ca718be7d8b748ffae3e6ceddebb313f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:30:04 -0700 Subject: [PATCH 052/247] LRC-PRINT-TEMPLATES: the Template Browser has folders, and a template can be dragged into one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Print dialog's templates are listed in folders: User Templates, which always exists, and folders made with New Folder… (a button beside Save, or a folder's context menu). Each folder opens and closes. Save and Import… put a template in the folder chosen beside them, and a template dragged onto a folder, or moved with its Move to Folder menu, moves there with its name and settings unchanged. Rename Folder… and Delete Folder work on every folder but User Templates. Deleting a folder asks first and moves its templates to User Templates. New commands: print.template.move and print.template.folder.create, rename and delete. print.template.list gives the folders and each template's folder; print.template.save and print.template.import take an optional folder. A save over an existing name keeps its folder unless one is given. Folders, empty ones included, are kept in the library's prefs.json; templates saved before are in User Templates, and .lcprint files stay version 1 without the folder. --- crates/engine/src/cmd/print.rs | 188 ++++++++++++-- crates/engine/src/lib.rs | 4 + crates/engine/src/library.rs | 5 + crates/engine/src/print/template.rs | 61 ++++- crates/engine/src/tests/print.rs | 183 +++++++++++++- crates/ui-egui/locales/cs-formats.json | 1 + crates/ui-egui/locales/cs.json | 6 +- crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/de.json | 6 +- crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/es.json | 6 +- crates/ui-egui/locales/fi-formats.json | 1 + crates/ui-egui/locales/fi.json | 6 +- crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/fr.json | 6 +- crates/ui-egui/locales/id-formats.json | 1 + crates/ui-egui/locales/id.json | 6 +- crates/ui-egui/locales/it-formats.json | 1 + crates/ui-egui/locales/it.json | 6 +- crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/ja.json | 6 +- crates/ui-egui/locales/ka-formats.json | 1 + crates/ui-egui/locales/ka.json | 6 +- crates/ui-egui/locales/pl-formats.json | 1 + crates/ui-egui/locales/pl.json | 6 +- crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/pt-br.json | 6 +- crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/ru.json | 6 +- crates/ui-egui/locales/sv-formats.json | 1 + crates/ui-egui/locales/sv.json | 6 +- crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/uk.json | 6 +- crates/ui-egui/locales/vi-formats.json | 1 + crates/ui-egui/locales/vi.json | 6 +- crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hans.json | 6 +- crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/locales/zh-hant.json | 6 +- crates/ui-egui/src/dialogs/print_view.rs | 263 +++++++++++++++++++- crates/ui-egui/src/tests/print.rs | 121 +++++++++ docs/parity-checklist.md | 3 +- 42 files changed, 902 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 1390ca1677..e9e8a9cbff 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -8,12 +8,15 @@ //! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset` //! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear` //! * `print.exportPdf {path, ids?}` -//! * `print.template.list|save|apply|delete`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.list|save|apply|delete|move`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.folder.create|rename|delete`: the Template Browser's folders use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, f64_req}; use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size}; -use crate::print::template::{FILE_EXT, MAX_FILE, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name, unique_name}; +use crate::print::template::{ + DEFAULT_FOLDER, FILE_EXT, MAX_FILE, MAX_FOLDERS, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_folder, clean_name, sort_folders, unique_name, +}; use crate::{Result, Session}; fn rect_json(r: &Rect) -> Value { @@ -270,18 +273,65 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { // ---- templates ------------------------------------------------------------------------------ fn template_list(s: &Session) -> Value { - json!({"templates": s.print_templates.iter().map(|t| json!({"name": t.name, "style": t.settings.pointer("/layout/style"), "settings": t.settings})).collect::>()}) + let count = |f: Option<&str>| s.print_templates.iter().filter(|t| t.folder.as_deref() == f).count(); + let folders = std::iter::once(json!({"name": DEFAULT_FOLDER, "default": true, "templates": count(None)})) + .chain(s.print_template_folders.iter().map(|f| json!({"name": f, "default": false, "templates": count(Some(f))}))); + json!({ + "folders": folders.collect::>(), + "templates": s.print_templates.iter().map(|t| json!({ + "name": t.name, + "folder": t.folder.as_deref().unwrap_or(DEFAULT_FOLDER), + "style": t.settings.pointer("/layout/style"), + "settings": t.settings, + })).collect::>(), + }) } fn template_name(p: &Value, id: &str) -> Result { clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e)) } -/// Save the preferences after a change to the templates; if that fails, the templates go back to -/// `before`, so the list matches what is saved and a retry does the same thing. -fn save_templates(s: &mut Session, before: Vec) -> Result<()> { +/// The folder `name` names: `None` for [`DEFAULT_FOLDER`], else the listed folder's spelling. +fn find_folder(s: &Session, name: &str, id: &str) -> Result> { + let name = name.trim(); + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Ok(None); + } + s.print_template_folders + .iter() + .find(|f| f.eq_ignore_ascii_case(name)) + .cloned() + .map(Some) + .ok_or_else(|| bad(id, format!("no print template folder `{name}` (see print.template.list)"))) +} + +/// The `folder` parameter: not given (`None`), or the folder it names (see [`find_folder`]). +fn folder_param(s: &Session, p: &Value, id: &str) -> Result>> { + match p.get("folder") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(f)) => find_folder(s, f, id).map(Some), + Some(_) => Err(bad(id, "`folder` must be a folder name")), + } +} + +/// A user folder named by `key`: the listed folder's spelling. [`DEFAULT_FOLDER`] is refused. +fn user_folder(s: &Session, p: &Value, key: &str, id: &str) -> Result { + let name = p.get(key).and_then(Value::as_str).ok_or_else(|| bad(id, format!("missing `{key}`")))?; + find_folder(s, name, id)?.ok_or_else(|| bad(id, format!("“{DEFAULT_FOLDER}” can't be renamed or deleted"))) +} + +/// The templates and folders before a change, put back by [`save_templates`] when it fails. +type Before = (Vec, Vec); + +fn before(s: &Session) -> Before { + (s.print_templates.clone(), s.print_template_folders.clone()) +} + +/// Save the preferences after a change to the templates or folders; if that fails, both go back +/// to `before`, so the list matches what is saved and a retry does the same thing. +fn save_templates(s: &mut Session, before: Before) -> Result<()> { if let Err(e) = s.save_prefs() { - s.print_templates = before; + (s.print_templates, s.print_template_folders) = before; return Err(e); } Ok(()) @@ -290,14 +340,20 @@ fn save_templates(s: &mut Session, before: Vec) -> Result<()> { fn template_save(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.save"; let name = template_name(p, ID)?; - let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; - let before = s.print_templates.clone(); + let folder = folder_param(s, p, ID)?; + let mut t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; + let before = before(s); match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) { - Some(x) => *x = t, + Some(x) => { + // a replaced template stays in its folder unless the call names another + t.folder = folder.unwrap_or_else(|| x.folder.clone()); + *x = t; + } None => { if s.print_templates.len() >= MAX_TEMPLATES { return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first"))); } + t.folder = folder.flatten(); s.print_templates.push(t); } } @@ -305,6 +361,90 @@ fn template_save(s: &mut Session, p: &Value) -> Result { Ok(template_list(s)) } +fn template_move(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.move"; + let name = template_name(p, ID)?; + let folder = folder_param(s, p, ID)?.ok_or_else(|| bad(ID, "missing `folder`"))?; + let i = s + .print_templates + .iter() + .position(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?; + let moved = s.print_templates.get(i).is_some_and(|t| t.folder != folder); + if moved { + let before = before(s); + if let Some(t) = s.print_templates.get_mut(i) { + t.folder = folder; + } + save_templates(s, before)?; + } + let mut out = template_list(s); + out["moved"] = json!(moved); + Ok(out) +} + +fn folder_create(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.create"; + let name = clean_folder(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `name`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&name)) { + return Err(bad(ID, format!("there is already a folder named “{name}”"))); + } + if s.print_template_folders.len() >= MAX_FOLDERS { + return Err(bad(ID, format!("at most {MAX_FOLDERS} folders; delete one first"))); + } + let before = before(s); + s.print_template_folders.push(name.clone()); + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(name); + Ok(out) +} + +fn folder_rename(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.rename"; + let from = user_folder(s, p, "name", ID)?; + let to = clean_folder(p.get("to").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `to`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&to) && *f != from) { + return Err(bad(ID, format!("there is already a folder named “{to}”"))); + } + let before = before(s); + for f in &mut s.print_template_folders { + if *f == from { + f.clone_from(&to); + } + } + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(from.as_str()) { + t.folder = Some(to.clone()); + } + } + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(to); + Ok(out) +} + +fn folder_delete(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.delete"; + let name = user_folder(s, p, "name", ID)?; + let before = before(s); + s.print_template_folders.retain(|f| *f != name); + let mut moved = 0usize; + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(name.as_str()) { + t.folder = None; + moved += 1; + } + } + save_templates(s, before)?; + let mut out = template_list(s); + out["deleted"] = json!(name); + out["moved"] = json!(moved); + Ok(out) +} + fn template_apply(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.apply"; let name = template_name(p, ID)?; @@ -320,9 +460,9 @@ fn template_apply(s: &mut Session, p: &Value) -> Result { fn template_delete(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.delete"; let name = template_name(p, ID)?; - let before = s.print_templates.clone(); + let before = before(s); s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name)); - if s.print_templates.len() == before.len() { + if s.print_templates.len() == before.0.len() { return Err(bad(ID, format!("no print template `{name}`"))); } save_templates(s, before)?; @@ -356,6 +496,7 @@ fn template_export(s: &mut Session, p: &Value) -> Result { fn template_import(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.import"; let path = std::path::Path::new(template_path(p, ID)?); + let folder = folder_param(s, p, ID)?.flatten(); let meta = std::fs::metadata(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; if !meta.is_file() { return Err(bad(ID, format!("{}: not a file", path.display()))); @@ -371,7 +512,8 @@ fn template_import(s: &mut Session, p: &Value) -> Result { let name = unique_name(&t.name, &s.print_templates); let renamed = name != t.name; t.name = name.clone(); - let before = s.print_templates.clone(); + t.folder = folder; + let before = before(s); s.print_templates.push(t); save_templates(s, before)?; let mut out = template_list(s); @@ -405,17 +547,31 @@ pub fn specs() -> Vec { cmd!(query "print.exportPdf", "Print to PDF", [], None, "{path, ids?: photo ids (default selection)} → {path, pages, photos, bytes}; prints the current print.get settings; replaces an existing output, never an original", always, export_pdf), - cmd!(query "print.template.list", "Print Templates", [], None, "{} → {templates: [{name, style, settings}]}", always, |s, _| Ok(template_list(s))), + cmd!(query "print.template.list", "Print Templates", [], None, + "{} → {folders: [{name, default, templates: count}] (\"User Templates\" first, then the others by name), templates: [{name, folder, style, settings}]}", + always, |s, _| Ok(template_list(s))), cmd!(query "print.template.save", "Save Print Template", [], None, - "{name} — saves the layout, image settings, page and job (not the cells' photos or the guides); an existing name (any case) is replaced → print.template.list", + "{name, folder?} — saves the layout, image settings, page and job (not the cells' photos or the guides) in `folder` (default \"User Templates\"); an existing name (any case) is replaced and stays in its folder unless `folder` is given → print.template.list", always, template_save), cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply), cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete), + cmd!(query "print.template.move", "Move Print Template to Folder", [], None, + "{name, folder} — lists the template in another Template Browser folder (\"User Templates\" or one made with print.template.folder.create); its name and settings stay → print.template.list + {moved: false when it was already there}", + always, template_move), + cmd!(query "print.template.folder.create", "New Print Template Folder", [], None, + "{name} — a Template Browser folder (1 to 80 characters, not \"User Templates\", unique in any case, at most 100); kept while empty → print.template.list + {name}", + always, folder_create), + cmd!(query "print.template.folder.rename", "Rename Print Template Folder", [], None, + "{name, to} — renames a folder and keeps its templates in it; \"User Templates\" can't be renamed → print.template.list + {name}", + always, folder_rename), + cmd!(query "print.template.folder.delete", "Delete Print Template Folder", [], None, + "{name} — deletes a folder; its templates move to \"User Templates\", which can't be deleted → print.template.list + {deleted, moved: templates moved}", + always, folder_delete), cmd!(query "print.template.export", "Export Print Template", [], None, "{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}", always, template_export), cmd!(query "print.template.import", "Import Print Template", [], None, - "{path: a .lcprint file (at most 256 KB)}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", + "{path: a .lcprint file (at most 256 KB), folder? (default \"User Templates\")}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", always, template_import), ] } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 163a102680..3135cc1dfc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -346,6 +346,9 @@ pub struct Session { pub print: print::template::PrintSettings, /// Saved print templates (`print.template.*`), persisted in prefs.json. pub print_templates: Vec, + /// The Template Browser's folders besides [`print::template::DEFAULT_FOLDER`], sorted by name + /// (`print.template.folder.*`), persisted in prefs.json. + pub print_template_folders: Vec, /// Metadata presets (`metadata.*`), persisted in prefs.json. pub metadata_presets: Vec, /// Saved filter-bar settings (`filter.*`), persisted in prefs.json. @@ -507,6 +510,7 @@ impl Session { export_presets: Vec::new(), print: Default::default(), print_templates: Vec::new(), + print_template_folders: Vec::new(), metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index caf51a0ab6..3535e6a464 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -263,6 +263,8 @@ struct PrefsFile { export_presets: Vec, /// Print templates. print_templates: Vec, + /// Print Template Browser folders, empty ones included. + print_template_folders: Vec, /// Metadata presets. metadata_presets: Vec, /// Filter presets. @@ -547,6 +549,8 @@ impl Session { self.last_merge = prefs.last_merge; self.export_presets = prefs.export_presets; self.print_templates = prefs.print_templates; + self.print_template_folders = prefs.print_template_folders; + crate::print::template::tidy_folders(&mut self.print_template_folders, &mut self.print_templates); self.metadata_presets = prefs.metadata_presets; self.filter_presets = prefs.filter_presets; self.curve_presets = prefs.curve_presets; @@ -827,6 +831,7 @@ impl Session { last_merge: self.last_merge.clone(), export_presets: self.export_presets.clone(), print_templates: self.print_templates.clone(), + print_template_folders: self.print_template_folders.clone(), metadata_presets: self.metadata_presets.clone(), filter_presets: self.filter_presets.clone(), curve_presets: self.curve_presets.clone(), diff --git a/crates/engine/src/print/template.rs b/crates/engine/src/print/template.rs index 7bb5336129..6a98aec5ad 100644 --- a/crates/engine/src/print/template.rs +++ b/crates/engine/src/print/template.rs @@ -38,6 +38,11 @@ const FILE_FORMAT: &str = "lightcraft.printTemplate"; const FILE_VERSION: u64 = 1; /// Largest template file read, bytes. pub const MAX_FILE: u64 = 256 * 1024; +/// The Template Browser folder a template is in until it is moved to another. It always exists +/// and can't be renamed or deleted. +pub const DEFAULT_FOLDER: &str = "User Templates"; +/// Most Template Browser folders kept, besides [`DEFAULT_FOLDER`]. +pub const MAX_FOLDERS: usize = 100; /// A saved print template: the layout, image settings, page and job of a print, without the /// photos assigned to cells and without the guides (a view preference). The settings are kept as @@ -47,9 +52,59 @@ pub const MAX_FILE: u64 = 256 * 1024; #[serde(rename_all = "camelCase")] pub struct PrintTemplate { pub name: String, + /// The Template Browser folder the template is listed in; `None`: [`DEFAULT_FOLDER`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, pub settings: serde_json::Value, } +/// A folder name: trimmed, 1 to [`MAX_NAME`] characters, no control characters, and not +/// [`DEFAULT_FOLDER`] in any case. +pub fn clean_folder(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) { + return Err(format!("a folder name is 1 to {MAX_NAME} characters without control characters")); + } + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Err(format!("“{DEFAULT_FOLDER}” is always there; choose another name")); + } + Ok(name.to_string()) +} + +/// Sorts `folders` by name, ignoring case. +pub fn sort_folders(folders: &mut [String]) { + folders.sort_by_cached_key(|f| f.to_lowercase()); +} + +/// Makes folders and templates read from the preferences consistent: folders with a bad, reserved +/// or repeated name and those past [`MAX_FOLDERS`] are dropped; a template in a folder that isn't +/// listed gets the folder listed when its name is good and there is room, and goes to +/// [`DEFAULT_FOLDER`] otherwise; each template's folder takes the listed folder's spelling. +pub fn tidy_folders(folders: &mut Vec, templates: &mut [PrintTemplate]) { + let mut kept: Vec = Vec::new(); + for f in folders.iter() { + if let Ok(f) = clean_folder(f) + && kept.len() < MAX_FOLDERS + && !kept.iter().any(|k| k.eq_ignore_ascii_case(&f)) + { + kept.push(f); + } + } + for t in templates.iter_mut() { + let Some(f) = t.folder.take() else { continue }; + if let Some(k) = kept.iter().find(|k| k.eq_ignore_ascii_case(f.trim())) { + t.folder = Some(k.clone()); + } else if let Ok(f) = clean_folder(&f) + && kept.len() < MAX_FOLDERS + { + kept.push(f.clone()); + t.folder = Some(f); + } + } + sort_folders(&mut kept); + *folders = kept; +} + /// A template name: trimmed, 1 to [`MAX_NAME`] characters, no control characters. pub fn clean_name(name: &str) -> Result { let name = name.trim(); @@ -71,7 +126,7 @@ impl PrintTemplate { if let Some(o) = value.as_object_mut() { o.remove("guides"); } - Ok(Self { name: clean_name(name)?, settings: value }) + Ok(Self { name: clean_name(name)?, folder: None, settings: value }) } /// The settings, checked: unknown fields, hostile numbers and inconsistent layouts are errors. @@ -106,7 +161,7 @@ impl PrintTemplate { } let name = clean_name(v.get("name").and_then(serde_json::Value::as_str).ok_or("a print template file needs a `name`")?)?; let settings = v.get("settings").cloned().ok_or("a print template file needs `settings`")?; - let checked = PrintTemplate { name: name.clone(), settings }.settings(&Guides::default())?; + let checked = PrintTemplate { name: name.clone(), folder: None, settings }.settings(&Guides::default())?; Self::new(&name, &checked) } } @@ -163,7 +218,7 @@ mod tests { for name in ["", " ", "a\nb", &"x".repeat(MAX_NAME + 1)] { assert!(PrintTemplate::new(name, &PrintSettings::default()).is_err(), "{name:?}"); } - let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), settings: v }.settings(&Guides::default()).is_err(); + let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), folder: None, settings: v }.settings(&Guides::default()).is_err(); assert!(bad(json!("text"))); assert!(bad(json!({"surprise": 1}))); assert!(bad(json!({"job": {"ppi": 1e30}}))); diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index 5a35adb5ba..e663b62e80 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -410,6 +410,173 @@ fn templates_export_to_a_file_and_import_from_one() { assert!(fails(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})).contains("at most")); } +/// The names of the folders `print.template.list` gives, User Templates first. +fn folder_names(r: &Value) -> Vec { + r["folders"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap().to_string()).collect() +} + +/// Each template's name and folder, in the order `print.template.list` gives them. +fn template_folders(r: &Value) -> Vec<(String, String)> { + r["templates"].as_array().unwrap().iter().map(|t| (t["name"].as_str().unwrap().into(), t["folder"].as_str().unwrap().into())).collect() +} + +fn pair(name: &str, folder: &str) -> (String, String) { + (name.into(), folder.into()) +} + +#[test] +fn template_folders_hold_templates_and_survive_reopening() { + let files = MemStore::new(); + let open = |files: &MemStore| { + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + s + }; + let mut s = open(&files); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(r["folders"], json!([{"name": "User Templates", "default": true, "templates": 0}])); + + // a folder is kept while it is empty, and the folders are listed by name after User Templates + let r = run(&mut s, "print.template.folder.create", json!({"name": " Weddings "})); + assert_eq!(r["name"], "Weddings"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Proofs", "Weddings"], "{r}"); + + // a template is saved into a folder, or into User Templates when none is named + run(&mut s, "print.set", json!({"layout": {"style": "contactSheet", "grid": {"columns": 4, "rows": 5}}})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "weddings"})); + let r = run(&mut s, "print.template.save", json!({"name": "Plain"})); + assert_eq!(template_folders(&r), [pair("Sheet", "Weddings"), pair("Plain", "User Templates")]); + assert_eq!(r["folders"][2], json!({"name": "Weddings", "default": false, "templates": 1})); + // saving over a name keeps its folder unless the call names another + run(&mut s, "print.set", json!({"layout": {"grid": {"columns": 6}}})); + let r = run(&mut s, "print.template.save", json!({"name": "sheet"})); + assert_eq!(template_folders(&r), [pair("sheet", "Weddings"), pair("Plain", "User Templates")]); + let r = run(&mut s, "print.template.save", json!({"name": "Plain", "folder": "Proofs"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "Proofs")); + + // a move changes only the folder; a move to where it is already does nothing + let settings = r["templates"][0]["settings"].clone(); + let r = run(&mut s, "print.template.move", json!({"name": "SHEET", "folder": "Proofs"})); + assert_eq!((r["moved"].as_bool(), template_folders(&r)[0].clone()), (Some(true), pair("sheet", "Proofs"))); + assert_eq!(r["templates"][0]["settings"], settings); + let r = run(&mut s, "print.template.move", json!({"name": "Sheet", "folder": "proofs"})); + assert_eq!(r["moved"], false); + let r = run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "user templates"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "Weddings"})); + + // a rename takes the folder's templates along; a change of case is a rename too + let r = run(&mut s, "print.template.folder.rename", json!({"name": "proofs", "to": "Contact Sheets"})); + assert_eq!(folder_names(&r), ["User Templates", "Contact Sheets", "Weddings"]); + assert_eq!(template_folders(&r)[0], pair("sheet", "Contact Sheets")); + let r = run(&mut s, "print.template.folder.rename", json!({"name": "contact sheets", "to": "contact sheets"})); + assert_eq!(template_folders(&r)[0], pair("sheet", "contact sheets")); + + // the folders and where each template is survive reopening the library + let mut again = open(&files); + let r = run(&mut again, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets", "Weddings"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "Weddings")]); + run(&mut again, "print.template.apply", json!({"name": "Sheet"})); + assert_eq!(again.print.layout.grid.columns, 6); + + // deleting a folder keeps its templates: they go to User Templates + let r = run(&mut s, "print.template.folder.delete", json!({"name": "WEDDINGS"})); + assert_eq!((r["deleted"].as_str(), r["moved"].as_u64()), (Some("Weddings"), Some(1))); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "User Templates")]); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + + // refusals change nothing + let before = run(&mut s, "print.template.list", json!({})); + for (id, p, why) in [ + ("print.template.folder.create", json!({}), "missing `name`"), + ("print.template.folder.create", json!({"name": " "}), "folder name"), + ("print.template.folder.create", json!({"name": "a\tb"}), "folder name"), + ("print.template.folder.create", json!({"name": "x".repeat(81)}), "folder name"), + ("print.template.folder.create", json!({"name": "user templates"}), "always there"), + ("print.template.folder.create", json!({"name": "Contact Sheets"}), "already a folder"), + ("print.template.folder.rename", json!({"name": "User Templates", "to": "Mine"}), "can't be renamed"), + ("print.template.folder.rename", json!({"name": "Nope", "to": "Mine"}), "no print template folder"), + ("print.template.folder.rename", json!({"name": "contact sheets"}), "missing `to`"), + ("print.template.folder.rename", json!({"name": "contact sheets", "to": "User Templates"}), "always there"), + ("print.template.folder.delete", json!({"name": "User Templates"}), "can't be renamed or deleted"), + ("print.template.folder.delete", json!({"name": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet"}), "missing `folder`"), + ("print.template.move", json!({"name": "Sheet", "folder": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet", "folder": 3}), "`folder` must be"), + ("print.template.move", json!({"name": "Nope", "folder": "User Templates"}), "no print template `Nope`"), + ("print.template.save", json!({"name": "New", "folder": "Nope"}), "no print template folder"), + ("print.template.import", json!({"path": "x.lcprint", "folder": "Nope"}), "no print template folder"), + ] { + let e = fails(&mut s, id, p.clone()); + assert!(e.contains(why), "{id} {p}: {e}"); + } + run(&mut s, "print.template.folder.create", json!({"name": "Second"})); + assert!(fails(&mut s, "print.template.folder.rename", json!({"name": "second", "to": "CONTACT SHEETS"})).contains("already a folder")); + run(&mut s, "print.template.folder.delete", json!({"name": "Second"})); + assert_eq!(run(&mut s, "print.template.list", json!({})), before); + + // a full list of folders takes no more + while s.print_template_folders.len() < crate::print::template::MAX_FOLDERS { + let n = s.print_template_folders.len(); + run(&mut s, "print.template.folder.create", json!({"name": format!("F{n}")})); + } + assert!(fails(&mut s, "print.template.folder.create", json!({"name": "One more"})).contains("at most")); +} + +#[test] +fn templates_import_into_a_folder_and_export_without_it() { + let mut s = Session::with_demo(); + let scratch = Scratch::new("folders"); + let file = scratch.0.join("proofs.lcprint"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "Proofs"})); + run(&mut s, "print.template.export", json!({"name": "Sheet", "path": file.to_string_lossy()})); + let doc: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let mut keys: Vec<&String> = doc.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!(keys, ["format", "name", "settings", "version"], "a .lcprint file stays version 1, without the folder"); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})); + assert_eq!(template_folders(&r)[1], pair("Sheet (2)", "User Templates")); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy(), "folder": "proofs"})); + assert_eq!(template_folders(&r)[2], pair("Sheet (3)", "Proofs")); +} + +#[test] +fn templates_from_before_folders_are_in_user_templates() { + let files = MemStore::new(); + let old = json!({"printTemplates": [ + {"name": "Old", "settings": {"layout": {"style": "contactSheet"}}}, + {"name": "Kept", "folder": "Family", "settings": {}}, + {"name": "Spelled", "folder": " family ", "settings": {}}, + {"name": "Bad", "folder": "a\nb", "settings": {}}, + {"name": "Reserved", "folder": "USER TEMPLATES", "settings": {}} + ], "printTemplateFolders": ["Empty", "", "empty", "User Templates", "Family"]}); + files.set("prefs.json", serde_json::to_vec(&old).unwrap()); + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + assert!(s.take_library_warnings().is_empty()); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Empty", "Family"]); + assert_eq!( + template_folders(&r), + [ + pair("Old", "User Templates"), + pair("Kept", "Family"), + pair("Spelled", "Family"), + pair("Bad", "User Templates"), + pair("Reserved", "User Templates") + ] + ); + run(&mut s, "print.template.apply", json!({"name": "Old"})); +} + /// A library whose `prefs.json` can't be read, so saving the preferences fails. #[derive(Clone, Default)] struct PrefsUnreadable(MemStore); @@ -442,7 +609,13 @@ fn template_changes_that_cant_be_saved_are_undone() { LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(PrefsUnreadable::default()), on_disk: false }; s.open_library_in(stores, false).unwrap(); s.print_templates.push(crate::print::template::PrintTemplate::new("Proofs", &s.print).unwrap()); - let names = |s: &Session| s.print_templates.iter().map(|t| (t.name.clone(), t.settings.clone())).collect::>(); + s.print_template_folders.push("Family".into()); + let names = |s: &Session| { + ( + s.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone(), t.settings.clone())).collect::>(), + s.print_template_folders.clone(), + ) + }; let kept = names(&s); let scratch = Scratch::new("unsaved"); let file = scratch.0.join("proofs.lcprint"); @@ -454,6 +627,10 @@ fn template_changes_that_cant_be_saved_are_undone() { ("print.template.save", json!({"name": "proofs"})), ("print.template.delete", json!({"name": "Proofs"})), ("print.template.import", json!({"path": file.to_string_lossy()})), + ("print.template.move", json!({"name": "Proofs", "folder": "Family"})), + ("print.template.folder.create", json!({"name": "Work"})), + ("print.template.folder.rename", json!({"name": "Family", "to": "Home"})), + ("print.template.folder.delete", json!({"name": "Family"})), ] { assert!(fails(&mut s, id, p.clone()).contains("prefs.json"), "{id} {p}"); assert_eq!(names(&s), kept, "{id} {p}"); @@ -503,6 +680,10 @@ fn every_print_command_is_registered_with_a_description() { "print.template.delete", "print.template.export", "print.template.import", + "print.template.move", + "print.template.folder.create", + "print.template.folder.rename", + "print.template.folder.delete", ] { let c = crate::find_command(id).unwrap_or_else(|| panic!("{id} missing")); assert!(c.params.len() > 3, "{id}"); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e0ec9f1baa..8158c582f2 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -283,6 +283,7 @@ "Exported to {path}": "Exportováno do {path}", "Saved template {name}": "Uložena šablona {name}", "Imported {name}": "Importováno: {name}", + "Moved {name} to {folder}": "{name} přesunuto do složky {folder}", "Skipped {problem}": "Přeskočeno: {problem}", "…and {more} more": "…a další: {more}", "Template preview: {name}": "Náhled šablony: {name}", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 6a056bbfb9..a24253de71 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2438,5 +2438,9 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "User Templates": "Uživatelské šablony", + "Delete Folder": "Odstranit složku", + "Folder name": "Název složky", + "Its templates move to User Templates.": "Její šablony se přesunou do složky Uživatelské šablony." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 782886be84..22c1799c8c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -284,6 +284,7 @@ "Exported to {path}": "Exportiert nach {path}", "Saved template {name}": "Vorlage {name} gespeichert", "Imported {name}": "{name} importiert", + "Moved {name} to {folder}": "{name} nach {folder} verschoben", "Skipped {problem}": "Übersprungen: {problem}", "…and {more} more": "…und {more} weitere", "Template preview: {name}": "Vorlagenvorschau: {name}", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 405c54a464..22d25fabf0 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3470,5 +3470,9 @@ "Top bar": "Obere Leiste", "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "User Templates": "Benutzervorlagen", + "Delete Folder": "Ordner löschen", + "Folder name": "Ordnername", + "Its templates move to User Templates.": "Seine Vorlagen werden nach „Benutzervorlagen“ verschoben." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 41ae09d66e..54fa87374a 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Exportado a {path}", "Saved template {name}": "Plantilla {name} guardada", "Imported {name}": "Se importó {name}", + "Moved {name} to {folder}": "{name} se movió a {folder}", "Skipped {problem}": "Omitido: {problem}", "…and {more} more": "…y {more} más", "Template preview: {name}": "Vista previa de la plantilla: {name}", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index e43ae8c49b..a35be35e6a 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2390,5 +2390,9 @@ "Top bar": "Barra superior", "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "User Templates": "Plantillas del usuario", + "Delete Folder": "Eliminar carpeta", + "Folder name": "Nombre de la carpeta", + "Its templates move to User Templates.": "Sus plantillas se moverán a Plantillas del usuario." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc..510a2f841d 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -99,6 +99,7 @@ "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", + "Moved {name} to {folder}": "{name} siirretty kansioon {folder}", "Imported {n} point curve preset{}": "Tuotuja pistekäyrän esiasetuksia: {n}{:.0}", "Imported {n} preset{}": "Tuotuja esiasetuksia: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Tuotuja esiasetuksia: {n}{:.0}, ei luettavissa olevia tiedostoja: {f}{:.0}", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff7e03c066..bacf89c76b 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2356,5 +2356,9 @@ "Set up name suggestions…": "Määritä nimiehdotukset…", "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", - "Bottom bar": "Alapalkki" + "Bottom bar": "Alapalkki", + "User Templates": "Käyttäjän mallipohjat", + "Delete Folder": "Poista kansio", + "Folder name": "Kansion nimi", + "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index fc46d653c6..f568fd63b9 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Exporté vers {path}", "Saved template {name}": "Modèle {name} enregistré", "Imported {name}": "{name} importé", + "Moved {name} to {folder}": "{name} déplacé vers {folder}", "Skipped {problem}": "Ignoré : {problem}", "…and {more} more": "…et {more} de plus", "Template preview: {name}": "Aperçu du modèle : {name}", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e032cf52f3..b06ca1727b 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3573,5 +3573,9 @@ "Top bar": "Barre supérieure", "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "User Templates": "Modèles utilisateur", + "Delete Folder": "Supprimer le dossier", + "Folder name": "Nom du dossier", + "Its templates move to User Templates.": "Ses modèles sont déplacés vers Modèles utilisateur." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3..9f98c8d0bc 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -286,6 +286,7 @@ "Exported to {path}": "Diekspor ke {path}", "Saved template {name}": "Templat {name} disimpan", "Imported {name}": "{name} diimpor", + "Moved {name} to {folder}": "{name} dipindahkan ke {folder}", "Skipped {problem}": "Dilewati: {problem}", "…and {more} more": "…dan {more} lainnya", "Template preview: {name}": "Pratinjau templat: {name}", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 1c70f26344..21d4efc19b 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2370,5 +2370,9 @@ "Set up name suggestions…": "Siapkan saran nama…", "Top bar": "Bilah atas", "Tool strip": "Bilah alat", - "Bottom bar": "Bilah bawah" + "Bottom bar": "Bilah bawah", + "User Templates": "Templat pengguna", + "Delete Folder": "Hapus folder", + "Folder name": "Nama folder", + "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 4437aa644d..6e9b5d5fba 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -285,6 +285,7 @@ "{n} JPEG files": "File JPEG: {n}", "Exported {} effect preset{}": "Preset effetto esportati: {}{:.0}", "Imported {name}": "{name} importato", + "Moved {name} to {folder}": "{name} spostato in {folder}", "{n} pages": "Pagine: {n}", " · kept, not applied: {}": " · conservato, non applicato: {}", "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a0d39d0610..bd288561f1 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2556,5 +2556,9 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "User Templates": "Modelli utente", + "Delete Folder": "Elimina cartella", + "Folder name": "Nome della cartella", + "Its templates move to User Templates.": "I suoi modelli vengono spostati in Modelli utente." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 2fb625ff6a..c8eed23029 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "{path} に書き出しました", "Saved template {name}": "テンプレート {name} を保存しました", "Imported {name}": "{name} を読み込みました", + "Moved {name} to {folder}": "{name} を {folder} に移動しました", "Skipped {problem}": "スキップ: {problem}", "…and {more} more": "…ほか {more} 件", "Template preview: {name}": "テンプレートのプレビュー: {name}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5f80d7896b..a82b2cbded 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2388,5 +2388,9 @@ "Top bar": "上部バー", "Tool strip": "ツールバー", "Bottom bar": "下部バー", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "User Templates": "ユーザーテンプレート", + "Delete Folder": "フォルダを削除", + "Folder name": "フォルダ名", + "Its templates move to User Templates.": "中のテンプレートは「ユーザーテンプレート」に移動します。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 329662ac1b..2fd821e83d 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -271,6 +271,7 @@ "Exported {} effect preset{}": "ექსპორტირებულია ეფექტის პრესეტი: {}{:.0}", "Imported {e} mask effect{} (Masking ▸ Effect)": "იმპორტირებულია ნიღბის ეფექტი: {e}{:.0} (ნიღბვა → ეფექტი)", "Imported {name}": "იმპორტირებულია: {name}", + "Moved {name} to {folder}": "{name} გადატანილია: {folder}", "Keywords of {n} selected photos": "მონიშნული ფოტოების ({n}) საკვანძო სიტყვები", "LightCraft stopped unexpectedly: {e}": "LightCraft მოულოდნელად შეწყდა: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft მოულოდნელად შეწყდა: {e}\n\nდეტალები ჟურნალის ფაილშია: {path}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 0ea7d3d805..da6c1b8ff3 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3659,5 +3659,9 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "User Templates": "მომხმარებლის შაბლონები", + "Delete Folder": "საქაღალდის წაშლა", + "Folder name": "საქაღალდის სახელი", + "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“." } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 3f0fd43a22..f8b6ef9453 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -277,6 +277,7 @@ "Exported to {path}": "Wyeksportowano do {path}", "Saved template {name}": "Zapisano szablon {name}", "Imported {name}": "Zaimportowano {name}", + "Moved {name} to {folder}": "Przeniesiono {name} do {folder}", "Skipped {problem}": "Pominięto: {problem}", "…and {more} more": "…i jeszcze {more}", "Template preview: {name}": "Podgląd szablonu: {name}", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index bb3729a5b6..5f595e8fbe 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2315,5 +2315,9 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "User Templates": "Szablony użytkownika", + "Delete Folder": "Usuń folder", + "Folder name": "Nazwa folderu", + "Its templates move to User Templates.": "Jego szablony zostaną przeniesione do folderu Szablony użytkownika." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index c26b2e281e..57cc0d3e07 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "Exportado para {path}", "Saved template {name}": "Modelo {name} salvo", "Imported {name}": "{name} importado", + "Moved {name} to {folder}": "{name} movido para {folder}", "Skipped {problem}": "Ignorado: {problem}", "…and {more} more": "…e mais {more}", "Template preview: {name}": "Prévia do modelo: {name}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index a0884dc56a..09211ff2b2 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2234,5 +2234,9 @@ "Top bar": "Barra superior", "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "User Templates": "Modelos do usuário", + "Delete Folder": "Excluir pasta", + "Folder name": "Nome da pasta", + "Its templates move to User Templates.": "Os modelos dela vão para Modelos do usuário." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 4be240ec5b..7c785a25d2 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Экспортировано в {path}", "Saved template {name}": "Шаблон {name} сохранён", "Imported {name}": "Импортировано: {name}", + "Moved {name} to {folder}": "{name} перемещено в {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…и ещё {more}", "Template preview: {name}": "Просмотр шаблона: {name}", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 598893c3bc..57d9796bfe 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2596,5 +2596,9 @@ "Top bar": "Верхняя панель", "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "User Templates": "Пользовательские шаблоны", + "Delete Folder": "Удалить папку", + "Folder name": "Название папки", + "Its templates move to User Templates.": "Её шаблоны будут перемещены в «Пользовательские шаблоны»." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..5e8c6f243f 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -97,6 +97,7 @@ "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", + "Moved {name} to {folder}": "Flyttade {name} till {folder}", "Imported {n} point curve preset{}": "Importerade {n} punktkurvförinställning{}", "Imported {n} preset{}": "Importerade {n} förinställning{}", "Imported {n} preset{}, {f} file{} not readable": "Importerade {n} förinställning{}, {f} fil{} kunde inte läsas", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index f229b9547c..c5209b58ee 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2459,5 +2459,9 @@ "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", - "Bottom bar": "Nedre fältet" + "Bottom bar": "Nedre fältet", + "User Templates": "Användarmallar", + "Delete Folder": "Radera mapp", + "Folder name": "Mappnamn", + "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index e87bd03749..943e69fffc 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -285,6 +285,7 @@ "Exported to {path}": "Експортовано до {path}", "Saved template {name}": "Шаблон {name} збережено", "Imported {name}": "Імпортовано: {name}", + "Moved {name} to {folder}": "{name} переміщено до {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…і ще {more}", "Template preview: {name}": "Перегляд шаблону: {name}", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a4efe34a60..c753263313 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2386,5 +2386,9 @@ "Top bar": "Верхня панель", "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "User Templates": "Власні шаблони", + "Delete Folder": "Видалити теку", + "Folder name": "Назва теки", + "Its templates move to User Templates.": "Її шаблони буде переміщено до «Власні шаблони»." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db5..ea881103d7 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -99,6 +99,7 @@ "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", + "Moved {name} to {folder}": "Đã chuyển {name} vào {folder}", "Imported {n} point curve preset{}": "Đã nhập {n} thiết lập sẵn đường cong điểm{:.0}", "Imported {n} preset{}": "Đã nhập {n} thiết lập sẵn{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Đã nhập {n} thiết lập sẵn{:.0}, {f} tệp{:.0} không đọc được", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c1610e428f..f612cd7db7 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2684,5 +2684,9 @@ "Set up name suggestions…": "Thiết lập gợi ý tên…", "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", - "Bottom bar": "Thanh dưới cùng" + "Bottom bar": "Thanh dưới cùng", + "User Templates": "Mẫu người dùng", + "Delete Folder": "Xóa thư mục", + "Folder name": "Tên thư mục", + "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0a8b94115f..8eabaabdd5 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "已导出到 {path}", "Saved template {name}": "已保存模板 {name}", "Imported {name}": "已导入 {name}", + "Moved {name} to {folder}": "已将 {name} 移到 {folder}", "Skipped {problem}": "已跳过:{problem}", "…and {more} more": "…还有 {more} 个", "Template preview: {name}": "模板预览:{name}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ea867f35e6..d71eb52d00 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2389,5 +2389,9 @@ "Set up name suggestions…": "设置姓名建议…", "Top bar": "顶部栏", "Tool strip": "工具栏", - "Bottom bar": "底部栏" + "Bottom bar": "底部栏", + "User Templates": "用户模板", + "Delete Folder": "删除文件夹", + "Folder name": "文件夹名称", + "Its templates move to User Templates.": "其中的模板将移到“用户模板”。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 178cd55a03..5c95be0ff8 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -289,6 +289,7 @@ "Exported to {path}": "已匯出到 {path}", "Saved template {name}": "已儲存範本 {name}", "Imported {name}": "已匯入 {name}", + "Moved {name} to {folder}": "已將 {name} 移至 {folder}", "Skipped {problem}": "已略過:{problem}", "…and {more} more": "…還有 {more} 個", "Template preview: {name}": "範本預覽:{name}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 90b3670ec3..8e2bbf9815 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2389,5 +2389,9 @@ "Top bar": "頂部列", "Tool strip": "工具列", "Bottom bar": "底部列", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "User Templates": "使用者範本", + "Delete Folder": "刪除資料夾", + "Folder name": "資料夾名稱", + "Its templates move to User Templates.": "其中的範本會移到「使用者範本」。" } diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index c9af1d776d..fdf9c643b0 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -10,7 +10,7 @@ use lightcraft_catalog::PhotoId; use lightcraft_engine::export::ExportOptions; use lightcraft_engine::print::compose::{self, place}; use lightcraft_engine::print::layout::{self, Snap, Style, Unit}; -use lightcraft_engine::print::template::PrintSettings; +use lightcraft_engine::print::template::{DEFAULT_FOLDER, PrintSettings}; use lightcraft_engine::print_color::{ManagedSpace, PrintColorSettings, PrintIntent, PrintMedia, PrintProfile, PrintSharpen}; use serde_json::{Value, json}; @@ -49,10 +49,27 @@ pub struct PrintUi { drag: Option, /// The name typed for Save Template. pub template_name: String, + /// The folder Save and Import… put a template in; `None`: User Templates. + pub save_folder: Option, + /// A folder name being typed in the Template Browser. + pub folder_edit: Option, + /// The folder whose Delete Folder waits for a confirmation. + pub delete_folder: Option, + /// Template Browser folders shown closed, lowercase. + pub closed_folders: Vec, + /// The template being dragged onto a folder. + pub dragging_template: Option, /// Size of the next cell added, inches. pub new_cell: Option<(f64, f64)>, } +/// New Folder… (`from: None`) or Rename Folder… of the folder `from`, with the name typed so far. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FolderEdit { + pub from: Option, + pub name: String, +} + fn run(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Option { match app.run(id, params) { Ok(v) => Some(v), @@ -196,31 +213,241 @@ pub fn body(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens) { app.ui.print = pu; } -/// The print templates: save the settings as one, import, and the saved ones to apply, export and delete. +/// The folder a command names for `folder` (`None`: User Templates). +fn folder_param(folder: Option<&str>) -> &str { + folder.unwrap_or(DEFAULT_FOLDER) +} + +/// How the Template Browser names `folder`: User Templates in the interface's language, a folder +/// of the user's as it was typed. +fn folder_label(folder: Option<&str>) -> String { + folder.map_or_else(|| crate::i18n::tr("User Templates").to_string(), str::to_string) +} + +/// The print templates: save the settings as one into a folder, import, and the Template Browser: +/// its folders (New Folder…, Rename Folder…, Delete Folder) and in each the saved templates to +/// apply, export, delete, and drag onto another folder or move there from their menu. fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi) { let ctx = ui.ctx().clone(); heading(ui, t, "Templates"); + // a folder deleted or renamed by a command is no longer the one Save uses + if pu.save_folder.as_ref().is_some_and(|f| !app.session.print_template_folders.contains(f)) { + pu.save_folder = None; + } ui.horizontal(|ui| { crate::text_field::TextField::singleline("field:printTemplateName", &mut pu.template_name) .hint(crate::i18n::tr("Template name")) .width(140.0) .show(ui); + let folder = folder_param(pu.save_folder.as_deref()).to_string(); if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() { - run(app, &ctx, "print.template.save", json!({"name": pu.template_name})); + run(app, &ctx, "print.template.save", json!({"name": pu.template_name, "folder": folder})); } if app.services.pick_print_templates.is_some() && text_button(ui, "printTemplateImport", "Import…", false).clicked() { let paths = app.services.pick_print_templates.as_mut().map(|pick| pick()).unwrap_or_default(); for path in paths { - if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path})) { + if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path, "folder": folder})) { app.toast(&ctx, crate::i18n::tr_format!("Imported {name}", name = r["name"].as_str().unwrap_or_default())); } } } }); - let names: Vec = app.session.print_templates.iter().map(|t| t.name.clone()).collect(); - for (i, name) in names.iter().enumerate() { + let folders: Vec> = std::iter::once(None).chain(app.session.print_template_folders.iter().cloned().map(Some)).collect(); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(crate::i18n::tr("Folder")).color(t.text_label)); + let c = craft_ui::ComboBox::from_id_salt("printSaveFolder").width(120.0).selected_text(folder_label(pu.save_folder.as_deref())).show_ui( + ui, + |ui| { + for (j, f) in folders.iter().enumerate() { + let r = ui.selectable_label(pu.save_folder == *f, folder_label(f.as_deref())); + register(ui, format!("item:printSaveFolder-{j}"), r.rect); + if r.clicked() { + pu.save_folder.clone_from(f); + } + } + }, + ); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Folder")); + register(ui, "combo:printSaveFolder", c.response.rect); + if text_button(ui, "printTemplateNewFolder", "New Folder…", false).clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + }); + folder_editor(app, ui, &ctx, pu); + folder_delete_confirmation(app, ui, t, &ctx, pu); + for (j, folder) in folders.iter().enumerate() { + folder_rows(app, ui, t, pu, j, folder.as_deref(), &folders); + } + template_drag_feedback(&ctx, t, pu); +} + +/// The New Folder… / Rename Folder… field under the Save row, while one is open: Return or its +/// button runs the command, Esc or Cancel closes it. A refused name keeps it open, with the reason +/// in a toast. +fn folder_editor(app: &mut LightcraftApp, ui: &mut Ui, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(mut edit) = pu.folder_edit.take() else { return }; + let (mut confirm, mut cancel) = (false, false); + ui.horizontal(|ui| { + let r = crate::text_field::TextField::singleline("field:printFolderName", &mut edit.name) + .hint(crate::i18n::tr("Folder name")) + .width(140.0) + .select_on_focus(true) + .show(ui); + if super::frame::just_opened(ui, "printFolderName") { + r.response.request_focus(); + } + match r.ending { + Some(crate::text_field::Ending::Return) => confirm = true, + Some(crate::text_field::Ending::Escape) => cancel = true, + _ => {} + } + confirm |= text_button(ui, "printFolderOk", if edit.from.is_some() { "Rename" } else { "Create" }, false).clicked(); + cancel |= text_button(ui, "printFolderCancel", "Cancel", false).clicked(); + }); + if cancel { + return; + } + if confirm { + let (id, params) = match &edit.from { + None => ("print.template.folder.create", json!({"name": edit.name})), + Some(from) => ("print.template.folder.rename", json!({"name": from, "to": edit.name})), + }; + if let Some(r) = run(app, ctx, id, params) { + let made = r["name"].as_str().map(str::to_string); + // a new folder is where the next Save goes; a renamed one keeps its place there and its closed state + if edit.from.is_none() || pu.save_folder == edit.from { + pu.save_folder.clone_from(&made); + } + if let (Some(from), Some(to)) = (&edit.from, &made) { + for c in &mut pu.closed_folders { + if *c == from.to_lowercase() { + *c = to.to_lowercase(); + } + } + } + return; + } + } + pu.folder_edit = Some(edit); +} + +/// Delete Folder's question, while it is asked: the folder's templates move to User Templates. +fn folder_delete_confirmation(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(name) = pu.delete_folder.clone() else { return }; + let question = + format!("{} {}", crate::i18n::tr_format!("Delete “{name}”?", name = name), crate::i18n::tr("Its templates move to User Templates.")); + ui.label(egui::RichText::new(question).color(t.text_label)); + ui.horizontal(|ui| { + if text_button(ui, "printFolderDeleteConfirm", "Delete Folder", false).clicked() + && run(app, ctx, "print.template.folder.delete", json!({"name": name})).is_some() + { + pu.delete_folder = None; + pu.closed_folders.retain(|c| *c != name.to_lowercase()); + } + if text_button(ui, "printFolderDeleteCancel", "Cancel", false).clicked() { + pu.delete_folder = None; + } + }); +} + +/// Moves the template `name` to `folder` and says so; nothing when it is there already. +fn move_template(app: &mut LightcraftApp, ctx: &egui::Context, name: &str, folder: Option<&str>) { + if let Some(r) = run(app, ctx, "print.template.move", json!({"name": name, "folder": folder_param(folder)})) + && r["moved"] == true + { + app.toast(ctx, crate::i18n::tr_format!("Moved {name} to {folder}", name = name, folder = folder_label(folder))); + } +} + +/// One Template Browser folder: its row (a click opens or closes it, a template dropped on it moves +/// there, its menu has New Folder… and, for the user's folders, Rename Folder… and Delete Folder), +/// then, while it is open, its templates. +fn folder_rows(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, j: usize, folder: Option<&str>, folders: &[Option]) { + let ctx = ui.ctx().clone(); + let label = folder_label(folder); + let key = folder_param(folder).to_lowercase(); + let open = !pu.closed_folders.contains(&key); + let count = app.session.print_templates.iter().filter(|x| x.folder.as_deref() == folder).count(); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); + crate::widgets::announce_disclosure(&resp, true, open, &label); + register(ui, format!("printTemplateFolder-{j}"), r); + let pointer = ui.input(|i| i.pointer.latest_pos()); + let under_drag = pu.dragging_template.is_some() && crate::docking::drop_target(ui, r, pointer); + if under_drag { + ui.painter().rect_stroke(r.shrink(1.0), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.6)); + } + crate::icons::paint( + ui.painter(), + Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(14.0, 14.0)), + if open { crate::icons::Icon::ChevronDown } else { crate::icons::Icon::ChevronRight }, + t.text_label, + ); + ui.painter().text(pos2(r.left() + 20.0, r.center().y), Align2::LEFT_CENTER, &label, t.semibold(12.0), t.text); + ui.painter().text(pos2(r.right() - 4.0, r.center().y), Align2::RIGHT_CENTER, count.to_string(), t.font(11.0), t.text_dim); + if resp.clicked() { + if open { + pu.closed_folders.push(key); + } else { + pu.closed_folders.retain(|c| *c != key); + } + } + if under_drag + && ui.input(|i| i.pointer.primary_released()) + && let Some(name) = pu.dragging_template.take() + { + move_template(app, &ctx, &name, folder); + } + crate::widgets::context_menu(&resp, |ui| { + let new = ui.button(crate::i18n::tr("New Folder…")); + register(ui, format!("item:printFolderNew-{j}"), new.rect); + if new.clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + if let Some(f) = folder { + let rename = ui.button(crate::i18n::tr("Rename Folder…")); + register(ui, format!("item:printFolderRename-{j}"), rename.rect); + if rename.clicked() { + pu.folder_edit = Some(FolderEdit { from: Some(f.to_string()), name: f.to_string() }); + pu.delete_folder = None; + } + let delete = ui.button(crate::i18n::tr("Delete Folder")); + register(ui, format!("item:printFolderDelete-{j}"), delete.rect); + if delete.clicked() { + pu.delete_folder = Some(f.to_string()); + pu.folder_edit = None; + } + } + }); + if !open { + return; + } + let rows: Vec<(usize, String)> = + app.session.print_templates.iter().enumerate().filter(|(_, x)| x.folder.as_deref() == folder).map(|(i, x)| (i, x.name.clone())).collect(); + for (i, name) in &rows { + let (i, name) = (*i, name.as_str()); ui.horizontal(|ui| { - ui.label(egui::RichText::new(name).color(t.text_label)); + ui.add_space(20.0); + let resp = ui.add(egui::Label::new(egui::RichText::new(name).color(t.text_label)).sense(Sense::click_and_drag())); + register(ui, format!("printTemplate-{i}"), resp.rect); + if resp.drag_started() { + pu.dragging_template = Some(name.to_string()); + } + crate::widgets::context_menu(&resp, |ui| { + let sub = crate::widgets::menu_button(ui, crate::i18n::tr("Move to Folder"), |ui| { + for (k, f) in folders.iter().enumerate().filter(|(_, f)| f.as_deref() != folder) { + let item = ui.button(folder_label(f.as_deref())); + register(ui, format!("item:printTemplateMove-{i}-{k}"), item.rect); + if item.clicked() { + move_template(app, &ctx, name, f.as_deref()); + } + } + }); + register(ui, format!("item:printTemplateMoveMenu-{i}"), sub.response.rect); + }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, &format!("printTemplateDelete-{i}"), "Delete", false).clicked() { run(app, &ctx, "print.template.delete", json!({"name": name})); @@ -244,6 +471,28 @@ fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut } } +/// A template being dragged: its name follows the pointer, and the drag ends with the button's +/// release (after the folder rows, which take the drop) or with Esc. +fn template_drag_feedback(ctx: &egui::Context, t: &Tokens, pu: &mut PrintUi) { + let Some(name) = pu.dragging_template.clone() else { return }; + let (released, down, at, esc) = + ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); + if released || !down || esc { + pu.dragging_template = None; + return; + } + let Some(at) = at else { return }; + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + egui::Area::new(egui::Id::unique("drag-print-template")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0))); + }); + }, + ); +} + /// The image settings: zoom, rotation, border and stroke. fn image_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSettings) { let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/tests/print.rs b/crates/ui-egui/src/tests/print.rs index 68f3d328d0..5169e47a56 100644 --- a/crates/ui-egui/src/tests/print.rs +++ b/crates/ui-egui/src/tests/print.rs @@ -90,6 +90,11 @@ fn style_buttons_and_checkboxes_run_print_set() { click(&mut h, "check:printZoomFill"); click(&mut h, "check:printStroke"); assert!(h.app.session.print.image.zoom_to_fill && h.app.session.print.image.stroke_enabled); + // (the page settings are below the Template Browser: the settings column is scrolled to them) + let column = rect(&h, "check:printStroke").center(); + h.request("ui.move", json!({"x": column.x, "y": column.y}), T); + h.request("ui.scroll", json!({"dy": -200.0}), T); + h.settle(T); click(&mut h, "button:printOrientation-1"); assert_eq!(h.app.session.print.layout.page.orientation, lightcraft_engine::print::layout::Orientation::Landscape); let p = rect(&h, "print:page"); @@ -248,6 +253,122 @@ fn templates_export_and_import_from_the_dialog() { let _ = std::fs::remove_dir_all(dir); } +/// Each template's name and folder (`None`: User Templates). +fn template_folders(h: &Headless) -> Vec<(String, Option)> { + h.app.session.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone())).collect() +} + +/// Drags the widget `from` onto the center of the widget `to`. +fn drag_onto(h: &mut Headless, from: &str, to: &str) { + let (a, b) = (rect(h, from).center(), rect(h, to).center()); + drag(h, from, b.x - a.x, b.y - a.y); +} + +#[test] +fn the_template_browser_makes_folders_and_saves_into_one() { + let mut h = demo(Services::default()); + open_print(&mut h); + assert!(has(&h, "printTemplateFolder-0"), "User Templates is listed"); + assert!(!has(&h, "printTemplateFolder-1")); + click(&mut h, "button:printTemplateNewFolder"); + assert!(has(&h, "field:printFolderName")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Weddings".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Weddings"]); + assert!(h.app.ui.print.folder_edit.is_none()); + assert!(has(&h, "printTemplateFolder-1")); + assert_eq!(h.app.ui.print.save_folder.as_deref(), Some("Weddings"), "a new folder is where Save goes"); + // a name taken is refused, and the field stays open + click(&mut h, "button:printTemplateNewFolder"); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "weddings".into(); + click(&mut h, "button:printFolderOk"); + assert!(h.app.ui.print.folder_edit.is_some()); + click(&mut h, "button:printFolderCancel"); + assert!(h.app.ui.print.folder_edit.is_none()); + assert_eq!(h.app.session.print_template_folders.len(), 1); + + h.app.ui.print.template_name = "Sheet".into(); + click(&mut h, "button:printSaveTemplate"); + h.app.ui.print.save_folder = None; + h.app.ui.print.template_name = "Plain".into(); + click(&mut h, "button:printSaveTemplate"); + assert_eq!(template_folders(&h), [("Sheet".into(), Some("Weddings".into())), ("Plain".into(), None)]); + // a folder's row opens and closes its list + assert!(has(&h, "printTemplate-0")); + click(&mut h, "printTemplateFolder-1"); + assert!(!has(&h, "printTemplate-0"), "a closed folder hides its templates"); + assert!(has(&h, "printTemplate-1")); + click(&mut h, "printTemplateFolder-1"); + assert!(has(&h, "printTemplate-0")); +} + +#[test] +fn a_template_dragged_onto_a_folder_moves_there() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let settings = h.app.session.print_templates[0].settings.clone(); + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + assert_eq!(h.app.session.print_templates[0].settings, settings, "only the folder changes"); + assert!(h.app.ui.print.dragging_template.is_none()); + // and back onto User Templates + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-0"); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + // a drop anywhere else leaves it where it is + drag(&mut h, "printTemplate-0", 0.0, 300.0); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.dragging_template.is_none()); +} + +#[test] +fn a_templates_menu_moves_it_and_a_folders_menu_renames_and_deletes() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let r = h.request("ui.clickWidget", json!({"id": "printTemplate-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert_eq!(h.request("ui.hoverWidget", json!({"id": "item:printTemplateMoveMenu-0"}), T)["ok"], true); + h.settle(T); + click(&mut h, "item:printTemplateMove-0-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderRename-1"); + assert_eq!(h.app.ui.print.folder_edit.as_ref().and_then(|e| e.from.as_deref()), Some("Weddings")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Family".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Family".into()))]); + + // Delete Folder asks first; its templates then go to User Templates + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderDelete-1"); + assert_eq!(h.app.session.print_template_folders, ["Family"], "nothing is deleted before the confirmation"); + click(&mut h, "button:printFolderDeleteCancel"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + h.app.ui.print.delete_folder = Some("Family".into()); + h.settle(T); + click(&mut h, "button:printFolderDeleteConfirm"); + assert!(h.app.session.print_template_folders.is_empty()); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.delete_folder.is_none()); + + // User Templates has New Folder… but no Rename or Delete + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert!(has(&h, "item:printFolderNew-0")); + assert!(!has(&h, "item:printFolderRename-0") && !has(&h, "item:printFolderDelete-0")); +} + #[test] fn template_files_need_the_hosts_file_dialogs() { let mut h = demo(Services::default()); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a9dd725236..f807285f20 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -766,7 +766,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-PRINT-CELLS | Picture-package cells | P2 | ✅ | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout`, `crates/ui-egui/src/dialogs/print_view.rs` | add cells at standard or custom sizes, drag and resize them on the page preview (snap to cells, grid or off), Send to Back / Backward / Forward / Bring to Front, a photo per cell (Custom Package), Auto Layout packing, New Page, Clear Layout; no Auto Layout for Custom Package | | LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | page background colour and margins in the Print dialog; Page Options for Single Image and Contact Sheet (`print.set {page: {pageNumbers, pageInfo, cropMarks}}`, checkboxes in the Page section, kept in templates): the page number at the bottom right, the print settings line (sharpening, profile, resolution) at the bottom left, crop marks at each photo's corners, drawn in the preview and in the PDF (`print::compose::tests::crop_marks_sit_outside_each_photo_corner`); filename captions in the contact-sheet PDF; no identity plate, watermark, photo info or package Cut Guides | | LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:print.set`, `cmd:print.exportPdf`, `crates/ui-egui/src/dialogs/print_view.rs`, `crates/engine/src/print_color.rs`, `crates/codecs/src/print.rs`, `crates/engine/src/pdf.rs`, `cmd:export.contactSheet` | the Print dialog's Print Job panel and `print.set {job}`: print resolution 72–720 ppi; colour management: Managed by Printer (sRGB / Adobe RGB, profile embedded) or a printer / paper ICC profile (RGB, CMYK or grey) converted here and named as the PDF's output intent; perceptual / relative colorimetric with black point compensation; Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte / Glossy; 16-bit (or 8-bit) ICC-tagged lossless page images; a bad profile fails before rendering (`tests_print::export_pdf_with_a_printer_profile`). The contact sheet keeps its fixed 150 dpi sRGB JPEG PDF. Missing: printing to a printer (OS print dialog), JPEG file output, Draft Mode | -| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); no built-in templates, no folders | +| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `cmd:print.template.move`, `cmd:print.template.folder.create`, `cmd:print.template.folder.rename`, `cmd:print.template.folder.delete`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); the Template Browser lists the templates in folders: User Templates and folders made with New Folder… (its button, or a folder's context menu), which open and close; Save and Import… put a template in the folder chosen beside them; a template dragged onto a folder, or moved with its context menu's Move to Folder, moves there; Rename Folder… and Delete Folder (asks first, and moves the folder's templates to User Templates, LightCraft's own rule) for every folder but User Templates; no built-in templates | | LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | | | LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | | | LRC-WEB-COLOR | Web gallery colours | OOS | 🚫 | | | @@ -1025,3 +1025,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-31 | minor | LRC-PRINT-TEMPLATES: the Print dialog's Template Browser has folders (`print.template.folder.create` / `rename` / `delete`), Save and Import… put a template in a chosen folder, and a template dragged onto a folder moves there (`print.template.move`); deleting a folder moves its templates to User Templates; status unchanged (🟡: no built-in templates) | From 93cf4785a5d2d35e6d727b70fd126e2c883767bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:30:36 -0700 Subject: [PATCH 053/247] Keywords: Enter Keywords applies an edit when its box is folded or hidden and reads a quoted name with commas as one Folding the Keywords box while the Enter Keywords field has the cursor applies the edit, as leaving the field does. An edit whose field lost the cursor while its panel was hidden is applied when the box is next drawn for the same photos. A name typed in double quotes that holds commas, such as "Paris, France", is read as one keyword whether or not the selection or the library has it. An unclosed quote leaves the pieces apart. --- crates/ui-egui/src/panels/keywording.rs | 68 +++++++++++++++------ crates/ui-egui/src/panels/right/keywords.rs | 14 ++++- crates/ui-egui/src/tests/keywording.rs | 24 ++++++++ 3 files changed, 85 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 75504aee38..e5408beb94 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -753,9 +753,10 @@ impl Entered { } /// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except -/// where pieces joined by their separators spell a keyword of `start` whose name holds a comma or a -/// new line (with or without its asterisk or its quotes) that the text has not named yet, which -/// stays one name. +/// where a name opened with a double quote closes with one after commas (the next piece holding a +/// double quote ends with it), or where pieces joined by their separators spell a keyword of +/// `start` whose name holds a comma or a new line (with or without its asterisk or its quotes) that +/// the text has not named yet. Either stays one name. fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { use lightcraft_catalog::keywords::{clean, same}; let is_separator = |ch: char| ch == ',' || ch == '\n'; @@ -770,20 +771,37 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { pieces.push(from..from + piece.len()); from += piece.len() + 1; } + let piece = |p: &std::ops::Range| text.get(p.clone()).unwrap_or_default().trim(); let mut names = Vec::new(); let mut i = 0; while let Some(first) = pieces.get(i) { - // the most pieces that spell a keyword with separators not named yet - let joined = start - .iter() - .map(|c| c.path.matches(is_separator).count()) - .filter(|&separators| separators > 0) - .filter_map(|separators| { - let last = pieces.get(i + separators)?; - let s = text.get(first.start..last.end)?.trim(); - unnamed(s, &named).map(|_| (separators, s)) + // a name in double quotes, up to the piece that closes it (an unclosed one is plain pieces) + let opened = piece(first).starts_with('"') && quoted(piece(first)).is_none(); + let quoted_run = opened + .then(|| { + pieces + .iter() + .enumerate() + .skip(i + 1) + .take_while(|(_, p)| p.start.checked_sub(1).and_then(|b| text.as_bytes().get(b)) == Some(&b',')) + .find(|(_, p)| piece(p).contains('"')) + .filter(|(_, p)| piece(p).ends_with('"')) + .and_then(|(j, p)| Some((j - i, text.get(first.start..p.end)?.trim()))) }) - .max_by_key(|&(separators, _)| separators); + .flatten(); + // else the most pieces that spell a keyword with separators not named yet + let joined = quoted_run.or_else(|| { + start + .iter() + .map(|c| c.path.matches(is_separator).count()) + .filter(|&separators| separators > 0) + .filter_map(|separators| { + let last = pieces.get(i + separators)?; + let s = text.get(first.start..last.end)?.trim(); + unnamed(s, &named).map(|_| (separators, s)) + }) + .max_by_key(|&(separators, _)| separators) + }); let (separators, name) = joined.unwrap_or((0, text.get(first.clone()).unwrap_or_default().trim())); if let Some(n) = unnamed(name, &named) { named[n] = true; @@ -797,11 +815,12 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { } /// Reads the Enter Keywords `text` against `start`, the selection's keywords when the edit began. -/// Keywords are separated by commas or new lines; a keyword of `start` whose name holds a comma is -/// read as one name. A keyword of `start` left out of the text is taken off every selected photo. -/// A name without an asterisk goes to every selected photo (a keyword of `start` keeps its -/// spelling, and a new name goes where `Catalog::typed_keyword` puts it). A keyword only some -/// photos have, still marked with its asterisk, stays on those photos only. A name in double +/// Keywords are separated by commas or new lines; a keyword of `start` whose name holds a comma, and +/// a name in double quotes holding commas, are each read as one name. A keyword of `start` left out +/// of the text is taken off every selected photo. A name without an asterisk goes to every +/// selected photo (a keyword of `start` keeps its spelling, and a new name goes where +/// `Catalog::typed_keyword` puts it). A keyword only some photos have, still marked with its +/// asterisk, stays on those photos only. A name in double /// quotes is read as written, an asterisk at its end included. A keyword every photo has whose own /// name ends in an asterisk is also kept when written without its quotes, unless a keyword only /// some photos have reads the same. An asterisk after any other name is refused: the error is the @@ -1230,6 +1249,19 @@ mod tests { assert_eq!(entered(&c, &start, "a, b, a"), Ok(edit(&[], &["b"]))); } + /// A name in double quotes holding a comma is read as one name, whether the selection, the + /// library or neither has it; an unclosed quote leaves the pieces apart. + #[test] + fn a_quoted_name_with_a_comma_is_one_name() { + let (c, ids) = library(&[&["beach"], &["beach"], &["Places|Rome, Italy"]]); + let start = chips(&c, &ids[..2]); + assert_eq!(entered(&c, &start, "beach, \"Paris, France\""), Ok(edit(&["Paris, France"], &[])), "a new name"); + assert_eq!(entered(&c, &start, " \"Places|Rome, Italy\" ,beach"), Ok(edit(&["Places|Rome, Italy"], &[])), "in the library"); + assert_eq!(entered(&c, &start, "\"a, b, c\""), Ok(edit(&["a, b, c"], &["beach"]))); + assert_eq!(entered(&c, &start, "beach, \"Paris, France"), Ok(edit(&["\"Paris", "France"], &[])), "unclosed"); + assert_eq!(entered(&c, &start, "\"Paris\nFrance\", beach"), Ok(edit(&["\"Paris", "France\""], &[])), "not across a new line"); + } + /// A keyword whose name holds a new line is read as one name, as one holding a comma is. #[test] fn a_keyword_with_a_line_break_is_one_name() { diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index 0be0f83b2b..228d118487 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -8,6 +8,10 @@ pub(super) fn keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) let top = ui.cursor().top(); if fold_header(app, ui, "keywording", "Keywords") { keywording(app, ui); + } else if ui.data(|d| d.get_temp::(enter_id())).is_some_and(|e| !e.refused) { + // a folded box applies the Enter Keywords edit it held, as leaving the box does + let selection = app.session.selected(); + leave_enter_keywords(app, ui, &selection); } hold_list_in_place(ui, top); crate::panels::keyword_list::show(app, ui); @@ -272,8 +276,9 @@ fn leave_enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: & } /// Enter Keywords: the selection's keywords as text, separated by commas, one only some of the -/// photos have marked with an asterisk. Return, leaving the box or choosing another view applies -/// the edit to the photos selected when it started, as one undo step; Esc gives it up. Another +/// photos have marked with an asterisk. Return, leaving the box, choosing another view or folding +/// the box applies the edit to the photos selected when it started, as one undo step; Esc gives it +/// up. An edit whose box was hidden with its panel is applied when the box is next drawn. Another /// selection while the box is being edited gives the edit up too. A refused edit keeps its text and /// says why. fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { @@ -287,6 +292,8 @@ fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[Photo if kept.as_ref().is_some_and(|e| e.selection != key) && focused { ui.memory_mut(|m| m.surrender_focus(fid)); } + // (an edit kept without the cursor lost it while the box was not drawn, its panel hidden) + let left_undrawn = !focused && kept.as_ref().is_some_and(|e| e.selection == key && !e.refused); let mut edit = kept.filter(|e| e.selection == key).unwrap_or_else(|| EnterEdit::new(&chips, selection, key)); // Return applies the edit (Shift+Return or a pasted line break separates keywords as a comma does) let returned = focused @@ -311,7 +318,8 @@ fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[Photo return; } let mut done = false; - if returned || r.committed() { + // (applied as leaving the box applies it) + if returned || r.committed() || (left_undrawn && !r.editing) { let applied = apply_enter(app, ui.ctx(), &edit); edit.refused = !applied; done = applied; diff --git a/crates/ui-egui/src/tests/keywording.rs b/crates/ui-egui/src/tests/keywording.rs index 0c9ba252e6..b44b859acf 100644 --- a/crates/ui-egui/src/tests/keywording.rs +++ b/crates/ui-egui/src/tests/keywording.rs @@ -1041,6 +1041,30 @@ fn enter_keywords_applies_an_edit_when_another_view_is_chosen() { assert!(all_have(&h, &ids, "harbour"), "the refused text came back to be put right"); } +/// Folding the Keywords box while typing applies the edit, as leaving the box does; so does hiding +/// its panel, once the box is shown again for the same photos. +#[test] +fn enter_keywords_applies_an_edit_when_the_box_is_folded_or_hidden() { + let (mut h, ids) = two_selected(); + enter(&mut h, "beach, Weddings*, sea"); + ask(&mut h, "ui.clickWidget", json!({"id": "section:keywording"})); + assert!(!has(&h, "field:enterKeywords"), "the box is folded"); + assert!(all_have(&h, &ids, "sea"), "folding the box applied it"); + ask(&mut h, "ui.clickWidget", json!({"id": "section:keywording"})); + enter(&mut h, "beach, Weddings*, sea, harbour"); + h.app.ui.toggle_folded("keywording"); + h.step(); + assert!(all_have(&h, &ids, "harbour"), "folded without a click, it applied it"); + h.app.ui.toggle_folded("keywording"); + h.step(); + enter(&mut h, "beach, Weddings*, sea, harbour, pier"); + ask(&mut h, "ui.set", json!({"right": "info"})); + h.step(); + ask(&mut h, "ui.set", json!({"right": "keywords"})); + h.step(); + assert!(all_have(&h, &ids, "pier"), "hiding the box with its panel applied it when it came back"); +} + /// An asterisk after a name that is not a keyword only some photos have is refused: the photos keep /// their keywords, the box keeps the cursor and its text, and the refusal is said. #[test] From fa93d6f836c34cff721842d53ddd3c03cce38109 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:39:00 -0700 Subject: [PATCH 054/247] LRC-SS-PLAYBACK: pan and zoom moves and zooms each photo during playback The new Pan and zoom setting (Settings > Slideshow > Playback, or panAndZoom in slideshow.playback and view.slideshow) moves each photo slowly from one window of itself to another over its slide's time, its fade in included. Its Low to High amount (panAndZoomAmount, 0 to 1, default 0.5) sets how far it zooms: about 1.01x at Low and 1.12x at High for the closer view. Every photo gets its own path from the playback seed, the pass and the photo, so each pass moves differently and a seed replays the same paths. The window never leaves the photo. In a composed slide the photo moves inside its image cell while the backdrop, margins, stroke and shadow stay still; with overlays on, the whole slide moves so an overlay is never split. Title screens do not move. Pause freezes the motion, a photo fading out stays at its end view, and a manual slideshow holds each photo at its start view. The setting is off by default, saved with the library and in slideshow templates. Exports show the photos still. --- crates/engine/src/cmd/slideshow.rs | 2 +- crates/engine/src/slide_template/tests.rs | 6 +- crates/engine/src/slideshow.rs | 81 +++++++++- crates/engine/src/slideshow/tests.rs | 84 +++++++++++ crates/engine/src/tests/prefs.rs | 4 +- crates/slideshow/src/lib.rs | 5 +- crates/slideshow/src/motion.rs | 140 ++++++++++++++++++ .../ui-egui/src/dialogs/settings/slideshow.rs | 22 +++ crates/ui-egui/src/panels/slideshow.rs | 94 +++++++++--- crates/ui-egui/src/tests/slideshow.rs | 74 +++++++++ docs/parity-checklist.md | 2 +- docs/slideshow.md | 6 +- 12 files changed, 486 insertions(+), 34 deletions(-) create mode 100644 crates/slideshow/src/motion.rs diff --git a/crates/engine/src/cmd/slideshow.rs b/crates/engine/src/cmd/slideshow.rs index 191cee953f..78fe2f65a2 100644 --- a/crates/engine/src/cmd/slideshow.rs +++ b/crates/engine/src/cmd/slideshow.rs @@ -379,7 +379,7 @@ pub fn specs() -> Vec { "Slideshow Playback Settings", [], None, - "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual}", + "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it), panAndZoom?: bool (each photo moves and zooms slowly over its slide, on its own path), panAndZoomAmount?: 0 (low) to 1 (high)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual, panAndZoom, panAndZoomAmount}", always, playback ), diff --git a/crates/engine/src/slide_template/tests.rs b/crates/engine/src/slide_template/tests.rs index 9d3e9c807b..241e069929 100644 --- a/crates/engine/src/slide_template/tests.rs +++ b/crates/engine/src/slide_template/tests.rs @@ -39,7 +39,11 @@ fn ids(s: &mut Session) -> Vec { /// A look different from the defaults in every section. fn custom(s: &mut Session) { - run(s, "slideshow.playback", json!({"slideDuration": 7.5, "fadeDuration": 0.5, "fadeColor": "#102030", "randomOrder": true, "repeat": false})); + run( + s, + "slideshow.playback", + json!({"slideDuration": 7.5, "fadeDuration": 0.5, "fadeColor": "#102030", "randomOrder": true, "repeat": false, "panAndZoom": true, "panAndZoomAmount": 0.8}), + ); run( s, "slideshow.layout", diff --git a/crates/engine/src/slideshow.rs b/crates/engine/src/slideshow.rs index 0e1c1294de..3eb538627a 100644 --- a/crates/engine/src/slideshow.rs +++ b/crates/engine/src/slideshow.rs @@ -1,6 +1,6 @@ //! Slideshow playback: the settings of Lightroom Classic's Playback panel and the timeline that //! plays the photos in view (durations, fades, random order, repeat, pause, stepping, manual -//! advance), between an optional intro and ending screen (the Titles panel, +//! advance, pan and zoom), between an optional intro and ending screen (the Titles panel, //! [`crate::slide_title`]). //! //! No UI here: [`Playback`] is a pure state machine driven with injected times (seconds on any @@ -14,6 +14,7 @@ //! with the `slideshow.playback` command. use lightcraft_catalog::PhotoId; +use lightcraft_slideshow::{Motion, View}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -23,7 +24,7 @@ pub const SLIDE_MAX: f64 = 120.0; /// Longest fade (seconds); a fade is never longer than the slide duration. pub const FADE_MAX: f64 = 10.0; -/// How playback runs (Lightroom Classic's Playback panel, without music and pan & zoom). +/// How playback runs (Lightroom Classic's Playback panel, without music). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PlaybackSettings { @@ -43,6 +44,10 @@ pub struct PlaybackSettings { /// Manual slideshow: a slide stays up until ← / → (or the controls) change it; the slide /// duration is not used for playback then. pub manual: bool, + /// Pan and zoom: each photo moves and zooms slowly over its slide's time, on its own path. + pub pan_and_zoom: bool, + /// How much it moves: 0 (Low) to 1 (High). + pub pan_and_zoom_amount: f64, } impl Default for PlaybackSettings { @@ -55,18 +60,22 @@ impl Default for PlaybackSettings { repeat: true, prepare_previews: true, manual: false, + pan_and_zoom: false, + pan_and_zoom_amount: 0.5, } } } impl PlaybackSettings { - /// The settings with every value in range (a non-finite duration takes the default; the fade - /// is never longer than the slide). + /// The settings with every value in range (a non-finite duration or amount takes the default; + /// the fade is never longer than the slide). pub fn sanitized(mut self) -> Self { let d = PlaybackSettings::default(); self.slide_duration = if self.slide_duration.is_finite() { self.slide_duration.clamp(SLIDE_MIN, SLIDE_MAX) } else { d.slide_duration }; let fade = if self.fade_duration.is_finite() { self.fade_duration } else { d.fade_duration }; self.fade_duration = fade.clamp(0.0, FADE_MAX).min(self.slide_duration); + self.pan_and_zoom_amount = + if self.pan_and_zoom_amount.is_finite() { self.pan_and_zoom_amount.clamp(0.0, 1.0) } else { d.pan_and_zoom_amount }; self } @@ -79,6 +88,8 @@ impl PlaybackSettings { "repeat": self.repeat, "preparePreviews": self.prepare_previews, "manual": self.manual, + "panAndZoom": self.pan_and_zoom, + "panAndZoomAmount": self.pan_and_zoom_amount, }) } @@ -96,9 +107,14 @@ impl PlaybackSettings { "repeat" => s.repeat = boolean(k, v)?, "preparePreviews" => s.prepare_previews = boolean(k, v)?, "manual" => s.manual = boolean(k, v)?, + "panAndZoom" => s.pan_and_zoom = boolean(k, v)?, + "panAndZoomAmount" => match v.as_f64() { + Some(x) if x.is_finite() => s.pan_and_zoom_amount = x, + _ => return Err(format!("`{k}` must be a finite number from 0 (low) to 1 (high), not {v}")), + }, other => { return Err(format!( - "unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual)" + "unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual, panAndZoom, panAndZoomAmount)" )); } } @@ -229,6 +245,16 @@ pub struct Frame { pub fade_color: Option<[u8; 3]>, } +/// The pan and zoom views at a moment of playback (`None`: the slide shows its whole picture, as +/// a title screen always does, and every slide when pan and zoom is off). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PanZoom { + /// The current slide's view. + pub current: Option, + /// The view of the slide being faded out: where its motion ended. + pub from: Option, +} + /// Where the timeline is: the intro, the photos, or the ending. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Phase { @@ -261,6 +287,10 @@ pub struct Playback { started: f64, /// The slide fading out (until the transition ends). from: Option, + /// The pan and zoom key of the slide fading out. + from_key: Option, + /// Times a single photo repeating has started over (each time on a new path). + reps: u64, /// Paused at this time. paused_at: Option, ended: bool, @@ -319,6 +349,8 @@ impl Playback { ending: None, started: now, from: None, + from_key: None, + reps: 0, paused_at: None, ended: false, held: None, @@ -516,8 +548,10 @@ impl Playback { } let Some(next) = self.upcoming(1).first().copied() else { if self.settings.repeat { - // a single photo repeating: nothing to change to + // a single photo repeating: nothing to change to (its pan and zoom starts again, + // on a new path) self.started = now; + self.reps = self.reps.wrapping_add(1); return Tick::Idle; } self.ended = true; @@ -529,14 +563,48 @@ impl Playback { } self.held = None; let old = self.current(); + let old_key = self.motion_key(old); let t = self.advance(); if let Tick::Advanced(new) = t { self.started = now; self.from = (self.fade_to(new) > 0.0).then_some(old); + self.from_key = self.from.and(old_key); } t } + /// The pan and zoom key of `item` up in the current pass (`None` for a title screen): the + /// seed, the pass, the photo and the repeats of a single photo, so every photo has its own + /// path, a new one in each pass, and the same seed plays the same paths. + fn motion_key(&self, item: Item) -> Option { + let photo = item.photo()?; + let mut st = self.seed ^ 0x7061_6e7a_6f6f_6d00; + for v in [self.pass, photo.0, self.reps] { + st = splitmix(&mut st) ^ v; + } + Some(splitmix(&mut st)) + } + + /// Where each slide's picture is at `now` with pan and zoom on: the current photo moves from + /// its start view (as it comes up, its fade in included) to its end view over its duration, + /// frozen while paused and held at the start in a manual slideshow (no slide is ever due + /// there); a photo fading out stays at its end view. Both are `None` with pan and zoom off. + pub fn pan_zoom(&self, now: f64) -> PanZoom { + if !self.settings.pan_and_zoom { + return PanZoom { current: None, from: None }; + } + let amount = self.settings.pan_and_zoom_amount; + let current = self.current(); + let t = if self.settings.manual { + 0.0 + } else { + let d = self.duration(current); + if d > 0.0 { (self.clock(now) - self.started) / d } else { 1.0 } + }; + let from = self.frame(now).from.and(self.from_key).map(|k| Motion::new(k, amount).at(1.0)); + PanZoom { current: self.motion_key(current).map(|k| Motion::new(k, amount).at(t)), from } + } + /// What to draw at `now`. pub fn frame(&self, now: f64) -> Frame { let now = self.clock(now); @@ -597,6 +665,7 @@ impl Playback { t = Tick::Advanced(self.current()); } self.from = None; + self.from_key = None; self.held = None; self.started = now; if self.paused_at.is_some() { diff --git a/crates/engine/src/slideshow/tests.rs b/crates/engine/src/slideshow/tests.rs index d329d5993d..310004e0d3 100644 --- a/crates/engine/src/slideshow/tests.rs +++ b/crates/engine/src/slideshow/tests.rs @@ -212,6 +212,90 @@ fn a_manual_slideshow_moves_only_with_the_arrows() { assert!(d.merged(&json!({"manual": "yes"})).is_err()); } +#[test] +fn pan_and_zoom_moves_each_photo_over_its_slide_on_its_own_path() { + // off: every slide shows its whole picture + let p = Playback::new(ids(3), None, settings(4.0, 1.0), 1, 0.0).unwrap(); + assert_eq!(p.pan_zoom(2.0), PanZoom { current: None, from: None }); + + let s = PlaybackSettings { pan_and_zoom: true, repeat: true, ..settings(4.0, 1.0) }; + let mut p = Playback::new(ids(3), None, s.clone(), 9, 0.0).unwrap().with_titles(Some(2.0), None); + assert_eq!(p.pan_zoom(1.0).current, None, "a title screen doesn't move"); + assert_eq!(p.tick(2.0, all_ready), Tick::Advanced(ph(1))); + let m1 = Motion::new(p.motion_key(ph(1)).unwrap(), 0.5); + assert_eq!(p.pan_zoom(2.0).current, Some(m1.start), "a photo comes up at its start view"); + assert_eq!(p.pan_zoom(2.5).from, None, "the intro fading out doesn't move either"); + assert_eq!(p.pan_zoom(4.0).current, Some(m1.at(0.5)), "half way through its 4 s, fade in included"); + // paused: frozen + p.toggle_pause(4.0); + assert_eq!(p.pan_zoom(100.0).current, Some(m1.at(0.5))); + p.toggle_pause(100.0); + assert_eq!(p.pan_zoom(101.0).current, Some(m1.at(0.75)), "and carries on from there"); + // the next photo: its own path from its start; the one fading out stays at its end view + assert_eq!(p.tick(102.0, all_ready), Tick::Advanced(ph(2))); + let z = p.pan_zoom(102.5); + let m2 = Motion::new(p.motion_key(ph(2)).unwrap(), 0.5); + assert_ne!(m1, m2, "every photo has its own path"); + assert_eq!(z.current, Some(m2.at(0.125))); + assert_eq!(z.from, Some(m1.end)); + assert_eq!(p.pan_zoom(103.5).from, None, "after the fade"); + // a slide that is due but not ready holds its end view + assert_eq!(p.tick(106.0, |i| i != ph(3)), Tick::Waiting(ph(3))); + assert_eq!(p.pan_zoom(110.0).current, Some(m2.end)); + // the same seed plays the same paths; another seed other ones + let q = Playback::new(ids(3), None, s.clone(), 9, 0.0).unwrap(); + assert_eq!(q.motion_key(ph(1)).map(|k| Motion::new(k, 0.5)), Some(m1)); + let r = Playback::new(ids(3), None, s, 10, 0.0).unwrap(); + assert_ne!(r.motion_key(ph(1)), q.motion_key(ph(1))); +} + +#[test] +fn pan_and_zoom_paths_change_each_pass_and_hold_in_a_manual_slideshow() { + let s = PlaybackSettings { pan_and_zoom: true, repeat: true, ..settings(4.0, 1.0) }; + // a new pass: a new path for the same photo + let mut p = Playback::new(ids(2), None, PlaybackSettings { fade_duration: 0.0, ..s.clone() }, 9, 0.0).unwrap(); + let first = p.pan_zoom(0.0).current; + p.tick(4.0, all_ready); + assert_eq!(p.tick(8.0, all_ready), Tick::Advanced(ph(1))); + assert_ne!(p.pan_zoom(8.0).current, first, "a fresh path in the next pass"); + // a single photo repeating starts again on a new path + let mut p = Playback::new(ids(1), None, s.clone(), 9, 0.0).unwrap(); + let first = p.pan_zoom(0.0).current; + assert_eq!(p.tick(4.0, all_ready), Tick::Idle); + assert_ne!(p.pan_zoom(4.0).current, first); + // the amount sets the zoom + let close = |amount: f64| { + let p = Playback::new(ids(1), None, PlaybackSettings { pan_and_zoom_amount: amount, ..s.clone() }, 9, 0.0).unwrap(); + let m = Motion::new(p.motion_key(ph(1)).unwrap(), amount); + m.start.zoom.max(m.end.zoom) + }; + assert!(close(1.0) > close(0.0)); + // a manual slideshow holds each photo at its start view; ← / → start the next one there + let mut p = Playback::new(ids(3), None, PlaybackSettings { manual: true, ..s }, 9, 0.0).unwrap(); + let start = Motion::new(p.motion_key(ph(1)).unwrap(), 0.5).start; + assert_eq!(p.pan_zoom(500.0).current, Some(start)); + p.step(1, 500.0); + assert_eq!(p.pan_zoom(900.0).current, Some(Motion::new(p.motion_key(ph(2)).unwrap(), 0.5).start)); +} + +#[test] +fn pan_and_zoom_settings_round_trip_and_are_checked() { + let d = PlaybackSettings::default(); + assert!(!d.pan_and_zoom, "off by default"); + assert_eq!(d.pan_and_zoom_amount, 0.5); + let m = d.merged(&json!({"panAndZoom": true, "panAndZoomAmount": 0.8})).unwrap(); + assert!(m.pan_and_zoom); + assert_eq!((m.to_json()["panAndZoom"].clone(), m.to_json()["panAndZoomAmount"].clone()), (json!(true), json!(0.8))); + assert_eq!(d.merged(&json!({"panAndZoomAmount": 3})).unwrap().pan_and_zoom_amount, 1.0, "clamped"); + assert_eq!(d.merged(&json!({"panAndZoomAmount": -1})).unwrap().pan_and_zoom_amount, 0.0); + assert!(d.merged(&json!({"panAndZoom": "on"})).is_err()); + assert!(d.merged(&json!({"panAndZoomAmount": "high"})).is_err()); + let s = PlaybackSettings { pan_and_zoom_amount: f64::NAN, ..d.clone() }.sanitized(); + assert_eq!(s.pan_and_zoom_amount, 0.5, "not finite: the default"); + let off = d.merged(&json!({"panAndZoomAmount": 0.2, "panAndZoom": false})).unwrap(); + assert_eq!(off.pan_and_zoom_amount, 0.2, "the amount is kept with the effect off"); +} + #[test] fn a_single_photo_repeats_without_changing() { let mut p = Playback::new(ids(1), None, settings(1.0, 0.5), 1, 0.0).unwrap(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index c0ded23ddb..a5b0a842b6 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -403,7 +403,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s .execute( "slideshow.playback", - &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "manual": true}), + &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "manual": true, "panAndZoom": true, "panAndZoomAmount": 0.25}), ) .unwrap(); assert_eq!(r["fadeColor"], "#000000"); @@ -417,7 +417,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s.execute("slideshow.playback", &json!({})).unwrap(); assert_eq!( r, - json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true, "manual": true}) + json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true, "manual": true, "panAndZoom": true, "panAndZoomAmount": 0.25}) ); drop(s); // out-of-range values written by hand are clamped when the library opens diff --git a/crates/slideshow/src/lib.rs b/crates/slideshow/src/lib.rs index 5827491d92..7de62086cd 100644 --- a/crates/slideshow/src/lib.rs +++ b/crates/slideshow/src/lib.rs @@ -1,6 +1,7 @@ //! Slideshow slides for LightCraft: the settings of Lightroom Classic's Slideshow Layout, Options //! and Backdrop panels ([`SlideSettings`]) and the CPU composer that draws one slide from a -//! rendered photo ([`compose`]). +//! rendered photo ([`compose`]), and the pan and zoom path a slide's photo follows during +//! playback ([`Motion`]). //! //! No UI and no catalog here: playback, the settings preview, the `slideshow.preview` command and //! (later) slideshow export all call [`compose`], so every one of them draws the same pixels. @@ -17,7 +18,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod compose; +mod motion; mod settings; pub use compose::{Layout, Rect, compose, compose_with, layout, photo_size}; +pub use motion::{Motion, View, ZOOM_HIGH, ZOOM_LOW}; pub use settings::{Aspect, MARGIN_MAX, MAX_SIDE, SHADOW_OFFSET_MAX, SHADOW_RADIUS_MAX, STROKE_MAX, SlideSettings, hex, parse_color}; diff --git a/crates/slideshow/src/motion.rs b/crates/slideshow/src/motion.rs new file mode 100644 index 0000000000..ed6d9cd8aa --- /dev/null +++ b/crates/slideshow/src/motion.rs @@ -0,0 +1,140 @@ +//! Pan and zoom (the Playback panel's Pan And Zoom): which part of a photo shows at each moment of +//! its slide. +//! +//! A [`Motion`] runs at constant speed from one [`View`] to another over the slide's time. A view +//! is a window of the photo in normalized coordinates (0–1 across and down) with the photo's own +//! aspect, so it never reaches past the photo's edges and is the same at any resolution. The path +//! comes from a key (playback derives it from its seed, the pass and the photo): the same key +//! always gives the same path, and different keys give different ones. + +/// Zoom of the closer view at amount 0 (Low) and at amount 1 (High). +pub const ZOOM_LOW: f64 = 1.01; +pub const ZOOM_HIGH: f64 = 1.12; +/// The wider view's share of the closer view's zoom above 1. +const WIDE_SHARE: f64 = 0.25; + +/// A window of the photo: its zoom (1 = the whole photo) and its centre (0–1 across and down). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct View { + pub zoom: f64, + pub x: f64, + pub y: f64, +} + +impl View { + /// The whole photo. + pub const FULL: View = View { zoom: 1.0, x: 0.5, y: 0.5 }; + + /// The window as (x0, y0, x1, y1), inside 0–1: a zoom below 1 or not finite is 1, and the + /// centre is kept far enough from the edges for the window to fit. + pub fn window(&self) -> (f64, f64, f64, f64) { + let z = if self.zoom.is_finite() { self.zoom.max(1.0) } else { 1.0 }; + let h = 0.5 / z; + let c = |v: f64| if v.is_finite() { v.clamp(h, 1.0 - h) } else { 0.5 }; + let (x, y) = (c(self.x), c(self.y)); + (x - h, y - h, x + h, y + h) + } +} + +/// A slide's pan and zoom: from `start` when the slide comes up to `end` when its time is over. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Motion { + pub start: View, + pub end: View, +} + +/// SplitMix64 step. +fn mix(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// A number in 0–1 from `state`. +fn unit(state: &mut u64) -> f64 { + (mix(state) >> 11) as f64 / (1u64 << 53) as f64 +} + +impl Motion { + /// The path for `key` at `amount` (0 = Low, 1 = High; clamped, not finite = 0.5). One end is + /// the closer view (zoom [`ZOOM_LOW`] at Low to [`ZOOM_HIGH`] at High), the other a wider one; + /// whether the slide zooms in or out and where each view sits come from the key. + pub fn new(key: u64, amount: f64) -> Motion { + let a = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.5 }; + let close = ZOOM_LOW + (ZOOM_HIGH - ZOOM_LOW) * a; + let wide = 1.0 + (close - 1.0) * WIDE_SHARE; + let mut st = key; + let (z0, z1) = if unit(&mut st) < 0.5 { (wide, close) } else { (close, wide) }; + let mut place = |z: f64| { + let room = 1.0 - 1.0 / z; + View { zoom: z, x: 0.5 / z + room * unit(&mut st), y: 0.5 / z + room * unit(&mut st) } + }; + let start = place(z0); + let end = place(z1); + Motion { start, end } + } + + /// The view at `t` (0 = the slide's start, 1 = its end; clamped, not finite = 0). Zoom and + /// centre move linearly; the window stays inside the photo all the way. + pub fn at(&self, t: f64) -> View { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + let l = |a: f64, b: f64| a + (b - a) * t; + View { zoom: l(self.start.zoom, self.end.zoom), x: l(self.start.x, self.end.x), y: l(self.start.y, self.end.y) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn inside(v: View) -> bool { + let (x0, y0, x1, y1) = v.window(); + x0 >= 0.0 && y0 >= 0.0 && x1 <= 1.0 + 1e-12 && y1 <= 1.0 + 1e-12 && x1 > x0 && y1 > y0 + } + + #[test] + fn the_same_key_gives_the_same_path_and_other_keys_other_paths() { + assert_eq!(Motion::new(7, 0.5), Motion::new(7, 0.5)); + let paths: Vec = (0..32).map(|k| Motion::new(k, 0.5)).collect(); + for (i, a) in paths.iter().enumerate() { + for b in &paths[i + 1..] { + assert_ne!(a, b, "every key has its own path"); + } + } + assert!(paths.iter().any(|m| m.start.zoom < m.end.zoom) && paths.iter().any(|m| m.start.zoom > m.end.zoom), "in and out"); + } + + #[test] + fn the_amount_sets_how_far_it_zooms() { + for k in 0..64 { + let low = Motion::new(k, 0.0); + let high = Motion::new(k, 1.0); + let close = |m: &Motion| m.start.zoom.max(m.end.zoom); + assert!((close(&low) - ZOOM_LOW).abs() < 1e-12, "{low:?}"); + assert!((close(&high) - ZOOM_HIGH).abs() < 1e-12, "{high:?}"); + assert!(low.start.zoom > 1.0 && low.end.zoom > 1.0, "Low still moves a little"); + } + assert_eq!(Motion::new(3, 7.0), Motion::new(3, 1.0), "clamped"); + assert_eq!(Motion::new(3, f64::NAN), Motion::new(3, 0.5)); + } + + #[test] + fn the_window_never_leaves_the_photo() { + for k in 0..256 { + let m = Motion::new(k, (k % 5) as f64 / 4.0); + for i in 0..=20 { + let v = m.at(i as f64 / 20.0); + assert!(inside(v), "key {k} at {i}: {v:?} {:?}", v.window()); + } + } + let m = Motion::new(1, 1.0); + assert_eq!(m.at(-1.0), m.start); + assert_eq!(m.at(2.0), m.end); + assert_eq!(m.at(f64::NAN), m.start); + assert_eq!(View::FULL.window(), (0.0, 0.0, 1.0, 1.0)); + assert_eq!(View { zoom: f64::NAN, x: 9.0, y: -1.0 }.window(), (0.0, 0.0, 1.0, 1.0), "bad values: the whole photo"); + assert_eq!(View { zoom: 2.0, x: 0.0, y: 1.0 }.window(), (0.0, 0.5, 0.5, 1.0), "the centre is moved in"); + } +} diff --git a/crates/ui-egui/src/dialogs/settings/slideshow.rs b/crates/ui-egui/src/dialogs/settings/slideshow.rs index a11bbfff60..1d280d0d31 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow.rs @@ -93,6 +93,28 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); + let mut v = s.pan_and_zoom; + if check(ui, "settings.slideshowPanAndZoom", &mut v, "Pan and zoom") { + let _ = app.run("slideshow.playback", json!({"panAndZoom": v})); + } + row(ui, t, crate::i18n::tr("Amount"), |ui| { + ui.add_enabled_ui(s.pan_and_zoom, |ui| { + ui.label(crate::i18n::tr("Low")); + let mut a = s.pan_and_zoom_amount; + let r = ui.add(egui::Slider::new(&mut a, 0.0..=1.0).show_value(false)); + register(ui, "slider:slideshowPanAndZoom", r.rect); + ui.label(crate::i18n::tr("High")); + if r.changed() + && let Ok(next) = app.session.slideshow.merged(&json!({"panAndZoomAmount": a})) + { + app.session.slideshow = next; + } + if r.drag_stopped() || (r.changed() && !r.dragged()) { + let _ = app.run("slideshow.playback", json!({"panAndZoomAmount": a})); + } + }); + }); + hint(ui, t, crate::i18n::tr("Each photo moves and zooms slowly while it is up, on a path of its own. Exports show the photos still.")); let mut v = s.random_order; if check(ui, "settings.slideshowRandom", &mut v, "Random order") { let _ = app.run("slideshow.playback", json!({"randomOrder": v})); diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index cfe0ce6e68..9671c96bf8 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -1,6 +1,6 @@ //! The slideshow (View ▸ Slideshow, ⌥⌘↩): the photos in view, full screen, played with the //! library's Playback settings (`slideshow.playback`: slide and fade durations, fade colour, -//! random order, repeat, preparing previews in advance, manual slideshow). +//! random order, repeat, preparing previews in advance, manual slideshow, pan and zoom). //! //! The timeline is [`lightcraft_engine::slideshow::Playback`] (no egui, tested on its own); this //! module renders the slides, draws the frame it asks for and the playback controls. @@ -22,11 +22,17 @@ //! render worker ([`crate::render::Renderer::request_title`]), prepared ahead, waited for and //! faded like photo slides. They never move the selection, and the controls show "Intro" / "End" //! in place of "n / N" while one is up (titles aren't photos, so N stays the number of photos). +//! +//! Pan and zoom ([`Playback::pan_zoom`]) moves the photo's part of each slide's texture: the photo +//! inside its image cell for a composed slide, while the backdrop, margins, stroke and shadow stay +//! where they are. A photo drawn on its own, and a slide with overlays (drawn into its texture, +//! where they can cross the cell's edge), move as a whole. A title screen does not move. use egui::{Align2, Color32, Pos2, Rect, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_engine::slideshow::{Item, Playback, Tick, Title}; use lightcraft_pipeline::geometry::Frame; +use lightcraft_slideshow::View; use serde_json::{Value, json}; use crate::LightcraftApp; @@ -53,9 +59,10 @@ pub struct Run { } /// `view.slideshow {interval?, seed?, slideDuration?, fadeDuration?, fadeColor?, randomOrder?, -/// repeat?, preparePreviews?, manual?}`: play the photos in view from the selected one with the library's -/// playback settings; the keys given change them for this run only (`interval` = slideDuration, -/// `seed` fixes the random order). The intro and ending screens that are on (`slideshow.titles`) +/// repeat?, preparePreviews?, manual?, panAndZoom?, panAndZoomAmount?}`: play the photos in view +/// from the selected one with the library's playback settings; the keys given change them for +/// this run only (`interval` = slideDuration, `seed` fixes the random order and the pan and zoom +/// paths). The intro and ending screens that are on (`slideshow.titles`) /// play before the first photo and after the last one. With no photos in view there is nothing /// to show (titles alone don't make a slideshow). pub fn start(app: &mut LightcraftApp, p: &Value, now: f64) -> Result { @@ -130,6 +137,12 @@ pub fn state(play: &Playback, now: f64) -> Value { // (null in a manual slideshow: no slide is ever due) "remaining": play.remaining(now), "manual": play.settings().manual, + "panAndZoom": play.settings().pan_and_zoom, + // (the current photo's window, 0–1 across and down; null when it shows whole) + "view": play.pan_zoom(now).current.map(|v| { + let (x0, y0, x1, y1) = v.window(); + json!([x0, y0, x1, y1]) + }), }) } @@ -173,8 +186,9 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { after(app, t); let Some(run) = app.ui.slideshow.as_ref() else { return }; let f = run.play.frame(now); - if f.from.is_some() { - ctx.request_repaint(); // a fade draws every frame + let moving = run.play.pan_zoom(now).current.is_some() && !run.play.is_paused() && !run.play.settings().manual; + if f.from.is_some() || moving { + ctx.request_repaint(); // a fade, and pan and zoom, draw every frame } else if !run.play.is_paused() && !run.play.settings().manual { ctx.request_repaint_after(std::time::Duration::from_secs_f64(run.play.remaining(now).clamp(0.016, 120.0))); } @@ -253,12 +267,44 @@ fn wanted(play: &Playback, now: f64) -> Vec<(Item, u32)> { /// screen has nothing to stand in for it: the black canvas shows until it lands. fn texture(app: &LightcraftApp, item: Item) -> Option<&crate::render::Tex> { let Item::Photo(id) = item else { return app.renderer.textures.get(&Slot::Slide(item)) }; - app.renderer - .textures - .get(&Slot::Slide(item)) - .filter(|t| t.photo == id) - .or_else(|| app.renderer.textures.get(&Slot::Main).filter(|t| t.photo == id)) - .or_else(|| app.renderer.thumb(id)) + slide_texture(app, id).or_else(|| app.renderer.textures.get(&Slot::Main).filter(|t| t.photo == id)).or_else(|| app.renderer.thumb(id)) +} + +/// Photo `id`'s own slide render. +fn slide_texture(app: &LightcraftApp, id: PhotoId) -> Option<&crate::render::Tex> { + app.renderer.textures.get(&Slot::Slide(Item::Photo(id))).filter(|t| t.photo == id) +} + +/// The part of `item`'s texture `t` that pan and zoom moves, in texture coordinates (0–1): the +/// photo's visible part of a composed slide without overlays (its image cell), else all of it (a +/// photo drawn on its own, a plain slide or a stand-in, and a slide with overlays, which are +/// drawn into its texture and can cross the cell's edge: they move with the slide). +pub(crate) fn moving_part(app: &LightcraftApp, item: Item, t: &crate::render::Tex) -> Rect { + let Item::Photo(id) = item else { return full_uv() }; + let composed = !app.session.slides_plain() && !app.session.slide_overlays.any() && slide_texture(app, id).is_some_and(|s| std::ptr::eq(s, t)); + let [w, h] = t.size; + let Some(aspect) = app.session.slide_photo_aspect(id).filter(|_| composed && w > 0 && h > 0) else { return full_uv() }; + let v = lightcraft_slideshow::layout(&app.session.slide_layout, aspect, w, h).visible; + let (w, h) = (w as f64, h as f64); + let uv = Rect::from_min_max(pos2((v.x0 / w) as f32, (v.y0 / h) as f32), pos2((v.x1 / w) as f32, (v.y1 / h) as f32)); + if uv.is_positive() { uv.intersect(full_uv()) } else { full_uv() } +} + +/// Draw texture `t` into `r` with `tint`. With a pan and zoom `view`, the `part` of it (texture +/// coordinates) shows that view's window of itself in the same place; the rest is drawn as is. +fn paint(p: &egui::Painter, t: &crate::render::Tex, r: Rect, part: Rect, view: Option, tint: Color32) { + let Some(v) = view else { + p.image(t.tex.id(), r, full_uv(), tint); + return; + }; + let at = |u: Pos2| pos2(r.min.x + u.x * r.width(), r.min.y + u.y * r.height()); + let place = Rect::from_min_max(at(part.min), at(part.max)); + for band in outside(r, place) { + p.with_clip_rect(band).image(t.tex.id(), r, full_uv(), tint); + } + let (x0, y0, x1, y1) = v.window(); + let sub = |x: f64, y: f64| pos2(part.min.x + x as f32 * part.width(), part.min.y + y as f32 * part.height()); + p.image(t.tex.id(), place, Rect::from_min_max(sub(x0, y0), sub(x1, y1)), tint); } fn full_uv() -> Rect { @@ -299,6 +345,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let side = super::detail::texture_side(ui.ctx()); let want = wanted(&run.play, now); let frame = run.play.frame(now); + let pz = run.play.pan_zoom(now); let mut unrenderable = Vec::new(); for (item, priority) in &want { match *item { @@ -325,12 +372,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let p = ui.painter_at(canvas); p.rect_filled(canvas, 0.0, Color32::BLACK); let rect_of = |t: &crate::render::Tex| super::detail::fit_texture_rect(canvas, t.size); - let draw = |id: Item, alpha: f32| -> Option { + let view_of = |id: Item| { + if id == frame.current { + pz.current + } else if Some(id) == frame.from { + pz.from + } else { + None + } + }; + let draw_on = |p: &egui::Painter, id: Item, alpha: f32| -> Option { let t = texture(app, id)?; let r = rect_of(t); - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); + paint(p, t, r, moving_part(app, id, t), view_of(id), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); Some(r) }; + let draw = |id: Item, alpha: f32| draw_on(&p, id, alpha); let k = frame.progress.clamp(0.0, 1.0); match (frame.from, frame.fade_color) { // fade through a colour: out to it, then in from it @@ -348,17 +405,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the old one is, it fades to the backdrop (Some(from), None) => { let new_rect = texture(app, frame.current).map(rect_of); - if let Some(t) = texture(app, from) { - let r = rect_of(t); + if let Some(r) = texture(app, from).map(rect_of) { match new_rect { Some(n) => { - p.with_clip_rect(n.intersect(canvas)).image(t.tex.id(), r, full_uv(), Color32::WHITE); + draw_on(&p.with_clip_rect(n.intersect(canvas)), from, 1.0); for band in outside(r, n) { - p.with_clip_rect(band).image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + draw_on(&p.with_clip_rect(band), from, 1.0 - k); } } None => { - p.image(t.tex.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + draw(from, 1.0 - k); } } } diff --git a/crates/ui-egui/src/tests/slideshow.rs b/crates/ui-egui/src/tests/slideshow.rs index 137dd9317a..e1b4b8b2cb 100644 --- a/crates/ui-egui/src/tests/slideshow.rs +++ b/crates/ui-egui/src/tests/slideshow.rs @@ -301,6 +301,80 @@ fn a_manual_slideshow_waits_for_the_arrow_keys() { h.settle(SETTLE); } +#[test] +fn pan_and_zoom_moves_the_photo_inside_its_cell() { + let mut h = grid(); + run(&mut h, "slideshow.layout", json!({"margins": 0.1, "backdropColor": "#ff0000"})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + let r = run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "seed": 3})); + assert_eq!((r["settings"]["panAndZoom"].clone(), r["settings"]["panAndZoomAmount"].clone()), (json!(true), json!(1.0)), "{r}"); + let current = photo_up(&h); + assert!(h.step_until(SETTLE, |h| has_slide(h, current)), "the slide is composed and ready"); + h.step(); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_eq!(s["panAndZoom"], true, "{s}"); + let start = s["view"].clone(); + let w = start.as_array().map(|v| v.iter().filter_map(|x| x.as_f64()).collect::>()).unwrap_or_default(); + assert_eq!(w.len(), 4, "{s}"); + assert!(w[0] >= 0.0 && w[1] >= 0.0 && w[2] <= 1.0 && w[3] <= 1.0 && w[2] - w[0] < 1.0, "a window inside the photo: {s}"); + let moving = h.paint(); + // the backdrop stays where it is + for (x, y) in [(5, 5), (995, 5), (500, 30), (30, 350), (985, 350)] { + assert_eq!(painted(&moving, x, y), [255, 0, 0], "margin at ({x}, {y})"); + } + // playing on, it moves + run(&mut h, "slideshow.togglePause", json!({})); + for _ in 0..240 { + h.step(); + } + assert_eq!(photo_up(&h), current, "the same slide is up"); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_ne!(s["view"], start, "{s}"); + // the photo's cell moves; with an overlay drawn into the slide, the whole slide moves, so an + // overlay crossing the cell's edge stays in one piece + let part = |h: &Headless| { + let tex = h.app.renderer.textures.get(&Slot::Slide(current.into())).unwrap(); + crate::panels::slideshow::moving_part(&h.app, current.into(), tex) + }; + let cell = part(&h); + assert!(cell.min.x > 0.05 && cell.max.x < 0.95 && cell.min.y > 0.05 && cell.max.y < 0.95, "{cell:?}"); + run(&mut h, "slideshow.overlays", json!({"ratingStars": {"enabled": true}})); + assert_eq!(part(&h), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0))); + run(&mut h, "slideshow.overlays", json!({"ratingStars": {"enabled": false}})); + run(&mut h, "slideshow.end", json!({})); + // off: the photo shows whole, so the same slide paints other pixels in its cell + run(&mut h, "slideshow.playback", json!({"panAndZoom": false})); + run(&mut h, "library.select", json!({"ids": [current.0]})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true})); + assert_eq!(photo_up(&h), current); + assert!(h.step_until(SETTLE, |h| has_slide(h, current))); + h.step(); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_eq!((s["panAndZoom"].clone(), s["view"].clone()), (json!(false), json!(null)), "{s}"); + let still = h.paint(); + let mut changed = 0; + for y in (100..600).step_by(4) { + for x in (100..900).step_by(4) { + if painted(&moving, x, y) != painted(&still, x, y) { + changed += 1; + } + } + } + assert!(changed > 500, "the zoomed photo differs from the whole one ({changed} samples)"); + assert_eq!(painted(&still, 5, 5), [255, 0, 0]); + run(&mut h, "slideshow.end", json!({})); + // the Settings controls + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + reveal(&mut h, "check:settings.slideshowPanAndZoom"); + assert!(latest_widget_rect(&h, "slider:slideshowPanAndZoom").is_some(), "the Low to High slider"); + let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowPanAndZoom"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.session.slideshow.pan_and_zoom, "the checkbox goes through slideshow.playback"); + h.settle(SETTLE); +} + #[test] fn random_order_starts_at_the_selection_and_is_fixed_by_the_seed() { let order = |seed: u64| { diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a9dd725236..21b94d253d 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -757,7 +757,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-SS-BACKDROP | Slideshow backdrop | P2 | ✅ | `cmd:slideshow.layout`, `path:crates/slideshow/src/compose.rs` | Background colour, Color Wash (a gradient from a second colour, full at the side its angle points to, at an opacity), Background Image (a library photo filling the slide at an opacity: "Use selected photo" in Settings ▸ Slideshow, `backgroundImage` in `slideshow.layout`; rendered once and shared by the slides). In the web build the composition runs on the main thread when a worker's render comes back | | LRC-SS-TITLES | Slideshow titles | P2 | 🟡 | `cmd:slideshow.titles`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_title.rs`, `path:crates/ui-egui/src/dialogs/settings/slide_titles.rs` | Intro screen and ending screen, each on or off (library preference, `slideshow.titles`; Settings ▸ Slideshow ▸ Titles): a background colour and, centred on it, the identity plate of the Overlays section (its text or image; Add Identity Plate) or the screen's own line of text, in the plate's colour or an override colour, at a scale (height as a share of the slide's shorter side; text wider than the slide shrinks to fit), for its own duration (default: the slide duration). Titles are items of the playback timeline: composed off the UI thread by the same composer at the screen's size, prepared ahead, waited for and faded like slides; the intro plays once before the first photo, the ending after the last photo when repeat is off; random order never moves them; ←/→ step across them; they never change the selection and the control bar shows Intro / End instead of n / N. `slideshow.preview {title}` renders a screen; the Settings preview shows Photo / Intro / Ending. An empty view still refuses to play ("no photos to show"). Missing: Classic's exact behaviour with Repeat on is not verified (we never show the ending, and show the intro only at the start, while repeating), the Identity Plate Editor's styled text (Inter SemiBold only), override colour leaves an image plate's colours alone, the Slideshow module's Titles panel (settings live in Settings ▸ Slideshow). Slideshow export (LRC-SS-EXPORT) includes them: a PDF page / JPEG each, and in video they hold and fade like slides | | LRC-SS-MUSIC | Slideshow music | P2 | ⬜ | | | -| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan & zoom, choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | +| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end`, `path:crates/slideshow/src/motion.rs` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration), pan and zoom (`panAndZoom`, off by default, with a Low–High amount `panAndZoomAmount` 0–1, default 0.5: each photo moves at constant speed from one window of itself to another over its slide's time, its fade in included, zooming in or out between about 1.0025× and 1.01× at Low and 1.03× and 1.12× at High, on a path from the playback seed, the pass and the photo, so every photo and every pass has its own path and a seed replays it; the photo moves inside its image cell and the backdrop stays still, except that with overlays on the whole slide moves with them; title screens don't move; pause freezes it, a photo fading out stays at its end view, a manual slideshow holds each photo at its start view; these motion rules are LightCraft's own). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan and zoom in exports (LRC-SS-EXPORT), choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | | LRC-SS-EXPORT | Slideshow export | P2 | 🟡 | `cmd:slideshow.export`, `cmd:slideshow.exportStatus`, `cmd:dialog.slideshowExport`, `cmd:app.slideshowExport`, `path:crates/engine/src/slideshow_export.rs`, `path:crates/codecs/src/video.rs`, `path:crates/ui-egui/src/dialogs/slideshow_export.rs` | View ▸ Export Slideshow… (and Export PDF / JPEG / Video in Settings ▸ Slideshow): the photos in view as their composed slides (layout, overlays) between the intro and ending screens that are on, in view order. **PDF**: one page per slide at 1024 / 1920 / 3840 px (any 64–8192 by command; page = slide pixels in points, aspect from the aspect preview, "screen" = 16:9), JPEG quality, each page carrying the slide duration and a fade transition for presentation mode, "Automatically show full screen" (`/PageMode /FullScreen`). **JPEG**: `-001.jpg`… in a new folder. **Video**: AV1 (rav1e, fast preset) in MP4 or WebM written by our own muxers, 720p / 1080p (64–2160 by command), 24 / 30 fps (25 / 60 by command); each slide held for its duration (one long sample: variable frame rate) and fades rendered as blended frames (crossfade or through the fade colour); at most 2 hours. Runs in the background with a row in the activity stack (frames or slides done, ✕ cancels); files are written as `.part` and renamed when complete, so a cancelled or failed export leaves nothing; a photo that can't be rendered is skipped with a warning. Missing: H.264 (Classic's codec; patents, no pure-Rust encoder), audio / music in the video (LRC-SS-MUSIC), random order and pan & zoom in exports, the PDF's per-page fades follow the viewer (Acrobat), export presets, Classic's export dialog sizes beyond these, the web build (no export) | | LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | ✅ | `cmd:dialog.print`, `cmd:print.set`, `cmd:print.get`, `cmd:print.exportPdf`, `cmd:export.contactSheet`, `crates/ui-egui/src/dialogs/print_view.rs` | File → Print… (⌘P): Single Image, Contact Sheet, Picture Package and Custom Package, one page preview each; also `print.*` commands for the CLI, control channel and MCP; the older File → Contact Sheet PDF stays | | LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | ✅ | `cmd:print.set`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | Zoom to Fill Frame, Rotate to Fit, Photo Border (width, colour; package styles) and Inner Stroke (width in points, colour) in the dialog, drawn in the preview and in the PDF; pixel-tested | diff --git a/docs/slideshow.md b/docs/slideshow.md index e0c89b0311..fc2084e2c7 100644 --- a/docs/slideshow.md +++ b/docs/slideshow.md @@ -7,7 +7,7 @@ next to a live preview of the selected photo's slide, and View ▸ Slideshow ( | Part | Commands | Code | |---|---|---| -| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead, manual slideshow | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/ui-egui/src/panels/slideshow.rs` | +| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead, manual slideshow, pan and zoom | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/slideshow/src/motion.rs` (the pan and zoom path), `crates/ui-egui/src/panels/slideshow.rs` | | Layout, options, backdrop: margins, aspect preview, zoom to fill, stroke, shadow, colour, colour wash, background photo | `slideshow.layout` | `crates/slideshow` (the composer, no UI), `crates/engine/src/slide.rs` | | Overlays: identity plate, rating stars, text with tokens, watermark | `slideshow.overlays` | `crates/engine/src/slide_overlay.rs` | | Intro and ending screens | `slideshow.titles` | `crates/engine/src/slide_title.rs` | @@ -23,7 +23,7 @@ the same pixels through the same composer. View ▸ Export Slideshow… (or Export PDF / JPEG / Video at the end of Settings ▸ Slideshow) chooses a format and size, then asks where to write. The slides are the photos in view, in view order, between the intro and ending screens that -are on; random order, repeat and manual slideshow are playback choices and don't apply. The slide aspect is the Layout's aspect preview +are on; random order, repeat, manual slideshow and pan and zoom are playback choices and don't apply. The slide aspect is the Layout's aspect preview (Screen exports 16:9). - **PDF** — one page per slide, its picture a JPEG at the chosen quality, the page as many points as the slide has @@ -61,4 +61,4 @@ rendering included. The cost is in the fades (one encoded frame per frame of fad ## Not yet The Slideshow module view (left-panel template browser, slide editor with draggable guides and overlays), music and -sync to music, pan & zoom, H.264 video, saving a slideshow with an album, export presets. +sync to music, pan and zoom in exports, H.264 video, saving a slideshow with an album, export presets. From 3d7541698171c3326db193b96d25823d17c9ebbb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 04:57:50 -0700 Subject: [PATCH 055/247] Keywords: Enter Keywords writes a keyword holding a comma or line break in quotes The Enter Keywords text now writes a keyword whose name holds a comma or a new line in double quotes, before its asterisk when only some of the selected photos have it ("Places|Paris, France"*). A marked name in quotes is read as the partial keyword inside them. Unquoted pieces are still joined into such a keyword, unless each piece is a keyword of the selection by itself. With a, b and "a, b" on every photo, deleting the "a, b" entry now takes that keyword off instead of a and b. --- crates/ui-egui/src/panels/keywording.rs | 98 ++++++++++++++++--------- 1 file changed, 64 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index e5408beb94..b513678a68 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -713,15 +713,20 @@ pub(crate) fn chips(catalog: &Catalog, photos: &[PhotoId]) -> Vec { /// The Enter Keywords text of the selection's keywords `chips`: each keyword's path, with commas /// between them and an asterisk after a keyword only some of the selected photos have. A keyword -/// every photo has whose name ends in an asterisk, or is itself in double quotes, is written in -/// double quotes, so that it reads differently from a partial keyword marked with the asterisk. +/// whose name holds a comma or a new line is written in double quotes (before its asterisk), so that +/// it reads as one name. A keyword every photo has whose name ends in an asterisk, or is itself in +/// double quotes, is also written in double quotes, so that it reads differently from a partial +/// keyword marked with the asterisk. pub(crate) fn entered_text(chips: &[Chip]) -> String { chips .iter() .map(|c| { - if !c.on_all() { + let separated = c.path.contains([',', '\n']); + if !c.on_all() && separated { + format!("\"{}\"*", c.path) + } else if !c.on_all() { format!("{}*", c.path) - } else if c.path.ends_with('*') || quoted(&c.path).is_some() { + } else if separated || c.path.ends_with('*') || quoted(&c.path).is_some() { format!("\"{}\"", c.path) } else { c.path.clone() @@ -753,14 +758,21 @@ impl Entered { } /// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except -/// where a name opened with a double quote closes with one after commas (the next piece holding a -/// double quote ends with it), or where pieces joined by their separators spell a keyword of -/// `start` whose name holds a comma or a new line (with or without its asterisk or its quotes) that -/// the text has not named yet. Either stays one name. +/// where a name opened with a double quote closes with one (the next piece holding a double quote +/// ends with it, or with it and an asterisk), and only commas lie between or the name spells a +/// keyword of `start` the text has not named yet; or where pieces joined by their separators spell +/// a keyword of `start` whose name holds a comma or a new line (with or without its asterisk or its +/// quotes) that the text has not named yet, unless each of those pieces is a keyword of `start` by +/// itself. Either stays one name. fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { use lightcraft_catalog::keywords::{clean, same}; let is_separator = |ch: char| ch == ',' || ch == '\n'; - let spells = |s: &str, c: &Chip| [Some(s), s.strip_suffix('*'), quoted(s)].into_iter().flatten().any(|n| same(&clean(n), &c.path)); + let spells = |s: &str, c: &Chip| { + let marked = s.strip_suffix('*'); + [Some(s), marked, quoted(s), marked.and_then(quoted)].into_iter().flatten().any(|n| same(&clean(n), &c.path)) + }; + // a piece that closes a name in double quotes + let closes = |s: &str| s.ends_with('"') || s.ends_with("\"*"); // the keywords of `start` the text has named so far let mut named = vec![false; start.len()]; let unnamed = |s: &str, named: &[bool]| start.iter().zip(named).position(|(c, n)| !n && spells(s, c)); @@ -776,20 +788,23 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { let mut i = 0; while let Some(first) = pieces.get(i) { // a name in double quotes, up to the piece that closes it (an unclosed one is plain pieces) - let opened = piece(first).starts_with('"') && quoted(piece(first)).is_none(); + let opened = piece(first).strip_prefix('"').is_some_and(|rest| !closes(rest)); let quoted_run = opened .then(|| { pieces .iter() .enumerate() .skip(i + 1) - .take_while(|(_, p)| p.start.checked_sub(1).and_then(|b| text.as_bytes().get(b)) == Some(&b',')) .find(|(_, p)| piece(p).contains('"')) - .filter(|(_, p)| piece(p).ends_with('"')) + .filter(|(_, p)| closes(piece(p))) .and_then(|(j, p)| Some((j - i, text.get(first.start..p.end)?.trim()))) + .filter(|&(_, s)| !s.contains('\n') || unnamed(s, &named).is_some()) }) .flatten(); - // else the most pieces that spell a keyword with separators not named yet + // else the most pieces that spell a keyword with separators not named yet, unless each + // piece is a keyword by itself + let one_each = + |from: usize, to: usize| pieces.get(from..=to).is_some_and(|run| run.iter().all(|p| start.iter().any(|c| spells(piece(p), c)))); let joined = quoted_run.or_else(|| { start .iter() @@ -798,7 +813,7 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { .filter_map(|separators| { let last = pieces.get(i + separators)?; let s = text.get(first.start..last.end)?.trim(); - unnamed(s, &named).map(|_| (separators, s)) + unnamed(s, &named).filter(|_| !one_each(i, i + separators)).map(|_| (separators, s)) }) .max_by_key(|&(separators, _)| separators) }); @@ -815,16 +830,17 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { } /// Reads the Enter Keywords `text` against `start`, the selection's keywords when the edit began. -/// Keywords are separated by commas or new lines; a keyword of `start` whose name holds a comma, and -/// a name in double quotes holding commas, are each read as one name. A keyword of `start` left out -/// of the text is taken off every selected photo. A name without an asterisk goes to every -/// selected photo (a keyword of `start` keeps its spelling, and a new name goes where +/// Keywords are separated by commas or new lines; a name in double quotes holding commas (or new +/// lines, when it is a keyword of `start`), and a keyword of `start` whose name holds a comma +/// written without its quotes, are each read as one name (see `entered_names`). A keyword of +/// `start` left out of the text is taken off every selected photo. A name without an asterisk goes +/// to every selected photo (a keyword of `start` keeps its spelling, and a new name goes where /// `Catalog::typed_keyword` puts it). A keyword only some photos have, still marked with its -/// asterisk, stays on those photos only. A name in double -/// quotes is read as written, an asterisk at its end included. A keyword every photo has whose own -/// name ends in an asterisk is also kept when written without its quotes, unless a keyword only -/// some photos have reads the same. An asterisk after any other name is refused: the error is the -/// name as typed. +/// asterisk, stays on those photos only, the name in double quotes before the asterisk included. A +/// name in double quotes is read as written, an asterisk at its end included. A keyword every +/// photo has whose own name ends in an asterisk is also kept when written without its quotes, +/// unless a keyword only some photos have reads the same. An asterisk after any other name is +/// refused: the error is the name as typed. pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result { use lightcraft_catalog::keywords::{clean, same}; let mut kept: Vec = Vec::new(); @@ -833,16 +849,20 @@ pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result Date: Sat, 31 Oct 2026 05:10:58 -0700 Subject: [PATCH 056/247] LRC-SS-PLAYBACK: the pan and zoom amount is saved and an old slide render moves whole The Amount slider writes the live value while it moves, so slideshow.playback found no change when the drag ended and did not save the library preferences. The slider now saves them after the command runs. While a slide's new render is on the way after a layout, overlay or crop change, pan and zoom moved the old texture's pixels at the cell the new settings give. The cell is now used only for the current render; an older texture moves whole until the new one lands. --- .../ui-egui/src/dialogs/settings/slideshow.rs | 5 ++ crates/ui-egui/src/panels/slideshow.rs | 9 ++- crates/ui-egui/src/tests/slideshow.rs | 71 +++++++++++++++++++ 3 files changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/settings/slideshow.rs b/crates/ui-egui/src/dialogs/settings/slideshow.rs index 1d280d0d31..49eebed646 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow.rs @@ -111,6 +111,11 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } if r.drag_stopped() || (r.changed() && !r.dragged()) { let _ = app.run("slideshow.playback", json!({"panAndZoomAmount": a})); + // the live value above already holds the amount, so the command finds no change + // to save: save it here + if let Err(e) = app.session.save_prefs() { + log::warn!("slideshow: {e}"); + } } }); }); diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index 9671c96bf8..4e843a03b5 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -278,10 +278,15 @@ fn slide_texture(app: &LightcraftApp, id: PhotoId) -> Option<&crate::render::Tex /// The part of `item`'s texture `t` that pan and zoom moves, in texture coordinates (0–1): the /// photo's visible part of a composed slide without overlays (its image cell), else all of it (a /// photo drawn on its own, a plain slide or a stand-in, and a slide with overlays, which are -/// drawn into its texture and can cross the cell's edge: they move with the slide). +/// drawn into its texture and can cross the cell's edge: they move with the slide). The cell +/// comes from the current settings, so a texture rendered with older ones (its new render still +/// on the way) also moves whole. pub(crate) fn moving_part(app: &LightcraftApp, item: Item, t: &crate::render::Tex) -> Rect { let Item::Photo(id) = item else { return full_uv() }; - let composed = !app.session.slides_plain() && !app.session.slide_overlays.any() && slide_texture(app, id).is_some_and(|s| std::ptr::eq(s, t)); + let composed = !app.session.slides_plain() + && !app.session.slide_overlays.any() + && slide_texture(app, id).is_some_and(|s| std::ptr::eq(s, t)) + && app.renderer.is_current(Slot::Slide(item), t.key); let [w, h] = t.size; let Some(aspect) = app.session.slide_photo_aspect(id).filter(|_| composed && w > 0 && h > 0) else { return full_uv() }; let v = lightcraft_slideshow::layout(&app.session.slide_layout, aspect, w, h).visible; diff --git a/crates/ui-egui/src/tests/slideshow.rs b/crates/ui-egui/src/tests/slideshow.rs index e1b4b8b2cb..48544c04b7 100644 --- a/crates/ui-egui/src/tests/slideshow.rs +++ b/crates/ui-egui/src/tests/slideshow.rs @@ -375,6 +375,77 @@ fn pan_and_zoom_moves_the_photo_inside_its_cell() { h.settle(SETTLE); } +/// While a slide's new render (after a layout change) is on the way, the old texture moves +/// whole: its cell is where the old settings put it, not where the new ones do. +#[test] +fn pan_and_zoom_moves_an_old_render_whole_until_the_new_one_lands() { + let mut h = grid(); + let open = Rc::new(Cell::new(true)); + h.app.renderer.set_offload(Box::new(RenderGate::new(open.clone()))); + run(&mut h, "slideshow.layout", json!({"margins": 0.1})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true, "seed": 3})); + let current = photo_up(&h); + let slot = Slot::Slide(current.into()); + assert!(h.step_until(SETTLE, |h| has_slide(h, current) && h.app.renderer.wanted(slot) == h.app.renderer.textures.get(&slot).map(|t| t.key))); + let part = |h: &Headless| { + let tex = h.app.renderer.textures.get(&slot).unwrap(); + crate::panels::slideshow::moving_part(&h.app, current.into(), tex) + }; + let cell = part(&h); + assert!(cell.min.x > 0.05 && cell.max.x < 0.95, "the photo's cell: {cell:?}"); + // the margins change while the next render is held back + open.set(false); + let old = h.app.renderer.textures.get(&slot).map(|t| t.key); + run(&mut h, "slideshow.layout", json!({"margins": 0.3})); + h.step(); + assert_eq!(h.app.renderer.textures.get(&slot).map(|t| t.key), old, "the old render is still drawn"); + assert_ne!(h.app.renderer.wanted(slot), old, "a new render is on the way"); + assert_eq!(part(&h), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), "the old texture moves whole"); + // the new render lands: its own cell moves again + open.set(true); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&slot).map(|t| t.key) != old)); + let cell = part(&h); + assert!(cell.min.x > 0.2 && cell.max.x < 0.8, "the new, smaller cell: {cell:?}"); + run(&mut h, "slideshow.end", json!({})); + h.settle(SETTLE); +} + +/// The amount set on the Low to High slider is saved with the library: the slider writes the +/// live value as it moves, which leaves `slideshow.playback` nothing to change when it ends. +#[test] +fn the_pan_and_zoom_amount_from_the_slider_is_there_when_the_library_reopens() { + struct Folder(std::path::PathBuf); + impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = Folder(std::env::temp_dir().join(format!("lc-ui-pan-zoom-amount-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir.0, false).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1000.0, 700.0], 1.0); + h.step(); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true})); + let before = h.app.session.slideshow.pan_and_zoom_amount; + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + let slider = reveal(&mut h, "slider:slideshowPanAndZoom"); + let r = h.request("ui.dragWidget", json!({"id": "slider:slideshowPanAndZoom", "toX": slider.left(), "toY": slider.center().y}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let amount = h.app.session.slideshow.pan_and_zoom_amount; + assert!(amount < before - 0.1, "the slider moved the amount from {before} to {amount}"); + h.settle(SETTLE); + drop(h); + let mut again = lightcraft_engine::Session::new().with_fs(); + again.open_library(&dir.0, false).unwrap(); + assert!(again.slideshow.pan_and_zoom, "the checkbox's setting is saved"); + assert_eq!(again.slideshow.pan_and_zoom_amount, amount, "the slider's amount is saved"); +} + #[test] fn random_order_starts_at_the_selection_and_is_fixed_by_the_seed() { let order = |seed: u64| { From 608e9cf1401abb477bd14b737ddb3dd614718a5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 05:13:56 -0700 Subject: [PATCH 057/247] Keywords: Enter Keywords gives up a pending edit when another library opens An Enter Keywords edit kept while its box was folded or hidden with its panel now records the library it was started in, and is given up, never applied, when the box is next drawn or folded in another library. Photo ids belong to one library, so the same ids in another library are other photos. --- crates/ui-egui/src/panels/right/keywords.rs | 31 ++++++++++++++------- crates/ui-egui/src/tests/keywording.rs | 23 +++++++++++++++ 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index 228d118487..78fcc5a500 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -216,21 +216,30 @@ struct EnterEdit { ids: Vec, /// The selection the edit was started on (`key_of`). selection: u64, + /// The library the edit was started in ([`lightcraft_engine::Session::library_generation`]): + /// photo ids are a library's own, so the same ids in another library are other photos. + library: u64, /// The last try to apply it was refused: the text stays to be put right. refused: bool, } impl EnterEdit { - fn new(chips: &[crate::panels::keywording::Chip], selection: &[PhotoId], key: u64) -> Self { + fn new(chips: &[crate::panels::keywording::Chip], selection: &[PhotoId], key: u64, library: u64) -> Self { let mut seen = std::collections::HashSet::new(); EnterEdit { text: crate::panels::keywording::entered_text(chips), start: chips.to_vec(), ids: selection.iter().filter(|id| seen.insert(**id)).map(|id| id.0).collect(), selection: key, + library, refused: false, } } + + /// Whether the edit was started on `selection` (`key_of`) in the open library. + fn is_for(&self, app: &LightcraftApp, selection: u64) -> bool { + self.selection == selection && self.library == app.session.library_generation() + } } /// The Enter Keywords box's field. @@ -261,13 +270,14 @@ fn apply_enter(app: &mut LightcraftApp, ctx: &egui::Context, edit: &EnterEdit) - } /// Another view chosen while the Enter Keywords box holds an edit: the edit is applied, as leaving -/// the box applies it, and the box gives up the cursor. An edit of another selection is given up. -/// A refused edit is kept, marked refused, and comes back when Enter Keywords is chosen again. +/// the box applies it, and the box gives up the cursor. An edit of another selection, or of another +/// library, is given up. A refused edit is kept, marked refused, and comes back when Enter Keywords +/// is chosen again. fn leave_enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { let id = enter_id(); ui.memory_mut(|m| m.surrender_focus(crate::text_field::id(ENTER_FIELD))); let Some(mut edit) = ui.data(|d| d.get_temp::(id)) else { return }; - if edit.selection == crate::key_of(selection) && !apply_enter(app, ui.ctx(), &edit) { + if edit.is_for(app, crate::key_of(selection)) && !apply_enter(app, ui.ctx(), &edit) { edit.refused = true; ui.data_mut(|d| d.insert_temp(id, edit)); } else { @@ -279,22 +289,23 @@ fn leave_enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: & /// photos have marked with an asterisk. Return, leaving the box, choosing another view or folding /// the box applies the edit to the photos selected when it started, as one undo step; Esc gives it /// up. An edit whose box was hidden with its panel is applied when the box is next drawn. Another -/// selection while the box is being edited gives the edit up too. A refused edit keeps its text and -/// says why. +/// selection while the box is being edited, or another library opened, gives the edit up too. A +/// refused edit keeps its text and says why. fn enter_keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) { let id = enter_id(); let key = crate::key_of(selection); + let library = app.session.library_generation(); let chips = app.caches.keyword_chips(&app.session.catalog, selection); let fid = crate::text_field::id(ENTER_FIELD); let focused = ui.memory(|m| m.has_focus(fid)); let kept: Option = ui.data(|d| d.get_temp(id)); - // (an edit of another selection is given up, never applied to this one) - if kept.as_ref().is_some_and(|e| e.selection != key) && focused { + // (an edit of another selection or library is given up, never applied to this one) + if kept.as_ref().is_some_and(|e| !e.is_for(app, key)) && focused { ui.memory_mut(|m| m.surrender_focus(fid)); } // (an edit kept without the cursor lost it while the box was not drawn, its panel hidden) - let left_undrawn = !focused && kept.as_ref().is_some_and(|e| e.selection == key && !e.refused); - let mut edit = kept.filter(|e| e.selection == key).unwrap_or_else(|| EnterEdit::new(&chips, selection, key)); + let left_undrawn = !focused && kept.as_ref().is_some_and(|e| e.is_for(app, key) && !e.refused); + let mut edit = kept.filter(|e| e.is_for(app, key)).unwrap_or_else(|| EnterEdit::new(&chips, selection, key, library)); // Return applies the edit (Shift+Return or a pasted line break separates keywords as a comma does) let returned = focused && ui.input_mut(|i| { diff --git a/crates/ui-egui/src/tests/keywording.rs b/crates/ui-egui/src/tests/keywording.rs index b44b859acf..5704612d5c 100644 --- a/crates/ui-egui/src/tests/keywording.rs +++ b/crates/ui-egui/src/tests/keywording.rs @@ -1065,6 +1065,29 @@ fn enter_keywords_applies_an_edit_when_the_box_is_folded_or_hidden() { assert!(all_have(&h, &ids, "pier"), "hiding the box with its panel applied it when it came back"); } +/// An edit kept while its box was hidden with its panel is given up when another library is open +/// by the time the box is drawn or folded again: that library's photos with the same ids keep their +/// keywords. +#[test] +fn enter_keywords_gives_up_an_edit_when_another_library_opens() { + for folded in [false, true] { + let (mut h, ids) = two_selected(); + enter(&mut h, "beach, Weddings*, pier"); + ask(&mut h, "ui.set", json!({"right": "info"})); + h.step(); + h.app.session = lightcraft_engine::Session::with_demo(); + ask(&mut h, "engine.execute", json!({"command": "library.select", "params": {"ids": ids}})); + let before: Vec> = ids.iter().map(|id| keywords_of(&h, *id)).collect(); + if folded { + h.app.ui.toggle_folded("keywording"); + } + ask(&mut h, "ui.set", json!({"right": "keywords"})); + h.step(); + let after: Vec> = ids.iter().map(|id| keywords_of(&h, *id)).collect(); + assert_eq!(after, before, "the other library's photos keep their keywords (box folded: {folded})"); + } +} + /// An asterisk after a name that is not a keyword only some photos have is refused: the photos keep /// their keywords, the box keeps the cursor and its text, and the refusal is said. #[test] From 41e2d5450ca9240313989ccbfcc963678c752554 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 05:22:46 -0700 Subject: [PATCH 058/247] LRC-SS-PLAYBACK: motion comments use American spelling --- crates/slideshow/src/motion.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/slideshow/src/motion.rs b/crates/slideshow/src/motion.rs index ed6d9cd8aa..9313b55257 100644 --- a/crates/slideshow/src/motion.rs +++ b/crates/slideshow/src/motion.rs @@ -13,7 +13,7 @@ pub const ZOOM_HIGH: f64 = 1.12; /// The wider view's share of the closer view's zoom above 1. const WIDE_SHARE: f64 = 0.25; -/// A window of the photo: its zoom (1 = the whole photo) and its centre (0–1 across and down). +/// A window of the photo: its zoom (1 = the whole photo) and its center (0–1 across and down). #[derive(Clone, Copy, Debug, PartialEq)] pub struct View { pub zoom: f64, @@ -26,7 +26,7 @@ impl View { pub const FULL: View = View { zoom: 1.0, x: 0.5, y: 0.5 }; /// The window as (x0, y0, x1, y1), inside 0–1: a zoom below 1 or not finite is 1, and the - /// centre is kept far enough from the edges for the window to fit. + /// center is kept far enough from the edges for the window to fit. pub fn window(&self) -> (f64, f64, f64, f64) { let z = if self.zoom.is_finite() { self.zoom.max(1.0) } else { 1.0 }; let h = 0.5 / z; @@ -77,7 +77,7 @@ impl Motion { } /// The view at `t` (0 = the slide's start, 1 = its end; clamped, not finite = 0). Zoom and - /// centre move linearly; the window stays inside the photo all the way. + /// center move linearly; the window stays inside the photo all the way. pub fn at(&self, t: f64) -> View { let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; let l = |a: f64, b: f64| a + (b - a) * t; @@ -135,6 +135,6 @@ mod tests { assert_eq!(m.at(f64::NAN), m.start); assert_eq!(View::FULL.window(), (0.0, 0.0, 1.0, 1.0)); assert_eq!(View { zoom: f64::NAN, x: 9.0, y: -1.0 }.window(), (0.0, 0.0, 1.0, 1.0), "bad values: the whole photo"); - assert_eq!(View { zoom: 2.0, x: 0.0, y: 1.0 }.window(), (0.0, 0.5, 0.5, 1.0), "the centre is moved in"); + assert_eq!(View { zoom: 2.0, x: 0.0, y: 1.0 }.window(), (0.0, 0.5, 0.5, 1.0), "the center is moved in"); } } From 2dc322deb7a61aedcd410c9ddb2f2755f59fe7b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 07:21:39 -0700 Subject: [PATCH 059/247] Docs: list Enter Keywords in the Keywording box's view switch The LRC-LIB-KEYWORDS row names Enter Keywords as one of the box's four views and describes it in its own sentence, after the list of the box's parts. --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ed019f08bf..2db693afe7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -711,7 +711,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-STACKS | Stacks (full) | P1 | ✅ | `crates/catalog/src/stacks.rs`, `cmd:stack.group`, `cmd:stack.split`, `cmd:stack.moveUp`, `cmd:stack.moveDown` | group / ungroup / toggle / set top / remove / auto by time / split / move up and down | | LRC-LIB-VC | Virtual copies | P1 | ✅ | `cmd:photo.virtualCopy` | ⌘' | | LRC-LIB-LABELS | Colour-label sets | P1 | ✅ | `cmd:label.sets`, `cmd:label.applySet`, `cmd:label.saveSet`, `cmd:label.deleteSet`, `cmd:label.setNames`, `crates/engine/src/cmd/manage.rs` | built-in Colors / Review sets + user sets (Photo ▸ Set Color Label, Edit Label Names… dialog); names written to and read from `xmp:Label` | -| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry); Enter Keywords (`keywordView:enter`, `field:enterKeywords`) shows the selection's keywords as text, commas between them and an asterisk after one only some selected photos have: Return or leaving the box applies the edit to the photos selected when it began as one undo step (a keyword left out comes off every one of them, a name typed goes to all of them, a marked keyword stays on the photos that have it and without its asterisk goes to all), Esc gives the edit up, another selection gives it up too, an asterisk after any other name is refused with the text kept, and containing keywords and synonyms stay out of the text (the rules for mixed keywords and for when an edit applies are LightCraft's own), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | +| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), an Enter Keywords / Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords as text or as chips to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Enter Keywords (`keywordView:enter`, `field:enterKeywords`) shows the selection's keywords as text, commas between them and an asterisk after one only some selected photos have: Return or leaving the box applies the edit to the photos selected when it began as one undo step (a keyword left out comes off every one of them, a name typed goes to all of them, a marked keyword stays on the photos that have it and without its asterisk goes to all), Esc gives the edit up, another selection gives it up too, an asterisk after any other name is refused with the text kept, and containing keywords and synonyms stay out of the text (the rules for mixed keywords and for when an edit applies are LightCraft's own). Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | | LRC-LIB-METADATA | Metadata panel & presets | P1 | ✅ | `cmd:photo.setMeta`, `cmd:metadata.savePreset`, `cmd:metadata.applyPreset`, `cmd:metadata.presets`, `cmd:metadata.deletePreset`, `cmd:dialog.captureTime` | IPTC core, accessibility, place, capture-time edit; copyright status (unknown / copyrighted / public domain), rights usage terms and copyright info URL (`photo.setMeta` `copyrightStatus`, `usageTerms`, `copyrightUrl`; XMP Rights Management fields, kept by "copyright only" exports, a smart-album rule); metadata presets (Photo → Metadata Preset, Save Metadata Preset… from the active photo; applied on import from Settings) | | LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step | | LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people From 484c9797f1ee4dadd662bdc98b5dd178cde5e52d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 07:43:46 -0700 Subject: [PATCH 060/247] Keywords: Enter Keywords writes a double quote inside a quoted keyword twice A keyword whose name holds a double quote is now written in double quotes with each double quote inside doubled, and the text reads a doubled quote back as one. Before, with a, b" and a", b on one photo, the untouched text split a", b into two names and Return removed it. --- crates/ui-egui/src/panels/keywording.rs | 101 +++++++++++++++++------- 1 file changed, 73 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index b513678a68..b0a5a9447b 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -713,21 +713,22 @@ pub(crate) fn chips(catalog: &Catalog, photos: &[PhotoId]) -> Vec { /// The Enter Keywords text of the selection's keywords `chips`: each keyword's path, with commas /// between them and an asterisk after a keyword only some of the selected photos have. A keyword -/// whose name holds a comma or a new line is written in double quotes (before its asterisk), so that -/// it reads as one name. A keyword every photo has whose name ends in an asterisk, or is itself in -/// double quotes, is also written in double quotes, so that it reads differently from a partial -/// keyword marked with the asterisk. +/// whose name holds a comma, a new line or a double quote is written in double quotes (before its +/// asterisk), each double quote inside written twice, so that it reads as one name. A keyword every +/// photo has whose name ends in an asterisk is also written in double quotes, so that it reads +/// differently from a partial keyword marked with the asterisk. pub(crate) fn entered_text(chips: &[Chip]) -> String { chips .iter() .map(|c| { - let separated = c.path.contains([',', '\n']); - if !c.on_all() && separated { - format!("\"{}\"*", c.path) + let in_quotes = || format!("\"{}\"", c.path.replace('"', "\"\"")); + let held = c.path.contains([',', '\n', '"']); + if !c.on_all() && held { + format!("{}*", in_quotes()) } else if !c.on_all() { format!("{}*", c.path) - } else if separated || c.path.ends_with('*') || quoted(&c.path).is_some() { - format!("\"{}\"", c.path) + } else if held || c.path.ends_with('*') { + in_quotes() } else { c.path.clone() } @@ -736,9 +737,19 @@ pub(crate) fn entered_text(chips: &[Chip]) -> String { .join(", ") } -/// The name inside `token` when it is in double quotes. -fn quoted(token: &str) -> Option<&str> { - token.strip_prefix('"')?.strip_suffix('"') +/// The name inside `token` when it is in double quotes, each double quote inside it written twice +/// (a single one inside means it is not). +fn quoted(token: &str) -> Option { + let inside = token.strip_prefix('"')?.strip_suffix('"')?; + let mut name = String::with_capacity(inside.len()); + let mut chars = inside.chars(); + while let Some(ch) = chars.next() { + if ch == '"' && chars.next() != Some('"') { + return None; + } + name.push(ch); + } + Some(name) } /// What an edit of the Enter Keywords text gives to and takes off the selected photos. @@ -759,20 +770,24 @@ impl Entered { /// The names in the Enter Keywords `text`, trimmed: the text split at commas and new lines, except /// where a name opened with a double quote closes with one (the next piece holding a double quote -/// ends with it, or with it and an asterisk), and only commas lie between or the name spells a -/// keyword of `start` the text has not named yet; or where pieces joined by their separators spell -/// a keyword of `start` whose name holds a comma or a new line (with or without its asterisk or its -/// quotes) that the text has not named yet, unless each of those pieces is a keyword of `start` by -/// itself. Either stays one name. +/// not written twice ends with it, or with it and an asterisk), only commas lie between or the +/// name spells a keyword of `start` the text has not named yet, and each double quote inside is +/// written twice; or where pieces joined by their separators spell a keyword of `start` whose name +/// holds a comma or a new line (with or without its asterisk or its quotes) that the text has not +/// named yet, unless each of those pieces is a keyword of `start` by itself. Either stays one name. fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { use lightcraft_catalog::keywords::{clean, same}; let is_separator = |ch: char| ch == ',' || ch == '\n'; let spells = |s: &str, c: &Chip| { let marked = s.strip_suffix('*'); - [Some(s), marked, quoted(s), marked.and_then(quoted)].into_iter().flatten().any(|n| same(&clean(n), &c.path)) + let inside = [quoted(s), marked.and_then(quoted)]; + [Some(s), marked].into_iter().flatten().chain(inside.iter().flatten().map(String::as_str)).any(|n| same(&clean(n), &c.path)) }; - // a piece that closes a name in double quotes - let closes = |s: &str| s.ends_with('"') || s.ends_with("\"*"); + // a piece holding a double quote that is not one written twice + let unpaired = |s: &str| s.split(|ch| ch != '"').any(|run| run.len() % 2 == 1); + // a piece that closes a name in double quotes: it ends with one (before an asterisk or not) + // that is not one written twice + let closes = |s: &str| s.strip_suffix('*').unwrap_or(s).chars().rev().take_while(|&ch| ch == '"').count() % 2 == 1; // the keywords of `start` the text has named so far let mut named = vec![false; start.len()]; let unnamed = |s: &str, named: &[bool]| start.iter().zip(named).position(|(c, n)| !n && spells(s, c)); @@ -795,9 +810,10 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { .iter() .enumerate() .skip(i + 1) - .find(|(_, p)| piece(p).contains('"')) + .find(|(_, p)| unpaired(piece(p))) .filter(|(_, p)| closes(piece(p))) .and_then(|(j, p)| Some((j - i, text.get(first.start..p.end)?.trim()))) + .filter(|&(_, s)| quoted(s.strip_suffix('*').unwrap_or(s)).is_some()) .filter(|&(_, s)| !s.contains('\n') || unnamed(s, &named).is_some()) }) .flatten(); @@ -837,10 +853,10 @@ fn entered_names<'a>(start: &[Chip], text: &'a str) -> Vec<&'a str> { /// to every selected photo (a keyword of `start` keeps its spelling, and a new name goes where /// `Catalog::typed_keyword` puts it). A keyword only some photos have, still marked with its /// asterisk, stays on those photos only, the name in double quotes before the asterisk included. A -/// name in double quotes is read as written, an asterisk at its end included. A keyword every -/// photo has whose own name ends in an asterisk is also kept when written without its quotes, -/// unless a keyword only some photos have reads the same. An asterisk after any other name is -/// refused: the error is the name as typed. +/// name in double quotes is read as written, an asterisk at its end included, and a double quote +/// written twice inside it is one double quote. A keyword every photo has whose own name ends in an +/// asterisk is also kept when written without its quotes, unless a keyword only some photos have +/// reads the same. An asterisk after any other name is refused: the error is the name as typed. pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result { use lightcraft_catalog::keywords::{clean, same}; let mut kept: Vec = Vec::new(); @@ -850,7 +866,7 @@ pub(crate) fn entered(catalog: &Catalog, start: &[Chip], text: &str) -> Result Result (c.path.clone(), c.on_all()), @@ -1329,10 +1345,39 @@ mod tests { // a keyword every photo has that is itself in quotes keeps them let (c, ids) = library(&[&["\"quoted\""]]); let start = chips(&c, &ids); - assert_eq!(entered_text(&start), "\"\"quoted\"\""); + assert_eq!(entered_text(&start), "\"\"\"quoted\"\"\""); assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default())); } + /// A keyword whose name holds a double quote is written in double quotes with that one written + /// twice, so that the text left as it is changes nothing, beside keywords spelled like its pieces + /// too. + #[test] + fn a_keyword_with_a_double_quote_reads_back() { + let sets: [&[&str]; 6] = [ + &["a", "b\"", "a\", b"], + &["a", "b\"", "a\"", "b"], + &["a\", b"], + &["\"b", "c\""], + &["\"quoted\"", "say \"hi\", there", "\"a, b"], + &["x", "a\"\"b"], + ]; + for set in sets { + let (c, ids) = library(&[set]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default()), "{set:?} on every photo: {}", entered_text(&start)); + // each one only some photos have + let (c, ids) = library(&[set, &["x"]]); + let start = chips(&c, &ids); + assert_eq!(entered(&c, &start, &entered_text(&start)), Ok(Entered::default()), "{set:?} partial: {}", entered_text(&start)); + } + let (c, ids) = library(&[&["a", "b\"", "a\", b"]]); + let start = chips(&c, &ids); + assert_eq!(entered_text(&start), "a, \"a\"\", b\", \"b\"\"\""); + assert_eq!(entered(&c, &start, "a, \"b\"\"\""), Ok(edit(&[], &["a\", b"])), "its entry deleted"); + assert_eq!(entered(&c, &start, "a, b\""), Ok(edit(&[], &["a\", b"])), "written without its quotes"); + } + /// A new name goes inside the default parent, as one typed in the Add keyword box does. #[test] fn a_new_name_goes_inside_the_default_parent() { From 1ad3f4e69e9bc66495e15320ef049c7f9c8cce75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 09:46:54 -0700 Subject: [PATCH 061/247] LRC-LIB-KEYWORDS: a new keyword name can't end in an asterisk The keyword help says "Keywords cannot end with an asterisk ( * )." The Keywording panel marks a keyword that only some of the selected photos have with one. keywords::valid_name checks a name, and Catalog::check_keyword_name refuses a level ending in `*` that the library does not have yet. These now refuse such a name: keyword.create (Create Keyword Tag), keyword.edit (Edit Keyword Tag), keyword.rename, keyword.merge, a new parent in keyword.move, photo.setMeta `keywords` and `addKeywords` (the Add keyword box), keyword.setShortcut, keyword.saveSet, library.import `keywords` and the keyword painter. A name with `*` inside (`a*b`) is allowed. Keywords read from sidecars, XMP, catalogs, keyword list files and the op log are kept as they are, and a keyword the library already has can still be given to photos. --- crates/catalog/src/keywords.rs | 22 ++++++++++++ crates/catalog/src/keywords/tests.rs | 27 +++++++++++++++ crates/engine/src/cmd/keywords.rs | 18 +++++++--- crates/engine/src/cmd/library/import.rs | 6 +++- crates/engine/src/cmd/library/specs.rs | 12 +++++++ crates/engine/src/tests/keyword_list.rs | 43 ++++++++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 9 ++++- crates/ui-egui/src/tests/keyword_list.rs | 40 ++++++++++++++++++++++ 8 files changed, 171 insertions(+), 6 deletions(-) diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index d36ab11cd6..3ec31d0f6e 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -24,6 +24,13 @@ pub fn clean(k: &str) -> String { k.split(SEP).map(str::trim).filter(|s| !s.is_empty()).collect::>().join("|") } +/// No level of `k` ends in `*` (after trimming): a name a user gives can't end in an asterisk, +/// which marks a keyword only some of the selected photos have. An asterisk inside a name (`a*b`) +/// is allowed. +pub fn valid_name(k: &str) -> bool { + !k.split(SEP).any(|level| level.trim().ends_with('*')) +} + /// The same name, whatever the case of any of its letters (not only ASCII ones). pub fn same(a: &str, b: &str) -> bool { a == b || a.to_lowercase() == b.to_lowercase() @@ -653,6 +660,19 @@ impl Catalog { self.keyword_path(path).is_some() } + /// Refuse a keyword a user gives (a new keyword, a new name, a keyword typed for photos) when a + /// level the library doesn't have yet ends in `*` ([`valid_name`]). Levels the library has, + /// such as those read from sidecars and catalogs, are accepted as they are. + pub fn check_keyword_name(&self, path: &str) -> Result<()> { + let levels: Vec<&str> = path.split(SEP).map(str::trim).filter(|s| !s.is_empty()).collect(); + for (i, level) in levels.iter().enumerate() { + if !valid_name(level) && !self.has_keyword(&levels.get(..=i).map(|l| l.join("|")).unwrap_or_default()) { + return Err(CatalogError::Invalid(format!("keyword names can't end in “*”: “{level}”"))); + } + } + Ok(()) + } + /// Where a keyword typed for a photo goes: inside the default parent when it is a new name (Put /// New Keywords Inside This Keyword); a keyword the library has, or a path typed whole, as /// typed (cleaned). @@ -757,6 +777,7 @@ impl Catalog { if self.has_keyword(&path) { return Err(CatalogError::KeywordExists(path)); } + self.check_keyword_name(&path)?; let path = self.spelled(&path); let mut ops = vec![Op::SetKeyword { path: path.clone(), info: Some(info) }]; for id in photos { @@ -811,6 +832,7 @@ impl Catalog { if !same(&to, &from) && self.has_keyword(&to) { return Err(CatalogError::KeywordExists(to)); } + self.check_keyword_name(&to)?; if let Op::Batch { ops: renamed } = self.rename_keyword_ops(&from, &to)? { ops = renamed; } diff --git a/crates/catalog/src/keywords/tests.rs b/crates/catalog/src/keywords/tests.rs index 6f50bd482e..075246b7a3 100644 --- a/crates/catalog/src/keywords/tests.rs +++ b/crates/catalog/src/keywords/tests.rs @@ -209,6 +209,33 @@ fn creating_a_keyword_lists_it_and_can_tag_photos() { assert!(c.create_keyword_ops(" | ", KeywordInfo::default(), &[]).is_err()); } +/// A new keyword's name can't end in `*` at any level, which marks a keyword only some of the +/// selected photos have; an asterisk inside a name is allowed. Levels the library already has, +/// as a sidecar or catalog wrote them, are accepted as they are. +#[test] +fn a_new_keyword_name_cannot_end_in_an_asterisk() { + assert!(!valid_name("travel*") && !valid_name("places | rome* ") && valid_name("a*b")); + let (mut c, ids) = lib(&[&["places|italy"], &[]]); + for name in ["travel*", "places|rome*", "travel *|rome"] { + let err = c.create_keyword_ops(name, KeywordInfo::default(), &[ids[1]]).unwrap_err(); + assert!(err.to_string().contains("can't end in “*”"), "{name}: {err}"); + } + assert!(c.edit_keyword_ops("places|italy", "Italy*", KeywordInfo::default()).is_err()); + let op = c.create_keyword_ops("a*b", KeywordInfo::default(), &[]).unwrap(); + c.apply(op).unwrap(); + assert!(c.has_keyword("a*b")); + // read from a file: kept, and it can be named again + assert_eq!(from_file(&["travel*".to_string()], &["old*|rome".to_string()]), ["old*|rome", "travel*"]); + let (mut c, ids) = lib(&[&["travel*", "old*|rome"], &[]]); + assert!(c.check_keyword_name("travel*").is_ok() && c.check_keyword_name("old*|rome").is_ok()); + let op = c.create_keyword_ops("old*|milan", KeywordInfo::default(), &[ids[1]]).unwrap(); + c.apply(op).unwrap(); + assert_eq!(kws(&c, ids[1]), ["old*|milan"]); + let op = c.edit_keyword_ops("travel*", "TRAVEL*", KeywordInfo::default()).unwrap(); + c.apply(op).unwrap(); + assert_eq!(kws(&c, ids[0]), ["TRAVEL*", "old*|rome"]); +} + /// Moving a keyword nests it inside another (or takes it to the top level), with its children, /// on photos and in the list. It can't go inside itself or one of its children, and moving it /// where it already is changes nothing. diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 0e612227f1..56f2609be5 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -170,6 +170,7 @@ fn shortcut_keywords(s: &Session, p: &Value) -> Result> { let mut out: Vec = Vec::new(); for k in typed { let k = s.catalog.typed_keyword(&k); + s.catalog.check_keyword_name(&k).map_err(|e| bad("keyword.setShortcut", e.to_string()))?; if !k.is_empty() && !out.iter().any(|x| lightcraft_catalog::keywords::same(x, &k)) { out.push(k); } @@ -266,7 +267,11 @@ pub fn specs() -> Vec { }; // keywords not given: the renamed set's own, else the current nine let keywords = if p.get("keywords").is_some() { - slots(&strs(p, "keywords")) + let keywords = slots(&strs(p, "keywords")); + for k in &keywords { + s.catalog.check_keyword_name(k).map_err(|e| bad("keyword.saveSet", e.to_string()))?; + } + keywords } else { match renames.and_then(|at| s.keyword_sets.get(at)) { Some(x) => x.keywords.clone(), @@ -437,7 +442,7 @@ pub fn specs() -> Vec { "Create Keyword", [], None, - "{name, parent?: keyword | null (default: the default parent; null = the top level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?, addToSelected?: bool, ids?} → {keyword}", + "{name (a new level can't end in `*`), parent?: keyword | null (default: the default parent; null = the top level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?, addToSelected?: bool, ids?} → {keyword}", always, |s, p| { let name = str_param(p, "name").map(clean).filter(|n| !n.is_empty()).ok_or_else(|| bad("keyword.create", "missing `name`"))?; @@ -467,7 +472,7 @@ pub fn specs() -> Vec { "Edit Keyword", [], None, - "{keyword, name?: its new name (one level), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?} — what isn't given keeps its value", + "{keyword, name?: its new name (one level, not ending in `*`), synonyms?, includeOnExport?, exportContaining?, exportSynonyms?, person?} — what isn't given keeps its value", always, |s, p| { let from = named_keyword(s, p, "keyword.edit")?; @@ -500,7 +505,10 @@ pub fn specs() -> Vec { // where it lands, as the catalog spells it: a parent that doesn't exist yet is made let leaf = from.rsplit('|').next().unwrap_or(&from).to_string(); let to = match parent.as_deref().map(|k| s.catalog.keyword_path(k).unwrap_or_else(|| clean(k))).filter(|k| !k.is_empty()) { - Some(parent) => format!("{parent}|{leaf}"), + Some(parent) => { + s.catalog.check_keyword_name(&parent).map_err(|e| bad("keyword.move", e.to_string()))?; + format!("{parent}|{leaf}") + } None => leaf, }; let op = s @@ -602,6 +610,7 @@ pub fn specs() -> Vec { |s, p| { let from = str_param(p, "from").ok_or_else(|| bad("keyword.rename", "missing `from`"))?.to_string(); let to = str_param(p, "to").ok_or_else(|| bad("keyword.rename", "missing `to`"))?.to_string(); + s.catalog.check_keyword_name(&to).map_err(|e| bad("keyword.rename", e.to_string()))?; let op = s.catalog.rename_keyword_ops(&from, &to).map_err(|e| bad("keyword.rename", e.to_string()))?; let (f, t) = (clean(&from), clean(&to)); commit_keywords(s, "Rename Keyword", op, |k| Some(if is_under(k, &f) { reparent(k, &f, &t) } else { k.to_string() })) @@ -631,6 +640,7 @@ pub fn specs() -> Vec { |s, p| { let from = strs(p, "from"); let into = str_param(p, "into").ok_or_else(|| bad("keyword.merge", "missing `into`"))?.to_string(); + s.catalog.check_keyword_name(&into).map_err(|e| bad("keyword.merge", e.to_string()))?; let op = s.catalog.merge_keywords_ops(&from, &into).map_err(|e| bad("keyword.merge", e.to_string()))?; let (from, into) = (from.iter().map(|f| clean(f)).collect::>(), clean(&into)); commit_keywords(s, "Merge Keywords", op, |k| { diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 2a663b79de..8f3cf773c6 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -70,11 +70,15 @@ pub fn import_params(s: &Session, p: &Value) -> Result { Some(n) => usize::try_from(n).map_err(|_| bad("library.import", "renameStart is too large for this platform"))?, None => 1, }; + let keywords = strs(p, "keywords"); + for k in &keywords { + s.catalog.check_keyword_name(k).map_err(|e| bad("library.import", e.to_string()))?; + } let opts = crate::import::ImportOptions { on_deleted, mode, preset, - keywords: strs(p, "keywords"), + keywords, destination: str_param(p, "destination").map(str::to_string), organize, rename: str_param(p, "rename").map(str::to_string), diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index a2a842106a..48f97f10ce 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -728,6 +728,14 @@ pub fn specs() -> Vec { ), None => None, }; + // the keywords given that the library refuses as new names, each checked once + let refused: Vec<(String, String)> = strs("keywords") + .into_iter() + .flatten() + .chain(strs("addKeywords").unwrap_or_default()) + .map(|k| lightcraft_catalog::keywords::clean(&k)) + .filter_map(|k| s.catalog.check_keyword_name(&k).err().map(|e| (k, e.to_string()))) + .collect(); let mut ops = Vec::new(); for id in targets { let Some(ph) = s.catalog.photo(id) else { continue }; @@ -764,6 +772,10 @@ pub fn specs() -> Vec { m.keywords.push(k); } }; + // a keyword the photo or the library doesn't have yet can't end in `*` + if let Some((_, e)) = refused.iter().find(|(k, _)| !m.keywords.iter().any(|x| same(&clean(x), k))) { + return Err(bad("photo.setMeta", e.clone())); + } if let Some(k) = strs("keywords") { m.keywords.clear(); for k in k { diff --git a/crates/engine/src/tests/keyword_list.rs b/crates/engine/src/tests/keyword_list.rs index e50d0d7b14..45e4cc9e39 100644 --- a/crates/engine/src/tests/keyword_list.rs +++ b/crates/engine/src/tests/keyword_list.rs @@ -54,6 +54,49 @@ fn creating_a_keyword_with_attributes_and_the_selection() { assert!(s.execute("keyword.info", &json!({"keyword": "lisbon"})).is_err(), "no such keyword"); } +/// Every command that names a keyword refuses a new name ending in `*` at any level, and changes +/// nothing; a name with `*` inside is allowed. A keyword the library has from a file keeps its name +/// and can still be given to photos. +#[test] +fn commands_refuse_a_new_keyword_name_ending_in_an_asterisk() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + s.execute("library.select", &json!({"ids": ids})).unwrap(); + s.execute("keyword.create", &json!({"name": "Lagoon", "parent": null})).unwrap(); + s.execute("keyword.saveSet", &json!({"name": "Mine", "keywords": ["Lagoon"]})).unwrap(); + for name in ["travel*", "places|rome*"] { + let before = s.catalog.to_snapshot(); + let sets = s.keyword_sets.clone(); + for (command, params) in [ + ("keyword.create", json!({"name": name, "parent": null})), + ("keyword.edit", json!({"keyword": "Lagoon", "name": name.rsplit('|').next()})), + ("keyword.rename", json!({"from": "Lagoon", "to": name})), + ("keyword.merge", json!({"from": ["Lagoon"], "into": name})), + ("keyword.move", json!({"keyword": "Lagoon", "parent": name})), + ("photo.setMeta", json!({"addKeywords": [name]})), + ("photo.setMeta", json!({"keywords": ["Lagoon", name]})), + ("keyword.setShortcut", json!({"keywords": [name]})), + ("keyword.saveSet", json!({"name": "Mine", "keywords": [name]})), + ("library.import", json!({"paths": ["missing.jpg"], "keywords": [name]})), + ] { + let err = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(err.contains("can't end in “*”"), "{command} {params}: {err}"); + } + assert!(s.catalog.to_snapshot() == before && s.keyword_sets == sets, "{name}: nothing changed"); + } + s.execute("photo.setMeta", &json!({"addKeywords": ["a*b"]})).unwrap(); + assert!(ids.iter().all(|id| keywords_of(&s, *id).contains(&"a*b".to_string()))); + // a keyword read from a file (here put on the photo as a sidecar read puts it) + let id = lightcraft_catalog::PhotoId(ids[0]); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.keywords.push("travel*".into()); + s.commit("Read Metadata", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.execute("photo.setMeta", &json!({"ids": [ids[1]], "addKeywords": ["TRAVEL*"]})).unwrap(); + assert!(keywords_of(&s, ids[1]).contains(&"TRAVEL*".to_string()), "{:?}", keywords_of(&s, ids[1])); + s.execute("keyword.edit", &json!({"keyword": "travel*", "synonyms": ["trip"]})).unwrap(); + assert!(keywords_of(&s, ids[0]).contains(&"travel*".to_string()), "its name is kept"); +} + /// "Put new keywords inside this keyword": new keywords go inside the default parent unless the /// command says otherwise (`parent: null` = the top level). It belongs to its keyword in the /// library: it follows a rename, goes with a delete, and undo and redo bring it back with them. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f..a90b9b945b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -217,7 +217,14 @@ fn ui_commands_1(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val } "tool.keywordPainter" => { // {keyword?}: paint that keyword onto photos in the grid by clicking them; no keyword stops - app.ui.keyword_painter = p.get("keyword").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(str::to_string); + let keyword = p.get("keyword").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(str::to_string); + // a new keyword ending in `*` is refused before painting starts, so no click fails unseen + if let Some(Err(e)) = keyword.as_deref().map(|k| app.session.catalog.check_keyword_name(k)) { + let e = format!("tool.keywordPainter: {e}"); + app.toast_error(ctx, e.clone()); + return Some(Err(e)); + } + app.ui.keyword_painter = keyword; if app.ui.keyword_painter.is_some() && !matches!(app.ui.view, ViewMode::PhotoGrid | ViewMode::SquareGrid) { app.ui.view = ViewMode::PhotoGrid; } diff --git a/crates/ui-egui/src/tests/keyword_list.rs b/crates/ui-egui/src/tests/keyword_list.rs index f82fa44a2c..dd40817486 100644 --- a/crates/ui-egui/src/tests/keyword_list.rs +++ b/crates/ui-egui/src/tests/keyword_list.rs @@ -249,6 +249,46 @@ fn creating_a_keyword_that_exists_keeps_the_dialog() { assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("already")), "{:?}", h.app.ui.toast); } +/// Create Keyword Tag and Edit Keyword Tag refuse a name ending in `*` (at any level) and stay +/// open with what was typed; nothing is created or renamed. +#[test] +fn keyword_tag_dialogs_refuse_a_name_ending_in_an_asterisk() { + let (mut h, _) = keywords_panel(); + for typed in ["travel*", "places|rome*"] { + ask(&mut h, "ui.clickWidget", json!({"id": "keywordList:create"})); + ask(&mut h, "ui.text", json!({"text": typed})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { name, .. }) if name == typed), "{typed}: {:?}", h.app.ui.dialog); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("can't end in “*”")), "{typed}: {:?}", h.app.ui.toast); + assert!(!h.app.session.catalog.has_keyword(typed), "{typed}"); + ask(&mut h, "ui.dialog.cancel", json!({})); + } + find(&mut h, "mountains"); + ask(&mut h, "ui.clickWidget", json!({"id": "keywordRow:mountains", "count": 2})); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { editing: Some(_), .. })), "{:?}", h.app.ui.dialog); + ask(&mut h, "ui.text", json!({"text": "mountains*"})); + ask(&mut h, "ui.key", json!({"key": "Enter"})); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("“mountains*”")), "{:?}", h.app.ui.toast); + assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::KeywordTag { editing: Some(_), .. })), "still open: {:?}", h.app.ui.dialog); + assert!(h.app.session.catalog.has_keyword("mountains") && !h.app.session.catalog.has_keyword("mountains*")); +} + +/// The keyword painter refuses a new keyword ending in `*` and says why, without starting to paint; +/// a keyword the library has paints as before. +#[test] +fn the_keyword_painter_refuses_a_name_ending_in_an_asterisk() { + let (mut h, _) = keywords_panel(); + for typed in ["travel*", "places|rome*"] { + let r = h.request("engine.execute", json!({"command": "tool.keywordPainter", "params": {"keyword": typed}}), T); + h.settle(SETTLE); + assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("can't end in “*”")), "{typed}: {r}"); + assert_eq!(h.app.ui.keyword_painter, None, "{typed}: not painting"); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("can't end in “*”")), "{typed}: {:?}", h.app.ui.toast); + } + run(&mut h, "tool.keywordPainter", json!({"keyword": "mountains"})); + assert_eq!(h.app.ui.keyword_painter.as_deref(), Some("mountains")); +} + /// A keyword's context menu: create a keyword inside it, edit it, make it where new keywords go /// (marked in the list), and purge the keywords no photo has. #[test] From decea8dbc416c38d1f7845ac8f9ec052e37ed715 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 09:46:54 -0700 Subject: [PATCH 062/247] Keywords: metadata presets cannot add a new keyword name ending in an asterisk metadata.savePreset refuses keywords that are new names ending in "*", and library.import checks the keywords of the chosen metadata preset and of the import defaults' preset. The import dialog checks the import before it creates a new album, so a refused import leaves no empty album. --- crates/engine/src/cmd/library/import.rs | 6 ++++++ crates/engine/src/cmd/metadata.rs | 10 ++++++++++ crates/engine/src/tests/keyword_list.rs | 12 +++++++++++- crates/ui-egui/src/dialogs/import.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/import/task.rs | 17 +++++++++++------ 5 files changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 8f3cf773c6..11b749a236 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -60,6 +60,12 @@ pub fn import_params(s: &Session, p: &Value) -> Result { { return Err(bad("library.import", format!("unknown metadata preset `{n}`"))); } + // the chosen preset and the import defaults' preset (presets saved earlier are kept in prefs) + for n in metadata_preset.iter().chain(s.import_defaults.metadata_preset.iter()) { + if let Some(mp) = s.metadata_presets.iter().find(|m| m.name.eq_ignore_ascii_case(n)) { + crate::cmd::metadata::check_keywords(s, &mp.fields, "library.import")?; + } + } let on_deleted = match str_param(p, "onDeleted") { Some(v) => { crate::import::OnDeleted::parse(v).ok_or_else(|| bad("library.import", format!("unknown onDeleted `{v}` (restore|skip|fresh)")))? diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index ca52f68139..ff5473971a 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -66,6 +66,15 @@ pub fn apply_to(m: &mut Meta, fields: &Value) { } } +/// Refuses preset `fields` whose keywords hold a new name the library cannot take +/// (`Catalog::check_keyword_name`). +pub fn check_keywords(s: &Session, fields: &Value, command: &str) -> Result<()> { + for kw in fields.get("keywords").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + s.catalog.check_keyword_name(kw).map_err(|e| bad(command, e.to_string()))?; + } + Ok(()) +} + fn list(s: &Session) -> Value { json!(s.metadata_presets) } @@ -113,6 +122,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Value::Object(o) } }; + check_keywords(s, &fields, C)?; let preset = MetadataPreset { name: name.clone(), fields }; match s.metadata_presets.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name)) { Some(m) => *m = preset, diff --git a/crates/engine/src/tests/keyword_list.rs b/crates/engine/src/tests/keyword_list.rs index 45e4cc9e39..f2e12385bc 100644 --- a/crates/engine/src/tests/keyword_list.rs +++ b/crates/engine/src/tests/keyword_list.rs @@ -65,8 +65,11 @@ fn commands_refuse_a_new_keyword_name_ending_in_an_asterisk() { s.execute("keyword.create", &json!({"name": "Lagoon", "parent": null})).unwrap(); s.execute("keyword.saveSet", &json!({"name": "Mine", "keywords": ["Lagoon"]})).unwrap(); for name in ["travel*", "places|rome*"] { + // a metadata preset in prefs that holds the name + s.metadata_presets = vec![crate::cmd::metadata::MetadataPreset { name: "Old".into(), fields: json!({"keywords": [name]}) }]; let before = s.catalog.to_snapshot(); let sets = s.keyword_sets.clone(); + let presets = s.metadata_presets.clone(); for (command, params) in [ ("keyword.create", json!({"name": name, "parent": null})), ("keyword.edit", json!({"keyword": "Lagoon", "name": name.rsplit('|').next()})), @@ -78,11 +81,18 @@ fn commands_refuse_a_new_keyword_name_ending_in_an_asterisk() { ("keyword.setShortcut", json!({"keywords": [name]})), ("keyword.saveSet", json!({"name": "Mine", "keywords": [name]})), ("library.import", json!({"paths": ["missing.jpg"], "keywords": [name]})), + ("metadata.savePreset", json!({"name": "Trip", "fields": {"keywords": ["Lagoon", name]}})), + ("library.import", json!({"paths": ["missing.jpg"], "metadataPreset": "Old"})), ] { let err = s.execute(command, ¶ms).unwrap_err().to_string(); assert!(err.contains("can't end in “*”"), "{command} {params}: {err}"); } - assert!(s.catalog.to_snapshot() == before && s.keyword_sets == sets, "{name}: nothing changed"); + // the import defaults' metadata preset + s.import_defaults.metadata_preset = Some("Old".into()); + let err = s.execute("library.import", &json!({"paths": ["missing.jpg"]})).unwrap_err().to_string(); + assert!(err.contains("can't end in “*”"), "import defaults: {err}"); + s.import_defaults.metadata_preset = None; + assert!(s.catalog.to_snapshot() == before && s.keyword_sets == sets && s.metadata_presets == presets, "{name}: nothing changed"); } s.execute("photo.setMeta", &json!({"addKeywords": ["a*b"]})).unwrap(); assert!(ids.iter().all(|id| keywords_of(&s, *id).contains(&"a*b".to_string()))); diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index e5bfab8817..3ef83ff3ce 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -259,6 +259,20 @@ mod tests { ImportDialog::new(candidates) } + /// An import the engine refuses creates no new album: its params are checked first. + #[test] + fn a_refused_import_creates_no_new_album() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let mut d = dialog(); + d.new_album = "Card 1".into(); + d.keywords = "travel*".into(); + let albums = app.session.catalog.albums().count(); + let err = start(&mut app, &d).unwrap_err(); + assert!(err.contains("can't end in “*”"), "{err}"); + assert_eq!(app.session.catalog.albums().count(), albums, "no album was created"); + assert!(app.import.is_none()); + } + /// Identical copies inside the source folder are not "already in the library" (a fresh library /// said "8 already in the library"). #[test] diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 5c27983400..7dcbcb9032 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -214,11 +214,6 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result return Err("no photos selected".into()); } let undo0 = app.session.undo.len(); - let mut album = d.album; - if album.is_none() && !d.new_album.trim().is_empty() { - let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?; - album = r["id"].as_u64(); - } let mode = match (d.copy, d.move_files) { (false, _) => "add", (true, false) => "copy", @@ -228,7 +223,7 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result if !d.on_deleted.is_empty() { params["onDeleted"] = json!(d.on_deleted); } - if let Some(a) = album { + if let Some(a) = d.album { params["album"] = json!(a); } if !d.preset.is_empty() { @@ -252,6 +247,16 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result params["dng"] = json!(true); } } + // the params are checked before a new album is created, so a refused import leaves no album + let mut check = params.clone(); + check["paths"] = json!(queue); + lightcraft_engine::cmd::library::import_params(&app.session, &check).map_err(|e| e.to_string())?; + if d.album.is_none() && !d.new_album.trim().is_empty() { + let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?; + if let Some(a) = r["id"].as_u64() { + params["album"] = json!(a); + } + } let total = queue.len(); app.import = Some(ImportTask::new(queue, params, undo0, false)); app.renderer.forget_imports(); From b119d4d2dc1510052b89aeb128eafa3899348f0c Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:20:09 -0500 Subject: [PATCH 063/247] LR-PROF-CAMERACOLOR: a dark frame with negative channels exports in every format A near-black frame with negative channels, pushed +4 EV, goes through the export's render request and encoders (encode_rendered, the gain map JPEG) for every rendered format, depth and HDR mode. Each file decodes to the right size with finite samples (AVIF and the linear DNG by structure), and a half-size JPEG comes out less tinted than the same frame clamped at decoding. --- crates/engine/src/export/tests.rs | 108 ++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index b8482a7df2..f0659b221b 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -1523,3 +1523,111 @@ fn export_weights_follow_the_source_and_output_sizes() { assert_eq!(render_weight(0, 0, SourceLevel::Full, 0), 0); assert!(render_weight(usize::MAX, 1, SourceLevel::Full, usize::MAX) > 0, "no overflow"); } + +/// A raw's linear Rec.2020 near black as decoding leaves it since it stopped clamping channels at zero: a flat dark +/// patch with sensor noise through a saturating camera matrix (a NIKON D780 profile's), so many channels are +/// negative, and a few strongly out-of-gamut pixels. `clamped` is the same frame as decoding left it before. +fn dark_frame_with_negative_channels(clamped: bool) -> lightcraft_raster::Rgb32f { + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + // ±0.004 of noise per channel, a hash of the position + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + lightcraft_raster::Rgb32f::from_fn(192, 128, |x, y| { + let rgb = if (x * 3 + y) % 97 == 0 { + [-0.05, 0.01, -0.02] + } else { + let cam: [f32; 3] = std::array::from_fn(|c| 0.002 + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + }; + if clamped { rgb.map(|v: f32| v.max(0.0)) } else { rgb } + }) +} + +/// Exports `src` pushed +4 EV at half its size, rendered as an export renders it (the options' depth and colour +/// space, a separate HDR render for a gain map JPEG) and written by the export's own encoders. +fn export_dark_frame(src: &lightcraft_raster::Rgb32f, o: &ExportOptions) -> Vec { + let info = lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() }; + let mut s = lightcraft_develop::DevelopSettings::default(); + s.light.exposure = 4.0; + s.hdr.enabled = o.hdr; + let render = |depth| { + let req = lightcraft_pipeline::RenderRequest { depth, space: o.effective_space(), ..lightcraft_pipeline::RenderRequest::fit(96, 96) }; + lightcraft_pipeline::render(src, &info, &s, &req) + }; + let r = render(o.effective_depth()); + if o.hdr_output() && o.format == ExportFormat::Jpeg { + let hdr = render(OutputDepth::F32Hdr).deep.expect("an HDR render has float samples"); + encode_gain_map_jpeg(&r.image, &hdr, o, None).unwrap() + } else { + encode_rendered(&r, o, None).unwrap() + } +} + +/// Mean 8-bit sRGB of a decoded export. +fn mean_srgb8(d: &lightcraft_codecs::Decoded) -> [f64; 3] { + let img = d.to_srgb8(); + let n = img.data.len().max(1) as f64; + std::array::from_fn(|c| img.data.iter().map(|p| f64::from(p[c])).sum::() / n) +} + +/// Negative channels from decoding reach the export encoders: a dark frame pushed +4 EV exports in every rendered +/// format, depth and HDR mode as a file that decodes to the right size with finite samples (AVIF, which LightCraft +/// can't decode, and the linear DNG are checked for their structure), and comes out less tinted than the same frame +/// with its channels clamped at decoding. (At full size the white-balance clamp before noise reduction still zeroes +/// them, #2598; the half-size export averages them first.) +#[test] +fn dark_frame_with_negative_channels_exports_in_every_format() { + let src = dark_frame_with_negative_channels(false); + assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives"); + let cases = [ + (ExportFormat::Jpeg, None, false), + (ExportFormat::Jpeg, None, true), + (ExportFormat::Png, Some(8), false), + (ExportFormat::Png, Some(16), false), + (ExportFormat::Png, None, true), + (ExportFormat::Tiff, Some(8), false), + (ExportFormat::Tiff, Some(16), false), + (ExportFormat::Tiff, Some(32), false), + (ExportFormat::Tiff, Some(32), true), + (ExportFormat::Psd, Some(8), false), + (ExportFormat::Psd, Some(16), false), + (ExportFormat::Webp, None, false), + (ExportFormat::Avif, Some(8), false), + (ExportFormat::Avif, Some(10), false), + (ExportFormat::Avif, None, true), + (ExportFormat::Jxl, Some(8), false), + (ExportFormat::Jxl, Some(16), false), + (ExportFormat::Jxl, None, true), + (ExportFormat::RenderedDng, None, false), + (ExportFormat::RenderedDng, None, true), + ]; + for (format, bit_depth, hdr) in cases { + let what = format!("{format:?}, {bit_depth:?} bits, HDR {hdr}"); + let bytes = export_dark_frame(&src, &ExportOptions { format, bit_depth, hdr, ..Default::default() }); + match format { + ExportFormat::Avif => assert_eq!(bytes.get(4..8), Some(&b"ftyp"[..]), "{what}"), + ExportFormat::RenderedDng => { + let dng = lightcraft_raw::decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((dng.width, dng.height), (96, 64), "{what}"); + } + _ => { + let d = lightcraft_codecs::decode(&bytes, Default::default()).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((d.width, d.height), (96, 64), "{what}"); + assert!(d.image.data.iter().flatten().all(|v| v.is_finite()), "{what}: non-finite samples"); + if format == ExportFormat::Jpeg && hdr { + let gm = lightcraft_codecs::gainmap::read_jpeg(&bytes).unwrap_or_else(|| panic!("{what}: no gain map")); + assert!(gm.meta.alternate_headroom.is_finite(), "{what}: gain map headroom"); + } + } + } + } + let jpeg = ExportOptions::default(); + let tint = |src| { + let m = mean_srgb8(&lightcraft_codecs::decode(&export_dark_frame(src, &jpeg), Default::default()).unwrap()); + m.iter().copied().fold(f64::MIN, f64::max) - m.iter().copied().fold(f64::MAX, f64::min) + }; + let (kept, clamped) = (tint(&src), tint(&dark_frame_with_negative_channels(true))); + assert!(kept < clamped / 2.0, "kept negatives tint the export by {kept:.1} codes, clamped ones by {clamped:.1}"); +} From 5e584d4bc6453c606dd0623bab7ea3690e9323cf Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:44:52 -0500 Subject: [PATCH 064/247] LR-PROF-CAMERACOLOR: Upright analyses the source with negative channels clipped Raw decoding now keeps negative channels. Upright's analysis image resampled them as they are, which lowered the luminance its segments are found in, so it found a different correction than for the same photo before (the GX85 night frames with PerspectiveUpright=3 that radialmonster measured on #2278). analysis_plane clips a copy of the source at zero when it has negative channels, so the analysis is the one it was; sources without them take the same path as before. --- crates/pipeline/src/tests_geometry.rs | 22 ++++++++++++++++++++++ crates/pipeline/src/upright.rs | 10 ++++++++++ 2 files changed, 32 insertions(+) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index d88b6cf5dd..b43f79004f 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -432,6 +432,28 @@ fn upright_analysis_is_resolution_independent() { assert_eq!(lazy.data, stored.data); } +/// Raw decoding keeps negative channels; Upright analyses a dark noisy frame as it did when decoding clipped them at +/// zero (resampled as they are, they lowered the luminance and changed the correction found). +#[test] +fn upright_analysis_clips_negative_channels_first() { + let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: 1.5, ..Default::default() }; + let grid = keystoned_grid(1200, 800, crate::transform::manual(&shot), 80.0); + // ±0.04 of noise per channel, a hash of the position + let noise = |i: usize, c: usize| { + let h = ((i * 7919 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.08 - 0.04 + }; + let mut signed = grid.clone(); + for (i, p) in signed.data.iter_mut().enumerate() { + *p = std::array::from_fn(|c| p[c] * 0.02 + noise(i, c)); + } + let clipped = signed.map(|p| p.map(|v| v.max(0.0))); + assert!(signed.data.iter().flatten().filter(|v| **v < 0.0).count() > signed.data.len() / 4, "the frame has few negatives"); + let (info, s) = (SourceInfo::default(), DevelopSettings::default()); + let (a, b) = (crate::upright::analysis_plane(&signed, &info, &s), crate::upright::analysis_plane(&clipped, &info, &s)); + assert!(a.data == b.data, "negative channels change Upright's analysis image"); +} + /// Regression: Upright Auto must not invent perspective in natural scenes (conical trees, ridgelines, a level /// water line) — the demo library has no buildings, so Auto should stay close to identity everywhere. #[test] diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index a77369eb4b..69e023dc84 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -579,6 +579,16 @@ pub(crate) fn analysis_key(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) /// The image an analysis reads: the lens-corrected source (optics applied, no perspective or crop) /// at [`ANALYSIS_LONG`] px, as perceptual lightness normalized to its bright end. pub(crate) fn analysis_plane(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Plane { + // Raw decoding keeps negative channels (noise near black through the camera matrix). Resampled as they are, + // they lower the luminance the segments are found in, so Upright would find a different correction than for + // the same photo decoded with its channels clipped at zero; it analyses that clipped source, as it always has. + let clipped; + let src = if src.data.iter().flatten().any(|v| *v < 0.0) { + clipped = src.map(|p| p.map(|v| v.max(0.0))); + &clipped + } else { + src + }; let mut base = s.clone(); base.geometry = Geometry::default(); base.crop = Crop::default(); From 189e1fdd17376cbe8db255ad8e2022d8d0dd48e0 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:26:28 +0100 Subject: [PATCH 065/247] Bursts: sort capture times by their wall clock, test a sharpness that does not measure order_key compared the capture time as raw text, which breaks for a zone suffix or a time that does not read. It now compares the ISO 8601 wall-clock part (fraction kept, zone left out as culling's burst gap does) and puts a time that does not read last. The sharpness key uses Reverse instead of negation, so a -inf sharpness can no longer overflow; NaN counts as 0. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/bursts.rs | 57 +++++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/crates/catalog/src/bursts.rs b/crates/catalog/src/bursts.rs index a5b393780b..b9c0bcf334 100644 --- a/crates/catalog/src/bursts.rs +++ b/crates/catalog/src/bursts.rs @@ -5,16 +5,39 @@ //! shots, then capture time. Once the person arranges a burst by hand every member carries its //! place ([`crate::Analysis::rank`]), and that order is kept. +use std::cmp::Reverse; use std::collections::{HashMap, HashSet}; use crate::{Catalog, Photo, PhotoId}; /// A photo's place in its burst: hand-placed ones by their place, then the best, the sharper, -/// the earlier, the lower id. -fn order_key(p: &Photo) -> (u32, bool, i64, &str, PhotoId) { +/// the earlier (a time that doesn't read last), the lower id. +fn order_key(p: &Photo) -> (u32, bool, Reverse, bool, &str, PhotoId) { let a = p.analysis.unwrap_or_default(); - // sharpness is 0..100: a fixed-point key keeps the sort total - (a.rank.unwrap_or(u32::MAX), !a.best, -((a.sharpness * 1000.0) as i64), p.captured.as_deref().unwrap_or("~"), p.id) + let when = p.captured.as_deref().and_then(wall_clock); + (a.rank.unwrap_or(u32::MAX), !a.best, Reverse(sharpness_key(a.sharpness)), when.is_none(), when.unwrap_or(""), p.id) +} + +/// Sharpness (0..100) in thousandths: a fixed-point key keeps the sort total. `as` saturates, so +/// an infinity is the sharpest or softest there is, and a NaN counts as 0. +fn sharpness_key(sharpness: f32) -> i64 { + (sharpness * 1000.0) as i64 +} + +/// The local wall-clock part of an ISO 8601 capture time (`2026-05-01T10:00:00`, with any +/// fraction of a second), or `None` when it isn't one. Its digits stand in fixed places, so as +/// text it sorts in time order. A zone suffix is left out, as culling's burst gap does: a burst's +/// shots are seconds apart from one camera and share their zone. +fn wall_clock(iso: &str) -> Option<&str> { + let b = iso.as_bytes(); + let digits = |from: usize, to: usize| b.get(from..to).is_some_and(|d| d.iter().all(u8::is_ascii_digit)); + let at = |i: usize, c: u8| b.get(i) == Some(&c); + let shape = digits(0, 4) && at(4, b'-') && digits(5, 7) && at(7, b'-') && digits(8, 10) && at(10, b'T'); + if !(shape && digits(11, 13) && at(13, b':') && digits(14, 16) && at(16, b':') && digits(17, 19)) { + return None; + } + let end = iso[19..].find(|c: char| c != '.' && !c.is_ascii_digit()).map_or(iso.len(), |i| 19 + i); + Some(&iso[..end]) } impl Catalog { @@ -115,4 +138,30 @@ mod tests { assert_eq!(c.burst(3), vec![a, b]); assert_eq!(c.next_burst_id(), 8); } + + #[test] + fn a_sharpness_that_does_not_measure_sorts_without_a_panic() { + let mut c = Catalog::new(); + let nan = add(&mut c, "2026-05-01T10:00:00", shot(4, f32::NAN, false, None)); + let soft = add(&mut c, "2026-05-01T10:00:01", shot(4, 10.0, false, None)); + let low = add(&mut c, "2026-05-01T10:00:02", shot(4, f32::NEG_INFINITY, false, None)); + let high = add(&mut c, "2026-05-01T10:00:03", shot(4, f32::INFINITY, false, None)); + // a NaN counts as 0; the infinities saturate at either end + assert_eq!(c.burst(4), vec![high, soft, nan, low]); + } + + #[test] + fn capture_times_sort_by_their_wall_clock() { + let mut c = Catalog::new(); + let s = |c: &mut Catalog, when: &str| add(c, when, shot(5, 50.0, false, None)); + let unread = s(&mut c, "1. Mai 2026"); + let second = s(&mut c, "2026-05-01T10:00:01+02:00"); + let half = s(&mut c, "2026-05-01T10:00:00.5"); + let missing = s(&mut c, ""); + let tenth = s(&mut c, "2026-05-01T10:00:00.12Z"); + // fractions of a second in order, the zone left out, a time that doesn't read last by id + assert_eq!(c.burst(5), vec![tenth, half, second, unread, missing]); + assert_eq!(super::wall_clock("2026-05-01T10:00:00.12-07:00"), Some("2026-05-01T10:00:00.12")); + assert_eq!(super::wall_clock("2026-05-01 10:00:00"), None); + } } From 7c3d7901321a9bb4862aa48f055a0c41d83af063 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:26:41 +0100 Subject: [PATCH 066/247] Assisted Culling: test two bursts and a deleted photo with stackGroups Two bursts make two stacks in one undo step; a deleted photo is measured but left out of its burst's stack. The blur and PNG helpers of the stacking test move to module level so both tests share them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests/import.rs | 116 +++++++++++++++++++++--------- 1 file changed, 82 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index d97b00a9c6..d2d44e722a 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -1120,6 +1120,44 @@ fn assisted_culling_burst_limits_are_adjustable() { let _ = std::fs::remove_dir_all(&dir); } +/// A box blur of radius `r`: the larger `r`, the lower the focus score. +fn soften(img: &lightcraft_raster::Rgb32f, r: usize) -> lightcraft_raster::Rgb32f { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out +} + +/// Write a linear image as an sRGB PNG. +fn save_png(img: &lightcraft_raster::Rgb32f, path: &std::path::Path) { + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(path, png).unwrap(); +} + /// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its /// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step, /// and a second run neither makes another stack nor splits the existing one. @@ -1127,40 +1165,7 @@ fn assisted_culling_burst_limits_are_adjustable() { fn assisted_culling_stacks_each_burst_best_on_top() { let dir = temp_dir("cull-stack"); let scene = lightcraft_scenes::demo_library()[0].render(480, 320); - let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { - let (w, h) = (img.width, img.height); - let mut out = img.clone(); - for y in 0..h { - for x in 0..w { - let (mut acc, mut n) = ([0f32; 3], 0.0); - for yy in y.saturating_sub(r)..(y + r + 1).min(h) { - for xx in x.saturating_sub(r)..(x + r + 1).min(w) { - let c = img.data[yy * w + xx]; - acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; - n += 1.0; - } - } - out.data[y * w + x] = acc.map(|v| v / n); - } - } - out - }; - let save = |img: &lightcraft_raster::Rgb32f, name: &str| { - let data: Vec<[u8; 4]> = img - .data - .iter() - .map(|c| { - let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; - [e(c[0]), e(c[1]), e(c[2]), 255] - }) - .collect(); - let png = lightcraft_codecs::encode_png( - &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), - &Default::default(), - ) - .unwrap(); - std::fs::write(dir.join(name), png).unwrap(); - }; + let save = |img: &lightcraft_raster::Rgb32f, name: &str| save_png(img, &dir.join(name)); save(&soften(&scene, 3), "a_soft.png"); save(&scene, "b_sharp.png"); save(&soften(&scene, 6), "c_softer.png"); @@ -1234,6 +1239,49 @@ fn assisted_culling_stacks_each_burst_best_on_top() { let _ = std::fs::remove_dir_all(&dir); } +/// Assisted culling with `stackGroups` (#2277): two bursts make two stacks in one undo step, and a +/// deleted photo is measured but left out of its burst's stack, even when it is the sharpest. +#[test] +fn assisted_culling_stacks_two_bursts_and_leaves_deleted_photos_out() { + let dir = temp_dir("cull-stack-two"); + let (one, two) = (lightcraft_scenes::demo_library()[0].render(480, 320), lightcraft_scenes::demo_library()[7].render(480, 320)); + let files = [ + ("a_soft.png", soften(&one, 3), "10:00:00"), + ("b_sharp.png", one.clone(), "10:00:01"), + ("c_softer.png", soften(&one, 6), "10:00:02"), + ("d_sharp.png", two.clone(), "10:05:00"), + ("e_soft.png", soften(&two, 4), "10:05:01"), + ]; + for (name, img, _) in &files { + save_png(img, &dir.join(name)); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (name, _, at) in &files { + let id = by_name(&s, name); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T{at}")) }).unwrap(); + } + let [soft, sharp, softer, d, e] = files.map(|f| by_name(&s, f.0)); + let ids: Vec = [soft, sharp, softer, d, e].iter().map(|p| p.0).collect(); + s.commit("t", lightcraft_catalog::Op::SetDeleted { id: sharp, deleted: true }).unwrap(); + let n = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!((r["groups"].clone(), r["stacks"].clone()), (json!(2), json!(2)), "{r}"); + assert_eq!(s.commits(), n + 1, "analysis and both stacks are one undo step"); + // the deleted photo is measured, but its burst is stacked from the other two + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some()); + assert!(s.catalog.stack_of(sharp).is_none(), "a deleted photo is never stacked"); + let st = s.catalog.stack_of(soft).unwrap(); + assert!(st.collapsed && st.top() == soft && st.photos.len() == 2 && st.photos.contains(&softer), "{st:?}"); + let st = s.catalog.stack_of(d).unwrap(); + assert!(st.collapsed && st.top() == d && st.photos.len() == 2 && st.photos.contains(&e), "{st:?}"); + // one undo removes both stacks + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { From 0eb5f8c29bea8b7f246a7bd39137d12cffd9d3c6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:27:15 +0100 Subject: [PATCH 067/247] #2359: spot thinning is tested on a long stroke and a zero size, and a zero size drops exact repeats Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/masks.rs | 37 +++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index 76c5bdc890..3cbd63a19d 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -1105,7 +1105,8 @@ fn thin_spot_points(pts: &[Point], size: f64, (w, h): (f64, f64)) -> Vec let spacing = size / 4.0; let mut out: Vec = Vec::with_capacity(pts.len().min(64)); for &q in pts { - if out.last().is_none_or(|&last| dist(last, q) >= spacing) { + // `> 0.0` as well: with a zero size an exact repeat would otherwise count as a step + if out.last().is_none_or(|&last| dist(last, q) > 0.0 && dist(last, q) >= spacing) { out.push(q); } } @@ -1230,4 +1231,38 @@ mod tests { // a zero-sized photo doesn't divide by zero assert_eq!(thin_spot_points(&[one[0], Point::new(0.6, 0.6)], 0.05, (0.0, 0.0)).len(), 1); } + + /// A long straight stroke keeps about one point per spacing, leaves no gap wider than a spacing plus one + /// recorded step (two spacings at the end), and still ends where the stroke ended, also after a hold there. + #[test] + fn a_long_stroke_is_thinned_without_gaps() { + let step = 0.0008; + let mut pts: Vec = (0..=1000).map(|i| Point::new(0.1 + step * f64::from(i), 0.5)).collect(); + // the pointer rests at the end for a few frames + pts.extend([*pts.last().unwrap(); 5]); + let (size, dims) = (0.04, (3.0, 2.0)); + let thin = thin_spot_points(&pts, size, dims); + // 0.8 long-edge units at one point per 0.01, plus the first + assert!((70..=82).contains(&thin.len()), "{}", thin.len()); + assert_eq!(thin.first(), pts.first()); + assert_eq!(thin.last(), pts.last()); + let gaps: Vec = thin.windows(2).map(|w| w[1].x - w[0].x).collect(); + let spacing = size / 4.0; + for &gap in &gaps[..gaps.len() - 1] { + assert!(gap > 0.0 && gap <= spacing + step + 1e-12, "gap {gap}"); + } + // the end takes the place of the last point kept, so the last gap may reach two spacings + let end_gap = gaps[gaps.len() - 1]; + assert!(end_gap > 0.0 && end_gap < 2.0 * spacing + step, "end gap {end_gap}"); + } + + /// A zero or tiny brush thins nothing but exact repeats: every distinct point is kept, in order. + #[test] + fn a_zero_or_tiny_size_keeps_every_distinct_point() { + let pts: Vec = (0..50).map(|i| Point::new(0.2 + 0.001 * f64::from(i), 0.3)).collect(); + let doubled: Vec = pts.iter().flat_map(|&q| [q, q]).collect(); + for size in [0.0, 1e-9] { + assert_eq!(thin_spot_points(&doubled, size, (3.0, 2.0)), pts, "size {size}"); + } + } } From 41a95eaa5322f1b63b83feb24730947127c133fb Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:29:14 +0100 Subject: [PATCH 068/247] Cull dialog: stack_groups defaults to off when left out main's dialog_copy test builds Dialog::Cull from JSON without stack_groups, as an older saved dialog would; the field now defaults like reset_bursts does. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state/dialog.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index c4a6b5f2a1..6247d12380 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -172,6 +172,7 @@ pub enum Dialog { Cull { reject_below: f32, pick_best: bool, + #[serde(default)] stack_groups: bool, burst_gap: f32, similarity: f32, From ed7dbd8082a5b8c88a313923ad9367c06bc89800 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:30:19 +0100 Subject: [PATCH 069/247] Assisted Culling: a cull dialog without stack_groups reads it as false Like reset_bursts, the field takes its default when the JSON leaves it out, so main's dialog-copy test builds the dialog unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state/dialog.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 4c0549e926..092da21881 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -171,6 +171,7 @@ pub enum Dialog { Cull { reject_below: f32, pick_best: bool, + #[serde(default)] stack_groups: bool, burst_gap: f32, similarity: f32, From 2309336204194f91c8675d2666a467f6f0b557bc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Wed, 21 Oct 2026 18:16:28 -0400 Subject: [PATCH 070/247] LR-BEHAV-BG-TASKS: detached readers for an import or scan: stall, skip and cap, with their own tests --- crates/engine/src/import.rs | 6 + crates/engine/src/import/reads.rs | 624 +++++++++++++++++++++++++ crates/engine/src/import/tests_pool.rs | 477 +++++++++++++++++++ 3 files changed, 1107 insertions(+) create mode 100644 crates/engine/src/import/reads.rs create mode 100644 crates/engine/src/import/tests_pool.rs diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 6a6b6e6a70..a3b51e4bae 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -38,6 +38,7 @@ mod commit; mod defaults; mod files; mod job; +mod reads; mod scan; mod types; @@ -52,6 +53,7 @@ pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; #[cfg(test)] use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; +pub use reads::{MAX_SKIPPED, MAX_STUCK_READERS, ReadWatch, STALL_AFTER, StalledRead, StuckReaders}; pub(crate) use scan::scan_files; pub use scan::{ScanInput, ScanOutput, ScanProgress, scan, scan_with}; #[cfg(test)] @@ -64,3 +66,7 @@ pub use types::{ #[cfg(test)] #[path = "import/tests_known.rs"] mod tests_known; + +#[cfg(test)] +#[path = "import/tests_pool.rs"] +mod tests_pool; diff --git a/crates/engine/src/import/reads.rs b/crates/engine/src/import/reads.rs new file mode 100644 index 0000000000..fb3291bea0 --- /dev/null +++ b/crates/engine/src/import/reads.rs @@ -0,0 +1,624 @@ +//! The file reads of an import (or a scan) that can stop answering (LR-BEHAV-BG-TASKS). +//! +//! **Not used yet:** this is the tested core. The import, the scans and Synchronize Folder move onto it in the +//! changes that follow (✕ ending them at once, then the activity row naming the stalled file and offering Skip), so +//! nothing outside this module's tests calls [`Pool::run`] today. +//! +//! A network drive that drops its connection leaves a read blocked inside the operating system, and a blocked read +//! cannot be interrupted. An import that waited for every read (as a scope of threads does: it cannot end before each +//! thread has) hung with it, and the only way out was to quit. Here the reads run on detached threads that pull their +//! jobs from a shared queue ([`Pool::run`]), and the calling thread only coordinates. It looks every +//! 250 ms at: +//! +//! - **✕:** the run stops at once. Jobs under way are given [`CANCEL_GRACE`] to finish (what they made is kept, as +//! before), then abandoned; jobs still queued are never started. +//! - **A stall:** a job that has made no progress for [`ReadWatch::stall_after`] is published +//! ([`ReadWatch::stalled`]), for the activity row to name ("Waiting for IMG_0457.jpg · 14 s"). Progress is a byte +//! read or written, or the end of a step: work that takes long without waiting on the disk (queueing for memory, +//! encoding a DNG) says so with [`progressed`], so a healthy slow job is never reported. +//! - **Skip:** [`ReadWatch::skip`] gives up the one read the row names (the longest without progress; the next is +//! named afterwards). It is reported as failed ("skipped: no answer after N s"), its thread is abandoned (it stays +//! blocked until the system lets it go, and its late result is dropped, never applied; it keeps its memory permit +//! until then) and a fresh thread takes its place, so the run goes on with the same number of readers. +//! - **A drive that is gone:** the [`MAX_SKIPPED`]th skipped read ends the run with an error ([`ReadWatch::ended`]) +//! instead of leaving yet another thread blocked. +//! +//! - **Earlier runs:** an abandoned read stays blocked after its run is over, and the next run builds a new pool. The +//! abandoned threads still alive are counted across runs ([`StuckReaders`], [`MAX_STUCK_READERS`]), whichever drive +//! they wait on; once that many are blocked, a run is not started (and a Skip starts no replacement reader) and the +//! run ends with an error saying so, so repeated cancel and restart cannot pile up blocked threads. The count is +//! looked at when a run starts and after each Skip; ✕ can still abandon the readers of the runs under way (at most +//! [`crate::import::workers`] per pool, and Synchronize Folder runs two) on top, so the bound is the cap plus that. +//! +//! Several pools can run at once under one [`ReadWatch`] (Synchronize Folder probes the new files while it checks +//! the library's photos): the watch names the longest stall of all, and Skip acts on the pool that has it. + +// (no caller outside the tests yet, see above: the tests use all of it, so only the non-test build allows it. On wasm32 +// the pool is not built at all, which the follow-up keeps allowing) +#![cfg_attr(not(test), allow(dead_code))] + +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use web_time::Instant; + +/// A read that has made no progress for this long is reported as stalled. +pub const STALL_AFTER: Duration = Duration::from_secs(10); +/// The skipped reads that end a run with an error: each leaves a thread blocked until the system lets it go. +pub const MAX_SKIPPED: usize = 4; +/// The abandoned reads that keep a new run from starting, over all runs of the process (eight runs' worth of +/// [`MAX_SKIPPED`]). It is looked at when a run starts and after a Skip, and ✕ can abandon the readers of the runs +/// under way on top: the blocked threads stay bounded by this plus a few runs' readers, not unbounded. +pub const MAX_STUCK_READERS: usize = 32; +/// How often the coordinating thread looks at ✕, Skip and the readers. +const POLL: Duration = Duration::from_millis(250); +/// Once ✕ is pressed, how long jobs under way get to finish before they are abandoned. +const CANCEL_GRACE: Duration = Duration::from_millis(400); + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// How many abandoned reader threads are still alive (blocked in the operating system), shared by every run that +/// uses it. A thread counts from the moment it is abandoned until it truly exits, however long after its run ended. +#[derive(Debug)] +pub struct StuckReaders { + alive: AtomicUsize, + cap: usize, +} + +impl StuckReaders { + pub fn new(cap: usize) -> Self { + StuckReaders { alive: AtomicUsize::new(0), cap } + } + + /// The process-wide count: the session will start with it, once the readers are wired in. + pub fn global() -> std::sync::Arc { + static GLOBAL: std::sync::OnceLock> = std::sync::OnceLock::new(); + GLOBAL.get_or_init(|| std::sync::Arc::new(StuckReaders::new(MAX_STUCK_READERS))).clone() + } + + /// Abandoned readers still blocked. + pub fn alive(&self) -> usize { + self.alive.load(Ordering::SeqCst) + } + + fn full(&self) -> bool { + self.alive() >= self.cap + } +} + +/// A read that has gone without progress ([`ReadWatch::stalled`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StalledRead { + /// The file's name. + pub what: String, + /// How long it has been without progress. + pub waited: Duration, +} + +/// What the reads of an import or scan are doing, shared between the run (which publishes it) and whoever shows it +/// and offers Skip. Everything is behind `&self`: hand out clones of the `Arc`. +#[derive(Debug)] +pub struct ReadWatch { + stall_after_ms: AtomicU64, + poll_ms: AtomicU64, + /// The longest stall of each running pool: (pool, the file's name, since when). + stalls: Mutex>, + pools: AtomicU64, + /// Skip was asked for this read (its name and since when it stalled). + skip: Mutex>, + skipped: AtomicUsize, + ended: Mutex>, + stuck: std::sync::Arc, +} + +impl Default for ReadWatch { + fn default() -> Self { + ReadWatch { + stall_after_ms: AtomicU64::new(millis(STALL_AFTER)), + poll_ms: AtomicU64::new(millis(POLL)), + stalls: Mutex::new(Vec::new()), + pools: AtomicU64::new(0), + skip: Mutex::new(None), + skipped: AtomicUsize::new(0), + ended: Mutex::new(None), + stuck: StuckReaders::global(), + } + } +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) +} + +impl ReadWatch { + /// A watch whose runs count their abandoned readers in `stuck` (the session's, once the readers are wired in). + pub fn with_stuck(after: Duration, stuck: std::sync::Arc) -> Self { + ReadWatch { stuck, ..ReadWatch::new(after) } + } + + /// A watch that calls a read stalled after `after` ([`STALL_AFTER`] by default). + pub fn new(after: Duration) -> Self { + let watch = ReadWatch::default(); + watch.set_stall_after(after); + watch + } + + /// How long a read goes without progress before it counts as stalled. + pub fn stall_after(&self) -> Duration { + Duration::from_millis(self.stall_after_ms.load(Ordering::Relaxed)) + } + + pub fn set_stall_after(&self, after: Duration) { + self.stall_after_ms.store(millis(after), Ordering::Relaxed); + } + + /// How often the reads are looked at, for tests that cannot wait a quarter of a second. + #[cfg(test)] + pub(crate) fn set_poll(&self, every: Duration) { + self.poll_ms.store(millis(every).max(1), Ordering::Relaxed); + } + + fn poll(&self) -> Duration { + Duration::from_millis(self.poll_ms.load(Ordering::Relaxed)) + } + + /// The read that has gone longest without progress, if one has for [`ReadWatch::stall_after`]. + pub fn stalled(&self) -> Option { + let stalls = lock(&self.stalls); + stalls.iter().min_by_key(|(_, _, since)| *since).map(|(_, what, since)| StalledRead { what: what.clone(), waited: since.elapsed() }) + } + + fn register_pool(&self) -> u64 { + self.pools.fetch_add(1, Ordering::Relaxed) + } + + /// Say which read of `pool` has stalled the longest (`None`: none has). + fn publish(&self, pool: u64, stalled: Option<(String, Instant)>) { + let mut stalls = lock(&self.stalls); + stalls.retain(|(p, ..)| *p != pool); + if let Some((what, since)) = stalled { + stalls.push((pool, what, since)); + } + // a Skip is for the read that was named: one that answered meanwhile (or was given up) takes it with it + let mut asked = lock(&self.skip); + if asked.as_ref().is_some_and(|(what, since)| !stalls.iter().any(|(_, w, s)| w == what && s == since)) { + *asked = None; + } + } + + /// Give up the read that is named ([`ReadWatch::stalled`]), at the next look: only that read, and only while it is + /// still the one named (a Skip for a read that answered meanwhile does nothing). Nothing happens when no read is + /// stalled. + pub fn skip(&self) { + let stalls = lock(&self.stalls); + *lock(&self.skip) = stalls.iter().min_by_key(|(_, _, since)| *since).map(|(_, what, since)| (what.clone(), *since)); + } + + /// Whether Skip was asked for the read `shown` (the one the row named when it was asked) and that read is the one + /// named now, which is `pool`'s; asking clears it. + fn take_skip_for(&self, pool: u64, shown: &(String, Instant)) -> bool { + let stalls = lock(&self.stalls); + let named_here = + stalls.iter().min_by_key(|(_, _, since)| *since).is_some_and(|(p, what, since)| *p == pool && (what, since) == (&shown.0, &shown.1)); + named_here && lock(&self.skip).take().is_some_and(|asked| asked == *shown) + } + + /// How many reads were given up by Skip so far. + pub fn skipped(&self) -> usize { + self.skipped.load(Ordering::Relaxed) + } + + /// Why the run cannot go on, once it cannot: too many reads were skipped, or a reader could not be started. + pub fn ended(&self) -> Option { + lock(&self.ended).clone() + } + + fn blocked_elsewhere(&self) -> String { + format!( + "a drive is not answering: {} reads that were given up are still waiting for it (try again later, or restart LightCraft)", + self.stuck.alive() + ) + } + + fn end(&self, why: String) { + lock(&self.ended).get_or_insert(why); + } +} + +/// How one job of a [`Pool::run`] came out. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +pub(super) enum Outcome { + Done(R), + /// It was skipped, or its worker panicked: why. + Failed(String), + /// Never started, or cut off before it finished: by ✕, or because the run ended (too many reads skipped, too many + /// given-up reads still blocked, or a reader that could not be started). + Unreached, +} + +/// Where one run of reads happens ([`Pool::run`]). +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct Pool<'a> { + pub watch: &'a ReadWatch, + /// ✕: set from outside (the activity row's, or the run's own). + pub cancel: &'a AtomicBool, + /// Thread names: `-`. + pub name: &'static str, + /// Reads at once. + pub threads: usize, +} + +/// A thread of the pool. It is *abandoned* when its job is given up: it never takes another job, and what it +/// finishes with goes to the `late` handler. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Worker { + /// The job it is on (its index) and when it last made progress. + busy: Mutex>, + abandoned: std::sync::Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + /// The pool thread this is, for [`progressed`]. + static CURRENT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// The abandon flag of the pool thread this is (`None` on any other thread), for the memory gate to tell the permits of +/// reads that were given up from the others. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn abandon_flag() -> Option> { + CURRENT.with(|current| current.borrow().as_ref().map(|worker| worker.abandoned.clone())) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn abandon_flag() -> Option> { + None +} + +/// The job on this thread has made progress (a chunk read or written, a wait for memory over, a step done): its +/// stall clock starts again. Does nothing on a thread that is not a pool's. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn progressed() { + CURRENT.with(|current| { + if let Some(worker) = current.borrow().as_ref() + && let Some(busy) = lock(&worker.busy).as_mut() + { + busy.1 = Instant::now(); + } + }); +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn progressed() {} + +type Message = (usize, Result); + +/// Where the workers hand in what they finished, until the run is over: a late hand-in is refused, so that its sender +/// disposes of it. +#[cfg(not(target_arch = "wasm32"))] +struct Inbox(Mutex>>>); + +#[cfg(not(target_arch = "wasm32"))] +impl Inbox { + fn hand_in(&self, message: Message) -> Result<(), Message> { + match lock(&self.0).as_ref() { + Some(tx) => tx.send(message).map_err(|e| e.0), + None => Err(message), + } + } + + fn close(&self) { + *lock(&self.0) = None; + } +} + +#[cfg(not(target_arch = "wasm32"))] +type Work = std::sync::Arc R + Send + Sync>; + +/// What every thread of one run shares. +#[cfg(not(target_arch = "wasm32"))] +struct Shared { + jobs: Mutex>, + inbox: Inbox, + work: Work, + late: std::sync::Arc, + init: std::sync::Arc, + /// The run is over: a job still queued is not started. + over: AtomicBool, + stuck: std::sync::Arc, +} + +/// Gives up the thread's place in the [`StuckReaders`] count when it exits, if it was abandoned. +#[cfg(not(target_arch = "wasm32"))] +struct Exit(std::sync::Arc, std::sync::Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Exit { + fn drop(&mut self) { + if self.0.abandoned.load(Ordering::SeqCst) { + self.1.alive.fetch_sub(1, Ordering::SeqCst); + } + } +} + +/// Abandon `w` (its job is given up), counting it until its thread exits. Call with its `busy` lock held and `Some`. +#[cfg(not(target_arch = "wasm32"))] +fn abandon(w: &Worker, stuck: &StuckReaders) { + if !w.abandoned.swap(true, Ordering::SeqCst) { + stuck.alive.fetch_add(1, Ordering::SeqCst); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn worker_loop(me: std::sync::Arc, shared: std::sync::Arc>) { + let _exit = Exit(me.clone(), shared.stuck.clone()); + CURRENT.with(|current| *current.borrow_mut() = Some(me.clone())); + // (a reader that cannot be set up still takes jobs: one that died here would be handed jobs it never takes) + if let Err(why) = crate::guard::catch("import", || (shared.init)()) { + log::warn!("import: a reader's set-up failed: {why}"); + } + loop { + // (the lock is held while waiting: the other idle workers queue behind it, and a worker blocked in a read does + // not hold it) + let next = lock(&shared.jobs).recv(); + let Ok((i, job)) = next else { return }; + // (checked and claimed under one lock: the end-of-run sweep sets `over` first, so it either sees this job and + // abandons the thread, or the thread sees `over` and never starts it) + { + let mut busy = lock(&me.busy); + if shared.over.load(Ordering::SeqCst) || me.abandoned.load(Ordering::SeqCst) { + return; + } + *busy = Some((i, Instant::now())); + } + let result = crate::guard::catch("import", || (shared.work)(job)); + // decided under the lock the coordinator abandons under, so that it never abandons the next job by mistake + let abandoned = { + let mut busy = lock(&me.busy); + *busy = None; + me.abandoned.load(Ordering::SeqCst) + }; + if abandoned { + if let Ok(r) = result { + (shared.late)(r); + } + return; + } + if let Err((_, Ok(r))) = shared.inbox.hand_in((i, result)) { + (shared.late)(r); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Pool<'_> { + fn halted(&self) -> bool { + self.cancel.load(Ordering::Relaxed) || self.watch.ended().is_some() + } + + /// Run `jobs` on [`Pool::threads`] detached threads; the outcome of each, in order. `label` names job `i` for the + /// row; `work` does one; `late` disposes of a result that arrives after its job was given up (nothing may be + /// applied: a copy that was made is taken back); `init` runs first on each new thread; `on_done` counts each job + /// settled (`None`: failed). + /// + /// Jobs are handed out by this thread, no more than there are readers at a time, so that ✕ stops the run + /// within a file or two. If no thread can be started the jobs run here, one after another. + pub(super) fn run( + &self, + jobs: Vec, + label: &dyn Fn(usize) -> String, + work: Work, + late: std::sync::Arc, + init: std::sync::Arc, + on_done: &dyn Fn(Option<&R>), + ) -> Vec> { + use std::sync::Arc; + use std::sync::mpsc; + let total = jobs.len(); + let mut outcomes: Vec> = (0..total).map(|_| Outcome::Unreached).collect(); + if total == 0 || self.halted() { + return outcomes; + } + if self.watch.stuck.full() { + self.watch.end(self.watch.blocked_elsewhere()); + return outcomes; + } + let pool = self.watch.register_pool(); + let (job_tx, job_rx) = mpsc::channel::<(usize, J)>(); + let (result_tx, result_rx) = mpsc::channel::>(); + let shared = Arc::new(Shared { + jobs: Mutex::new(job_rx), + inbox: Inbox(Mutex::new(Some(result_tx))), + work: work.clone(), + late: late.clone(), + init, + over: AtomicBool::new(false), + stuck: self.watch.stuck.clone(), + }); + let start = |n: usize| -> std::io::Result> { + let me = Arc::new(Worker::default()); + let (mine, shared) = (me.clone(), shared.clone()); + std::thread::Builder::new().name(format!("{}-{n}", self.name)).spawn(move || worker_loop(mine, shared))?; + Ok(me) + }; + let mut live: Vec> = Vec::new(); + for n in 0..self.threads.clamp(1, total) { + match start(n) { + Ok(w) => live.push(w), + Err(e) => { + log::warn!("import: could not start a reader: {e}"); + break; + } + } + } + if live.is_empty() { + // no thread to be had: read here, one after another + for (job, slot) in jobs.into_iter().zip(outcomes.iter_mut()) { + if self.halted() { + break; + } + *slot = match crate::guard::catch("import", || work(job)) { + Ok(r) => { + on_done(Some(&r)); + Outcome::Done(r) + } + Err(e) => { + on_done(None); + Outcome::Failed(e) + } + }; + } + return outcomes; + } + let mut jobs: Vec> = jobs.into_iter().map(Some).collect(); + let mut started = live.len(); + let (mut next, mut outstanding) = (0usize, 0usize); + let mut halted_at: Option = None; + let settle = |outcomes: &mut Vec>, outstanding: &mut usize, (i, result): Message| { + let Some(slot) = outcomes.get_mut(i) else { return }; + if !matches!(slot, Outcome::Unreached) { + // its job was given up already: this is the late answer + if let Ok(r) = result { + late(r); + } + return; + } + *outstanding = outstanding.saturating_sub(1); + *slot = match result { + Ok(r) => { + on_done(Some(&r)); + Outcome::Done(r) + } + Err(e) => { + on_done(None); + Outcome::Failed(e) + } + }; + }; + loop { + if halted_at.is_none() && self.halted() { + halted_at = Some(Instant::now()); + } + if halted_at.is_none() { + while outstanding < live.len() && next < total { + let Some(job) = jobs.get_mut(next).and_then(Option::take) else { + next += 1; + continue; + }; + if job_tx.send((next, job)).is_err() { + self.watch.end("the readers stopped unexpectedly".into()); + break; + } + next += 1; + outstanding += 1; + } + } + if outstanding == 0 && (halted_at.is_some() || next >= total) { + break; + } + if let Some(at) = halted_at + && (self.watch.ended().is_some() || at.elapsed() >= CANCEL_GRACE) + { + break; + } + match result_rx.recv_timeout(self.watch.poll()) { + Ok(message) => settle(&mut outcomes, &mut outstanding, message), + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + // jobs without progress: the longest is published for the row, and given up when Skip was asked for + let after = self.watch.stall_after(); + let stalled = live + .iter() + .enumerate() + .filter_map(|(k, w)| (*lock(&w.busy)).filter(|(_, since)| since.elapsed() >= after).map(|(i, since)| (k, i, since))) + .min_by_key(|&(_, _, since)| since); + self.watch.publish(pool, stalled.map(|(_, i, since)| (label(i), since))); + if let Some((k, i, since)) = stalled + && halted_at.is_none() + && self.watch.take_skip_for(pool, &(label(i), since)) + && let Some(w) = live.get(k) + { + { + let busy = lock(&w.busy); + if *busy != Some((i, since)) { + continue; // it answered just now + } + abandon(w, &self.watch.stuck); + } + live.remove(k); + let secs = since.elapsed().as_secs(); + if let Some(slot) = outcomes.get_mut(i) { + *slot = Outcome::Failed(format!("skipped: no answer after {secs} s")); + } + on_done(None); + outstanding = outstanding.saturating_sub(1); + let skipped = self.watch.skipped.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if skipped >= MAX_SKIPPED { + self.watch.end(format!("the drive is not answering ({} is the last file it stopped on)", label(i))); + } else if self.watch.stuck.full() { + self.watch.end(self.watch.blocked_elsewhere()); + } else { + match start(started) { + Ok(w) => { + started += 1; + live.push(w); + } + Err(e) => self.watch.end(format!("could not start a reader: {e}")), + } + } + } + } + // Over (or stopped): jobs still queued are not started, and the readers still at one are abandoned: they + // dispose of their own results. What arrived already is taken, so nothing is lost between the last look and + // here. + shared.over.store(true, Ordering::SeqCst); + for w in &live { + let busy = lock(&w.busy); + if busy.is_some() { + abandon(w, &self.watch.stuck); + } + } + drop(job_tx); + shared.inbox.close(); + while let Ok(message) = result_rx.try_recv() { + settle(&mut outcomes, &mut outstanding, message); + } + self.watch.publish(pool, None); + outcomes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A Skip is for the read that was named when it was asked: once that read answered and another is named, the + /// request does nothing. + #[test] + fn a_stale_skip_does_nothing() { + let watch = ReadWatch::default(); + let old = Instant::now(); + watch.publish(0, Some(("a.jpg".into(), old))); + watch.skip(); + // a.jpg answered; b.jpg stalled since + watch.publish(0, Some(("b.jpg".into(), Instant::now()))); + assert!(watch.skip.lock().unwrap().is_none(), "the request went with the read it was for"); + assert!(!watch.take_skip_for(0, &("b.jpg".into(), Instant::now()))); + // a request for the read that is named is taken, once + let now = Instant::now(); + watch.publish(0, Some(("b.jpg".into(), now))); + watch.skip(); + assert!(watch.take_skip_for(0, &("b.jpg".into(), now))); + assert!(!watch.take_skip_for(0, &("b.jpg".into(), now))); + // nothing named: Skip asks for nothing + watch.publish(0, None); + watch.skip(); + assert!(watch.skip.lock().unwrap().is_none()); + } +} diff --git a/crates/engine/src/import/tests_pool.rs b/crates/engine/src/import/tests_pool.rs new file mode 100644 index 0000000000..3de4da6239 --- /dev/null +++ b/crates/engine/src/import/tests_pool.rs @@ -0,0 +1,477 @@ +//! The detached readers on their own ([`super::reads`]): the pool is driven with fake reads that hang, make progress, +//! panic and answer late, with no import around it. What a stalled read looks like to the person is up to whoever uses +//! the pool; these tests are about what the pool does: ✕, naming the stalled read, Skip, the cap, a late answer. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use super::reads::{MAX_SKIPPED, MAX_STUCK_READERS, Outcome, Pool, ReadWatch, StuckReaders, abandon_flag, progressed}; + +/// How long a read may go without progress before the tests call it stalled. Long next to anything a test does between +/// two signs of progress (a few milliseconds), so that a busy machine delaying a thread does not name a healthy read. +const STALL: Duration = Duration::from_millis(500); + +/// A read that does not answer until `open`. +#[derive(Clone, Default)] +struct Gate(Arc<(Mutex, Condvar)>); + +impl Gate { + fn wait(&self) { + let (open, bell) = &*self.0; + let mut open = open.lock().unwrap(); + while !*open { + open = bell.wait(open).unwrap(); + } + } + + fn open(&self) { + *self.0.0.lock().unwrap() = true; + self.0.1.notify_all(); + } +} + +fn stuck() -> Arc { + Arc::new(StuckReaders::new(MAX_STUCK_READERS)) +} + +/// A watch that looks every 10 ms (not 250) and counts its abandoned readers in `stuck`. +fn watch(stuck: &Arc) -> Arc { + let watch = ReadWatch::with_stuck(STALL, stuck.clone()); + watch.set_poll(Duration::from_millis(10)); + Arc::new(watch) +} + +/// Run `work` over `jobs` on `threads` readers, job `i` named "job"; results that arrive late go to `late`. +fn run( + watch: &ReadWatch, + cancel: &AtomicBool, + threads: usize, + jobs: Vec, + work: impl Fn(J) -> R + Send + Sync + 'static, + late: impl Fn(R) + Send + Sync + 'static, +) -> Vec> { + let pool = Pool { watch, cancel, name: "test-read", threads }; + pool.run(jobs, &|i| format!("job{i}"), Arc::new(work), Arc::new(late), Arc::new(|| {}), &|_| {}) +} + +/// [`run`] on a thread of its own, so that the test can watch it and press ✕ or Skip meanwhile. +fn run_in_background( + watch: &Arc, + cancel: &Arc, + threads: usize, + jobs: Vec, + work: impl Fn(J) -> R + Send + Sync + 'static, + late: impl Fn(R) + Send + Sync + 'static, +) -> JoinHandle>> { + let (watch, cancel) = (watch.clone(), cancel.clone()); + std::thread::spawn(move || run(&watch, &cancel, threads, jobs, work, late)) +} + +/// Wait for `condition` for up to 30 s (a hung test is worse than a slow one). +fn wait_until(what: &str, mut condition: impl FnMut() -> bool) { + let until = Instant::now() + Duration::from_secs(30); + while !condition() { + assert!(Instant::now() < until, "gave up waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Wait for a run started with [`run_in_background`] to end, for up to 30 s: a run that never ends fails the test +/// instead of hanging it. +fn join_within(handle: JoinHandle) -> R { + wait_until("the run to end", || handle.is_finished()); + handle.join().unwrap() +} + +fn is_skipped(outcome: &Outcome) -> bool { + matches!(outcome, Outcome::Failed(why) if why.starts_with("skipped: no answer after ")) +} + +#[test] +fn every_job_is_done_and_counted_in_its_own_slot() { + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let counted = AtomicUsize::new(0); + let pool = Pool { watch: &watch, cancel: &cancel, name: "test-read", threads: 3 }; + let outcomes = pool.run((0..10u32).collect(), &|i| format!("job{i}"), Arc::new(|n: u32| n * 2), Arc::new(|_| {}), Arc::new(|| {}), &|r| { + assert!(r.is_some()); + counted.fetch_add(1, Relaxed); + }); + let got: Vec = outcomes.iter().map(|o| if let Outcome::Done(n) = o { *n } else { u32::MAX }).collect(); + assert_eq!(got, (0..10).map(|n| n * 2).collect::>()); + assert_eq!(counted.load(Relaxed), 10); + assert_eq!((watch.skipped(), watch.ended(), watch.stalled()), (0, None, None)); + assert_eq!(stuck.alive(), 0); +} + +#[test] +fn a_panicking_job_fails_only_itself() { + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let outcomes = run( + &watch, + &cancel, + 2, + vec![1u32, 2, 3, 4], + |n| { + assert_ne!(n, 3, "a read that panics"); + n + }, + |_| {}, + ); + assert!(matches!(outcomes[0], Outcome::Done(1)) && matches!(outcomes[1], Outcome::Done(2)) && matches!(outcomes[3], Outcome::Done(4))); + assert!(matches!(&outcomes[2], Outcome::Failed(_)), "{:?}", outcomes[2]); + assert_eq!(watch.ended(), None, "one failed read does not end the run"); +} + +/// Given reads that hang, +/// When ✕ is pressed, +/// Then the run ends at once with what answered so far, the hung reads are left behind and the jobs still queued never +/// start. +#[test] +fn cancel_ends_the_run_while_reads_hang() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let (gate, started) = (Gate::default(), Arc::new(AtomicUsize::new(0))); + let (g, s) = (gate.clone(), started.clone()); + let run = run_in_background( + &watch, + &cancel, + 2, + (0..8u32).collect(), + move |n| { + s.fetch_add(1, Relaxed); + if n < 2 { + g.wait(); + } + n + }, + |_| {}, + ); + wait_until("both readers to be on a hung read", || started.load(Relaxed) == 2); + let pressed = Instant::now(); + cancel.store(true, Relaxed); + let outcomes = join_within(run); + assert!(pressed.elapsed() < Duration::from_secs(3), "the run took {:?} to end", pressed.elapsed()); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Unreached)), "{outcomes:?}"); + assert_eq!(started.load(Relaxed), 2, "no queued job was started"); + assert_eq!(stuck.alive(), 2, "the two readers that were left behind are counted"); + gate.open(); + wait_until("the readers left behind to exit", || stuck.alive() == 0); + assert_eq!(started.load(Relaxed), 2, "and they took no job on their way out"); +} + +/// Given a read that makes progress now and then for much longer than the stall time, +/// Then it is never named. +#[test] +fn a_slow_read_that_keeps_progressing_is_never_named() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![()], + |()| { + for _ in 0..120 { + std::thread::sleep(Duration::from_millis(20)); + progressed(); + } + }, + |_| {}, + ); + let mut named = None; + wait_until("the run to end", || { + named = named.take().or(watch.stalled()); + run.is_finished() + }); + assert!(matches!(join_within(run)[0], Outcome::Done(()))); + assert_eq!(named, None, "a read that goes on is not stalled (it ran for {:?}, the stall time is {STALL:?})", Duration::from_millis(2400)); +} + +/// Given a read that does not progress, +/// Then it is named after the stall time, and nothing is named once it answers. +#[test] +fn a_read_without_progress_is_named_until_it_answers() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + wait_until("the read to be named", || watch.stalled().is_some()); + let named = watch.stalled().unwrap(); + assert_eq!(named.what, "job0"); + assert!(named.waited >= STALL, "{named:?}"); + gate.open(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); + assert_eq!(watch.stalled(), None); +} + +/// Given two reads that both hang, +/// When Skip is asked for, +/// Then only the one that is named (the longest without progress) is given up, a fresh reader takes its place so that +/// the other jobs go on, and the other read is named next. +#[test] +fn skip_gives_up_only_the_read_that_is_named() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gates = [Gate::default(), Gate::default()]; + let hung = gates.clone(); + let late = Arc::new(Mutex::new(Vec::new())); + let l = late.clone(); + let reading = run_in_background( + &watch, + &cancel, + 2, + vec![0usize, 1, 2, 3], + move |n| { + if let Some(gate) = hung.get(n) { + gate.wait(); + } + n + }, + move |n| l.lock().unwrap().push(n), + ); + // (which of the two is named first depends on which reader took its job first) + wait_until("a read to be named", || watch.stalled().is_some()); + let first: usize = watch.stalled().unwrap().what.trim_start_matches("job").parse().unwrap(); + let second = 1 - first; + watch.skip(); + wait_until("the other read to be named after it", || watch.stalled().is_some_and(|s| s.what == format!("job{second}"))); + assert_eq!(watch.skipped(), 1); + gates[second].open(); + let outcomes = join_within(reading); + assert!(is_skipped(&outcomes[first]), "{:?}", outcomes[first]); + assert!(matches!(outcomes[second], Outcome::Done(n) if n == second), "the other hung read was not skipped: {:?}", outcomes[second]); + assert!(matches!(outcomes[2], Outcome::Done(2)) && matches!(outcomes[3], Outcome::Done(3)), "a fresh reader goes on"); + assert_eq!((watch.skipped(), watch.ended()), (1, None)); + assert_eq!(stuck.alive(), 1, "the given-up read is still blocked, and counted"); + assert!(late.lock().unwrap().is_empty()); + gates[first].open(); + wait_until("the given-up read to exit", || stuck.alive() == 0); +} + +/// Given a given-up read that answers after all, +/// Then its result goes to the late handler (which disposes of it: nothing is applied), and the job stays failed. +#[test] +fn a_late_answer_from_a_given_up_read_goes_to_the_late_handler() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let late = Arc::new(Mutex::new(Vec::new())); + let l = late.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![7u32, 8], + move |n| { + if n == 7 { + g.wait(); + } + n + }, + move |n| l.lock().unwrap().push(n), + ); + wait_until("job0 to be named", || watch.stalled().is_some()); + watch.skip(); + let outcomes = join_within(run); + assert!(is_skipped(&outcomes[0]) && matches!(outcomes[1], Outcome::Done(8)), "{outcomes:?}"); + gate.open(); + wait_until("the late answer", || !late.lock().unwrap().is_empty()); + assert_eq!(*late.lock().unwrap(), vec![7]); + assert!(is_skipped(&outcomes[0]), "the job stays failed"); + wait_until("the given-up read to exit", || stuck.alive() == 0); +} + +/// A Skip asked for when nothing has stalled, or for a read that answered meanwhile, gives up nothing. +#[test] +fn a_skip_with_nothing_stalled_does_nothing() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + |n| { + std::thread::sleep(Duration::from_millis(150)); + n + }, + |_| {}, + ); + watch.skip(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); + assert_eq!((watch.skipped(), watch.ended(), stuck.alive()), (0, None, 0)); + // and a request made before the next stall is not kept for it + let gate = Gate::default(); + let g = gate.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + watch.skip(); + wait_until("the read to be named", || watch.stalled().is_some()); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(watch.skipped(), 0, "a Skip made while nothing was named is not kept"); + gate.open(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); +} + +/// Given a drive whose reads all hang, +/// When each stalled read is skipped as it is named, +/// Then the fourth skip ends the run with an error naming the last file, instead of leaving more threads blocked. +#[test] +fn the_fourth_skipped_read_ends_the_run() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let started = Arc::new(AtomicUsize::new(0)); + let s = started.clone(); + let run = run_in_background( + &watch, + &cancel, + 2, + (0..12u32).collect(), + move |n| { + s.fetch_add(1, Relaxed); + g.wait(); + n + }, + |_| {}, + ); + // (Skip is asked for only once every reader is on a read: the two first ones, then the replacement each Skip + // started, so that how many readers are left behind at the end does not depend on how quickly a thread starts) + wait_until("the run to end", || { + if watch.stalled().is_some() && started.load(Relaxed) == watch.skipped() + 2 { + watch.skip(); + } + run.is_finished() + }); + let outcomes = join_within(run); + assert_eq!(MAX_SKIPPED, 4); + assert_eq!(watch.skipped(), MAX_SKIPPED); + let why = watch.ended().expect("the run ended with an error"); + assert!(why.contains("not answering") && why.contains("job"), "{why}"); + assert_eq!(outcomes.iter().filter(|o| is_skipped(o)).count(), MAX_SKIPPED); + assert!(outcomes.iter().all(|o| is_skipped(o) || matches!(o, Outcome::Unreached)), "{outcomes:?}"); + // (the four given up, and the one reader still on a read when the run ended: it is left behind too, and no fifth + // reader was started) + assert_eq!(stuck.alive(), MAX_SKIPPED + 1); + gate.open(); + wait_until("the given-up reads to exit", || stuck.alive() == 0); +} + +/// Given too many given-up reads still blocked (of any run, on any drive), +/// Then a run does not start (and says why), and does once the reads let go. +#[test] +fn a_run_does_not_start_while_too_many_given_up_reads_are_blocked() { + let (stuck, cancel) = (Arc::new(StuckReaders::new(1)), Arc::new(AtomicBool::new(false))); + let first = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let reading = run_in_background( + &first, + &cancel, + 1, + vec![0u32, 1], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + wait_until("the read to be named", || first.stalled().is_some()); + first.skip(); + let outcomes = join_within(reading); + assert!(is_skipped(&outcomes[0]) && matches!(outcomes[1], Outcome::Unreached), "{outcomes:?}"); + let why = first.ended().expect("the cap ended the run"); + assert!(why.contains("still waiting"), "{why}"); + // another run, another watch, the same count + let second = watch(&stuck); + let started = Arc::new(AtomicUsize::new(0)); + let s = started.clone(); + let outcomes = run( + &second, + &cancel, + 2, + vec![1u32, 2], + move |n| { + s.fetch_add(1, Relaxed); + n + }, + |_| {}, + ); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Unreached)), "{outcomes:?}"); + assert_eq!(started.load(Relaxed), 0, "nothing was started"); + assert!(second.ended().is_some_and(|why| why.contains("still waiting"))); + gate.open(); + wait_until("the given-up read to exit", || stuck.alive() == 0); + let third = watch(&stuck); + let outcomes = run(&third, &cancel, 2, vec![1u32, 2], |n| n, |_| {}); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Done(_))), "{outcomes:?}"); +} + +/// Given an `init` that panics on every reader, +/// Then the jobs are still read: a reader that could not be set up is not left waiting for a job it never takes. +#[test] +fn a_panicking_init_does_not_strand_the_jobs() { + let stuck = stuck(); + let watch = watch(&stuck); + let pool_watch = watch.clone(); + let reading = std::thread::spawn(move || { + let cancel = AtomicBool::new(false); + let pool = Pool { watch: &pool_watch, cancel: &cancel, name: "test-read", threads: 2 }; + pool.run( + vec![1u32, 2, 3], + &|i| format!("job{i}"), + Arc::new(|n| n), + Arc::new(|_| {}), + Arc::new(|| panic!("a reader that cannot be set up")), + &|_| {}, + ) + }); + let outcomes = join_within(reading); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Done(_))), "{outcomes:?}"); +} + +/// `progressed` and the abandon flag belong to the pool's threads: elsewhere they do nothing. +#[test] +fn progress_and_the_abandon_flag_belong_to_the_pool_threads() { + progressed(); + assert!(abandon_flag().is_none()); + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let outcomes = run(&watch, &cancel, 1, vec![()], |()| abandon_flag().map(|f| f.load(Relaxed)), |_| {}); + assert!(matches!(outcomes[0], Outcome::Done(Some(false))), "{outcomes:?}"); +} + +#[test] +fn a_watch_calls_a_read_stalled_after_the_time_it_is_given() { + let watch = ReadWatch::default(); + assert_eq!(watch.stall_after(), super::STALL_AFTER); + watch.set_stall_after(Duration::from_secs(3)); + assert_eq!(watch.stall_after(), Duration::from_secs(3)); + assert_eq!((watch.stalled(), watch.skipped(), watch.ended()), (None, 0, None)); +} From 04707a0eb1ee1eed8a18308745395aae3e977002 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 17:39:04 -0400 Subject: [PATCH 071/247] LR-BEHAV-MULTISELECT: several sidebar albums, keywords or folders are deleted, moved or labeled as one undo step (engine) album.delete and album.move take `ids`, keyword.delete and keyword.move take `keywords`, library.removeFolder and folder.label take `paths`. Each checks everything before it changes anything, is one step to undo, and names what it refuses. Engine only: no UI calls it yet. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/keywords.rs | 87 +++++++ crates/engine/src/cmd/keywords.rs | 62 ++++- crates/engine/src/cmd/library/specs.rs | 264 ++++++++++++++++---- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/batch_sidebar.rs | 301 +++++++++++++++++++++++ docs/parity-checklist.md | 5 +- 6 files changed, 660 insertions(+), 60 deletions(-) create mode 100644 crates/engine/src/tests/batch_sidebar.rs diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index d36ab11cd6..9851666bc7 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -442,6 +442,93 @@ impl Catalog { Ok(Op::Batch { ops }) } + /// [`Self::delete_keyword_ops`] for several keywords at once: one batch, so one undo step. + /// Unlike one keyword (which may be absent and then changes nothing), every keyword named must + /// exist, or the whole batch is refused. + pub fn delete_keywords_ops(&self, keywords: &[String]) -> Result { + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + if gone.is_empty() || gone.iter().any(String::is_empty) { + return Err(CatalogError::Invalid("empty keyword".into())); + } + // case folded once here, and each candidate once below, not once per pair + let folded: Vec = gone.iter().map(|g| g.to_lowercase()).collect(); + let under = |k: &str, p: &str| k == p || k.strip_prefix(p).is_some_and(|rest| rest.starts_with(SEP)); + let mut found = vec![false; folded.len()]; + let listed = self.keyword_list.values().map(|l| &l.path); + for k in listed.chain(self.photos().filter(|p| p.in_library()).flat_map(|p| p.meta.keywords.iter())) { + let k = k.to_lowercase(); + for (hit, p) in found.iter_mut().zip(&folded) { + *hit |= under(&k, p); + } + } + if let Some(i) = found.iter().position(|hit| !hit) { + return Err(CatalogError::Invalid(format!("no keyword “{}”", gone[i]))); + } + let goes = |k: &str| { + let k = k.to_lowercase(); + folded.iter().any(|p| under(&k, p)) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().filter(|x| !goes(x)).cloned().collect()); + ops.extend(self.list_ops(|list| list.retain(|_, l| !goes(&l.path)))); + Ok(Op::Batch { ops }) + } + + /// Move several keywords (each with the keywords below it) inside `parent`, or to the top + /// level (`None`), as one batch. Each keeps its name. Of a keyword and one below it only the + /// upper one moves (the lower goes with it). Nothing merges here: a name that is taken where + /// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole + /// move. Returns the batch and each move as `(from, to)`. + pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> { + let mut from: Vec = Vec::new(); + for k in keywords { + let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?; + if !from.iter().any(|f| same(f, &path)) { + from.push(path); + } + } + if from.is_empty() { + return Err(CatalogError::Invalid("no keyword to move".into())); + } + // the upper ones only + let all = from.clone(); + from.retain(|f| !all.iter().any(|o| !same(o, f) && is_under(f, o))); + let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p)); + if let Some(p) = &parent + && from.iter().any(|f| is_under(p, f)) + { + return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + } + let mut moves: Vec<(String, String)> = Vec::new(); + for f in &from { + let leaf = f.rsplit(SEP).next().unwrap_or(f); + let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}")); + if moves.iter().any(|(_, t)| same(t, &to)) { + return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time"))); + } + moves.push((f.clone(), to)); + } + // one that is there already stays; the others must find their name free + moves.retain(|(f, t)| !same(f, t)); + if let Some((_, taken)) = moves.iter().find(|(_, t)| self.has_keyword(t)) { + return Err(CatalogError::KeywordExists(taken.clone())); + } + // case folded once here and once per photo keyword, not once per pair + let folded_from: Vec = moves.iter().map(|(f, _)| f.to_lowercase()).collect(); + let moved = |k: &str| { + let k_folded = k.to_lowercase(); + moves.iter().zip(&folded_from).find_map(|((f, t), f_folded)| { + let under = k_folded == *f_folded || k_folded.strip_prefix(f_folded.as_str()).is_some_and(|rest| rest.starts_with(SEP)); + under.then(|| reparent(k, f, t)) + }) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().map(|k| moved(k).unwrap_or_else(|| k.clone())).collect()); + // (the moves touch apart parts of the list: each one's listings are its own) + for (f, t) in &moves { + ops.extend(self.list_move_ops(std::slice::from_ref(f), t)); + } + Ok((Op::Batch { ops }, moves)) + } + /// Merge several keywords (with their children) into `into`. pub fn merge_keywords_ops(&self, from: &[String], into: &str) -> Result { let into = clean(into); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 0e612227f1..429f7b0a02 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -66,6 +66,39 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo { } } +/// `keyword.move`'s `parent`: a keyword, or null for the top level. +fn move_parent(p: &Value) -> Result> { + match p.get("parent") { + Some(Value::String(k)) => Ok(Some(k.clone())), + Some(Value::Null) => Ok(None), + _ => Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), + } +} + +/// How many keywords one call may name (far more than a person chooses in a list). +const MAX_KEYWORDS: usize = 10_000; + +/// The keywords a command names in `keywords`: a list of them, each once (whatever its case), +/// none empty. +fn keyword_list(p: &Value, command: &str) -> Result> { + let list = p.get("keywords").and_then(Value::as_array).ok_or_else(|| bad(command, "`keywords` must be a list of keywords"))?; + if list.len() > MAX_KEYWORDS { + return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords"))); + } + let mut out: Vec = Vec::new(); + for k in list { + let k = + k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?; + if !out.iter().any(|o| lightcraft_catalog::keywords::same(o, &k)) { + out.push(k); + } + } + if out.is_empty() { + return Err(bad(command, "`keywords` names no keyword")); + } + Ok(out) +} + /// The keyword a command names (`keyword`), as the library writes it. fn named_keyword(s: &Session, p: &Value, command: &str) -> Result { let k = str_param(p, "keyword").ok_or_else(|| bad(command, "missing `keyword`"))?; @@ -488,15 +521,23 @@ pub fn specs() -> Vec { "Move Keyword", [], None, - "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`", + "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`. Several at once: {keywords: [keyword], parent} as one undo step (of a keyword and one below it the upper one moves); nothing merges then: a name that is taken, or two of them with one name, refuses the whole move", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let parent = move_parent(p)?; + let keywords = keyword_list(p, "keyword.move")?; + let (op, moves) = s + .catalog + .move_keywords_ops(&keywords, parent.as_deref()) + .map_err(|e| refused("keyword.move", e, ": moving would merge the two (move that one by itself, with merge: true)"))?; + let label = if moves.len() == 1 { "Move Keyword".to_string() } else { format!("Move {} Keywords", moves.len()) }; + return commit_keywords(s, &label, op, |k| { + Some(moves.iter().find(|(f, _)| is_under(k, f)).map_or_else(|| k.to_string(), |(f, t)| reparent(k, f, t))) + }); + } let from = named_keyword(s, p, "keyword.move")?; - let parent = match p.get("parent") { - Some(Value::String(k)) => Some(k.clone()), - Some(Value::Null) => None, - _ => return Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), - }; + let parent = move_parent(p)?; // where it lands, as the catalog spells it: a parent that doesn't exist yet is made let leaf = from.rsplit('|').next().unwrap_or(&from).to_string(); let to = match parent.as_deref().map(|k| s.catalog.keyword_path(k).unwrap_or_else(|| clean(k))).filter(|k| !k.is_empty()) { @@ -612,9 +653,16 @@ pub fn specs() -> Vec { "Delete Keyword", [], None, - "{keyword} — removes it (and the keywords below it) from every photo", + "{keyword} — removes it (and the keywords below it) from every photo. Several at once: {keywords: [keyword]}, as one undo step", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let keywords = keyword_list(p, "keyword.delete")?; + let op = s.catalog.delete_keywords_ops(&keywords).map_err(|e| bad("keyword.delete", e.to_string()))?; + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + let label = if gone.len() == 1 { "Delete Keyword".to_string() } else { format!("Delete {} Keywords", gone.len()) }; + return commit_keywords(s, &label, op, |f| (!gone.iter().any(|g| is_under(f, g))).then(|| f.to_string())); + } let k = str_param(p, "keyword").ok_or_else(|| bad("keyword.delete", "missing `keyword`"))?.to_string(); let op = s.catalog.delete_keyword_ops(&k).map_err(|e| bad("keyword.delete", e.to_string()))?; let c = clean(&k); diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index a2a842106a..c73325b7cc 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -6,8 +6,8 @@ use super::selection::{ opt_album_param, rotate, row_step, select_after_deletion, select_by, step, strs, }; use super::{ - Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey, - Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, + Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Session, Sort, + SortKey, Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, }; /// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote. @@ -29,6 +29,91 @@ fn next_seed(prev: u64, now: &str) -> u64 { (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1) } +/// `album.move` for several albums and folders (`ids`) at once: everything is checked first, then +/// they move as one undo step. +fn move_albums(s: &mut Session, p: &Value) -> Result { + const C: &str = "album.move"; + let ids = album_ids(p.get("ids").unwrap_or(&Value::Null), C)?; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, format!("no such album {}", gone.0))); + } + let parent = opt_album_param(p, "parent", C)?; + if let Some(folder) = parent + && !s.catalog.album(folder).is_some_and(|a| a.folder) + { + return Err(bad(C, format!("album {} is not a folder of albums", folder.0))); + } + // where `parent` sits: itself and the folders above it (a ring, in a damaged library, ends the walk) + let mut above: Vec = Vec::new(); + let mut cur = parent; + while let Some(c) = cur.filter(|c| !above.contains(c)) { + above.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + // of a folder and what is inside it, the folder moves + let inside_another = |id: AlbumId| { + let mut seen: Vec = Vec::new(); + let mut cur = s.catalog.album(id).and_then(|a| a.parent); + while let Some(c) = cur.filter(|c| !seen.contains(c)) { + if ids.contains(&c) { + return true; + } + seen.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + false + }; + let moving: Vec = ids.iter().copied().filter(|id| !inside_another(*id)).collect(); + for id in &moving { + let name = s.catalog.album(*id).map(|a| a.name.clone()).unwrap_or_default(); + if above.contains(id) { + return Err(bad(C, format!("“{name}” can't go inside itself"))); + } + } + let ops: Vec = moving.iter().map(|id| Op::MoveAlbum { id: *id, parent }).collect(); + let label = if moving.len() == 1 { "Move Album".to_string() } else { format!("Move {} Albums", moving.len()) }; + s.commit(&label, Op::Batch { ops })?; + Ok(json!({"moved": moving.len()})) +} + +/// How many albums or folders one call may name: far more than a person +/// chooses in a sidebar, and a bound on what one call can make the engine check. +pub(crate) const MAX_SOURCES: usize = 1000; + +/// A command's `ids`: album ids, each once (named twice, the last naming counts). +fn album_ids(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`ids` must be a list of album ids"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`ids` names more than {MAX_SOURCES} albums"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let id = AlbumId(x.as_u64().ok_or_else(|| bad(c, format!("`ids` must be a list of album ids, not {x}")))?); + out.retain(|o| *o != id); + out.push(id); + } + Ok(out) +} + +/// A command's `paths`: folder paths, each folder once (named twice, the last counts). +fn folder_paths(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`paths` must be a list of folder paths"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`paths` names more than {MAX_SOURCES} folders"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let path = x.as_str().ok_or_else(|| bad(c, format!("`paths` must be a list of folder paths, not {x}")))?; + let key = lightcraft_catalog::query::folder_key(path); + out.retain(|o| lightcraft_catalog::query::folder_key(o) != key); + out.push(path.to_string()); + } + Ok(out) +} + pub fn specs() -> Vec { vec![ // ---- view source / filter / sort @@ -128,35 +213,52 @@ pub fn specs() -> Vec { "Remove Folder from Library", [], None, - "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}", + "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}. Several at once: {paths: [path]}, still one undo step; one that can't be removed refuses the whole call", always, |s, p| { const C: &str = "library.removeFolder"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; - if lightcraft_catalog::query::folder_key(path).is_empty() { - return Err(bad(C, format!("{path}: not a folder"))); + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); } - if lightcraft_catalog::folders::is_startup_disk(path) { - return Err(bad(C, "choose a folder, not the whole startup disk")); + // every folder is checked before a photo leaves; a photo in two of them leaves once + let mut ids: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for path in &paths { + let path = path.as_str(); + if path.trim().is_empty() || lightcraft_catalog::query::folder_key(path).is_empty() { + return Err(bad(C, format!("{path}: not a folder"))); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(bad(C, "choose a folder, not the whole startup disk")); + } + if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); + } + let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + let found = s.catalog.query(&f, &Sort::default()); + if found.is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if covers_other_disks(s, path, &found) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); + } + ids.extend(found.into_iter().filter(|id| seen.insert(*id))); } - if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); - } - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - let ids = s.catalog.query(&f, &Sort::default()); - if ids.is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); - } - if covers_other_disks(s, path, &ids) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); - } - mark_deleted(s, &ids, "Remove Folder from Library")?; - if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + let label = + if paths.len() == 1 { "Remove Folder from Library".to_string() } else { format!("Remove {} Folders from Library", paths.len()) }; + mark_deleted(s, &ids, &label)?; + let within = |c: &str| paths.iter().any(|path| lightcraft_catalog::query::folder_within(c, path)); + if s.filter.library_folder.as_deref().is_some_and(within) { s.filter.library_folder = None; } // a filter put aside by Enable Filters must not bring the removed folder back if let Some(f) = s.shelved_filter.as_mut() - && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) + && f.library_folder.as_deref().is_some_and(within) { f.library_folder = None; } @@ -164,7 +266,7 @@ pub fn specs() -> Vec { s.shelved_filter = None; } // the folder being shown is gone: back to everything, as for a deleted album - if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + if s.library_folder.as_deref().is_some_and(within) { s.library_folder = None; if s.source == LibrarySource::LibraryFolder { s.source = LibrarySource::All; @@ -180,26 +282,46 @@ pub fn specs() -> Vec { "Set Folder Color Label", [], None, - "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}", + "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}. Several at once: {paths: [path], label}, as one undo step", always, |s, p| { const C: &str = "folder.label"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); + } let label = match str_param(p, "label").ok_or_else(|| bad(C, "missing `label` (red|yellow|green|blue|purple|none)"))? { "none" => None, x => Some(ColorLabel::parse(x).ok_or_else(|| bad(C, format!("unknown label {x:?}")))?), }; - // taking a label off always works, also once the folder's photos are gone - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + let mut ops = Vec::new(); + for path in &paths { + if path.trim().is_empty() { + return Err(bad(C, "missing `path`")); + } + // taking a label off always works, also once the folder's photos are gone + let f = Filter { library_folder: Some(path.clone()), ..Default::default() }; + if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if label.is_some() || s.catalog.folder_record(path).is_some() { + ops.push(s.catalog.folder_label_op(path, label)); + } } - if label.is_none() && s.catalog.folder_record(path).is_none() { - return Ok(json!({"path": path, "label": label})); + let name = if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }; + match (ops.len(), ops.pop()) { + (0, _) | (_, None) => {} + (1, Some(op)) => s.commit(name, op)?, + (_, Some(last)) => { + ops.push(last); + s.commit(name, Op::Batch { ops })? + } } - let op = s.catalog.folder_label_op(path, label); - s.commit(if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }, op)?; - Ok(json!({"path": path, "label": label})) + if several { Ok(json!({"paths": paths, "label": label})) } else { Ok(json!({"path": paths.first(), "label": label})) } } ), cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| { @@ -926,11 +1048,22 @@ pub fn specs() -> Vec { "Delete Album", [], None, - "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step", + "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step. Several at once: {ids: [albumId]} → {deleted}, still one undo step; one that does not exist refuses the whole call", always, |s, p| { - let id = album_param(p, "id", "album.delete")?; - let folder = s.catalog.album(id).ok_or_else(|| bad("album.delete", "no such album"))?.folder; + const C: &str = "album.delete"; + let several = p.get("ids").is_some_and(|v| !v.is_null()); + let ids = match p.get("ids") { + Some(v) if several => album_ids(v, C)?, + _ => vec![album_param(p, "id", C)?], + }; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, if several { format!("no such album {}", gone.0) } else { "no such album".into() })); + } + let folder = ids.first().and_then(|id| s.catalog.album(*id)).is_some_and(|a| a.folder); let mut children = std::collections::BTreeMap::>::new(); for album in s.catalog.albums() { if let Some(parent) = album.parent { @@ -940,32 +1073,61 @@ pub fn specs() -> Vec { // Iterative traversal: even a malformed cycle is rejected before any change. // Reverse parent-first order removes children first; the batch inverse restores // parents first, including memberships, smart rules, covers and manual ordering. - let mut pending = vec![id]; let mut order = Vec::new(); let mut removed = std::collections::BTreeSet::new(); - while let Some(next) = pending.pop() { - if !removed.insert(next) { - return Err(bad("album.delete", "cycle in album folders")); + for id in &ids { + // inside one named before it: it goes with that one + if removed.contains(id) { + continue; } - order.push(next); - if let Some(nested) = children.remove(&next) { - pending.extend(nested); + let mut pending = vec![*id]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(next) = pending.pop() { + if !seen.insert(next) { + return Err(bad(C, "cycle in album folders")); + } + // one named before, now found inside this one: it is listed once, here + if removed.insert(next) { + order.push(next); + } else if let Some(at) = order.iter().position(|o| *o == next) { + let moved = order.remove(at); + order.push(moved); + } + if let Some(nested) = children.get(&next) { + pending.extend(nested.iter().copied()); + } } } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); - s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; + let label = match (ids.len(), folder) { + (1, true) => "Delete Folder".to_string(), + (1, false) => "Delete Album".to_string(), + (n, _) => format!("Delete {n} Albums"), + }; + s.commit(&label, Op::Batch { ops })?; if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { s.source = LibrarySource::All; } + if several { Ok(json!({"deleted": ids.len()})) } else { ok() } + } + ), + cmd!( + "album.move", + "Move Album", + [], + None, + "{id, parent?: folderId|null} — into a folder, or to the top level. Several at once: {ids: [albumId], parent} as one undo step (of a folder and an album inside it the folder moves); one that can't go there refuses the whole call", + always, + |s, p| { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return move_albums(s, p); + } + let id = album_param(p, "id", "album.move")?; + let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); + s.commit("Move Album", Op::MoveAlbum { id, parent })?; ok() } ), - cmd!("album.move", "Move Album", [], None, "{id, parent?: folderId|null}", always, |s, p| { - let id = album_param(p, "id", "album.move")?; - let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); - s.commit("Move Album", Op::MoveAlbum { id, parent })?; - ok() - }), cmd!( "album.reorder", "Reorder Album", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 37b300dbfc..fff26dc4d3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,6 +7,7 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +mod batch_sidebar; mod color; mod constrain_crop; mod crop_angle; diff --git a/crates/engine/src/tests/batch_sidebar.rs b/crates/engine/src/tests/batch_sidebar.rs new file mode 100644 index 0000000000..1568ae58e7 --- /dev/null +++ b/crates/engine/src/tests/batch_sidebar.rs @@ -0,0 +1,301 @@ +//! Acting on several sidebar rows at once: the commands a context menu runs when several albums, +//! folders or keywords are chosen. Each is one step to undo, checks everything before it changes +//! anything, and a refusal names what it refused. +//! +//! Scenarios: +//! - Given three albums, when two are deleted at once (`album.delete {ids}`), then both are gone, +//! the third stays, and one undo brings both back. +//! - Given a folder of albums and an album inside it both named, then deleting them deletes the +//! folder with what is in it, once. +//! - An album that does not exist among those to delete is refused by name, and nothing is deleted. +//! - Given two albums, when both are moved into a folder (`album.move {ids, parent}`), then both +//! are inside it, and one undo puts both back; a folder is not moved into itself, and then +//! nothing moves. +//! - Given keywords on photos, when several are deleted at once (`keyword.delete {keywords}`), +//! then every photo loses them and one undo gives them back; one that is no keyword refuses the +//! whole call and nothing is deleted (one keyword that is no keyword still changes nothing). +//! - Given several keywords, when they are moved inside another (`keyword.move {keywords, +//! parent}`), then each is nested there with its photos, as one undo step; a name that is taken +//! there, or two of them with one name, is refused and nothing moves. +//! - Given two folders of the library, when both are removed at once (`library.removeFolder +//! {paths}`), then their photos go to Recently Deleted as one undo step; one that is not a +//! folder of the library refuses the whole call. +//! - Given two folders, when both get a colour label at once (`folder.label {paths}`), then both +//! show it, and one undo takes both off. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::Session; + +fn photos(s: &mut Session, n: u64) -> Vec { + (1..=n) + .map(|day| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }) + .collect() +} + +fn album(s: &mut Session, params: serde_json::Value) -> u64 { + s.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap() +} + +fn has_album(s: &Session, id: u64) -> bool { + s.catalog.album(AlbumId(id)).is_some() +} + +fn parent_of(s: &Session, id: u64) -> Option { + s.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0) +} + +fn tag(s: &mut Session, id: u64, keywords: &[&str]) { + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = vec![PhotoId(id)]; + s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": keywords})).unwrap(); + s.selection.ids.clear(); +} + +fn keywords_of(s: &Session, id: u64) -> Vec { + let mut k = s.catalog.photo(PhotoId(id)).unwrap().meta.keywords.clone(); + k.sort(); + k +} + +fn undo(s: &mut Session) { + s.execute("edit.undo", &json!({})).unwrap(); +} + +#[test] +fn several_albums_are_deleted_as_one_step() { + let mut s = Session::new(); + let (a, b, c) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"})), album(&mut s, json!({"name": "C"}))); + let steps = s.undo.len(); + let r = s.execute("album.delete", &json!({"ids": [a, c]})).unwrap(); + assert_eq!(r["deleted"], 2); + assert_eq!((has_album(&s, a), has_album(&s, b), has_album(&s, c)), (false, true, false)); + assert_eq!(s.undo.len(), steps + 1, "one step"); + assert_eq!(s.undo.last().unwrap().label, "Delete 2 Albums"); + undo(&mut s); + assert!(has_album(&s, a) && has_album(&s, c)); +} + +#[test] +fn a_folder_and_an_album_inside_it_are_deleted_once() { + let mut s = Session::new(); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inside = album(&mut s, json!({"name": "Alps", "parent": folder})); + let other = album(&mut s, json!({"name": "Other"})); + s.execute("album.delete", &json!({"ids": [inside, folder, other]})).unwrap(); + assert!(!has_album(&s, folder) && !has_album(&s, inside) && !has_album(&s, other)); + undo(&mut s); + assert_eq!(parent_of(&s, inside), Some(folder), "back where it was"); + assert!(has_album(&s, other)); +} + +#[test] +fn deleting_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let steps = s.undo.len(); + let e = s.execute("album.delete", &json!({"ids": [a, 4242]})).unwrap_err().to_string(); + assert!(e.contains("4242"), "{e}"); + assert!(has_album(&s, a), "nothing was deleted"); + assert_eq!(s.undo.len(), steps); + for bad in [json!([]), json!("a"), json!([a, "b"])] { + assert!(s.execute("album.delete", &json!({"ids": bad})).is_err(), "{bad}"); + } + assert!(has_album(&s, a)); + // one alone, the way it always was + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert!(!has_album(&s, a)); + assert_eq!(s.undo.last().unwrap().label, "Delete Album"); +} + +#[test] +fn several_albums_move_into_a_folder_as_one_step() { + let mut s = Session::new(); + let (a, b) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"}))); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let steps = s.undo.len(); + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (Some(folder), Some(folder))); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Albums"); + undo(&mut s); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); + // back to the top level, both at once + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + s.execute("album.move", &json!({"ids": [a, b], "parent": null})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); +} + +#[test] +fn moving_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inner = album(&mut s, json!({"name": "Inner", "folder": true, "parent": folder})); + // a folder can't go inside itself or inside a folder it holds: then nothing moves + for parent in [folder, inner] { + let e = s.execute("album.move", &json!({"ids": [a, folder], "parent": parent})).unwrap_err().to_string(); + assert!(e.contains("Trips"), "the refusal names it: {e}"); + assert_eq!(parent_of(&s, a), None, "nothing moved"); + } + // into something that is not a folder, or not there + assert!(s.execute("album.move", &json!({"ids": [folder], "parent": a})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a], "parent": 4242})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a, 4242], "parent": folder})).is_err()); + assert_eq!(parent_of(&s, a), None); + // a folder and an album already inside it: the folder moves, and the album with it + let outer = album(&mut s, json!({"name": "Outer", "folder": true})); + let within = album(&mut s, json!({"name": "Within", "parent": inner})); + s.execute("album.move", &json!({"ids": [within, inner], "parent": outer})).unwrap(); + assert_eq!((parent_of(&s, inner), parent_of(&s, within)), (Some(outer), Some(inner))); +} + +#[test] +fn several_keywords_are_deleted_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach", "trips|italy"]); + tag(&mut s, ids[1], &["beach", "town"]); + let steps = s.undo.len(); + let r = s.execute("keyword.delete", &json!({"keywords": ["alps", "beach", "trips"]})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + assert_eq!(keywords_of(&s, ids[1]), vec!["town"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Delete 3 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach", "trips|italy"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); + // nothing named: refused, as is something that is no keyword + for bad in [json!([]), json!([""]), json!(7), json!(["alps", 7])] { + assert!(s.execute("keyword.delete", &json!({"keywords": bad})).is_err(), "{bad}"); + } + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); +} + +#[test] +fn deleting_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 1); + tag(&mut s, ids[0], &["alps", "trips|italy"]); + let steps = s.undo.len(); + let e = s.execute("keyword.delete", &json!({"keywords": ["alps", "nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("no keyword") && e.contains("nowhere"), "names the one that is missing: {e}"); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "trips|italy"]); + assert_eq!(s.undo.len(), steps); + // a keyword that is only the upper level of one, in another case, is there + s.execute("keyword.delete", &json!({"keywords": ["ALPS", "Trips"]})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + // one keyword that is not there is still a no-op, as before + let steps = s.undo.len(); + s.execute("keyword.delete", &json!({"keyword": "nowhere"})).unwrap(); + assert_eq!(s.undo.len(), steps); +} + +#[test] +fn several_keywords_move_inside_another_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach"]); + tag(&mut s, ids[1], &["beach", "places"]); + let steps = s.undo.len(); + let r = s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), vec!["places|alps", "places|beach"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["places", "places|beach"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); + // …and back out to the top level + s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + s.execute("keyword.move", &json!({"keywords": ["places|alps", "places|beach"], "parent": null})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); +} + +#[test] +fn moving_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "europe|alps", "beach", "asia|beach", "places"]); + let before = keywords_of(&s, ids[0]); + let steps = s.undo.len(); + // a name that is taken where they go: moving would merge the two, which is not done in a batch + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "alps"], "parent": "europe"})).unwrap_err().to_string(); + assert!(e.contains("europe|alps"), "names the one in the way: {e}"); + // two of them with one name + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "asia|beach"], "parent": "places"})).unwrap_err().to_string(); + assert!(e.to_lowercase().contains("beach"), "{e}"); + // inside one of themselves; one that is no keyword + assert!(s.execute("keyword.move", &json!({"keywords": ["places", "alps"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": ["alps", "nope"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": [], "parent": "places"})).is_err()); + assert_eq!(keywords_of(&s, ids[0]), before, "nothing moved"); + assert_eq!(s.undo.len(), steps); + // a keyword and one below it: the upper one moves, and the lower with it + s.execute("keyword.move", &json!({"keywords": ["europe|alps", "europe"], "parent": "places"})).unwrap(); + assert!(keywords_of(&s, ids[0]).contains(&"places|europe|alps".to_string())); +} + +fn add_file(s: &mut Session, path: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +fn deleted(s: &Session, id: u64) -> bool { + s.catalog.photo(PhotoId(id)).unwrap().deleted +} + +#[test] +fn several_folders_leave_the_library_as_one_step() { + let mut s = Session::new(); + let alps = add_file(&mut s, "/pics/2025/alps/a.jpg"); + let beach = add_file(&mut s, "/pics/2026/beach/c.jpg"); + let town = add_file(&mut s, "/pics/2026/town/d.jpg"); + let steps = s.undo.len(); + // refused as a whole when one is not a folder of the library + let e = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(!deleted(&s, alps)); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"]})).unwrap(); + assert_eq!(r["removed"], 2); + assert_eq!((deleted(&s, alps), deleted(&s, beach), deleted(&s, town)), (true, true, false)); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Remove 2 Folders from Library"); + undo(&mut s); + assert!(!deleted(&s, alps) && !deleted(&s, beach)); + // a folder and one inside it: each photo once + add_file(&mut s, "/pics/2025/alps/day1/b.jpg"); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps/day1", "/pics/2025/alps"]})).unwrap(); + assert_eq!(r["removed"], 2); +} + +#[test] +fn several_folders_get_a_colour_label_as_one_step() { + let mut s = Session::new(); + add_file(&mut s, "/pics/2025/alps/a.jpg"); + add_file(&mut s, "/pics/2026/beach/c.jpg"); + let label = |s: &Session, path: &str| s.catalog.folder_record(path).and_then(|r| r.label); + let steps = s.undo.len(); + let e = s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/nowhere"], "label": "red"})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(label(&s, "/pics/2025/alps").is_none(), "nothing was labelled"); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "red"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_some() && label(&s, "/pics/2026/beach").is_some()); + assert_eq!(s.undo.len(), steps + 1); + undo(&mut s); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); + // taking the labels off, both at once + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "blue"})).unwrap(); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "none"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 46aabad737..865c1e0099 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-MULTISELECT: several sidebar albums, keywords or folders are deleted, moved or labeled as one undo step in the engine, no sidebar caller yet; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -457,7 +457,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`) | `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1026,3 +1026,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); status unchanged (✅) | From 7488ac076cf0aa69b6fab06cf8b23f2222ede7d0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 12:40:07 -0400 Subject: [PATCH 072/247] LR-BEHAV-MULTISELECT: batch keyword checks fold each path once and use sets move_keywords_ops and the keyword list of keyword.delete / keyword.move compared every pair of paths, lower-casing both each time. Each path is now folded once and looked up in a set, with the upper levels of a path checked at each separator. Same keywords refused or moved, same errors. --- crates/catalog/src/keywords.rs | 30 ++++++++++++++++++++---------- crates/engine/src/cmd/keywords.rs | 3 ++- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index 9851666bc7..072c0bbc5b 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -10,7 +10,7 @@ //! photo has them, or given attributes ([`KeywordInfo`]: synonyms, export options, person). The //! tree is the keyword list together with the keywords photos carry. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use serde::{Deserialize, Serialize}; @@ -35,6 +35,12 @@ pub fn is_under(k: &str, parent: &str) -> bool { k == p || k.strip_prefix(&p).is_some_and(|rest| rest.starts_with(SEP)) } +/// The upper levels of a case folded keyword path, each as a prefix of it ending before a `|` +/// (`a|b|c` gives `a`, `a|b`), the way [`is_under`] sees them. +fn upper_levels(folded: &str) -> impl Iterator { + folded.match_indices(SEP).map(|(i, _)| &folded[..i]) +} + /// Replace the `from` prefix of `k` (which [`is_under`] `from`) with `to`. By levels, not bytes: /// `from` may be written in another case, which can change a letter's length (ẞ / ß). pub fn reparent(k: &str, from: &str, to: &str) -> String { @@ -479,30 +485,34 @@ impl Catalog { /// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole /// move. Returns the batch and each move as `(from, to)`. pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> { + // paths are case folded once and kept in sets: a batch of thousands stays linear let mut from: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); for k in keywords { let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?; - if !from.iter().any(|f| same(f, &path)) { + if seen.insert(path.to_lowercase()) { from.push(path); } } if from.is_empty() { return Err(CatalogError::Invalid("no keyword to move".into())); } - // the upper ones only - let all = from.clone(); - from.retain(|f| !all.iter().any(|o| !same(o, f) && is_under(f, o))); + // the upper ones only: a keyword goes when one of its upper levels is named too + from.retain(|f| !upper_levels(&f.to_lowercase()).any(|up| seen.contains(up))); + let upper: HashSet = from.iter().map(|f| f.to_lowercase()).collect(); let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p)); - if let Some(p) = &parent - && from.iter().any(|f| is_under(p, f)) - { - return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + if let Some(p) = &parent { + let p = p.to_lowercase(); + if upper.contains(&p) || upper_levels(&p).any(|up| upper.contains(up)) { + return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + } } let mut moves: Vec<(String, String)> = Vec::new(); + let mut names: HashSet = HashSet::new(); for f in &from { let leaf = f.rsplit(SEP).next().unwrap_or(f); let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}")); - if moves.iter().any(|(_, t)| same(t, &to)) { + if !names.insert(to.to_lowercase()) { return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time"))); } moves.push((f.clone(), to)); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 429f7b0a02..7f3f94b6be 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -86,10 +86,11 @@ fn keyword_list(p: &Value, command: &str) -> Result> { return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords"))); } let mut out: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); for k in list { let k = k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?; - if !out.iter().any(|o| lightcraft_catalog::keywords::same(o, &k)) { + if seen.insert(k.to_lowercase()) { out.push(k); } } From 5ab04d7ee1cb819a8981e5e1856c55901ef384cc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 12:42:24 -0400 Subject: [PATCH 073/247] LR-BEHAV-MULTISELECT: the parity row is partial until the sidebar calls the batch commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine commands exist but no sidebar row can choose several items yet, so the row is 🟡, not ✅ (usable end to end). Summary counts refreshed. --- docs/parity-checklist.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 865c1e0099..06f6b32ea9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -49,13 +49,13 @@ cited here still exists. Formerly docs/parity.md. | U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) | | V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) | | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | -| X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | +| X. Cross-cutting behaviours (BEHAV) | 22 | 7 | 1 | 1 | 7/8 (88%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 420 | 66 | 57 | 35 | 195/203 (96%) | 146/161 (91%) | +| **Total** | 419 | 67 | 57 | 35 | 194/203 (96%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.4%** of 543 in-scope rows — P0 98.0% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.3%** of 543 in-scope rows — P0 97.8% of 203 · P1 94.4% of 161 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -457,7 +457,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | 🟡 | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1026,4 +1026,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | -| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); status unchanged (✅) | +| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); downgraded ✅ → 🟡 until they exist | From 0c5a99402f8aac8289274b654904f2f40d12b2cc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 19 Oct 2026 19:14:12 -0400 Subject: [PATCH 074/247] LR-BEHAV-ACCESS: Reduce motion setting stops zoom and spinner animations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings ▸ Interface ▸ Reduce motion (also View ▸ Reduce Motion, `view.reduceMotion {on?}`), off by default and saved with the UI settings. With it on, a click on the photo or Z zooms at once, egui's widget easing time is 0, the Synchronize Folder spinner becomes a still dot and the activity panel's indeterminate bar stands still. Toast and slideshow fades stay. `motion.rs` is the one place animations ask; the setting reaches it through the egui context each frame (sync_theme), and theme changes keep the easing at 0. The OS preference is not read: that needs native calls, which only `crates/sysmem` may make. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs.json | 5 +- crates/ui-egui/locales/de.json | 5 +- crates/ui-egui/locales/es.json | 5 +- crates/ui-egui/locales/fr.json | 5 +- crates/ui-egui/locales/it.json | 5 +- crates/ui-egui/locales/ja.json | 5 +- crates/ui-egui/locales/ka.json | 5 +- crates/ui-egui/locales/pl.json | 5 +- crates/ui-egui/locales/pt-br.json | 5 +- crates/ui-egui/locales/ru.json | 5 +- crates/ui-egui/locales/uk.json | 5 +- crates/ui-egui/locales/zh-hans.json | 5 +- crates/ui-egui/locales/zh-hant.json | 5 +- crates/ui-egui/src/app/prefs.rs | 1 + .../ui-egui/src/dialogs/settings/display.rs | 3 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus/menubar.rs | 2 + crates/ui-egui/src/menus/run.rs | 5 + crates/ui-egui/src/menus/ui_commands.rs | 1 + crates/ui-egui/src/motion.rs | 56 ++++++++ crates/ui-egui/src/panels/activity.rs | 13 ++ crates/ui-egui/src/panels/detail/geometry.rs | 2 +- crates/ui-egui/src/state/settings.rs | 4 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/reduce_motion.rs | 124 ++++++++++++++++++ crates/ui-egui/src/theme.rs | 3 +- docs/control-protocol.md | 3 + docs/parity-checklist.md | 5 +- docs/whats-new.md | 8 +- 29 files changed, 279 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/src/motion.rs create mode 100644 crates/ui-egui/src/tests/reduce_motion.rs diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 6a056bbfb9..08d2ef0aa0 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2438,5 +2438,8 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "Reduce Motion": "Omezit pohyb", + "Reduce motion": "Omezit pohyb", + "Turns off zoom and spinner animations. Fades stay.": "Vypne animace přiblížení a načítacích indikátorů. Prolínání zůstává." } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 405c54a464..d2625c0db3 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3470,5 +3470,8 @@ "Top bar": "Obere Leiste", "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "Reduce Motion": "Bewegung reduzieren", + "Reduce motion": "Bewegung reduzieren", + "Turns off zoom and spinner animations. Fades stay.": "Schaltet Zoom- und Ladeanimationen ab. Überblendungen bleiben erhalten." } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index e43ae8c49b..73191b3065 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2390,5 +2390,8 @@ "Top bar": "Barra superior", "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "Reduce Motion": "Reducir movimiento", + "Reduce motion": "Reducir movimiento", + "Turns off zoom and spinner animations. Fades stay.": "Desactiva las animaciones del zoom y de los indicadores de actividad. Los fundidos se mantienen." } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e032cf52f3..ad3735d013 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3573,5 +3573,8 @@ "Top bar": "Barre supérieure", "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "Reduce Motion": "Réduire les animations", + "Reduce motion": "Réduire les animations", + "Turns off zoom and spinner animations. Fades stay.": "Désactive les animations du zoom et des indicateurs d’activité. Les fondus restent." } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a0d39d0610..05dad346a4 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2556,5 +2556,8 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "Reduce Motion": "Riduci movimento", + "Reduce motion": "Riduci movimento", + "Turns off zoom and spinner animations. Fades stay.": "Disattiva le animazioni dello zoom e degli indicatori di attività. Le dissolvenze restano." } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5f80d7896b..7304d0ba9a 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2388,5 +2388,8 @@ "Top bar": "上部バー", "Tool strip": "ツールバー", "Bottom bar": "下部バー", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "Reduce Motion": "動きを減らす", + "Reduce motion": "動きを減らす", + "Turns off zoom and spinner animations. Fades stay.": "ズームとスピナーのアニメーションをオフにします。フェードはそのまま残ります。" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 0ea7d3d805..155dc38a89 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3659,5 +3659,8 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "Reduce Motion": "მოძრაობის შემცირება", + "Reduce motion": "მოძრაობის შემცირება", + "Turns off zoom and spinner animations. Fades stay.": "გამორთავს მასშტაბირებისა და მიმდინარეობის ინდიკატორის ანიმაციებს. გაბუნდოვნება შენარჩუნდება." } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index bb3729a5b6..f11302c149 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2315,5 +2315,8 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "Reduce Motion": "Ogranicz ruch", + "Reduce motion": "Ogranicz ruch", + "Turns off zoom and spinner animations. Fades stay.": "Wyłącza animacje powiększania i wskaźników pracy. Zanikanie i przenikanie zostają." } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index a0884dc56a..e3904fbb99 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2234,5 +2234,8 @@ "Top bar": "Barra superior", "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "Reduce Motion": "Reduzir movimento", + "Reduce motion": "Reduzir movimento", + "Turns off zoom and spinner animations. Fades stay.": "Desativa as animações de zoom e dos indicadores de atividade. As transições de opacidade continuam." } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 598893c3bc..b6b7f59f40 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2596,5 +2596,8 @@ "Top bar": "Верхняя панель", "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "Reduce Motion": "Уменьшить движение", + "Reduce motion": "Уменьшить движение", + "Turns off zoom and spinner animations. Fades stay.": "Отключает анимацию масштабирования и индикаторов работы. Плавные затухания остаются." } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index a4efe34a60..838ee566af 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2386,5 +2386,8 @@ "Top bar": "Верхня панель", "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "Reduce Motion": "Зменшити рух", + "Reduce motion": "Зменшити рух", + "Turns off zoom and spinner animations. Fades stay.": "Вимикає анімацію масштабування та індикаторів роботи. Плавні згасання залишаються." } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ea867f35e6..c851427130 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2389,5 +2389,8 @@ "Set up name suggestions…": "设置姓名建议…", "Top bar": "顶部栏", "Tool strip": "工具栏", - "Bottom bar": "底部栏" + "Bottom bar": "底部栏", + "Reduce Motion": "减少动态效果", + "Reduce motion": "减少动态效果", + "Turns off zoom and spinner animations. Fades stay.": "关闭缩放和旋转指示器的动画。淡入淡出效果保留。" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 90b3670ec3..664f93a85c 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2389,5 +2389,8 @@ "Top bar": "頂部列", "Tool strip": "工具列", "Bottom bar": "底部列", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "Reduce Motion": "減少動態效果", + "Reduce motion": "減少動態效果", + "Turns off zoom and spinner animations. Fades stay.": "關閉縮放與旋轉指示器的動畫。淡入淡出效果保留。" } diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 9a5c612f12..1e63fc9a06 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -9,6 +9,7 @@ impl LightcraftApp { /// Restyle `ctx` when the theme the settings select (Appearance Mode, the dark and light /// themes, the system's appearance in Auto) is not the one it shows. A no-op otherwise. pub fn sync_theme(&mut self, ctx: &egui::Context) { + motion::sync(ctx, self.ui.settings.reduce_motion); let wanted = self.ui.settings.theme(self.system_theme(ctx)); if theme::current(ctx) != Some(wanted) { theme::apply_kind(ctx, wanted); diff --git a/crates/ui-egui/src/dialogs/settings/display.rs b/crates/ui-egui/src/dialogs/settings/display.rs index a5b1974d21..573f75c213 100644 --- a/crates/ui-egui/src/dialogs/settings/display.rs +++ b/crates/ui-egui/src/dialogs/settings/display.rs @@ -78,6 +78,9 @@ pub(super) fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let system = app.system_theme(ui.ctx()); appearance(ui, t, &mut app.ui.settings, system); + let r = ui.checkbox(&mut app.ui.settings.reduce_motion, crate::i18n::tr("Reduce motion")); + register(ui, "check:settings.reduceMotion".to_string(), r.rect); + r.on_hover_text(crate::i18n::tr("Turns off zoom and spinner animations. Fades stay.")); heading(ui, t, crate::i18n::tr("Filmstrip")); check(ui, "settings.filmNames", &mut app.ui.settings.film_names, "Show file names"); check(ui, "settings.filmBadges", &mut app.ui.settings.film_badges, "Show ratings, flags and edit badges"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7a67d87109..5075265e93 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -34,6 +34,7 @@ pub mod links; pub mod menus; mod missing_sweep; mod model_setup; +pub mod motion; pub mod panels; pub mod pick; pub mod recheck; diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 672c7cbccc..45854bce66 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -200,6 +200,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "view.faceBoxes", "view.focusPoint", "view.zoomToFocus", + "view.reduceMotion", "view.filmstrip", "view.histogram", "view.navigator", @@ -408,6 +409,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "view.faceBoxes" => Some(u.face_boxes), "view.focusPoint" => Some(u.settings.focus_point), "view.zoomToFocus" => Some(u.settings.zoom_to_focus), + "view.reduceMotion" => Some(u.settings.reduce_motion), "view.filmstrip" => Some(u.filmstrip), "view.frameRate" => Some(u.frame_rate), "view.histogram" => Some(u.histogram), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f..75aac5aa36 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -348,6 +348,11 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val app.ui.settings.zoom_to_focus = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.settings.zoom_to_focus); Ok(json!({"on": app.ui.settings.zoom_to_focus})) } + "view.reduceMotion" => { + // {on?}; no params toggles. Zoom and spinner animations stop; fades stay. + app.ui.settings.reduce_motion = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.settings.reduce_motion); + Ok(json!({"on": app.ui.settings.reduce_motion})) + } "view.faceBoxes" => { app.ui.face_boxes = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.face_boxes); Ok(json!({"show": app.ui.face_boxes})) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c803de7193..7e322dddaa 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -75,6 +75,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.faceBoxes", "Face Boxes", None, "View"), ("view.focusPoint", "Focus Point", Some("Alt+F"), "View"), ("view.zoomToFocus", "Zoom to Focus Point", None, "View"), + ("view.reduceMotion", "Reduce Motion", None, "View"), ("view.reference", "Reference View", Some("Shift+R"), "View"), ("photo.setReference", "Set as Reference Photo", None, ""), ("compare.swap", "Swap Compare Photos", None, "View"), diff --git a/crates/ui-egui/src/motion.rs b/crates/ui-egui/src/motion.rs new file mode 100644 index 0000000000..c2564f6b54 --- /dev/null +++ b/crates/ui-egui/src/motion.rs @@ -0,0 +1,56 @@ +//! The one place every animation asks whether motion is reduced (Settings ▸ Interface ▸ Reduce motion). +//! +//! The rule: with reduce motion on, things that move or turn stop moving (the click-zoom tween, +//! egui's own widget easing, spinners, the activity bar's sweep); opacity fades that tell a state +//! change stay (toasts, the slideshow crossfade and its control bar). +//! +//! [`LightcraftApp::sync_theme`](crate::LightcraftApp::sync_theme) stores the setting in the egui +//! context every frame ([`sync`]), so drawing code needs only the `Context`, not the app. + +use egui::{Context, Id, Sense, Ui, vec2}; + +/// egui's widget easing time when motion is on. +const ANIMATION_TIME: f32 = 0.08; +/// How long the click-zoom tween runs when motion is on. +pub const ZOOM_TWEEN_SECONDS: f32 = 0.22; + +fn id() -> Id { + Id::unique("lightcraft_reduce_motion") +} + +/// Record the setting for this frame and set egui's easing time to match (0 when reduced). +pub fn sync(ctx: &Context, reduced: bool) { + if ctx.data(|d| d.get_temp::(id())) == Some(reduced) { + return; + } + ctx.data_mut(|d| d.insert_temp(id(), reduced)); + let time = animation_time(reduced); + ctx.all_styles_mut(|s| s.animation_time = time); +} + +/// Whether things that move or turn should stand still. +pub fn reduced(ctx: &Context) -> bool { + ctx.data(|d| d.get_temp::(id())).unwrap_or(false) +} + +/// egui's `animation_time` for the setting. +pub fn animation_time(reduced: bool) -> f32 { + if reduced { 0.0 } else { ANIMATION_TIME } +} + +/// How long a click-zoom tween runs: none when reduced. +pub fn zoom_tween_seconds(ctx: &Context) -> f32 { + if reduced(ctx) { 0.0 } else { ZOOM_TWEEN_SECONDS } +} + +/// A "working" indicator: egui's turning spinner, or with reduced motion a still dot of the same size +/// (so the layout doesn't move). +pub fn spinner(ui: &mut Ui) { + if !reduced(ui.ctx()) { + ui.spinner(); + return; + } + let side = ui.spacing().interact_size.y; + let (rect, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + ui.painter().circle_filled(rect.center(), side * 0.18, ui.visuals().text_color()); +} diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index dffdd1c4d3..1a92c79922 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -154,3 +154,16 @@ pub(crate) fn bar(ui: &mut egui::Ui, task: &TaskInfo, width: f32) -> egui::Respo crate::widgets::screen_reader_name(ui.ctx(), response.id, tr(&task.label)); response } + +/// The progress bar; while the amount of work isn't known, a segment sweeps across. +/// The sweeping segment of an indeterminate bar, as offsets from the bar's left edge. Reduced motion +/// leaves a still segment (a quarter of the bar, at its left end) that says "working" without moving. +pub(crate) fn indeterminate_span(width: f32, time: f64, reduced: bool) -> (f32, f32) { + if reduced { + return (0.0, width * 0.25); + } + let phase = (time * 0.7).fract() as f32; + let w = width * 0.3; + let x = (width + w) * phase - w; + (x.max(0.0), (x + w).min(width)) +} diff --git a/crates/ui-egui/src/panels/detail/geometry.rs b/crates/ui-egui/src/panels/detail/geometry.rs index d679010f17..09b413faec 100644 --- a/crates/ui-egui/src/panels/detail/geometry.rs +++ b/crates/ui-egui/src/panels/detail/geometry.rs @@ -246,7 +246,7 @@ pub(crate) fn focus_pan(app: &LightcraftApp, id: PhotoId) -> Option<(f32, f32)> /// Ease the loupe rect toward `target` while a click-zoom animation runs; otherwise follow it exactly. pub(super) fn animated_rect(ctx: &egui::Context, anim: &mut bool, target: Rect) -> Rect { - let t = if *anim { 0.22 } else { 0.0 }; + let t = if *anim { crate::motion::zoom_tween_seconds(ctx) } else { 0.0 }; let id = egui::Id::unique("loupe_anim"); let v = |k: &str, x: f32| ctx.animate_value_with_time(id.with(k), x, t); let (c, s) = (target.center(), target.size()); diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index ffd2a0f8d0..4a595335e3 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -195,6 +195,9 @@ pub struct AppSettings { /// gets a new one, or always merge (issue #2672; the window's "Don't ask again" picks that). #[serde(deserialize_with = "lenient")] pub lightroom_import: LightroomImport, + /// Settings ▸ Interface ▸ Reduce motion: things that move or turn stand still; fades stay + /// (`view.reduceMotion`; see [`crate::motion`]). + pub reduce_motion: bool, } /// Where File ▸ Import Lightroom Catalog… puts a catalog (Settings ▸ General ▸ Library). Saved as @@ -245,6 +248,7 @@ impl Default for AppSettings { zoom_to_focus: true, loupe_info: LoupeInfo::default(), lightroom_import: LightroomImport::Ask, + reduce_motion: false, } } } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 09e7703d77..98b8e45d20 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -74,6 +74,7 @@ mod progress; mod quit_unsaved; mod rating; mod recheck; +mod reduce_motion; mod rename_person; mod rules_editor; mod sam_setup; diff --git a/crates/ui-egui/src/tests/reduce_motion.rs b/crates/ui-egui/src/tests/reduce_motion.rs new file mode 100644 index 0000000000..e684ecc6b9 --- /dev/null +++ b/crates/ui-egui/src/tests/reduce_motion.rs @@ -0,0 +1,124 @@ +//! Headless tests of Settings ▸ Interface ▸ Reduce motion (`view.reduceMotion`): the click-zoom lands +//! at once, egui's own easing stops, the activity bar's sweep stands still; with it off, all as before. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Zoom; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn detail() -> Headless { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + app.ui.settings.gpu = false; + let mut h = Headless::new(app, [1000.0, 700.0], 1.0); + h.request("ui.set", json!({"view": "detail", "right": "none"}), T); + h.settle(SETTLE); + h +} + +fn run(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_json::Value { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + r["result"].clone() +} + +/// Click the middle of the photo with real pointer events, stopping on the frame that handled the click. +fn click_photo(h: &mut Headless) { + let pos = h.app.image_rect.expect("image").center(); + h.app.synthetic.extend([ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ]); + while !h.app.synthetic.is_empty() { + h.step(); + } + assert_eq!(h.app.ui.zoom, Zoom::Percent(100.0), "the click zoomed in"); +} + +#[test] +fn a_click_zoom_lands_on_the_next_frame_with_reduce_motion_on() { + let mut h = detail(); + run(&mut h, "view.reduceMotion", json!({"on": true})); + click_photo(&mut h); + h.step(); + let next = h.app.image_rect.unwrap(); + assert!(!h.app.ui.zoom_anim, "the animation ended"); + h.settle(SETTLE); + let settled = h.app.image_rect.unwrap(); + assert_eq!(next, settled, "the next frame already shows the target"); +} + +#[test] +fn a_click_zoom_still_animates_with_reduce_motion_off() { + let mut h = detail(); + click_photo(&mut h); + h.step(); + let next = h.app.image_rect.unwrap(); + assert!(h.app.ui.zoom_anim, "still tweening"); + h.settle(SETTLE); + assert_ne!(next, h.app.image_rect.unwrap(), "an intermediate frame exists"); +} + +#[test] +fn z_zooms_at_once_with_reduce_motion_on() { + let mut h = detail(); + run(&mut h, "view.reduceMotion", json!({"on": true})); + h.request("ui.key", json!({"key": "z"}), T); + h.step(); + let next = h.app.image_rect.unwrap(); + h.settle(SETTLE); + assert!(!h.app.ui.zoom_anim); + assert_eq!(next, h.app.image_rect.unwrap()); +} + +#[test] +fn the_setting_survives_saving_and_loading_the_ui_settings() { + let mut h = detail(); + run(&mut h, "view.reduceMotion", json!({"on": true})); + let saved = serde_json::to_string(&h.app.ui).unwrap(); + let back = serde_json::from_str::(&saved).unwrap().sanitized(); + assert!(back.settings.reduce_motion); + assert!(!crate::state::AppSettings::default().reduce_motion, "off by default"); +} + +#[test] +fn the_command_toggles_and_sets_the_setting() { + let mut h = detail(); + assert_eq!(run(&mut h, "view.reduceMotion", json!({}))["on"], true); + assert!(h.app.ui.settings.reduce_motion); + assert_eq!(run(&mut h, "view.reduceMotion", json!({}))["on"], false); + assert_eq!(run(&mut h, "view.reduceMotion", json!({"on": true}))["on"], true); + assert_eq!(run(&mut h, "view.reduceMotion", json!({"on": true}))["on"], true, "set, not toggled"); + assert_eq!(run(&mut h, "view.reduceMotion", json!({"on": false}))["on"], false); +} + +#[test] +fn egui_easing_stops_with_reduce_motion_on_and_returns_when_off() { + let mut h = detail(); + assert_eq!(h.view.ctx.global_style().animation_time, 0.08); + run(&mut h, "view.reduceMotion", json!({"on": true})); + assert_eq!(h.view.ctx.global_style().animation_time, 0.0); + // a theme change restyles egui: the easing stays off + run(&mut h, "view.appearance", json!({"mode": "light"})); + assert_eq!(h.view.ctx.global_style().animation_time, 0.0); + run(&mut h, "view.reduceMotion", json!({"on": false})); + assert_eq!(h.view.ctx.global_style().animation_time, 0.08); +} + +#[test] +fn the_activity_bar_stands_still_with_reduce_motion_on() { + use crate::panels::activity::indeterminate_span; + let still: Vec<_> = (0..120).map(|f| indeterminate_span(200.0, f as f64 / 60.0, true)).collect(); + assert!(still.windows(2).all(|w| w[0] == w[1]), "no movement between frames"); + assert!(still[0].1 > still[0].0, "but something is shown"); + let moving: Vec<_> = (0..120).map(|f| indeterminate_span(200.0, f as f64 / 60.0, false)).collect(); + assert!(moving.windows(2).any(|w| w[0] != w[1]), "it sweeps when motion is on"); +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 0c562f451f..02fbfea056 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -461,6 +461,7 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { ctx.set_visuals_of(egui::Theme::Dark, v.clone()); ctx.set_visuals_of(egui::Theme::Light, v); ctx.set_theme(if dark { egui::Theme::Dark } else { egui::Theme::Light }); + let animation_time = crate::motion::animation_time(crate::motion::reduced(ctx)); ctx.all_styles_mut(|s| { s.spacing.item_spacing = egui::vec2(6.0, 4.0); s.spacing.button_padding = egui::vec2(8.0, 3.0); @@ -469,7 +470,7 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.text_styles.insert(egui::TextStyle::Button, FontId::proportional(13.0)); s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); - s.animation_time = 0.08; + s.animation_time = animation_time; }); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c086e5c6f..3e0cbe5d7c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -153,6 +153,9 @@ The camera's focus point ([focus-points.md](focus-points.md)) is `meta.focus` in x1, y1}, mode?, area?, tracking?}`, normalized to the upright photo (absent when the file records none). `view.focusPoint {on?}` shows it over the photo (no params toggles; replies `{on}`), and `view.zoomToFocus {on?}` (on by default) makes `view.zoomToggle` zoom in centred on it, replying `{focus: [x, y]}` (the `pan` it set). +`view.reduceMotion {on?}` (off by default; no params toggles; replies `{on}`) is Settings ▸ Interface ▸ Reduce motion: the +click-zoom and `view.zoomToggle` land at once, egui's widget easing and the spinners stop, and the activity bar's sweep +stands still; fades (toasts, the slideshow) stay. `photo.readFocusPoints {ids?, wait?}` reads the point for photos imported before it was read, from a few KB of each file, on a background job (activity kind `focus`); `wait: true` returns the run's counts when done. The app calls `focus.pump {pace}` every frame to drive it. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 46aabad737..15b8e78cc3 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-ACCESS: Reduce motion setting; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -479,7 +479,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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 | | LR-BEHAV-HEADLESS | Headless UI snapshots | P2 | ✅ | `apps/lightcraft-cli/src/main.rs`, `crates/ui-egui/src/headless.rs`, `docs/control-protocol.md` | `snapshot` rasterizes the UI and defaults photo development to the CPU before the first frame, without adapter discovery; scaled dimensions are validated before allocation, and UI zoom preserves the requested physical viewport; JSON-lines control scripts are supported | -| LR-BEHAV-ACCESS | Accessibility | P2 | 🟡 | `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/grid.rs`, `crates/ui-egui/tests/it/accessibility.rs` | AccessKit (VoiceOver / Narrator / AT-SPI): sliders announce control, value, range and step and take Increment / Decrement (the value field beside each is named ` value` and describes how to type or drag), buttons / icon buttons / dropdowns / section headers / sources their labels and state, text fields their caption, grid thumbnails file name, rating, flag and label. `tests/it/accessibility.rs` fails on an unnamed control, a slider without range or an untitled dialog in every view, Develop tool and 13 dialogs, and checks that Crop and Remove sliders are reached with Tab and that Tab walks the right panels top to bottom. Canvas tools by keyboard (`crates/ui-egui/src/canvas_keys.rs`, `crates/ui-egui/src/tests/canvas_keys.rs`): crop corners, edges and box, spot targets and sources, a New spot point (Return adds), radial / linear gradient handles and mask pins take the focus, are announced with their position and move with the arrows (Shift: further). Dialogs with one name field (New Album, New Smart Album, Save Metadata Preset, the renames) take the focus once when they open, so Tab and Shift+Tab reach their check box, Cancel and OK, and Return and Esc still confirm and cancel (`crates/ui-egui/src/tests/dialog_tab.rs`). The photo in Detail is named like its grid cell, `Photo: , , ,