diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index eeeafaa7f1..4c569062a3 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -298,8 +298,11 @@ fn calibrate(args: &[String]) -> Result<(), String> { let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes)); let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; match result { - Ok(Some(model)) => eprintln!("[{n}/{}] {} ({model})", files.len(), path.display()), - Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable camera JPEG or colour)", files.len(), path.display()), + Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model), + Ok(Some(added)) => { + eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model) + } + Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()), Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()), } } @@ -319,11 +322,12 @@ fn calibrate(args: &[String]) -> Result<(), String> { Ok(profile) => { let path = lightcraft_engine::camera_profiles::save(&profile, &dir)?; println!( - "{}: {} photos, {} colour pairs, hue/saturation table {} → {}", + "{}: {} photos, {} colour pairs, hue/saturation table {}, tone curve {} → {}", profile.model, profile.files, profile.samples, profile.hue_sat.is_some(), + profile.tone.is_some(), path.display() ); written += 1; diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 283ce88ed1..e621b77a16 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -1,7 +1,8 @@ //! 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, which //! photos have their file in a folder, which have a file of a given name, which photos have the same -//! content. +//! content, the lower-cased text the free-text search reads, and the text a smart album's Text rule +//! reads (each made for every photo the first time it is needed for every photo). //! //! 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 @@ -13,6 +14,7 @@ //! is kept up to date, and the photos with a photo's content touched, by the ops that change a //! photo's content as the library sees it, once a rule has built it or while a smart album asks //! about contents ([`Catalog::follows_contents`], [`Catalog::content_moved`]). +//! The two texts follow every op that changes a photo's fields, and the photo moving to another place in memory. use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; @@ -37,6 +39,10 @@ pub(crate) struct Indexes { /// File name, lower-cased ([`file_name_index_key`]) → the photos whose file has it (same /// states as `folders`). names: OnceLock>>, + /// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search. + search: OnceLock>, + /// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]). + rule_text: OnceLock>, } /// A copy builds its own when asked (copies are made to be saved, not queried). @@ -93,6 +99,34 @@ impl Indexes { } } + /// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again. + pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) { + if let Some(m) = self.search.get_mut() { + match p { + Some(p) => m.insert(id, PhotoText::of(p)), + None => m.remove(&id), + }; + } + if let Some(m) = self.rule_text.get_mut() { + match p { + Some(p) => m.insert(id, RuleText::of(p)), + None => m.remove(&id), + }; + } + } + + /// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold + /// (`Arc::make_mut`) puts it at another address, which its text follows. + pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) { + let at = addr(p); + if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + } + /// Photo `id` had content `old` and has `new` now (`None`: none the library counts). fn content_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option) { let Some(m) = self.contents.get_mut() else { return }; @@ -129,6 +163,135 @@ impl Indexes { } } +/// A map from photos, for a pass over the library that asks about each one in id order. +type ByPhoto = HashMap>; + +/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so +/// ids that follow each other sit next to each other and a pass in id order walks it in order +/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top +/// bits, which tag an entry in the table, are mixed so entries still tell each other apart. +#[derive(Default)] +pub(crate) struct IdHasher(u64); + +impl std::hash::Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000) + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = self.0.rotate_left(8) ^ u64::from(*b); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = n; + } +} + +/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the +/// address it was made for. The catalog's own photos (`Arc` contents) stay where they are +/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]; `repair` +/// copies them in bulk and drops every lookup instead); +/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy +/// of a photo (a candidate tried with other values) is at another address, so it is read from its +/// own fields, never from a text kept for the photo with its id. Only ids and addresses are +/// compared; the address is never turned back into a reference. A catalog read from a snapshot +/// (and then repaired) or cloned starts with no texts at all: they are made when asked. +fn addr(p: &Photo) -> usize { + std::ptr::from_ref(p).addr() +} + +/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does +/// for each field alone: file name, title, caption, camera, lens, location, format, then each +/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold +/// white space (a quoted phrase); one that holds NUL is read from the fields one by one +/// ([`PhotoText::field_contains`]), so no word runs over a field. +pub(crate) struct PhotoText { + /// The address of the photo this was made from ([`addr`]). + at: usize, + text: Box, +} + +impl PhotoText { + /// The fields of `p` that the text joins before its keywords and people. + fn fields(p: &Photo) -> [&String; 7] { + [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format] + } + + pub(crate) fn of(p: &Photo) -> PhotoText { + let fields = Self::fields(p); + let people = p.people(); + // (exact for ASCII, which most text is: the box takes the buffer without copying it) + let len = fields + .iter() + .map(|f| f.len() + 1) + .chain(p.meta.keywords.iter().map(|k| k.len() + 1)) + .chain(people.iter().map(|n| n.len() + 1)) + .sum::() + .saturating_sub(1); + let mut text = String::with_capacity(len); + for (i, field) in fields.into_iter().enumerate() { + if i > 0 { + text.push('\0'); + } + push_lowercase(&mut text, field); + } + for k in p.meta.keywords.iter().map(String::as_str).chain(people) { + text.push('\0'); + push_lowercase(&mut text, k); + } + PhotoText { at: addr(p), text: text.into_boxed_str() } + } + + /// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, + /// location, format, a keyword or the name of a person. + pub(crate) fn contains(&self, t: &str) -> bool { + self.text.contains(t) + } + + /// [`PhotoText::contains`] read from `p`'s fields one by one, for a word that holds NUL: the joined text can't tell + /// the NUL that separates two fields from one inside a field, and a word never runs over two fields. + pub(crate) fn field_contains(p: &Photo, t: &str) -> bool { + Self::fields(p) + .into_iter() + .map(String::as_str) + .chain(p.meta.keywords.iter().map(String::as_str)) + .chain(p.people()) + .any(|f| f.to_lowercase().contains(t)) + } + + #[cfg(test)] + pub(crate) fn text(&self) -> &str { + &self.text + } +} + +/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII. +fn push_lowercase(out: &mut String, s: &str) { + if s.is_ascii() { + let from = out.len(); + out.push_str(s); + if let Some(added) = out.get_mut(from..) { + added.make_ascii_lowercase(); + } + } else { + out.push_str(&s.to_lowercase()); + } +} + +/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`]. +struct RuleText { + at: usize, + text: Box, +} + +impl RuleText { + fn of(p: &Photo) -> RuleText { + RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() } + } +} + fn rekey(m: &mut HashMap>, id: PhotoId, old: Option, new: Option) { if let Some(k) = old && let Some(set) = m.get_mut(&k) @@ -232,6 +395,34 @@ impl Catalog { m.get(&album).is_some_and(|s| s.contains(&photo)) } + /// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the + /// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole + /// library does; testing one photo shouldn't build it for 300 000). + pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> { + let m = if build { + self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect()) + } else { + self.index.search.get()? + }; + m.get(&p.id).filter(|t| t.at == addr(p)) + } + + /// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of + /// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or + /// view asks for it photo by photo). + pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> { + let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect()); + let t = m.get(&p.id)?; + (t.at == addr(p)).then_some(&*t.text) + } + + /// Whether the Text rules' text has been made (asking for it makes it, so a test cannot look with + /// [`Catalog::rule_text_of`]). + #[cfg(test)] + pub(crate) fn rule_text_made(&self) -> bool { + self.index.rule_text.get().is_some() + } + /// Content → its photos, by the index (built on first use). fn contents(&self) -> &HashMap> { self.index.contents.get_or_init(|| { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1d33d3f029..bbf3e7bca1 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -688,7 +688,10 @@ impl Catalog { fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> { self.touch(id); - self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id)) + let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?; + // (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy) + self.index.text_moved(id, p); + Ok(p) } /// The op being applied changes photo `id` (or adds or removes it). @@ -917,11 +920,13 @@ impl Catalog { 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)); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); 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); + self.index.text_changed(id, None); // album membership is restored by the batch the engine builds (see `delete_permanently`) Op::AddPhoto { photo: Box::new((*p).clone()) } } @@ -949,7 +954,9 @@ impl Catalog { } Op::SetMeta { id, meta } => { let p = self.photo_mut(id)?; - Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) } + let old = std::mem::replace(&mut p.meta, *meta); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + Op::SetMeta { id, meta: Box::new(old) } } Op::SetDeleted { id, deleted } => { let p = self.photo_mut(id)?; @@ -1137,7 +1144,9 @@ impl Catalog { 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)); - Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format } + let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => { let p = self.photo_mut(id)?; @@ -1171,7 +1180,9 @@ impl Catalog { } 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) } + let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetLabelName { label, name } => { let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()); @@ -1287,6 +1298,10 @@ impl Catalog { /// wrote). pub fn repair(&mut self) -> Vec { let mut changed = Vec::new(); + // Photos others hold are copied below (`Arc::make_mut`), which moves them in memory and strands the text kept + // for their address ([`index::Indexes`]), and stacks and albums change outside `apply`: nothing derived is + // kept across a repair, and the lookups are built again when asked. + self.index = index::Indexes::default(); // Segmentation grids shared by the snapshot this was read from (issue #2154): each // reference takes its grid's data, and the table is not kept — a live catalog always // stores the data inline, so masks render and serialize without the snapshot's table. @@ -1397,9 +1412,8 @@ impl Catalog { self.next_stack = self.next_stack.max(stack); } if !changed.is_empty() { - // stacks and albums changed outside `apply`: the lookups are built again when asked - self.index = index::Indexes::default(); - // (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too) + // stacks and albums changed outside `apply`: what was worked out from the albums is made again (the guard of + // [`Self::keeps_written_order`] too) self.plans = PlansMemo::default(); } changed @@ -1622,6 +1636,8 @@ mod tests_rule_order; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_search_text; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index efa62ea6d8..069b01b781 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -152,6 +152,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 { pub(crate) struct Prepared { root: Option, only: Option>, + /// The search words ([`Filter::tokens`]). + tokens: Vec, + /// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]). + whole: bool, /// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]); /// `None` tests them as written. rules: Option, @@ -186,8 +190,8 @@ fn unquote(s: &str) -> &str { s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner)) } -fn token_matches(p: &Photo, tok: &str) -> bool { - let t = tok.to_lowercase(); +/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text. +fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool { // a token that starts with a quote is a phrase, even with a colon in it if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) { let val = unquote(quoted); @@ -231,20 +235,36 @@ fn token_matches(p: &Photo, tok: &str) -> bool { "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted // (`re:"a b"` is the text `re:a b`). - _ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")), - _ => text_matches(p, &t), + _ if val.len() != quoted.len() => hay.contains(&format!("{field}:{val}")), + _ => hay.contains(t), }; } - text_matches(p, unquote(&t)) + hay.contains(unquote(t)) } -/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location, -/// format, a keyword or the name of a person (a named face) of `p`. -fn text_matches(p: &Photo, t: &str) -> bool { - let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; - hay.iter().any(|h| h.to_lowercase().contains(t)) - || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) - || p.people().iter().any(|n| n.to_lowercase().contains(t)) +/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its +/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked. +struct Hay<'a> { + p: &'a Photo, + cat: &'a Catalog, + whole: bool, + kept: std::cell::OnceCell>, + own: std::cell::OnceCell, +} + +impl Hay<'_> { + fn text(&self) -> &crate::index::PhotoText { + match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) { + Some(t) => t, + None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)), + } + } + + /// Whether `t` (lower-cased) is in one field of the photo ([`crate::index::PhotoText::contains`]): a word with NUL + /// is read from the fields themselves, for the joined text separates them with NUL. + fn contains(&self, t: &str) -> bool { + if t.contains('\0') { crate::index::PhotoText::field_contains(self.p, t) } else { self.text().contains(t) } + } } /// Whether `p` has a named face region called `name` (case-insensitive). @@ -356,13 +376,13 @@ impl Filter { pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { // one photo: its rules are tested as written (ordering them would cost more than it saves) - self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None }) + self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: None }) } /// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once /// (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared { - Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) } + Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: self.ordered_rules(cat) } } /// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None` @@ -376,16 +396,23 @@ impl Filter { } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than - /// once per photo: the library folder's identity, the `only` ids as a set and the rules in the - /// order to test them. + /// once per photo: the library folder's identity, the `only` ids as a set, the search words and the + /// rules in the order to test them. pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared { Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), + tokens: self.tokens(), + whole: true, rules: self.ordered_rules(cat), } } + /// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo). + fn tokens(&self) -> Vec { + search_tokens(&self.text).map(str::to_lowercase).collect() + } + /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. fn library_root(&self) -> Option { // as given: a folder may be named with spaces at its edge, and trimming would make it @@ -510,7 +537,11 @@ impl Filter { { return false; } - search_tokens(&self.text).all(|tok| token_matches(p, tok)) + if prepared.tokens.is_empty() { + return true; + } + let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() }; + prepared.tokens.iter().all(|t| token_matches(p, t, &hay)) } } diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index cac6ac3a09..787a37a302 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -714,8 +714,37 @@ fn lower(v: &Value) -> String { } } +/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city, +/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased. +pub(crate) fn rule_text(p: &Photo) -> String { + let m = &p.meta; + let all = [ + p.file_name.as_str(), + &m.title, + &m.caption, + &m.camera, + &m.lens, + &m.location, + &m.city, + &m.state, + &m.country, + &m.alt_text, + &p.format, + &m.keywords.join(" "), + &p.people().join(" "), + p.copy_name.as_deref().unwrap_or(""), + ] + .join(" "); + let all = all.trim(); + if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() } +} + fn text_op(op: &str, have: &str, want: &str) -> bool { - let have = have.trim().to_lowercase(); + text_op_lowered(op, &have.trim().to_lowercase(), want) +} + +/// [`text_op`] for a `have` that is trimmed and lower-cased already. +fn text_op_lowered(op: &str, have: &str, want: &str) -> bool { match op { "contains" => want.split_whitespace().all(|w| have.contains(w)), "notContains" => !want.split_whitespace().any(|w| have.contains(w)), @@ -1060,26 +1089,10 @@ impl Rule { "keywordCount" => num_op(op, Some(p.keyword_count() as f64), value), "person" => names_op(op, &p.people(), &want), "personCount" => num_op(op, Some(p.people().len() as f64), value), - "text" => { - let all = [ - p.file_name.as_str(), - &m.title, - &m.caption, - &m.camera, - &m.lens, - &m.location, - &m.city, - &m.state, - &m.country, - &m.alt_text, - &p.format, - &m.keywords.join(" "), - &p.people().join(" "), - p.copy_name.as_deref().unwrap_or(""), - ] - .join(" "); - text(&all) - } + "text" => match cat.rule_text_of(p) { + Some(have) => text_op_lowered(op, have, &want), + None => text_op_lowered(op, &rule_text(p), &want), + }, "fileName" => text(&p.file_name), "extension" => text_op(op, p.extension(), want.trim_start_matches('.')), "duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value), diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs new file mode 100644 index 0000000000..2c9ae6c668 --- /dev/null +++ b/crates/catalog/src/tests_search_text.rs @@ -0,0 +1,474 @@ +//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache +//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The +//! cache must give the matches the fields give, and follow every edit of a field it holds. + +use lightcraft_meta::{Rect, Region, RegionKind}; +use serde_json::json; + +use super::*; +use crate::index::PhotoText; + +fn photo(id: u64, file: &str) -> Photo { + Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00") +} + +fn face(name: &str) -> Region { + Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None } +} + +/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on +/// its neighbours, a word that is only there across two fields, a colon in a plain word. +fn library() -> Catalog { + let mut photos = Vec::new(); + let mut p = photo(1, "IMG_0001.JPG"); + p.rating = 3; + p.meta.camera = "Canon EOS R5".into(); + p.meta.lens = "RF24-70mm F2.8 L".into(); + p.meta.title = "Trip to Ōsaka".into(); + p.meta.caption = "Straße am Fluss".into(); + p.meta.location = "Kyōto".into(); + p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()]; + photos.push(p); + let mut p = photo(2, "İstanbul.jpg"); + p.meta.title = "ΣΊΣΥΦΟΣ".into(); + p.meta.caption = "Re: 10:30 meeting".into(); + p.meta.city = "Zürich".into(); + p.meta.regions = vec![face("Ana Lima")]; + photos.push(p); + let mut p = photo(3, "plain.png"); + p.format = "PNG".into(); + photos.push(p); + let mut p = photo(4, "abc"); + p.meta.camera = "def".into(); + p.meta.title = "Dž dž".into(); + photos.push(p); + let mut p = photo(5, "name:colon.jpg"); + p.meta.lens = "title:trip".into(); + p.copy_name = Some("Black and White".into()); + photos.push(p); + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +/// How the search read a word before the cache: each field lower-cased alone, for every photo. +fn before_text_matches(p: &Photo, t: &str) -> bool { + let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + hay.iter().any(|h| h.to_lowercase().contains(t)) + || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) + || p.people().iter().any(|n| n.to_lowercase().contains(t)) +} + +/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves. +fn before_matches(p: &Photo, text: &str) -> bool { + text.split_whitespace().all(|tok| { + let t = tok.to_lowercase(); + match t.split_once(':') { + Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val), + Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val), + Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val), + Some(("rating", val)) => p.rating.to_string() == val, + Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)), + _ => before_text_matches(p, &t), + } + }) +} + +const QUERIES: &[&str] = &[ + "img", + "IMG_0001", + "IMG_0001.JPG", + "canon r5", + "CANON eos", + "ōsaka", + "ŌSAKA", + "osaka", + "straße", + "STRASSE", + "i̇stanbul", + "İSTANBUL", + "istanbul", + "σίσυφος", + "ΣΊΣΥΦΟΣ", + "ς", + "σ", + "ὀδυσσεύς", + "travel", + "italy", + "travel|italy", + "kyōto japan", + "kyōto", + "10:30", + "re:", + "name:img", + "NAME:IMG_0001", + "file:plain", + "name:", + "camera:canon", + "camera:r5", + "lens:rf24", + "lens:", + "title:trip", + "abcdef", + "abc def", + "dž", + "rating:3 trip", + "kw:travel ōsaka", + "kw:travel osaka", + "png jpeg", + "", + " ", + "zzz", +]; + +fn shown(c: &Catalog, text: &str) -> Vec { + let f = Filter { text: text.into(), ..Default::default() }; + let mut ids: Vec = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +fn expected(c: &Catalog, text: &str) -> Vec { + c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect() +} + +/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the +/// library that makes the cache, or one photo after that. +#[test] +fn search_matches_as_the_fields_do() { + let c = library(); + let mut one_by_one = Vec::new(); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::>()); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library"); + for (q, got) in QUERIES.iter().zip(&one_by_one) { + assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time"); + } + for q in QUERIES.iter().copied() { + assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library"); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache"); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + let got: Vec = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect(); + assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache"); + } +} + +/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read +/// from its own fields, not from what the catalog kept for the photo with its id. +#[test] +fn a_copy_of_a_photo_is_read_as_it_is() { + let c = library(); + let f = Filter { text: "ōsaka".into(), ..Default::default() }; + assert_eq!(c.count(&f), 1); + let mut p = (**c.photo(PhotoId(1)).unwrap()).clone(); + p.meta.title = "Trip to Nara".into(); + p.meta.keywords.clear(); + p.meta.location.clear(); + assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't"); + let nara = Filter { text: "nara".into(), ..Default::default() }; + assert!(nara.matches(&p, &c)); + assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c)); + let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() }; + assert_eq!(c.count(&rule), 0); + assert!(rule.matches(&p, &c)); +} + +fn rules(v: serde_json::Value) -> RuleSet { + serde_json::from_value(v).unwrap() +} + +fn text_rule(op: &str, value: &str) -> Filter { + Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() } +} + +/// What the cache holds is what a scan of the photos would give it, and every photo's is used. +fn assert_current(c: &Catalog) { + for p in c.photos() { + let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0)); + let now = PhotoText::of(p); + assert_eq!(kept.text(), now.text(), "photo {}", p.id.0); + assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0); + } +} + +/// Make the caches, as the first search and the first smart album with a Text rule do. +fn warm(c: &Catalog) { + c.count(&Filter { text: "x".into(), ..Default::default() }); + c.count(&text_rule("contains", "x")); + assert_current(c); +} + +fn found(c: &Catalog, text: &str) -> usize { + c.count(&Filter { text: text.into(), ..Default::default() }) +} + +fn found_by_rule(c: &Catalog, text: &str) -> usize { + c.count(&text_rule("contains", text)) +} + +/// An edit of each field that is searched puts the new text in the cache and takes the old one out, +/// through the op, its inverse and a batch that fails and is taken back. +#[test] +fn the_cache_follows_every_field_that_is_searched() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| { + let mut meta = c.photo(id).unwrap().meta.clone(); + set(&mut meta); + c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap() + }; + type Set = fn(&mut Meta, &str); + let fields: [(&str, Set); 6] = [ + ("title", |m, v| m.title = v.into()), + ("caption", |m, v| m.caption = v.into()), + ("camera", |m, v| m.camera = v.into()), + ("lens", |m, v| m.lens = v.into()), + ("location", |m, v| m.location = v.into()), + ("keywords", |m, v| m.keywords = vec![v.into()]), + ]; + for (n, (field, set)) in fields.into_iter().enumerate() { + let word = format!("Zq{n}x"); + let before = found(&c, &word); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit"); + assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found(&c, &word), 0, "{field}: gone after the undo"); + assert_current(&c); + } + // the fields only Text rules read + let rule_fields: [(&str, Set); 3] = + [("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())]; + for (n, (field, set)) in rule_fields.into_iter().enumerate() { + let word = format!("zr{n}y"); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo"); + } + let undo = edit(&mut c, &|m| m.alt_text = "zalt".into()); + assert_eq!(found_by_rule(&c, "zalt"), 1); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zalt"), 0); + let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]); + assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face"); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zed person"), 0); + assert_current(&c); +} + +#[test] +fn the_cache_follows_a_file_name_and_a_format() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let source = Source::Demo { scene: 1 }; + let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1)); + assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1)); + assert_current(&c); + + let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0)); + assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1)); + assert_current(&c); +} + +/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does +/// too, and a virtual copy's name is read by a Text rule. +#[test] +fn the_cache_follows_photos_that_come_and_go() { + let mut c = library(); + warm(&c); + let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone(); + copy.id = PhotoId(9); + copy.copy_of = Some(PhotoId(1)); + copy.meta = Default::default(); + copy.copy_name = Some("Zcopy Name".into()); + copy.file_name = "Zfresh.jpg".into(); + let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0)); + assert_current(&c); + let redo = c.apply(undo).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0)); + assert_current(&c); + c.apply(redo).unwrap(); + assert_eq!(found(&c, "zfresh"), 1); + assert_current(&c); + let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap(); + assert_eq!(found(&c, "ōsaka"), 0); + assert_current(&c); + c.apply(removed).unwrap(); + assert_eq!(found(&c, "ōsaka"), 1); + assert_current(&c); +} + +/// A batch that fails half way is taken back, and the cache with it. +#[test] +fn the_cache_follows_a_batch_that_fails() { + let mut c = library(); + warm(&c); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Zbatch title".into(); + let batch = Op::Batch { + ops: vec![ + Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }, + Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } }, + Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } }, + ], + }; + assert!(c.apply(batch).is_err()); + assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0)); + assert_eq!(found(&c, "plain"), 1); + assert_current(&c); +} + +/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another +/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields. +#[test] +fn the_cache_follows_a_photo_that_others_hold() { + let mut c = library(); + warm(&c); + let held: Vec<_> = c.photos().cloned().collect(); + for p in &held { + c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap(); + } + assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos"); + assert_current(&c); + assert_eq!(found(&c, "ōsaka"), 1); + c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + assert_current(&c); + assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0)); +} + +/// A catalog read from a snapshot or cloned starts with no cache and builds its own. +#[test] +fn a_clone_builds_its_own() { + let mut c = library(); + warm(&c); + let mut copy = c.clone(); + assert!(copy.photos().all(|p| copy.search_text(p, false).is_none())); + assert_eq!(found(©, "ōsaka"), 1); + warm(©); + let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone(); + meta.title = "Elsewhere".into(); + copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap(); + assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0)); + c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap(); + assert_current(&c); +} + +/// `repair` copies the photos others hold (`Arc::make_mut`) without reporting a change, so the cache would +/// still keep a text for the address the retained photo has. The retained photo, changed on its own, is +/// read from its fields, never from the text kept for the photo with its id. +#[test] +fn repair_keeps_no_text_for_a_photo_it_copied() { + let mut c = library(); + warm(&c); + let mut held = c.photo(PhotoId(1)).unwrap().clone(); + assert!(c.repair().is_empty(), "a sound catalog"); + assert!(!std::ptr::eq(&*held, &**c.photo(PhotoId(1)).unwrap()), "repair copied the photo"); + std::sync::Arc::make_mut(&mut held).meta.title = "Trip to Nara".into(); + let nara = Filter { text: "nara".into(), ..Default::default() }; + let osaka = Filter { text: "ōsaka".into(), ..Default::default() }; + assert!(nara.matches(&held, &c), "the retained photo's own title"); + assert!(!osaka.matches(&held, &c), "not the title it had"); + assert!(text_rule("contains", "nara").matches(&held, &c), "the Text rule reads the retained photo's own title"); + assert!(!text_rule("contains", "ōsaka").matches(&held, &c)); + warm(&c); + assert_eq!((found(&c, "ōsaka"), found(&c, "nara")), (1, 0)); +} + +/// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each +/// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the +/// kept text gives. +#[test] +fn text_rules_match_as_the_fields_do() { + let c = library(); + let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"]; + let values = + ["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"]; + assert!(!c.rule_text_made(), "nothing made the text yet"); + let after: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect(); + assert!(c.rule_text_made(), "the first rule asked made the text"); + let from_the_fields: Vec> = every_op + .iter() + .map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(&Photo::clone(p), &c)).count()).collect()) + .collect(); + assert_eq!(from_the_fields, after); + assert!(after.iter().flatten().any(|&n| n > 0), "the rules found something"); + let again: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + assert_eq!(after, again); +} + +/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the +/// kept text: it is made there, and an edit shows in the next count. +#[test] +fn a_smart_album_count_reads_the_kept_text() { + let mut c = library(); + let mut album = Album::new(AlbumId(1), "Osaka"); + album.smart = Some(Box::new(text_rule("contains", "ōsaka"))); + c.apply(Op::AddAlbum { album }).unwrap(); + let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count(); + assert!(!c.rule_text_made(), "nothing made the text yet"); + assert_eq!(one_by_one(&c), 1); + assert!(c.rule_text_made(), "counting made the text"); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Ōsaka again".into(); + c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap(); + assert_eq!(one_by_one(&c), 2); +} + +/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as +/// one word that never runs from one field into the next. +#[test] +fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() { + let mut c = library(); + warm(&c); + assert_eq!(found(&c, "ana"), 1, "a person's name is searched"); + assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase"); + assert_eq!(found(&c, "\"lima ana\""), 0); + assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption"); + assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field"); + assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword"); + // (the photo that has Ana Lima's face) + let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone(); + meta.regions = vec![face("Zed Person")]; + c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap(); + assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once"); + assert_eq!(found(&c, "ana"), 0, "and the old name is gone"); + assert_current(&c); +} + +/// A word that holds NUL (a filter's text can) is looked for inside one field, as before the cache: it never matches across +/// the NUL the cache puts between two fields, and still matches a field that holds NUL itself. +#[test] +fn a_word_holding_nul_never_runs_over_two_fields() { + let mut c = Catalog::new(); + let mut p = photo(1, "a"); + p.meta.title = "b".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let mut p = photo(2, "c\0d"); + p.meta.title = "e".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + for text in ["a\0b", "\"a\0b\"", "b\0", "\0e"] { + assert_eq!(shown(&c, text), Vec::::new(), "{text:?}"); + } + assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found"); +} diff --git a/crates/denoise/src/cpu.rs b/crates/denoise/src/cpu.rs index 34e5269e42..9447fa28f4 100644 --- a/crates/denoise/src/cpu.rs +++ b/crates/denoise/src/cpu.rs @@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option) { match op { Op::Conv(c) => (c.src, c.src2), Op::ConvT2(c) => (c.src, None), + Op::Add { src, src2 } => (*src, Some(*src2)), Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => (*src, None), } } @@ -108,6 +109,7 @@ impl NetRunner { (a.channels, a.side / 2) } Op::DepthToSpace2 { .. } => (a.channels / 4, a.side.checked_mul(2).ok_or_else(|| bad("size overflow"))?), + Op::Add { .. } => (a.channels, a.side), }; let n = count(channels, side)?; let slot = busy @@ -215,6 +217,7 @@ impl NetRunner { &mut w.lower, &mut w.product, )?, + Op::Add { .. } => add(a, b.ok_or_else(|| bad("Add needs two inputs"))?, shape.side, dest)?, Op::MaxPool2 { .. } => pool(a, shape.side, dest)?, Op::DepthToSpace2 { .. } => shuffle(a, shape.side, dest)?, } @@ -381,6 +384,46 @@ fn shuffle(a: &[f32], side: usize, dest: &mut [f32]) -> Result<()> { } Ok(()) } +fn add(a: &[f32], b: &[f32], side: usize, dest: &mut [f32]) -> Result<()> { + let pixels = side * side; + let channels = a.len() / pixels; + let need = channels.checked_mul(pixels).ok_or_else(|| bad("Add size overflows"))?; + if a.len() < need || b.len() < need || dest.len() < need { + return Err(bad("Add inputs and output are not the same size")); + } + for c in 0..channels { + let a_plane = &a[c * pixels..(c + 1) * pixels]; + let b_plane = &b[c * pixels..(c + 1) * pixels]; + let d_plane = &mut dest[c * pixels..(c + 1) * pixels]; + for (d, (&av, &bv)) in d_plane.iter_mut().zip(a_plane.iter().zip(b_plane)) { + *d = av + bv; + } + } + Ok(()) +} + +#[cfg(test)] +#[test] +fn add_op_produces_elementwise_sum() { + use crate::net::{Conv, Net, Op, TensorId}; + + fn conv(src: TensorId, cin: usize, cout: usize) -> Op { + Op::Conv(Conv { src, src2: None, cin, cout, k: 1, weight: vec![0.1; cout * cin], bias: vec![0.0; cout], leaky: None }) + } + + let tile = 8usize; + let ops = vec![conv(0, 4, 12), Op::Add { src: 1, src2: 1 }, Op::DepthToSpace2 { src: 2 }]; + let net = Net::new(4, ops).unwrap(); + let runner = NetRunner::new(&net, tile).unwrap(); + + let pixels = tile * tile; + let input: Vec = vec![1.0; 4 * pixels]; + let output = runner.run(&input).unwrap(); + assert_eq!(output.len(), 3 * (2 * tile) * (2 * tile)); + for &v in &output { + assert!((v - 0.8).abs() < 1e-4, "expected 0.8, got {v}"); + } +} #[cfg(test)] mod tests; diff --git a/crates/denoise/src/net.rs b/crates/denoise/src/net.rs index 422418336b..7c648bb042 100644 --- a/crates/denoise/src/net.rs +++ b/crates/denoise/src/net.rs @@ -63,6 +63,11 @@ pub struct ConvT2 { pub enum Op { Conv(Conv), ConvT2(ConvT2), + /// Elementwise addition of two same-shape tensors. + Add { + src: TensorId, + src2: TensorId, + }, /// 2 × 2 maximum, stride 2. MaxPool2 { src: TensorId, @@ -146,6 +151,20 @@ impl Net { check_weights(i, &c.weight, c.cin.checked_mul(c.cout).and_then(|n| n.checked_mul(4)), &c.bias, c.cout, c.leaky, &mut weights)?; Shape { channels: c.cout, level: a.level - 1 } } + Op::Add { src, src2 } => { + let a = shape_of(*src)?; + let b = shape_of(*src2)?; + if a.channels != b.channels || a.level != b.level { + return invalid(format!("layer {i}: add of tensors of different shapes")); + } + if a.channels == 0 { + return invalid(format!("layer {i}: add with zero channels")); + } + if a.channels > MAX_CHANNELS { + return invalid(format!("layer {i}: add with more than {} channels", MAX_CHANNELS)); + } + Shape { channels: a.channels, level: a.level } + } Op::MaxPool2 { src } => { let a = shape_of(*src)?; Shape { channels: a.channels, level: a.level + 1 } diff --git a/crates/denoise/src/onnx.rs b/crates/denoise/src/onnx.rs index 074963695f..edc22a638d 100644 --- a/crates/denoise/src/onnx.rs +++ b/crates/denoise/src/onnx.rs @@ -2,16 +2,18 @@ //! //! Only what the denoise U-Nets are made of is understood: `Conv` (3 × 3 "same" or 1 × 1, stride 1, no groups, no //! dilation) optionally followed by `LeakyRelu`, `ConvTranspose` (2 × 2, stride 2) likewise, `MaxPool` (2 × 2, stride 2), -//! a two-input `Concat` on the channels that feeds a convolution, and a final `DepthToSpace` (2, `CRD`). Any other +//! a two-input `Concat` on the channels that feeds a convolution, an `Add` of two same-shape tensors (elementwise addition), +//! a standalone `LeakyRelu` (as a 1 × 1 identity convolution with the +//! activation, when its source has more than one reader), and a final `DepthToSpace` (2, `CRD`). Any other //! operator or attribute is [`NetError::Unsupported`], which is reported to the user by both runners. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::Path; use crate::onnx_proto::{self, AttributeProto, NodeProto, TensorProto, ValueInfoProto}; use std::io::Read; -use crate::net::{Conv, ConvT2, MAX_WEIGHTS, Net, NetError, Op, TensorId}; +use crate::net::{Conv, ConvT2, MAX_CHANNELS, MAX_OPS, MAX_WEIGHTS, Net, NetError, Op, TensorId}; fn unsupported(why: impl Into) -> Result { Err(NetError::Unsupported(why.into())) @@ -62,11 +64,23 @@ fn read_bytes(bytes: &[u8]) -> Result { // a Concat is not a layer of its own: the convolution that reads it takes both sources let mut joins: HashMap = HashMap::new(); let mut ops: Vec = Vec::new(); + let mut shapes: Vec<(usize, i32)> = vec![(in_channels, 0)]; let mut weights_total = 0usize; let nodes = &graph.node; let mut i = 0; + let mut fused_indices = HashSet::new(); while i < nodes.len() { + // Skip nodes that were fused as LeakyRelu activations + while i < nodes.len() && fused_indices.contains(&i) { + i += 1; + } + if i >= nodes.len() { + break; + } + if ops.len() >= MAX_OPS { + return invalid("the network has too many layers"); + } let Some(node) = nodes.get(i) else { break }; i += 1; if node.output.len() != 1 || node.output.first().is_none_or(|n| n.is_empty() || ids.contains_key(n) || joins.contains_key(n)) { @@ -77,6 +91,8 @@ fn read_bytes(bytes: &[u8]) -> Result { "ConvTranspose" => &["kernel_shape", "pads", "strides", "dilations", "group", "output_padding", "auto_pad"], "MaxPool" => &["kernel_shape", "pads", "strides", "dilations", "ceil_mode", "storage_order", "auto_pad"], "Concat" => &["axis"], + "Add" => &[], + "LeakyRelu" => &["alpha"], "DepthToSpace" => &["blocksize", "mode"], _ => &[], }; @@ -87,25 +103,37 @@ fn read_bytes(bytes: &[u8]) -> Result { let lookup = |name: &str| -> Result { ids.get(name).copied().ok_or_else(|| NetError::Invalid(format!("`{}` reads `{name}`, which nothing makes", node.op_type))) }; - // a LeakyRelu straight after this layer, which nothing else reads, is part of it - let mut fuse_leaky = |out: &str| -> Result<(Option, String), NetError> { - if let Some(next) = nodes.get(i) - && next.op_type == "LeakyRelu" - && next.input.first().map(String::as_str) == Some(out) - && readers.get(out).copied() == Some(1) - { - if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") { - return invalid("malformed LeakyRelu"); + // a LeakyRelu consuming this output, which nothing else reads, is part of it + let mut fuse_leaky = |out: &str, joins: &HashMap| -> Result<(Option, String), NetError> { + // Search forward for a LeakyRelu consuming this output + for j in i..nodes.len() { + if fused_indices.contains(&j) { + continue; + } + let next = &nodes[j]; + if next.op_type == "LeakyRelu" && next.input.first().map(String::as_str) == Some(out) && readers.get(out).copied() == Some(1) { + if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") { + return invalid("malformed LeakyRelu"); + } + // only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0 + let alpha = match next.attribute.as_slice() { + [] => 0.01, + [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, + _ => return invalid("LeakyRelu alpha is not a single float"), + }; + let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; + if name.is_empty() || ids.contains_key(&name) || joins.contains_key(&name) { + continue; + } + // Fusing gives the LeakyRelu's output the id of this op. If that output is the graph + // output it must stay the last tensor, so decline the fusion when another node after + // this one emits an operation: it would push the graph output before a later tensor. + if name == output.name.as_str() && nodes[i..].iter().enumerate().any(|(k, n)| i + k != j && emits_op(n.op_type.as_str())) { + continue; + } + fused_indices.insert(j); + return Ok((Some(alpha), name)); } - // only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0 - let alpha = match next.attribute.as_slice() { - [] => 0.01, - [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, - _ => return invalid("LeakyRelu alpha is not a single float"), - }; - i += 1; - let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; - return Ok((Some(alpha), name)); } Ok((None, out.to_string())) }; @@ -147,8 +175,9 @@ fn read_bytes(bytes: &[u8]) -> Result { None => (lookup(src_name)?, None), }; let out = node.output.first().ok_or_else(|| NetError::Invalid("Conv without an output".into()))?; - let (leaky, out_name) = fuse_leaky(out)?; + let (leaky, out_name) = fuse_leaky(out, &joins)?; ids.insert(out_name, this); + shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1))); ops.push(Op::Conv(Conv { src, src2, cin, cout, k: kh, weight: w.1, bias: b, leaky })); } "ConvTranspose" => { @@ -172,8 +201,9 @@ fn read_bytes(bytes: &[u8]) -> Result { } let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("ConvTranspose without an output".into()))?; - let (leaky, out_name) = fuse_leaky(out)?; + let (leaky, out_name) = fuse_leaky(out, &joins)?; ids.insert(out_name, this); + shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1) - 1)); ops.push(Op::ConvT2(ConvT2 { src, cin, cout, weight: w.1, bias: b, leaky })); } "MaxPool" => { @@ -190,8 +220,72 @@ fn read_bytes(bytes: &[u8]) -> Result { let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("MaxPool without an output".into()))?; ids.insert(out.clone(), this); + shapes.push(shapes.get(src).copied().map_or((in_channels, 1), |(c, l)| (c, l + 1))); ops.push(Op::MaxPool2 { src }); } + "Add" => { + let [a, b] = node.input.as_slice() else { return unsupported("Add of other than two tensors") }; + if joins.contains_key(a) || joins.contains_key(b) { + return unsupported("Add reading a Concat output"); + } + if initialisers.contains_key(a.as_str()) || initialisers.contains_key(b.as_str()) { + return unsupported("Add with an initializer operand"); + } + let src = lookup(a)?; + let src2 = lookup(b)?; + let out = node.output.first().ok_or_else(|| NetError::Invalid("Add without an output".into()))?; + let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?; + let (cb, lb) = shapes.get(src2).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?; + if ca != cb || la != lb { + return unsupported("Add of tensors of different shapes"); + } + if ca == 0 { + return invalid("Add with zero channels"); + } + if ca > MAX_CHANNELS { + return unsupported("Add with more than 4096 channels"); + } + ids.insert(out.clone(), this); + shapes.push((ca, la)); + ops.push(Op::Add { src, src2 }); + } + "LeakyRelu" => { + let [a] = node.input.as_slice() else { return invalid("malformed LeakyRelu") }; + if joins.contains_key(a) { + return unsupported("LeakyRelu reading a Concat output"); + } + if initialisers.contains_key(a.as_str()) { + return unsupported("LeakyRelu with an initializer operand"); + } + let src = lookup(a)?; + let out = node.output.first().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; + let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("LeakyRelu reads a tensor with no shape".into()))?; + if ca == 0 { + return invalid("LeakyRelu with zero channels"); + } + if ca > MAX_CHANNELS { + return unsupported("LeakyRelu with more than 4096 channels"); + } + let alpha = match node.attribute.as_slice() { + [] => 0.01, + [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, + _ => return invalid("LeakyRelu alpha is not a single float"), + }; + let nn = ca.checked_mul(ca).ok_or_else(|| NetError::Invalid("LeakyRelu channel count overflows".into()))?; + weights_total = weights_total.saturating_add(nn).saturating_add(ca); + if weights_total > MAX_WEIGHTS { + return invalid("the network has too many weights"); + } + let mut weight = vec![0.0f32; nn]; + for c in 0..ca { + if let Some(w) = weight.get_mut(c * ca + c) { + *w = 1.0; + } + } + ids.insert(out.clone(), this); + shapes.push((ca, la)); + ops.push(Op::Conv(Conv { src, src2: None, cin: ca, cout: ca, k: 1, weight, bias: vec![0.0; ca], leaky: Some(alpha) })); + } "DepthToSpace" => { if attr(node, "blocksize").map(|a| a.i) != Some(2) || attr(node, "mode").map(|a| a.s.as_slice()) != Some(&b"CRD"[..]) { return unsupported("depth-to-space other than block size 2 in CRD order"); @@ -199,6 +293,7 @@ fn read_bytes(bytes: &[u8]) -> Result { let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("DepthToSpace without an output".into()))?; ids.insert(out.clone(), this); + shapes.push(shapes.get(src).copied().map_or((in_channels / 4, -1), |(c, l)| (c / 4, l - 1))); ops.push(Op::DepthToSpace2 { src }); } other => return unsupported(format!("the `{other}` operator")), @@ -222,6 +317,12 @@ fn ints_or(n: &NodeProto, name: &str, default: &[i64]) -> Vec { attr(n, name).map_or_else(|| default.to_vec(), |a| a.ints.clone()) } +/// Whether an ONNX operator node emits a denoise-layer operation. `Concat` does not: it only +/// records a join for the convolution that follows it. +fn emits_op(op_type: &str) -> bool { + matches!(op_type, "Conv" | "ConvTranspose" | "MaxPool" | "Add" | "LeakyRelu" | "DepthToSpace") +} + fn four(dims: &[i64]) -> Result<(usize, usize, usize, usize), NetError> { match dims { [a, b, c, d] if dims.iter().all(|&v| v > 0 && v <= 1 << 20) => Ok((*a as usize, *b as usize, *c as usize, *d as usize)), @@ -297,6 +398,7 @@ fn channel_dim(v: &ValueInfoProto) -> Option { mod tests { use super::*; use crate::synthetic::unet_onnx; + use crate::synthetic_proto::{len_field, value_info_bytes, varint_field}; fn temp_model(name: &str, bytes: &[u8]) -> std::path::PathBuf { let p = std::env::temp_dir().join(format!("lc-denoise-onnx-{name}-{}.onnx", std::process::id())); @@ -304,6 +406,109 @@ mod tests { p } + fn node(op: &str, inputs: &[&str], output: &str, ints: &[(&str, i64)]) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, op.as_bytes(), &mut n); + for (name, value) in ints { + let mut a = Vec::new(); + len_field(1, name.as_bytes(), &mut a); + varint_field(3, *value as u64, &mut a); + varint_field(20, 2, &mut a); + len_field(5, &a, &mut n); + } + n + } + + fn tensor(name: &str, dims: &[u64], values: &[f32]) -> Vec { + let mut t = Vec::new(); + for d in dims { + varint_field(1, *d, &mut t); + } + varint_field(2, 1, &mut t); + len_field(8, name.as_bytes(), &mut t); + let raw: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + len_field(9, &raw, &mut t); + t + } + + fn model(nodes: &[Vec], in_channels: u64, out: &str) -> Vec { + let mut graph = Vec::new(); + for n in nodes { + len_field(1, n, &mut graph); + } + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(in_channels), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes(out, 1, &[Ok(1), Ok(3), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + model + } + + fn varint(mut v: u64, out: &mut Vec) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + + fn node_with_ints(op: &str, inputs: &[&str], output: &str, ints: &[(&str, &[i64])]) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, op.as_bytes(), &mut n); + for &(name, values) in ints { + let mut a = Vec::new(); + len_field(1, name.as_bytes(), &mut a); + // field 8: INTS (wire type 2) - varint-encoded list + varint(8 << 3 | 2, &mut a); + // length of the list in bytes (we'll compute after writing values) + let mut vals = Vec::new(); + for &v in values { + varint(v as u64, &mut vals); + } + varint(vals.len() as u64, &mut a); + a.extend_from_slice(&vals); + // field 20: type = 7 (INTS) + varint_field(20, 7, &mut a); + len_field(5, &a, &mut n); + } + n + } + + fn leaky_relu_node(inputs: &[&str], output: &str, alpha: f32) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, b"LeakyRelu", &mut n); + // alpha attribute: field 1=name, field 2=float value (wire type 5), field 20=type=1 (FLOAT) + let mut a = Vec::new(); + len_field(1, b"alpha", &mut a); + // field 2 with wire type 5 (fixed 4-byte float) + varint(2 << 3 | 5, &mut a); + a.extend_from_slice(&alpha.to_le_bytes()); + // field 20: type = 1 (FLOAT) + varint_field(20, 1, &mut a); + len_field(5, &a, &mut n); + n + } + #[test] fn a_u_net_is_read_with_its_layers_fused() { let (tile, depth) = (32usize, 2usize); @@ -324,6 +529,38 @@ mod tests { let _ = std::fs::remove_file(p); } + #[test] + fn add_operator_model_is_accepted() { + // the convolution output added back to the input, as a residual block does + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + } + #[test] fn a_leaky_relu_alpha_that_is_not_a_float_is_rejected() { let good = unet_onnx(4, 3, 1, 7); @@ -390,4 +627,213 @@ mod tests { // a missing file assert!(read(Path::new("/does/not/exist.onnx")).is_err()); } + + #[test] + fn add_reading_concat_and_oversized_channels_are_unsupported() { + let concat_model = + model(&[node("Concat", &["data", "data"], "joined", &[("axis", 1)]), node("Add", &["joined", "data"], "a1", &[])], 4, "a1"); + assert!(matches!(read_bytes(&concat_model), Err(NetError::Unsupported(_)))); + + let oversized_model = model(&[node("Add", &["data", "data"], "a1", &[])], 4097, "a1"); + assert!(matches!(read_bytes(&oversized_model), Err(NetError::Unsupported(_)))); + + let mut depth = node("DepthToSpace", &["data"], "d", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth); + let zero_model = model(&[depth, node("Add", &["d", "d"], "a1", &[])], 3, "a1"); + assert!(matches!(read_bytes(&zero_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn many_adds_on_a_wide_input_are_accepted_up_to_max_ops() { + // 32 Add nodes on 4096 channels should be accepted (32 < MAX_OPS=512, no weight allocation) + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..32 { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let wide_model = model(&nodes, 4096, &prev); + assert!(read_bytes(&wide_model).is_ok(), "many Add nodes on wide input should be accepted"); + + // But exceeding MAX_OPS should still be rejected + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..=MAX_OPS { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let too_many_model = model(&nodes, 1, &prev); + assert!(matches!(read_bytes(&too_many_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn leaky_relu_with_an_add_residual_branch_is_accepted() { + // the convolution output is read by both the LeakyRelu and the Add residual branch + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("LeakyRelu", &["c1"], "l1", &[]), &mut graph); + len_field(1, &node("Add", &["c1", "l1"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a LeakyRelu residual model was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + } + + #[test] + fn leaky_relu_fuses_across_interleaved_nodes() { + // Conv produces "c1", then an unrelated MaxPool (reading "data") comes between, + // then a LeakyRelu consumes "c1". The fusion should still happen. + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + // Valid MaxPool: 2x2 kernel, stride 2, no padding, no dilation + len_field( + 1, + &node_with_ints( + "MaxPool", + &["data"], + "mp1", + &[("kernel_shape", &[2, 2]), ("strides", &[2, 2]), ("pads", &[0, 0, 0, 0]), ("dilations", &[1, 1])], + ), + &mut graph, + ); + len_field(1, &leaky_relu_node(&["c1"], "l1", 0.2), &mut graph); // alpha=0.2 + let mut depth_to_space = node("DepthToSpace", &["l1"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "LeakyRelu across interleaved nodes was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + // The Conv should have the leaky ReLU fused with alpha=0.2 + let ops = net.ops(); + assert_eq!(ops.len(), 3); // Conv (fused), MaxPool, DepthToSpace + match &ops[0] { + crate::net::Op::Conv(c) => { + assert_eq!(c.leaky, Some(0.2), "LeakyRelu alpha should be fused into Conv"); + } + _ => panic!("first op should be fused Conv"), + } + assert!(matches!(ops[1], crate::net::Op::MaxPool2 { .. })); + assert!(matches!(ops[2], crate::net::Op::DepthToSpace2 { .. })); + } + + #[test] + fn add_with_initializer_operand_is_unsupported() { + let mut graph = Vec::new(); + len_field(1, &node("Add", &["data", "w1"], "a1", &[]), &mut graph); + len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("a1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_)))); + } + + #[test] + fn leaky_relu_with_initializer_operand_is_unsupported() { + let mut graph = Vec::new(); + len_field(1, &node("LeakyRelu", &["w1"], "l1", &[]), &mut graph); + len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("l1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_)))); + } + + #[test] + fn more_than_max_ops_small_adds_are_rejected_as_too_many_layers() { + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..=MAX_OPS { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let many_model = model(&nodes, 1, &prev); + assert!(matches!(read_bytes(&many_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn add_operator_model_is_accepted_review_regression_1() { + // An Add residual block: the convolution output is added back to the input. + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err()); + } } diff --git a/crates/denoise/src/reference.rs b/crates/denoise/src/reference.rs index 488e9a7b7c..351679749b 100644 --- a/crates/denoise/src/reference.rs +++ b/crates/denoise/src/reference.rs @@ -104,6 +104,16 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result, NetError> } T { channels: c.cout, side: out_side, data } } + Op::Add { src, src2 } => { + let a = get(&tensors, *src)?; + let b = get(&tensors, *src2)?; + let (channels, side) = (tensors[a].channels, tensors[a].side); + let mut data = tensor(channels, side, &mut total)?; + for (d, (&av, &bv)) in data.iter_mut().zip(tensors[a].data.iter().zip(&tensors[b].data)) { + *d = av + bv; + } + T { channels, side, data } + } Op::MaxPool2 { src } => { let a = get(&tensors, *src)?; let (channels, side) = (tensors[a].channels, tensors[a].side / 2); diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 995e7c25f0..c6b6065b44 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -7,14 +7,80 @@ //! check between files or photos: the guard adopts it ([`Cancel::Flag`]), so the stack's ✕, `activity.cancel` and the //! job's own Cancel all set the same atomic. Numbers are worded by the frontend from `done`, `total` and [`Unit`]; a //! detail set here is a name (a file, a model), never a sentence, so the frontend can translate everything else. +//! +//! Jobs that must not run side by side share a [`Lane`]. One asked for while its lane is busy can wait in line +//! ([`Activity::enqueue`]): it keeps what it was asked ([`Request`], the command and its parameters) and runs it +//! when the jobs ahead of it are over ([`crate::Session::start_waiting`]), planning its work then, not when it was +//! asked. Nothing waits across another library: the files may have changed meanwhile. use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use serde::Serialize; +use serde_json::Value; /// The longest label or detail kept, in characters (a file name can be anything). const MAX_TEXT: usize = 200; +/// The most tasks waiting in line, in all lanes. +pub const MAX_WAITING: usize = 100; + +/// Jobs that must not run side by side: one waits for those ahead of it to end. Kinds without a lane run as they +/// always did (and are refused while one of their kind runs, where that is the rule). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Lane { + /// Build Previews and Build / Discard Smart Previews: one preview build at a time (`Session::preview_build`). + Previews, +} + +impl Lane { + /// The lane of tasks of `kind` ([`TaskInfo::kind`]). + pub fn of(kind: &str) -> Option { + match kind { + "previews" | "smartPreviews" => Some(Lane::Previews), + _ => None, + } + } +} + +/// What a job was asked: the command and its parameters, with everything that depends on the moment (the +/// selection, the photos in view) written out, so that running it later does the same work. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + pub command: String, + pub params: Value, +} + +/// A task waiting in line ([`Activity::enqueue`]), as [`Activity::take_ready`] hands it over to be started. +#[derive(Debug)] +pub struct Waiting { + pub id: u64, + pub kind: &'static str, + pub label: String, + pub lane: Lane, + pub request: Request, + queued: web_time::Instant, +} + +impl Waiting { + fn info(&self, place: usize) -> TaskInfo { + TaskInfo { + id: self.id, + kind: self.kind, + label: self.label.clone(), + done: 0, + total: 0, + unit: Unit::Count, + detail: String::new(), + cancellable: true, + cancelling: false, + age_ms: millis(self.queued.elapsed()), + waiting: true, + place, + lane: Some(self.lane), + } + } +} /// The background tasks in flight. Cheap to clone (one `Arc`), so worker threads can hold it. #[derive(Clone, Default)] @@ -26,6 +92,10 @@ pub struct Activity { struct Inner { /// Oldest first. tasks: Mutex>>, + /// The tasks waiting in line, in the order they were asked for. + waiting: Mutex>, + /// The id the waiting task being started keeps (its kind, its id): see [`Activity::take_ready`]. + reserved: Mutex>, next: AtomicU64, } @@ -87,6 +157,11 @@ pub struct TaskInfo { /// Cancel was asked for; the job stops at its next check. pub cancelling: bool, pub age_ms: u64, + /// It waits in line for the tasks ahead of it in its lane (nothing done yet: `done` and `total` are 0). + pub waiting: bool, + /// Its place in its lane's line, from 1; 0 for a running task. + pub place: usize, + pub lane: Option, } struct Entry { @@ -162,7 +237,10 @@ impl Entry { detail: lock(&self.detail).clone(), cancellable: self.is_cancellable(), cancelling: self.is_cancelled(), - age_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + age_ms: millis(self.started.elapsed()), + waiting: false, + place: 0, + lane: Lane::of(self.kind), } } } @@ -171,7 +249,9 @@ impl Activity { /// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend /// translates it). pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard { - let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + // a task that waited in line keeps the id it had there + let reserved = lock(&self.inner.reserved).take_if(|(k, _)| *k == kind).map(|(_, id)| id); + let id = reserved.unwrap_or_else(|| self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1)); let cancel = match cancel { Cancel::No => None, Cancel::Yes => Some(Arc::new(AtomicBool::new(false))), @@ -194,23 +274,56 @@ impl Activity { TaskGuard { activity: self.clone(), entry } } - /// Every task in flight, oldest first. + /// Every task in flight, oldest first, then those waiting in line, in the order they were asked for. pub fn list(&self) -> Vec { - lock(&self.inner.tasks).iter().map(|e| e.info()).collect() + let mut rows: Vec = lock(&self.inner.tasks).iter().map(|e| e.info()).collect(); + rows.extend(self.waiting()); + rows } - /// Ask task `id` to stop (it stops at its next check). An unknown id (the task may have just ended) or a task - /// that can't be cancelled is an error. + /// The tasks waiting in line, in the order they were asked for, each with its place in its lane. + pub fn waiting(&self) -> Vec { + let waiting = lock(&self.inner.waiting); + let mut ahead: Vec<(Lane, usize)> = Vec::new(); + waiting + .iter() + .map(|w| { + let place = match ahead.iter_mut().find(|(lane, _)| *lane == w.lane) { + Some((_, n)) => { + *n += 1; + *n + } + None => { + ahead.push((w.lane, 1)); + 1 + } + }; + w.info(place) + }) + .collect() + } + + /// Ask task `id` to stop (it stops at its next check), or take it out of the line if it waits. An unknown id + /// (the task may have just ended) or a task that can't be cancelled is an error. pub fn cancel(&self, id: u64) -> Result<(), String> { + { + let mut waiting = lock(&self.inner.waiting); + if let Some(at) = waiting.iter().position(|w| w.id == id) { + waiting.remove(at); + return Ok(()); + } + } let tasks = lock(&self.inner.tasks); let entry = tasks.iter().find(|e| e.id == id).ok_or_else(|| format!("no task {id}"))?; if entry.try_cancel() { Ok(()) } else { Err(format!("{} can't be cancelled", entry.label)) } } - /// Ask every cancellable task to stop; returns how many were asked. + /// Ask every cancellable task to stop, and empty the line (what waits would start as soon as they stopped); + /// returns how many were asked or taken out. pub fn cancel_all(&self) -> usize { + let dropped = std::mem::take(&mut *lock(&self.inner.waiting)).len(); let tasks = lock(&self.inner.tasks); - tasks.iter().filter(|e| e.try_cancel()).count() + dropped + tasks.iter().filter(|e| e.try_cancel()).count() } /// Whether a task of one of `kinds` is in flight. Its guard's lifetime is the answer: a task that @@ -223,6 +336,74 @@ impl Activity { pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Put a task of `kind` in line behind the others of its lane; it runs `request` when its turn comes. Returns + /// its id and its place in the line. A kind without a lane, or a line already [`MAX_WAITING`] long, is an error. + pub fn enqueue(&self, kind: &'static str, label: &str, request: Request) -> Result<(u64, usize), String> { + let lane = Lane::of(kind).ok_or_else(|| format!("{kind} tasks don't wait in line"))?; + let mut waiting = lock(&self.inner.waiting); + if waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} tasks are waiting already")); + } + let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + waiting.push(Waiting { id, kind, label: capped(label), lane, request, queued: web_time::Instant::now() }); + let place = waiting.iter().filter(|w| w.lane == lane).count(); + Ok((id, place)) + } + + /// Whether a task of `lane` runs now. + pub fn lane_busy(&self, lane: Lane) -> bool { + lock(&self.inner.tasks).iter().any(|e| Lane::of(e.kind) == Some(lane)) + } + + /// Whether a task waits in `lane`'s line. + pub fn lane_waiting(&self, lane: Lane) -> bool { + lock(&self.inner.waiting).iter().any(|w| w.lane == lane) + } + + /// Take the first waiting task whose lane is free out of the line, to be started now. The next task of its + /// kind started ([`Activity::start`]) keeps its id, until [`Activity::started`] says the attempt is over. + pub fn take_ready(&self) -> Option { + self.take_ready_if(|_| true) + } + + /// [`Activity::take_ready`] among the tasks whose request `runs` can run: each frontend starts what it knows how to + /// (the engine its commands, the app its own). Only the first in each lane's line is looked at: one the caller + /// can't run holds its lane, as it would if it had started. + pub fn take_ready_if(&self, runs: impl Fn(&Request) -> bool) -> Option { + let mut waiting = lock(&self.inner.waiting); + let mut held: Vec = lock(&self.inner.tasks).iter().filter_map(|e| Lane::of(e.kind)).collect(); + let mut at = None; + for (i, w) in waiting.iter().enumerate() { + if held.contains(&w.lane) { + continue; + } + if runs(&w.request) { + at = Some(i); + break; + } + held.push(w.lane); + } + let w = waiting.remove(at?); + *lock(&self.inner.reserved) = Some((w.kind, w.id)); + Some(w) + } + + /// The attempt to start the task [`Activity::take_ready`] handed over is over (it started, or it could not). + pub fn started(&self) { + *lock(&self.inner.reserved) = None; + } + + /// Another library was opened: what waited in line was about the old one's photos and folders, so the line + /// empties. Returns how many tasks waited. + pub fn library_changed(&self) -> usize { + std::mem::take(&mut *lock(&self.inner.waiting)).len() + } +} + +/// Milliseconds, saturating. +fn millis(d: std::time::Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -461,4 +642,93 @@ mod tests { std::thread::spawn(move || h.progress(3, 7)).join().unwrap(); assert_eq!((a.list()[0].done, a.list()[0].total), (3, 7)); } + + fn request(command: &str) -> Request { + Request { command: command.into(), params: serde_json::json!({}) } + } + + #[test] + fn a_task_of_a_kind_without_a_lane_does_not_wait() { + let a = Activity::default(); + let e = a.enqueue("export", "Exporting", request("x")).unwrap_err(); + assert!(e.contains("export"), "{e}"); + assert!(a.list().is_empty()); + } + + #[test] + fn the_line_is_bounded_and_lists_places_per_lane() { + let a = Activity::default(); + for place in 1..=MAX_WAITING { + assert_eq!(a.enqueue("previews", "P", request("x")).unwrap().1, place); + } + assert!(a.enqueue("smartPreviews", "S", request("x")).unwrap_err().contains("100")); + let rows = a.list(); + assert_eq!(rows.len(), MAX_WAITING); + assert!(rows.iter().all(|r| r.waiting && r.lane == Some(Lane::Previews))); + assert_eq!(rows.iter().map(|r| r.place).collect::>(), (1..=MAX_WAITING).collect::>()); + } + + #[test] + fn a_waiting_task_starts_when_its_lane_is_free_and_keeps_its_id() { + let a = Activity::default(); + let ahead = a.start("previews", "P", Cancel::Yes); + let (id, _) = a.enqueue("smartPreviews", "S", request("smart")).unwrap(); + assert!(a.lane_busy(Lane::Previews) && a.lane_waiting(Lane::Previews)); + assert!(a.take_ready().is_none(), "the lane is busy: one preview build at a time"); + drop(ahead); + assert!(!a.lane_busy(Lane::Previews)); + let w = a.take_ready().expect("the lane is free"); + assert_eq!((w.id, w.request.command.as_str()), (id, "smart")); + assert!(!a.lane_waiting(Lane::Previews)); + let g = a.start("smartPreviews", "S", Cancel::Yes); + a.started(); + assert_eq!(g.id(), id, "it keeps the id it had in line"); + assert!(!a.list()[0].waiting); + assert_ne!(a.start("export", "E", Cancel::Yes).id(), id); + } + + #[test] + fn an_attempt_that_did_not_start_a_task_gives_its_id_up() { + let a = Activity::default(); + let (id, _) = a.enqueue("previews", "P", request("x")).unwrap(); + let w = a.take_ready().unwrap(); + assert_eq!(w.id, id); + a.started(); // the command failed before starting anything + assert_ne!(a.start("previews", "P", Cancel::Yes).id(), id, "a later task of the kind doesn't take it"); + } + + #[test] + fn take_ready_if_skips_what_the_caller_cannot_run_but_keeps_its_lane_held() { + let a = Activity::default(); + a.enqueue("previews", "mine", request("engine")).unwrap(); + a.enqueue("previews", "next", request("engine")).unwrap(); + assert!(a.take_ready_if(|r| r.command == "other").is_none(), "the first in the lane isn't ours: it holds the lane"); + assert_eq!(a.take_ready_if(|_| true).map(|w| w.label), Some("mine".to_string())); + } + + #[test] + fn cancelling_a_waiting_task_removes_it_and_cancel_all_empties_the_line() { + let a = Activity::default(); + let _running = a.start("previews", "P", Cancel::Yes); + let (first, _) = a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("previews", "B", request("x")).unwrap(); + a.enqueue("smartPreviews", "C", request("x")).unwrap(); + a.cancel(first).unwrap(); + assert!(a.cancel(first).is_err()); + assert_eq!(a.waiting().iter().map(|t| (t.label.as_str(), t.place)).collect::>(), vec![("B", 1), ("C", 2)]); + assert_eq!(a.cancel_all(), 3, "the running one and the two that waited"); + assert!(a.waiting().is_empty() && !a.lane_waiting(Lane::Previews)); + } + + #[test] + fn a_library_change_empties_the_line() { + let a = Activity::default(); + let running = a.start("previews", "P", Cancel::Yes); + a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("smartPreviews", "B", request("x")).unwrap(); + assert_eq!(a.library_changed(), 2); + assert_eq!(a.list().len(), 1, "what runs goes on"); + drop(running); + assert!(a.take_ready().is_none()); + } } diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index d0ffe33fa7..73e2463b00 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -37,7 +37,7 @@ pub(crate) use look_fit::fit_preview; #[cfg(test)] use look_fit::{ FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, at_most, clips_more, correct_vignetting, fit_look, fit_look_with, sony_dro_off_tone, with_dro_off_tone, - without_clipped, + with_pooled_tone, with_profile_colour, without_clipped, }; #[cfg(test)] use mono::{fit_dark_tone, fit_tone_only, monochrome, monochrome_look, to_prophoto}; @@ -50,9 +50,10 @@ use pairs::{ pub(crate) use proxy::LensGeometry; #[cfg(test)] use proxy::{ - Cr3Framing, MIN_PREVIEW_FRACTION, alignment, estimate_cr3_framing, into_lens_geometry, proxies, reference_at, sensor_proxy, structure_agrees, + Cr3Framing, MIN_PREVIEW_FRACTION, THIN_TOLERANCE, alignment, estimate_cr3_framing, extend_tone, into_lens_geometry, proxies, reference_at, + samples_from_proxies, sensor_proxy, structure_agrees, }; -pub(crate) use proxy::{fit_profile, lens_geometry, profile_pairs}; +pub(crate) use proxy::{fit_profile, fit_profile_tone, lens_geometry, profile_samples}; #[cfg(test)] use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; @@ -86,7 +87,11 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black. /// 14: bundled camera profiles also match the Nikon model spellings that differ in case, spacing or the Z8 alias, /// so previews made without the profile are rebuilt. -pub const LOOK_VERSION: u32 = 14; +/// 15: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. +/// 16: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. +/// 17: only a look with the profile's colour continues along its pooled tone curve. +/// 18: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`). +pub const LOOK_VERSION: u32 = 18; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index fac4e2df40..adb7126936 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -1,7 +1,7 @@ use super::colour::{PROXY, file_local_look}; use super::mono::{fit_tone_only_with, monochrome}; use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered}; -use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, proxies, structure_agrees}; +use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, extend_tone, proxies, structure_agrees}; use super::tone::{HighlightCheck, highlights}; use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020}; @@ -26,18 +26,17 @@ pub(crate) fn fit_preview( // Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions, // not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO. let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true); - let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro) { - Some(look) => look, - // A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve - // (`monochrome_look` does it without a profile). - None if colour.is_some() && black_and_white => { - let unclipped = without_clipped(&sensor, &clipped); - let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true }; - let Some(look) = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, colour, &bright) else { return (None, true) }; - look - } - None => return (None, black_and_white), + let pooled = profile.as_ref().and_then(|p| p.tone); + let profile_matrix = colour.as_ref().map(|c| c.0); + let fitted = fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro); + let tone_only = |colour| { + let unclipped = without_clipped(&sensor, &clipped); + let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true }; + fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, Some(colour), &bright) }; + let Some(look) = with_profile_colour(fitted, colour, pooled, tone_only) else { return (None, black_and_white) }; + // the camera's own curve past what this photo's JPEG showed + let look = with_pooled_tone(look, profile_matrix, pooled); let look = if dro { with_dro_off_tone(look) } else { look }; if lightcraft_pipeline::profiling() { eprintln!( @@ -52,6 +51,36 @@ pub(crate) fn fit_preview( (Some(look), black_and_white) } +/// `look` with its tone curve continued along the camera profile's `pooled` one ([`extend_tone`]), when the look +/// takes the profile's colour (`profile_matrix`). A look fitted with the photo's own matrix keeps its curve: the pooled +/// one maps luminance through the profile's matrix, which that photo's colours don't go through. +pub(super) fn with_pooled_tone(look: CameraLook, profile_matrix: Option, pooled: Option) -> CameraLook { + match (pooled, profile_matrix) { + (Some(pooled), Some(matrix)) if look.matrix == matrix => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look }, + _ => look, + } +} + +/// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few +/// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one +/// (`monochrome_look` does it without a profile), else the profile's pooled tone curve, else the default raw one. Dropping the profile there for the +/// neutral fallback left a NIKON D780 frame 3.7 EV under, pushed back up, at 37% of its properly exposed twin's chroma +/// (88-99% with the profile's colour). +pub(super) fn with_profile_colour( + fitted: Option, + colour: Option<(Mat3, Option)>, + pooled: Option, + tone_only: impl FnOnce((Mat3, Option)) -> Option, +) -> Option { + if fitted.is_some() { + return fitted; + } + let colour = colour?; + tone_only(colour.clone()).or_else(|| { + Some(CameraLook { matrix: colour.0, tone: pooled.or_else(lightcraft_pipeline::tone::default_raw_camera_tone)?, hue_sat: colour.1 }) + }) +} + /// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in /// the render's highlight reconstruction. pub(super) const SENSOR_CLIP: f32 = 0.99; diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index e5a9cf06cb..7644a96398 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -1,8 +1,10 @@ use super::colour::{PROFILE_PROXY, PROXY, file_local_look}; use super::hue_sat::fit_hue_sat; use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, correct_vignetting, without_clipped}; -use super::pairs::{collect_pairs, fit_matrix}; -use super::{CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize}; +use super::mono::monochrome; +use super::pairs::{collect_pairs, fit_matrix, luma}; +use super::tone::fit_tone; +use super::{CameraTone, CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize}; /// The embedded preview's long edge must be at least this share of the raw's (and 384 px): a DNG whose preview is a /// small thumbnail is not fitted. The fit itself runs on a proxy of at most 384 px, so the 1024 px preview @@ -314,10 +316,19 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg (apply(&sensor), apply(&clipped)) } -/// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the -/// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own -/// colour matrices, other files or unusable previews. -pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option> { +/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB. +pub(crate) struct ProfileSamples { + /// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020 (empty when the photo has too little colour). + pub colour: Vec<([f64; 3], [f64; 3])>, + /// Tone samples: camera RGB → the camera JPEG's luminance, dark pixels included (as the photo's own toe fit takes + /// them, [`fit_tone_with_shadows`](super::pairs::fit_tone_with_shadows)). + pub tone: Vec<([f64; 3], f64)>, +} + +/// A raw's colour and tone samples for a pooled camera profile (`lightcraft-cli calibrate`): white-balanced camera +/// RGB (with the baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own colour +/// matrices, other files or unusable previews. +pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option { if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) { return None; } @@ -326,8 +337,130 @@ pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeom let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); - let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?; - Some(pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect()) + samples_from_proxies(&sensor, &reference, &to_camera) +} + +/// [`profile_samples`] from a raw's sensor proxy (clipped pixels left out) and its camera JPEG's, `to_camera` taking the +/// sensor proxy back to white-balanced camera RGB. +pub(super) fn samples_from_proxies(sensor: &Rgb32f, reference: &Rgb32f, to_camera: &Mat3) -> Option { + // a black-and-white JPEG went through a monochrome picture style's own mix and curve: nothing for the profile + if monochrome(reference) { + return None; + } + // a dark or colourless photo has no colour pairs but still shows the shadows the pooled curve needs + let colour = collect_pairs(sensor, reference, 0.05, None, false).map_or_else(Vec::new, |(pairs, _)| pairs); + let tone: Vec<_> = sensor + .data + .iter() + .zip(&reference.data) + .filter(|(input, output)| tone_sample(**input, **output)) + .map(|(input, output)| (to_camera.apply(input.map(f64::from)), f64::from(luminance_2020(*output)))) + .collect(); + if colour.is_empty() && tone.is_empty() { + return None; + } + Some(ProfileSamples { colour: colour.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone }) +} + +/// Whether a sensor/JPEG proxy pixel pair can teach the tone curve: every channel above the sensor floor, the JPEG +/// pixel about one 8-bit sRGB code above black (no flat black segment learnt from JPEG compression) and below the +/// highlights (clipped or rolled off). +fn tone_sample(input: [f32; 3], output: [f32; 3]) -> bool { + input.iter().all(|v| v.is_finite() && *v > 0.0001 && *v < 1.5) + && output.iter().all(|v| v.is_finite() && *v >= 0.0) + && (0.0003..0.85).contains(&luminance_2020(output)) +} + +/// A camera profile's tone curve from the tone samples pooled over its photos, through the profile's `matrix`: one +/// curve for the camera, from shadows that only dark photos show to highlights that only bright ones show. Quantile +/// matching ([`fit_tone`]) pools correctly because every photo went through the same camera curve (picture styles and +/// Active D-Lighting aside, which it averages). Luminance is taken with negative channels kept, as the render feeds +/// the curve (raw decoding keeps them, `files::CameraColourModel`). +pub(crate) fn fit_profile_tone(samples: &[([f64; 3], f64)], matrix: &Mat3) -> Option { + fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x)), *y)).filter(|(x, _)| *x > 0.0).collect()) +} + +/// `photo`'s tone curve where its JPEG taught it, `pooled`'s past that: from the photo's last knot it fades over +/// 1 EV (`EXTEND_FADE_EV`) from its own level onto the camera's pooled curve, instead of the bounded shoulder +/// ([`CameraTone::apply`]) whose rate comes from the photo's last two knots. A dark photo's curve ends in the shadows, +/// and that shoulder rendered it, pushed back up, 4-7 L* darker than a properly exposed photo of the same scene. +/// `photo` unchanged when the pooled curve doesn't reach on past it. +pub(super) fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { + /// EV over which the extension moves from the photo's level onto the pooled curve. + const EXTEND_FADE_EV: f32 = 1.0; + /// Knots per EV of the extension. + const EXTEND_KNOTS_PER_EV: f32 = 3.0; + let (own, camera) = (photo.knots(), pooled.knots()); + let (end, last) = (own[31], camera[31][0]); + let span = (last / end[0]).log2(); + if !(span.is_finite() && span > 0.2) { + return *photo; + } + // the photo's own knots, the ones its curve needs least dropped to make room: as many extension knots as keep the + // curve within `THIN_TOLERANCE` where the JPEG taught it, at least 2, else the photo keeps its curve as it is + let Some((extra, own)) = + (2..=((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16)).rev().find_map(|extra| thinned_knots(own, 32 - extra).map(|k| (extra, k))) + else { + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: the photo's curve can't make room for the pooled one, kept as fitted"); + } + return *photo; + }; + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: pooled tone curve joined with {extra} knots past the photo's"); + } + let at_end = pooled.apply(end[0]); + let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 }; + let mut knots = [[0.0f32; 2]; 32]; + let kept = 32 - extra; + for (knot, own) in knots.iter_mut().zip(&own) { + *knot = *own; + } + for k in 1..=extra { + let ev = span * k as f32 / extra as f32; + let x = end[0] * ev.exp2(); + let t = (ev / EXTEND_FADE_EV).clamp(0.0, 1.0); + let w = t * t * (3.0 - 2.0 * t); + knots[kept + k - 1] = [x, pooled.apply(x) * ratio.powf(1.0 - w)]; + } + // monotone and below white whatever the two curves do + let mut floor = 0.0f32; + for knot in &mut knots { + knot[1] = knot[1].max(floor).min(0.999); + floor = knot[1]; + } + CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo) +} + +/// Largest change, in gamma-encoded display values (1/2.2), that thinning a photo's curve for [`extend_tone`] may make +/// where its JPEG taught it: one 8-bit code. +pub(super) const THIN_TOLERANCE: f32 = 1.0 / 255.0; + +/// `knots` thinned to `keep` (first and last kept), dropping one at a time the knot whose removal changes the curve +/// least (`CameraTone::apply` interpolates linearly, so the change peaks at a dropped knot); `None` when that change +/// would exceed [`THIN_TOLERANCE`]. +fn thinned_knots(knots: &[[f32; 2]; 32], keep: usize) -> Option> { + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // the change from leaving out every knot strictly between kept indices `a` and `b` + let gap = |a: usize, b: usize| { + let ([x0, y0], [x1, y1]) = (knots[a], knots[b]); + (a + 1..b) + .map(|i| { + let [x, y] = knots[i]; + let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 }; + (encoded(y0 + t * (y1 - y0)) - encoded(y)).abs() + }) + .fold(0.0f32, f32::max) + }; + let mut kept: Vec = (0..knots.len()).collect(); + while kept.len() > keep.max(2) { + let (i, change) = (1..kept.len() - 1).map(|i| (i, gap(kept[i - 1], kept[i + 1]))).min_by(|a, b| a.1.total_cmp(&b.1))?; + if change > THIN_TOLERANCE { + return None; + } + kept.remove(i); + } + Some(kept.into_iter().map(|i| knots[i]).collect()) } /// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index c2e0ad1e01..4c23ba3d4f 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2457,6 +2457,171 @@ fn dng_tone_fit_takes_lightroom_sized_previews() { assert!(1024.0 >= floor(9504.0), "a 61 MP raw too"); } +#[test] +fn a_photo_no_look_fits_keeps_its_camera_profiles_colour() { + let colour = ( + Mat3([[1.8, -0.6, -0.2], [-0.3, 1.5, -0.2], [0.0, -0.4, 1.4]]), + dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| x).hue_sat, + ); + // too dark for any look, no tone either: the profile's colour, the default raw tone curve + let look = with_profile_colour(None, Some(colour.clone()), None, |_| None).expect("the profile's colour"); + assert_eq!((look.matrix, look.hue_sat.is_some()), (colour.0, true)); + assert_eq!(look.tone, lightcraft_pipeline::tone::default_raw_camera_tone().unwrap()); + // the JPEG's tone curve when it has one + let toned = dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| 0.9 * x); + let look = with_profile_colour(None, Some(colour.clone()), None, |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap(); + assert_eq!((look.matrix, look.tone), (colour.0, toned.tone)); + // a photo's own look wins; without a profile there is nothing to keep (the neutral fallback follows) + let own = with_profile_colour(Some(toned.clone()), Some(colour), None, |_| panic!("the photo's own look is used")).unwrap(); + assert_eq!(own.matrix, toned.matrix); + assert!(with_profile_colour(None, None, None, |_| panic!("no colour to fit")).is_none()); +} + +/// A camera curve: a toe, then a shoulder toward 0.95, the shape camera JPEG curves have. +fn camera_curve(x: f32) -> f32 { + 0.95 * (x / (x + 0.12)).powf(1.3) * 1.1 +} + +fn sampled(curve: impl Fn(f32) -> f32, from: f32, to: f32) -> CameraTone { + CameraTone::new(std::array::from_fn(|i| { + let x = from * (to / from).powf(i as f32 / 31.0); + [x, curve(x)] + })) + .unwrap() +} + +#[test] +fn a_dark_photos_curve_goes_on_along_the_cameras_pooled_one() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + // a dark photo's JPEG showed the curve up to 0.02, 10% darker than the camera's (a picture style) + let photo = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02).with_chroma([1.4, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]).unwrap(); + let tone = extend_tone(&photo, &pooled); + assert_eq!(tone.chroma(), photo.chroma()); + // its own curve where its JPEG taught it, the pooled one from 1 EV past that, a monotone fade in between + for x in [0.001f32, 0.005, 0.01, 0.019] { + assert!((tone.apply(x) - photo.apply(x)).abs() < 0.02 * photo.apply(x), "{x}: {} vs {}", tone.apply(x), photo.apply(x)); + } + for x in [0.05f32, 0.1, 0.3, 0.8] { + assert!((tone.apply(x) - pooled.apply(x)).abs() < 0.01, "{x}: {} vs {}", tone.apply(x), pooled.apply(x)); + } + assert!(tone.knots().windows(2).all(|k| k[1][0] > k[0][0] && k[1][1] >= k[0][1])); + // a photo that already reaches as far keeps its curve + let bright = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.85); + assert_eq!(extend_tone(&bright, &pooled), bright); +} + +#[test] +fn extending_a_photos_curve_keeps_it_where_its_jpeg_taught_it() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // a smooth dark curve, and one with a sharp toe (flat, then a steep rise over two knots) + let smooth = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let toe = CameraTone::new(std::array::from_fn(|i| { + let x = 0.0005 * 40f32.powf(i as f32 / 31.0); + [ + x, + if i < 9 { + 0.001 + 0.0001 * i as f32 + } else if i < 11 { + 0.004 + 0.012 * (i - 8) as f32 + } else { + 0.03 + 0.004 * (i - 10) as f32 + }, + ] + })) + .unwrap(); + for photo in [smooth, toe] { + let tone = extend_tone(&photo, &pooled); + for [x, _] in photo.knots() { + let change = (encoded(tone.apply(*x)) - encoded(photo.apply(*x))).abs(); + assert!(change <= THIN_TOLERANCE + 1e-5, "{x}: {} vs {} ({change})", tone.apply(*x), photo.apply(*x)); + } + } + // the smooth one still goes on along the pooled curve + assert!((extend_tone(&smooth, &pooled).apply(0.3) - pooled.apply(0.3)).abs() < 0.01); +} + +#[test] +fn a_pooled_tone_curve_spans_dark_and_bright_photos() { + // camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve + let matrix = Mat3::IDENTITY; + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let x = if i % 2 == 0 { 0.0005 * 40f64.powf((i / 2) as f64 / 2000.0) } else { 0.02 * 40f64.powf((i / 2) as f64 / 2000.0) }; + ([x; 3], f64::from(camera_curve(x as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.001f32, 0.01, 0.05, 0.2, 0.6] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } + assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples"); +} + +#[test] +fn a_photo_too_dark_for_colour_pairs_still_gives_the_pooled_curve_its_shadows() { + // a scene of saturated colours, its camera JPEG a linear map of the sensor; `level` sets the exposure + let colours = [[0.9, 0.2, 0.1], [0.1, 0.8, 0.2], [0.2, 0.3, 0.9], [0.8, 0.7, 0.1], [0.6, 0.2, 0.7], [0.5, 0.5, 0.5]]; + let scene = |level: f32| { + let sensor = Rgb32f::from_fn(64, 64, |x, y| colours[(x / 8 + y / 8) % colours.len()].map(|v| v * level * (1.0 + (x % 8) as f32 / 16.0))); + let reference = Rgb32f::from_fn(64, 64, |x, y| sensor.data[y * 64 + x].map(|v| v * 0.8)); + (sensor, reference) + }; + let (sensor, reference) = scene(0.3); + let bright = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).unwrap(); + assert!(!bright.colour.is_empty() && !bright.tone.is_empty()); + // every JPEG channel under the colour-pair floor, its luminance still above the tone floor + let (sensor, reference) = scene(0.003); + assert!(reference.data.iter().all(|p| p.iter().all(|v| *v < 0.004))); + let dark = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).expect("tone samples from a dark photo"); + assert!(dark.colour.is_empty() && dark.tone.len() > 1000, "{} colour pairs, {} tone samples", dark.colour.len(), dark.tone.len()); + // a black-and-white camera JPEG gives nothing + let grey = Rgb32f::from_fn(64, 64, |x, y| [luminance_2020(reference.data[y * 64 + x]) * 100.0; 3]); + assert!(samples_from_proxies(&scene(0.3).0, &grey, &Mat3::IDENTITY).is_none()); +} + +#[test] +fn a_pooled_tone_curve_takes_luminance_with_negative_channels_as_the_render_does() { + // a saturating matrix sends this magenta's green channel negative; the render keeps it, so the curve's input + // is the unclamped luminance (clamped, the magenta samples read 30% brighter and pull the pooled quantiles) + let matrix = Mat3([[1.3, -0.2, -0.1], [-0.1, 1.2, -0.1], [-0.1, -0.5, 1.6]]); + let magenta = [0.9, 0.05, 0.9]; + assert!(matrix.apply(magenta)[1] < 0.0); + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let colour = if i % 2 == 0 { magenta } else { [1.0; 3] }; + let x = colour.map(|v| v * 0.001 * 500f64.powf(f64::from(i / 2) / 2000.0)); + (x, f64::from(camera_curve(luma(matrix.apply(x)) as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.002f32, 0.02, 0.1, 0.3] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } +} + +#[test] +fn only_a_look_with_the_profiles_colour_continues_along_its_pooled_curve() { + let profile = Mat3([[1.2, -0.1, -0.1], [-0.1, 1.1, 0.0], [0.0, -0.2, 1.2]]); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let dark = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let with = |matrix| CameraLook { matrix, tone: dark, hue_sat: None }; + // the profile's colour: the curve goes on along the pooled one + assert_eq!(with_pooled_tone(with(profile), Some(profile), Some(pooled)).tone, extend_tone(&dark, &pooled)); + // the photo's own matrix (the profile's colour rejected): its curve as fitted + assert_eq!(with_pooled_tone(with(Mat3::IDENTITY), Some(profile), Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), None, Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), Some(profile), None).tone, dark); +} + +#[test] +fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() { + let colour = (Mat3::IDENTITY, None); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let look = with_profile_colour(None, Some(colour), Some(pooled), |_| None).unwrap(); + assert_eq!(look.tone, pooled); +} + /// Pairs whose scene luminance spans `ratio` from the darkest to the brightest pixel, mapped /// to the JPEG through a steep camera curve (a hazy scene the camera stretches). fn low_contrast_pairs(ratio: f64) -> Vec<(f64, f64)> { diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index ed6e601cd2..26386134a4 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -12,6 +12,7 @@ //! in; a damaged or hostile file is ignored with a warning. They hold aggregate colour statistics //! only, never image content. use lightcraft_color::Mat3; +use lightcraft_pipeline::tone::CameraTone; use lightcraft_raw::profile::HsvTable; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -50,11 +51,21 @@ pub struct CameraProfile { matrix: [[f64; 3]; 3], /// Hue/saturation/value correction after `matrix` (linear ProPhoto RGB). pub hue_sat: Option, + /// The camera's tone curve pooled over the photos (scene luminance after `matrix` → the camera JPEG's): a photo + /// follows it past what its own JPEG shows, and takes it whole when its JPEG teaches no curve. Absent in profiles + /// fitted before it existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tone: Option, } impl CameraProfile { pub fn new(model: &str, files: usize, samples: usize, matrix: Mat3, hue_sat: Option) -> CameraProfile { - CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat } + CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat, tone: None } + } + + /// The profile with its pooled tone curve. + pub fn with_tone(self, tone: Option) -> CameraProfile { + CameraProfile { tone, ..self } } pub fn matrix(&self) -> Mat3 { @@ -263,31 +274,62 @@ fn cache_key_for(directory: Option<&Path>) -> u64 { h.finish().0 as u64 } -/// Per camera model: the photos read and their pooled colour pairs. +/// Per camera model: the photos read and their pooled colour pairs and tone samples. #[derive(Default)] pub struct Pool { - models: HashMap)>, + models: HashMap, } -/// Most colour pairs kept per photo, so a few busy photos can't dominate a profile. +#[derive(Default)] +struct Model { + /// Photos that gave colour pairs (the colour fit's photo count). + files: usize, + /// Photos that gave tone samples only (too dark or colourless for colour pairs). + tone_files: usize, + pairs: Vec<([f64; 3], [f64; 3])>, + tone: Vec<([f64; 3], f64)>, +} + +/// What [`Pool::add`] took from one raw file. +#[derive(Clone, Debug, PartialEq)] +pub struct Added { + pub model: String, + /// Whether it gave colour pairs; `false`: tone samples only, not counted toward a profile's photos. + pub colour: bool, +} + +/// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile. const PAIRS_PER_FILE: usize = 4000; +/// Every `n`-th item, `n` chosen to keep at most [`PAIRS_PER_FILE`]. +fn thinned(items: Vec) -> impl Iterator { + let step = items.len().div_ceil(PAIRS_PER_FILE).max(1); + items.into_iter().step_by(step) +} + impl Pool { - /// Add one raw file's colour pairs. `Ok(None)` when the file can't contribute (not an ARW, - /// NEF or RAF without colour matrices, no usable camera JPEG, too little colour). - pub fn add(&mut self, bytes: &[u8]) -> Result, String> { + /// Add one raw file's colour pairs and tone samples. A photo too dark or colourless for colour pairs still gives + /// its tone samples (the shadows the pooled curve needs) without counting toward the profile's photos. `Ok(None)` + /// when the file can't contribute (not an ARW, NEF or RAF without colour matrices, no usable or a black-and-white + /// camera JPEG). + pub fn add(&mut self, bytes: &[u8]) -> Result, String> { let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?; // colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow // the warp the camera applied to its JPEG) let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; - let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) }; - let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1); + let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) }; let entry = self.models.entry(model.to_owned()).or_default(); - entry.0 += 1; - entry.1.extend(pairs.into_iter().step_by(step)); - Ok(Some(model.to_owned())) + let colour = !samples.colour.is_empty(); + if colour { + entry.files += 1; + entry.pairs.extend(thinned(samples.colour)); + } else { + entry.tone_files += 1; + } + entry.tone.extend(thinned(samples.tone)); + Ok(Some(Added { model: model.to_owned(), colour })) } /// Fit a profile per model with at least `min_files` photos. @@ -296,26 +338,29 @@ impl Pool { models.sort_by(|a, b| a.0.cmp(b.0)); models .into_iter() - .filter(|(_, (files, _))| *files >= min_files) - .map(|(model, (files, pairs))| { - let (matrix, hue_sat) = crate::camera_preview::fit_profile(pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; - Ok(CameraProfile::new(model, *files, pairs.len(), matrix, hue_sat)) + .filter(|(_, m)| m.files >= min_files) + .map(|(model, m)| { + let (matrix, hue_sat) = crate::camera_preview::fit_profile(&m.pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; + let tone = crate::camera_preview::fit_profile_tone(&m.tone, &matrix); + Ok(CameraProfile::new(model, m.files, m.pairs.len(), matrix, hue_sat).with_tone(tone)) }) .collect() } /// Add another pool's photos and pairs (pools filled on separate threads). pub fn merge(&mut self, other: Pool) { - for (model, (files, pairs)) in other.models { + for (model, m) in other.models { let entry = self.models.entry(model).or_default(); - entry.0 += files; - entry.1.extend(pairs); + entry.files += m.files; + entry.tone_files += m.tone_files; + entry.pairs.extend(m.pairs); + entry.tone.extend(m.tone); } } /// Photos read per model. pub fn files(&self) -> Vec<(String, usize)> { - let mut v: Vec<_> = self.models.iter().map(|(m, (n, _))| (m.clone(), *n)).collect(); + let mut v: Vec<_> = self.models.iter().map(|(name, m)| (name.clone(), m.files)).collect(); v.sort(); v } @@ -355,6 +400,14 @@ mod tests { let mut p = profile(); p.version = 99; assert!(bad(p), "unknown version"); + // a pooled tone curve round-trips; a broken one (knots going backwards) is a damaged file + let toned = profile().with_tone(lightcraft_pipeline::tone::default_raw_camera_tone()); + let path = save(&toned, &dir).unwrap(); + assert_eq!(load(&path).unwrap(), toned); + let mut json: serde_json::Value = serde_json::to_value(&toned).unwrap(); + json["tone"]["knots"][3][0] = serde_json::json!(5.0); + std::fs::write(dir.join("bad.json"), serde_json::to_vec(&json).unwrap()).unwrap(); + assert!(load(&dir.join("bad.json")).is_err(), "invalid tone curve"); std::fs::write(dir.join("junk.json"), b"{not json").unwrap(); assert!(load(&dir.join("junk.json")).is_err()); assert!(load(&dir.join("missing.json")).is_err()); diff --git a/crates/engine/src/cmd/activity.rs b/crates/engine/src/cmd/activity.rs index ed4e8d35c7..3fa99b488a 100644 --- a/crates/engine/src/cmd/activity.rs +++ b/crates/engine/src/cmd/activity.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Background Tasks", [], None, - "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first; total 0 = not known yet", + "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for a task of their lane (waiting: true, place: 1 = next in its lane, lane: previews; done and total 0); total 0 = not known yet", always, |s, _| Ok(json!({"tasks": s.activity.list()})) ), @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Cancel Background Task", [], None, - "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). An unknown id (it may have just finished) or a task that can't be cancelled is an error", + "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). A task waiting in line is taken out of it and never runs; all also empties the line. An unknown id (it may have just finished) or a task that can't be cancelled is an error", always, |s, p| { const C: &str = "activity.cancel"; diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 470b00bbd9..feb513636e 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -522,15 +522,29 @@ 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")); } - // compared as the folders are on disk (a differently spelled or linked path to the library - // names the same folder), with the spelling as a fallback where that can't be told + // `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 parents), 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. Compared as + // the folders are on disk (a differently spelled or linked path to the library names the same folder), with + // the spelling as a fallback where that can't be told let same_folder = |l: &Path| { let (lib, chosen) = (l.canonicalize().unwrap_or_else(|_| l.to_path_buf()), src.canonicalize().unwrap_or_else(|_| src.to_path_buf())); - lib.starts_with(&chosen) || chosen.starts_with(&lib) || l.starts_with(src) || src.starts_with(l) + lib.starts_with(&chosen) || chosen.parent() == Some(lib.as_path()) || l.starts_with(src) || src.parent() == Some(l) }; if s.library.as_ref().is_some_and(|l| same_folder(&l.dir)) { return Err("the library's own folders can't be moved here".into()); } + // a folder inside the library reached through a link (or another spelling of the library's path) would move on + // disk, but its photos are stored under the library's own spelling, so the relink below couldn't find them + if let Some(l) = s.library.as_ref() { + let (lib, chosen) = (l.dir.canonicalize().unwrap_or_else(|_| l.dir.clone()), src.canonicalize().unwrap_or_else(|_| src.to_path_buf())); + if chosen.starts_with(&lib) && !src.starts_with(&l.dir) { + return Err(format!("{from}: give the folder's path inside the library as {}", l.dir.display())); + } + } // Repairs retain their exact old paths, including those on surviving history entries. // Complete them before the directory moves; an unavailable repair leaves it in place. s.repair_sidecars_with(&crate::rename::RealFs).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 404e3fbdc8..2d487fcdb3 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, str_param}; -use crate::activity::{Cancel, TaskGuard}; +use crate::activity::{Cancel, Lane, Request, TaskGuard}; use crate::media::{RenderJob, THUMB_SIZES}; use crate::{Result, Session}; @@ -25,6 +25,9 @@ pub struct PreviewBuild { /// Shared with the build's row in the activity stack (its ✕ sets it). pub cancel: Arc, pub finished: AtomicBool, + /// A frontend announced how it ended (the app's toast); one that ended and was not announced is kept when the next + /// build replaces it ([`Session::take_unreported_builds`]). + pub reported: AtomicBool, /// Damaged smart previews rebuilt (Build Smart Previews only). pub repaired: AtomicUsize, /// What is built ("" = previews; "smart previews" — Build Smart Previews runs the same way). @@ -194,19 +197,97 @@ impl Drop for Building { } } -/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). -fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { - let (kind, label) = match state.what { - "" if state.background => ("previews", "Preparing photos in the background"), +/// The row in the activity stack of a build of `what` (as in [`PreviewBuild::what`]), `background`: the background +/// preparation's build ([`PreviewBuild::background`]): its kind and its label. +fn row_of(what: &str, background: bool) -> (&'static str, &'static str) { + match what { + "" if background => ("previews", "Preparing photos in the background"), "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), - }; + } +} + +/// The build's row in the activity stack. +fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { + let (kind, label) = row_of(state.what, state.background); let task = s.activity.start(kind, label, Cancel::Flag(state.cancel.clone())); task.progress(0, state.total as u64); task } +/// A build's state and its row, which go together. However the build ends (it finishes, its worker panics, or the +/// worker can't be started) the state reads as finished first, and then the row goes: a build waiting in line starts +/// when the row is gone, and is refused if the state still said a build runs. A build that did not mark itself +/// finished did not end well: it says so, instead of reading as one that built nothing. +/// (A build asked for with `row: false` has no row: the job that asked shows it.) +struct Running { + state: Arc, + task: Option, +} + +impl Drop for Running { + fn drop(&mut self) { + if !self.state.finished.load(Ordering::Relaxed) { + self.state + .error + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get_or_insert_with(|| "the build stopped unexpectedly".to_string()); + } + self.state.finished.store(true, Ordering::Relaxed); + } +} + +/// Make `state` the session's current build. A build that ended and was not announced yet ([`PreviewBuild::reported`]) +/// is kept for the frontend to announce ([`Session::take_unreported_builds`]), so that starting the next one right +/// after it (as a build waiting in line does) does not lose its result, its failed count or its error. +fn set_current(s: &mut Session, state: Arc) { + if let Some(old) = s.preview_build.replace(state) + && old.finished.load(Ordering::Relaxed) + && !old.reported.load(Ordering::Relaxed) + { + s.keep_unreported_build(old); + } +} + +/// What a build of `ids` was asked, as it runs later (from the line): the photos written out (the selection or the +/// view may have changed by then), in the background (nothing waits for it then), and not queued again. +fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> Request { + let mut params = p.as_object().cloned().unwrap_or_default(); + for key in ["id", "queue", "wait"] { + params.remove(key); + } + params.insert("ids".into(), ids.iter().map(|id| id.0).collect()); + Request { command: command.into(), params: Value::Object(params) } +} + +/// The refusal of a build while another runs, unless the call asks to `queue`. +const REFUSED: &str = "a preview build is already running"; + +/// Builds wait in line ahead of one asked for now (not counting the line a build is being started from). +fn line_ahead(s: &Session) -> bool { + !s.starting_waiting && s.activity.lane_waiting(Lane::Previews) +} + +fn queue_param(p: &Value) -> bool { + p.get("queue").and_then(Value::as_bool).unwrap_or(false) +} + +/// A build asked for with `queue`: while one runs (`busy`: one that does not give way to this one) or others already +/// wait, this one waits in line behind them → `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. +fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, busy: bool, request: &Request) -> Option> { + if !busy && !s.activity.lane_waiting(Lane::Previews) { + return None; + } + if p.get("wait").and_then(Value::as_bool) == Some(true) { + return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); + } + let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); + let (kind, label) = row_of(what, background); + Some(s.activity.enqueue(kind, label, request.clone()).map(|(id, place)| json!({"queued": id, "place": place})).map_err(|e| bad(c, e))) +} + /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. @@ -494,18 +575,26 @@ fn build(s: &mut Session, p: &Value) -> Result { let force = p.get("force").and_then(Value::as_bool).unwrap_or(false); // (`row: false`: the job that asked shows the progress in its own row) let row = p.get("row").and_then(Value::as_bool).unwrap_or(true); + let queue = queue_param(p); // the background preparation gives way to a build that was asked for; nothing replaces a build // that was asked for (it carries on, and the photos it built are skipped by the next). The // background one is stopped only once this request is known to be good (below): a request // with bad ids leaves it running (CodeRabbit on #3544) let mut gives_way = None; + // (a build that runs and does not give way: this one is refused, or waits in line) + let mut busy = false; if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background && !background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + // (nor ahead of builds already waiting: the line starts them after this command, in the order asked; the build + // `start_waiting` is starting itself is not held back by the line it came out of) + if !queue && (busy || line_ahead(s)) { + return Err(bad(C, REFUSED)); + } s.fit_disk_cache(); // explicit ids, else the selected photos (more than one: as the menu says), else everything in // view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu) @@ -514,6 +603,9 @@ fn build(s: &mut Session, p: &Value) -> Result { } else { s.visible_cloned() }; + if queue && let Some(queued) = wait_in_line(s, C, p, "", busy, &request_for(C, p, &ids)) { + return queued; + } let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); // the background build stays the session's until this one has started (a worker that can't // start leaves it running and in place: CodeRabbit on #3544) @@ -529,8 +621,8 @@ fn build(s: &mut Session, p: &Value) -> Result { if let Some(at) = p.get("from").and_then(Value::as_u64) { state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false)); } - s.preview_build = Some(state.clone()); - let task = row.then(|| task_for(s, &state)); + set_current(s, state.clone()); + let run = Running { task: row.then(|| task_for(s, &state)), state: state.clone() }; // the background preparation leaves most of the machine to the photo on screen and the user let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) }; let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); @@ -538,22 +630,22 @@ fn build(s: &mut Session, p: &Value) -> Result { if let Some(cancel) = gives_way { cancel.store(true, Ordering::Relaxed); } - run_all(jobs, &state, task.as_ref(), lanes, force); + run_all(jobs, &run.state, run.task.as_ref(), lanes, force); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) - let st = state.clone(); #[cfg(test)] let started = if test_gate::take_fail_spawn() { - drop(task); + drop(run); Err(std::io::Error::other("no thread (test)")) } else { - std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)) + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)) }; #[cfg(not(test))] - let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)); + let started = + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)); if let Err(e) = started { // never started: not left "running", which would hold every later build back, and the // build it was to replace carries on @@ -767,15 +859,24 @@ fn smart(s: &mut Session, p: &Value) -> Result { // (as Build Previews: the photos named, or the selected ones when more than one is, else // everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577) let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + let queue = background && queue_param(p); // (the background preparation gives way, as to Build Previews: once this one's worker has started) let mut gives_way = None; + let mut busy = false; if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + if background && !queue && (busy || line_ahead(s)) { + return Err(bad(C, REFUSED)); + } + let what = if discard { "discarding smart previews" } else { "smart previews" }; + if queue && let Some(queued) = wait_in_line(s, C, p, what, busy, &request_for(C, p, &ids)) { + return queued; + } let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -790,17 +891,17 @@ fn smart(s: &mut Session, p: &Value) -> Result { } let custom = s.smart_previews_dir.is_some(); if background { - let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); - let previous = s.preview_build.replace(state.clone()); - let task = task_for(s, &state); - let st = state.clone(); + let previous = s.preview_build.clone(); + set_current(s, state.clone()); + // (this build always has its row) + let run = Running { task: Some(task_for(s, &state)), state: state.clone() }; let work = move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + if let Err(e) = smart_run(&dir, custom, discard, jobs, run.task.as_ref().map(|task| (&*run.state, task))) { log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + *run.state.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); } - st.finished.store(true, Ordering::Relaxed); + run.state.finished.store(true, Ordering::Relaxed); }; #[cfg(test)] let started = if test_gate::take_fail_spawn() { @@ -958,7 +1059,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, refreshed, staleKept, newerKept, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool, queue?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, refreshed, staleKept, newerKept, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews). A background one while a preview build runs is refused, or with queue waits in line for it, as library.buildPreviews does → {queued, place}", always, smart ), @@ -985,7 +1086,7 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background; the background preparation gives way to a build asked for): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs", always, build ), @@ -1088,4 +1189,38 @@ mod tests { assert_eq!(r["total"], json!(ids.len())); assert_eq!(r["failed"], json!(0)); } + // Given a build whose worker dies (or can't start), the build reads as finished and its row goes, so that a + // build waiting in line starts instead of being refused as "already running" + #[test] + fn a_build_whose_worker_dies_reads_as_finished_before_its_row_goes() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + assert!(s.activity.lane_busy(crate::activity::Lane::Previews)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _run = run; + panic!("synthetic worker panic"); + })); + assert!(r.is_err()); + assert!(state.finished.load(Ordering::Relaxed)); + assert_eq!(state.error().as_deref(), Some("the build stopped unexpectedly"), "a crash is not a success that built nothing"); + assert!(!s.activity.lane_busy(crate::activity::Lane::Previews)); + } + + // Given a build that marked itself finished, its row going leaves no error + #[test] + fn a_build_that_finished_leaves_no_error() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + state.finished.store(true, Ordering::Relaxed); + drop(run); + assert!(state.error().is_none()); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c7c1528d03..71d2e93321 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -339,6 +339,8 @@ pub struct Session { /// Current time provider (ISO 8601); injectable for tests and wasm. pub clock: Box String + Send>, depth: u32, + /// [`Session::start_waiting`] is starting tasks (the commands it runs don't start more themselves). + starting_waiting: bool, /// Selected mask (Masking panel), by mask id. pub active_mask: Option, /// AI masks (SAM 3): the model and the last photo prepared for it. @@ -418,6 +420,9 @@ pub struct Session { /// The long edge (px) the loupe renders at on this screen, as the frontend last said /// (0: not known). Standard previews are built at least this big, so the loupe can use them. pub loupe_edge: usize, + /// Builds that ended and were replaced by the next one before a frontend announced them + /// ([`Session::take_unreported_builds`]). + unreported_builds: Vec>, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). @@ -529,6 +534,7 @@ impl Session { media: media::MediaCache::default(), clock: Box::new(|| "2026-09-30T12:00:00".to_string()), depth: 0, + starting_waiting: false, active_mask: None, segmenter: segment::Segmenter::default(), active_spot: None, @@ -562,6 +568,7 @@ impl Session { preview_build: None, prep: Default::default(), loupe_edge: 0, + unreported_builds: Vec::new(), slideshow_export: None, import_defaults: import::ImportDefaults::default(), cache_mb: 0, @@ -594,6 +601,15 @@ impl Session { /// Run a command by id. THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let r = self.dispatch(id, params, true); + // a task this command freed the lane of starts now, not at the next frame + self.start_waiting(); + r + } + + /// [`Session::execute`] without starting waiting tasks; `journal`: record the call when the command is journaled + /// (not for a task that waited: the call that asked for it is recorded already). + fn dispatch(&mut self, id: &str, params: &Value, journal: bool) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // a command that validates the photos a call names isn't held back by the selection if !(spec.explicit_targets && cmd::names_photos(params)) { @@ -601,13 +617,49 @@ impl Session { } let empty = Value::Object(Default::default()); let params = if params.is_null() { &empty } else { params }; - self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { + self.run_command(id, (journal && spec.journal).then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { // a shared parameter check ([`Session::targets`]) names the command it ran for EngineError::BadParams { cmd, msg } if cmd.is_empty() => EngineError::BadParams { cmd: id.to_string(), msg }, e => e, }) } + /// A build that ended is replaced by the next one before a frontend announced it: keep it (at most 16; the oldest + /// goes first) for [`Session::take_unreported_builds`]. + pub(crate) fn keep_unreported_build(&mut self, build: std::sync::Arc) { + const KEEP: usize = 16; + if self.unreported_builds.len() >= KEEP { + self.unreported_builds.remove(0); + } + self.unreported_builds.push(build); + } + + /// The builds that ended and were replaced before a frontend announced them, oldest first, once. The frontend + /// announces each (and sets its `reported`) like the current build's end. + pub fn take_unreported_builds(&mut self) -> Vec> { + std::mem::take(&mut self.unreported_builds) + } + + /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was + /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each + /// command; the app also calls it every frame, for a lane that frees while nothing is asked. + pub fn start_waiting(&mut self) { + if self.depth > 0 || self.starting_waiting { + return; + } + self.starting_waiting = true; + // (bounded: each turn takes one task out of a line that is at most this long) + for _ in 0..activity::MAX_WAITING { + let Some(w) = self.activity.take_ready() else { break }; + let r = self.dispatch(&w.request.command, &w.request.params, false); + self.activity.started(); + if let Err(e) = r { + log::warn!("{}: a task that waited could not start: {e}", w.request.command); + } + } + self.starting_waiting = false; + } + /// Run `f` as command `id` with what [`Session::execute`] does around every command: the /// panic guard, auto versions, XMP sidecar auto-write and the durable save (a failed save is /// `NotSaved`). Not journaled. The app's import task commits its batches this way. @@ -1485,6 +1537,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option { } } +#[cfg(test)] +mod lightroom_fixture; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index daca499f6f..3102d66cfe 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -609,6 +609,11 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; self.catalog = catalog; + // nor do tasks waiting in line carry over: they name the old library's photos and folders + let dropped = self.activity.library_changed(); + if dropped > 0 { + log::info!("library: {dropped} task(s) waiting in line were dropped with the old library"); + } // (nothing of the list the last library showed is this one's) self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 511f81f308..4af75bb1a9 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -2,10 +2,10 @@ //! //! Archives use a deterministic JSON representation wrapped in zlib. The JSON //! writer streams through a bounded compressor, so an import cannot first build -//! an unbounded archive buffer. Blob columns are omitted by the catalog reader; -//! decoded XMP, -//! settings, history, snapshots, identities, paths, collections & membership -//! remain available for recovery. +//! an unbounded archive buffer. The catalog reader decodes Lightroom's compressed +//! XMP and history-step and snapshot settings and omits other blob columns, so +//! decoded XMP, settings, history, snapshots, identities, paths, collections & +//! membership remain available for recovery. use std::collections::BTreeMap; use std::fs::{self, File}; @@ -29,6 +29,41 @@ pub const MAX_TOTAL_ARCHIVE_BYTES: u64 = 128 * 1024 * 1024; /// Maximum number of managed archives retained. pub const MAX_MANAGED_ARCHIVES: usize = 8; +/// Why [`store`] stored no archive. +#[derive(Debug)] +pub enum StoreError { + /// The archive would pass [`MAX_ARCHIVE_BYTES`], as JSON or on disk. + TooBig, + /// Anything else, such as a folder or file that can't be written. + Failed(String), +} + +impl From for StoreError { + fn from(why: String) -> Self { + Self::Failed(why) + } +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooBig => write!(f, "{TooBig}"), + Self::Failed(why) => f.write_str(why), + } + } +} + +/// What [`store_best_effort`] kept. +#[derive(Debug, PartialEq, Eq)] +pub enum Kept { + /// The whole archive. + All(PathBuf), + /// The archive without history-step and snapshot settings (`text`): with them it passed [`MAX_ARCHIVE_BYTES`]. + WithoutSettings(PathBuf), + /// No archive: it passed [`MAX_ARCHIVE_BYTES`] even without them. + Nothing, +} + const FORMAT_VERSION: u8 = 1; const HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; const NAME_PREFIX: &str = "lightroom-import-"; @@ -44,13 +79,18 @@ const IO_BUFFER: usize = 16 * 1024; /// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy /// `lightroom-import-*.json` files are deliberately ignored and preserved for /// an explicit caller warning. -pub fn store(directory: &Path, data: &CatalogImport) -> Result { +pub fn store(directory: &Path, data: &CatalogImport) -> Result { + store_with(directory, data, true) +} + +/// [`store`], with the `text` of history steps and snapshots only when `settings`. +fn store_with(directory: &Path, data: &CatalogImport, settings: bool) -> Result { prepare_directory(directory)?; let mut managed = managed_files(directory)?; managed.sort_by_key(|entry| entry.index); let temporary = temporary_path(directory)?; - write_archive(&temporary, data).inspect_err(|_| { + write_archive(&temporary, data, settings).inspect_err(|_| { let _ = remove_managed_file(&temporary); })?; @@ -60,7 +100,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(same) => same, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; if same { @@ -75,20 +115,20 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let index = managed.last().map_or(0, |entry| entry.index.saturating_add(1)); if managed.last().is_some_and(|entry| entry.index == u64::MAX) { let _ = remove_managed_file(&temporary); - return Err("managed Lightroom archive index is exhausted".into()); + return Err(StoreError::Failed("managed Lightroom archive index is exhausted".into())); } let destination = match next_destination(directory, index) { Ok(path) => path, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let size = match fs::metadata(&temporary) { Ok(meta) => meta.len(), Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; let new_entry = Managed { index, path: destination.clone(), size }; @@ -99,40 +139,46 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(retirees) => retirees, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let quarantined = match quarantine(&retirees) { Ok(quarantined) => quarantined, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; if let Err(error) = publish_new(&temporary, &destination) { rollback_quarantine(&quarantined); let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } if let Err(error) = remove_managed_file(&temporary) { - return Err(format!("archive published but temporary cleanup failed: {error}")); + return Err(StoreError::Failed(format!("archive published but temporary cleanup failed: {error}"))); } for (old, held) in quarantined { if let Err(error) = remove_managed_file(&held) { - return Err(format!("archive published but could not retire {}: {error}", old.display())); + return Err(StoreError::Failed(format!("archive published but could not retire {}: {error}", old.display()))); } } Ok(destination) } -/// Store source data when possible. An archive that reaches its bounded size is -/// omitted with a warning so catalog import can still complete. -pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { +/// Store source data when possible, so catalog import can still complete. An archive past +/// [`MAX_ARCHIVE_BYTES`] is stored again without the history-step and snapshot settings, which +/// can be most of a catalog's data; one still too big is not stored at all. +pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result { match store(directory, data) { - Ok(path) => Ok(Some(path)), - Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None), - Err(error) => Err(error), + Ok(path) => return Ok(Kept::All(path)), + Err(StoreError::TooBig) => {} + Err(StoreError::Failed(why)) => return Err(why), + } + match store_with(directory, data, false) { + Ok(path) => Ok(Kept::WithoutSettings(path)), + Err(StoreError::TooBig) => Ok(Kept::Nothing), + Err(StoreError::Failed(why)) => Err(why), } } @@ -213,21 +259,25 @@ fn next_destination(directory: &Path, mut index: u64) -> Result Err("no safe managed archive name available".into()) } -fn write_archive(path: &Path, data: &CatalogImport) -> Result<(), String> { +fn write_archive(path: &Path, data: &CatalogImport, settings: bool) -> Result<(), StoreError> { lightcraft_catalog::safe_file::write_atomic_with(path, &mut |raw| { let mut bounded = BoundedWriter { inner: raw, total: 0 }; bounded.write_all(HEADER)?; let mut compressor = ZlibWriter::new(&mut bounded); - serde_json::to_writer(&mut compressor, &ArchiveRef(data)).map_err(json_io)?; + serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?; compressor.finish()?; Ok(()) }) .map(|_| ()) - .map_err(|error| format!("could not write Lightroom archive: {error}")) + .map_err(|error| match error.get_ref().is_some_and(|inner| inner.is::()) { + true => StoreError::TooBig, + false => StoreError::Failed(format!("could not write Lightroom archive: {error}")), + }) } +/// A write error from the archive writers keeps its own `io::Error`, so [`TooBig`] can still be told apart. fn json_io(error: serde_json::Error) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, error.to_string()) + io::Error::from(error) } struct BoundedWriter<'a> { @@ -251,8 +301,20 @@ impl Write for BoundedWriter<'_> { } } +/// The archive writers' error when the archive would pass [`MAX_ARCHIVE_BYTES`]. +#[derive(Debug)] +struct TooBig; + +impl std::fmt::Display for TooBig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lightroom archive exceeds {} MiB", MAX_ARCHIVE_BYTES >> 20) + } +} + +impl std::error::Error for TooBig {} + fn limit_error() -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, "Lightroom archive exceeds 32 MiB") + io::Error::new(io::ErrorKind::InvalidData, TooBig) } struct ZlibWriter<'a, 'b> { @@ -435,67 +497,70 @@ fn remove_managed_file(path: &Path) -> io::Result<()> { fs::remove_file(path) } -struct ArchiveRef<'a>(&'a CatalogImport); +/// The archive of a catalog import, with the `text` of history steps and snapshots only when `.1`. +struct ArchiveRef<'a>(&'a CatalogImport, bool); impl Serialize for ArchiveRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_struct("CatalogImportArchive", 7)?; out.serialize_field("version", &FORMAT_VERSION)?; out.serialize_field("source", &self.0.source)?; - out.serialize_field("photos", &PhotoSeq(&self.0.photos))?; - out.serialize_field("collections", &RowSeq(&self.0.collections))?; - out.serialize_field("members", &RowSeq(&self.0.members))?; - out.serialize_field("collection_content", &RowSeq(&self.0.collection_content))?; + out.serialize_field("photos", &PhotoSeq(&self.0.photos, self.1))?; + out.serialize_field("collections", &RowSeq(&self.0.collections, None))?; + out.serialize_field("members", &RowSeq(&self.0.members, None))?; + out.serialize_field("collection_content", &RowSeq(&self.0.collection_content, None))?; out.serialize_field("warnings", &self.0.warnings)?; out.end() } } -struct PhotoSeq<'a>(&'a [CatalogPhoto]); +struct PhotoSeq<'a>(&'a [CatalogPhoto], bool); impl Serialize for PhotoSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for photo in self.0 { - out.serialize_element(&PhotoRef(photo))?; + out.serialize_element(&PhotoRef(photo, self.1))?; } out.end() } } -struct PhotoRef<'a>(&'a CatalogPhoto); +struct PhotoRef<'a>(&'a CatalogPhoto, bool); impl Serialize for PhotoRef<'_> { fn serialize(&self, serializer: S) -> Result { let p = self.0; + let skip = (!self.1).then_some("text"); let mut out = serializer.serialize_struct("CatalogPhotoArchive", 8)?; out.serialize_field("source_id", &p.source_id)?; out.serialize_field("uuid", &p.uuid)?; out.serialize_field("path", &p.path)?; - out.serialize_field("image", &RowRef(&p.image))?; + out.serialize_field("image", &RowRef(&p.image, None))?; out.serialize_field("settings", &p.settings)?; out.serialize_field("xmp", &p.xmp)?; out.serialize_field("keywords", &p.keywords)?; - out.serialize_field("history", &RowSeq(&p.history))?; - out.serialize_field("snapshots", &RowSeq(&p.snapshots))?; + out.serialize_field("history", &RowSeq(&p.history, skip))?; + out.serialize_field("snapshots", &RowSeq(&p.snapshots, skip))?; out.end() } } -struct RowSeq<'a>(&'a [BTreeMap]); +/// Rows, each without the column `.1` names. +struct RowSeq<'a>(&'a [BTreeMap], Option<&'a str>); impl Serialize for RowSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for row in self.0 { - out.serialize_element(&RowRef(row))?; + out.serialize_element(&RowRef(row, self.1))?; } out.end() } } -struct RowRef<'a>(&'a BTreeMap); +struct RowRef<'a>(&'a BTreeMap, Option<&'a str>); impl Serialize for RowRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_map(None)?; - for (key, value) in self.0 { + for (key, value) in self.0.iter().filter(|(key, _)| Some(key.as_str()) != self.1) { out.serialize_entry(key, value)?; } out.end() @@ -608,40 +673,84 @@ mod tests { fn rejects_oversize_before_creating_archive() { let path = tempdir(); let input = data("x".repeat((MAX_ARCHIVE_BYTES as usize) + 1)); - assert!(store(&path, &input).is_err()); + assert!(matches!(store(&path, &input), Err(StoreError::TooBig)), "an oversize archive is told apart by its error"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } - #[test] - fn large_catalog_history_is_best_effort_and_does_not_abort_import() { - let path = tempdir(); + /// 5,000 photos with 8 KiB of history settings each: about 40 MiB of JSON. + fn large_catalog(history: bool) -> CatalogImport { let mut input = data("catalog.lrcat".into()); input.photos = (0..5_000) - .map(|index| CatalogPhoto { - source_id: index, - uuid: format!("photo-{index}"), - path: format!("/photos/{index}.raw"), - image: BTreeMap::new(), - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])], - snapshots: Vec::new(), - original: crate::lightroom_catalog::Original::Local, + .map(|index| { + let bulk = format!("history-{index}-{}", "x".repeat(8 * 1024)); + CatalogPhoto { + source_id: index, + uuid: format!("photo-{index}"), + path: format!("/photos/{index}.raw"), + image: BTreeMap::new(), + settings: if history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![BTreeMap::from([ + ("name".into(), serde_json::json!("Exposure")), + ("text".into(), serde_json::json!(if history { bulk.as_str() } else { "s = {}" })), + ])], + snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])], + original: crate::lightroom_catalog::Original::Local, + } }) .collect(); - assert_eq!(store_best_effort(&path, &input).unwrap(), None); + input + } + + #[test] + fn an_archive_too_big_with_its_history_settings_is_kept_without_them() { + let path = tempdir(); + let kept = store_best_effort(&path, &large_catalog(true)).unwrap(); + let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") }; + let decoded = crate::lightroom_fixture::read_archive(&archive); + let photos = decoded["photos"].as_array().unwrap(); + assert_eq!(photos.len(), 5_000, "every photo is still archived"); + assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7")); + assert_eq!(photos[7]["history"], serde_json::json!([{"name": "Exposure"}]), "history steps keep everything but their settings"); + assert_eq!(photos[7]["snapshots"], serde_json::json!([{"name": "Before"}]), "and so do snapshots"); + assert_eq!(fs::read_dir(&path).unwrap().count(), 1, "the first, too big try leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + + #[test] + fn large_catalog_is_best_effort_and_does_not_abort_import() { + let path = tempdir(); + assert_eq!(store_best_effort(&path, &large_catalog(false)).unwrap(), Kept::Nothing, "too big even without history settings"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } + /// Only the size limit leads to a smaller archive or none: any other failure is reported as such. + #[test] + fn a_write_failure_is_not_taken_for_an_oversize_archive() { + let path = tempdir(); + let file = path.join("not-a-folder"); + fs::write(&file, b"x").unwrap(); + assert!(matches!(store(&file, &rich_data()), Err(StoreError::Failed(_))), "a folder that can't be made"); + let folder = path.join("Interop"); + { + let _full = lightcraft_catalog::safe_file::fail_writes_after(0); + assert!(matches!(store(&folder, &rich_data()), Err(StoreError::Failed(_))), "a full disk while writing"); + assert!(store_best_effort(&folder, &rich_data()).is_err(), "a failure is an error, not a skipped archive"); + } + assert_eq!(fs::read_dir(&folder).unwrap().count(), 0, "a failed write leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + #[test] fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() { let path = tempdir(); let archive = store(&path, &rich_data()).unwrap(); let bytes = fs::read(archive).unwrap(); assert!(bytes.starts_with(HEADER)); + assert_eq!(crate::lightroom_fixture::ARCHIVE_HEADER, HEADER, "the fixture reads archives with this module's header"); let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); let decoded: Value = serde_json::from_slice(&json).unwrap(); assert_eq!(decoded["version"], serde_json::json!(FORMAT_VERSION)); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 71721af264..914c70c7c9 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -48,8 +48,31 @@ struct Reader { db: Database, tables: Vec, } +/// Most bytes of history-step or snapshot settings decoded from one table. They are only archived, and an archive +/// holds at most [`crate::lightroom_archive::MAX_ARCHIVE_BYTES`] of JSON, so this keeps all a catalog can archive while +/// a hostile one can't make the reader allocate without bound (each row alone may decode to 16 MiB). +const MAX_DECODED_SETTINGS: usize = crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize; + +/// The column of table `name` that Lightroom Classic 13 and later store as compressed text (see [`decode_compressed`]), +/// and what a warning calls one and several of its rows. +fn compressed_settings(name: &str) -> Option<(&'static str, &'static str, &'static str)> { + match name { + "Adobe_libraryImageDevelopHistoryStep" => Some(("text", "history step", "history steps")), + "Adobe_libraryImageDevelopSnapshot" => Some(("text", "snapshot", "snapshots")), + _ => None, + } +} + impl Reader { - fn table(&self, name: &str, required: bool) -> Result, String> { + fn table(&self, name: &str, required: bool, warnings: &mut Vec) -> Result, String> { + self.table_within(name, required, MAX_DECODED_SETTINGS, warnings) + } + + /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded within `budget` + /// bytes for the whole table: each value is charged its declared length before it is inflated, even one that then + /// fails to decode. A value that can't be decoded is left out of its row with a warning naming the image, and + /// those past the budget with one warning for all. Other BLOB columns are always left out. + fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec) -> Result, String> { let Some(t) = self.tables.iter().find(|t| t.name == name) else { return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; }; @@ -58,37 +81,69 @@ impl Reader { if rows.len() > 1_000_000 { return Err(format!("{name}: more than one million records")); } - Ok(rows - .into_iter() - .map(|r| { - columns - .iter() - .cloned() - .zip(r.values.into_iter().map(|v| match v { - SqlValue::Null => Some(Value::Null), - SqlValue::Integer(n) => Some(json!(n)), - SqlValue::Real(n) => Some(json!(n)), - SqlValue::Text(s) => Some(json!(s)), - // Opaque Lightroom payloads never become JSON byte arrays. - SqlValue::Blob(_) => None, - })) - .filter_map(|(column, value)| value.map(|value| (column, value))) - .collect() - }) - .collect()) + let compressed = compressed_settings(name); + let mut left = budget; + let mut over_budget = 0usize; + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let mut row = Row::new(); + let mut settings = None; + for (column, value) in columns.iter().zip(r.values) { + let value = match value { + SqlValue::Null => Value::Null, + SqlValue::Integer(n) => json!(n), + SqlValue::Real(n) => json!(n), + SqlValue::Text(s) => json!(s), + SqlValue::Blob(bytes) => { + if compressed.is_some_and(|(settings_column, _, _)| settings_column == column) { + settings = Some((column, bytes)); + } + // Other opaque Lightroom payloads never become JSON byte arrays. + continue; + } + }; + row.insert(column.clone(), value); + } + if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) { + // charged at its declared length before it is inflated (which never goes past that length), so + // a row that then fails to decode counts too; past the budget, the rest aren't inflated at all + let declared = compressed_len(&bytes); + if declared.is_some_and(|n| over_budget > 0 || n > left) { + over_budget += 1; + } else { + left -= declared.unwrap_or(0); + match decode_compressed(&bytes, "settings") { + Ok(text) => { + row.insert(column.clone(), Value::String(text)); + } + Err(why) => warnings.push(format!( + "image {}: {what} {}: {why}; archived without its settings", + number(&row, "image"), + number(&row, "id_local") + )), + } + } + } + out.push(row); + } + if let (Some((_, one, many)), 1..) = (compressed, over_budget) { + let what = if over_budget == 1 { one } else { many }; + warnings.push(format!("{over_budget} {what} archived without their settings: more than {} MiB of settings in {name}", budget >> 20)); + } + Ok(out) } /// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None` /// when the table or the value is missing or doesn't look like an id. fn catalog_id(&self) -> Option { - let rows = self.table("Adobe_variablesTable", false).ok()?; + let rows = self.table("Adobe_variablesTable", false, &mut Vec::new()).ok()?; let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?; let id = text(row, "value").trim(); (!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string()) } fn optional_table(&self, name: &str, warnings: &mut Vec) -> Result, String> { - match self.table(name, false) { + match self.table(name, false, warnings) { Ok(rows) => Ok(rows), Err(error) => { warnings.push(format!("skipping optional Lightroom table {name}: {error}")); @@ -125,7 +180,7 @@ impl Reader { SqlValue::Integer(n) => Some(json!(n)), SqlValue::Real(n) => Some(json!(n)), SqlValue::Text(s) => Some(json!(s)), - SqlValue::Blob(bytes) if column == "xmp" => match decode_xmp_bytes(&bytes) { + SqlValue::Blob(bytes) if column == "xmp" => match decode_compressed(&bytes, "XMP") { Ok(packet) => Some(Value::String(packet)), Err(error) => { warnings.push(format!("image {image}: {error}")); @@ -352,17 +407,27 @@ fn xmp(v: Option<&Value>) -> Result { } } -fn decode_xmp_bytes(bytes: &[u8]) -> Result { - let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or("truncated XMP header")?; - if size > 16 << 20 { - return Err("XMP packet exceeds 16 MiB".into()); +/// The decoded length [`decode_compressed`] reads from `bytes`' header, when it has one of at most 16 MiB. +fn compressed_len(bytes: &[u8]) -> Option { + let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes)?; + usize::try_from(size).ok().filter(|size| *size <= 16 << 20) +} + +/// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom +/// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it +/// `what`. +fn decode_compressed(bytes: &[u8], what: &str) -> Result { + if bytes.len() < 4 { + return Err(format!("truncated {what} header")); } - let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or("truncated XMP")?, 16 << 20) - .map_err(|_| "invalid compressed XMP")?; - if decoded.len() != size as usize { - return Err("XMP packet length mismatch".into()); + let size = compressed_len(bytes).ok_or_else(|| format!("{what} longer than 16 MiB"))?; + // inflated no further than its declared length: a stream that goes on is invalid, at no more cost than a valid one + let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, size) + .map_err(|_| format!("invalid compressed {what}"))?; + if decoded.len() != size { + return Err(format!("{what} length mismatch")); } - String::from_utf8(decoded).map_err(|e| e.to_string()) + String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}")) } // SQLite file format §4: validate the live checksum chain in constant space, then overlay @@ -482,9 +547,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d } let reader = Reader { tables: db.live_tables()?, db }; let mut warnings = Vec::new(); - let table = |name: &str, required: bool| -> Result, String> { + let table = |name: &str, required: bool, warnings: &mut Vec| -> Result, String> { ensure_read_active(cancel)?; - let rows = reader.table(name, required)?; + let rows = reader.table(name, required, warnings)?; done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; @@ -494,9 +559,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let roots: HashMap<_, _> = table("AgLibraryRootFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let folders: HashMap<_, _> = table("AgLibraryFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let files: HashMap<_, _> = table("AgLibraryFile", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)? .into_iter() .map(|r| (number(&r, "image"), text(&r, "text").to_string())) @@ -580,7 +645,7 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); - for image in table("Adobe_images", true)? { + for image in table("Adobe_images", true, &mut out.warnings)? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { @@ -947,7 +1012,7 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?; + let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(|e| error(e.to_string()))).transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index fefc9577ae..3503960858 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -2012,3 +2012,62 @@ fn oversized_optional_table_warns_and_is_skipped() { assert!(rows.is_empty()); assert!(warnings.iter().any(|warning| warning.contains("optional_history"))); } + +/// A catalog whose settings decode to more than the budget keeps every row, archives the settings that fit, and +/// says once how many it left out, instead of allocating whatever its BLOBs inflate to. +#[test] +fn settings_past_the_decode_budget_are_left_out_with_one_warning() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget"); + let catalog = dir.join("test.lrcat"); + let big = "x".repeat(512 << 10); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(fixture::compressed(&big)))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!(rows.iter().filter(|r| r.contains_key("text")).count(), 2, "the two steps within 1 MiB keep their settings"); + assert_eq!(warnings, ["2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// A stream that inflates past the length its header declares is stopped there, not inflated up to 16 MiB first. +#[test] +fn a_stream_longer_than_its_declared_length_is_stopped_at_that_length() { + let mut bytes = 10u32.to_be_bytes().to_vec(); + bytes.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&bytes, "settings"), Err("invalid compressed settings".to_string())); + let mut exact = 1024u32.to_be_bytes().to_vec(); + exact.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&exact, "settings").map(|text| text.len()), Ok(1024), "exactly its length decodes"); +} + +/// Settings that fail to decode still cost their declared length, so a catalog of damaged rows can't make the +/// reader inflate without bound: past the budget, the rest are left out without being inflated. +#[test] +fn settings_that_fail_to_decode_still_count_against_the_budget() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget-bad"); + let catalog = dir.join("test.lrcat"); + let mut damaged = (512u32 << 10).to_be_bytes().to_vec(); + damaged.extend([1, 2, 3]); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(damaged.clone()))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!( + warnings, + [ + "image 1: history step 1: invalid compressed settings; archived without its settings", + "image 1: history step 2: invalid compressed settings; archived without its settings", + "2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep", + ], + "the two damaged steps within 1 MiB are tried; the other two aren't" + ); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs new file mode 100644 index 0000000000..ce8325a91e --- /dev/null +++ b/crates/engine/src/lightroom_fixture.rs @@ -0,0 +1,259 @@ +//! Synthetic Lightroom catalogs for tests: a small SQLite file written page by page, so the catalog reader is tested +//! on the bytes it reads in the field (text and BLOB cells, Lightroom's compressed encoding) with no SQLite library. +//! Each table is one leaf page; rows must fit in it without overflow pages. + +use std::path::{Path, PathBuf}; + +const PAGE_SIZE: usize = 4096; +/// The largest record a 4096-byte table leaf holds without an overflow page (SQLite file format §1.6: U - 35). +const MAX_LOCAL: usize = PAGE_SIZE - 35; + +#[derive(Clone, Debug)] +pub(crate) enum Field { + Null, + Integer(i64), + Real(f64), + Text(String), + Blob(Vec), +} + +pub(crate) fn text(s: &str) -> Field { + Field::Text(s.into()) +} + +pub(crate) struct Table { + pub name: &'static str, + /// The column list of its `CREATE TABLE`, as Lightroom writes it. + pub columns: &'static str, + pub rows: Vec>, +} + +/// Lightroom Classic's compressed text (as in `Adobe_AdditionalMetadata.xmp`, and history steps and snapshots since +/// Lightroom Classic 13): the decoded length as 4 big-endian bytes, then the zlib stream. +pub(crate) fn compressed(text: &str) -> Vec { + compressed_bytes(text.as_bytes()) +} + +/// [`compressed`] for any bytes, including ones that aren't UTF-8. +pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec { + let mut out = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + out.extend(miniz_oxide::deflate::compress_to_vec_zlib(bytes, 6)); + out +} + +pub(crate) const HISTORY_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, dateCreated, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, name, relValueString, text, valueString"; +pub(crate) const SNAPSHOT_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, locked, name, snapshotID, text"; + +/// A history step row for image `image` (columns as in [`HISTORY_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn history_step(id: i64, image: i64, date: f64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("history-{id}")), + Field::Real(date), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + text(name), + Field::Null, + settings, + Field::Null, + ] +} + +/// A snapshot row for image `image` (columns as in [`SNAPSHOT_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn snapshot(id: i64, image: i64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("snapshot-{id}")), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + Field::Null, + text(name), + Field::Null, + settings, + ] +} + +/// The tables of a catalog with one photo, image 1 (`/Photos/test.ARW`, not created), with the develop +/// settings `settings`. Add history, snapshot or other tables and pass them all to [`write`]. +pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec { + let mut root = originals.to_string_lossy().into_owned(); + if !root.ends_with('/') { + root.push('/'); + } + vec![ + Table { + name: "AgLibraryRootFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, absolutePath UNIQUE NOT NULL DEFAULT '', name NOT NULL DEFAULT '', relativePathFromCatalog", + rows: vec![vec![Field::Integer(1), text("root-1"), Field::Text(root), text("originals"), Field::Null]], + }, + Table { + name: "AgLibraryFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, pathFromRoot NOT NULL DEFAULT '', rootFolder INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![Field::Integer(1), text("folder-1"), text("Photos/"), Field::Integer(1)]], + }, + Table { + name: "AgLibraryFile", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, baseName NOT NULL DEFAULT '', extension NOT NULL DEFAULT '', folder INTEGER NOT NULL DEFAULT 0, idx_filename NOT NULL DEFAULT ''", + rows: vec![vec![Field::Integer(1), text("file-1"), text("test"), text("ARW"), Field::Integer(1), text("test.ARW")]], + }, + Table { + name: "Adobe_images", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, fileFormat NOT NULL DEFAULT 'unset', fileHeight, fileWidth, masterImage INTEGER, pick NOT NULL DEFAULT 0, rating, rootFile INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![ + Field::Integer(1), + text("image-1"), + text("RAW"), + Field::Integer(10), + Field::Integer(20), + Field::Null, + Field::Integer(0), + Field::Null, + Field::Integer(1), + ]], + }, + Table { + name: "Adobe_imageDevelopSettings", + columns: "id_local INTEGER PRIMARY KEY, image INTEGER, text", + rows: vec![vec![Field::Integer(1), Field::Integer(1), text(settings)]], + }, + ] +} + +/// The format header an import archive starts with (`lightroom_archive`'s), before its zlib-compressed JSON. +pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; + +/// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped +/// at `MAX_ARCHIVE_BYTES` too, so that is the most it can inflate to. +pub(crate) fn read_archive(path: &Path) -> serde_json::Value { + let bytes = std::fs::read(path).unwrap(); + let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display())); + serde_json::from_slice( + &miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize).unwrap(), + ) + .unwrap() +} + +/// A new, empty folder for one test's catalog. +pub(crate) fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Write `tables` as a SQLite database at `path`: page 1 holds the schema, table `i` page `i + 2`. +pub(crate) fn write(path: &Path, tables: &[Table]) { + let mut schema = Vec::new(); + let mut pages = Vec::new(); + for (i, table) in tables.iter().enumerate() { + let root = i64::try_from(i + 2).unwrap(); + schema.push(vec![ + text("table"), + text(table.name), + text(table.name), + Field::Integer(root), + Field::Text(format!("CREATE TABLE {}({})", table.name, table.columns)), + ]); + pages.push(leaf(0, &table.rows, table.name)); + } + let mut first = leaf(100, &schema, "sqlite_master"); + first[..16].copy_from_slice(b"SQLite format 3\0"); + first[16..18].copy_from_slice(&u16::try_from(PAGE_SIZE).unwrap().to_be_bytes()); + first[18] = 1; // legacy journal mode: no WAL file is read unless it exists + first[19] = 1; + first[21] = 64; + first[22] = 32; + first[23] = 32; + first[24..28].copy_from_slice(&1u32.to_be_bytes()); + first[28..32].copy_from_slice(&u32::try_from(pages.len() + 1).unwrap().to_be_bytes()); + first[40..44].copy_from_slice(&1u32.to_be_bytes()); + first[44..48].copy_from_slice(&4u32.to_be_bytes()); + first[56..60].copy_from_slice(&1u32.to_be_bytes()); // UTF-8 + first[92..96].copy_from_slice(&1u32.to_be_bytes()); + first[96..100].copy_from_slice(&3_045_000u32.to_be_bytes()); + let mut bytes = first; + for page in pages { + bytes.extend(page); + } + std::fs::write(path, bytes).unwrap(); +} + +fn leaf(base: usize, rows: &[Vec], table: &str) -> Vec { + let mut page = vec![0u8; PAGE_SIZE]; + page[base] = 0x0d; + page[base + 3..base + 5].copy_from_slice(&u16::try_from(rows.len()).unwrap().to_be_bytes()); + let mut end = PAGE_SIZE; + for (i, values) in rows.iter().enumerate() { + let payload = record(values); + assert!(payload.len() <= MAX_LOCAL, "{table} row {i}: {} bytes needs an overflow page, which the fixture doesn't write", payload.len()); + let rowid = match values.first() { + Some(Field::Integer(id)) => u64::try_from(*id).unwrap(), + _ => u64::try_from(i + 1).unwrap(), + }; + let mut cell = varint(u64::try_from(payload.len()).unwrap()); + cell.extend(varint(rowid)); + cell.extend(payload); + let pointers_end = base + 8 + (i + 1) * 2; + end = end.checked_sub(cell.len()).filter(|e| *e >= pointers_end).unwrap_or_else(|| panic!("{table}: rows don't fit in one page")); + page[end..end + cell.len()].copy_from_slice(&cell); + page[pointers_end - 2..pointers_end].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + } + page[base + 5..base + 7].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + page +} + +/// A record (SQLite file format §2.1). An `INTEGER PRIMARY KEY` column's value is the rowid, stored as NULL. +fn record(values: &[Field]) -> Vec { + let mut serials = Vec::new(); + let mut body = Vec::new(); + for (i, value) in values.iter().enumerate() { + let serial = match value { + Field::Integer(_) if i == 0 => 0, + Field::Null => 0, + Field::Integer(n) => { + body.extend(n.to_be_bytes()); + 6 + } + Field::Real(n) => { + body.extend(n.to_be_bytes()); + 7 + } + Field::Text(s) => { + body.extend(s.as_bytes()); + 13 + 2 * u64::try_from(s.len()).unwrap() + } + Field::Blob(b) => { + body.extend(b); + 12 + 2 * u64::try_from(b.len()).unwrap() + } + }; + serials.extend(varint(serial)); + } + // the header length counts its own varint + let mut header_len = serials.len() + 1; + if varint(u64::try_from(header_len).unwrap()).len() > 1 { + header_len += 1; + } + let mut out = varint(u64::try_from(header_len).unwrap()); + out.extend(serials); + out.extend(body); + out +} + +/// SQLite's big-endian varint (values below 2^56, which is all a fixture needs). +fn varint(mut value: u64) -> Vec { + let mut out = vec![(value & 0x7f) as u8]; + value >>= 7; + while value != 0 { + out.push((value & 0x7f) as u8 | 0x80); + value >>= 7; + } + out.reverse(); + out +} diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 7a039fe0f1..695398bcc6 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError { } fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { - let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten(); - if archive_dir.is_some() && archive_path.is_none() { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); - } - Ok(archive_path) + use crate::lightroom_archive::{Kept, MAX_ARCHIVE_BYTES}; + let Some(dir) = archive_dir else { return Ok(None) }; + let limit = MAX_ARCHIVE_BYTES >> 20; + Ok(match crate::lightroom_archive::store_best_effort(dir, data).map_err(error)? { + Kept::All(path) => Some(path), + Kept::WithoutSettings(path) => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archived without history-step and snapshot settings")); + Some(path) + } + Kept::Nothing => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archive skipped")); + None + } + }) } /// Memory identity of the library which owns a prepared completion. @@ -521,59 +530,67 @@ mod tests { assert_eq!(session.undo.len(), 3); } + /// 5,000 photos with 8 KiB each of history settings (`in_history`) or develop settings: about 40 MiB of JSON. An + /// archive too big with its history settings is kept without them; one too big even then is skipped. Either + /// way the import goes on and says so. #[test] - fn oversized_history_archive_keeps_prepared_import_successful_with_warning() { - let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{}", std::process::id())); - let mut data = empty_data(); - data.photos = (0..5_000) - .map(|source_id| { - let image = std::collections::BTreeMap::from([ - ("id_local".into(), serde_json::json!(source_id)), - ("fileFormat".into(), serde_json::json!("JPG")), - ("fileWidth".into(), serde_json::json!(1)), - ("fileHeight".into(), serde_json::json!(1)), - ]); - lightroom_catalog::CatalogPhoto { - source_id, - uuid: format!("scale-{source_id}"), - path: format!("/missing/scale-{source_id}.jpg"), - image, - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![std::collections::BTreeMap::from([( - "text".into(), - serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))), - )])], - snapshots: Vec::new(), - original: lightroom_catalog::Original::Local, - } - }) - .collect(); - let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); - assert!(archive_path.is_none()); - let mut session = crate::Session::new(); - let token = LightroomLibraryToken::capture(&session); - let prepared = PreparedLightroom { - data, - normal: Prepared::default(), - index: ImportIndex::default(), - archive_path, - token, - missing_sources: HashSet::new(), - update_existing: false, - now: "2026-01-01T00:00:00".into(), - cancelled: false, - }; - let completion = commit_prepared(&mut session, prepared).unwrap(); - assert_eq!(completion.report["photos"], 5_000); - assert!( - completion.report["warnings"] - .as_array() - .is_some_and(|warnings| warnings.iter().any(|warning| warning == "Lightroom source archive exceeded 32 MiB; archive skipped")) - ); - assert_eq!(session.catalog.len(), 5_000); - std::fs::remove_dir_all(archive_dir).unwrap(); + fn oversized_archive_keeps_prepared_import_successful_with_warning() { + for (in_history, warning, archived) in [ + (true, "Lightroom source archive exceeded 32 MiB; archived without history-step and snapshot settings", true), + (false, "Lightroom source archive exceeded 32 MiB; archive skipped", false), + ] { + let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{in_history}-{}", std::process::id())); + let mut data = empty_data(); + data.photos = (0..5_000) + .map(|source_id| { + let image = std::collections::BTreeMap::from([ + ("id_local".into(), serde_json::json!(source_id)), + ("fileFormat".into(), serde_json::json!("JPG")), + ("fileWidth".into(), serde_json::json!(1)), + ("fileHeight".into(), serde_json::json!(1)), + ]); + let bulk = format!("history-{source_id}-{}", "x".repeat(8 * 1024)); + lightroom_catalog::CatalogPhoto { + source_id, + uuid: format!("scale-{source_id}"), + path: format!("/missing/scale-{source_id}.jpg"), + image, + settings: if in_history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![std::collections::BTreeMap::from([( + "text".into(), + serde_json::json!(if in_history { bulk } else { String::new() }), + )])], + snapshots: Vec::new(), + original: lightroom_catalog::Original::Local, + } + }) + .collect(); + let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); + assert_eq!(archive_path.is_some(), archived, "{warning}"); + let mut session = crate::Session::new(); + let token = LightroomLibraryToken::capture(&session); + let prepared = PreparedLightroom { + data, + normal: Prepared::default(), + index: ImportIndex::default(), + archive_path, + token, + missing_sources: HashSet::new(), + update_existing: false, + now: "2026-01-01T00:00:00".into(), + cancelled: false, + }; + let completion = commit_prepared(&mut session, prepared).unwrap(); + assert_eq!(completion.report["photos"], 5_000); + assert!( + completion.report["warnings"].as_array().is_some_and(|warnings| warnings.iter().any(|w| w == warning)), + "the report should say: {warning}" + ); + assert_eq!(session.catalog.len(), 5_000); + std::fs::remove_dir_all(archive_dir).unwrap(); + } } #[test] diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index 6624e3f195..fc18426689 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,10 +1,11 @@ use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. +/// 86: pushed shadows keep the camera profile's colour and tone (#2092). /// 85: raw decoding keeps negative channels (#2278). /// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328). /// 83 is reserved by open #3943. -pub const RENDER_CACHE_VERSION: u64 = 85; +pub const RENDER_CACHE_VERSION: u64 = 86; /// 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/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 76bcfd7f29..70ad1328fb 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -430,29 +430,72 @@ impl Session { /// apply Auto Settings / the auto crop. Returns `{id, path, …info}`. pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result { let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1; - // a new file under a free name (never replacing one), complete and synced before it appears - let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) - .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? - .to_string_lossy() - .to_string(); - let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?; - let id = report - .imported - .first() - .copied() - .map(PhotoId) - .ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?; - if job.finish.stack { + let output_hash = lightcraft_preview::hash_bytes(&out.dng).to_string(); + // Import deduplicates by content. Reuse an existing merge only while its live source has + // matching bytes; stale, missing or deleted rows fail before another file is published. + let candidates: Vec<(PhotoId, String, bool)> = self + .catalog + .photos() + .filter_map(|p| { + if p.content_hash.as_deref() != Some(output_hash.as_str()) { + return None; + } + let Source::File { path } = &p.source else { return None }; + Some((p.id, path.clone(), p.deleted)) + }) + .collect(); + let valid_existing = candidates + .iter() + .find(|(_, path, deleted)| { + if *deleted { + return false; + } + let bytes = match &self.media.file_bytes { + Some(read) => read(path).ok(), + None => std::fs::read(path).ok(), + }; + bytes.is_some_and(|bytes| lightcraft_preview::hash_bytes(&bytes).to_string() == output_hash) + }) + .cloned(); + let (id, path, reused) = if let Some((id, path, _)) = valid_existing { + (id, path, true) + } else if let Some((id, path, deleted)) = candidates.first() { + let state = if *deleted { "deleted" } else { "missing or changed" }; + return Err(EngineError::Other(format!( + "existing merge result {id:?} has a {state} source at {path}; relink or remove it before repeating the merge" + ))); + } else { + // A new file under a free name (never replacing one), complete and synced before it appears. + let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) + .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? + .to_string_lossy() + .to_string(); + let report = match crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add) { + Ok(report) => report, + Err(e) => { + let _ = std::fs::remove_file(&path); + return Err(e); + } + }; + if let Some(id) = report.imported.first().copied().map(PhotoId) { + (id, path, false) + } else { + let _ = std::fs::remove_file(&path); + return Err(EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed))); + } + }; + if !reused && job.finish.stack { let sources: Vec = job.sources.iter().map(|(p, _)| *p).collect(); if let Some(op) = self.catalog.stack_with_ops(id, &sources) { self.commit("Stack with Sources", op)?; } } self.selection = crate::Selection::single(id); - if job.finish.auto_settings { + if !reused && job.finish.auto_settings { self.execute("develop.auto", &json!({}))?; } - if let Some(c) = out.crop + if !reused + && let Some(c) = out.crop && let Some(d) = self.develop_of(id) { let mut d = (*d).clone(); @@ -463,6 +506,7 @@ impl Session { info["id"] = json!(id.0); info["path"] = json!(path); info["bytes"] = json!(out.dng.len()); + info["reused"] = json!(reused); Ok(info) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ccf2d461c3..9c84b179da 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -38,6 +38,7 @@ mod lens_refresh; mod libops; mod library; mod lightroom_folder; +mod lightroom_history; mod mask_effects; mod mask_geometry; mod merge; @@ -62,6 +63,7 @@ mod slideshow_export; mod slow_drive; mod spots; mod sync; +mod task_queue; mod view_follow; pub(super) mod xmp; diff --git a/crates/engine/src/tests/folders.rs b/crates/engine/src/tests/folders.rs index 6877572768..4e7fd42281 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}; @@ -702,6 +703,78 @@ 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(); + let photo = day.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + let paths = |s: &Session| -> Vec { + s.catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect() + }; + let day = day.to_string_lossy().to_string(); + let r = s.execute("folder.rename", &json!({"path": day, "name": "Beach"})).unwrap(); + assert_eq!(r["relinked"], 1, "the photo inside is relinked"); + assert!(lib.join("Originals/Beach").is_dir(), "the imported date folder is renamed"); + assert!(!Path::new(&day).exists()); + let moved = lib.join("Originals").join("Beach").join("a.jpg"); + assert_eq!(paths(&s), [moved.to_string_lossy().to_string()], "the catalog follows the photo"); + assert!(moved.is_file()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(Path::new(&day).is_dir(), "undo names it back"); + assert_eq!(paths(&s), [photo.to_string_lossy().to_string()], "and points the photo back, in one step"); + assert!(photo.is_file()); + 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"); + 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()); +} + +/// A date folder inside the library named through a link to the library would move on disk while its photos, +/// stored under the library's own path, kept pointing at the old folder: it is refused and nothing moves. +#[cfg(unix)] +#[test] +fn a_folder_inside_the_library_named_through_a_link_is_refused_and_its_photos_keep_their_paths() { + let dir = Scratch::new("in-library-link"); + 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(); + let photo = day.join("a.jpg").to_string_lossy().to_string(); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo); + std::os::unix::fs::symlink(&lib, dir.0.join("lib-link")).unwrap(); + let linked = dir.0.join("lib-link").join("Originals").join("2026-10-16").to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": linked, "name": "Beach"})).is_err(), "a linked spelling is refused"); + assert!(day.is_dir() && !lib.join("Originals/Beach").exists(), "nothing moved on disk"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert!(paths.iter().all(|p| Path::new(p).exists()), "every photo still points at a file: {paths:?}"); +} + #[cfg(unix)] #[test] fn the_library_folder_is_protected_however_its_path_is_spelled() { diff --git a/crates/engine/src/tests/lightroom_history.rs b/crates/engine/src/tests/lightroom_history.rs new file mode 100644 index 0000000000..d1fa044186 --- /dev/null +++ b/crates/engine/src/tests/lightroom_history.rs @@ -0,0 +1,136 @@ +//! Lightroom history steps and snapshots read from a catalog file into the import archive: stored as text +//! (Lightroom 6) or as compressed BLOBs (history steps since Lightroom Classic 13, which also converts an upgraded +//! catalog's steps). + +use crate::lightroom_fixture::{self as fixture, Field, Table}; +use serde_json::{Value, json}; + +const CURRENT: &str = "s = { Exposure2012 = 1.25, Contrast2012 = 17 }"; +const FIRST: &str = "s = { Exposure2012 = 1.25 }"; + +/// Write a one-photo catalog with `extra` tables, read it, archive it, and return the archive's JSON. +fn archive(tag: &str, extra: Vec
) -> Value { + let dir = fixture::dir(tag); + let mut tables = fixture::one_photo(&dir.join("originals"), CURRENT); + tables.extend(extra); + let catalog = dir.join("test.lrcat"); + fixture::write(&catalog, &tables); + let data = crate::lightroom_catalog::read(&catalog).unwrap(); + let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap(); + let archived = fixture::read_archive(&stored); + let _ = std::fs::remove_dir_all(dir); + archived +} + +fn steps(settings: impl Fn(&str) -> Field) -> Table { + Table { + name: "Adobe_libraryImageDevelopHistoryStep", + columns: fixture::HISTORY_COLUMNS, + rows: vec![fixture::history_step(3, 1, 20.0, "Contrast", settings(CURRENT)), fixture::history_step(2, 1, 10.0, "Exposure", settings(FIRST))], + } +} + +/// `(name, dateCreated, text)` of each archived row, in the order the archive holds them. +fn rows(archive: &Value, key: &str) -> Vec<(Value, Value, Value)> { + let rows = archive["photos"][0][key].as_array().unwrap_or_else(|| panic!("the archive should list {key}: {archive}")); + rows.iter().map(|r| (r["name"].clone(), r["dateCreated"].clone(), r["text"].clone())).collect() +} + +#[test] +fn compressed_history_steps_keep_their_settings_in_the_archive() { + let archived = archive("history-blob", vec![steps(|t| Field::Blob(fixture::compressed(t)))]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!( + steps, + [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], + "each compressed step should be archived with its decoded settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([]), "no step should be reported unreadable"); +} + +#[test] +fn text_history_steps_are_archived_as_before() { + let archived = archive("history-text", vec![steps(fixture::text)]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!(steps, [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], "{archived}"); + assert_eq!(archived["warnings"], json!([])); +} + +#[test] +fn compressed_and_text_snapshots_keep_their_settings_in_the_archive() { + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![ + fixture::snapshot(5, 1, "Bright", Field::Blob(fixture::compressed("s = { Exposure2012 = 2 }"))), + fixture::snapshot(6, 1, "Plain", fixture::text("s = { Contrast2012 = 30 }")), + ], + }; + let archived = archive("snapshot-blob", vec![snapshots]); + let mut kept: Vec<_> = rows(&archived, "snapshots").into_iter().map(|(name, _, text)| (name, text)).collect(); + kept.sort_by_key(|(name, _)| name.to_string()); + assert_eq!( + kept, + [(json!("Bright"), json!("s = { Exposure2012 = 2 }")), (json!("Plain"), json!("s = { Contrast2012 = 30 }"))], + "compressed and text snapshots should both be archived with their settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([])); +} + +/// A hostile or damaged catalog: each bad BLOB costs only its own row's settings, with a warning naming the image. +#[test] +fn a_malformed_settings_blob_is_archived_without_its_settings_and_warned_about() { + let mut mismatch = fixture::compressed(FIRST); + mismatch[3] = mismatch[3].wrapping_add(1); + let mut over_cap = fixture::compressed(FIRST); + over_cap[..4].copy_from_slice(&((16u32 << 20) + 1).to_be_bytes()); + let bad = [ + ("Short", vec![0, 0]), + ("Not zlib", vec![0, 0, 0, 5, 1, 2, 3, 4, 5]), + ("Wrong length", mismatch), + ("Too big", over_cap), + ("Not UTF-8", fixture::compressed_bytes(&[0xff, 0xfe])), + ]; + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for (i, (name, bytes)) in bad.iter().enumerate() { + let id = 10 + i64::try_from(i).unwrap(); + history.rows.push(fixture::history_step(id, 1, 30.0 + id as f64, name, Field::Blob(bytes.clone()))); + } + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![fixture::snapshot(5, 1, "Broken", Field::Blob(vec![0, 0, 0, 9, 9]))], + }; + let archived = archive("history-bad", vec![history, snapshots]); + assert_eq!(archived["photos"].as_array().map(Vec::len), Some(1), "the photo is still read: {archived}"); + let steps = rows(&archived, "history"); + assert_eq!(steps.len(), 7, "every step is still archived: {archived}"); + for (name, _, text) in &steps { + let good = name == "Exposure" || name == "Contrast"; + assert_eq!(text.is_string(), good, "{name}: only the good steps keep settings: {archived}"); + } + assert_eq!(rows(&archived, "snapshots")[0].2, Value::Null, "the broken snapshot is archived without settings"); + let warnings: Vec<_> = archived["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(warnings.len(), bad.len() + 1, "one warning per bad step and snapshot: {warnings:?}"); + assert!(warnings.iter().all(|w| w.starts_with("image 1: ")), "each warning names the image: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("history step 10")), "a warning names the step: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("snapshot 5")), "a warning names the snapshot: {warnings:?}"); +} + +/// Only the settings column is decoded; any other BLOB (even one in Lightroom's compressed encoding) stays out of +/// the archive, as before. +#[test] +fn other_blob_columns_never_reach_the_archive() { + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for row in &mut history.rows { + row[3] = Field::Blob(vec![1, 2, 3, 4]); // digest + row[10] = Field::Blob(fixture::compressed("s = { Exposure2012 = 3 }")); // valueString + } + let archived = archive("history-other-blobs", vec![history]); + for step in archived["photos"][0]["history"].as_array().unwrap() { + assert!(step.get("digest").is_none() && step.get("valueString").is_none(), "other BLOB columns leaked: {step}"); + assert!(step["text"].is_string(), "the settings are still decoded: {step}"); + } +} diff --git a/crates/engine/src/tests/merge.rs b/crates/engine/src/tests/merge.rs index 432ad14ca1..2d82c20570 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -40,6 +40,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() { let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); let path = r["path"].as_str().unwrap(); assert!(path.ends_with("IMG_0-HDR.dng"), "{path}"); + assert_eq!(r["reused"].as_bool(), Some(false)); let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap()); let p = s.catalog.photo(id).unwrap().clone(); assert_eq!((p.width, p.height), (480, 320)); @@ -55,15 +56,25 @@ fn hdr_merge_command_creates_and_imports_a_dng() { assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::>(), ids); assert!(st.collapsed); assert_eq!(s.visible_cloned(), vec![id]); - // the second merge doesn't overwrite the first - let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); - assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng")); - let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap()); - assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option"); + // A repeated deterministic merge reuses the existing content instead of publishing an + // unimported uniquely named orphan. + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).unwrap().clone(); + let undo_before = s.undo.len(); + let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); + assert_eq!(r2["id"].as_u64(), Some(id.0)); + assert_eq!(r2["reused"].as_bool(), Some(true)); + assert_eq!(r2["path"].as_str(), Some(path)); + assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan"); + assert_eq!(s.catalog.photos().count(), 4); + assert_eq!(s.undo.len(), undo_before, "reusing merge content added an undo step"); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "reusing merge content changed edits"); + assert_eq!(s.catalog.stack_of(id), Some(&stack_before), "reusing merge content changed stack"); // the type filter finds merge results (and only them) s.execute("library.filter", &json!({"merged": "hdr"})).unwrap(); let found: std::collections::HashSet<_> = s.catalog.query(&s.filter, &Default::default()).into_iter().collect(); - assert_eq!(found, [id, id2].into_iter().collect()); + assert_eq!(found, [id].into_iter().collect()); let _ = std::fs::remove_dir_all(&dir); } @@ -143,6 +154,55 @@ fn a_merge_of_raws_without_colour_matrices_keeps_their_colour() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn hdr_merge_refuses_stale_result_before_writing() { + let dir = temp_dir("hdr-stale"); + let mut paths = Vec::new(); + for (i, b) in lightcraft_merge::synth::bracket_dngs(240, 160, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() { + let p = dir.join(format!("IMG_{i}.dng")); + std::fs::write(&p, b).unwrap(); + paths.push(p.to_string_lossy().to_string()); + } + let mut s = Session::new().with_fs(); + let ids = import(&mut s, paths.clone()); + let first = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); + let id = lightcraft_catalog::PhotoId(first["id"].as_u64().unwrap()); + let path = first["path"].as_str().unwrap().to_string(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).cloned(); + + std::fs::remove_file(&path).unwrap(); + let undo_before = s.undo.len(); + let missing = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(missing.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert!(!std::path::Path::new(&path).exists()); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + std::fs::write(&path, std::fs::read(&paths[0]).unwrap()).unwrap(); + let changed_bytes = std::fs::read(&path).unwrap(); + let changed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(changed.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert_eq!(std::fs::read(&path).unwrap(), changed_bytes); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "changed-source repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let deleted_bytes = std::fs::read(&path).unwrap(); + let undo_after_delete = s.undo.len(); + let failed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})); + assert!(failed.as_ref().unwrap_err().to_string().contains("deleted")); + assert_eq!(std::fs::read(&path).unwrap(), deleted_bytes); + assert!(!dir.join("IMG_0-HDR-3.dng").exists(), "failed import left an orphan"); + assert_eq!(s.undo.len(), undo_after_delete); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn panorama_command_with_auto_crop() { let dir = temp_dir("pano"); diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs new file mode 100644 index 0000000000..939c2d3042 --- /dev/null +++ b/crates/engine/src/tests/task_queue.rs @@ -0,0 +1,318 @@ +//! Tasks waiting in line for their lane (see `crate::activity`), with the preview builds. +//! +//! Scenarios, in the words of an agent building previews for several shoots: +//! +//! * Build Previews while a build runs: without `queue` it is refused, as it always was. With `queue` it waits +//! behind the build, `activity.list` says it is next, and it builds the photos chosen when it was asked. +//! * It starts by itself when the build ahead of it ends. +//! * `activity.cancel` on it takes it out of the line: it never runs; `all` empties the line. +//! * The line is bounded. +//! * Another library: nothing waits for it. +//! +//! These go through commands and `activity.list` only, so that they describe what a control or MCP client sees. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::activity::{Cancel, MAX_WAITING, TaskGuard}; +use crate::cmd::previews::PreviewBuild; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-task-queue-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A preview build that holds the lane until [`release`]: its row runs, and the build reads as unfinished. +struct Hold { + _row: TaskGuard, + build: Arc, +} + +fn hold(s: &mut Session) -> Hold { + let build = Arc::new(PreviewBuild::default()); + s.preview_build = Some(build.clone()); + Hold { _row: s.activity.start("previews", "Building previews", Cancel::Yes), build } +} + +/// The held build ends as a real one does: finished first, then its row goes. +fn release(h: Hold) { + h.build.finished.store(true, Ordering::Release); + drop(h); +} + +/// Wait (at most a minute) until no task runs or waits. +fn settle(s: &mut Session) { + let t0 = std::time::Instant::now(); + loop { + // any command lets a waiting task whose lane is free start (the app's frame loop does too) + let rows = tasks(s); + if rows.is_empty() { + return; + } + assert!(t0.elapsed().as_secs() < 60, "tasks still listed: {rows:?}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + +fn tasks(s: &mut Session) -> Vec { + s.execute("activity.list", &json!({})).unwrap()["tasks"].as_array().cloned().unwrap_or_default() +} + +fn build_ids(s: &Session, n: usize) -> Vec { + s.catalog.photos().take(n).map(|p| p.id.0).collect() +} + +/// Given a preview build running and two photos chosen, when Build Previews is asked for with `queue`, then it waits +/// behind the build, first in line, with nothing done. When other photos are chosen meanwhile and the build ahead +/// ends, then it starts by itself and builds the two photos chosen when it was asked. +#[test] +fn a_build_asked_for_while_one_runs_waits_behind_it_and_builds_the_photos_chosen_then() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 3); + s.execute("library.select", &json!({"ids": [ids[0], ids[1]]})).unwrap(); + let h = hold(&mut s); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true})).unwrap(); + let id = r["queued"].as_u64().expect("an id while it waits"); + assert_eq!(r["place"], 1); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 2, "the running build, then the waiting one: {rows:?}"); + assert_eq!(rows[1]["id"], id); + assert_eq!((rows[1]["waiting"].as_bool(), rows[1]["place"].as_u64(), rows[1]["lane"].as_str()), (Some(true), Some(1), Some("previews"))); + assert_eq!((rows[1]["done"].as_u64(), rows[1]["total"].as_u64()), (Some(0), Some(0))); + assert_eq!(rows[1]["label"], "Building previews"); + assert_eq!((rows[0]["waiting"].as_bool(), rows[0]["place"].as_u64()), (Some(false), Some(0)), "the running one is not in line"); + s.execute("library.select", &json!({"ids": [ids[2]]})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(2), Some(2)), "{progress}"); + // the journal has the call that asked for it, once: starting it was not a second call + assert_eq!(s.journal.iter().filter(|(c, _)| c == "library.buildPreviews").count(), 1, "{:?}", s.journal); +} + +/// Given a preview build running, when a build is asked for without `queue`, then it is refused as before, and +/// nothing waits. +#[test] +fn a_build_asked_for_while_one_runs_is_refused_unless_it_asks_to_queue() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": false})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is listed"); + release(h); + assert!(tasks(&mut s).is_empty()); +} + +/// Given no build running, when a build is asked for with `queue`, then it starts at once, as one without it does. +#[test] +fn a_build_that_asks_to_queue_starts_at_once_when_nothing_is_ahead_of_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!((r["total"].as_u64(), r["done"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +/// Given a build waiting behind another, when `activity.cancel` is asked for it, then it leaves the line and never +/// runs. +#[test] +fn a_waiting_build_taken_out_of_the_line_never_runs() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + let id = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().unwrap(); + assert_eq!(s.execute("activity.cancel", &json!({"id": id})).unwrap()["cancelled"], 1); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is left"); + assert!(s.execute("activity.cancel", &json!({"id": id})).is_err(), "it is gone: an unknown id"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "no build started after the held one"); +} + +/// Given builds waiting, when every task is cancelled, then the line is empty and the count includes the waiting ones, +/// so that nothing starts as soon as the running build stops. +#[test] +fn cancelling_every_task_empties_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + } + assert_eq!(tasks(&mut s).len(), 3); + assert_eq!(s.execute("activity.cancel", &json!({"all": true})).unwrap()["cancelled"], 3, "the running one and the two waiting"); + assert_eq!(tasks(&mut s).len(), 1, "only the running (stopping) build is listed"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "nothing started after it"); +} + +/// Given a full line, when one more build is asked for, then it is refused and says why; the line is as it was. +#[test] +fn the_line_is_bounded() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + for place in 1..=MAX_WAITING { + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(r["place"].as_u64(), Some(place as u64)); + } + let e = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap_err().to_string(); + assert!(e.contains(&MAX_WAITING.to_string()), "{e}"); + assert_eq!(tasks(&mut s).len(), MAX_WAITING + 1); + s.execute("activity.cancel", &json!({"all": true})).unwrap(); + release(h); +} + +/// Build Smart Previews in the background waits in the same line (one preview build at a time). +#[test] +fn smart_previews_wait_behind_a_preview_build() { + let dir = temp_dir("smart"); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + let ids = build_ids(&s, 2); + let h = hold(&mut s); + let e = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true})).unwrap_err().to_string(); + assert!(e.contains("already running"), "{e}"); + let r = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true, "queue": true})).unwrap(); + assert!(r["queued"].is_u64(), "{r}"); + let rows = tasks(&mut s); + assert_eq!( + (rows[1]["kind"].as_str(), rows[1]["waiting"].as_bool(), rows[1]["lane"].as_str()), + (Some("smartPreviews"), Some(true), Some("previews")) + ); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + // (the demo photos aren't files, so it has nothing to build: that it ran at all is what counts) + assert_eq!(progress["what"], "smart previews", "{progress}"); + assert_eq!(progress["running"], false, "{progress}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two builds waiting, the first of which can't start (here: it was asked for a size no build accepts, as if what it +/// needs went away while it waited): the second still runs. +#[test] +fn a_build_that_can_not_start_does_not_hold_up_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}) }; + s.activity.enqueue("previews", "Building previews", bad).unwrap(); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(1), Some(1)), "{progress}"); +} + +/// `queue` with `wait` while a build runs: the call can't both wait in line and return when the build is done. +#[test] +fn a_build_that_would_wait_for_its_turn_and_its_end_is_refused() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true, "wait": true})).unwrap_err().to_string(); + assert!(e.contains("wait"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1); + release(h); +} + +/// Given a build waiting and one still running, when another library is opened, then nothing waits any more: the +/// build asked for was about the old library's photos. +#[test] +fn another_library_drops_what_waits() { + let dir = temp_dir("switch"); + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(tasks(&mut s).len(), 2); + s.open_library(&dir, false).unwrap(); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 1, "only the old library's running build: {rows:?}"); + assert_eq!(rows[0]["waiting"], false); + release(h); + settle(&mut s); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Given a build that ended and a build waiting behind it, when the next command starts the waiting one before the +/// app announced the first, then the first is kept (once, with its counts) for the frontend to announce, and the +/// new build is the current one. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_kept_until_it_is_announced() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let first = h.build.clone(); + first.done.store(2, Ordering::Relaxed); + first.failed.store(1, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); // the command that ends up starting the waiting build + assert!(s.preview_build.as_ref().is_some_and(|b| !Arc::ptr_eq(b, &first)), "the waiting build is the current one"); + let kept = s.take_unreported_builds(); + assert_eq!(kept.len(), 1); + assert!(Arc::ptr_eq(&kept[0], &first)); + assert_eq!((kept[0].done.load(Ordering::Relaxed), kept[0].failed.load(Ordering::Relaxed)), (2, 1)); + assert!(s.take_unreported_builds().is_empty(), "once"); + settle(&mut s); +} + +/// A build the frontend announced already is not kept when the next one replaces it. +#[test] +fn a_build_that_was_announced_is_not_kept_when_the_next_one_replaces_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + h.build.reported.store(true, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); + assert!(s.take_unreported_builds().is_empty()); + settle(&mut s); +} + +/// Given a build that ended and a build waiting in line behind it that has not been started yet, when Build Previews is +/// asked for without `queue`, then it is refused, as it is while a build runs: it does not start ahead of the one +/// waiting, which the line starts after this command. +#[test] +fn a_build_asked_for_without_queue_does_not_go_ahead_of_one_waiting_in_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + // the build ends, and nothing has started the one waiting yet (no command or frame since) + release(running); + let refused = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256})).unwrap_err().to_string(); + assert!(refused.contains("preview build"), "{refused}"); + settle(&mut s); +} + +/// Given a build running and two builds waiting behind it, when the build ends, then both start in turn, each one when +/// the lane is free (the line is not "ahead" of the build it is starting). +#[test] +fn builds_waiting_in_line_all_start_in_turn() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + } + release(running); + settle(&mut s); + // the held build, and the first of the two, were replaced by the next: three builds ran in all + assert_eq!(s.take_unreported_builds().len(), 2, "both waiting builds started"); +} diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 05a001308e..eec3de8314 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -1,17 +1,21 @@ -//! Times the SAM 3 backbone on the GPU (wgpu) against the candle backbone on the CPU, on a procedural photo. +//! Times the SAM 3 backbone and both necks 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. +//! kernel creation, the weight upload, the first and the warm forward passes, each neck's first run (which builds +//! it) and warm runs, the text detector's mask decoder (first and warm, on made-up inputs), 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, necks, DETR encoder and mask decoder, the rest in candle on the CPU): encode, click +//! features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they ran on +//! the GPU; `--cpu-masks`: with the mask decoder in candle). use std::path::PathBuf; use std::time::Instant; use lightcraft_gpu::sam3::{self, Precision}; -use lightcraft_segment::{BackboneAccel, INPUT, Sam3}; +use lightcraft_segment::{BackboneAccel, INPUT, NeckKind, Sam3, WeightReader}; fn model_dir() -> Option { let dir = match std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()) { @@ -31,6 +35,8 @@ fn main() -> Result<(), String> { }; let cpu = !args.iter().any(|a| a == "--no-cpu"); let app = args.iter().any(|a| a == "--app"); + let cpu_necks = args.iter().any(|a| a == "--cpu-necks"); + let cpu_masks = args.iter().any(|a| a == "--cpu-masks"); let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; let scene = &lightcraft_scenes::demo_library()[0]; @@ -41,7 +47,7 @@ fn main() -> Result<(), 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 reader = WeightReader::open(&dir).map_err(|e| e.to_string())?; let t = Instant::now(); let gpu = sam3::load(&reader, precision)?; println!( @@ -63,6 +69,31 @@ fn main() -> Result<(), String> { sum += ms; } println!("warm forward: {:7.1} ms (mean of {runs}: {:.1} ms)", best, sum / runs.max(1) as f64); + // a head that fails here is reported, and the `--app` run below still measures its fallback to candle + for which in [NeckKind::Tracker, NeckKind::Detector] { + match timed(runs, || gpu.neck(which, &out, 3).map(drop)) { + Ok((first, best, mean)) => println!("{which:?} neck: first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms)"), + Err(e) => println!("{which:?} neck failed on the GPU: {e}"), + } + } + println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + { + let (memory, text, valid) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256], vec![true; 32]); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + match timed(runs, || gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).map(drop)) { + Ok((first, best, mean)) => { + let (w, b) = gpu.mask_decoder_bytes().unwrap_or_default(); + println!( + "mask decoder (200 queries): first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms); {:.0} MB weights, {:.0} MB work buffers", + w as f64 / 1e6, + b as f64 / 1e6 + ); + } + Err(e) => println!("mask decoder failed on the GPU: {e}"), + } + } + 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())?; @@ -84,7 +115,7 @@ fn main() -> Result<(), String> { } drop(gpu); if app { - as_the_app(&dir, &rgb, (img.width, img.height), runs)?; + as_the_app(&dir, &rgb, (img.width, img.height), runs, (cpu_necks, cpu_masks))?; } // no GPU work in flight when the process ends (issue #620) lightcraft_gpu::begin_shutdown(); @@ -92,14 +123,75 @@ fn main() -> Result<(), String> { Ok(()) } +/// `f` once (its first run, in ms), then `runs` times: (first, best, mean) in milliseconds; the first error ends it. +fn timed(runs: usize, mut f: impl FnMut() -> Result<(), String>) -> Result<(f64, f64, f64), String> { + let t = Instant::now(); + f()?; + let first = t.elapsed().as_secs_f64() * 1e3; + let (mut best, mut sum) = (f64::MAX, 0.0); + for _ in 0..runs { + let t = Instant::now(); + f()?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + Ok((first, best, sum / runs.max(1) as f64)) +} + fn ms(t: Instant) -> String { format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) } +/// The model's GPU accelerator with the necks (`--cpu-necks`) or the mask decoder (`--cpu-masks`) left to candle. +struct Heads { + gpu: Box, + necks: bool, + masks: bool, +} + +impl BackboneAccel for Heads { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + fn device(&self) -> String { + self.gpu.device() + } + fn runs_necks(&self) -> bool { + self.necks && self.gpu.runs_necks() + } + fn runs_detr_encoder(&self) -> bool { + self.gpu.runs_detr_encoder() + } + fn runs_mask_decoder(&self) -> bool { + self.masks && self.gpu.runs_mask_decoder() + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) + } +} + /// 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> { +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, (cpu_necks, cpu_masks): (bool, bool)) -> 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())?; + let make = |r: &WeightReader| -> Result, String> { + Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks, masks: !cpu_masks })) + }; + let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, make).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) { diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index cca52177fc..f1064b5bc2 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -255,6 +255,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec) let reads: Vec = match op { Op::Conv(c) => std::iter::once(c.src).chain(c.src2).collect(), Op::ConvT2(c) => vec![c.src], + Op::Add { src, src2 } => vec![*src, *src2], Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => vec![*src], }; for t in reads { @@ -448,6 +449,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec) } // run as part of the 1 × 1 convolution before it Op::DepthToSpace2 { .. } => {} + Op::Add { .. } => return unsupported("an elementwise add is not supported on the GPU"), } // buffers whose last reader was this layer are free for the next layer's result for t in 0..=i { diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index bf37f72454..1c059268d7 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -14,8 +14,11 @@ //! `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. +//! per layer and reads the result back once. No subgroups or shader-f16 needed. The two necks that follow the +//! backbone run on the same device, built when first asked for (`sam3/neck.rs`). +//! +//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`) and its mask decoder (`sam3/pixel.rs`); +//! their weights load on the first text prompt. //! //! 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 @@ -27,9 +30,12 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use std::time::Duration; use bytemuck::Pod; -use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, WeightReader}; +use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, NeckKind, WeightReader}; use wgpu::util::DeviceExt; +mod detr; +mod neck; +mod pixel; #[cfg(test)] mod tests; @@ -947,6 +953,12 @@ pub struct Sam3Gpu { /// Bytes of work buffers on the device. work_bytes: u64, precision: Precision, + /// The detector's DETR encoder, loaded on the first text prompt. + detr: detr::Encoder, + /// The feature pyramids, built on first use. + necks: neck::Necks, + /// The detector's mask decoder, loaded on the first text prompt. + masks: pixel::MaskDecoder, } /// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, @@ -1040,7 +1052,20 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) } 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 }) + let detr = detr::Encoder::new(weights.clone()); + let necks = neck::Necks::new(weights.clone()); + let masks = pixel::MaskDecoder::new(weights.clone()); + Ok(Sam3Gpu { + dev, + recorded, + work: Mutex::new(Work { pixels, out: y, staging }), + weight_bytes: ld.bytes, + work_bytes, + precision, + detr, + necks, + masks, + }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1062,6 +1087,16 @@ impl Sam3Gpu { self.work_bytes + (TOKENS * HIDDEN * 4) as u64 } + /// Bytes of device memory the DETR encoder's weights and work buffers take, once a text prompt loaded them. + pub fn detr_bytes(&self) -> Option<(u64, u64)> { + self.detr.bytes() + } + + /// Bytes of device memory the mask decoder's weights and work buffers take, once a text prompt loaded them. + pub fn mask_decoder_bytes(&self) -> Option<(u64, u64)> { + self.masks.bytes() + } + fn run(&self, pixels: &[f32]) -> Result, String> { if pixels.len() != 3 * IMAGE * IMAGE { return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); @@ -1088,10 +1123,62 @@ impl BackboneAccel for Sam3Gpu { guarded("the SAM 3 backbone", || self.run(pixels)) } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> 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("a SAM 3 neck", || self.necks.run(self.dev, which, backbone, n)) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> 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); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[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); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 mask decoder", || self.masks.run(self.dev, memory, text, valid, levels, rows, bias)) + } + fn closing(&self) -> bool { crate::shutting_down() } + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/detr.rs b/crates/gpu/src/sam3/detr.rs new file mode 100644 index 0000000000..a3e28c25cb --- /dev/null +++ b/crates/gpu/src/sam3/detr.rs @@ -0,0 +1,356 @@ +//! The DETR encoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): six +//! layers over the 72 × 72 image tokens of 256, each self-attention (q and k from the normed tokens plus their sine +//! position encoding, v from the normed tokens) → cross-attention to the prompt's 32 tokens (with the key-padding bias) +//! → MLP 256 → 2048 → 256 with ReLU, each after a layer norm (eps 1e-5) and added to the tokens. ~4 s per prompt on +//! the CPU through candle. +//! +//! Kernels: the backbone's matrix product (ReLU in its epilogue) and layer norm, and `wgsl/sam3_detr.wgsl`: attention +//! with heads of 32 whose q, k and v come from separate buffers (the cross-attention's k and v from the prompt), with +//! an optional per-key bias, and a sum. The weights (38 MB) and the kernels load on the first prompt, not with the +//! backbone; then every dispatch is recorded once, and a prompt writes the tokens, their position encoding, the +//! prompt's tokens and its padding bias, submits one command buffer per layer and reads the memory back. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::{Dev, Graph, Precision, Recorded, TIMEOUT, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the encoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.detr_encoder"; +/// Image tokens (72 × 72), their width, the prompt's tokens. +const TOKENS: usize = 72 * 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +const MLP: usize = 2048; +const LAYERS: usize = 6; +/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`). +const EPS: f32 = 1e-5; +/// Keys per step of the attention kernel (the prompt's 32 tokens are one step). +const KEYS: u32 = 32; +/// `p.gelu` of the matrix product: ReLU. +const RELU: u32 = 2; +/// No bias in the attention kernel. +const NONE: u32 = u32::MAX; + +pub(super) struct Kernels { + attention: wgpu::ComputePipeline, + add: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The encoder's kernels, compiled on first use (the mask decoder's prompt attention uses them too). +pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = attention_source(KEYS); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry); + let k = Kernels { attention: pipe("attention"), add: pipe("add") }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 DETR kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_detr.wgsl` (as the backbone's). +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} = qs[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) * SCALE + Bs[{j}u];\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_detr.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// Where an attention's q, k and v are: a buffer, its row stride and the column of head 0 (in floats). +pub(super) struct Operand<'a> { + pub(super) buffer: &'a wgpu::Buffer, + pub(super) stride: usize, + pub(super) offset: usize, +} + +impl Graph { + /// Layer norm with PyTorch's eps (the backbone's is 1e-6). + pub(super) fn layernorm_torch(&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(()) + } + + /// `y = relu(x · wᵀ + bias)`. + fn matmul_relu(&mut self, buffers: [&wgpu::Buffer; 4], dims: (usize, usize, usize)) -> Result<(), String> { + self.matmul(buffers, dims, 1, false, false, Precision::F32)?; + if let Some(step) = self.steps.last_mut() { + step.params[4] = RELU; + } + Ok(()) + } + + /// `out = a + b`, `len` floats (a multiple of 4). + fn add(&mut self, k: &'static Kernels, [a, b, out]: [&wgpu::Buffer; 3], len: usize) -> Result<(), String> { + if !len.is_multiple_of(4) { + return Err("a sum the SAM 3 kernel cannot do".into()); + } + let (g, row) = self.flat((len / 4).div_ceil(256))?; + self.push(&k.add, [u32_of(len / 4)?, row, 0, 0, 0, 0, 0, 0], [a, b, &self.dev.dummy, out], g); + Ok(()) + } + + /// Attention of `queries` queries over `keys` keys, `heads` heads of 32, into `out` (`[queries, heads · 32]`); + /// with `bias`, key j's scores get `k.buffer[bias + j]` added. + #[allow(clippy::too_many_arguments)] + pub(super) fn attention_detr( + &mut self, + kernels: &'static Kernels, + [q, k, v]: [Operand; 3], + bias: Option, + out: &wgpu::Buffer, + (queries, keys, heads): (usize, usize, usize), + ) -> Result<(), String> { + let aligned = [q.stride, q.offset, k.stride, k.offset, v.stride, v.offset].iter().all(|n| n.is_multiple_of(4)); + if keys == 0 || !keys.is_multiple_of(KEYS as usize) || !aligned || q.offset != 0 { + return Err("an attention the SAM 3 DETR kernel cannot do".into()); + } + let bias = match bias { + Some(b) => u32_of(b)?, + None => NONE, + }; + let params = + [u32_of(queries)?, u32_of(keys)?, u32_of(q.stride)?, u32_of(k.stride)?, u32_of(v.stride)?, u32_of(k.offset)?, u32_of(v.offset)?, bias]; + let groups = [u32_of(queries.div_ceil(64))?, u32_of(heads)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many queries for the SAM 3 DETR attention kernel".into()); + } + self.push(&kernels.attention, params, [q.buffer, k.buffer, v.buffer, out], groups); + Ok(()) + } +} + +/// One layer's weights on the device: (weight, bias) pairs, the q | k and k | v ones concatenated. +struct Layer { + ln1: [wgpu::Buffer; 2], + self_qk: [wgpu::Buffer; 2], + self_v: [wgpu::Buffer; 2], + self_o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + cross_q: [wgpu::Buffer; 2], + cross_kv: [wgpu::Buffer; 2], + cross_o: [wgpu::Buffer; 2], + ln3: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the encoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn upload(&mut self, names: &[String], shape: &[usize]) -> Result { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{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:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(upload(self.dev, names.first().map_or("weight", String::as_str), &all)) + } + + /// A linear layer (or several along n): `[n, k]` weights and their bias. + fn linear(&mut self, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + Ok([self.upload(&w, &[n, k])?, self.upload(&b, &[n])?]) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.upload(&[format!("{name}.weight")], &[WIDTH])?, self.upload(&[format!("{name}.bias")], &[WIDTH])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let (s, c) = (format!("{l}.self_attn"), format!("{l}.cross_attn")); + let proj = |a: &str, ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + Ok(Layer { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + self_qk: self.linear(&proj(&s, &["q", "k"]), WIDTH, WIDTH)?, + self_v: self.linear(&proj(&s, &["v"]), WIDTH, WIDTH)?, + self_o: self.linear(&proj(&s, &["o"]), WIDTH, WIDTH)?, + ln2: self.norm(&format!("{l}.layer_norm2"))?, + cross_q: self.linear(&proj(&c, &["q"]), WIDTH, WIDTH)?, + cross_kv: self.linear(&proj(&c, &["k", "v"]), WIDTH, WIDTH)?, + cross_o: self.linear(&proj(&c, &["o"]), WIDTH, WIDTH)?, + ln3: self.norm(&format!("{l}.layer_norm3"))?, + fc1: self.linear(&[format!("{l}.mlp.fc1")], MLP, WIDTH)?, + fc2: self.linear(&[format!("{l}.mlp.fc2")], WIDTH, MLP)?, + }) + } +} + +/// The buffers a prompt writes and reads. +struct Work { + /// The image tokens in, the memory out (the layers add to it in place). + x: wgpu::Buffer, + pos: wgpu::Buffer, + text: wgpu::Buffer, + /// The cross-attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The encoder with its weights on the device and its dispatches recorded. +struct Built { + recorded: Recorded, + /// One prompt at a time (they share the work buffers). + work: Mutex, + /// Bytes of device memory: weights, work buffers. + weight_bytes: u64, + work_bytes: u64, +} + +/// The DETR encoder, built on first use from the checkpoint the backbone came from. +pub(super) struct Encoder { + weights: WeightReader, + built: OnceLock>, +} + +impl Encoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, b.work_bytes)) + } + + /// The memory `[5184, 256]` for the image tokens and their position encoding (`[5184, 256]` each) and the prompt's + /// tokens `[32, 256]` (`valid`: its real ones). + pub(super) fn run(&self, dev: &'static Dev, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + if image.len() != TOKENS * WIDTH || pos.len() != TOKENS * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT { + return Err(format!( + "{} image, {} position, {} prompt values and {} prompt tokens, expected {TOKENS} × {WIDTH}, {TOKENS} × {WIDTH}, {TEXT} × {WIDTH} and {TEXT}", + image.len(), + pos.len(), + text.len(), + valid.len() + )); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + dev.queue.write_buffer(&work.x, 0, bytemuck::cast_slice(image)); + dev.queue.write_buffer(&work.pos, 0, bytemuck::cast_slice(pos)); + dev.queue.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + dev.queue.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + let out = b.recorded.run("the SAM 3 DETR encoder", dev, &work.x, &work.staging, TOKENS * WIDTH)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU DETR encoder produced non-finite values".into()); + } + Ok(out) + } +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + let k = kernels(dev)?; + 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, k, weights); + // 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!("not enough GPU memory for the SAM 3 DETR encoder: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 DETR encoder: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader) -> Result { + let mut ld = Loader { weights, dev, bytes: 0 }; + let layers = (0..LAYERS).map(|i| ld.layer(i)).collect::, _>>()?; + + let tokens = |label: &str| buffer(dev, label, TOKENS * WIDTH); + let (x, y, hp, v, att, pos) = + (tokens("detr hidden"), tokens("detr normed"), tokens("detr normed + pos"), tokens("detr v"), tokens("detr attention"), tokens("detr pos")); + // the self-attention's q | k, then the MLP's hidden activations + let wide = buffer(dev, "detr wide", TOKENS * MLP.max(2 * WIDTH)); + let text = buffer(dev, "detr prompt", TEXT * WIDTH); + let text_kv = buffer(dev, "detr prompt k|v", TEXT * 2 * WIDTH + TEXT); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("detr read-back"), + size: (TOKENS * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((7 * TOKENS * WIDTH + TOKENS * MLP + TEXT * (3 * WIDTH + 1)) * 4) as u64; + + let mut g = Graph::new(dev); + let heads = WIDTH / HEAD_DIM; + for l in &layers { + // self-attention: q and k from the normed tokens plus their position, v from the normed tokens + g.layernorm_torch([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, WIDTH)?; + g.add(k, [&y, &pos, &hp], TOKENS * WIDTH)?; + g.matmul([&hp, &l.self_qk[0], &l.self_qk[1], &wide], (TOKENS, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&y, &l.self_v[0], &l.self_v[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (q, kk) = (Operand { buffer: &wide, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &wide, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [q, kk, Operand { buffer: &v, stride: WIDTH, offset: 0 }], None, &att, (TOKENS, TOKENS, heads))?; + g.matmul([&att, &l.self_o[0], &l.self_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // cross-attention to the prompt, its padding masked + g.layernorm_torch([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, WIDTH)?; + g.matmul([&y, &l.cross_q[0], &l.cross_q[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&text, &l.cross_kv[0], &l.cross_kv[1], &text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (tk, tv) = (Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [Operand { buffer: &v, stride: WIDTH, offset: 0 }, tk, tv], Some(TEXT * 2 * WIDTH), &att, (TOKENS, TEXT, heads))?; + g.matmul([&att, &l.cross_o[0], &l.cross_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // MLP + g.layernorm_torch([&x, &l.ln3[0], &l.ln3[1], &y], TOKENS, WIDTH)?; + g.matmul_relu([&y, &l.fc1[0], &l.fc1[1], &wide], (TOKENS, MLP, WIDTH))?; + g.matmul([&wide, &l.fc2[0], &l.fc2[1], &x], (TOKENS, WIDTH, MLP), 1, false, true, Precision::F32)?; + g.cut(); + } + let recorded = g.record(); + Ok(Built { recorded, work: Mutex::new(Work { x, pos, text, text_kv, staging }), weight_bytes: ld.bytes, work_bytes }) +} diff --git a/crates/gpu/src/sam3/detr/tests.rs b/crates/gpu/src/sam3/detr/tests.rs new file mode 100644 index 0000000000..95884facab --- /dev/null +++ b/crates/gpu/src/sam3/detr/tests.rs @@ -0,0 +1,267 @@ +//! The DETR encoder's kernels against plain loops: attention with heads of 32 (self- and cross-attention, the padding +//! bias, queries not filling the last workgroup), the sum, ReLU and the layer norm's eps. The whole encoder against +//! candle: `tests/it/sam3_detr.rs`. + +use super::super::dev; +use super::*; + +fn gpu() -> Option<(&'static Dev, &'static Kernels)> { + let d = match dev() { + Ok(d) => 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})"); + return None; + } + }; + Some((d, kernels(d).unwrap())) +} + +/// Deterministic values in −scale..scale. +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() +} + +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() +} + +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())) +} + +/// Where a test attention's operand is in its buffer. +struct At<'a> { + data: &'a [f32], + stride: usize, + offset: usize, +} + +/// Softmax attention of every query over all keys, `heads` heads of 32, as candle computes it: the scores +/// `q · k / sqrt(32) + bias` in f32 (so f32::MIN swallows a padded key's score), the rest in f64. +fn attention_ref(q: At, k: At, v: At, bias: Option<&[f32]>, (queries, keys, heads): (usize, usize, usize)) -> Vec { + let scale = (HEAD_DIM as f32).powf(-0.5); + let mut out = vec![0f32; queries * heads * HEAD_DIM]; + for t in 0..queries { + for h in 0..heads { + let at = |o: &At, row: usize, c: usize| o.data[row * o.stride + o.offset + h * HEAD_DIM + c]; + let scores: Vec = (0..keys) + .map(|j| { + let dot = (0..HEAD_DIM).map(|c| f64::from(at(&q, t, c)) * f64::from(at(&k, j, c))).sum::() as f32; + dot * scale + bias.map_or(0.0, |b| b[j]) + }) + .collect(); + let top = scores.iter().fold(f32::MIN, |m, s| m.max(*s)); + let w: Vec = scores.iter().map(|s| f64::from(s - top).exp()).collect(); + let sum: f64 = w.iter().sum(); + for c in 0..HEAD_DIM { + let o = (0..keys).map(|j| w[j] * f64::from(at(&v, j, c))).sum::() / sum; + out[(t * heads + h) * HEAD_DIM + c] = o as f32; + } + } + } + out +} + +#[test] +fn the_kernel_source_is_written_out() { + let src = attention_source(KEYS); + assert!(!src.contains("{{"), "a mark is left"); + assert!(src.contains("let s31 = ") && !src.contains("let s32 = ")); + assert!(src.contains("let q7 = ") && !src.contains("let q8 = ")); +} + +#[test] +fn self_attention_over_8_heads_of_32_gives_the_softmax_of_the_definition() { + let Some((d, k)) = gpu() else { return }; + let heads = 8; + let w = heads * HEAD_DIM; + // q | k in one buffer (k at column 256), v in another; 200 queries leave the last workgroup part empty + for (queries, keys) in [(200, 96), (64, 32), (130, 320)] { + let rows = queries.max(keys); + let qk = values(rows * 2 * w, queries as u64, 2.0); + let v = values(keys * w, 7 + keys as u64, 1.0); + let (bqk, bv) = (upload(d, "qk", &qk), upload(d, "v", &v)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bqk, stride: 2 * w, offset: 0 }, + Operand { buffer: &bqk, stride: 2 * w, offset: w }, + Operand { buffer: &bv, stride: w, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &out, (queries, keys, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &qk, stride: 2 * w, offset: 0 }, + At { data: &qk, stride: 2 * w, offset: w }, + At { data: &v, stride: w, offset: 0 }, + None, + (queries, keys, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{queries} queries × {keys} keys: off by {err}"); + } +} + +#[test] +fn cross_attention_to_32_prompt_tokens_leaves_out_the_padding() { + let Some((d, k)) = gpu() else { return }; + let (heads, queries) = (8, 130); + let w = heads * HEAD_DIM; + let q = values(queries * w, 1, 2.0); + // the prompt's k | v ([32, 512]), then its bias: 0 for the real tokens, f32::MIN for padding + for real in [5, 32, 1, 0] { + let mut kv = values(TEXT * 2 * w, 2 + real as u64, 2.0); + let bias: Vec = (0..TEXT).map(|j| if j < real { 0.0 } else { f32::MIN }).collect(); + kv.extend(&bias); + let (bq, bkv) = (upload(d, "q", &q), upload(d, "kv", &kv)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bq, stride: w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: w }, + ]; + g.attention_detr(k, ops, Some(TEXT * 2 * w), &out, (queries, TEXT, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &q, stride: w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: w }, + Some(&bias), + (queries, TEXT, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{real} real tokens: off by {err}"); + if real == 1 { + // one real token: every query gets its v + let first = &kv[w..2 * w]; + assert!(worst(&got[..w], first) < 1e-6); + } + } +} + +#[test] +fn attention_the_kernel_cannot_do_is_an_error() { + let Some((d, k)) = gpu() else { return }; + let b = buffer(d, "b", 64 * 256); + let op = |stride, offset| Operand { buffer: &b, stride, offset }; + // keys not a multiple of 32, a stride not a multiple of 4, q not at column 0 + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(256, 0), op(256, 0)], None, &b, (64, 40, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(258, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 4), op(256, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).add(k, [&b, &b, &b], 6).is_err()); +} + +#[test] +fn sum_relu_and_torch_layer_norm_give_what_the_definitions_give() { + let Some((d, k)) = gpu() else { return }; + // the sum, over more than one row of workgroups' worth + let n = 4 * 256 * 70 + 12; + let (a, b) = (values(n, 1, 1.0), values(n, 2, 1.0)); + let (ba, bb, out) = (upload(d, "a", &a), upload(d, "b", &b), buffer(d, "out", n)); + let mut g = Graph::new(d); + g.add(k, [&ba, &bb, &out], n).unwrap(); + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + assert_eq!(read(d, g, &out, n), want); + + // ReLU in the product's epilogue + let (m, nn, kk) = (70, 90, 64); + let (x, w, bias) = (values(m * kk, 3, 1.0), values(nn * kk, 4, 0.3), values(nn, 5, 0.5)); + let (bx, bw, bbias, by) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "bias", &bias), buffer(d, "y", m * nn)); + let mut g = Graph::new(d); + g.matmul_relu([&bx, &bw, &bbias, &by], (m, nn, kk)).unwrap(); + let got = read(d, g, &by, m * nn); + let want: Vec = (0..m * nn) + .map(|o| { + let (i, j) = (o / nn, o % nn); + let v = f64::from(bias[j]) + (0..kk).map(|t| f64::from(x[i * kk + t]) * f64::from(w[j * kk + t])).sum::(); + v.max(0.0) as f32 + }) + .collect(); + assert!(worst(&got, &want) < 1e-5); + assert!(got.contains(&0.0) && got.iter().any(|v| *v > 0.0)); + + // rows of small spread, where eps 1e-5 and 1e-6 differ + let (rows, c) = (5, WIDTH); + let x = values(rows * c, 6, 3e-3); + let (gamma, beta) = (values(c, 7, 1.0), values(c, 8, 0.1)); + 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_torch([&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| f64::from(*v)).sum::() / c as f64; + let var = row.iter().map(|v| (f64::from(*v) - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((f64::from(row[i]) - mean) / (var + f64::from(EPS)).sqrt() * f64::from(gamma[i]) + f64::from(beta[i])) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 1e-4, "layer norm off by {err}"); +} + +/// The encoder's steps at its shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::detr::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some((d, k)) = 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 * WIDTH); + let b = buffer(d, "b", MLP); + for (n, kk) in [(2 * WIDTH, WIDTH), (WIDTH, WIDTH), (MLP, WIDTH), (WIDTH, MLP)] { + let flops = 2.0 * (TOKENS * n * kk) as f64; + time(&format!("matmul {TOKENS}x{n}x{kk}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, kk), 1, false, false, Precision::F32).unwrap()); + } + for keys in [TOKENS, TEXT] { + let flops = 4.0 * (TOKENS * keys * WIDTH) as f64; + time(&format!("attention {keys} keys"), flops, &|g| { + let ops = [ + Operand { buffer: &x, stride: 2 * WIDTH, offset: 0 }, + Operand { buffer: &x, stride: 2 * WIDTH, offset: WIDTH }, + Operand { buffer: &x, stride: WIDTH, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &y, (TOKENS, keys, WIDTH / HEAD_DIM)).unwrap() + }); + } + time("layernorm", 0.0, &|g| g.layernorm_torch([&x, &b, &b, &y], TOKENS, WIDTH).unwrap()); + time("add", 0.0, &|g| g.add(k, [&x, &x, &y], TOKENS * WIDTH).unwrap()); +} diff --git a/crates/gpu/src/sam3/neck.rs b/crates/gpu/src/sam3/neck.rs new file mode 100644 index 0000000000..1d42fd341f --- /dev/null +++ b/crates/gpu/src/sam3/neck.rs @@ -0,0 +1,425 @@ +//! SAM 3's feature pyramids on the GPU: the necks of `lightcraft-segment` (`neck.rs`, the reference) for the click +//! decoder (`tracker_neck`) and the text detector (`detector_model.vision_encoder.neck`), the three finest levels of +//! each (288, 144 and 72 per side, 256 channels), from the backbone's `[1024, 72, 72]`. +//! +//! Images are kept as pixel rows (`[pixels, channels]`), so every step is a product of the backbone's matrix kernel: +//! - a 2 × 2 stride-2 transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` +//! (the checkpoint's `[cin, cout, 2, 2]` laid out as `[(ky, kx, cout), cin]` on upload), whose row holds the +//! pixel's four outputs one after the other; GELU (erf) between the two of level 0 runs in its epilogue; +//! - `proj1` (1 × 1) is a plain product, and does not care in which order the pixels come; +//! - `unshuffle` (`wgsl/sam3_neck.wgsl`) then puts the pixels of the transposed convolutions in row-major order; +//! - `proj2` (3 × 3, padding 1) is the same kernel with an A-tile loader that reads the 9 · cin numbers of a pixel's +//! neighbourhood straight from the image (`wgsl/sam3_conv.wgsl`): an implicit GEMM, the im2col matrix (764 MB at +//! 288²) never exists; +//! - `to_chw` (`wgsl/sam3_ops.wgsl`) writes the channels-first result. +//! +//! Nothing is uploaded with the backbone: the kernels compile, the work buffers (~190 MB, shared by both necks) are +//! made and a neck's weights (~27 MB) are uploaded when that neck is first asked for. A level is one submission +//! and one read-back, so no buffer exceeds the backbone's limits. Level 3 (36², a max pool) is not needed by either +//! head and is not run here. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::{NeckKind, WeightReader}; + +use super::{Dev, GRID, Graph, HIDDEN, Matmul, Precision, Recorded, TILE, TIMEOUT, buffer, matmul_source_with, pipeline, u32_of, upload}; + +#[cfg(test)] +pub(super) mod tests; + +/// Channels of every level. +const FPN: usize = 256; +/// Levels run here: 288², 144² and 72². +const LEVELS: usize = 3; + +/// The sizes of a neck: the backbone's side and channels, and the channels of the levels (SAM 3's, or small ones +/// in tests). +#[derive(Clone, Copy, Debug)] +struct Sizes { + grid: usize, + hidden: usize, + fpn: usize, +} + +const SAM3: Sizes = Sizes { grid: GRID, hidden: HIDDEN, fpn: FPN }; + +impl Sizes { + /// Floats of the largest step of level 0: the second transposed convolution's output (4 · grid² · hidden), or a + /// 256-channel image of (4 · grid)² (both 85 MB for SAM 3). + fn largest(self) -> usize { + self.grid * self.grid * (4 * self.hidden).max(16 * self.fpn) + } +} + +/// Where a neck's tensors are in the checkpoint. +fn prefix(which: NeckKind) -> &'static str { + match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// kernels + +pub(super) struct Kernels { + /// The 3 × 3 convolution: the matrix product with the implicit-im2col A loader. + conv: Matmul, + to_rows: wgpu::ComputePipeline, + unshuffle: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The neck's own kernels, compiled on first use (the backbone's are compiled with the device; the mask decoder uses +/// the 3 × 3 convolution too). +pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&dev.device, &dev.pipeline_layout, label, source, entry); + let conv = matmul_source_with(TILE, false, Some(include_str!("../wgsl/sam3_conv.wgsl"))); + let ops = include_str!("../wgsl/sam3_neck.wgsl"); + let k = Kernels { + conv: Matmul { pipeline: pipe("sam3 conv3x3", &conv, "main"), tile: TILE }, + to_rows: pipe("sam3 neck", ops, "to_rows"), + unshuffle: pipe("sam3 neck", ops, "unshuffle"), + }; + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 neck kernels did not compile ({e})", dev.info.name)); + } + Ok(k) + }) + .as_ref() + .map_err(Clone::clone) +} + +impl Graph { + /// The 3 × 3 convolution (padding 1) of the image `x` (`[side², cin]`, cin a multiple of 4) with `w` + /// (`[cout, 3, 3, cin]`) and `bias` (`[cout]`) into `y` (`[side², cout]`). + pub(super) fn conv3( + &mut self, + k: &'static Kernels, + [x, w, bias, y]: [&wgpu::Buffer; 4], + side: usize, + (cin, cout): (usize, usize), + ) -> Result<(), String> { + if side == 0 || !cin.is_multiple_of(4) || cin == 0 || cout == 0 { + return Err(format!("a {side}² {cin} → {cout} convolution the SAM 3 kernel cannot do")); + } + let (m, depth) = (side * side, 9 * cin); + let params = [u32_of(m)?, u32_of(cout)?, u32_of(depth)?, 1, 0, 0, u32_of(side)?, 0]; + let groups = [u32_of(cout.div_ceil(k.conv.tile.bn()))?, u32_of(m.div_ceil(k.conv.tile.bm()))?, 1]; + if groups[1] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("an image too large for the SAM 3 convolution kernel".into()); + } + self.push(&k.conv.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// `[channels, pixels]` (channels-first) to `[pixels, channels]`. + fn channels_last(&mut self, k: &'static Kernels, src: &wgpu::Buffer, dst: &wgpu::Buffer, channels: usize, pixels: usize) -> Result<(), String> { + let count = channels.checked_mul(pixels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.to_rows, [u32_of(channels)?, u32_of(pixels)?, 0, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } + + /// The rows of a `side × side` image after `ups` 2 × 2 stride-2 transposed convolutions (in their order, see + /// `wgsl/sam3_neck.wgsl`) in row-major order. + fn unshuffle( + &mut self, + k: &'static Kernels, + src: &wgpu::Buffer, + dst: &wgpu::Buffer, + channels: usize, + side: usize, + ups: usize, + ) -> Result<(), String> { + if ups >= 16 || !side.is_multiple_of(1 << ups) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(side * side).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.unshuffle, [u32_of(channels)?, u32_of(side)?, u32_of(ups)?, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// weights + +/// A transposed convolution's weights `[cin, cout, 2, 2]` as the rows of a product: `[(ky · 2 + kx) · cout + co, ci]`. +fn transposed_rows(w: &[f32], cin: usize, cout: usize) -> Vec { + let mut out = vec![0f32; w.len()]; + for ci in 0..cin { + for co in 0..cout { + for q in 0..4 { + if let (Some(o), Some(v)) = (out.get_mut((q * cout + co) * cin + ci), w.get((ci * cout + co) * 4 + q)) { + *o = *v; + } + } + } + } + out +} + +/// A convolution's weights `[cout, cin, k, k]` in the order of the convolution's A columns: `[cout, k, k, cin]`. +fn conv_rows(w: &[f32], cout: usize, cin: usize, k: usize) -> Vec { + let taps = k * k; + let mut out = vec![0f32; w.len()]; + for co in 0..cout { + for ci in 0..cin { + for t in 0..taps { + if let (Some(o), Some(v)) = (out.get_mut((co * taps + t) * cin + ci), w.get((co * cin + ci) * taps + t)) { + *o = *v; + } + } + } + } + out +} + +/// A transposed convolution's weight `[cin, cout, 2, 2]` and bias on the device: rows `[4 · cout, cin]`, and the +/// bias repeated for the four outputs. +fn transposed_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], cin: usize, cout: usize) -> [wgpu::Buffer; 2] { + [upload(dev, label, &transposed_rows(w, cin, cout)), upload(dev, label, &b.repeat(4))] +} + +/// A `k × k` convolution's weight `[cout, cin, k, k]` and bias on the device: rows `[cout, k, k, cin]`. +pub(super) fn conv_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], (cin, cout, k): (usize, usize, usize)) -> [wgpu::Buffer; 2] { + [upload(dev, label, &conv_rows(w, cout, cin, k)), upload(dev, label, b)] +} + +/// One level's weights on the device: the transposed convolutions (none, one or two), `proj1`, `proj2`. +struct LevelWeights { + up: Vec<[wgpu::Buffer; 2]>, + proj1: [wgpu::Buffer; 2], + proj2: [wgpu::Buffer; 2], +} + +/// Reads a neck's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + prefix: &'static str, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{}.{name}", self.prefix); + 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 2 × 2 stride-2 transposed convolution. + fn transposed(&mut self, name: &str, cin: usize, cout: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cin, cout, 2, 2])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + 4 * b.len()) as u64 * 4; + Ok(transposed_weights(self.dev, name, &w, &b, cin, cout)) + } + + /// A `k × k` convolution. + fn conv(&mut self, name: &str, cin: usize, cout: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cout, cin, k, k])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + b.len()) as u64 * 4; + Ok(conv_weights(self.dev, name, &w, &b, (cin, cout, k))) + } + + /// Level `i` (0: 4× up, 1: 2× up, 2: as is). + fn level(&mut self, i: usize) -> Result { + let l = format!("fpn_layers.{i}"); + let s = format!("{l}.scale_layers"); + let (up, inter) = match i { + 0 => ( + vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?, self.transposed(&format!("{s}.2"), HIDDEN / 2, HIDDEN / 4)?], + HIDDEN / 4, + ), + 1 => (vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?], HIDDEN / 2), + 2 => (Vec::new(), HIDDEN), + _ => return Err(format!("level {i} of the SAM 3 neck does not run on the GPU")), + }; + Ok(LevelWeights { up, proj1: self.conv(&format!("{l}.proj1"), inter, FPN, 1)?, proj2: self.conv(&format!("{l}.proj2"), FPN, FPN, 3)? }) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the necks + +/// The work buffers, shared by both necks (one runs at a time): the backbone as pixel rows, two buffers the steps +/// alternate between (the backbone's upload lands in the first), and the read-back. +struct Work { + x: wgpu::Buffer, + a: wgpu::Buffer, + b: wgpu::Buffer, + staging: wgpu::Buffer, +} + +impl Work { + fn new(dev: &Dev, sizes: Sizes) -> Work { + let largest = sizes.largest(); + Work { + x: buffer(dev, "sam3 neck input", sizes.hidden * sizes.grid * sizes.grid), + a: buffer(dev, "sam3 neck ping", largest), + b: buffer(dev, "sam3 neck pong", largest), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 neck read-back"), + size: (largest.max(4) * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes(sizes: Sizes) -> u64 { + ((sizes.hidden * sizes.grid * sizes.grid + 2 * sizes.largest()) * 4) as u64 + } +} + +/// One level, recorded: its dispatches, and the buffer its `[256, side, side]` result ends in (`len` floats). +struct Level { + recorded: Recorded, + out: wgpu::Buffer, + len: usize, +} + +/// A neck with its weights uploaded and its levels recorded. +struct Built { + levels: Vec, + weight_bytes: u64, +} + +/// The dispatches of level `i` from the pixel rows in `work.x` (level 0 first fills them from the channels-first +/// upload in `work.a`). +fn record_level(dev: &'static Dev, k: &'static Kernels, work: &Work, w: &LevelWeights, i: usize, sizes: Sizes) -> Result { + let Sizes { grid, hidden, fpn } = sizes; + let mut g = Graph::new(dev); + if i == 0 { + g.channels_last(k, &work.a, &work.x, hidden, grid * grid)?; + } + let mut spare = [&work.a, &work.b].into_iter().cycle(); + let mut next = || spare.next().ok_or_else(|| "no work buffer".to_string()); + let (mut cur, mut pixels, mut channels, mut side) = (&work.x, grid * grid, hidden, grid); + for (j, [weight, bias]) in w.up.iter().enumerate() { + let cout = channels / 2; + let dst = next()?; + // GELU between the two of level 0 + g.matmul([cur, weight, bias, dst], (pixels, 4 * cout, channels), 1, j + 1 < w.up.len(), false, Precision::F32)?; + (cur, pixels, channels, side) = (dst, pixels * 4, cout, side * 2); + } + let dst = next()?; + g.matmul([cur, &w.proj1[0], &w.proj1[1], dst], (pixels, fpn, channels), 1, false, false, Precision::F32)?; + cur = dst; + if !w.up.is_empty() { + let dst = next()?; + g.unshuffle(k, cur, dst, fpn, side, w.up.len())?; + cur = dst; + } + let dst = next()?; + g.conv3(k, [cur, &w.proj2[0], &w.proj2[1], dst], side, (fpn, fpn))?; + cur = dst; + let dst = next()?; + g.channels_first(cur, dst, fpn, side, side)?; + Ok(Level { recorded: g.record(), out: dst.clone(), len: fpn * side * side }) +} + +fn build(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader, which: NeckKind, work: &Work) -> Result { + let mut ld = Loader { weights, dev, prefix: prefix(which), bytes: 0 }; + let mut levels = Vec::with_capacity(LEVELS); + for i in 0..LEVELS { + let w = ld.level(i)?; + levels.push(record_level(dev, k, work, &w, i, SAM3)?); + } + Ok(Built { levels, weight_bytes: ld.bytes }) +} + +/// Run `f` (buffer creation and uploads for `stage`), turning the device's out-of-memory and validation errors into an +/// `Err` that names the stage. +pub(super) fn scoped(dev: &Dev, stage: &str, f: impl FnOnce() -> Result) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = f(); + // 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!("not enough GPU memory for {stage}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected {stage}: {e}")); + } + made +} + +#[derive(Default)] +struct State { + work: Option, + tracker: Option, + detector: Option, +} + +/// Both necks of a backbone on the GPU, each built when first run. +pub(super) struct Necks { + weights: WeightReader, + state: Mutex, +} + +impl Necks { + pub(super) fn new(weights: WeightReader) -> Necks { + Necks { weights, state: Mutex::new(State::default()) } + } + + /// The `n` finest levels of the `which` neck for `backbone` (`[1024, 72, 72]`), each `[256, s, s]`. + pub(super) fn run(&self, dev: &'static Dev, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if n > LEVELS { + return Err(format!("{n} levels asked for; the GPU neck makes the {LEVELS} finest")); + } + if backbone.len() != HIDDEN * GRID * GRID { + return Err(format!("{} backbone values, expected {HIDDEN} × {GRID} × {GRID}", backbone.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let State { work, tracker, detector } = &mut *state; + let work = match work { + Some(w) => w, + None => work.insert(scoped(dev, "the SAM 3 necks", || Ok(Work::new(dev, SAM3)))?), + }; + let built = match which { + NeckKind::Tracker => tracker, + NeckKind::Detector => detector, + }; + let built = match built { + Some(b) => b, + None => { + let k = kernels(dev)?; + built.insert(scoped(dev, "a SAM 3 neck", || build(dev, k, &self.weights, which, work))?) + } + }; + dev.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(backbone)); + built.levels.iter().take(n).map(|l| l.recorded.run("a SAM 3 neck", dev, &l.out, &work.staging, l.len)).collect() + } + + /// Device memory the necks built so far take (weights and work buffers). + fn bytes(&self) -> u64 { + let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let weights: u64 = [&state.tracker, &state.detector].into_iter().flatten().map(|b| b.weight_bytes).sum(); + weights + if state.work.is_some() { Work::bytes(SAM3) } else { 0 } + } +} + +impl super::Sam3Gpu { + /// Bytes of device memory the necks run so far take (0 before the first): their weights and the work buffers + /// they share. + pub fn neck_bytes(&self) -> u64 { + self.necks.bytes() + } +} diff --git a/crates/gpu/src/sam3/neck/tests.rs b/crates/gpu/src/sam3/neck/tests.rs new file mode 100644 index 0000000000..d7b1ec668e --- /dev/null +++ b/crates/gpu/src/sam3/neck/tests.rs @@ -0,0 +1,215 @@ +//! The neck kernels against plain loops in f64 (odd sizes, every border of the 3 × 3 convolution, tiles cut off), and +//! a whole small neck against a direct transcription of `Neck::forward`. The real necks against candle: +//! `tests/it/sam3_backbone.rs`. + +use super::super::tests::{gelu, gpu, read, values, worst}; +use super::*; + +/// The neck's kernels on the test device; a kernel that doesn't compile is a failure. +fn neck_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// PyTorch's `ConvTranspose2d(cin, cout, 2, stride 2)` on pixel rows `x` (`[side², cin]`), weight `[cin, cout, 2, 2]`: +/// `[(2 · side)², cout]`, row-major. +fn conv_transpose_ref(x: &[f64], side: usize, (cin, cout): (usize, usize), w: &[f32], b: &[f32]) -> Vec { + let out_side = 2 * side; + let mut y = vec![0f64; out_side * out_side * cout]; + for i in 0..side { + for j in 0..side { + for ky in 0..2 { + for kx in 0..2 { + for co in 0..cout { + let mut v = b[co] as f64; + for ci in 0..cin { + v += x[(i * side + j) * cin + ci] * w[((ci * cout + co) * 2 + ky) * 2 + kx] as f64; + } + y[((2 * i + ky) * out_side + 2 * j + kx) * cout + co] = v; + } + } + } + } + } + y +} + +/// PyTorch's `Conv2d(cin, cout, k, padding k / 2)` on pixel rows `x` (`[side², cin]`), weight `[cout, cin, k, k]`: +/// `[side², cout]`. +pub(in crate::sam3) fn conv_ref(x: &[f64], side: usize, (cin, cout, k): (usize, usize, usize), w: &[f32], b: &[f32]) -> Vec { + let pad = (k / 2) as isize; + let mut y = vec![0f64; side * side * cout]; + for r in 0..side { + for c in 0..side { + for co in 0..cout { + let mut v = b[co] as f64; + for ky in 0..k { + for kx in 0..k { + let (rr, cc) = (r as isize + ky as isize - pad, c as isize + kx as isize - pad); + if rr < 0 || cc < 0 || rr >= side as isize || cc >= side as isize { + continue; + } + let at = (rr as usize * side + cc as usize) * cin; + for ci in 0..cin { + v += x[at + ci] * w[((co * cin + ci) * k + ky) * k + kx] as f64; + } + } + } + y[(r * side + c) * cout + co] = v; + } + } + } + y +} + +pub(in crate::sam3) fn f32s(v: &[f64]) -> Vec { + v.iter().map(|x| *x as f32).collect() +} + +pub(in crate::sam3) fn f64s(v: &[f32]) -> Vec { + v.iter().map(|x| *x as f64).collect() +} + +#[test] +fn weights_are_laid_out_as_the_products_read_them() { + // ConvTranspose2d [cin 2, cout 3, 2, 2]: value = 1000 ci + 100 co + 10 ky + kx; rows [(ky, kx, co), ci] + let w: Vec = + (0..2).flat_map(|ci| (0..3).flat_map(move |co| (0..4).map(move |q| (1000 * ci + 100 * co + 10 * (q / 2) + q % 2) as f32))).collect(); + let rows = transposed_rows(&w, 2, 3); + assert_eq!(rows[(3 * 3 + 2) * 2 + 1], 1211.0); + assert_eq!(rows[3 * 2], 1.0); + // Conv2d [cout 2, cin 3, 3, 3]: value = 1000 co + 100 ci + 10 ky + kx; rows [cout, ky, kx, cin] + let w: Vec = + (0..2).flat_map(|co| (0..3).flat_map(move |ci| (0..9).map(move |t| (1000 * co + 100 * ci + 10 * (t / 3) + t % 3) as f32))).collect(); + let rows = conv_rows(&w, 2, 3, 3); + assert_eq!(rows[(9 + 2 * 3 + 1) * 3 + 2], 1221.0); + assert_eq!(rows[4 * 3], 11.0); +} + +#[test] +fn transposed_convolutions_and_the_reorder_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // one up-sampling (odd side, cut-off tiles), and two with GELU between as in level 0 + for (case, (side, chans)) in [(5usize, vec![8usize, 6]), (3, vec![12, 8, 4]), (9, vec![4, 68])].into_iter().enumerate() { + let x = values(side * side * chans[0], 10 + case as u64, 1.0); + let mut want = f64s(&x); + let mut s = side; + let mut g = Graph::new(d); + let mut cur = upload(d, "x", &x); + for (j, pair) in chans.windows(2).enumerate() { + let (cin, cout) = (pair[0], pair[1]); + let w = values(cin * cout * 4, 20 + j as u64, 0.3); + let b = values(cout, 30 + j as u64, 0.5); + let gelu_after = j + 2 < chans.len(); + want = conv_transpose_ref(&want, s, (cin, cout), &w, &b); + if gelu_after { + want.iter_mut().for_each(|v| *v = gelu(*v)); + } + let [bw, bb] = transposed_weights(d, "w", &w, &b, cin, cout); + let y = buffer(d, "y", s * s * 4 * cout); + g.matmul([&cur, &bw, &bb, &y], (s * s, 4 * cout, cin), 1, gelu_after, false, Precision::F32).unwrap(); + cur = y; + s *= 2; + } + let cout = *chans.last().unwrap(); + let out = buffer(d, "out", s * s * cout); + g.unshuffle(k, &cur, &out, cout, s, chans.len() - 1).unwrap(); + let got = read(d, g, &out, s * s * cout); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "case {case}: off by {err}"); + } +} + +#[test] +fn the_3x3_convolution_gives_the_definition_at_every_border() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // odd sides, a single pixel (all border), N not a multiple of the tile, more pixels than one tile + for (case, (side, cin, cout)) in [(7usize, 12usize, 5usize), (1, 8, 3), (9, 4, 70), (17, 16, 64), (2, 256, 9)].into_iter().enumerate() { + let x = values(side * side * cin, 40 + case as u64, 1.0); + let w = values(cout * cin * 9, 50 + case as u64, 0.2); + let b = values(cout, 60 + case as u64, 0.5); + let [bw, bb] = conv_weights(d, "w", &w, &b, (cin, cout, 3)); + let (bx, by) = (upload(d, "x", &x), buffer(d, "y", side * side * cout)); + let mut g = Graph::new(d); + g.conv3(k, [&bx, &bw, &bb, &by], side, (cin, cout)).unwrap(); + let got = read(d, g, &by, side * side * cout); + let want = f32s(&conv_ref(&f64s(&x), side, (cin, cout, 3), &w, &b)); + let err = worst(&got, &want); + assert!(err < 2e-5 * ((9 * cin) as f32).sqrt(), "case {case} ({side}² {cin} → {cout}): off by {err}"); + } +} + +#[test] +fn the_neck_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.conv3(k, [&b, &b, &b, &b], 4, (6, 8)).is_err(), "channels not a multiple of 4"); + assert!(g.conv3(k, [&b, &b, &b, &b], 0, (8, 8)).is_err(), "an empty image"); + assert!(g.unshuffle(k, &b, &b, 4, 6, 2).is_err(), "a side that is not a multiple of 2^ups"); +} + +/// A neck level's weights in the checkpoint's layouts: the transposed convolutions (weight, bias, cin, cout), +/// `proj1` (weight, bias, cin) and `proj2`. +struct RefLevel { + up: Vec<(Vec, Vec, usize, usize)>, + proj1: (Vec, Vec, usize), + proj2: (Vec, Vec), +} + +/// `Neck::forward` for one level on the channels-first backbone `x`, in f64: `[fpn, side, side]`. +fn level_ref(x: &[f32], sizes: Sizes, l: &RefLevel) -> Vec { + let Sizes { grid, hidden, fpn } = sizes; + let mut rows: Vec = (0..grid * grid).flat_map(|p| (0..hidden).map(move |c| x[c * grid * grid + p] as f64)).collect(); + let mut side = grid; + for (j, (w, b, cin, cout)) in l.up.iter().enumerate() { + rows = conv_transpose_ref(&rows, side, (*cin, *cout), w, b); + if j + 1 < l.up.len() { + rows.iter_mut().for_each(|v| *v = gelu(*v)); + } + side *= 2; + } + let (w1, b1, inter) = &l.proj1; + let rows = conv_ref(&rows, side, (*inter, fpn, 1), w1, b1); + let rows = conv_ref(&rows, side, (fpn, fpn, 3), &l.proj2.0, &l.proj2.1); + (0..fpn).flat_map(|c| (0..side * side).map(move |p| (c, p))).map(|(c, p)| rows[p * fpn + c] as f32).collect() +} + +#[test] +fn a_small_neck_gives_what_the_reference_neck_gives() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let sizes = Sizes { grid: 6, hidden: 32, fpn: 8 }; + let Sizes { grid, hidden, fpn } = sizes; + let x = values(hidden * grid * grid, 70, 1.0); + let work = Work::new(d, sizes); + d.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(&x)); + let mut seed = 80; + let mut next = |n: usize, scale: f32| { + seed += 1; + values(n, seed, scale) + }; + // in order: level 0 turns the upload into the pixel rows the others read + for i in 0..LEVELS { + let chans: Vec = match i { + 0 => vec![hidden, hidden / 2, hidden / 4], + 1 => vec![hidden, hidden / 2], + _ => vec![hidden], + }; + let up: Vec<_> = chans.windows(2).map(|p| (next(p[0] * p[1] * 4, 0.3), next(p[1], 0.3), p[0], p[1])).collect(); + let inter = *chans.last().unwrap(); + let r = RefLevel { up, proj1: (next(fpn * inter, 0.3), next(fpn, 0.3), inter), proj2: (next(fpn * fpn * 9, 0.2), next(fpn, 0.3)) }; + let w = LevelWeights { + up: r.up.iter().map(|(w, b, cin, cout)| transposed_weights(d, "up", w, b, *cin, *cout)).collect(), + proj1: conv_weights(d, "proj1", &r.proj1.0, &r.proj1.1, (inter, fpn, 1)), + proj2: conv_weights(d, "proj2", &r.proj2.0, &r.proj2.1, (fpn, fpn, 3)), + }; + let level = record_level(d, k, &work, &w, i, sizes).unwrap(); + let got = level.recorded.run("a test", d, &level.out, &work.staging, level.len).unwrap(); + let want = level_ref(&x, sizes, &r); + let err = worst(&got, &want); + assert!(err < 1e-4, "level {i}: off by {err}"); + } +} diff --git a/crates/gpu/src/sam3/pixel.rs b/crates/gpu/src/sam3/pixel.rs new file mode 100644 index 0000000000..08d5f5b749 --- /dev/null +++ b/crates/gpu/src/sam3/pixel.rs @@ -0,0 +1,377 @@ +//! The mask decoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): the +//! DETR encoder's memory (72 × 72 tokens of 256) attends to the prompt and is added to it (`prompt_cross_attn`, after +//! its layer norm), then the pixel decoder brings it up to 288 × 288 in two stages, each a nearest 2 × up-sampling plus +//! the detector neck's level of that size (144², then 288²) → 3 × 3 convolution → GroupNorm (8 groups, eps 1e-5) → +//! ReLU; last, every row of a `[r, 256]` matrix (with its bias) is a 1 × 1 projection of the decoder's output, an image +//! `[r, 288, 288]`. The detector passes its 200 mask embeddings with the instance projection folded in, so these are the +//! per-query mask logits. ~0.9–1.4 s per prompt on the CPU through candle, most of it the 288² convolution. +//! +//! Images are pixel rows (`[pixels, channels]`), as in the necks (`sam3/neck.rs`): the convolutions are the necks' +//! implicit GEMM, the projection the backbone's matrix product (`[pixels, 256] · [r, 256]ᵀ`, then `to_chw`), the +//! prompt attention the DETR encoder's kernels (`sam3/detr.rs`). `wgsl/sam3_pixel.wgsl` adds the up-sampling, which +//! adds the channels-first neck level as uploaded, and GroupNorm + ReLU: two-pass statistics per chunk of 256 pixels, +//! merged per group (the parallel variance formula), then applied in place. +//! +//! Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, ~280 MB of work buffers. A prompt uploads +//! the memory, the prompt's tokens and padding bias, both neck levels (106 MB; they stay on the CPU with the image's +//! features, see `docs/gpu-pipeline.md`) and the rows, submits once and reads `r · 288²` numbers back. The dispatches +//! are recorded once per row count. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::detr::{self, Operand}; +use super::neck::{self, conv_weights, scoped}; +use super::{Dev, Graph, Precision, Recorded, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the decoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.mask_decoder"; +/// The memory's side (72 × 72 tokens), the width of everything, the prompt's tokens. +const GRID: usize = 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +/// The decoder's stages (each doubles the side): 144², 288². +const STAGES: usize = 2; +/// The output's side. +const SIDE: usize = GRID << STAGES; +/// GroupNorm's groups and eps (`candle_nn::group_norm(8, 256, 1e-5)`), and PyTorch's layer norm eps. +const GROUPS: usize = 8; +const EPS: f32 = 1e-5; +/// Pixels per workgroup of the GroupNorm statistics. +const CHUNK: usize = 256; + +struct Kernels { + upsample_add: wgpu::ComputePipeline, + group_stats: wgpu::ComputePipeline, + group_merge: wgpu::ComputePipeline, + group_norm_relu: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The decoder's own kernels, compiled on first use. +fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = include_str!("../wgsl/sam3_pixel.wgsl"); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 pixel", source, entry); + let k = Kernels { + upsample_add: pipe("upsample_add"), + group_stats: pipe("group_stats"), + group_merge: pipe("group_merge"), + group_norm_relu: pipe("group_norm_relu"), + }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 mask decoder kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// Floats of the GroupNorm statistics of chunks for an image of `pixels`, `groups` groups. +fn partials_len(pixels: usize, groups: usize) -> usize { + pixels.div_ceil(CHUNK) * groups * 2 +} + +impl Graph { + /// Nearest up-sampling of the rows `src` (`[from², channels]`) to `to × to`, plus the channels-first image `skip` + /// (`[channels, to, to]`), into the rows `dst` (`[to², channels]`). + fn upsample_add( + &mut self, + k: &'static Kernels, + [src, skip, dst]: [&wgpu::Buffer; 3], + channels: usize, + (from, to): (usize, usize), + ) -> Result<(), String> { + if from == 0 || to < from || channels == 0 { + return Err("an up-sampling the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(to * to).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let params = [u32_of(channels)?, u32_of(to)?, u32_of(from)?, 0, 0, 0, u32_of(count)?, row]; + self.push(&k.upsample_add, params, [src, skip, &self.dev.dummy, dst], g); + Ok(()) + } + + /// GroupNorm (`groups` groups of channels, eps) and ReLU in place on the rows `x` (`[pixels, channels]`, channels + /// ≤ 256), with the per-channel `gamma` and `beta`; `partials` (at least [`partials_len`] floats) and `stats` + /// (2 · groups) hold the statistics on the way. + #[allow(clippy::too_many_arguments)] + fn group_norm_relu( + &mut self, + k: &'static Kernels, + [x, gamma, beta]: [&wgpu::Buffer; 3], + [partials, stats]: [&wgpu::Buffer; 2], + (pixels, channels, groups): (usize, usize, usize), + eps: f32, + ) -> Result<(), String> { + if pixels == 0 || channels == 0 || channels > 256 || groups == 0 || !channels.is_multiple_of(groups) { + return Err("a GroupNorm the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let chunks = pixels.div_ceil(CHUNK); + let (g, row) = self.flat(chunks)?; + let params = [u32_of(channels)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, 0, 0, 0, row]; + self.push(&k.group_stats, params, [x, dummy, dummy, partials], g); + let params = [u32_of(chunks)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, eps.to_bits(), u32_of(channels / groups)?, 0, 0]; + self.push(&k.group_merge, params, [partials, dummy, dummy, stats], [u32_of(groups)?, 1, 1]); + let count = pixels.checked_mul(channels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + self.push(&k.group_norm_relu, [u32_of(channels)?, 0, 0, u32_of(groups)?, 0, 0, u32_of(count)?, row], [stats, gamma, beta, x], g); + Ok(()) + } +} + +/// The decoder's weights on the device: (weight, bias) pairs, the prompt attention's k | v concatenated, the +/// convolutions as rows `[cout, 3, 3, cin]`. +struct Weights { + ln: [wgpu::Buffer; 2], + q: [wgpu::Buffer; 2], + kv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + convs: Vec<[wgpu::Buffer; 2]>, + norms: Vec<[wgpu::Buffer; 2]>, +} + +/// Reads the decoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn read(&mut self, names: &[String], shape: &[usize]) -> Result, String> { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{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:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(all) + } + + /// A pair of `{name}.weight` (`[n, k]`, several concatenated along n) and `{name}.bias` (or a norm's scale and shift + /// with `k` 0), uploaded. + fn pair(&mut self, dev: &Dev, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + let shape: &[usize] = if k == 0 { &[n] } else { &[n, k] }; + let label = names.first().map_or("weight", String::as_str); + Ok([upload(dev, label, &self.read(&w, shape)?), upload(dev, label, &self.read(&b, &[n])?)]) + } + + fn load(&mut self, dev: &Dev) -> Result { + let a = "prompt_cross_attn"; + let proj = |ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + let mut convs = Vec::with_capacity(STAGES); + let mut norms = Vec::with_capacity(STAGES); + for i in 0..STAGES { + let name = format!("pixel_decoder.conv_layers.{i}"); + let w = self.read(&[format!("{name}.weight")], &[WIDTH, WIDTH, 3, 3])?; + let b = self.read(&[format!("{name}.bias")], &[WIDTH])?; + convs.push(conv_weights(dev, &name, &w, &b, (WIDTH, WIDTH, 3))); + norms.push(self.pair(dev, &[format!("pixel_decoder.norms.{i}")], WIDTH, 0)?); + } + Ok(Weights { + ln: self.pair(dev, &["prompt_cross_attn_norm".to_string()], WIDTH, 0)?, + q: self.pair(dev, &proj(&["q"]), WIDTH, WIDTH)?, + kv: self.pair(dev, &proj(&["k", "v"]), WIDTH, WIDTH)?, + o: self.pair(dev, &proj(&["o"]), WIDTH, WIDTH)?, + convs, + norms, + }) + } +} + +/// The buffers a prompt writes and reads, and its dispatches (recorded for one row count). +struct Work { + /// The memory in, then the memory after the prompt attention. + x: wgpu::Buffer, + text: wgpu::Buffer, + /// The prompt attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + /// The neck's levels as uploaded (`[256, 144, 144]`, `[256, 288, 288]`); the projection's channels-first result + /// ends in the second. + skip1: wgpu::Buffer, + skip0: wgpu::Buffer, + /// Two 288² images the steps alternate between (the prompt attention's smaller ones too). + a: wgpu::Buffer, + b: wgpu::Buffer, + rows: wgpu::Buffer, + row_bias: wgpu::Buffer, + partials: wgpu::Buffer, + stats: wgpu::Buffer, + staging: wgpu::Buffer, + recorded: Option<(usize, Recorded)>, +} + +impl Work { + fn new(dev: &Dev) -> Work { + let image = |label: &str| buffer(dev, label, SIDE * SIDE * WIDTH); + Work { + x: buffer(dev, "mask memory", GRID * GRID * WIDTH), + text: buffer(dev, "mask prompt", TEXT * WIDTH), + text_kv: buffer(dev, "mask prompt k|v", TEXT * 2 * WIDTH + TEXT), + skip1: buffer(dev, "mask level 1", WIDTH * (SIDE / 2) * (SIDE / 2)), + skip0: image("mask level 0"), + a: image("mask ping"), + b: image("mask pong"), + rows: buffer(dev, "mask rows", WIDTH * WIDTH), + row_bias: buffer(dev, "mask row bias", WIDTH), + partials: buffer(dev, "mask norm partials", partials_len(SIDE * SIDE, GROUPS)), + stats: buffer(dev, "mask norm stats", 2 * GROUPS), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mask read-back"), + size: (SIDE * SIDE * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + recorded: None, + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes() -> u64 { + let floats = GRID * GRID * WIDTH + + TEXT * (3 * WIDTH + 1) + + WIDTH * (SIDE / 2) * (SIDE / 2) + + 3 * SIDE * SIDE * WIDTH + + WIDTH * (WIDTH + 1) + + partials_len(SIDE * SIDE, GROUPS) + + 2 * GROUPS; + (floats * 4) as u64 + } +} + +/// The dispatches of a prompt with `r` rows: everything after the uploads, the result in `work.skip0`. +fn record(dev: &'static Dev, w: &Weights, work: &Work, r: usize) -> Result { + let (kd, kn, k) = (detr::kernels(dev)?, neck::kernels(dev)?, kernels(dev)?); + let mut g = Graph::new(dev); + let tokens = GRID * GRID; + // the memory attends to the prompt (padding masked): x += o(attention(q(ln(x)), k | v(text))) + g.layernorm_torch([&work.x, &w.ln[0], &w.ln[1], &work.a], tokens, WIDTH)?; + g.matmul([&work.a, &w.q[0], &w.q[1], &work.b], (tokens, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&work.text, &w.kv[0], &w.kv[1], &work.text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let q = Operand { buffer: &work.b, stride: WIDTH, offset: 0 }; + let (tk, tv) = + (Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(kd, [q, tk, tv], Some(TEXT * 2 * WIDTH), &work.a, (tokens, TEXT, WIDTH / HEAD_DIM))?; + g.matmul([&work.a, &w.o[0], &w.o[1], &work.x], (tokens, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // the pixel decoder: up-sample + the neck's level → 3 × 3 convolution → GroupNorm → ReLU, at 144² and at 288² + let mut cur = &work.x; + let mut side = GRID; + for (i, skip) in [&work.skip1, &work.skip0].into_iter().enumerate() { + let (Some(conv), Some(norm)) = (w.convs.get(i), w.norms.get(i)) else { return Err("a pixel decoder stage without weights".into()) }; + g.upsample_add(k, [cur, skip, &work.a], WIDTH, (side, 2 * side))?; + side *= 2; + g.conv3(kn, [&work.a, &conv[0], &conv[1], &work.b], side, (WIDTH, WIDTH))?; + g.group_norm_relu(k, [&work.b, &norm[0], &norm[1]], [&work.partials, &work.stats], (side * side, WIDTH, GROUPS), EPS)?; + cur = &work.b; + } + // each row a 1 × 1 projection of the decoder's output: [pixels, r], then channels-first into the spent level 0 + g.matmul([&work.b, &work.rows, &work.row_bias, &work.a], (side * side, r, WIDTH), 1, false, false, Precision::F32)?; + g.channels_first(&work.a, &work.skip0, r, side, side)?; + Ok(g.record()) +} + +/// The decoder with its weights on the device. +struct Built { + weights: Weights, + /// One prompt at a time (they share the work buffers). + work: Mutex, + weight_bytes: u64, +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + // every kernel compiles before anything is uploaded + detr::kernels(dev)?; + neck::kernels(dev)?; + kernels(dev)?; + scoped(dev, "the SAM 3 mask decoder", || { + let mut ld = Loader { weights, bytes: 0 }; + let w = ld.load(dev)?; + Ok(Built { weights: w, work: Mutex::new(Work::new(dev)), weight_bytes: ld.bytes }) + }) +} + +/// The mask decoder, built on first use from the checkpoint the backbone came from. +pub(super) struct MaskDecoder { + weights: WeightReader, + built: OnceLock>, +} + +impl MaskDecoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, Work::bytes())) + } + + /// `[r, 288, 288]` for the encoder memory `[5184, 256]`, the prompt's tokens `[32, 256]` (`valid`: its real ones), + /// the detector neck's levels `[256, 144, 144]` and `[256, 288, 288]` (channels-first) and the rows `[r, 256]` + /// with their bias `[r]` (1 ≤ r ≤ 256). + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &self, + dev: &'static Dev, + memory: &[f32], + text: &[f32], + valid: &[bool], + [level1, level0]: [&[f32]; 2], + rows: &[f32], + row_bias: &[f32], + ) -> Result, String> { + let r = row_bias.len(); + let (l1, l0) = (WIDTH * (SIDE / 2) * (SIDE / 2), WIDTH * SIDE * SIDE); + if memory.len() != GRID * GRID * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT || level1.len() != l1 || level0.len() != l0 { + return Err(format!( + "{} memory, {} prompt values, {} prompt tokens and levels of {} and {} values, expected {GRID}² × {WIDTH}, {TEXT} × {WIDTH}, {TEXT}, {l1} and {l0}", + memory.len(), + text.len(), + valid.len(), + level1.len(), + level0.len() + )); + } + if r == 0 || r > WIDTH || rows.len() != r * WIDTH { + return Err(format!("{} row values and {r} biases, expected r × {WIDTH} and r (1 ≤ r ≤ {WIDTH})", rows.len())); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let mut work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + if work.recorded.as_ref().is_none_or(|(n, _)| *n != r) { + let recorded = scoped(dev, "the SAM 3 mask decoder", || record(dev, &b.weights, &work, r))?; + work.recorded = Some((r, recorded)); + } + let q = &dev.queue; + q.write_buffer(&work.x, 0, bytemuck::cast_slice(memory)); + q.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + q.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + q.write_buffer(&work.skip1, 0, bytemuck::cast_slice(level1)); + q.write_buffer(&work.skip0, 0, bytemuck::cast_slice(level0)); + q.write_buffer(&work.rows, 0, bytemuck::cast_slice(rows)); + q.write_buffer(&work.row_bias, 0, bytemuck::cast_slice(row_bias)); + let Some((_, recorded)) = &work.recorded else { return Err("the mask decoder was not recorded".into()) }; + let out = recorded.run("the SAM 3 mask decoder", dev, &work.skip0, &work.staging, r * SIDE * SIDE)?; + if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("the GPU mask decoder produced non-finite values".into()); + } + Ok(out) + } +} diff --git a/crates/gpu/src/sam3/pixel/tests.rs b/crates/gpu/src/sam3/pixel/tests.rs new file mode 100644 index 0000000000..ece1185c0e --- /dev/null +++ b/crates/gpu/src/sam3/pixel/tests.rs @@ -0,0 +1,165 @@ +//! The mask decoder's kernels against plain loops in f64: the up-sampling with the channels-first level added (odd +//! sides, cut-off workgroups), GroupNorm + ReLU (chunks cut off, a large mean, group sizes), and one whole pixel +//! decoder stage (up-sampling → 3 × 3 convolution at every border → GroupNorm → ReLU) on small images. The real +//! decoder against candle: `tests/it/sam3_mask_decoder.rs`. + +use super::super::neck::tests::{conv_ref, f32s, f64s}; +use super::super::tests::{gpu, read, values, worst}; +use super::*; + +fn pixel_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// Nearest up-sampling of the rows `x` (`[from², c]`) to `to²`, plus the channels-first `skip` (`[c, to, to]`). +fn upsample_add_ref(x: &[f64], skip: &[f32], c: usize, (from, to): (usize, usize)) -> Vec { + let mut y = vec![0f64; to * to * c]; + for r in 0..to { + for col in 0..to { + // candle's upsample_nearest2d: floor(i · from / to) + let (sr, sc) = ((r as f64 * from as f64 / to as f64) as usize, (col as f64 * from as f64 / to as f64) as usize); + for ch in 0..c { + y[(r * to + col) * c + ch] = x[(sr * from + sc) * c + ch] + skip[ch * to * to + r * to + col] as f64; + } + } + } + y +} + +/// GroupNorm (centred two-pass variance, as candle's) and ReLU on the rows `x` (`[pixels, c]`). +fn group_norm_relu_ref(x: &[f64], c: usize, groups: usize, gamma: &[f32], beta: &[f32], eps: f64) -> Vec { + let pixels = x.len() / c; + let per = c / groups; + let mut y = x.to_vec(); + for g in 0..groups { + let at = |p: usize, i: usize| x[p * c + g * per + i]; + let n = (pixels * per) as f64; + let mean = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| at(p, i)).sum::() / n; + let var = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| (at(p, i) - mean).powi(2)).sum::() / n; + for p in 0..pixels { + for i in 0..per { + let ch = g * per + i; + let v = (x[p * c + ch] - mean) / (var + eps).sqrt() * gamma[ch] as f64 + beta[ch] as f64; + y[p * c + ch] = v.max(0.0); + } + } + } + y +} + +#[test] +fn up_sampling_adds_the_channels_first_level() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // the decoder's doublings, an odd one, and channels that leave the last workgroup part empty + for (case, (from, to, c)) in [(3usize, 6usize, 4usize), (5, 10, 12), (4, 7, 3), (1, 2, 256)].into_iter().enumerate() { + let x = values(from * from * c, 100 + case as u64, 1.0); + let skip = values(c * to * to, 110 + case as u64, 1.0); + let (bx, bs, by) = (upload(d, "x", &x), upload(d, "skip", &skip), buffer(d, "y", to * to * c)); + let mut g = Graph::new(d); + g.upsample_add(k, [&bx, &bs, &by], c, (from, to)).unwrap(); + let got = read(d, g, &by, to * to * c); + let err = worst(&got, &f32s(&upsample_add_ref(&f64s(&x), &skip, c, (from, to)))); + assert!(err < 1e-6, "case {case}: off by {err}"); + } +} + +#[test] +fn group_norm_and_relu_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // one chunk cut short; several with the last cut short; the decoder's 256 channels in 8 groups over chunks of + // 256 pixels, around a mean far from 0 (where E[x²] − E[x]² in f32 would lose the variance) + for (case, (pixels, c, groups, offset)) in + [(37usize, 16usize, 4usize, 0f32), (700, 24, 3, 0.0), (1100, 256, 8, 0.0), (600, 256, 8, 50.0), (5, 8, 1, 0.0)].into_iter().enumerate() + { + let x: Vec = values(pixels * c, 120 + case as u64, 2.0).iter().map(|v| v + offset).collect(); + let gamma = values(c, 130 + case as u64, 1.5); + let beta = values(c, 140 + case as u64, 0.5); + // normed in place, then read back: a buffer that can be copied from + let bx = buffer(d, "x", pixels * c); + d.queue.write_buffer(&bx, 0, bytemuck::cast_slice(&x)); + let (bg, bb) = (upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(pixels, groups)), buffer(d, "stats", 2 * groups)); + let mut g = Graph::new(d); + g.group_norm_relu(k, [&bx, &bg, &bb], [&partials, &stats], (pixels, c, groups), EPS).unwrap(); + let got = read(d, g, &bx, pixels * c); + let want = f32s(&group_norm_relu_ref(&f64s(&x), c, groups, &gamma, &beta, f64::from(EPS))); + let err = worst(&got, &want); + assert!(err < 2e-5, "case {case} ({pixels} pixels, {c} channels, {groups} groups): off by {err}"); + assert!(got.iter().all(|v| *v >= 0.0), "case {case}: ReLU"); + } +} + +#[test] +fn a_small_pixel_decoder_stage_gives_the_definition() { + let Some(d) = gpu() else { return }; + let (k, kn) = (pixel_kernels(d), neck::kernels(d).unwrap()); + // two stages as in the decoder (3² → 6² → 12²), 16 channels in 4 groups + let (c, groups) = (16usize, 4usize); + let x = values(3 * 3 * c, 150, 1.0); + let mut want = f64s(&x); + let mut cur = upload(d, "x", &x); + let mut g = Graph::new(d); + let mut side = 3; + for stage in 0..2u64 { + let skip = values(c * 4 * side * side, 160 + stage, 1.0); + let (w, b) = (values(c * c * 9, 170 + stage, 0.3), values(c, 180 + stage, 0.3)); + let (gamma, beta) = (values(c, 190 + stage, 1.0), values(c, 200 + stage, 0.3)); + want = upsample_add_ref(&want, &skip, c, (side, 2 * side)); + side *= 2; + want = conv_ref(&want, side, (c, c, 3), &w, &b); + want = group_norm_relu_ref(&want, c, groups, &gamma, &beta, f64::from(EPS)); + + let up = buffer(d, "up", side * side * c); + let out = buffer(d, "out", side * side * c); + let [bw, bb] = conv_weights(d, "conv", &w, &b, (c, c, 3)); + let (bs, bg, bt) = (upload(d, "skip", &skip), upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(side * side, groups)), buffer(d, "stats", 2 * groups)); + g.upsample_add(k, [&cur, &bs, &up], c, (side / 2, side)).unwrap(); + g.conv3(kn, [&up, &bw, &bb, &out], side, (c, c)).unwrap(); + g.group_norm_relu(k, [&out, &bg, &bt], [&partials, &stats], (side * side, c, groups), EPS).unwrap(); + cur = out; + } + let got = read(d, g, &cur, side * side * c); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "off by {err}"); +} + +#[test] +fn the_mask_decoder_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (0, 2)).is_err(), "an empty image"); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (4, 2)).is_err(), "down-sampling"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 12, 8), EPS).is_err(), "channels not a multiple of the groups"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 512, 8), EPS).is_err(), "more channels than threads"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (0, 8, 8), EPS).is_err(), "no pixels"); +} + +#[test] +fn the_decoder_refuses_inputs_of_the_wrong_size() { + let Some(d) = gpu() else { return }; + // checked before the checkpoint is read: an empty reader is never touched + let dir = std::env::temp_dir().join(format!("lc-sam3-pixel-{}", 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("model.safetensors"), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + let m = MaskDecoder::new(WeightReader::open(&dir).unwrap()); + let (mem, text, valid) = (vec![0f32; GRID * GRID * WIDTH], vec![0f32; TEXT * WIDTH], vec![true; TEXT]); + let (l1, l0) = (vec![0f32; WIDTH * 144 * 144], vec![0f32; WIDTH * SIDE * SIDE]); + let rows = vec![0f32; 3 * WIDTH]; + assert!(m.run(d, &mem[1..], &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l0, &l1], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 2]).is_err_and(|e| e.contains("row values"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &[], &[]).is_err_and(|e| e.contains("row values"))); + // the right sizes reach the checkpoint, which has no decoder + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("mask_decoder"))); + assert!(m.bytes().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/gpu/src/wgsl/sam3_conv.wgsl b/crates/gpu/src/wgsl/sam3_conv.wgsl new file mode 100644 index 0000000000..67cc55ef73 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_conv.wgsl @@ -0,0 +1,29 @@ +// The A-tile loader of the necks' 3 x 3 convolution (`sam3/neck.rs`, padding 1, stride 1): spliced into +// `sam3_matmul.wgsl` in place of its dense `load_a`, so the convolution is that kernel's product over an im2col +// matrix that is never stored (an implicit GEMM; at 288 x 288 x 256 the stored one would be 764 MB). +// +// X [side², cin] the image, pixels row-major, channels last (cin a multiple of 4) +// A [side², 9 · cin] row m: output pixel (m / side, m % side); column k = tap · cin + c: input channel c of the +// pixel at tap (ky, kx) = (tap / 3, tap % 3), i.e. (row + ky − 1, col + kx − 1), zero outside the image +// W [cout, 9 · cin] the weights in the same (ky, kx, c) order +// +// A vector of four k is four channels of one pixel, so it is one aligned load from X. + +// Vector e of the A tile at k0 (row e / KV); zero outside the image (the padding) and outside A. +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 vec4(0.0); + } + let side = p.side; + let c4 = k4 / 9u; + let tap = kq / c4; + let row = i32(m / side) + i32(tap / 3u) - 1; + let col = i32(m % side) + i32(tap % 3u) - 1; + if (row < 0 || col < 0 || row >= i32(side) || col >= i32(side)) { + return vec4(0.0); + } + return x[(u32(row) * side + u32(col)) * c4 + kq % c4]; +} diff --git a/crates/gpu/src/wgsl/sam3_detr.wgsl b/crates/gpu/src/wgsl/sam3_detr.wgsl new file mode 100644 index 0000000000..2ed63db145 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_detr.wgsl @@ -0,0 +1,105 @@ +// The DETR encoder of SAM 3's text detector (`sam3/detr.rs`): attention with heads of 32 (8 of them over 256 numbers), +// for the image tokens over themselves (self-attention) and over the prompt's tokens (cross-attention, with a +// key-padding bias), and the sum of two arrays (the position encoding added to the normed tokens). +// +// q [queries, q_stride]: head h's q at h · 32 (binding 1) +// k [keys, k_stride] from k_off (binding 2), v [keys, v_stride] from v_off (binding 3); 2 and 3 may be one buffer +// bias `keys` floats in binding 2 from `bias` (NONE: no bias), added to every score of its key: 0 for a real +// token, f32::MIN for padding, as candle's `padding_bias` +// out [queries, heads · 32] +// +// Strides and offsets count floats (multiples of 4); keys is a multiple of KB. Flash style like +// `sam3_attention.wgsl`: one query per thread with its q and partial output in registers, keys and values KB at a +// time through workgroup memory, online softmax. The running maximum starts at f32::MIN rather than below it: a padded +// key's score is then exactly f32::MIN (as in candle, where s + f32::MIN rounds to f32::MIN) and weighs nothing next +// to a real one, and a query whose keys are all padding averages them, as candle's softmax over equal scores does. +// The host writes out the per-thread work with one variable per vector and score (the DECL, SCORES, RESCALE, +// ACCUMULATE and STORE marks). + +struct P { + queries: u32, + keys: u32, + q_stride: u32, + k_stride: u32, + v_stride: u32, + k_off: u32, + v_off: u32, + bias: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qs: array>; +@group(0) @binding(2) var ks: array>; +@group(0) @binding(3) var vs: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step, 1 / sqrt(head_dim) +const D4: u32 = 8u; +const KB: u32 = {{KB}}u; +const SCALE: f32 = 0.17677669529663687; +const NONE: u32 = 0xffffffffu; +const LOWEST: f32 = -3.4028234663852886e38; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; +var Bs: array; + +@compute @workgroup_size(64) +fn attention(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) groups: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let tq = wg.x * 64u + lid; + // threads past the last query compute on query 0 (the barriers below stay uniform) and store nothing + let live = tq < p.queries; + let qa = select(0u, tq, live) * (p.q_stride / 4u) + head * D4; + let k4 = p.k_stride / 4u; + let v4 = p.v_stride / 4u; + let ka = p.k_off / 4u + head * D4; + let va = p.v_off / 4u + head * D4; + +{{DECL}} + var m = LOWEST; + var l = 0.0; + + for (var k0 = 0u; k0 < p.keys; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = k0 + e / D4; + Ks[e] = ks[t * k4 + ka + e % D4]; + Vs[e] = vs[t * v4 + va + e % D4]; + } + if (lid < KB) { + var b = 0.0; + if (p.bias != NONE) { + let i = p.bias + k0 + lid; + b = ks[i / 4u][i % 4u]; + } + Bs[lid] = b; + } + 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(); + } + + if (live) { + let r = 1.0 / l; + let oa = tq * groups.y * D4 + head * D4; +{{STORE}} + } +} + +// out = qs + ks, `queries` vectors (keys: workgroups per row of the dispatch). +@compute @workgroup_size(256) +fn add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let i = (wg.y * p.keys + wg.x) * 256u + lid; + if (i >= p.queries) { + return; + } + out[i] = qs[i] + ks[i]; +} diff --git a/crates/gpu/src/wgsl/sam3_neck.wgsl b/crates/gpu/src/wgsl/sam3_neck.wgsl new file mode 100644 index 0000000000..db2853a1b4 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_neck.wgsl @@ -0,0 +1,60 @@ +// The reorderings of the SAM 3 necks (`sam3/neck.rs`) around their products: the backbone's channels-first output +// to pixel rows, and the rows of the transposed convolutions back to row-major. (Back to channels-first: `to_chw` +// of `sam3_ops.wgsl`, with one window over the whole image.) +// +// Same bindings and parameter block as `sam3_ops.wgsl`; 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; +} + +// Channels-first to pixel rows (a: channels, b: pixels): dst[pixel, ch] = src[ch, pixel]. +@compute @workgroup_size(256) +fn to_rows(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + dst[g] = src[g % p.a * p.b + g / p.a]; +} + +// Pixel rows after `c` 2 x 2 stride-2 transposed convolutions to row-major (a: channels, b: side). Such a convolution +// is one product per input pixel whose row holds its four output pixels (ky, kx) one after the other, so after c of +// them the pixels of the side x side image come ordered by (row >> c, col >> c), then the (ky, kx) of the first, …, +// of the last: dst[row · side + col, ch] = src[that position, ch]. +@compute @workgroup_size(256) +fn unshuffle(@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.b; + let ups = p.c; + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / side; + let col = pixel % side; + var at = (row >> ups) * (side >> ups) + (col >> ups); + for (var s = ups; s > 0u; s--) { + at = at * 4u + ((row >> (s - 1u)) & 1u) * 2u + ((col >> (s - 1u)) & 1u); + } + dst[g] = src[at * p.a + ch]; +} diff --git a/crates/gpu/src/wgsl/sam3_pixel.wgsl b/crates/gpu/src/wgsl/sam3_pixel.wgsl new file mode 100644 index 0000000000..bc6b972cfd --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_pixel.wgsl @@ -0,0 +1,161 @@ +// The small steps of the text detector's pixel decoder (`sam3/pixel.rs`) around its 3 x 3 convolutions: nearest +// up-sampling plus the neck level it is added to, and GroupNorm + ReLU (statistics per chunk of pixels, merged per +// group, then applied in place). +// +// Images are pixel rows (`[pixels, channels]`, row-major); the neck levels come channels-first, as uploaded. Same +// bindings and parameter block as `sam3_ops.wgsl`; 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; +} + +// Nearest up-sampling of the rows `src` (a: channels, c: side) to side b, plus the channels-first image `aux` +// (`[a, b, b]`): dst[row · b + col, ch] = src[(row · c / b) · c + col · c / b, ch] + aux[ch, row, col]. (candle's +// `upsample_nearest2d` takes floor(i · c / b), the same for the decoder's exact doublings.) +@compute @workgroup_size(256) +fn upsample_add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / p.b; + let col = pixel % p.b; + let at = row * p.c / p.b * p.c + col * p.c / p.b; + dst[g] = src[at * p.a + ch] + aux[ch * p.b * p.b + pixel]; +} + +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; +} + +// Thread `lid` holds channel lid's `v`: leaves the sum over each group's channels in red[group] (a: channels, +// d: groups). +fn group_sums(lid: u32, v: f32) { + red[lid] = v; + workgroupBarrier(); + let per = p.a / p.d; + var s = 0.0; + if (lid < p.d) { + for (var i = 0u; i < per; i++) { + s += red[lid * per + i]; + } + } + workgroupBarrier(); + if (lid < p.d) { + red[lid] = s; + } + workgroupBarrier(); +} + +// GroupNorm statistics of one chunk of pixels (a: channels ≤ 256, b: pixels, c: pixels per chunk, d: groups), one +// workgroup per chunk, thread = channel: each group's mean over the chunk and the sum of squared differences from +// it, at dst[(chunk · d + group) · 2 + 0 | 1]. Two passes over the chunk (the second from the cache), so a large mean +// costs no precision. +@compute @workgroup_size(256) +fn group_stats(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let chunk = wg.y * p.row + wg.x; + let first = chunk * p.c; + if (first >= p.b) { + return; + } + let last = min(first + p.c, p.b); + let live = lid < p.a; + let ch = min(lid, p.a - 1u); + let per = p.a / p.d; + let n = f32((last - first) * per); + var s = 0.0; + if (live) { + for (var px = first; px < last; px++) { + s += src[px * p.a + ch]; + } + } + group_sums(lid, s); + let mean = red[ch / per] / n; + let own = red[min(lid, p.d - 1u)] / n; + workgroupBarrier(); + var q = 0.0; + if (live) { + for (var px = first; px < last; px++) { + let d = src[px * p.a + ch] - mean; + q += d * d; + } + } + group_sums(lid, q); + if (lid < p.d) { + let o = (chunk * p.d + lid) * 2u; + dst[o] = own; + dst[o + 1u] = red[lid]; + } +} + +// The chunks' statistics merged, one workgroup per group (a: chunks, b: pixels, c: pixels per chunk, d: groups, +// e: eps bits, f: channels per group): dst[group · 2 + 0 | 1] = the group's mean and 1 / sqrt(variance + eps), the +// variance biased (over all of the group's numbers), as candle's GroupNorm. +@compute @workgroup_size(256) +fn group_merge(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = wg.x; + let total = f32(p.b * p.f); + var s = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + s += n * src[(i * p.d + g) * 2u]; + } + let mean = reduce(lid, s) / total; + var q = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + let o = (i * p.d + g) * 2u; + let d = src[o] - mean; + q += src[o + 1u] + n * d * d; + } + let variance = reduce(lid, q) / total; + if (lid == 0u) { + dst[g * 2u] = mean; + dst[g * 2u + 1u] = inverseSqrt(variance + bitcast(p.e)); + } +} + +// GroupNorm and ReLU in place on the rows `dst` (a: channels, d: groups) with the merged statistics `src`, the scale +// `aux` and the shift `aux2` (`[a]` each): dst = max((dst − mean) · rstd · aux + aux2, 0). +@compute @workgroup_size(256) +fn group_norm_relu(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let group = ch / (p.a / p.d); + dst[g] = max((dst[g] - src[group * 2u]) * src[group * 2u + 1u] * aux[ch] + aux2[ch], 0.0); +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 3755824f27..893b4b279d 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -10,4 +10,10 @@ mod fallback; mod gpu_probe; #[cfg(feature = "sam")] mod sam3_backbone; +#[cfg(feature = "sam")] +mod sam3_detr; +#[cfg(feature = "sam")] +mod sam3_mask_decoder; +#[cfg(feature = "sam")] +mod sam3_necks; mod thumbs_bench; diff --git a/crates/gpu/tests/it/sam3_detr.rs b/crates/gpu/tests/it/sam3_detr.rs new file mode 100644 index 0000000000..69e2355626 --- /dev/null +++ b/crates/gpu/tests/it/sam3_detr.rs @@ -0,0 +1,182 @@ +//! The text detector's DETR encoder on the GPU against the candle encoder (the reference), on one photo: the encoder +//! memory, and what the difference does to the detector's outputs (per-query logits, presence, boxes and the merged +//! Describe mask) for a few prompts. Both models get the same backbone output (one GPU backbone, shared), so only the +//! encoder differs. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_detr:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, 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 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), and how many instances that is. +fn merged(out: &DetectorOutput) -> (Vec, usize) { + let masks = values(&out.masks); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + (merged, keep.len()) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + 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(); + } + 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() +} + +/// One GPU backbone for both models; the DETR encoder only for one of them (`asked` counts the calls). +struct Shared { + gpu: Arc, + detr: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_detr_encoder(&self) -> bool { + true + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.detr { self.gpu.detr_encoder(image, pos, text, valid) } else { Err("left to candle for the comparison".into()) } + } +} + +#[test] +fn the_gpu_detr_encoder_matches_the_candle_encoder() { + 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 gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |detr: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, detr, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + assert_eq!(values(enc_cpu.backbone()), values(enc_acc.backbone()), "the same backbone output for both"); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle encoder {cpu_time:?}, with the GPU encoder {gpu_time:?}{first}"); + assert_eq!(acc.detr_fallback(), None, "the GPU encoder ran"); + assert!(cpu.detr_fallback().is_some_and(|w| w.contains("left to candle"))); + + let (_, rel, mean) = errors("memory", &values(&got.memory), &values(&want.memory)); + assert!(rel < 1e-3 && mean < 1e-4, "the GPU encoder memory is off"); + let (logits, _, _) = errors("query logits", &got.logits, &want.logits); + let presence = (got.presence - want.presence).abs(); + let boxes = got.boxes.iter().flatten().zip(want.boxes.iter().flatten()).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + let ((mask_g, kept_g), (mask_c, kept_c)) = (merged(&got), merged(&want)); + let i = iou(&mask_g, &mask_c); + eprintln!( + " presence {:.4} vs {:.4} (logit diff {presence:.2e}), boxes max diff {boxes:.2e}, instances {kept_g} vs {kept_c}, mask IoU {i:.5}", + sigmoid(got.presence), + sigmoid(want.presence) + ); + // every query's mask, not only the merged ones: the largest |Δ| of the logits and of the masks (sigmoid, 0..1) + let (dl, dm) = values(&got.masks) + .iter() + .zip(&values(&want.masks)) + .fold((0f32, 0f32), |(l, m), (a, b)| (l.max((a - b).abs()), m.max((sigmoid(*a) - sigmoid(*b)).abs()))); + eprintln!(" masks of all {} queries: max |Δ| logits {dl:.2e}, mask {dm:.2e}", got.logits.len()); + assert!(logits < 0.05 && presence < 0.05 && boxes < 1e-2, "the detector outputs moved"); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99, "describe mask IoU {i}"); + } + // an accelerator that failed on the encoder once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the encoder alone (with the uploads and the read-back) + let (image, pos, text) = (vec![0.1f32; 5184 * 256], vec![0.2f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.detr_encoder(&image, &pos, &text, &valid).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.detr_bytes().unwrap(); + eprintln!("GPU DETR encoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/crates/gpu/tests/it/sam3_mask_decoder.rs b/crates/gpu/tests/it/sam3_mask_decoder.rs new file mode 100644 index 0000000000..09520ebea9 --- /dev/null +++ b/crates/gpu/tests/it/sam3_mask_decoder.rs @@ -0,0 +1,287 @@ +//! The text detector's mask decoder on the GPU against the candle decoder (the reference), on one photo: the per-query +//! mask logits of all 200 queries, and the merged Describe mask, for a few prompts. Both models get the same backbone +//! output, necks and DETR encoder memory (one GPU accelerator, shared), so only the mask decoder differs. For the first +//! prompt, the instance features also against the decoder transcribed with candle's tensor ops in f64 (and in f32, to +//! show how far candle's own f32 decoder is from it). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_mask_decoder:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, NeckKind, 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 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), the instances, and the best-scoring query. +fn merged(out: &DetectorOutput, masks: &[f32]) -> (Vec, Vec, usize) { + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + let best = (0..out.logits.len()).max_by(|a, b| out.logits[*a].total_cmp(&out.logits[*b])).unwrap(); + (merged, keep, best) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + 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(); + } + 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() +} + +/// The mask decoder transcribed with candle's tensor ops in `dtype` (f64: the arbiter between the two f32 decoders): +/// the instance features `[256, 288 · 288]` for the encoder memory `[5184, 256]`, the prompt `[32, 256]` (`valid`: its +/// real tokens) and the neck levels `[256, 144, 144]`, `[256, 288, 288]`. +fn decoder_ref(w: &WeightReader, memory: &Tensor, (text, valid): (&Tensor, &[bool]), [l1, l0]: [&Tensor; 2], dtype: candle_core::DType) -> Tensor { + let get = |name: &str| { + let (shape, data) = w.read(&format!("detector_model.mask_decoder.{name}")).unwrap(); + Tensor::from_vec(data, shape, &Device::Cpu).unwrap().to_dtype(dtype).unwrap() + }; + let lin = |x: &Tensor, name: &str| { + x.matmul(&get(&format!("{name}.weight")).t().unwrap()).unwrap().broadcast_add(&get(&format!("{name}.bias"))).unwrap() + }; + let (memory, text) = (memory.to_dtype(dtype).unwrap(), text.to_dtype(dtype).unwrap()); + // prompt attention: LN (eps 1e-5) → 8 heads of 32 over the prompt (padding masked) → output projection, added + let mean = memory.mean_keepdim(1).unwrap(); + let centred = memory.broadcast_sub(&mean).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let h = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap(); + let h = h.broadcast_mul(&get("prompt_cross_attn_norm.weight")).unwrap().broadcast_add(&get("prompt_cross_attn_norm.bias")).unwrap(); + let heads = |x: Tensor| x.reshape((x.dim(0).unwrap(), 8, 32)).unwrap().transpose(0, 1).unwrap().contiguous().unwrap(); + let q = heads(lin(&h, "prompt_cross_attn.q_proj")); + let k = heads(lin(&text, "prompt_cross_attn.k_proj")); + let v = heads(lin(&text, "prompt_cross_attn.v_proj")); + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let bias = Tensor::from_vec(bias, (1, 1, 32), &Device::Cpu).unwrap().to_dtype(dtype).unwrap(); + let s = (q.matmul(&k.t().unwrap()).unwrap() * (32f64).powf(-0.5)).unwrap().broadcast_add(&bias).unwrap(); + let e = s.broadcast_sub(&s.max_keepdim(2).unwrap()).unwrap().exp().unwrap(); + let p = e.broadcast_div(&e.sum_keepdim(2).unwrap()).unwrap(); + let o = p.matmul(&v).unwrap().transpose(0, 1).unwrap().reshape((5184, 256)).unwrap(); + let mem = (memory + lin(&o, "prompt_cross_attn.o_proj")).unwrap(); + // the pixel decoder + let mut prev = mem.t().unwrap().reshape((1, 256, 72, 72)).unwrap(); + for (i, skip) in [l1, l0].into_iter().enumerate() { + let side = skip.dim(1).unwrap(); + prev = (prev.upsample_nearest2d(side, side).unwrap() + skip.to_dtype(dtype).unwrap().unsqueeze(0).unwrap()).unwrap(); + let c = format!("pixel_decoder.conv_layers.{i}"); + prev = prev + .conv2d(&get(&format!("{c}.weight")), 1, 1, 1, 1) + .unwrap() + .broadcast_add(&get(&format!("{c}.bias")).reshape((1, 256, 1, 1)).unwrap()) + .unwrap(); + let g = prev.reshape((8, 32 * side * side)).unwrap(); + let centred = g.broadcast_sub(&g.mean_keepdim(1).unwrap()).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let normed = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap().reshape((1, 256, side, side)).unwrap(); + let n = format!("pixel_decoder.norms.{i}"); + let (gamma, beta) = + (get(&format!("{n}.weight")).reshape((1, 256, 1, 1)).unwrap(), get(&format!("{n}.bias")).reshape((1, 256, 1, 1)).unwrap()); + prev = normed.broadcast_mul(&gamma).unwrap().broadcast_add(&beta).unwrap().relu().unwrap(); + } + let inst = prev.conv2d(&get("instance_projection.weight"), 0, 1, 1, 1).unwrap(); + inst.broadcast_add(&get("instance_projection.bias").reshape((1, 256, 1, 1)).unwrap()).unwrap().reshape((256, 288 * 288)).unwrap() +} + +/// One GPU accelerator for both models; the mask decoder only for one of them, the other gets a result of the wrong +/// size (and then runs the candle decoder; `asked` counts the calls). +struct Shared { + gpu: Arc, + masks: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.masks { self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) } else { Ok(vec![0.0; 10]) } + } +} + +#[test] +fn the_gpu_mask_decoder_matches_the_candle_decoder() { + 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 gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |masks: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, masks, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle mask decoder {cpu_time:?}, with the GPU one {gpu_time:?}{first}"); + assert_eq!(acc.mask_fallback(), None, "the GPU mask decoder ran"); + assert!(cpu.mask_fallback().is_some_and(|w| w.contains("returned 10 values"))); + assert_eq!(acc.heads_device(), "CPU; the necks, the DETR encoder and the mask decoder on the GPU"); + assert_eq!(cpu.heads_device(), "CPU; the necks and the DETR encoder on the GPU"); + + if n == 0 { + // the instance features (the instance projection as the rows) against the f64 transcription, and how far + // the same transcription in f32 is from it + let reader = WeightReader::open(&dir).unwrap(); + let (_, valid) = lightcraft_segment::tokenizer::Tokenizer::load(&dir).unwrap().encode(prompt); + let levels = acc.neck_levels(NeckKind::Detector, &enc_acc).unwrap(); + let (l1, l0) = (levels[1].squeeze(0).unwrap(), levels[0].squeeze(0).unwrap()); + let (memory, text) = (got.memory.squeeze(0).unwrap(), got.text.squeeze(0).unwrap()); + let (_, rows) = reader.read("detector_model.mask_decoder.instance_projection.weight").unwrap(); + let (_, bias) = reader.read("detector_model.mask_decoder.instance_projection.bias").unwrap(); + let t = Instant::now(); + let ours = gpu.mask_decoder(&values(&memory), &values(&text), &valid, [&values(&l1), &values(&l0)], &rows, &bias).unwrap(); + eprintln!(" GPU instance features {:?}", t.elapsed()); + let t = Instant::now(); + let f64_ref: Vec = values( + &decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F64).to_dtype(candle_core::DType::F32).unwrap(), + ); + let f32_ref = values(&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F32)); + eprintln!(" references {:?}", t.elapsed()); + let (_, rel, mean) = errors("instance features, GPU vs f64", &ours, &f64_ref); + errors("instance features, candle f32 vs f64", &f32_ref, &f64_ref); + assert!(rel < 1e-4 && mean < 1e-5, "the GPU instance features are off"); + } + + // the same memory and decoder for both: only the masks may differ, by candle's own error (its f32 decoder is + // ~400 × further from the f64 one than the GPU's, above) + let (_, logits, _) = errors("query logits", &got.logits, &want.logits); + assert!(logits < 1e-4, "the query logits moved"); + let (mg, mc) = (values(&got.masks), values(&want.masks)); + let (_, rel, mean) = errors("mask logits (200 queries), GPU vs candle", &mg, &mc); + assert!(rel < 1e-2 && mean < 0.1, "the GPU mask logits are off"); + let ((mask_g, kept_g, best_g), (mask_c, kept_c, best_c)) = (merged(&got, &mg), merged(&want, &mc)); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let best = iou(&mg[best_g * side..(best_g + 1) * side], &mc[best_c * side..(best_c + 1) * side]); + let i = iou(&mask_g, &mask_c); + eprintln!(" instances {} vs {}, Describe mask IoU {i:.5}, best query's mask IoU {best:.5}", kept_g.len(), kept_c.len()); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99 && best > 0.99, "describe mask IoU {i}, best query {best}"); + // the semantic mask (one more row of the GPU's mask product) + let (_, rel, mean) = errors("semantic mask logits, GPU vs candle", &got.semantic, &want.semantic); + let semantic = iou(&got.semantic, &want.semantic); + eprintln!(" semantic mask IoU {semantic:.5}"); + assert!(rel < 1e-2 && mean < 0.1 && semantic > 0.99, "the GPU semantic mask is off"); + } + // an accelerator whose decoder failed once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the decoder alone (with the uploads and the read-back) + let (memory, text) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.mask_decoder_bytes().unwrap(); + eprintln!("GPU mask decoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/crates/gpu/tests/it/sam3_necks.rs b/crates/gpu/tests/it/sam3_necks.rs new file mode 100644 index 0000000000..8529162de7 --- /dev/null +++ b/crates/gpu/tests/it/sam3_necks.rs @@ -0,0 +1,165 @@ +//! SAM 3's two necks on the GPU against the candle necks on the CPU (the reference), on one photo: every level, and +//! what the difference does to the masks downstream (click masks and a Describe mask). Both models get the same +//! GPU backbone output, so only the necks differ. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_necks:: -- --nocapture`. `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"). Skipped +//! without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, Click, INPUT, NeckKind, Sam3}; + +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()))) +} + +/// One GPU backbone for both models: with its necks (counting the levels it hands out), or without (candle's run). +struct Shared { + gpu: Arc, + necks: bool, + runs: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + fn device(&self) -> String { + self.gpu.device() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if !self.necks { + return Err("necks off".into()); + } + let levels = self.gpu.neck(which, backbone, n)?; + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(levels) + } +} + +#[test] +fn the_gpu_necks_match_the_cpu_necks() { + 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 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(); + let pixels = Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap(); + + let reader = lightcraft_segment::WeightReader::open(&dir).unwrap(); + let gpu = Arc::new(sam3::load(&reader, Precision::F32).unwrap()); + let runs = Arc::new(AtomicUsize::new(0)); + let accel = |necks: bool| { + let shared = Shared { gpu: gpu.clone(), necks, runs: runs.clone() }; + move |_: &lightcraft_segment::WeightReader| -> Result, String> { Ok(Box::new(shared)) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(false)).unwrap(); + let mut on_gpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(true)).unwrap(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + let mut got = on_gpu.encode_pixels(&pixels).unwrap(); + assert_eq!(values(want.backbone()), values(got.backbone()), "the same backbone output for both"); + + for which in [NeckKind::Tracker, NeckKind::Detector] { + let t = Instant::now(); + let reference = cpu.neck_levels(which, &want).unwrap(); + eprintln!("{which:?} neck, CPU: {:?}", t.elapsed()); + let before = runs.load(Ordering::Relaxed); + let t = Instant::now(); + let levels = on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (first, builds it): {:?} on {adapter}", t.elapsed()); + let t = Instant::now(); + on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (again): {:?}", t.elapsed()); + assert_eq!(runs.load(Ordering::Relaxed), before + 2, "{which:?}: the GPU neck ran"); + for (i, (g, c)) in levels.iter().zip(&reference).enumerate() { + assert_eq!(g.dims(), c.dims(), "{which:?} level {i}"); + let (_, rel, mean) = errors(&format!("{which:?} level {i}"), &values(g), &values(c)); + assert!(rel < 1e-4 && mean < 1e-5, "{which:?} level {i} is off"); + } + } + + // 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(), on_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.995, "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(), on_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.99, "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()), + } + assert_eq!(runs.load(Ordering::Relaxed), 4 + 2, "the clicks and the prompt used the GPU necks"); + eprintln!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + drop((cpu, on_gpu, gpu)); + // 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)); +} diff --git a/crates/pipeline/src/tone.rs b/crates/pipeline/src/tone.rs index 74a2861f70..c0f800c742 100644 --- a/crates/pipeline/src/tone.rs +++ b/crates/pipeline/src/tone.rs @@ -1,3 +1,30 @@ //! The global tone map: scene luminance → display-linear luminance, backed by `craft_develop::tone`. pub use craft_develop::tone::{CHROMA_N, CameraTone, GENERIC_KNEE_STOPS, GREY, LUT_MAX_EV, LUT_MIN_EV, LUT_N, ROLLOFF_STOPS, ToneMap}; + +/// The default raw tone curve ([`ToneMap::new`] at neutral settings) as camera-curve knots, about 1/3 EV apart +/// from 8 EV below grey to just under display white: for a camera look that knows a photo's colour but not its tone. +pub fn default_raw_camera_tone() -> Option { + const FROM_EV: f32 = -8.0; + const TO_EV: f32 = 2.6; + let map = ToneMap::new(0.0, 0.0, 0.0); + CameraTone::new(std::array::from_fn(|i| { + let x = GREY * 2f32.powf(FROM_EV + (TO_EV - FROM_EV) * i as f32 / 31.0); + [x, map.apply(x)] + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_raw_camera_tone_follows_the_default_tone_curve() { + let (camera, default) = (default_raw_camera_tone().unwrap(), ToneMap::new(0.0, 0.0, 0.0)); + for ev in [-8.0f32, -6.0, -4.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.5] { + let y = GREY * 2f32.powf(ev); + let (a, b) = (camera.apply(y), default.apply(y)); + assert!((a - b).abs() <= 0.01 * b.max(0.01), "{ev} EV: {a} vs {b}"); + } + } +} diff --git a/crates/segment/src/remote.rs b/crates/segment/src/remote.rs index 4f23d10bc7..2534e9ff05 100644 --- a/crates/segment/src/remote.rs +++ b/crates/segment/src/remote.rs @@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize}; const CONTROL_LIMIT: usize = 16 * 1024; const RESPONSE_LIMIT: usize = 4 * 1024 * 1024; const TIMEOUT: Duration = Duration::from_secs(9 * 60); +const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100); pub const ENV: &str = "LIGHTCRAFT_SAM3_REMOTE"; #[derive(Serialize, Deserialize)] @@ -194,6 +195,30 @@ fn serve_client(stream: &mut TcpStream, dir: &Path, device: candle_core::Device) } } +fn serve_connections(incoming: I, mut handle_client: H, mut retry_sleep: S) +where + I: IntoIterator>, + H: FnMut(&mut C) -> Result<(), String>, + S: FnMut(Duration), +{ + for connection in incoming { + let mut stream = match connection { + Ok(stream) => stream, + Err(error) => { + eprintln!("SAM3 accept failed: {error}"); + retry_sleep(ACCEPT_RETRY_DELAY); + continue; + } + }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_client(&mut stream))); + match result { + Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"), + Err(_) => eprintln!("SAM3 session panicked; model released"), + Ok(Ok(())) => {} + } + } +} + pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Result<(), String> { if !address.ip().is_loopback() || !device.is_metal() { return Err("SAM worker requires a loopback address and a Metal device".into()); @@ -203,14 +228,97 @@ pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Re } let listener = TcpListener::bind(address).map_err(|e| e.to_string())?; eprintln!("SAM3 worker listening on {address}; device=Metal; idle unload=600s"); - for stream in listener.incoming() { - let mut stream = stream.map_err(|e| e.to_string())?; - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| serve_client(&mut stream, dir, device.clone()))); - match result { - Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"), - Err(_) => eprintln!("SAM3 session panicked; model released"), - Ok(Ok(())) => {} - } - } + serve_connections(listener.incoming(), |stream| serve_client(stream, dir, device.clone()), std::thread::sleep); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn accept_error() -> io::Result { + Err(io::Error::new(io::ErrorKind::ConnectionAborted, "injected accept failure")) + } + + #[test] + fn sam_accept_error_before_client_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [accept_error(), Ok(1_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1]); + } + + #[test] + fn sam_accept_error_between_clients_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [Ok(1_u8), accept_error(), Ok(2_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1, 2]); + } + + #[test] + fn sam_accept_repeated_errors_back_off() { + let mut handled = Vec::new(); + let mut delays = Vec::new(); + serve_connections( + [accept_error(), accept_error(), Ok(1_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |delay| delays.push(delay), + ); + + assert_eq!(handled, [1]); + assert_eq!(delays, [Duration::from_millis(100), Duration::from_millis(100)]); + } + + #[test] + fn sam_accept_client_failure_keeps_serving() { + let mut handled = Vec::new(); + let mut delays = Vec::new(); + serve_connections( + [Ok(1_u8), Ok(2_u8)], + |stream| { + handled.push(*stream); + if *stream == 1 { Err("injected client failure".into()) } else { Ok(()) } + }, + |delay| delays.push(delay), + ); + + assert_eq!(handled, [1, 2]); + assert!(delays.is_empty()); + } + + #[test] + fn sam_accept_client_panic_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [Ok(1_u8), Ok(2_u8)], + |stream| { + handled.push(*stream); + if *stream == 1 { + std::panic::resume_unwind(Box::new("injected client panic")); + } + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1, 2]); + } +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 41af6556c2..c919a1f9ee 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -303,10 +303,10 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Barevný prostor: Rec. 2020 {curve} (HDR AVIF)", "{n} selected photo{} · {pages} page{}": "Vybrané fotografie: {n} · stránek: {pages}{:.0}{:.0}", "Already in “{}”": "Již v „{}“", - "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Přesunout do „{1}“ soubory: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Přesunout do „{1}“ soubory: {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} file{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto souborů: {n}{0:.0}. Úpravy → Zpět je vrátí.", "Drop to review {n} item{} for import": "Pusťte pro kontrolu před importem (položek: {n}){:.0}", "Drop to import {n} item{}": "Pusťte pro import (položek: {n}){:.0}", "Drop to import {n} preset{}": "Pusťte pro import přednastavení: {n}{:.0}", @@ -328,6 +328,9 @@ "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", + "Add {n} photo{} to “{}”": "Přidat do „{1}“ fotografie: {n}{0:.0}", + "{n} already there": "již tam je: {n}", + "Add “{keyword}” to {n} photo{}": "Přidat „{keyword}“ k fotografiím: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek", ", rating {} of 5": ", hodnocení: {} z 5" diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 74507b9cfc..bdd7646675 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -60,6 +60,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… nebo je přetáhněte sem", "This row covers more than one disk: drop on a folder inside it": "Tento řádek zahrnuje více disků: přetáhněte položky na některou ze složek v něm", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Místní fotografie zatím nejsou v knihovně: nejprve použijte Přidat do mých fotografií a pak je přesuňte", + "Demo photos have no file on disk, so they can't be moved": "Ukázkové fotografie nemají soubor na disku, proto je nelze přesunout", "Add to My Photos First": "Nejprve přidat do mých fotografií", "Add to Selected Photos": "Přidat k vybraným fotografiím", "Add to Target Album": "Přidat do cílového alba", @@ -2517,6 +2518,14 @@ "Get Started": "Začít", "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", "Keywords and presets apply to new files only, not to photos already in Local": "Klíčová slova a předvolby se použijí jen u nových souborů, ne u fotografií, které už jsou v Místních souborech", + "Can't add to an album folder": "Nelze přidat do složky alb", + "An album folder holds albums, not photos: drop on an album inside it": "Složka alb obsahuje alba, ne fotografie: pusťte je na album uvnitř", + "Can't add to a smart album": "Nelze přidat do inteligentního alba", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "O fotografiích inteligentního alba rozhodují jeho pravidla: změníte je přes Upravit inteligentní album…", + "Add keywords in the Keyword List": "Klíčová slova přidávejte v Seznamu klíčových slov", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Klíčové slovo fotografiím přidáte v Seznamu klíčových slov (Okno → Klíčová slova, K): pusťte je tam na klíčové slovo", + "Already on these photos": "Už je mají", + "Can't go inside itself": "Nemůže jít samo do sebe", "Same Content as Another Photo": "Stejný obsah jako jiná fotografie", "Reduce Motion": "Omezit pohyb", "Reduce motion": "Omezit pohyb", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index f7da724e8f..047de384f6 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}-Zusammenfügung mit {mp} hinzugefügt: die volle Größe, {full}, braucht mehr Arbeitsspeicher, als dieser Computer hat", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}-Zusammenfügung mit {mp} hinzugefügt, der größten möglichen Panoramagröße (volle Größe: {full})", "Already in “{}”": "Bereits in „{}“", - "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", - "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", + "Move {n} file{} to “{}”": "Nach „{1}“ verschieben (Dateien: {n}){0:.0}", + "Move {n} file{} to “{}”?": "Nach „{1}“ verschieben (Dateien: {n})?{0:.0}", "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} file{} to “{}”. Edit → Undo moves them back.": "Nach „{1}“ verschoben (Dateien: {n}). Bearbeiten → Rückgängig holt sie zurück.{0:.0}", "Drop to review {n} item{} for import": "Ablegen, um vor dem Import zu prüfen (Objekte: {n}){:.0}", "Drop to import {n} item{}": "Ablegen zum Importieren (Objekte: {n}){:.0}", "Drop to import {n} preset{}": "Ablegen zum Importieren von Vorgaben: {n}{:.0}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", + "Add {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzufügen", + "{n} already there": "{n} bereits enthalten", + "Add “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzufügen", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} von {m}: {what}. Mit den Pfeiltasten verschieben", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppe {n} von {m}: erfülle {mode}, {count} darin. Mit den Pfeiltasten verschieben", ", rating {} of 5": ", Bewertung: {} von 5" diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 60654c8a75..30d8a3e3db 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -60,6 +60,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importiere Fotos über Datei → Fotos importieren… oder lege sie hier ab", "This row covers more than one disk: drop on a folder inside it": "Diese Zeile umfasst mehr als ein Laufwerk: auf einem Ordner darin ablegen", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokale Fotos sind noch nicht in der Bibliothek: erst zu „Meine Fotos“ hinzufügen, dann verschieben", + "Demo photos have no file on disk, so they can't be moved": "Demofotos haben keine Datei auf dem Datenträger und lassen sich deshalb nicht verschieben", "Add to Selected Photos": "Zu ausgewählten Fotos hinzufügen", "Add to Target Album": "Zu Zielalbum hinzufügen", "Add to this mask": "Zu dieser Maske hinzufügen", @@ -3575,6 +3576,14 @@ "Next": "Weiter", "Get Started": "Loslegen", "Keywords and presets apply to new files only, not to photos already in Local": "Stichwörter und Vorgaben gelten nur für neue Dateien, nicht für Fotos, die schon in „Lokal“ sind", + "Can't add to an album folder": "Nicht zu einem Albenordner hinzufügbar", + "An album folder holds albums, not photos: drop on an album inside it": "Ein Albenordner enthält Alben, keine Fotos: auf ein Album darin ablegen", + "Can't add to a smart album": "Nicht zu einem Smart-Album hinzufügbar", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Die Regeln eines Smart-Albums bestimmen seine Fotos: ändere sie mit Smart-Album bearbeiten…", + "Add keywords in the Keyword List": "Stichwörter in der Stichwortliste hinzufügen", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Stichwörter vergibst du in der Stichwortliste (Fenster → Stichwörter, K): Fotos dort auf ein Stichwort ziehen", + "Already on these photos": "Bereits bei diesen Fotos", + "Can't go inside itself": "Kann nicht in sich selbst liegen", "Same Content as Another Photo": "Gleicher Inhalt wie ein anderes Foto", "Reduce Motion": "Bewegung reduzieren", "Reduce motion": "Bewegung reduzieren", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index b580c3f7e8..f0e7d06bb3 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Combinación {what} añadida a {mp}: el tamaño completo, {full}, necesita más memoria de la que tiene este ordenador", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Combinación {what} añadida a {mp}, el tamaño máximo de una panorámica (tamaño completo: {full})", "Already in “{}”": "Ya está en “{}”", - "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", - "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", + "Move {n} file{} to “{}”": "Mover {n} archivo{0} a “{1}”", + "Move {n} file{} to “{}”?": "¿Mover {n} archivo{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} file{} to “{}”. Edit → Undo moves them back.": "{n} archivo{0} movido{0} a “{1}”. Editar → Deshacer los devuelve.", "Drop to review {n} item{} for import": "Suelta para revisar {n} elemento{} antes de importar", "Drop to import {n} item{}": "Suelta para importar {n} elemento{}", "Drop to import {n} preset{}": "Suelta para importar {n} ajuste{0} preestablecido{0}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", + "Add {n} photo{} to “{}”": "Añadir {n} foto{0} a “{1}”", + "{n} already there": "ya en el álbum: {n}", + "Add “{keyword}” to {n} photo{}": "Añadir “{keyword}” a {n} foto{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regla {n} de {m}: {what}. Mover con las teclas de flecha", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: coincidir con {mode}, {count} dentro. Mover con las teclas de flecha", ", rating {} of 5": ", valoración: {} de 5" diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 7c6c503bf1..cd479a3d6c 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importar fotos con Archivo → Importar fotos… o soltarlas aquí", "This row covers more than one disk: drop on a folder inside it": "Esta fila abarca más de un disco: suéltalas en una carpeta dentro de ella", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Las fotos locales aún no están en la biblioteca: primero Añadir a Mis fotos y luego muévelas", + "Demo photos have no file on disk, so they can't be moved": "Las fotos de demostración no tienen archivo en el disco, así que no se pueden mover", "Add to Selected Photos": "Añadir a las fotos seleccionadas", "Add to Target Album": "Añadir al álbum de destino", "Add to this mask": "Añadir a esta máscara", @@ -2471,6 +2472,14 @@ "Next": "Siguiente", "Get Started": "Empezar", "Keywords and presets apply to new files only, not to photos already in Local": "Las palabras clave y los ajustes preestablecidos solo se aplican a archivos nuevos, no a fotos que ya están en Local", + "Can't add to an album folder": "No se puede añadir a una carpeta de álbumes", + "An album folder holds albums, not photos: drop on an album inside it": "Una carpeta de álbumes contiene álbumes, no fotos: suéltalas en un álbum de dentro", + "Can't add to a smart album": "No se puede añadir a un álbum inteligente", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Las reglas de un álbum inteligente eligen sus fotos: cámbialas con Editar álbum inteligente…", + "Add keywords in the Keyword List": "Añade palabras clave en la Lista de palabras clave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar una palabra clave a las fotos, usa la Lista de palabras clave (Ventana → Palabras clave, K): suéltalas allí sobre ella", + "Already on these photos": "Ya las tienen estas fotos", + "Can't go inside itself": "No puede ir dentro de sí misma", "Same Content as Another Photo": "Mismo contenido que otra foto", "Reduce Motion": "Reducir movimiento", "Reduce motion": "Reducir movimiento", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 3384571909..56f6473dc6 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -130,10 +130,10 @@ "Making the denoised picture… {}%": "Tehdään kohinanpoistettua kuvaa… {}%", "Matches: {}": "Täsmäävät: {}", "Merging… {stage} {:.0}%": "Yhdistetään… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Siirrä kuvia kohteeseen ”{1}”: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Siirretäänkö kuvat kohteeseen ”{1}” ({n}){0:.0}?", + "Move {n} file{} to “{}”": "Siirrä tiedostoja kohteeseen ”{1}”: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Siirretäänkö tiedostot kohteeseen ”{1}” ({n}){0:.0}?", "Move {what} to Recently Deleted?": "Siirretäänkö {what} Äskettäin poistettuihin?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Siirretty kuvia kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Siirretty tiedostoja kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.", "Moved {} photo(s)": "Siirretty kuvia: {}", "Moved; {} photo(s) relinked": "Siirretty; yhdistetty uudelleen kuvia: {}", "Named ({named_n})": "Nimetyt ({named_n})", @@ -325,6 +325,9 @@ "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", + "Add {n} photo{} to “{}”": "Lisää kuvia albumiin ”{1}”: {n}{0:.0}", + "Add “{keyword}” to {n} photo{}": "Lisää ”{keyword}” kuviin: {n}{:.0}", + "{n} already there": "jo albumissa: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä", ", rating {} of 5": ", luokitus: {} / 5" diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 27bc00f2f1..c360df6c18 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2427,6 +2427,15 @@ "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat.", "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", "Keywords and presets apply to new files only, not to photos already in Local": "Avainsanat ja esiasetukset koskevat vain uusia tiedostoja, eivät kuvia, jotka ovat jo Paikallisessa", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Älyalbumin säännöt valitsevat sen kuvat: muuta niitä komennolla Muokkaa älyalbumia…", + "Add keywords in the Keyword List": "Lisää avainsanoja avainsanaluettelossa", + "Already on these photos": "Jo näissä kuvissa", + "An album folder holds albums, not photos: drop on an album inside it": "Albumikansio sisältää albumeja, ei kuvia: pudota kuvat sen sisällä olevalle albumille", + "Can't add to a smart album": "Älyalbumiin ei voi lisätä", + "Can't add to an album folder": "Albumikansioon ei voi lisätä", + "Can't go inside itself": "Ei voi siirtää itsensä sisään", + "Demo photos have no file on disk, so they can't be moved": "Demokuvilla ei ole tiedostoa levyllä, joten niitä ei voi siirtää", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Anna kuville avainsana avainsanaluettelossa (Ikkuna → Avainsanat, K): pudota ne siellä avainsanan päälle", "Same Content as Another Photo": "Sama sisältö kuin toisella kuvalla", "Reduce Motion": "Vähennä liikettä", "Reduce motion": "Vähennä liikettä", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 4e0c8eaef0..7f1803c9c1 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Fusion de {what} ajoutée en {mp} : la taille complète, {full}, demande plus de mémoire que n’en a cet ordinateur", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Fusion de {what} ajoutée en {mp}, la plus grande taille possible pour un panorama (taille complète : {full})", "Already in “{}”": "Déjà dans « {} »", - "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", - "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", + "Move {n} file{} to “{}”": "Déplacer {n} fichier{} vers « {} »", + "Move {n} file{} to “{}”?": "Déplacer {n} fichier{} 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{0} déplacée{0} vers « {1} ». Modifier → Annuler les remet en place.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} fichier{0} déplacé{0} vers « {1} ». Modifier → Annuler les remet en place.", "Drop to review {n} item{} for import": "Déposez pour vérifier {n} élément{} avant l'import", "Drop to import {n} item{}": "Déposez pour importer {n} élément{}", "Drop to import {n} preset{}": "Déposez pour importer {n} préréglage{}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", + "Add {n} photo{} to “{}”": "Ajouter {n} photo{} à « {} »", + "{n} already there": "{n} déjà présent(s)", + "Add “{keyword}” to {n} photo{}": "Ajouter « {keyword} » à {n} photo{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Règle {n} sur {m} : {what}. Déplacer avec les flèches", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Groupe {n} sur {m} : correspondre à {mode}, {count} à l’intérieur. Déplacer avec les flèches", ", rating {} of 5": ", note : {} sur 5" diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 11722dad75..a3d7bf8f52 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importez des photos avec Fichier → Importer des photos… ou déposez-les ici", "This row covers more than one disk: drop on a folder inside it": "Cette ligne couvre plusieurs disques : déposez-les sur un dossier qu’elle contient", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Les photos locales ne sont pas encore dans la bibliothèque : Ajouter à Mes photos d’abord, puis déplacez-les", + "Demo photos have no file on disk, so they can't be moved": "Les photos de démonstration n’ont pas de fichier sur le disque : on ne peut pas les déplacer", "Add to Selected Photos": "Ajouter aux photos sélectionnées", "Add to Target Album": "Ajouter à l'album cible", "Add to this mask": "Ajouter à ce masque", @@ -3654,6 +3655,14 @@ "Next": "Suivant", "Get Started": "Commencer", "Keywords and presets apply to new files only, not to photos already in Local": "Les mots-clés et les préréglages ne s'appliquent qu'aux nouveaux fichiers, pas aux photos déjà dans Local", + "Can't add to an album folder": "Impossible d’ajouter à un dossier d’albums", + "An album folder holds albums, not photos: drop on an album inside it": "Un dossier d’albums contient des albums, pas des photos : déposez-les sur un album à l’intérieur", + "Can't add to a smart album": "Impossible d’ajouter à un album intelligent", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Les règles d’un album intelligent choisissent ses photos : modifiez-les avec Modifier l'album intelligent…", + "Add keywords in the Keyword List": "Ajoutez des mots-clés dans la Liste des mots-clés", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Pour donner un mot-clé à des photos, utilisez la Liste des mots-clés (Fenêtre → Mots-clés, K) : déposez-les sur le mot-clé", + "Already on these photos": "Déjà sur ces photos", + "Can't go inside itself": "Ne peut pas aller dans lui-même", "Same Content as Another Photo": "Même contenu qu'une autre photo", "Reduce Motion": "Réduire les animations", "Reduce motion": "Réduire les animations", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index ee6b6778ec..fc4e7093f0 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft tidak dapat membuka jendela: {e}\n\nDetailnya ada di file log: {path}", "Matches: {}": "Cocok: {}", "Merging… {stage} {:.0}%": "Menggabungkan… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Pindahkan {n} foto{0:.0} ke “{1}”", - "Move {n} photo{} to “{}”?": "Pindahkan {n} foto{0:.0} ke “{1}”?", + "Move {n} file{} to “{}”": "Pindahkan {n} file{0:.0} ke “{1}”", + "Move {n} file{} to “{}”?": "Pindahkan {n} file{0:.0} ke “{1}”?", "Move {what} to Recently Deleted?": "Pindahkan {what} ke Baru dihapus?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} file dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.", "Named ({named_n})": "Bernama ({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "Tempel ke {n} foto{:.0} — hanya menempelkan pengaturan yang disalin", "Preset: {name}": "Preset: {name}", @@ -328,6 +328,9 @@ "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", + "Add {n} photo{} to “{}”": "Tambahkan {n} foto{0:.0} ke “{1}”", + "Add “{keyword}” to {n} photo{}": "Tambahkan “{keyword}” ke {n} foto{:.0}", + "{n} already there": "{n} sudah ada", "Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah", ", rating {} of 5": ", rating: {} dari 5" diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index c1dbe90f35..d07ec76104 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2441,6 +2441,15 @@ "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna.", "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", "Keywords and presets apply to new files only, not to photos already in Local": "Kata kunci dan prasetel hanya berlaku untuk berkas baru, bukan foto yang sudah ada di Lokal", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Aturan album pintar menentukan fotonya: ubah dengan Edit album pintar…", + "Add keywords in the Keyword List": "Tambahkan kata kunci di Daftar kata kunci", + "Already on these photos": "Sudah ada pada foto ini", + "An album folder holds albums, not photos: drop on an album inside it": "Folder album berisi album, bukan foto: jatuhkan ke album di dalamnya", + "Can't add to a smart album": "Tidak dapat menambahkan ke album pintar", + "Can't add to an album folder": "Tidak dapat menambahkan ke folder album", + "Can't go inside itself": "Tidak dapat dimasukkan ke dalam dirinya sendiri", + "Demo photos have no file on disk, so they can't be moved": "Foto demo tidak memiliki file di disk, sehingga tidak dapat dipindahkan", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Beri foto kata kunci di Daftar kata kunci (Jendela → Kata kunci, K): jatuhkan ke kata kunci di sana", "Same Content as Another Photo": "Konten sama dengan foto lain", "Reduce Motion": "Kurangi gerakan", "Reduce motion": "Kurangi gerakan", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index dffff0cace..a1a567312b 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -303,9 +303,9 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Spazio colore: Rec. 2020 {curve} (AVIF HDR)", "{n} selected photo{} · {pages} page{}": "Foto selezionate: {n} · pagine: {pages}{:.0}{:.0}", "Already in “{}”": "Già in “{}”", - "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.", + "Move {n} file{} to “{}”": "Sposta file in “{1}” ({n}){0:.0}", + "Move {n} file{} to “{}”?": "Spostare i file in “{1}” ({n})?{0:.0}", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "File spostati in “{1}”: {n}{0:.0}. Modifica → Annulla li riporta indietro.", "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", "Drop to review {n} item{} for import": "Rilascia per rivedere prima dell'importazione (elementi: {n}){:.0}", "Drop to import {n} item{}": "Rilascia per importare (elementi: {n}){:.0}", @@ -328,6 +328,9 @@ "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", + "Add {n} photo{} to “{}”": "Aggiungi {n} foto{0:.0} a “{1}”", + "{n} already there": "{n} già presenti", + "Add “{keyword}” to {n} photo{}": "Aggiungi “{keyword}” a {n} foto{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce", ", rating {} of 5": ", valutazione: {} su 5" diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index fd15462668..56e83e7991 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importa le foto con File → Importa foto…, oppure trascinale qui", "This row covers more than one disk: drop on a folder inside it": "Questa riga comprende più di un disco: rilascia su una cartella al suo interno", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Le foto locali non sono ancora nella libreria: prima Aggiungi a Le mie foto, poi spostale", + "Demo photos have no file on disk, so they can't be moved": "Le foto dimostrative non hanno un file su disco, quindi non si possono spostare", "Add to Selected Photos": "Aggiungi alle foto selezionate", "Add to Target Album": "Aggiungi all'album di destinazione", "Add to this mask": "Aggiungi a questa maschera", @@ -2635,6 +2636,14 @@ "Get Started": "Inizia", "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", "Keywords and presets apply to new files only, not to photos already in Local": "Parole chiave e preset si applicano solo ai file nuovi, non alle foto già in Locale", + "Can't add to an album folder": "Impossibile aggiungere a una cartella di album", + "An album folder holds albums, not photos: drop on an album inside it": "Una cartella di album contiene album, non foto: rilascia su un album al suo interno", + "Can't add to a smart album": "Impossibile aggiungere a un album smart", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Le regole di un album smart scelgono le sue foto: cambiale con Modifica album smart…", + "Add keywords in the Keyword List": "Aggiungi le parole chiave nell'Elenco parole chiave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Per dare una parola chiave alle foto usa l'Elenco parole chiave (Finestra → Parole chiave, K): rilasciale lì sulla parola chiave", + "Already on these photos": "Già presente su queste foto", + "Can't go inside itself": "Non può andare dentro se stessa", "Same Content as Another Photo": "Stesso contenuto di un'altra foto", "Reduce Motion": "Riduci movimento", "Reduce motion": "Riduci movimento", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 11adadc07c..17b85d82fe 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraftのウィンドウを開けませんでした: {e}\n\n詳しくはログファイルをご覧ください: {path}", "Matches: {}": "一致条件:{}", "Merging… {stage} {:.0}%": "合成中… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "{n}枚を「{1}」に移動{0:.0}", - "Move {n} photo{} to “{}”?": "{n}枚を「{1}」に移動しますか?{0:.0}", + "Move {n} file{} to “{}”": "{n}件のファイルを「{1}」に移動{0:.0}", + "Move {n} file{} to “{}”?": "{n}件のファイルを「{1}」に移動しますか?{0:.0}", "Move {what} to Recently Deleted?": "{what}を「最近削除した写真」に移動しますか?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n}枚を「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n}件のファイルを「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}", "Named ({named_n})": "名前付き({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "{n}枚に貼り付け{:.0}(コピーされた設定だけを適用)", "Preset: {name}": "プリセット:{name}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", + "Add {n} photo{} to “{}”": "{n}枚を「{1}」に追加{0:.0}", + "{n} already there": "{n}枚は追加済み", + "Add “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "条件 {n}/{m}:{what}。矢印キーで移動", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "グループ {n}/{m}:一致条件 {mode}、中に {count} 件。矢印キーで移動", ", rating {} of 5": "、評価: 5段階中{}" diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index f34575eaad..7e6acaa181 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -46,6 +46,7 @@ "Import photos with File → Import Photos…, or drop them here": "「ファイル → 写真を読み込む…」から読み込むか、ここに写真をドロップしてください", "This row covers more than one disk: drop on a folder inside it": "この行は複数のディスクにまたがっています。中のフォルダにドロップしてください", "Local photos aren't in the library yet: Add to My Photos first, then move them": "ローカルの写真はまだライブラリにありません。先に「マイフォトに追加」してから移動してください", + "Demo photos have no file on disk, so they can't be moved": "デモの写真にはディスク上のファイルがないため、移動できません", "Add to Selected Photos": "選択した写真に追加", "Add to Target Album": "追加先アルバムに追加", "Add to this mask": "このマスクに追加", @@ -2469,6 +2470,14 @@ "Next": "次へ", "Get Started": "始める", "Keywords and presets apply to new files only, not to photos already in Local": "キーワードとプリセットは新しいファイルにのみ適用され、すでにローカルにある写真には適用されません", + "Can't add to an album folder": "アルバムフォルダには追加できません", + "An album folder holds albums, not photos: drop on an album inside it": "アルバムフォルダに入れられるのはアルバムだけです:中のアルバムにドロップしてください", + "Can't add to a smart album": "スマートアルバムには追加できません", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "スマートアルバムの写真はルールで決まります:「スマートアルバムを編集…」で変更してください", + "Add keywords in the Keyword List": "キーワードはキーワードリストで追加します", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "写真にキーワードを付けるには、キーワードリスト(ウィンドウ → キーワード、K)で、そのキーワードにドロップしてください", + "Already on these photos": "すでにこの写真にあります", + "Can't go inside itself": "自分の中には入れられません", "Same Content as Another Photo": "他の写真と同じ内容", "Reduce Motion": "動きを減らす", "Reduce motion": "動きを減らす", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c6fe5fb034..3d52e54c26 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -306,10 +306,10 @@ "{n} selected photos · {pages} pages": "მონიშნული ფოტო: {n} · გვერდი: {pages}", "{n} selected photo{} · {pages} page{}": "არჩეული ფოტო: {n} · გვერდი: {pages}{:.0}{:.0}", "Already in “{}”": "უკვე „{}“-შია", - "Move {n} photo{} to “{}”": "ფოტოს გადატანა „{1}“-ში: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "გადავიდეს „{1}“-ში ფოტო: {n}{0:.0}?", + "Move {n} file{} to “{}”": "ფაილის გადატანა „{1}“-ში: {n}{0:.0}", + "Move {n} file{} 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} file{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფაილი: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.", "Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}", "Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}", "Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}", @@ -331,6 +331,9 @@ "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", + "Add {n} photo{} to “{}”": "დაამატეთ ფოტო „{1}“-ში: {n}{0:.0}", + "{n} already there": "{n} უკვე არის", + "Add “{keyword}” to {n} photo{}": "დაამატეთ „{keyword}“ ფოტოებს: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით", ", rating {} of 5": ", შეფასება: {} 5-დან" diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 22b96e8759..096c817b41 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3738,6 +3738,15 @@ "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“.", "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", "Keywords and presets apply to new files only, not to photos already in Local": "საკვანძო სიტყვები და პრესეტები მხოლოდ ახალ ფაილებზე მოქმედებს და არა იმ ფოტოებზე, რომლებიც უკვე ლოკალშია", + "Can't add to an album folder": "ალბომების საქაღალდეში დამატება შეუძლებელია", + "An album folder holds albums, not photos: drop on an album inside it": "ალბომების საქაღალდეში ალბომებია, არა ფოტოები: ჩააგდეთ მასში არსებულ ალბომზე", + "Can't add to a smart album": "სმარტ-ალბომში დამატება შეუძლებელია", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "სმარტ-ალბომის ფოტოებს მისი წესები ირჩევს: შეცვალეთ „სმარტ-ალბომის რედაქტირება…“-ით", + "Add keywords in the Keyword List": "საკვანძო სიტყვები დაამატეთ საკვანძო სიტყვების სიაში", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "ფოტოებისთვის საკვანძო სიტყვის მისაცემად გამოიყენეთ საკვანძო სიტყვების სია (ფანჯარა → საკვანძო სიტყვები, K): ჩააგდეთ იქ სასურველ სიტყვაზე", + "Already on these photos": "ამ ფოტოებს უკვე აქვთ", + "Can't go inside itself": "საკუთარ თავში ვერ მოხვდება", + "Demo photos have no file on disk, so they can't be moved": "სადემონსტრაციო ფოტოებს დისკზე ფაილი არ აქვთ, ამიტომ მათი გადატანა შეუძლებელია", "Same Content as Another Photo": "იგივე შიგთავსი, რაც სხვა ფოტოს", "Reduce Motion": "მოძრაობის შემცირება", "Reduce motion": "მოძრაობის შემცირება", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index c77e105650..f46b718f40 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -302,10 +302,10 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Przestrzeń kolorów: Rec. 2020 {curve} (HDR AVIF)", "{n} selected photo{} · {pages} page{}": "Wybrane zdjęcia: {n} · stron: {pages}{:.0}{:.0}", "Already in “{}”": "Już w „{}”", - "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Przenieś do „{1}” — pliki: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Przenieść do „{1}” — pliki: {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} file{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — pliki: {n}{0:.0}. Edytuj → Cofnij przywróci je.", "Drop to review {n} item{} for import": "Upuść, aby przejrzeć przed importem (elementy: {n}){:.0}", "Drop to import {n} item{}": "Upuść, aby zaimportować (elementy: {n}){:.0}", "Drop to import {n} preset{}": "Upuść, aby zaimportować ustawienia wstępne: {n}{:.0}", @@ -328,6 +328,9 @@ "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", + "Add {n} photo{} to “{}”": "Dodaj do „{1}” — zdjęcia: {n}{0:.0}", + "{n} already there": "{n} już tam jest", + "Add “{keyword}” to {n} photo{}": "Dodaj „{keyword}” do zdjęć: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami", ", rating {} of 5": ", ocena: {} na 5" diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 8691af1191..d184ccc91a 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2396,6 +2396,15 @@ "Get Started": "Zaczynamy", "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", "Keywords and presets apply to new files only, not to photos already in Local": "Słowa kluczowe i ustawienia predefiniowane dotyczą tylko nowych plików, nie zdjęć, które już są w Lokalnych", + "Can't add to an album folder": "Nie można dodać do folderu albumów", + "An album folder holds albums, not photos: drop on an album inside it": "Folder albumów zawiera albumy, nie zdjęcia: upuść na album w jego wnętrzu", + "Can't add to a smart album": "Nie można dodać do albumu inteligentnego", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "O zdjęciach albumu inteligentnego decydują jego reguły: zmienisz je przez Edytuj album inteligentny…", + "Add keywords in the Keyword List": "Dodawaj słowa kluczowe na Liście słów kluczowych", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Aby nadać zdjęciom słowo kluczowe, użyj Listy słów kluczowych (Okno → Słowa kluczowe, K): upuść je tam na to słowo", + "Already on these photos": "Już mają je te zdjęcia", + "Can't go inside itself": "Nie może trafić do siebie samego", + "Demo photos have no file on disk, so they can't be moved": "Zdjęcia demonstracyjne nie mają pliku na dysku, więc nie można ich przenieść", "Same Content as Another Photo": "Ta sama zawartość co inne zdjęcie", "Reduce Motion": "Ogranicz ruch", "Reduce motion": "Ogranicz ruch", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index d7d5b054c0..b61ac02c84 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -61,10 +61,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "O LightCraft não conseguiu abrir sua janela: {e}\n\nO arquivo de log tem os detalhes: {path}", "Matches: {}": "Correspondências: {}", "Merging… {stage} {:.0}%": "Mesclando… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Mover {n} foto{0} para “{1}”", - "Move {n} photo{} to “{}”?": "Mover {n} foto{0} para “{1}”?", + "Move {n} file{} to “{}”": "Mover {n} arquivo{0} para “{1}”", + "Move {n} file{} to “{}”?": "Mover {n} arquivo{0} para “{1}”?", "Move {what} to Recently Deleted?": "Mover {what} para Excluídos recentemente?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} para “{1}”. Editar → Desfazer as traz de volta.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} arquivo{0} movido{0} para “{1}”. Editar → Desfazer os traz de volta.", "Named ({named_n})": "Nomeadas ({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "Colar em {n} foto{} — somente os ajustes copiados são colados", "Preset: {name}": "Predefinição: {name}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", + "Add {n} photo{} to “{}”": "Adicionar {n} foto{0} a “{1}”", + "{n} already there": "já no álbum: {n}", + "Add “{keyword}” to {n} photo{}": "Adicionar “{keyword}” a {n} foto{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regra {n} de {m}: {what}. Mova com as setas", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: igualar {mode}, {count} dentro. Mova com as setas", ", rating {} of 5": ", avaliação: {} de 5" diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 6a46bb33dc..7e8ef0e9e1 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importe fotos com Arquivo → Importar fotos… ou solte-as aqui", "This row covers more than one disk: drop on a folder inside it": "Esta linha abrange mais de um disco: solte em uma pasta dentro dela", "Local photos aren't in the library yet: Add to My Photos first, then move them": "As fotos locais ainda não estão na biblioteca: primeiro Adicionar às Minhas fotos, depois mova-as", + "Demo photos have no file on disk, so they can't be moved": "As fotos de demonstração não têm arquivo no disco, então não podem ser movidas", "Add to Selected Photos": "Adicionar às fotos selecionadas", "Add to Target Album": "Adicionar ao álbum de destino", "Add to this mask": "Adicionar a esta máscara", @@ -2315,6 +2316,14 @@ "Next": "Próximo", "Get Started": "Começar", "Keywords and presets apply to new files only, not to photos already in Local": "Palavras-chave e predefinições valem só para arquivos novos, não para fotos que já estão em Local", + "Can't add to an album folder": "Não é possível adicionar a uma pasta de álbuns", + "An album folder holds albums, not photos: drop on an album inside it": "Uma pasta de álbuns contém álbuns, não fotos: solte em um álbum dentro dela", + "Can't add to a smart album": "Não é possível adicionar a um álbum inteligente", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "As regras de um álbum inteligente escolhem suas fotos: altere-as com Editar álbum inteligente…", + "Add keywords in the Keyword List": "Adicione palavras-chave na Lista de palavras-chave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar uma palavra-chave às fotos, use a Lista de palavras-chave (Janela → Palavras-chave, K): solte-as lá sobre ela", + "Already on these photos": "Já estão nestas fotos", + "Can't go inside itself": "Não pode ficar dentro de si mesma", "Same Content as Another Photo": "Mesmo conteúdo que outra foto", "Reduce Motion": "Reduzir movimento", "Reduce motion": "Reduzir movimento", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 6987693107..167218dac3 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: слияние добавлено в размере {mp}: для полного размера ({full}) не хватает памяти этого компьютера", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: слияние добавлено в размере {mp} — это наибольший размер панорамы (полный размер: {full})", "Already in “{}”": "Уже в «{}»", - "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Переместить в «{1}» файлов: {n}{0:.0}", + "Move {n} file{} 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} file{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено файлов: {n}{0:.0}. Правка → Отменить вернёт их.", "Drop to review {n} item{} for import": "Отпустите для проверки перед импортом (элементов: {n}){:.0}", "Drop to import {n} item{}": "Отпустите для импорта (элементов: {n}){:.0}", "Drop to import {n} preset{}": "Отпустите для импорта пресетов: {n}{:.0}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", + "Add {n} photo{} to “{}”": "Добавить в «{1}» фото: {n}{0:.0}", + "{n} already there": "{n} уже там", + "Add “{keyword}” to {n} photo{}": "Добавить «{keyword}» к фото: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Условие {n} из {m}: {what}. Перемещение стрелками", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Группа {n} из {m}: совпадение {mode}, внутри {count}. Перемещение стрелками", ", rating {} of 5": ", оценка: {} из 5" diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b9c6c9f31f..e69871707c 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -221,6 +221,7 @@ "Import photos with File → Import Photos…, or drop them here": "Импортируйте фото через Файл → Импорт фото… или перетащите их сюда", "This row covers more than one disk: drop on a folder inside it": "Эта строка охватывает несколько дисков: перетащите на папку внутри неё", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальных фото ещё нет в библиотеке: сначала «Добавить в «Мои фото»», затем перемещайте", + "Demo photos have no file on disk, so they can't be moved": "У демонстрационных фото нет файла на диске, поэтому их нельзя переместить", "Add to Selected Photos": "Добавить к выбранным фото", "Add to Target Album": "Добавить в целевой альбом", "Add to this mask": "Добавить к этой маске", @@ -2677,6 +2678,14 @@ "Next": "Далее", "Get Started": "Начать", "Keywords and presets apply to new files only, not to photos already in Local": "Ключевые слова и пресеты применяются только к новым файлам, а не к фото, которые уже есть в «Локальных»", + "Can't add to an album folder": "Нельзя добавить в папку альбомов", + "An album folder holds albums, not photos: drop on an album inside it": "В папке альбомов лежат альбомы, а не фото: бросьте на альбом внутри неё", + "Can't add to a smart album": "Нельзя добавить в смарт-альбом", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбома определяются его правилами: измените их через «Изменить смарт-альбом…»", + "Add keywords in the Keyword List": "Добавляйте ключевые слова в списке ключевых слов", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Чтобы задать фото ключевое слово, используйте список ключевых слов (Окно → Ключевые слова, K): бросьте фото там на нужное слово", + "Already on these photos": "Уже есть у этих фото", + "Can't go inside itself": "Нельзя поместить внутрь себя", "Same Content as Another Photo": "То же содержимое, что у другого фото", "Reduce Motion": "Уменьшить движение", "Reduce motion": "Уменьшить движение", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 1b84af4708..fc6d574441 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -299,9 +299,9 @@ "…and {more} more": "…och {more} till", "Already in “{}”": "Already in “{}”", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Color space: Rec. 2020 {curve} (HDR AVIF)", - "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", - "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Move {n} file{} to “{}”": "Move {n} file{} to “{}”", + "Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} katalogfoton finns i Nyligen raderade i det här biblioteket och ligger kvar där; återställ dem från Nyligen raderade för att se dem.", "{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.", @@ -328,6 +328,9 @@ "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", + "Add {n} photo{} to “{}”": "Lägg till foton i ”{1}”: {n}{0:.0}", + "Add “{keyword}” to {n} photo{}": "Lägg till ”{keyword}” på foton: {n}{:.0}", + "{n} already there": "redan i albumet: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna", ", rating {} of 5": ", betyg: {} av 5" diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index d803eda012..4441aa4b2d 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2531,6 +2531,15 @@ "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar.", "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", "Keywords and presets apply to new files only, not to photos already in Local": "Nyckelord och förinställningar gäller bara nya filer, inte foton som redan finns i Lokalt", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Ett smart albums regler väljer dess foton: ändra dem med Redigera smart album…", + "Add keywords in the Keyword List": "Lägg till nyckelord i nyckelordslistan", + "Already on these photos": "Finns redan på de här fotona", + "An album folder holds albums, not photos: drop on an album inside it": "En albummapp innehåller album, inte foton: släpp på ett album i den", + "Can't add to a smart album": "Kan inte läggas till i ett smart album", + "Can't add to an album folder": "Kan inte läggas till i en albummapp", + "Can't go inside itself": "Kan inte läggas inuti sig själv", + "Demo photos have no file on disk, so they can't be moved": "Demofoton har ingen fil på disken och kan därför inte flyttas", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Ge foton ett nyckelord i nyckelordslistan (Fönster → Nyckelord, K): släpp dem på det där", "Same Content as Another Photo": "Samma innehåll som ett annat foto", "Reduce Motion": "Minska rörelse", "Reduce motion": "Minska rörelse", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index b8515e952c..526785046d 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: об’єднання додано в розмірі {mp}: для повного розміру ({full}) бракує пам’яті цього комп’ютера", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: об’єднання додано в розмірі {mp} — це найбільший розмір панорами (повний розмір: {full})", "Already in “{}”": "Уже в «{}»", - "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Перемістити до «{1}» файлів: {n}{0:.0}", + "Move {n} file{} 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} file{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено файлів: {n}{0:.0}. Редагування → Скасувати поверне їх.", "Drop to review {n} item{} for import": "Відпустіть для перегляду перед імпортом (елементів: {n}){:.0}", "Drop to import {n} item{}": "Відпустіть для імпорту (елементів: {n}){:.0}", "Drop to import {n} preset{}": "Відпустіть для імпорту наборів налаштувань: {n}{:.0}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", + "Add {n} photo{} to “{}”": "Додати до «{1}» фото: {n}{0:.0}", + "{n} already there": "{n} уже там", + "Add “{keyword}” to {n} photo{}": "Додати «{keyword}» до фото: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Правило {n} з {m}: {what}. Переміщення стрілками", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Група {n} з {m}: збіг {mode}, усередині {count}. Переміщення стрілками", ", rating {} of 5": ", оцінка: {} з 5" diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index eab47d43cc..4163d6d5ed 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -398,6 +398,7 @@ "Can't be moved here": "Сюди перемістити не можна", "This row covers more than one disk: drop on a folder inside it": "Цей рядок охоплює кілька дисків: перетягніть на теку всередині нього", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальних фото ще немає в бібліотеці: спершу «Додати до моїх фото», потім переміщуйте", + "Demo photos have no file on disk, so they can't be moved": "Демонстраційні фото не мають файлу на диску, тому їх не можна перемістити", "Add to Selected Photos": "Додати до вибраних фото", "Add to Target Album": "Додати до цільового альбому", "Add to this mask": "Додати до цієї маски", @@ -2467,6 +2468,14 @@ "Next": "Далі", "Get Started": "Почати", "Keywords and presets apply to new files only, not to photos already in Local": "Ключові слова та пресети застосовуються лише до нових файлів, а не до фото, що вже є в «Локальних»", + "Can't add to an album folder": "Не можна додати до теки альбомів", + "An album folder holds albums, not photos: drop on an album inside it": "У теці альбомів лежать альбоми, а не фото: киньте на альбом усередині неї", + "Can't add to a smart album": "Не можна додати до смарт-альбому", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбому визначаються його правилами: змініть їх через «Редагувати смарт-альбом…»", + "Add keywords in the Keyword List": "Додавайте ключові слова у списку ключових слів", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Щоб задати фото ключове слово, скористайтеся списком ключових слів (Вікно → Ключові слова, K): киньте фото там на потрібне слово", + "Already on these photos": "Уже є в цих фото", + "Can't go inside itself": "Не можна помістити всередину себе", "Same Content as Another Photo": "Той самий вміст, що й в іншого фото", "Reduce Motion": "Зменшити рух", "Reduce motion": "Зменшити рух", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 9335abe147..a1d9b0a34b 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -130,10 +130,10 @@ "Making the denoised picture… {}%": "Đang tạo ảnh đã khử nhiễu… {}%", "Matches: {}": "Khớp: {}", "Merging… {stage} {:.0}%": "Đang ghép… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", - "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", + "Move {n} file{} to “{}”": "Move {n} file{} to “{}”", + "Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?", "Move {what} to Recently Deleted?": "Chuyển {what} vào Đã xóa gần đây?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.", "Moved {} photo(s)": "Đã di chuyển {} ảnh", "Moved; {} photo(s) relinked": "Đã di chuyển; liên kết lại {} ảnh", "Named ({named_n})": "Có tên ({named_n})", @@ -325,6 +325,9 @@ "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", + "Add {n} photo{} to “{}”": "Thêm {n} ảnh{0:.0} vào “{1}”", + "Add “{keyword}” to {n} photo{}": "Thêm “{keyword}” vào {n} ảnh{:.0}", + "{n} already there": "{n} đã có sẵn", "Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên", ", rating {} of 5": ", xếp hạng: {} trên 5" diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 664c8bbe7f..cd1408ddcd 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2755,6 +2755,15 @@ "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng.", "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", "Keywords and presets apply to new files only, not to photos already in Local": "Từ khóa và cài đặt sẵn chỉ áp dụng cho tệp mới, không áp dụng cho ảnh đã có trong Cục bộ", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Quy tắc của album thông minh chọn ảnh của nó: thay đổi bằng Chỉnh sửa album thông minh…", + "Add keywords in the Keyword List": "Thêm từ khóa trong Danh sách từ khóa", + "Already on these photos": "Đã có trên các ảnh này", + "An album folder holds albums, not photos: drop on an album inside it": "Thư mục album chứa album, không chứa ảnh: hãy thả vào một album bên trong nó", + "Can't add to a smart album": "Không thể thêm vào album thông minh", + "Can't add to an album folder": "Không thể thêm vào thư mục album", + "Can't go inside itself": "Không thể đặt vào chính nó", + "Demo photos have no file on disk, so they can't be moved": "Ảnh demo không có tệp trên đĩa nên không thể di chuyển", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Gán từ khóa cho ảnh trong Danh sách từ khóa (Cửa sổ → Từ khóa, K): hãy thả ảnh lên từ khóa ở đó", "Same Content as Another Photo": "Cùng nội dung với ảnh khác", "Reduce Motion": "Giảm chuyển động", "Reduce motion": "Giảm chuyển động", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 2a44d9815d..11c1a72bdb 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 无法打开窗口:{e}\n\n详细信息见日志文件:{path}", "Matches: {}": "匹配项:{0}", "Merging… {stage} {:.0}%": "合成中… {stage} {0:.0}%", - "Move {n} photo{} to “{}”": "将 {n} 张照片移到“{1}”{0:.0}", - "Move {n} photo{} to “{}”?": "将 {n} 张照片移到“{1}”?{0:.0}", + "Move {n} file{} to “{}”": "将 {n} 个文件移到“{1}”{0:.0}", + "Move {n} file{} to “{}”?": "将 {n} 个文件移到“{1}”?{0:.0}", "Move {what} to Recently Deleted?": "将 {what} 移到最近删除?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已将 {n} 张照片移到“{1}”{0:.0}。编辑 → 撤销 可移回。", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已将 {n} 个文件移到“{1}”{0:.0}。编辑 → 撤销 可移回。", "Named ({named_n})": "已命名({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "粘贴到 {n} 张照片 — 仅粘贴已复制的设置{0:.0}", "Preset: {name}": "预设:{name}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", + "Add {n} photo{} to “{}”": "将 {n} 张照片添加到“{1}”{0:.0}", + "{n} already there": "{n} 张已在其中", + "Add “{keyword}” to {n} photo{}": "将“{keyword}”添加到 {n} 张照片{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "规则 {n}/{m}:{what}。用方向键移动", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "组 {n}/{m}:匹配{mode},内含 {count} 项。用方向键移动", ", rating {} of 5": ",评分:{}/5" diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index f64a9dd2cf..d542ced17e 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "使用“文件 → 导入照片…”导入照片,或将照片拖放到此处", "This row covers more than one disk: drop on a folder inside it": "此行涵盖多个磁盘:请拖放到其中的文件夹", "Local photos aren't in the library yet: Add to My Photos first, then move them": "本地照片尚未在图库中:请先“添加到我的照片”,再移动", + "Demo photos have no file on disk, so they can't be moved": "演示照片在磁盘上没有文件,因此无法移动", "Add to Selected Photos": "添加到所选照片", "Add to Target Album": "添加到目标相册", "Add to this mask": "添加到此蒙版", @@ -2470,6 +2471,14 @@ "Next": "下一步", "Get Started": "开始使用", "Keywords and presets apply to new files only, not to photos already in Local": "关键词和预设仅应用于新文件,不适用于已在“本地”中的照片", + "Can't add to an album folder": "无法添加到相册文件夹", + "An album folder holds albums, not photos: drop on an album inside it": "相册文件夹里放的是相册,不是照片:请拖到其中的某个相册上", + "Can't add to a smart album": "无法添加到智能相册", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "智能相册的照片由其规则决定:请用“编辑智能相册…”更改规则", + "Add keywords in the Keyword List": "请在关键字列表中添加关键字", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要给照片添加关键字,请使用关键字列表(窗口 → 关键字,K),把照片拖到那里的关键字上", + "Already on these photos": "这些照片已有", + "Can't go inside itself": "不能放入自身", "Same Content as Another Photo": "与另一张照片内容相同", "Reduce Motion": "减少动态效果", "Reduce motion": "减少动态效果", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 941ca9ae27..5f70bf9171 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -58,10 +58,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 無法開啟視窗:{e}\n\n詳細資訊請見記錄檔:{path}", "Matches: {}": "符合條件:{}", "Merging… {stage} {:.0}%": "正在合併… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "將 {n} 張照片移到「{1}」{0:.0}", - "Move {n} photo{} to “{}”?": "將 {n} 張照片移到「{1}」?{0:.0}", + "Move {n} file{} to “{}”": "將 {n} 個檔案移到「{1}」{0:.0}", + "Move {n} file{} to “{}”?": "將 {n} 個檔案移到「{1}」?{0:.0}", "Move {what} to Recently Deleted?": "要將{what}移至「最近刪除」嗎?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已將 {n} 張照片移到「{1}」{0:.0}。編輯 → 復原 可移回。", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已將 {n} 個檔案移到「{1}」{0:.0}。編輯 → 復原 可移回。", "Named ({named_n})": "已命名({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "貼上至 {n} 張照片{:.0} — 只貼上已複製的設定", "Preset: {name}": "預設集:{name}", @@ -329,6 +329,9 @@ "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", + "Add {n} photo{} to “{}”": "將 {n} 張照片加入「{1}」{0:.0}", + "{n} already there": "{n} 張已在其中", + "Add “{keyword}” to {n} photo{}": "將「{keyword}」加入 {n} 張照片{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "規則 {n}/{m}:{what}。用方向鍵移動", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "群組 {n}/{m}:符合{mode},內含 {count} 項。用方向鍵移動", ", rating {} of 5": ",評分:{}/5" diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index d4870219d3..af34d9283f 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "使用「檔案 → 匯入照片…」,或將照片拖放至此", "This row covers more than one disk: drop on a folder inside it": "此列涵蓋多個磁碟:請拖放到其中的資料夾", "Local photos aren't in the library yet: Add to My Photos first, then move them": "本機照片尚未在照片庫中:請先「加入我的照片」,再移動", + "Demo photos have no file on disk, so they can't be moved": "示範照片在磁碟上沒有檔案,因此無法移動", "Add to Selected Photos": "加入選取的照片", "Add to Target Album": "加入目標相簿", "Add to this mask": "加入此遮色片", @@ -2471,6 +2472,14 @@ "Next": "下一步", "Get Started": "開始使用", "Keywords and presets apply to new files only, not to photos already in Local": "關鍵字和預設集僅套用於新檔案,不適用於已在「本機」中的照片", + "Can't add to an album folder": "無法加入相簿資料夾", + "An album folder holds albums, not photos: drop on an album inside it": "相簿資料夾裡放的是相簿,不是照片:請拖到其中的某個相簿上", + "Can't add to a smart album": "無法加入智慧型相簿", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "智慧型相簿的照片由其規則決定:請用「編輯智慧型相簿…」變更規則", + "Add keywords in the Keyword List": "請在關鍵字清單中加入關鍵字", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要替照片加入關鍵字,請使用關鍵字清單(視窗 → 關鍵字,K),把照片拖到那裡的關鍵字上", + "Already on these photos": "這些照片已有", + "Can't go inside itself": "不能放入自身", "Same Content as Another Photo": "與另一張照片內容相同", "Reduce Motion": "減少動態效果", "Reduce motion": "減少動態效果", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5845b2a0be..3994e3a0b0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -70,6 +70,7 @@ impl LightcraftApp { #[cfg(test)] missing_count_test_delay: None, shadow: None, + drawing_offscreen: false, synthetic: vec![], pointer_cleanup: false, drop_hover: vec![], @@ -212,6 +213,9 @@ impl LightcraftApp { // UI passes still counts as changed) self.selection_changes(); let r = self.run_command(id, params); + // the panel a command left on show is noted now, not at the next frame, success or not: the next command + // of the same frame (a script, queued shortcuts) sees it (Close Panel, B, Done = the column stays hidden) + self.ui.note_right(); self.selection_changes(); r } @@ -429,32 +433,48 @@ impl LightcraftApp { panels::slideshow::tick(self, ctx, now); } - /// Announce the end of a Build Previews run. + /// A task waiting in line whose lane freed while nothing was asked starts now (commands start them too); then the + /// run in progress is looked at, so that one started here is polled for its end from this frame on. + pub(crate) fn tick_preview_builds(&mut self, ctx: &egui::Context) { + self.session.start_waiting(); + self.preview_build_status(ctx); + } + + /// Announce the end of a Build Previews run, and of those a build waiting in line replaced before it was announced + /// (in one toast, oldest first). A build is announced once: its `reported` flag says so, not where it lives. fn preview_build_status(&mut self, ctx: &egui::Context) { use std::sync::atomic::Ordering; - let Some(b) = self.session.preview_build.clone() else { return }; - let key = std::sync::Arc::as_ptr(&b) as usize; - if b.finished.load(Ordering::Relaxed) { - if self.ui.preview_build_seen != Some((key, true)) { - self.ui.preview_build_seen = Some((key, true)); - let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); - let plural = if done == 1 { "" } else { "s" }; - let mut msg = match (b.error(), b.what) { - (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), - (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), - (None, what) => { - crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) - } - }; - if failed > 0 { - msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); - } - self.toast(ctx, msg); + let mut ended = self.session.take_unreported_builds(); + match self.session.preview_build.clone() { + Some(b) if b.finished.load(Ordering::Relaxed) => ended.push(b), + Some(_) => { + // The activity stack shows the run while it works; poll for the end. + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } - } else { - // The activity stack shows the run while it works; poll for the end. - ctx.request_repaint_after(std::time::Duration::from_millis(250)); + None => {} } + let msgs: Vec = ended.iter().filter(|b| !b.reported.swap(true, Ordering::Relaxed)).map(|b| Self::build_message(b)).collect(); + if !msgs.is_empty() { + self.toast(ctx, msgs.join("; ")); + } + } + + /// How a finished Build Previews run ended, as the toast words it. + fn build_message(b: &lightcraft_engine::cmd::previews::PreviewBuild) -> String { + use std::sync::atomic::Ordering; + let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); + let plural = if done == 1 { "" } else { "s" }; + let mut msg = match (b.error(), b.what) { + (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), + (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), + (None, what) => { + crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) + } + }; + if failed > 0 { + msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); + } + msg } /// Announce when saving the library starts failing (changes then live only in memory and are @@ -694,6 +714,31 @@ impl LightcraftApp { self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms); } + /// Ends drags that must not go on, before any panel or dialog sees the frame: Esc gives up a + /// drag and is taken, so a dialog open over it doesn't also close; and a drag outlives its + /// button in no layout (full screen and the slideshow don't run the panels that end it). + /// The frame a button is released in is left to the drop targets, except in full screen, which has none. + fn end_drags(&mut self, ctx: &egui::Context) { + if self.drawing_offscreen || !self.ui.drag_active() { + return; + } + let (esc, down, released) = ctx.input(|i| (i.key_pressed(egui::Key::Escape), i.pointer.any_down(), i.pointer.any_released())); + // a release is left to the drop targets, except in full screen, where there are none: the + // drag ends on that frame, so an Esc on the next one can't find it still going + if !esc && (down || (released && !self.ui.fullscreen)) { + return; + } + if esc { + widgets::take_escape(ctx); + } + if self.ui.dragging_album.take().is_some() { + panels::left::forget_hover(self, ctx); + } + self.ui.dragging_photos = None; + self.ui.dragging_section = None; + self.ui.dragging_keyword = None; + } + /// Lay out the whole window: input/setup for the known UI phase, then presentation, then the /// frame bookkeeping. A hidden `run_logic` never reaches this. pub fn ui(&mut self, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 87ad344cb6..9b4e220b85 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -93,7 +93,7 @@ impl LightcraftApp { // after the poll: a lookup that just finished is cleared, so photos queued meanwhile are looked up now crate::lens_db::tick(self); updates_ui::tick(self, ctx); - self.preview_build_status(ctx); + self.tick_preview_builds(ctx); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); @@ -437,8 +437,11 @@ impl LightcraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } self.library_changed(&ctx); + // (a tool panel opened some other way still remembers the panel it took the place of) + self.ui.note_right(); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; + self.end_drags(&ctx); if self.ui.fullscreen { // full-screen preview: the photo alone on black egui::CentralPanel::default() @@ -491,10 +494,13 @@ impl LightcraftApp { panels::activity::show(self, &ctx); export_task::poll_photos(self, &ctx); pick::poll(self, &ctx); - panels::grid::drag_feedback(self, &ctx); - panels::left::album_drag_feedback(self, &ctx); - panels::left::section_drag_feedback(self, &ctx); - panels::keyword_list::drag_feedback(self, &ctx); + // (each ends its drag when the button is up, which an offscreen frame's pointer never is) + if !self.drawing_offscreen { + panels::grid::drag_feedback(self, &ctx); + panels::left::album_drag_feedback(self, &ctx); + panels::left::section_drag_feedback(self, &ctx); + panels::keyword_list::drag_feedback(self, &ctx); + } panels::toast(self, &ctx); drop_overlay::show(self, &ctx); // AppKit moves the window on a drag anywhere in the title-bar band unless the window isn't diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs index 79b4639954..faca642831 100644 --- a/crates/ui-egui/src/app/screenshot.rs +++ b/crates/ui-egui/src/app/screenshot.rs @@ -267,7 +267,9 @@ impl LightcraftApp { // same scroll offsets, open sections, style… as the window let memory = main.memory(|m| m.clone()); view.ctx.memory_mut(|m| *m = memory); + self.drawing_offscreen = true; view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.draw_window(ui)); + self.drawing_offscreen = false; let img = capture.then(|| { let mut tex = self.renderer.cpu_textures(); if let (Some((t, ..)), Some(px)) = (&self.merge.preview, &self.merge.preview_pixels) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6d67ceb1e7..d839284dd4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -158,7 +158,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "export": {"running": app.export.as_ref().map(crate::export_task::ExportTask::status), "last": app.last_export_result}, "import": app.import.as_ref().map(crate::import::ImportTask::status), "tasks": app.tasks.labels(), - // every long-running task in flight, as the activity stack shows them (`activity.list`) + // every long-running task in flight and every task waiting in line (`activity.list`); the stack draws the running ones "activity": app.session.activity.list(), // commands waiting on a native file dialog shown off the UI thread (`pick`) "fileDialogs": app.pending_picks.iter().map(|p| p.command.clone()).collect::>(), @@ -422,10 +422,21 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest } u.collapsed_sidebar.clear(); u.toast = app.ui.toast.clone(); + // the panel a tool panel took the place of, to put back when it closes, survives a ui.set + u.tool_return = app.ui.tool_return; + u.right_seen = app.ui.right_seen; + // (and what a panel toggle replaced, so pressing its key again still puts that back) + u.toggle_return = app.ui.toggle_return.clone(); + u.right_shown_by_f8 = app.ui.right_shown_by_f8; u.dialog = app.ui.dialog.clone(); u.status = app.ui.status.clone(); + let right_changed = u.right != app.ui.right; crate::docking::cancel_replaced_gesture(app, u.docking.as_ref()); app.ui = u; + if right_changed { + // noted now, as a command does: the next request may open a tool before a frame is drawn + app.ui.note_right(); + } crate::i18n::set_language(app.ui.language); ctx.request_repaint(); ok(serde_json::to_value(&app.ui).unwrap_or_default()) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e2f37b666d..7950666896 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1017,7 +1017,8 @@ fn all_metadata_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { for (n, v) in list { ui.label(egui::RichText::new(n).color(t.text_dim)); - ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); + // values (serial numbers, lens names) are copied out of here; the field names are not + ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap().selectable(true)); ui.end_row(); } }); @@ -2002,9 +2003,9 @@ fn delete_effects_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { /// The body of the MovePhotos dialog. fn move_photos_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { - let Dialog::MovePhotos { ids, name, dont_ask, .. } = dlg else { return }; - let n = ids.len(); - ui.label(crate::i18n::tr_format!("Move {n} photo{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); + let Dialog::MovePhotos { name, files, dont_ask, .. } = dlg else { return }; + let n = *files; + ui.label(crate::i18n::tr_format!("Move {n} file{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim)); ui.add_space(4.0); let c = ui.checkbox(dont_ask, crate::i18n::tr("Don't ask again")); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8a20293c11..6542dbe097 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -240,6 +240,9 @@ pub struct LightcraftApp { pub(crate) missing_count_test_delay: Option, /// Offscreen context for headless screenshots of the windowed app. shadow: Option, + /// The frame being laid out is the offscreen one of a headless screenshot: it has no pointer of + /// its own, so it must not end a drag the window's pointer is still holding. + drawing_offscreen: bool, /// Synthetic input events (from the control channel) injected one step per frame. pub synthetic: Vec, /// A gesture was canceled after its synthetic pointer press reached egui. The next diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 1c7675f754..3962137cfc 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -3,19 +3,25 @@ use super::ui_commands::{UI_COMMANDS, language_from_command}; use super::{BeforeAfter, Dialog, LightcraftApp, PickRequest, Picked, RightPanel, Value, ViewMode, Zoom, json, thumb_size_view}; fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) { - if app.ui.right == p && crate::docking::exposed(app, crate::docking::Panel::Tools) { - app.ui.right = RightPanel::None; + // toggled off: back to exactly what the right column showed before (in the same frame: no flash, no jump), + // closed when it was closed (note 21) + let exposed = crate::docking::exposed(app, crate::docking::Panel::Tools); + let tool_before = app.ui.tool.clone(); + let on = app.ui.toggle_panel(p, exposed); + // toggled off: the panel put back brings its own tool back (Masking's Brush, Remove's Heal or Clone) + let tool_restored = !on && app.ui.tool != tool_before; + if !on { app.toast(ctx, crate::i18n::tr_format!("{name} Off", name = crate::i18n::tr(name))); } else { - app.ui.right = p; app.toast(ctx, crate::i18n::tr_format!("{name} On", name = crate::i18n::tr(name))); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; } } - if p != RightPanel::Masking && app.ui.tool != "wbPicker" { + if !tool_restored && p != RightPanel::Masking && app.ui.tool != "wbPicker" { app.ui.tool.clear(); } + app.ui.note_right(); let _ = app.session.end_interaction(); } @@ -643,6 +649,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va if app.ui.right != RightPanel::None && crate::docking::exposed(app, crate::docking::Panel::Tools) { app.ui.right_hidden = app.ui.right; app.ui.right = RightPanel::None; + // noted now, not at the frame's end: a command after it in the same frame (a batch of control + // requests) opens a tool on the hidden column, not on the panel F8 hid + app.ui.note_right(); if app.ui.tool != "wbPicker" { app.ui.tool.clear(); } @@ -653,6 +662,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va p => p, }; app.ui.right = p; + // (a tool shown again this way still closes to the panel before it; noted now, as for hiding) + app.ui.right_shown_by_f8 = Some(p); + app.ui.note_right(); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; } @@ -1050,7 +1062,7 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(Value::Null) } "tool.done" => { - // Return commits a tool panel (crop, remove, red eye, masking): back to Edit + // Return commits a tool panel (crop, remove, red eye, masking): back to the panel before it use RightPanel::*; if app.ui.dialog.is_none() && matches!(app.ui.right, Crop | Remove | RedEye | Masking) { if app.ui.right == Crop { @@ -1058,7 +1070,8 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val } let _ = app.session.end_interaction(); app.ui.tool.clear(); - app.ui.right = Edit; + // back to the panel shown before the tool (hidden if it was) + app.ui.right = app.ui.leave_tool(); } Ok(Value::Null) } diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index c8398ca5c8..5d5128977c 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -55,7 +55,8 @@ fn detail_line(t: &TaskInfo) -> String { /// Draw the stack (called every frame, after the panels and dialogs). pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { - let all = app.session.activity.list(); + // (a task waiting in line has nothing to show yet and no progress to draw: agents see it in `activity.list`) + let all: Vec = app.session.activity.list().into_iter().filter(|t| !t.waiting).collect(); if all.is_empty() { app.activity_expanded = false; return; diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 39f6c7f6d6..57f4208e22 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1115,6 +1115,17 @@ pub fn drag_hint(ctx: &egui::Context, text: String) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique("drag-photos-hint"), (frame, text))); } +/// What a drop target that refuses the dragged photos does: the label says so, the cursor shows +/// it, and a release there toasts `why` and ends the drag, changing nothing. +pub fn refuse_drop(app: &mut LightcraftApp, ctx: &egui::Context, hint: String, why: &str, released: bool) { + drag_hint(ctx, hint); + ctx.set_cursor_icon(egui::CursorIcon::NotAllowed); + if released { + app.toast(ctx, why); + app.ui.dragging_photos = None; + } +} + pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(ids) = &app.ui.dragging_photos else { return }; let (released, down, pos) = ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos())); @@ -1125,7 +1136,10 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(pos) = pos else { return }; let t = Tokens::get(ctx); let n = ids.len(); - ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + // (a row that refuses them has set the not-allowed cursor this frame: it stays) + if ctx.output(|o| o.cursor_icon) != egui::CursorIcon::NotAllowed { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } // a drop target under the pointer says where they would go (only this frame's) let frame = ctx.cumulative_frame_nr(); let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text); diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 2da58c594a..026c10fd7f 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -115,21 +115,28 @@ fn shown_under(ui: &egui::Ui, rect: Rect, pointer: Option) -> bool { crate::docking::drop_target(ui, rect, pointer) } +/// What the dragged keyword's label says this frame instead of its name (a row refusing it sets it). +const KEYWORD_HINT: &str = "drag-keyword-hint"; + /// A keyword being dragged, each frame (after the panels, which take the drop): its name follows /// the pointer, and the drag ends with the button's release wherever it is (the list may be gone -/// by then) or with Esc. +/// by then). Esc ends it earlier in the frame (`LightcraftApp::end_drags`). pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(keyword) = app.ui.dragging_keyword.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 { + let (released, down, at) = ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos())); + if released || !down { app.ui.dragging_keyword = None; return; } let Some(at) = at else { return }; let t = Tokens::get(ctx); - ctx.set_cursor_icon(egui::CursorIcon::Grabbing); - let name = keyword.rsplit('|').next().unwrap_or(&keyword).to_string(); + // (a row that refuses it has set the not-allowed cursor this frame: it stays) + if ctx.output(|o| o.cursor_icon) != egui::CursorIcon::NotAllowed { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } + let frame = ctx.cumulative_frame_nr(); + let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique(KEYWORD_HINT))).filter(|(f, _)| *f == frame).map(|(_, text)| text); + let name = hint.unwrap_or_else(|| keyword.rsplit('|').next().unwrap_or(&keyword).to_string()); egui::Area::new(egui::Id::unique("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( ctx, |ui| { @@ -326,9 +333,16 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, path: &st return; } let t = Tokens::get(ui.ctx()); - let outline = |ui: &egui::Ui| ui.painter().rect_stroke(rect.shrink2(vec2(16.0, 1.0)), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + let outline = |ui: &egui::Ui| { + ui.painter().rect_stroke(rect.shrink2(vec2(16.0, 1.0)), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + }; if let Some(k) = app.ui.dragging_keyword.clone() { if lightcraft_catalog::keywords::is_under(path, &k) { + // never inside itself or what is inside it: the not-allowed cursor, and the dragged + // label says why; a release does nothing + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(KEYWORD_HINT), (frame, crate::i18n::tr("Can't go inside itself").to_string()))); return; } outline(ui); @@ -336,30 +350,44 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, path: &st drop_keyword(app, ui.ctx(), &k, Some(path)); } } else if let Some(ids) = app.ui.dragging_photos.clone() { - outline(ui); + drop_photos_on_keyword(app, ui, &ids, path, &outline); + } +} + +/// Photos dragged over the keyword row `path`: only the photos that don't have it get it. `outline` +/// marks the row when a release would give it to some. +fn drop_photos_on_keyword(app: &mut LightcraftApp, ui: &mut egui::Ui, ids: &[u64], path: &str, outline: &dyn Fn(&egui::Ui)) { + // (photos drop on the primary's release only, like the album and folder rows) + let released = ui.input(|i| i.pointer.primary_released()); + let lacking = |id: &u64| { + app.session.catalog.photo(PhotoId(*id)).is_some_and(|p| !p.meta.keywords.iter().any(|k| same(&lightcraft_catalog::keywords::clean(k), path))) + }; + let n = ids.iter().filter(|id| lacking(id)).count(); + if n == 0 { + super::grid::drag_hint(ui.ctx(), crate::i18n::tr("Already on these photos").to_string()); if released { - // only the photos that didn't have it get it - let lacking = |id: &u64| { - app.session - .catalog - .photo(PhotoId(*id)) - .is_some_and(|p| !p.meta.keywords.iter().any(|k| same(&lightcraft_catalog::keywords::clean(k), path))) - }; - let n = ids.iter().filter(|id| lacking(id)).count(); app.ui.dragging_photos = None; - match app.run("photo.setMeta", json!({"ids": ids, "addKeywords": [path]})) { - Ok(_) => app.toast( - ui.ctx(), - crate::i18n::tr_format!( - "Added “{keyword}” to {n} photo{}", - if n == 1 { "" } else { "s" }, - keyword = path.replace('|', " › "), - n = n - ), - ), - Err(e) => app.toast(ui.ctx(), e), - } } + return; + } + let keyword = path.replace('|', " › "); + super::grid::drag_hint( + ui.ctx(), + crate::i18n::tr_format!("Add “{keyword}” to {n} photo{}", if n == 1 { "" } else { "s" }, keyword = keyword, n = n), + ); + outline(ui); + if released { + app.ui.dragging_photos = None; + give_keyword(app, ui.ctx(), ids, path, n); + } +} + +/// Gives the keyword `path` to the dragged photos and toasts how many (`n`) lacked it. +fn give_keyword(app: &mut LightcraftApp, ctx: &egui::Context, ids: &[u64], path: &str, n: usize) { + let keyword = path.replace('|', " › "); + match app.run("photo.setMeta", json!({"ids": ids, "addKeywords": [path]})) { + Ok(_) => app.toast(ctx, crate::i18n::tr_format!("Added “{keyword}” to {n} photo{}", if n == 1 { "" } else { "s" }, keyword = keyword, n = n)), + Err(e) => app.toast(ctx, e), } } diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index d4f5f2e6e6..c2cf2a71fd 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -21,6 +21,7 @@ mod sections; use albums::albums_rows; pub(crate) use albums::drag_auto_scroll; +pub(crate) use albums::forget_hover; pub use albums::{album_drag_feedback, auto_scroll_speed}; pub(crate) use dates::browse_all_photos; use dates::date_rows; diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 11bda7fc5a..b3c3bf38e1 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -52,6 +52,13 @@ fn albums_tree( if album_drag_over(app, ui, &resp, a, has_children.then_some(&mut open), indent) { set_tree_open(ui, open_id, true); } + refuse_photos( + app, + ui, + &resp, + crate::i18n::tr("Can't add to an album folder"), + crate::i18n::tr("An album folder holds albums, not photos: drop on an album inside it"), + ); // what this frame draws; a click shows from the next one let draw_open = open; let mut toggled = false; @@ -95,7 +102,15 @@ fn albums_tree( app.ui.dragging_album = Some(a.id.0); } album_drag_over(app, ui, &resp, a, None, indent); - if !a.is_smart() { + if a.is_smart() { + refuse_photos( + app, + ui, + &resp, + crate::i18n::tr("Can't add to a smart album"), + crate::i18n::tr("A smart album's rules choose its photos: change them with Edit Smart Album…"), + ); + } else { drop_target(app, ui, &resp, a); } if let Some(rules) = &a.smart { @@ -211,7 +226,7 @@ fn finish_drop(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, result: } /// Forgets how long the pointer rested on each folder (a new drag starts counting again). -fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { +pub(crate) fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { let ids: Vec = app.session.catalog.albums().filter(|a| a.folder).map(|a| a.id.0).collect(); ctx.data_mut(|d| { for id in ids { @@ -362,9 +377,8 @@ pub(super) fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, /// button is up (the drop targets act on the release frame, before this runs). pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(id) = app.ui.dragging_album else { return }; - let (released, down, pos, esc) = - ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); - if released || !down || esc { + let (released, down, pos) = ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos())); + if released || !down { app.ui.dragging_album = None; forget_hover(app, ctx); return; @@ -382,8 +396,45 @@ pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { ); } -/// An album row while photos are dragged from the grid: highlighted under the pointer; a -/// release there adds them. +/// A row that can't hold photos, while photos are dragged from the grid: the not-allowed cursor +/// and a label saying so (`hint`); a release there says why (`why`) and changes nothing. +pub(super) fn refuse_photos(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, hint: &str, why: &str) { + if app.ui.dragging_photos.is_none() || !pointer_over_row(ui, resp.rect) { + return; + } + let released = ui.input(|i| i.pointer.primary_released()); + crate::panels::grid::refuse_drop(app, ui.ctx(), hint.to_string(), why, released); +} + +/// How many of the dragged photos are library photos, and how many of those the album holds already. +fn dragged_and_there(app: &LightcraftApp, a: &Album, ids: &[u64]) -> (usize, usize) { + let library = ids.iter().filter(|id| app.session.catalog.photo(lightcraft_catalog::PhotoId(**id)).is_some_and(|p| !p.local)).count(); + let dragged: std::collections::HashSet = ids.iter().copied().collect(); + (library, a.photos.iter().filter(|p| dragged.contains(&p.0)).count().min(library)) +} + +/// A drop on album `a` that would add nothing: `local` Local photos in the drag aren't in the album +/// either, so a release says why they stay out; else the library photos are all there already, and a +/// release only ends the drag. +fn drop_adds_nothing(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, local: usize, released: bool) { + if local > 0 { + let why = crate::i18n::tr_format!( + "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)", + if local == 1 { "" } else { "s" }, + n = local + ); + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::panels::grid::albums_hint(), &why, released); + return; + } + crate::panels::grid::drag_hint(ui.ctx(), crate::i18n::tr_format!("Already in “{}”", a.name)); + if released { + app.ui.dragging_photos = None; + } +} + +/// An album row while photos are dragged from the grid: highlighted under the pointer, the dragged +/// label saying how many photos a release there adds (the ones the album doesn't hold yet). When it +/// holds them all it says so, and a release does nothing. fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, a: &Album) { let Some(ids) = app.ui.dragging_photos.clone() else { return }; // only where the row can be seen: not scrolled out of the sidebar or beneath the pinned header @@ -396,37 +447,48 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response // light up, and a release says why let photos: Vec = ids.iter().map(|id| lightcraft_catalog::PhotoId(*id)).collect(); if crate::panels::grid::local_only(app, &photos) { - ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); - if released { - app.toast(ui.ctx(), crate::panels::grid::albums_hint()); - app.ui.dragging_photos = None; - } + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::panels::grid::albums_hint(), &crate::panels::grid::albums_hint(), released); return; } + // of the library photos dragged, the album holds some already + let (library, there) = dragged_and_there(app, a, &ids); + let fresh = library.saturating_sub(there); + if fresh == 0 { + drop_adds_nothing(app, ui, a, ids.len() - library, released); + return; + } + crate::panels::grid::drag_hint( + ui.ctx(), + crate::i18n::tr_format!("Add {n} photo{} to “{}”", if fresh == 1 { "" } else { "s" }, a.name, n = fresh), + ); let t = Tokens::get(ui.ctx()); ui.painter().rect_stroke(resp.rect.shrink2(vec2(8.0, 1.0)), 4.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); if released { - drop_photos_on_album(app, ui, a, ids); + drop_photos_on_album(app, ui, a, ids, there); app.ui.dragging_photos = None; } } /// Adds the dragged photos to the album and toasts how many went in (and how many Local ones were skipped). -fn drop_photos_on_album(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, ids: Vec) { +fn drop_photos_on_album(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, ids: Vec, there: usize) { match app.run("album.addPhotos", json!({"id": a.id.0, "ids": ids})) { Ok(r) => { let name = crate::destination::album(&app.session.catalog, a); - app.toast(ui.ctx(), added_message(&name, &r)); + app.toast(ui.ctx(), added_message(&name, &r, there)); } Err(e) => app.toast(ui.ctx(), e), } } -/// "Added N photos to “album”", plus a note when Local photos were skipped. -fn added_message(name: &str, r: &serde_json::Value) -> String { +/// "Added N photos to “album”", plus a note when some were there already and when Local photos were skipped. +fn added_message(name: &str, r: &serde_json::Value, there: usize) -> String { let n = r.get("added").and_then(serde_json::Value::as_u64).unwrap_or(0); let skipped = r.get("skipped").and_then(serde_json::Value::as_u64).unwrap_or(0); let mut msg = crate::i18n::tr_format!("Added {n} photo{} to “{}”", if n == 1 { "" } else { "s" }, name, n = n); + if there > 0 { + msg.push_str(" · "); + msg.push_str(&crate::i18n::tr_format!("{n} already there", n = there)); + } if skipped > 0 { msg.push_str(" · "); msg.push_str(&skipped_note(skipped)); diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index bf19804d19..60fa3df3ad 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -368,6 +368,26 @@ fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &s /// can be reached. const SPRING_OPEN_SECONDS: f64 = 0.7; +/// Whether the photo's file is directly in the folder `folder`. +fn is_in_folder(p: &lightcraft_catalog::Photo, folder: &str) -> bool { + match &p.source { + lightcraft_catalog::Source::File { path } => std::path::Path::new(path).parent().is_some_and(|d| same_folder(&d.to_string_lossy(), folder)), + _ => false, + } +} + +/// How many files a drop of `photos` on `folder` moves (`photo.moveToFolder`): the photos already +/// there stay, and virtual copies of one file move it once. +fn files_moved(photos: &[&std::sync::Arc], folder: &str) -> usize { + let mut paths = std::collections::HashSet::new(); + for p in photos.iter().filter(|p| !is_in_folder(p, folder)) { + if let lightcraft_catalog::Source::File { path } = &p.source { + paths.insert(path.as_str()); + } + } + paths.len() +} + /// A Folders row while photos are dragged from the grid: a release moves their files there on /// disk (`photo.moveToFolder`, one undo step). The row lights up and the dragged label says where /// they will go, as the same gesture onto an album only adds them to it. Held over a closed row, @@ -387,30 +407,25 @@ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::R Some(crate::i18n::tr("This row covers more than one disk: drop on a folder inside it")) } else if photos.iter().any(|p| p.local) { Some(crate::i18n::tr("Local photos aren't in the library yet: Add to My Photos first, then move them")) + } else if photos.iter().any(|p| !matches!(p.source, lightcraft_catalog::Source::File { .. })) { + // `photo.moveToFolder` refuses a photo with no file + Some(crate::i18n::tr("Demo photos have no file on disk, so they can't be moved")) } else { None }; - let here = |p: &lightcraft_catalog::Photo| match &p.source { - lightcraft_catalog::Source::File { path } => std::path::Path::new(path).parent().is_some_and(|d| same_folder(&d.to_string_lossy(), &n.path)), - _ => false, - }; - let all_here = !photos.is_empty() && photos.iter().all(|p| here(p)); - let count = photos.len(); + let count = files_moved(&photos, &n.path); + let all_here = !photos.is_empty() && photos.iter().all(|p| is_in_folder(p, &n.path)); let released = ui.input(|i| i.pointer.primary_released()); - let hint = match (&refused, all_here) { - (Some(_), _) => crate::i18n::tr("Can't be moved here").to_string(), - (None, true) => crate::i18n::tr_format!("Already in “{}”", name), - (None, false) => crate::i18n::tr_format!("Move {n} photo{} to “{}”", if count == 1 { "" } else { "s" }, name, n = count), - }; - crate::panels::grid::drag_hint(ui.ctx(), hint); if let Some(why) = refused { - ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); - if released { - app.toast(ui.ctx(), why); - app.ui.dragging_photos = None; - } + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::i18n::tr("Can't be moved here").to_string(), why, released); return; } + let hint = if all_here { + crate::i18n::tr_format!("Already in “{}”", name) + } else { + crate::i18n::tr_format!("Move {n} file{} to “{}”", if count == 1 { "" } else { "s" }, name, n = count) + }; + crate::panels::grid::drag_hint(ui.ctx(), hint); if all_here { if released { app.ui.dragging_photos = None; @@ -425,7 +440,7 @@ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::R // said not to; the menu's Move Selected Photos Here is asked for by name and goes at once if app.ui.settings.ask_before_move { let library = app.session.library_generation(); - app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, dont_ask: false, library }); + app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, files: count, dont_ask: false, library }); } else { move_photos_here(app, ui.ctx(), Some(&ids), &n.path, &name); } @@ -481,7 +496,7 @@ pub(crate) fn moved_text(n: u64, name: &str) -> String { if n == 0 { crate::i18n::tr_format!("Already in “{}”", name) } else { - crate::i18n::tr_format!("Moved {n} photo{} to “{}”. Edit → Undo moves them back.", if n == 1 { "" } else { "s" }, name, n = n) + crate::i18n::tr_format!("Moved {n} file{} to “{}”. Edit → Undo moves them back.", if n == 1 { "" } else { "s" }, name, n = n) } } diff --git a/crates/ui-egui/src/panels/left/keywords.rs b/crates/ui-egui/src/panels/left/keywords.rs index d2998e504e..72190166b5 100644 --- a/crates/ui-egui/src/panels/left/keywords.rs +++ b/crates/ui-egui/src/panels/left/keywords.rs @@ -1,3 +1,4 @@ +use super::albums::refuse_photos; use super::dates::browse_all_photos; use super::rows::{INDENT_STEP, Inside, Row, Said, out_of_sight, tree_inside, tree_open, tree_toggle}; use super::{Icon, KeywordNode, LightcraftApp, json}; @@ -24,6 +25,13 @@ pub(super) fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[ fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: &str, indent: f32, open_id: Option, open: &mut bool) { let sel = app.session.filter.keyword.as_deref().is_some_and(|k| k.eq_ignore_ascii_case(&n.path)); let resp = Row::new(id, Icon::Tag, &n.name).count(Some(n.count)).selected(sel).indent(indent).show(app, ui); + refuse_photos( + app, + ui, + &resp, + crate::i18n::tr("Add keywords in the Keyword List"), + crate::i18n::tr("Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there"), + ); if let Some(k) = open_id { // (no keyword inside it has keywords of its own: there is nothing inside it to say of) let inside = if n.children.iter().any(|c| !c.children.is_empty()) { Inside::OpensAndFolds } else { Inside::Alone }; diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index 1704a64266..5ebef57e4f 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -123,13 +123,7 @@ pub(crate) fn section_drop_before(placed: &[PlacedSection], y: f32) -> Option (&'static str, RightPanel) { + ("right-scroll", panel) +} + pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); @@ -45,7 +51,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if app.ui.right == RightPanel::Keywords { // (without a selection there is no Add keyword box for Add Keywords to put the cursor in) app.ui.focus_keywords = None; - egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt(scroll_salt(RightPanel::Keywords)).auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; if fold_header(app, ui, "keywording", "Keywords") { padded(ui, |ui| { @@ -70,7 +76,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = 0.0; super::edit::histogram(app, ui, id); } - let mut area = egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]); + // each panel keeps its own scroll position: Edit is where it was after Masking or Crop + let mut area = egui::ScrollArea::vertical().id_salt(scroll_salt(app.ui.right)).auto_shrink([false, false]); if let Some(offset) = held { area = area.vertical_scroll_offset(offset); } diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index 5810a0f272..5fbba25698 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -102,7 +102,8 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { lightcraft_catalog::Source::File { path } => path.clone(), lightcraft_catalog::Source::Demo { .. } => crate::i18n::tr("Generated demo photo").into(), }; - ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate()); + // Selectable so the source path can still be copied (#1885 turned plain labels off). + ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate().selectable(true)); if crate::menus::ui_enabled(app, "app.showInFinder") { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoReveal", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) diff --git a/crates/ui-egui/src/panels/right/tests.rs b/crates/ui-egui/src/panels/right/tests.rs index 1f1d60d609..2085f7300e 100644 --- a/crates/ui-egui/src/panels/right/tests.rs +++ b/crates/ui-egui/src/panels/right/tests.rs @@ -30,3 +30,61 @@ fn short_times() { assert_eq!(super::short_time("2026-09-30T12:00:05"), "Sep 30, 2026, 12:00 PM"); assert_eq!(super::short_time("2026-01-02"), "Jan 2, 2026"); } + +// Feature: the Keywords panel keeps its scroll position when a photo is selected (CodeRabbit on #3031: the +// no-selection list scrolled under another id) +#[test] +fn the_keywords_panel_scrolls_under_one_id_with_or_without_a_selection() { + use crate::state::RightPanel; + // (`show` names the no-selection list's scroll area by `scroll_salt(RightPanel::Keywords)`, as it names the + // panel's with a selection by `scroll_salt(app.ui.right)`) + assert_eq!(super::scroll_salt(RightPanel::Keywords), ("right-scroll", RightPanel::Keywords)); + assert_ne!(super::scroll_salt(RightPanel::Keywords), super::scroll_salt(RightPanel::Edit), "each panel keeps its own"); +} + +// The Keywords panel scrolled with no photo selected is the same scroll area as with one: the offset it was left at +// is there when a photo is selected (CodeRabbit on #3031) +#[test] +fn the_keywords_panel_keeps_its_offset_from_no_selection_to_a_selection() { + use crate::headless::Headless; + use serde_json::json; + use std::time::Duration; + const T: Duration = Duration::from_secs(20); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 420.0], 1.0); + // a Keyword List longer than the panel + for i in 0..80 { + h.app.session.execute("keyword.create", &json!({"name": format!("keyword {i:02}")})).unwrap(); + } + let r = h.request("ui.set", json!({"view": "detail", "right": "keywords"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + // with a selection: the panel's scroll area (as the panel records it) + let area = h.view.ctx.data(|d| d.get_temp::(egui::Id::unique(super::AREA))).expect("the panel's scroll area"); + let offset = |h: &Headless| egui::scroll_area::State::load(&h.view.ctx, area).map_or(0.0, |s| s.clamped_offset().y); + assert_eq!(offset(&h), 0.0); + // no selection: the list scrolled down + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": []}}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..4 { + h.step(); + } + assert!(h.app.session.active().is_none()); + let panel = h.app.widgets.iter().find(|(w, _)| w == "panel:right_panel").map(|(_, r)| *r).expect("the right panel"); + h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T); + let r = h.request("ui.scroll", json!({"dy": -300.0}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + h.step(); + } + let scrolled = offset(&h); + assert!(scrolled > 50.0, "the no-selection list scrolls the panel's own area: {scrolled}"); + // a photo selected: the area keeps the offset (moved down only by the Keywords box put above the list) + let id = h.app.session.visible_cloned()[0]; + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [id.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..10 { + h.step(); + } + assert!(offset(&h) >= scrolled - 0.5, "the offset is kept: {} after {scrolled}", offset(&h)); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 9ab12fe079..00237c1482 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -431,6 +431,9 @@ fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context) -> (Vec, V let popup_open = egui::Popup::is_any_open(ctx); // Esc that just took a text field's focus away (it gives back the field's text) does nothing else let popup_open = popup_open || app.text_focus; + // a drag in progress: Esc gives it up (`LightcraftApp::end_drags`) and does nothing else, even when no + // button is down any more (a hidden pass can take the release before `end_drags` sees it) + let popup_open = popup_open || app.ui.drag_active(); ctx.input(|i| { // Enter opens the active grid photo; widgets, popups and custom bindings keep the key. if grid diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3c45ab474f..ac1cab1b2c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -33,9 +33,6 @@ pub struct UiState { pub docking_version: u32, #[serde(default = "crate::i18n::default_language")] pub language: crate::i18n::Locale, - /// The Build Previews run last announced (its identity, finished?). - #[serde(skip)] - pub preview_build_seen: Option<(usize, bool)>, /// Saving the library is failing (announced with a toast; the top bar shows a warning until /// a later save succeeds). #[serde(skip)] @@ -50,6 +47,26 @@ pub struct UiState { /// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again. #[serde(skip)] pub right_hidden: RightPanel, + /// The panel F8 just showed again, until [`UiState::note_right`] sees it: a tool coming back this way still closes + /// to the panel before it, while a tool opened any other way on a hidden column closes to the hidden column. + #[serde(skip)] + pub right_shown_by_f8: Option, + /// The panel on show before a tool panel ([`RightPanel::is_tool`]) took its place, put back + /// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden). + #[serde(skip)] + pub tool_return: Option, + /// The panels toggles (a panel key or button: I, M, R, Q…) opened, each with what the right column showed before + /// it and that one's [`UiState::tool_return`], the latest last: toggling the panel on show off puts back exactly + /// that, closed included (test notes 2026-10-24 note 21), and the one below it is then on show with its own + /// record (Edit → I → K → K → I = Edit). Forgotten once another panel is shown (not when F8 hides the panel and + /// shows it again). At most [`TOGGLE_HISTORY`] deep. + #[serde(skip)] + /// Each record also holds the on-canvas tool of the panel it replaced (Masking's Brush, Remove's Heal or Clone), + /// put back with that panel (`None`: a tool opened by a command, which leaves the tool as it is). + pub toggle_return: Vec<(RightPanel, RightPanel, Option, Option)>, + /// The panel [`UiState::note_right`] last saw. + #[serde(skip)] + pub right_seen: RightPanel, /// Widths of the left sidebar and of the right panel in points (dragging their inner edge /// resizes them; within [`LEFT_WIDTH`] / [`RIGHT_WIDTH`]). pub left_width: f32, @@ -390,6 +407,112 @@ pub struct UiState { pub print: crate::print_view::PrintUi, } +/// How many panel toggles [`UiState::toggle_return`] remembers (pressing I and K in turn would grow it without end). +pub const TOGGLE_HISTORY: usize = 16; + +impl UiState { + /// Notes the panel on show: a tool panel opened from another panel (or from none) remembers + /// that one, to put it back when the tool closes; any other panel forgets it. + pub fn note_right(&mut self) { + self.note_right_from(None); + } + + /// [`UiState::note_right`], told which panel a toggle ([`UiState::toggle_panel`]) just opened (its record is + /// on the history already). + fn note_right_from(&mut self, toggled: Option) { + let shown_by_f8 = self.right_shown_by_f8.take(); + if self.right == self.right_seen { + return; + } + // F8 showing a tool it hid: the panel before that tool still holds (`None` is F8's hidden column, not + // what the tool came from). A tool opened another way on the hidden column came from the hidden column. + let back_from_f8 = self.right_seen == RightPanel::None && shown_by_f8 == Some(self.right); + // A tool opened by a command, not a toggle (B, a mask tool from Crop…), is recorded like a toggle: closing + // it shows exactly what the column showed before (Info → Crop → B → Done = Crop), and the records below it + // stay (Crop closed = Info, I = Edit). That holds when the history already ends with this tool: F8 hiding it + // kept its record, and opening it again by a command on the hidden column (Info → Remove → F8 → Visualize + // Spots) closes it back to the hidden column, not to Info. + let opened_directly = self.right.is_tool() && !back_from_f8 && toggled != Some(self.right); + if opened_directly { + if self.toggle_return.len() >= TOGGLE_HISTORY { + self.toggle_return.remove(0); + } + self.toggle_return.push((self.right, self.right_seen, self.tool_return, None)); + } + // F8 hiding the panel a toggle opened keeps its record, for F8 showing it again + let f8_hid = |opened: RightPanel| self.right == RightPanel::None && self.right_hidden == opened; + if !opened_directly && self.toggle_return.last().is_some_and(|&(opened, ..)| opened != self.right && !f8_hid(opened)) { + self.toggle_return.clear(); + } + if self.right.is_tool() { + if !self.right_seen.is_tool() && !back_from_f8 { + self.tool_return = Some(self.right_seen); + } + } else if !(self.right == RightPanel::None && self.right_seen.is_tool() && self.right_hidden == self.right_seen) { + // any panel but F8 hiding the tool on show forgets it + self.tool_return = None; + } + self.right_seen = self.right; + } + + /// The panel to show when the tool panel on show closes: the one shown before it, or none + /// when the panel was hidden (Edit when nothing is known). + pub fn leave_tool(&mut self) -> RightPanel { + self.note_right(); + if let Some(back) = self.untoggle() { + return back; + } + let back = self.tool_return.take().unwrap_or(RightPanel::Edit); + if back.is_tool() { RightPanel::Edit } else { back } + } + + /// A panel toggle (`panel.info`, `panel.masking`…) for `p`: when `p` is on show (`exposed`: not hidden behind + /// another dock tab) it goes and the right column shows exactly what it showed before the toggle opened it, or + /// stays closed when it was (note 21); otherwise `p` comes up and what was there is remembered. Returns whether + /// `p` is now on. + pub fn toggle_panel(&mut self, p: RightPanel, exposed: bool) -> bool { + self.note_right(); + if self.right == p && exposed { + self.right = match self.untoggle() { + Some(back) => back, + None if p.is_tool() => self.leave_tool(), + None => RightPanel::None, + }; + self.note_right(); + false + } else { + // (a column hidden behind another dock tab comes back hidden, with no on-canvas tool: what it held + // wasn't on show) + let saved = + if exposed { (p, self.right, self.tool_return, Some(self.tool.clone())) } else { (p, RightPanel::None, self.tool_return, None) }; + if self.toggle_return.len() >= TOGGLE_HISTORY { + self.toggle_return.remove(0); + } + // (on the history before `note_right` sees `p`: the panel it replaced keeps its own record below it) + self.toggle_return.push(saved); + self.right = p; + self.note_right_from(Some(p)); + true + } + } + + /// What the toggle that opened the panel on show replaced (see [`UiState::toggle_panel`]), with its own tool + /// memory and on-canvas tool put back, or `None` when that panel wasn't opened by a toggle. + fn untoggle(&mut self) -> Option { + let &(opened, before, tool_return, _) = self.toggle_return.last()?; + if opened != self.right { + return None; + } + if let Some((.., Some(tool))) = self.toggle_return.pop() { + self.tool = tool; + } + self.tool_return = tool_return; + // seen already: `note_right` must not take the panel being left for the one this came back from + self.right_seen = before; + Some(before) + } +} + impl Default for UiState { /// Initialize the library and import review sizes as independent app preferences. fn default() -> Self { @@ -398,7 +521,6 @@ impl Default for UiState { docking: None, docking_version: crate::docking::DOCKING_VERSION, language: crate::i18n::default_language(), - preview_build_seen: None, unsaved_seen: false, frame_rate: std::env::var("LIGHTCRAFT_FPS").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")), luminance_map_restore: None, @@ -408,6 +530,10 @@ impl Default for UiState { right_width: RIGHT_WIDTH.default, right: RightPanel::Edit, right_hidden: RightPanel::None, + tool_return: None, + toggle_return: Vec::new(), + right_shown_by_f8: None, + right_seen: RightPanel::Edit, presets: false, preset_thumbs: false, filmstrip: true, @@ -545,6 +671,11 @@ impl Default for UiState { } impl UiState { + /// Whether photos, an album, a sidebar section or a keyword are being dragged. + pub fn drag_active(&self) -> bool { + self.dragging_photos.is_some() || self.dragging_album.is_some() || self.dragging_section.is_some() || self.dragging_keyword.is_some() + } + /// Which colour grading wheels (shadows, midtones, highlights) are hidden for viewing `photo`. pub fn grading_hidden_for(&self, photo: lightcraft_catalog::PhotoId) -> [bool; 3] { match self.grading_hidden { diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index e589c9dd35..4891d6bdf0 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -341,6 +341,9 @@ pub enum Dialog { ids: Vec, folder: String, name: String, + /// How many files the move touches (the drag label's count, `files_moved`): photos + /// already in the folder stay, and virtual copies of one file move it once. + files: usize, dont_ask: bool, /// The library the photos were dropped in (`Session::library_generation`): ids are /// numbered per library, so in another one they name other photos. diff --git a/crates/ui-egui/src/state/view.rs b/crates/ui-egui/src/state/view.rs index 976f1b44e4..864fd7cd8f 100644 --- a/crates/ui-egui/src/state/view.rs +++ b/crates/ui-egui/src/state/view.rs @@ -19,7 +19,7 @@ pub enum ViewMode { } /// The right-hand tool/panel shown next to the tool strip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum RightPanel { #[default] @@ -40,6 +40,12 @@ pub enum RightPanel { } impl RightPanel { + /// A tool that takes the panel's place while it is used (Crop, Remove, Masking, Red Eye): on + /// closing, the panel shown before it comes back ([`UiState::leave_tool`]). + pub fn is_tool(self) -> bool { + matches!(self, RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) + } + pub fn is_edit_tool(self) -> bool { matches!(self, RightPanel::Edit | RightPanel::Profiles | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 3576500e4d..9f1eb5019e 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -41,6 +41,7 @@ mod dialog_tab; mod dialogs; mod disk_space; mod docking_acceptance; +mod drag_contract; mod drop_import; mod edit_layout; mod empty_library; @@ -85,6 +86,7 @@ mod mode_dropdowns; mod move_folder; mod offline; mod open_lightroom; +mod panel_restore; pub(super) mod panels; mod preset_favorites; mod preset_import; diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index bdeaccf4e9..a7d7afc069 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -110,6 +110,9 @@ fn count_text_by_unit() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; assert_eq!(count_text(&t), "3 of 25"); (t.done, t.total, t.unit) = (12 * 1_048_576, 340 * 1_048_576, Unit::Bytes); @@ -591,3 +594,92 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.run("library.compact", json!({})).is_err()); assert!(h.app.ui.toast.is_none()); } + +/// Given a preview build running and another waiting in line behind it, then the stack shows the running build only, +/// and the waiting one starts by itself, in a frame, when the build ahead of it ends. +#[test] +fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let build = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(build.clone()); + let running = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + let queued = h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + let waiting = queued["queued"].as_u64().expect("it waits"); + assert_eq!(h.app.session.activity.list().len(), 2); + wait_visible(&mut h); + assert!(has(&h, &format!("activity:row:{}", running.id()))); + assert!(!has(&h, &format!("activity:row:{waiting}")) && rows(&h) == 1, "a waiting task draws no row"); + // the lane frees with no command asked: the frame loop starts it + build.finished.store(true, Ordering::Release); + drop(running); + let t0 = std::time::Instant::now(); + while h.app.session.activity.list().iter().any(|t| t.id == waiting && t.label == "Building previews") && t0.elapsed() < T { + h.step(); + let started = h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)); + if started { + break; + } + } + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} + +/// Given a build that ended and a build waiting behind it, when a command starts the waiting one before the frame that +/// announces the first, then the first one's end is still announced, and once. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_still_announced() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + first.done.store(2, Ordering::Relaxed); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + // a command in the same frame, before the app looks at the finished build + h.app.session.execute("activity.list", &json!({})).unwrap(); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build replaced it"); + h.step(); + assert!(first.reported.load(Ordering::Relaxed), "its end was announced"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("Previews ready for 2 photos"), "{toast}"); + assert!(h.app.session.take_unreported_builds().is_empty()); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} + +/// Given a build that ended and a build waiting behind it, when the frame starts the waiting one, then the same frame +/// asks to be drawn again to see how it goes: nothing else repaints an idle window (the list is closed, or Full Screen +/// Preview hides it). +#[test] +fn the_frame_that_starts_a_waiting_build_asks_for_the_next_one() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + let ctx = egui::Context::default(); + // (a few empty passes let the context's own first-frame requests go by) + for _ in 0..4 { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint(), "an idle context asks for nothing"); + h.app.tick_preview_builds(&ctx); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build started"); + assert!(ctx.has_requested_repaint(), "and the frame asked to look at it again"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} diff --git a/crates/ui-egui/src/tests/docking_acceptance.rs b/crates/ui-egui/src/tests/docking_acceptance.rs index 2056103f48..266bd75bfd 100644 --- a/crates/ui-egui/src/tests/docking_acceptance.rs +++ b/crates/ui-egui/src/tests/docking_acceptance.rs @@ -198,6 +198,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { let mut h = app(); h.app.run("app.setShortcut", json!({"id":"panel.crop","shortcut":"K"})).unwrap(); dock(&mut h, json!({"operation":"move","panel":"tools","target":"library","zone":"center"})); + let before = h.app.ui.right; h.app.run("panel.crop", json!({})).unwrap(); h.step(); // The test chooses the renderer's actual registered tab, rather than an arbitrary focus owner. @@ -207,7 +208,9 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { key(&mut h, egui::Key::Enter); assert_eq!(h.app.ui.right, RightPanel::Crop, "Enter activates the tab without tool.done"); key(&mut h, egui::Key::K); - assert_eq!(h.app.ui.right, RightPanel::None, "the global crop toggle is reachable from tab focus"); + // toggled off, Crop gives back the panel it took the place of (KEY-INFO / UiState::toggle_panel) + assert_eq!(h.app.ui.right, before, "the global crop toggle is reachable from tab focus"); + assert_ne!(before, RightPanel::Crop); } #[test] diff --git a/crates/ui-egui/src/tests/drag_contract.rs b/crates/ui-egui/src/tests/drag_contract.rs new file mode 100644 index 0000000000..df178105ed --- /dev/null +++ b/crates/ui-egui/src/tests/drag_contract.rs @@ -0,0 +1,432 @@ +//! What a drag of photos (or a keyword) promises: Esc gives it up and does nothing else, every row +//! it passes over says what a drop would do, a drop that would do nothing does nothing (no undo +//! step, no toast), and a row that can't take it shows so (the not-allowed cursor and a reason). + +use std::time::Duration; + +use egui::{Pos2, Rect}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// The demo library in the grid with the sidebar's Albums and Keywords and the Keyword List open, +/// in a window tall enough for every row to be on screen. +fn app() -> Headless { + let services = Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 2600.0], 1.0); + let hidden = |id: &str| json!({"id": id, "hidden": true}); + let r = h.request( + "ui.set", + json!({ + "view": "photoGrid", "leftPanel": true, "right": "keywords", + "sidebar": ["albums", "keywords", hidden("local"), hidden("byDate"), hidden("folders")], + }), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + 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, "{command}: {r}"); + h.settle(SETTLE); + r["result"].clone() +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn pointer(h: &mut Headless, at: Pos2, pressed: Option) { + h.events.push(egui::Event::PointerMoved(at)); + if let Some(pressed) = pressed { + h.events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + h.step(); +} + +/// Press on `from`, then move to `to` over a few frames, holding. +fn hold(h: &mut Headless, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for i in 1..=8 { + pointer(h, from + (to - from) * (i as f32 / 8.0), None); + } + // a few more, so what a row says about the drop has settled + h.step(); + h.step(); +} + +fn release(h: &mut Headless, at: Pos2) { + pointer(h, at, Some(false)); + // (not settled: a toast lapses with the frames) + h.step(); + h.step(); +} + +fn esc(h: &mut Headless) { + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); +} + +/// What the dragged label says this frame instead of the count, if a drop target set it. +fn hint(h: &Headless) -> Option { + // (only the frame just run: `step` leaves the counter at the next one) + let frame = h.view.ctx.cumulative_frame_nr(); + h.view + .ctx + .data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))) + .filter(|(f, _)| frame.saturating_sub(*f) <= 1) + .map(|(_, text)| text) +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default() +} + +fn select(h: &mut Headless, ids: &[u64]) { + run(h, "library.select", json!({"ids": ids})); +} + +fn members(h: &Headless, album: u64) -> Vec { + h.app.session.catalog.album(lightcraft_catalog::AlbumId(album)).map(|a| a.photos.iter().map(|p| p.0).collect()).unwrap_or_default() +} + +fn keywords_of(h: &Headless, id: u64) -> Vec { + h.app.session.catalog.photo(lightcraft_catalog::PhotoId(id)).map(|p| p.meta.keywords.clone()).unwrap_or_default() +} + +/// Two photos of the grid that are not in `album`, and one that is. +fn photos_around(h: &mut Headless, album: u64) -> (Vec, u64) { + let held = members(h, album); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let outside: Vec = shown.iter().copied().filter(|id| !held.contains(id)).take(2).collect(); + let inside = *held.iter().find(|id| shown.contains(id)).expect("the album holds a photo the grid shows"); + (outside, inside) +} + +const GARDEN: u64 = 6; + +/// Drag the selection `ids` from its first photo to `to`, still holding. +fn drag_photos(h: &mut Headless, ids: &[u64], to: &str) -> Pos2 { + select(h, ids); + let from = widget(h, &format!("thumb:{}", ids[0])).center(); + let target = widget(h, to).center(); + hold(h, from, target); + assert_eq!(h.app.ui.dragging_photos.as_deref(), Some(ids), "the photos are being dragged"); + target +} + +#[test] +fn esc_gives_up_a_photo_drag_and_does_nothing_else() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + // Esc's own command (Back: lights out → on) is something the drag must not also trigger + h.app.ui.lights_out = crate::state::LightsOut::Dim; + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "given up"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); + assert_eq!(h.app.session.selection.ids.iter().map(|p| p.0).collect::>(), outside, "the selection stays"); + // let go over the album afterwards: nothing is added + release(&mut h, target); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(toast(&h), ""); +} + +/// A headless screenshot draws the UI in an offscreen context that has no pointer: it must not +/// give up the drag the window is holding. +#[test] +fn a_headless_screenshot_during_a_drag_leaves_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let main = h.view.ctx.clone(); + h.app.headless_screenshot(&main, false); + assert_eq!(h.app.ui.dragging_photos.as_deref(), Some(&outside[..]), "the window's drag goes on"); +} + +/// Esc and the button's release in one frame: the drag is given up, and Esc's own command (Back) +/// doesn't also run. +#[test] +fn esc_on_the_frame_the_button_is_released_only_gives_up_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let before = members(&h, GARDEN); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.events.push(egui::Event::PointerButton { pos: target, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.step(); + h.step(); + assert_eq!(h.app.ui.dragging_photos, None, "the drag is over"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); + assert_eq!(members(&h, GARDEN), before, "Esc beat the release: nothing was added"); +} + +#[test] +fn esc_only_gives_up_an_album_or_keyword_drag() { + let mut h = app(); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + // an album dragged in the sidebar + let from = widget(&h, &format!("source:album:{GARDEN}")).center(); + hold(&mut h, from, from + egui::vec2(0.0, 40.0)); + assert_eq!(h.app.ui.dragging_album, Some(GARDEN), "dragging an album"); + esc(&mut h); + assert_eq!(h.app.ui.dragging_album, None); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "an album drag's Esc is its own"); + release(&mut h, from); + // a keyword dragged in the Keyword List + let from = widget(&h, "keywordRow:mountains").center(); + hold(&mut h, from, from + egui::vec2(0.0, 40.0)); + assert_eq!(h.app.ui.dragging_keyword.as_deref(), Some("mountains")); + esc(&mut h); + assert_eq!(h.app.ui.dragging_keyword, None); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "a keyword drag's Esc is its own"); + release(&mut h, from); + // and with nothing dragged, Esc does what it did + esc(&mut h); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::On); +} + +fn key(h: &mut Headless, key: egui::Key) { + for pressed in [true, false] { + h.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + } +} + +#[test] +fn a_drag_started_before_full_screen_ends_with_the_button_and_esc_leaves() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + // F while the button is still held: the layout that runs the drag's feedback is gone + key(&mut h, egui::Key::F); + assert!(h.app.ui.fullscreen, "F opened the full-screen preview"); + release(&mut h, target); + assert_eq!(h.app.ui.dragging_photos, None, "the drag ended with the button"); + key(&mut h, egui::Key::Escape); + assert!(!h.app.ui.fullscreen, "Esc leaves full screen"); +} + +/// In full screen no drop target reads the release, so the release frame ends the drag itself rather +/// than leaving it standing for one more frame (where the shortcuts no longer hold Esc back for it). +#[test] +fn esc_the_frame_after_a_release_in_full_screen_leaves_full_screen() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + key(&mut h, egui::Key::F); + assert!(h.app.ui.fullscreen, "F opened the full-screen preview"); + pointer(&mut h, target, Some(false)); + assert_eq!(h.app.ui.dragging_photos, None, "the release frame ended the drag"); + key(&mut h, egui::Key::Escape); + assert!(!h.app.ui.fullscreen, "and Esc then leaves full screen"); +} + +/// A right-button release over a row that refuses photos (a smart album, an album folder, a keyword +/// row) is not the drop the primary button's release is: no refusal is said. (Whether the drag itself +/// goes on after that release is the grid's `drag_feedback`, not this row's.) +#[test] +fn a_right_button_release_over_a_refusing_row_says_nothing() { + let mut h = app(); + let smart = run(&mut h, "album.createSmart", json!({"name": "Fours", "rules": {"rating": 4}}))["id"].as_u64().unwrap(); + h.settle(SETTLE); + let (outside, _) = photos_around(&mut h, GARDEN); + for row in [format!("source:album:{smart}"), "source:folder:1".to_string(), "source:keyword:mountains".to_string()] { + let target = drag_photos(&mut h, &outside, &row); + for pressed in [true, false] { + h.events.push(egui::Event::PointerButton { + pos: target, + button: egui::PointerButton::Secondary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + } + assert_eq!(toast(&h), "", "{row}: nothing is said: {}", toast(&h)); + release(&mut h, target); + h.app.ui.toast = None; + } +} + +/// A release that a hidden pass took leaves the drag set with no button down: Esc on the next frame +/// still only gives it up, before Back can run. +#[test] +fn esc_with_a_drag_left_over_and_no_button_down_only_gives_up_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + h.app.ui.dragging_photos = Some(outside); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "given up"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); +} + +#[test] +fn esc_during_a_drag_leaves_a_dialog_open() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + run(&mut h, "dialog.newAlbum", json!({})); + h.step(); + assert!(h.app.ui.dialog.is_some(), "a dialog opened over the drag"); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "Esc gave up the drag"); + assert!(h.app.ui.dialog.is_some(), "and only the drag"); +} + +#[test] +fn an_album_row_says_how_many_photos_a_drop_adds() { + let mut h = app(); + let (outside, inside) = photos_around(&mut h, GARDEN); + let before = members(&h, GARDEN); + // two photos that aren't in the album + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("2 photos") && said.contains("Garden"), "{said}"); + assert!(h.painted_text().contains(&said), "the dragged label shows it"); + release(&mut h, target); + assert_eq!(members(&h, GARDEN).len(), before.len() + 2); + assert_eq!(toast(&h), "Added 2 photos to “Garden”"); + // one that is there already and one that isn't: only the one counts, and the toast says so + let (fresh, _) = photos_around(&mut h, GARDEN); + let fresh = *fresh.first().expect("the grid shows a photo Garden still lacks"); + let pair = [inside, fresh]; + let target = drag_photos(&mut h, &pair, &format!("source:album:{GARDEN}")); + assert!(hint(&h).is_some_and(|t| t.contains("1 photo ") && !t.contains("2 ")), "{:?}", hint(&h)); + release(&mut h, target); + assert_eq!(toast(&h), "Added 1 photo to “Garden” · 1 already there"); +} + +#[test] +fn a_drop_on_an_album_that_adds_nothing_does_nothing() { + let mut h = app(); + let (_, inside) = photos_around(&mut h, GARDEN); + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &[inside], &format!("source:album:{GARDEN}")); + let said = hint(&h).expect("the row says so"); + assert!(said.contains("Garden") && !said.starts_with("Add "), "{said}"); + assert_ne!(h.last_cursor, egui::CursorIcon::NotAllowed, "it isn't refused: it is just already there"); + release(&mut h, target); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo, "no undo step for nothing"); + assert_eq!(toast(&h), "", "and nothing to say"); + assert_eq!(h.app.ui.dragging_photos, None); +} + +/// A drag of a photo the album holds and a Local one: nothing is added, and the row says why the +/// Local one stays out instead of only "Already in". +#[test] +fn an_album_row_explains_the_local_photos_of_a_drag_it_adds_nothing_of() { + use lightcraft_catalog::{Op, Photo, Source}; + let mut h = app(); + let (_, inside) = photos_around(&mut h, GARDEN); + let id = h.app.session.catalog.alloc_photo_id(); + let mut local = Photo::new(id, Source::File { path: "/nowhere/local.png".into() }, "local.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + local.local = true; + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(local) }).unwrap(); + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &[inside], &format!("source:album:{GARDEN}")); + // the Local photo joins the drag (the grid shows none; a folder view's selection would) + h.app.ui.dragging_photos = Some(vec![inside, id.0]); + h.step(); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("Add to My Photos first"), "{said}"); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed); + release(&mut h, target); + assert!(toast(&h).contains("1 Local photo skipped"), "{}", toast(&h)); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.ui.dragging_photos, None); +} + +#[test] +fn rows_that_cannot_hold_photos_say_so_and_refuse() { + let mut h = app(); + let smart = run(&mut h, "album.createSmart", json!({"name": "Fours", "rules": {"rating": 4}}))["id"].as_u64().unwrap(); + h.settle(SETTLE); + let (outside, _) = photos_around(&mut h, GARDEN); + let travel_folder = 1u64; + let undo = h.app.session.undo.len(); + let albums_before: Vec<_> = h.app.session.catalog.albums().map(|a| (a.id.0, a.photos.len())).collect(); + for (row, pointing_at) in [ + (format!("source:album:{smart}"), "Edit Smart Album…"), + (format!("source:folder:{travel_folder}"), "inside"), + ("source:keyword:mountains".to_string(), "Keyword List"), + ] { + let target = drag_photos(&mut h, &outside, &row); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed, "{row}: refused"); + assert!(hint(&h).is_some(), "{row}: the dragged label says so"); + release(&mut h, target); + assert!(toast(&h).contains(pointing_at), "{row}: the toast says why: {}", toast(&h)); + assert_eq!(h.app.ui.dragging_photos, None, "{row}"); + assert_eq!(h.app.session.undo.len(), undo, "{row}: nothing changed"); + h.app.ui.toast = None; + } + let albums_after: Vec<_> = h.app.session.catalog.albums().map(|a| (a.id.0, a.photos.len())).collect(); + assert_eq!(albums_before, albums_after); +} + +#[test] +fn a_keyword_row_says_how_many_photos_would_get_it() { + let mut h = app(); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let (with, without): (Vec, Vec) = shown.iter().copied().partition(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains")); + assert!(!with.is_empty() && without.len() >= 2, "the demo has photos with and without the keyword"); + let pair = [with[0], without[0], without[1]]; + let target = drag_photos(&mut h, &pair, "keywordRow:mountains"); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("mountains") && said.contains("2 photos"), "{said}"); + release(&mut h, target); + assert!(pair.iter().all(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains"))); +} + +#[test] +fn a_drop_on_a_keyword_every_photo_has_does_nothing() { + let mut h = app(); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let with: Vec = shown.iter().copied().filter(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains")).take(2).collect(); + assert!(!with.is_empty()); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &with, "keywordRow:mountains"); + assert!(hint(&h).is_some_and(|t| !t.starts_with("Add ")), "{:?}", hint(&h)); + release(&mut h, target); + assert_eq!(h.app.session.undo.len(), undo, "no undo step for nothing"); + assert_eq!(toast(&h), ""); +} + +#[test] +fn a_keyword_cannot_be_dropped_inside_itself() { + let mut h = app(); + run(&mut h, "keyword.create", json!({"name": "Weddings", "parent": "Events"})); + let r = h.request("ui.clickWidget", json!({"id": "keywordRowToggle:Events"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let tree = |h: &Headless| (h.app.session.catalog.has_keyword("Events|Weddings"), h.app.session.catalog.has_keyword("Weddings")); + assert_eq!(tree(&h), (true, false)); + let undo = h.app.session.undo.len(); + for over in ["keywordRow:Events", "keywordRow:Events|Weddings"] { + let (from, to) = (widget(&h, "keywordRow:Events").center(), widget(&h, over).center()); + hold(&mut h, from, to + egui::vec2(60.0, 3.0)); + assert_eq!(h.app.ui.dragging_keyword.as_deref(), Some("Events"), "{over}"); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed, "{over}: refused"); + assert!(h.painted_text().iter().any(|t| t == "Can't go inside itself"), "{over}: the label says why: {:?}", h.painted_text()); + release(&mut h, to); + assert_eq!(tree(&h), (true, false), "{over}: nothing moved"); + assert_eq!(h.app.session.undo.len(), undo); + } +} diff --git a/crates/ui-egui/src/tests/folder_drop.rs b/crates/ui-egui/src/tests/folder_drop.rs index 6bb1afe119..6e47a1824f 100644 --- a/crates/ui-egui/src/tests/folder_drop.rs +++ b/crates/ui-egui/src/tests/folder_drop.rs @@ -138,7 +138,7 @@ fn photos_dropped_on_a_folder_move_there_on_disk() { let target = folder_row(&h, &home).expect("held over, the folder opened"); // When it is brought over home: the label says where it will go glide(&mut h, parent.center(), target.center()); - assert_eq!(hint(&h).as_deref(), Some("Move 1 photo to “home”")); + assert_eq!(hint(&h).as_deref(), Some("Move 1 file to “home”")); // and released there: it asks first, nothing moved yet release(&mut h, target.center()); assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::MovePhotos { .. })), "{:?}", h.app.ui.dialog); @@ -149,7 +149,7 @@ fn photos_dropped_on_a_folder_move_there_on_disk() { assert!(home.join("beach.png").is_file() && !trip.join("beach.png").exists(), "moved on disk"); let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).unwrap(); assert!(matches!(&photo.source, lightcraft_catalog::Source::File { path } if Path::new(path) == home.join("beach.png"))); - assert!(toast(&h).starts_with("Moved 1 photo to “home”. Edit → Undo moves them back."), "{}", toast(&h)); + assert!(toast(&h).starts_with("Moved 1 file to “home”. Edit → Undo moves them back."), "{}", toast(&h)); assert!(h.app.ui.dragging_photos.is_none(), "the drag ended"); // and one Undo moves it back h.app.run("edit.undo", json!({})).unwrap(); @@ -219,7 +219,6 @@ fn photos_already_in_the_folder_stay_put() { release(&mut h, toggle.center()); let target = folder_row(&h, &home).expect("opened"); let garden = id_of(&h, "garden.png"); - h.app.ui.dragging_photos = Some(vec![garden]); h.app.synthetic.push(egui::Event::PointerMoved(target.center())); h.app.synthetic.push(egui::Event::PointerButton { pos: target.center(), @@ -228,6 +227,10 @@ fn photos_already_in_the_folder_stay_put() { modifiers: egui::Modifiers::NONE, }); h.step(); + h.step(); + // a drag exists only with a button down: the photos are picked up once it is + h.app.ui.dragging_photos = Some(vec![garden]); + h.step(); assert_eq!(hint(&h).as_deref(), Some("Already in “home”")); let undo = h.app.session.undo.len(); release(&mut h, target.center()); @@ -236,6 +239,96 @@ fn photos_already_in_the_folder_stay_put() { let _ = std::fs::remove_dir_all(&root); } +/// Open the folder holding `home`, add `extra_copies` photos at `trip/beach.png` (virtual copies of +/// the same file), hold the ids `pick` chooses over `home` and say what the label reads. +fn hint_over_home(tag: &str, extra_copies: usize, demo: bool, pick: impl Fn(&Headless) -> Vec) -> Option { + use lightcraft_catalog::{Op, Photo, Source}; + let (root, trip, home) = folders(tag); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + for _ in 0..extra_copies { + let id = h.app.session.catalog.alloc_photo_id(); + let p = + Photo::new(id, Source::File { path: trip.join("beach.png").to_string_lossy().into() }, "beach.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + if demo { + let id = h.app.session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::Demo { scene: 1 }, "demo.jpg", "JPEG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let toggle = widget(&h, &format!("libraryFolderToggle:{}", folder_key(&root))).unwrap(); + press(&mut h, toggle.center()); + release(&mut h, toggle.center()); + let target = folder_row(&h, &home).expect("opened"); + press(&mut h, target.center()); + h.step(); + // a drag exists only with a button down: the photos are picked up once it is + h.app.ui.dragging_photos = Some(pick(&h)); + h.step(); + let text = hint(&h); + let _ = std::fs::remove_dir_all(&root); + text +} + +#[test] +fn the_label_counts_only_the_photos_a_drop_moves() { + // one already in home, one outside it + let text = hint_over_home("count", 0, false, |h| vec![id_of(h, "garden.png"), id_of(h, "beach.png")]); + assert_eq!(text.as_deref(), Some("Move 1 file to “home”")); +} + +#[test] +fn a_photo_without_a_file_is_refused_not_moved_or_already_there() { + let text = hint_over_home("demo", 0, true, |h| vec![id_of(h, "demo.jpg")]); + assert_eq!(text.as_deref(), Some("Can't be moved here")); +} + +#[test] +fn virtual_copies_of_one_file_count_once() { + // the master and a virtual copy of beach.png: one file moves + let text = + hint_over_home("copies", 1, false, |h| h.app.session.catalog.photos().filter(|p| p.file_name == "beach.png").map(|p| p.id.0).collect()); + assert_eq!(text.as_deref(), Some("Move 1 file to “home”")); +} + +/// What the question asked after the photos `pick` chooses are dropped on `home` says it moves. +fn question_over_home(tag: &str, extra_copies: usize, pick: impl Fn(&Headless) -> Vec) -> String { + use lightcraft_catalog::{Op, Photo, Source}; + let (root, trip, home) = folders(tag); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + assert!(h.app.ui.settings.ask_before_move); + for _ in 0..extra_copies { + let id = h.app.session.catalog.alloc_photo_id(); + let p = + Photo::new(id, Source::File { path: trip.join("beach.png").to_string_lossy().into() }, "beach.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + click(&mut h, &format!("libraryFolderToggle:{}", folder_key(&root))); + let target = folder_row(&h, &home).expect("opened"); + press(&mut h, target.center()); + h.step(); + h.app.ui.dragging_photos = Some(pick(&h)); + h.step(); + release(&mut h, target.center()); + h.step(); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::MovePhotos { .. })), "{:?}", h.app.ui.dialog); + let text = h.painted_text().into_iter().find(|t| t.starts_with("Move ") && t.ends_with('?')).unwrap_or_default(); + let _ = std::fs::remove_dir_all(&root); + text +} + +#[test] +fn the_question_counts_virtual_copies_of_one_file_once_like_the_label() { + let text = question_over_home("q-copies", 1, |h| h.app.session.catalog.photos().filter(|p| p.file_name == "beach.png").map(|p| p.id.0).collect()); + assert_eq!(text, "Move 1 file to “home”?"); +} + +#[test] +fn the_question_leaves_out_a_photo_already_in_the_folder_like_the_label() { + let text = question_over_home("q-count", 0, |h| vec![id_of(h, "garden.png"), id_of(h, "beach.png")]); + assert_eq!(text, "Move 1 file to “home”?"); +} + #[test] fn photos_that_leave_the_view_leave_the_selection() { let (root, trip, home) = folders("selection"); @@ -366,7 +459,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { // (synthetic pointer events reach the app one a frame, the press's two included: one more // frame brings the pointer to the end of the glide) h.step(); - assert_eq!(hint(&h).as_deref(), Some("Move 1 photo to “home”"), "over home"); + assert_eq!(hint(&h).as_deref(), Some("Move 1 file to “home”"), "over home"); release(&mut h, target.center()); h.step(); assert!(h.app.ui.dialog.is_none(), "not asked"); @@ -468,8 +561,8 @@ fn two_folders_with_one_name_are_told_apart_in_the_label_the_question_and_the_to glide(&mut h, row_a.center(), row_b.center()); h.step(); let label_b = hint(&h).expect("a label over b/home"); - assert!(label_a.starts_with("Move 1 photo to “home (") && label_a.ends_with("/a)”"), "{label_a}"); - assert!(label_b.starts_with("Move 1 photo to “home (") && label_b.ends_with("/b)”"), "{label_b}"); + assert!(label_a.starts_with("Move 1 file to “home (") && label_a.ends_with("/a)”"), "{label_a}"); + assert!(label_b.starts_with("Move 1 file to “home (") && label_b.ends_with("/b)”"), "{label_b}"); // and the question asked on the release says the same release(&mut h, row_b.center()); let Some(crate::state::Dialog::MovePhotos { name, .. }) = &h.app.ui.dialog else { panic!("{:?}", h.app.ui.dialog) }; @@ -477,7 +570,7 @@ fn two_folders_with_one_name_are_told_apart_in_the_label_the_question_and_the_to // and so does the toast h.step(); click(&mut h, "button:dialogOk"); - assert!(toast(&h).starts_with("Moved 1 photo to “home (") && toast(&h).contains("/b)”"), "{}", toast(&h)); + assert!(toast(&h).starts_with("Moved 1 file to “home (") && toast(&h).contains("/b)”"), "{}", toast(&h)); assert!(b.join("beach.png").is_file(), "moved into the one that was asked about"); let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/ui-egui/src/tests/panel_restore.rs b/crates/ui-egui/src/tests/panel_restore.rs new file mode 100644 index 0000000000..cb775e324e --- /dev/null +++ b/crates/ui-egui/src/tests/panel_restore.rs @@ -0,0 +1,393 @@ +//! The panel a tool takes the place of comes back when the tool closes (item 12 of the evening +//! retest): open Edit → Masking (or Crop) → close it → Edit again, at the same width and scroll +//! position, with the photo where it was; a hidden panel stays hidden. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn detail() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +fn exec(h: &mut Headless, command: &str) { + let r = h.request("engine.execute", json!({"command": command, "params": {}}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.step(); + h.step(); +} + +fn widget(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The Edit panel's first slider on show (its id and where it is: it moves when the panel scrolls). +fn first_slider(h: &Headless) -> (String, egui::Rect) { + let panel = widget(h, "panel:right_panel").expect("the right panel"); + h.app + .widgets + .iter() + .filter(|(w, r)| w.starts_with("slider:") && panel.contains_rect(*r)) + .min_by(|a, b| a.1.top().total_cmp(&b.1.top())) + .map(|(w, r)| (w.clone(), *r)) + .expect("a slider in the Edit panel") +} + +#[test] +fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() { + let mut h = detail(); + // scroll the Edit panel down a little (the wheel scrolls what the pointer is over) + let panel = widget(&h, "panel:right_panel").expect("the right panel"); + h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T); + let r = h.request("ui.scroll", json!({"dy": -300.0}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + h.step(); + } + let (slider, at) = first_slider(&h); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop", "panel.remove", "panel.redeye"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool}: {:?}", h.app.ui.right); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: the panel keeps its place and width"); + // the same button again closes the tool: Edit is back, as it was + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{tool}: the Edit panel comes back"); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: same place and width"); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo didn't move"); + assert_eq!(widget(&h, &slider), Some(at), "{tool}: Edit kept its scroll position"); + } + // Masking, then Crop from it, then Crop closed: exactly what was there before, Masking (note 21); then Edit + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // Return (Done) in a tool also goes back + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +#[test] +fn a_hidden_panel_stays_hidden_after_a_tool() { + let mut h = detail(); + exec(&mut h, "panel.close"); + assert_eq!(h.app.ui.right, RightPanel::None); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool} shows"); + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::None, "{tool}: nothing shows again"); + h.settle(SETTLE); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo is where it was"); + } + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Done: hidden as before"); + // a panel picked meanwhile is what comes back: Info → Masking → closed = Info + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} + +/// "I" toggles the Info panel; pressing it again brings back exactly what the right column showed before, closed +/// included (test notes 2026-10-24 note 21: the Edit sliders stayed gone). +#[test] +fn info_toggled_off_brings_back_exactly_what_was_there() { + let mut h = detail(); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // the key, as the user pressed it + let key = |h: &mut Headless| { + let r = h.request("ui.key", json!({"key": "I"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + }; + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → I = Edit"); + exec(&mut h, "panel.masking"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks"); + // and Masks still closes back to Edit + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + for panel in ["panel.keywords", "panel.versions", "panel.activity"] { + exec(&mut h, panel); + exec(&mut h, panel); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{panel} toggled off: Edit again"); + } + exec(&mut h, "panel.close"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::None, "closed → I → I = closed"); +} + +/// A `ui.set` that changes something else (here the panel width) keeps a pending toggle: I still puts Edit back +/// (CodeRabbit on #3031). +#[test] +fn a_ui_set_between_the_two_presses_keeps_the_toggle() { + let mut h = detail(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + let r = h.request("ui.set", json!({"rightWidth": 320.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → ui.set → I = Edit"); +} + +/// A tool panel restored from the saved UI state (the panel before it unknown) closes to Edit, not to a hidden column. +#[test] +fn a_tool_restored_from_saved_state_closes_to_edit() { + let mut ui: crate::state::UiState = serde_json::from_str(r#"{"right": "crop"}"#).unwrap(); + assert_eq!(ui.right, RightPanel::Crop); + ui.note_right(); + assert_eq!(ui.leave_tool(), RightPanel::Edit); +} + +/// F8 hiding a tool and F8 showing it again keeps what the tool closes to: Info → Crop → F8 → F8 → Done = Info, not a +/// hidden column (CodeRabbit on #3031). +#[test] +fn a_tool_hidden_and_shown_by_f8_still_closes_to_the_panel_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Info, "{close}: Info → Crop → F8 → F8 → closed = Info"); + } + // a panel picked while the tool was hidden is not undone: Crop → F8 → Masking → closed = closed, as before + exec(&mut h, "panel.close"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info, "a panel picked after F8 is what comes back"); +} + +/// A tool opened another way on the column F8 hid is not F8 showing a tool again: Info → Crop → F8 → Brush → Done +/// leaves the column hidden, as it was when the brush was picked (CodeRabbit on #3031). +#[test] +fn a_tool_opened_on_the_column_f8_hid_closes_to_the_hidden_column() { + let mut h = detail(); + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "tool.brush"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Info → Crop → F8 → Brush → Done = hidden"); +} + +/// A tool opened from another tool keeps where it closes to across F8: Masking → Crop → F8 → F8 → closed = Masking, +/// and Masking then closes to Edit (CodeRabbit on #3031). +#[test] +fn a_nested_tool_hidden_and_shown_by_f8_still_closes_to_the_tool_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Masking, "{close}: Masking → Crop → F8 → F8 → closed = Masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{close}: then Masking closes to Edit"); + } +} + +/// Toggles nest: Edit → I → K → K → I = Edit, each press taking back exactly the one before it (CodeRabbit on #3031). +#[test] +fn nested_panel_toggles_come_back_one_at_a_time() { + let mut h = detail(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Keywords); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info, "Keywords toggled off: Info again"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Info toggled off: Edit again"); + // pressing two keys in turn many times keeps a bounded history and still unwinds to a panel + for _ in 0..crate::state::TOGGLE_HISTORY { + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + } + assert!(h.app.ui.toggle_return.len() <= crate::state::TOGGLE_HISTORY); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} + +/// A tool opened by a command from another tool closes back to that tool, and the panels before it still come back +/// in turn: Info → Crop → B → Done = Crop, Crop closed = Info, I = Edit (CodeRabbit on #3031). +#[test] +fn a_tool_opened_from_another_tool_closes_back_to_it() { + let mut h = detail(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.crop"); + exec(&mut h, "tool.brush"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "Info → Crop → B → Done = Crop"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Info, "then Crop closes to Info"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "and I gives back Edit"); + // a tool opened by a command from a panel closes to that panel + exec(&mut h, "tool.brush"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +/// Commands run back to back with no frame between them (a batch of control requests) see F8's hide at once: +/// Info → Crop → F8 → Brush → Done leaves the column hidden (CodeRabbit on #3031). +#[test] +fn f8_is_noted_before_the_next_command_of_the_same_frame() { + let mut h = detail(); + exec(&mut h, "panel.close"); + for command in ["panel.info", "panel.crop", "view.rightPanel", "tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column"); +} + +/// Info → Remove → F8 → A (Visualize Spots opens Remove again on the hidden column) → Done leaves the column +/// hidden: F8 kept Remove's record, but this opening is a new one, from the hidden column (CodeRabbit on #3031). +#[test] +fn a_tool_hidden_by_f8_and_opened_again_by_a_command_closes_to_the_hidden_column() { + let mut h = detail(); + for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Remove); + h.app.run("tool.done", json!({})).unwrap_or_else(|e| panic!("tool.done: {e}")); + assert_eq!(h.app.ui.right, RightPanel::None, "Remove was opened again on the hidden column"); + // the same steps a frame apart + let mut h = detail(); + for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots", "tool.done"] { + exec(&mut h, command); + } + assert_eq!(h.app.ui.right, RightPanel::None, "frame by frame"); +} + +/// Commands run in one frame (a script, queued shortcuts) each see the panel the one before left: Close Panel → +/// B → Done keeps the column hidden, and B → A → Done goes back to Masking (CodeRabbit on #3031). +#[test] +fn every_command_notes_the_panel_it_leaves_on_show() { + let mut h = detail(); + for command in ["panel.close", "tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column"); + let mut h = detail(); + for command in ["tool.brush", "view.visualizeSpots", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Masking, "Remove was opened from Masking"); +} + +/// `ui.set` changing the panel notes it at once: a tool opened before the next frame closes back to that panel +/// (CodeRabbit on #3031). +#[test] +fn a_panel_set_by_ui_set_is_noted_before_the_next_command() { + let mut h = detail(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"right": "info"})); + let ctx = h.view.ctx.clone(); + let _ = crate::control::handle(&mut h.app, &ctx, &req); + assert_eq!(h.app.ui.right, RightPanel::Info); + for command in ["tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Info, "the brush was opened from Info"); +} + +/// A tool panel put back by a toggle brings its own on-canvas tool back: Masking's Brush, Remove's Heal or Clone +/// (CodeRabbit on #3031). The panels come back as before (Edit → I → K → K → I = Edit). +#[test] +fn a_panel_put_back_by_a_toggle_keeps_its_tool() { + let mut h = detail(); + exec(&mut h, "panel.masking"); + h.app.ui.tool = "brush".into(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks"); + assert_eq!(h.app.ui.tool, "brush", "Masks → I → I keeps the Brush"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + assert_eq!(h.app.ui.tool, "", "Edit comes back with no tool"); + + exec(&mut h, "panel.remove"); + assert_eq!(h.app.ui.right, RightPanel::Remove); + for mode in ["heal", "clone"] { + h.app.ui.tool = mode.into(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Remove); + assert_eq!(h.app.ui.tool, mode, "Remove → I → I keeps {mode}"); + } + exec(&mut h, "panel.remove"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + + // the panels themselves come back as before + for (command, right) in [ + ("panel.info", RightPanel::Info), + ("panel.keywords", RightPanel::Keywords), + ("panel.keywords", RightPanel::Info), + ("panel.info", RightPanel::Edit), + ] { + exec(&mut h, command); + assert_eq!(h.app.ui.right, right, "Edit → I → K → K → I, after {command}"); + } +} + +/// A toggle that opens a panel while the Tools column is behind another dock tab remembers the +/// column as hidden: toggled off, it doesn't come back with the panel or the on-canvas tool it held +/// out of sight (CodeRabbit on #3031: Remove in Heal behind another tab came back with Heal armed). +#[test] +fn a_toggle_over_a_hidden_tools_column_puts_back_a_hidden_column() { + let mut ui = crate::state::UiState { right: RightPanel::Remove, tool: "heal".into(), ..Default::default() }; + assert!(ui.toggle_panel(RightPanel::Info, false), "Info comes up"); + assert_eq!(ui.right, RightPanel::Info); + assert!(!ui.toggle_panel(RightPanel::Info, true), "and goes"); + assert_eq!(ui.right, RightPanel::None, "the column was out of sight: it stays out of sight"); + assert_eq!(ui.tool, "heal", "no tool put back (the command clears it)"); + let mut ui = crate::state::UiState { right: RightPanel::Edit, ..Default::default() }; + ui.toggle_panel(RightPanel::Info, false); + ui.toggle_panel(RightPanel::Info, true); + assert_eq!(ui.right, RightPanel::None, "Edit behind another tab isn't brought forward either"); +} diff --git a/crates/ui-egui/src/tests/progress.rs b/crates/ui-egui/src/tests/progress.rs index 09e9234a0c..b0c9f6f7d4 100644 --- a/crates/ui-egui/src/tests/progress.rs +++ b/crates/ui-egui/src/tests/progress.rs @@ -276,6 +276,9 @@ fn an_activity_bar_is_named_after_its_task() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width()); let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 63ada41941..b83265e6aa 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -490,6 +490,9 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { 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 = animation_time; + // Captions and headings are not text to select (#1885); text meant for copying opts in + // with `Label::selectable(true)`. + s.interaction.selectable_labels = false; }); } @@ -584,6 +587,46 @@ mod tests { } } + /// Drag the pointer across `label` from end to end, press Copy, and return what egui copied. + fn drag_and_copy(label: impl Fn() -> egui::Label) -> Option { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::default()); + let frame = |events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), + events, + ..Default::default() + }; + let mut rect = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| rect = ui.add(label()).rect); + out.textures_delta.clear(); + (out.platform_output.commands, rect) + }; + let (_, rect) = frame(vec![]); + let (from, to) = (rect.left_center() + egui::vec2(1.0, 0.0), rect.right_center() - egui::vec2(1.0, 0.0)); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(from)], + vec![button(from, true)], + vec![egui::Event::PointerMoved(to)], + vec![button(to, false)], + vec![egui::Event::Copy], + ] { + commands.extend(frame(events).0); + } + commands.into_iter().find_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text) } else { None }) + } + + /// #1885: a panel caption is not text to select, as in Lightroom; text a dialog offers for + /// copying (a path) opts in and still copies. + #[test] + fn static_labels_cannot_be_drag_selected_but_opted_in_text_can() { + assert_eq!(drag_and_copy(|| egui::Label::new("Exposure")), None, "a plain label was selected and copied"); + assert_eq!(drag_and_copy(|| egui::Label::new("/Users/me/Pictures").selectable(true)).as_deref(), Some("/Users/me/Pictures")); + } + /// #736: the release input must carry Thai, not silently skip the check with an older pin. /// Exercise the Thai characters of the reported folder name through every egui family. #[test] diff --git a/docs/ai-masks.md b/docs/ai-masks.md index a10933a3f9..20c3b13d87 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -2,8 +2,10 @@ LightCraft selects objects with **SAM 3** (Segment Anything with Concepts, Meta 2025), run in pure Rust by `crates/segment` on [candle](https://github.com/huggingface/candle): on the GPU -through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't run it, it runs on -the CPU (see the worker below). +through Metal on macOS (if the Mac's GPU can't run it, it runs on the CPU, see the worker below); on Linux and Windows the image encoder (most of the work) runs on the GPU +through wgpu (Vulkan / DX12), with the two necks and the text detector's DETR encoder and mask +decoder, and the rest on the CPU, falling back to the CPU when there is no usable GPU +([Where it runs](#where-it-runs)). **The model is optional.** It is not part of LightCraft, and nothing requires it: without it, Object, Describe and Lens Blur's **Find Subject** offer to download it, every other feature (and @@ -48,19 +50,91 @@ 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, ~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. +look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the +model after launch; ~0.6 s on an RTX 5070 under Linux, of which 0.45 s is the image encoder and +0.12 s the click features, plus ~1–2 s once for loading the model onto the GPU; ~11 s with all of +it on the CPU of a 12-core Ryzen 9 3900X). 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 need the model, so masks survive moving the library to a machine without it, and the web build renders them. Editing the photo's look later does not recompute a mask (click again to update). +## Where it runs + +| | Image encoder (once per photo) | Click features, clicks, descriptions | +|---|---|---| +| macOS | GPU: Metal (candle) | GPU: Metal (candle) | +| Linux, Windows | GPU: wgpu compute on Vulkan / DX12 (`lightcraft-gpu`, module `sam3`) | the two necks and the text detector's DETR encoder and mask decoder on the GPU (wgpu); the click decoder, the text encoder and the DETR decoder on the CPU (candle) | +| no usable GPU, `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off`, or the GPU failed; outside macOS also GPU rendering off | CPU (candle) | CPU (candle) | +| **CPU** chosen in Settings (any platform, macOS included) | CPU (candle) | CPU (candle) | + +Measured on Linux (AMD Ryzen 9 3900X, 12 cores / 24 threads; NVIDIA RTX 5070), release build, +the photo already rendered: + +| Step | CPU only | On the GPU | +|---|---|---| +| Image encoder (once per photo) | 30.2–31.2 s | 0.49–0.57 s (0.43–0.44 s of it on the GPU, see [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12)) | +| Loading the model (once, and again after 10 min idle) | ~1.5 s | ~1.8 s (device and kernels 0.16–1 s, weight upload ~1.1 s) | +| A photo's whole analysis before its first click | 32.3–33.4 s | 0.56–0.69 s | +| Click features (once per photo, before the first click) | 2.1–2.3 s | 0.12–0.19 s (the tracker neck on the GPU, 38 ms) | +| A click | ~0.14 s | ~0.14 s (CPU) | +| First description on a photo (detector features + text) | 6.3–6.9 s | 0.5–0.8 s (1.3 s the very first time, with the detector loading) (the detector neck, the DETR encoder and the mask decoder on the GPU) | +| A further description | 4.4–4.5 s | ~0.7 s (the DETR encoder and the mask decoder on the GPU, 24 + 33 ms; the rest on the CPU) | +| A prompt used before (on this or an earlier photo; the latest 16 are kept) | ~4.35 s | 0.45–0.46 s (no text encoder) | + +(CPU: `cargo run -p lightcraft-segment --release --example sam3_bench -- `; GPU: +`LIGHTCRAFT_SAM3_DIR= cargo run -p lightcraft-gpu --release --features sam --example +sam3_backbone_bench -- --app`, and the desktop app's log lines, `SAM 3 loaded in …` and `SAM 3 +analyzed …`. What each GPU part takes: [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12).) + +**Falling back.** When the GPU can't be used (no adapter, a software one, the driver refuses the +device, not enough memory) the model loads with the image encoder on the CPU. When the GPU fails +on a photo (device lost, an output of the wrong size or with NaN), that photo is analyzed again on +the CPU and the model stays there until it loads again (except while LightCraft is closing: then +the work ends with its error, and nothing starts on the CPU). Neither is an error: the log says why +(`SAM 3 backbone accelerator unavailable (…)`, `SAM 3 backbone failed on … (…)`), and so do +Settings and `segment.model.status`. + +**Forcing the CPU.** Choose **Settings ▸ Performance ▸ AI masks ▸ Run on: CPU** +(`segment.settings {"runOn": "cpu"}`; back with `"auto"`, the default). It puts all of SAM 3 on the +CPU on every platform, macOS included (candle's CPU device instead of Metal), for a GPU that can't +run the model, and leaves GPU rendering alone. The choice is kept in +`/models/sam3-settings.json` (`{"runOn": "cpu"}`) and `segment.model.status` reports it as +`runOn`. Automatic also gives way to the switches every GPU compute in LightCraft follows (AI +Denoise, faces): `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off` at start (no GPU at all for the +process) put SAM 3 on the CPU on every platform, macOS included; **Settings ▸ Performance ▸ Use the +GPU for rendering** off (`app.gpu {"enabled": false}`) does so outside macOS, where it governs the +wgpu kernels, while on macOS candle keeps Metal. When a switch changes where it runs, a model +already loaded moves at its next request (it loads again). + +**Seeing where it runs.** Settings ▸ Performance ▸ AI masks shows what the image encoder runs on +(the GPU's name, "Metal GPU" or "CPU", with the reason when it is not on the GPU) and how long the +last photo took. `segment.model.status` → `backend` says the same for agents and scripts: + +```json +"backend": { + "device": "NVIDIA GeForce RTX 5070 (Vulkan)", + "runtime": "wgpu", + "heads": "CPU; the necks, the DETR encoder and the mask decoder on the GPU", + "fallback": null, + "encodeMs": 1234, + "analyzeMs": 3456 +} +``` + +`device` is what runs the image encoder (`null` until the model first loads), `runtime` `wgpu` +(LightCraft's kernels) or `candle`, `heads` what runs the rest, `fallback` why the encoder is not on +the GPU where it could be, `encodeMs` the last image encoder run and `analyzeMs` the last photo's +analysis before its first click (encoder and click features). The log (info level) has each load +(`SAM 3 loaded in …: the backbone on the …, the rest on the CPU; the necks, the DETR encoder and the +mask decoder on the GPU`) and each photo (`SAM 3 analyzed W×H in …: backbone … on the …, click features … on the …`). + ## Remote Metal inference Native builds with `sam` can keep the editor, RAW files, library, and exports local while @@ -81,13 +155,17 @@ LIGHTCRAFT_SAM3_REMOTE=127.0.0.1:8793 lightcraft Object clicks, Describe prompts, detail refinement and Lens Blur's Find Subject (people and animals, from the camera's focus point when the file records it) use the remote worker; a worker older than the -app rejects a request it doesn't know with an error, so update both together. Only the +app rejects a request it doesn't know with an error, so update both together. **Run on** (Settings +▸ Performance ▸ AI masks, `segment.settings`) only places local inference: the remote worker +always runs on the Mac's Metal device, whatever is chosen here. Only the rendered model input (long edge at most 1008 pixels) and prompts cross the tunnel. The worker caches the current photo; detail crops do not replace that cache. Returned masks stay in the local library, so later adjustments and exports work without the connection. The worker requires Metal and accepts one editing connection at a time. It loads weights on demand and releases them when the client disconnects or remains idle for ten minutes. +If the listener reports an accept error, the worker logs it, waits 100 ms, and retries; startup +validation and bind errors still stop the worker. Both endpoints require loopback addresses: SSH provides authentication and encryption. The listener has no independent authentication; do not expose it through a public proxy. Any process of any user on the worker Mac can connect to it, and on the editing computer a local @@ -209,11 +287,14 @@ Therefore: | `mask.objectPoint` | `{x, y, exclude?: bool, id?}` | one click on the selected mask's Object selection (≤ 64 clicks) | | `mask.refineDetail` | `{id?, component?}` | the zoomed-in detail pass → `{started}` | | `segment.prepare` | `{}` | load the model and analyze the active photo → `{busy}` | -| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, runOn, backend, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.settings` | `{runOn?: "auto" \| "cpu"}` | where SAM 3 runs ([Where it runs](#where-it-runs)) → `{runOn}` | | `segment.model.download` | `{acknowledged: true}` | start the download in the background → `{started}` | | `segment.model.cancel` | `{}` | stop it (it resumes next time) → `{cancelled}` | `remote` reports the configured endpoint, not its health. `installed` describes local weights only. +`backend` is where the model runs and how long the last photo took ([Where it runs](#where-it-runs)); `null` in a +build without AI masks. `download` is `{running, done, total, file, error, cancelled, finished}`: `cancelled` is true when the last download was cancelled (its `error` says so in words; decide on the flag). An AI mask command refused because the model is not installed (or still downloading) fails with an error that starts with "The SAM 3 model is @@ -245,6 +326,13 @@ wait and return the result (when built with the `sam` feature; the default CLI h memory map: `unsafe` stays in `lightcraft-sysmem`), only the tensors a path needs, and every tensor's byte range is checked against the file's length when it is opened (a truncated or damaged file is an error, never a crash). +- The image encoder can run outside candle: `lightcraft_segment::BackboneAccel` (pixels in, the + backbone's `[1024, 72, 72]` features out), built from the checkpoint through `WeightReader` and + given to `Sam3::load_accelerated`. `lightcraft-gpu` (feature `sam`, on with the engine's `sam`) + implements it in WGSL. `Sam3` checks every result (size, finite values) and drops the + accelerator for the candle backbone on the first failure; `Sam3::backbone_device` / + `accelerated` / `backbone_fallback` report it. The engine's worker picks the placement + (`Placement` in `worker.rs`). - The engine (`crates/engine/src/segment/`) owns one worker thread with the model and the last encoded photo; the session sends it jobs and receives results over channels, never holding a lock the model holds. Each job runs under `catch_unwind`: a panic inside candle becomes an diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 6f2b003477..650a94063f 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -49,6 +49,18 @@ guard.detail(&file_name); - **Quiet periodic work** shows no row: the auto-import folder listing runs every few seconds through `tasks::spawn(.., None, ..)`. +## Waiting in line + +Jobs that must not run side by side share a lane (`activity::Lane`; for now only the preview builds: Build Previews and +the background Build / Discard Smart Previews). A call that sets `queue: true` while its lane is busy does not fail: +`Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) +and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after +every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, +`place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out +of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names +belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is +busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged and the next in line goes on. + ## Examples in the code | Job | Where | Shows how to | diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index da58c69e4b..8879e67bf3 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -155,7 +155,7 @@ on a 4× finer proxy roughly halves it in a simulation, but the acceptance gates One photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). `lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos. -Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); ILCE-7RM5, 220 photos (Standard creative style); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit before falling back to neutral rendering. Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. +Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); ILCE-7RM5, 220 photos (Standard creative style); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. ### Sony ILCE-7CR @@ -177,7 +177,7 @@ Without a profile all 150 photos accept their own fit (ΔE 1.8–13.5). For vali With CR3 and CR2 input to `calibrate` (#1073), tried on one photographer's library (CR3, RAW and C-RAW, October 2025 to September 2026) and measured as above, against each file's own full-size embedded JPEG (6960 × 4640 R7, 6000 × 4000 R6 Mark II): - Held out: 40 photos per body from different shoots, every fifth withheld (8 per body), profiles fitted on the other 32 (30 R7 photos with 107,286 colour pairs, 28 R6 Mark II with 93,200; both with a hue/saturation table). On the withheld photos the profile changes little: R7 mean ΔE 2.52 → 2.57 (median 2.37 → 2.25; 3 better, 3 worse, 2 unchanged; largest regression +0.51 on an almost colourless photo), R6 Mark II 6.12 → 6.09 (median 5.73 → 5.50; 3 better, 4 worse, 1 unchanged; largest regression +0.48, best gain −0.67). Mean ΔL\* 0.00 (R7) and +0.57 (R6 Mark II) either way. Not bundled. -- The profile only replaces the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit is rejected renders the neutral fallback with or without it: 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. +- When this was measured the profile only replaced the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit was rejected rendered the neutral fallback with or without it (since `LOOK_VERSION` 14 it keeps the profile's colour, below): 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. - Library-wide (`--max 600` over 35,796 CR3s): 410 R7 photos (1.39 million pairs), 119 R6 Mark II (386k) and 38 EOS R100 (129k) gave profiles; 32 photos had no usable camera JPEG or colour (mostly moon, night and other near-colourless scenes) and one did not decode. The R6 Mark II writes its Exif model as "Canon EOS R6m2", the profile's file name too. - Decoding: 4 of the R6 Mark II C-RAW files tried (3 of 40 sampled, 1 of 119 in the library run) are refused with "unsupported raw variant: Canon CRX adaptive QP value 172" (or 175) and open preview-only. @@ -233,7 +233,13 @@ A raw starts from the first of these that is available (`camera_preview::startin 4. the model's spectral matrices, with LightCraft's default tone curve and no JPEG fit; 5. the neutral fallback. -When the file's JPEG is black and white, step 2 fits the tone curve alone with the profile's colour; without a profile, or when that fit fails, 4 and 5 take the tone curve fitted to it (see the black-and-white JPEG paragraph above). If every existing JPEG fit fails, a near-black frame may take the guarded tone-only fallback described above, after its spectral or neutral colour has been chosen. +When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above (continued along the profile's pooled tone curve when it has one, below), else the pooled tone curve whole, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. Without a profile, if every existing JPEG fit fails, a near-black frame may take the guarded tone-only fallback described above, after its spectral or neutral colour has been chosen. + +Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). + +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose sensor channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85; the floor applies before the profile's matrix, so channels the matrix sends negative stay in the luminance, as in the render, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 17); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 16); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. + +On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). The spectral matrices only replace the neutral fallback: a photo whose JPEG fit is accepted (with or without a profile) renders exactly as before, and a covered model takes its spectral matrices only when that fit fails the diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 655a1fbf36..5bad083341 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list` (including tasks waiting in line, which have no row); the activity stack in the top-left corner shows the running ones, and a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?, alt?, shift?, cmd?, ctrl?}` (`button: "right"` right-clicks; `count` is capped at 16; the modifiers are held for the click or drag, e.g. `alt: true` on a sidebar triangle opens or folds the row with all the rows inside it; in Local it folds them and opens the one row) / `{id, fx?, fy?, toX?, toY?, dx?, dy?, steps?, alt?, shift?, cmd?, ctrl?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | @@ -106,8 +106,8 @@ filmstrip is visible. | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | -| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | | `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` | diff --git a/docs/gaps.md b/docs/gaps.md index b2ee3d4b40..867e067561 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -100,6 +100,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | +| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker logs and retries listener accept errors after 100 ms; startup and bind failures remain errors; gap ranking and readiness unchanged | | 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain | | 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) | | 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 701a64659e..5f9b12c888 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -479,6 +479,176 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source - Result (M4 Pro, 14 raws, loupe, 12 steps): peak RSS 1.9–2.3 GB → 0.83–0.99 GB, peak footprint 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). +## SAM 3 backbone (M12) +AI masks (Object, Subject, Describe) spend almost all of their time in SAM 3's vision backbone, a 32-layer ViT +(`crates/segment/src/vit.rs`, ~4.6 TFLOP plus attention per photo): ~37–40 s on the CPU through candle. With the +`sam` feature, `lightcraft_gpu::sam3::backbone(&WeightReader)` runs it with wgpu compute kernels instead and returns +a `lightcraft_segment::BackboneAccel` for `Sam3::load_accelerated`; the heads stay on candle (the necks: below). It has a +device of its own (like denoise and faces) with the same switches, crash sentinel, shutdown gate and +stop-after-a-device-error handling; any failure is an `Err` and the candle backbone runs instead. +- Same math as `vit.rs`: patch embedding (im2col + matrix product, 24 × 24 position table tiled), `ln_pre`, then per + layer LN → one q|k|v product (the three weights concatenated) → 2-D RoPE (`rope_tables`, recomputed bit for bit) + → attention over 24 × 24 windows, or all 5184 tokens in layers 7/15/23/31 → output projection + residual → LN → + MLP 1024 → 4736 → 1024 with GELU (erf form; A&S 7.1.26, |error| < 1.5e-7) + residual. +- Tokens stay in *window order* (window-major, row-major inside a window) from the patch embedding to the last + layer: a window is a contiguous range of keys, the position table repeats per window (a bias table indexed by + row % 576), and global attention does not depend on order (its RoPE table is stored in window order). The last + kernel writes the `[1024, 72, 72]` channels-first output. +- Kernels (`wgsl/sam3_*.wgsl`): `sam3_matmul` (Y = X · Wᵀ with the checkpoint's `[N, K]` weights as they are, + 64 × 64 tiles, 4 × 4 per thread, k in steps of 16 through padded workgroup memory, bias/GELU/residual in the + epilogue; written out per tile size with one variable per accumulator), `sam3_attention` (flash style: one query + per thread, keys and values 32 at a time through workgroup memory, online softmax; the 16 × 5184² scores of a + global layer never exist; also written out, since arrays indexed in loops spilled to local memory and ran 3.5 × + slower), `sam3_ops` (layer norm, RoPE in place with the 1/8 scale folded into q, im2col, the final reorder). No + subgroups and no shader-f16 needed. +- All 228 dispatches, their parameters (one uniform buffer) and bind groups are recorded once with the weights; a + forward pass writes the pixels, submits one command buffer per layer and reads the result back once. +- Limits requested: WebGPU downlevel defaults plus 98 MB storage bindings / buffers (the MLP's activations, + 5184 × 4736 floats) and 16 KB of workgroup memory. Device memory: 1.8 GB of f32 weights + 0.2 GB of work + buffers. When the f32 weights don't fit (out-of-memory while uploading), it retries with f16 weights (pairs + packed in u32, unpacked with `unpack2x16float`, products still in f32): 0.9 GB, but ~20 × the error (below). + An adapter short of a limit gets no device (`short_limits`, e.g. "max_storage_buffer_binding_size 67108864 < + 98205696"), nor does one whose device creation fails or panics (the crash sentinel keeps a driver crash from + repeating on the next start); SAM 3 then runs in candle on the CPU, and `segment.model.status` → `backend.fallback` + and Settings ▸ Performance ▸ AI masks say why. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`): device + kernel compile 0.16–0.3 s (≈1 s with a + cold driver shader cache), weight upload 1.1 s, first forward 0.43–0.47 s, warm forward 0.43–0.44 s; candle on + the CPU 36–40 s. Matrix products ~13.5 TFLOP/s (~80 % of the time), attention ~12 TFLOP/s. f16 weights: 0.47 s + (no faster: the products are compute-bound), upload 2.9 s. +- Accuracy (`tests/it/sam3_backbone.rs`, a photo with a Hugging Face reference from `tools/sam3_reference.py`): GPU vs + CPU backbone max abs 5.3e-2 at a scale of 223 (max rel 2.4e-4), mean abs 2.2e-5; against Hugging Face the GPU is + as close as the CPU port (max rel 1.4e-4 vs 2.0e-4). Click masks and a Describe mask ("person") from either + backbone: IoU 1.0. With f16 weights: max rel 3.8e-3, mean abs 5.4e-4, mask IoU ≥ 0.9997. +- Tests: kernel unit tests against plain loops (`src/sam3/tests.rs`: cut-off tiles, K not a multiple of the tile, + windowed and global attention, LN, RoPE, im2col/reorder, f16 rounding), skipped without a GPU; the end-to-end + test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan), Apple silicon (M4 Pro, Metal + through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992) and AMD (RX 7900 XTX on + Windows 11, DX12 and Vulkan, all four `sam3_` tests: backbone 0.46 s on DX12 and 0.51 s on Vulkan against 26 s in + candle on the CPU, max rel 4.3e-5 / 5.1e-5; on DX12 Describe, semantic and click masks IoU ≥ 0.9993). Intel is untested. + +### SAM 3 necks +After the backbone, the click decoder needs the tracker neck (`tracker_neck`) and Describe the detector's +(`detector_model.vision_encoder.neck`): the same `Sam3VisionNeck` (`crates/segment/src/neck.rs`) with other weights, +three levels each (288², 144² and 72², 256 channels; the 36² level is used by neither head). In candle on the CPU +they took ~2.3 and ~2.6 s per photo, more than the GPU backbone. `BackboneAccel::neck` runs them with the backbone's +device (`crates/gpu/src/sam3/neck.rs`); `Sam3` turns the levels into candle tensors on its device, checks their +sizes and values, and on any `Err` warns once and runs that neck in candle from then on (the other neck and the +backbone stay on the GPU). +- Images are pixel rows (`[pixels, channels]`), so every step is the backbone's matrix kernel. A 2 × 2 stride-2 + transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` (PyTorch's + `[cin, cout, 2, 2]` weight laid out as `[(ky, kx, cout), cin]` on upload, the bias repeated 4 ×), GELU (erf) + between level 0's two in the epilogue. Its output rows hold each pixel's four outputs one after the other; `proj1` + (1 × 1) doesn't care about pixel order, so one reorder (`unshuffle` in `wgsl/sam3_neck.wgsl`) after it puts the + pixels of one or two up-samplings in row-major order. +- `proj2` (3 × 3, padding 1) is an implicit GEMM: the matrix kernel with another A-tile loader + (`wgsl/sam3_conv.wgsl`, spliced in place of the dense one between `// #if dense` marks of `sam3_matmul.wgsl`) that + reads the 9 · 256 numbers of a pixel's neighbourhood straight from the image (K ordered tap-major, so each vec4 is + four channels of one pixel; zero outside). The im2col matrix (764 MB at 288²) never exists. The weights go to + `[cout, ky, kx, cin]` on upload. The last step is `to_chw` with one window over the whole image. +- Built on first use, not with the backbone: the three kernels compile (≈0.2 s with a cold driver cache, a few ms + warm), the work buffers are made (pixel rows of the backbone, 21 MB, and two 85 MB buffers the steps alternate + between, shared by both necks), and the neck's weights (~27 MB) are read, laid out and uploaded (~0.1 s). Each + level is recorded once and is one submission with its own read-back (85 / 21 / 5 MB), so no buffer exceeds the + backbone's 98 MB limits and no limit is raised. Device memory: ~245 MB with both necks built. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`; `--app` times the app's per-photo steps, + `--cpu-necks` the same with candle's necks): a neck 38 ms warm (level 0: 13 ms of products at ~12 TFLOP/s, the + rest mostly the 85 MB read-back), first use 0.08–0.12 s (0.4 s with a cold driver shader cache); candle 2.3–3.5 s. + Per photo in the app's order: click features (the tracker neck plus the tracker's two 1 × 1 convolutions, still + candle) 0.11–0.19 s instead of 2.0–2.3 s, so encode + click features 0.56–0.69 s instead of 2.4–2.9 s; the first + Describe 5.1–5.8 s instead of 7.0–7.4 s (the rest of it is the DETR encoder and decoder in candle). +- Accuracy (`tests/it/sam3_necks.rs`, both models fed the same GPU backbone output): every level of both necks within + max rel 2.1e-6, mean abs ≤ 7.7e-7 of candle; click and Describe masks IoU 1.0. +- Tests: kernel unit tests against plain f64 loops (`src/sam3/neck/tests.rs`: transposed convolutions + reorder + with odd sides, the 3 × 3 convolution at every border, single-pixel and odd sizes, cut-off tiles, the weight + layouts, a whole small neck against a transcription of `Neck::forward`); `crates/segment` tests the fallback + (wrong sizes, NaN) with a fake accelerator. + +### SAM 3 DETR encoder +Each text prompt (Describe; Subject's "person") runs the text detector (`crates/segment/src/detector.rs`), whose +DETR encoder fuses the prompt into the 72 × 72 image tokens: ~4–5 s of the ~5–7 s a prompt took on the CPU. The +same accelerator runs it (`BackboneAccel::detr_encoder`, `src/sam3/detr.rs`); `Detector::predict` uses its result +as the encoder memory and runs the rest in candle. Any failure (no such accelerator, out of memory, a wrong-sized +or non-finite result) is logged once and noted (`Sam3::detr_fallback`), and from then on candle runs the encoder +for that model. +- Same math as `detector.rs`, six layers over 5184 tokens of 256: LN (eps 1e-5, PyTorch's default) → self-attention + (8 heads of 32; q and k from the normed tokens plus their sine position encoding, v from the normed tokens; q | k + one product with the weights concatenated) → output projection + residual → LN → cross-attention to the prompt's + 32 tokens (k | v one product) with the key-padding bias → output projection + residual → LN → MLP 256 → 2048 → + 256 with ReLU + residual. +- Kernels: the backbone's matrix product (ReLU as a third epilogue activation) and layer norm (with eps 1e-5), and + `wgsl/sam3_detr.wgsl`: attention for heads of 32 (flash style, written out like the backbone's) whose q, k and v + come from separate buffers with their own strides and offsets, with an optional per-key bias stored after the + prompt's k | v (0 or f32::MIN, as candle's `padding_bias`; the running maximum starts at f32::MIN, so a padded key + weighs exactly nothing and an all-padding prompt averages, as candle's softmax does); and a sum (tokens + position). +- Loaded on the first prompt, not with the backbone: kernels, 38 MB of f32 weights, 80 MB of work buffers (model + load time and memory before the first Describe are unchanged). 84 dispatches, recorded once; a prompt writes the + tokens, their position encoding, the prompt's tokens and its padding bias, submits one command buffer per layer + and reads the memory back. +- Measured (RTX 5070, Vulkan; CPU busy with parallel builds, load ~7–10): the encoder 23–25 ms with uploads and + read-back (self-attention 2.2 ms a layer at 12 TFLOP/s, products 10–12 TFLOP/s), candle 4.6–5.7 s (3.9–4.4 s on + an idle CPU). A Describe on a photo already analyzed (second prompt) 6.6 s → 2.0 s. What remains, per prompt: + CLIP text encoder 0.27–0.46 s, DETR decoder 0.75–1.3 s (of it the box relative-position bias ~75 ms a layer), + mask head ~0.9–1.4 s (pixel decoder 3 × 3 convs at 144² and 288² ~0.75–1.2 s, 1 × 1 instance projection 0.12 s, + mask products 25 ms; now on the GPU, below). +- Accuracy (`tests/it/sam3_detr.rs`, the photo of `tools/sam3_reference.py`, prompts "person", "sky", "the red car"; + both models share one GPU backbone, so only the encoder differs): memory max rel 1.7e-6–4.2e-6, mean abs + 2.3e-6–7.7e-6; query logits max abs ≤ 2.5e-4; presence logits ≤ 2.3e-5 apart; boxes ≤ 1.2e-4; the same instances + and Describe mask IoU 1.0. Kernel unit tests (`src/sam3/detr/tests.rs`): self-attention with 8 × 32 heads and a + part-empty last workgroup, cross-attention to 32 keys with 0, 1, 5 and 32 real tokens, ReLU, the sum, the eps. + +### SAM 3 mask head +A prompt's masks come from the detector's mask decoder (`mask_decoder` in the checkpoint): the encoder memory attends +to the prompt (`prompt_cross_attn`, after its layer norm) and is added to it; the pixel decoder brings it from 72² to +288² in two stages, each nearest 2 × up-sampling + the detector neck's level of that size → 3 × 3 convolution → +GroupNorm (8 groups, eps 1e-5) → ReLU; the 1 × 1 instance projection follows, and each query's mask embedding (the +`mask_embedder` MLP on the decoder's queries) times that is its mask logits. ~0.7–1.4 s per prompt in candle on the +CPU, most of it the 288² convolution. `BackboneAccel::mask_decoder` runs it on the accelerator (`src/sam3/pixel.rs`); +any failure (out of memory, a wrong-sized or non-finite result) is logged once and noted (`Sam3::mask_fallback`), and +candle runs the decoder for that model from then on. +- Interface: the encoder memory, the prompt's tokens and which are real, both neck levels (channels-first, as + `Features` holds them) and `rows` `[r, 256]` with a bias `[r]` (r ≤ 256), each row a 1 × 1 projection of the pixel + decoder's output; it returns `[r, 288, 288]`. The detector folds the instance projection into its 200 mask + embeddings on the CPU (e · (W x + b) = (e W) x + e b: 13 MFLOP instead of the projection's 11 GFLOP), so one + product `[82944, 256] · [200, 256]ᵀ` on the GPU gives the masks and the CPU fallback stays the candle code as it was. + SAM 3's semantic segmentation head (the semantic mask Describe and Subject share out to their instances, #1963) is + another 1 × 1 read-out of the same output, so it is one more row: 201 rows, the last one the semantic mask. +- Kernels: the prompt attention is the DETR encoder's (torch-eps layer norm, products, attention with the padding + bias); the convolutions are the necks' implicit GEMM; `wgsl/sam3_pixel.wgsl` adds the up-sampling, which adds the + neck level as uploaded (channels-first, so no separate reorder), and GroupNorm + ReLU: two-pass statistics per + chunk of 256 pixels (thread = channel, so the loads are contiguous), merged per group with the parallel variance + formula, then normalized in place. The projection's `[pixels, r]` goes channels-first with `to_chw`. +- Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, 282 MB of work buffers (and an 85 MB + read-back buffer in host memory). 17 dispatches, recorded once per row count; a prompt uploads the memory (5 MB), + the prompt, both neck levels (106 MB) and the rows, submits once and reads `r · 288²` numbers back (66 MB). + Keeping the levels on the device after `BackboneAccel::neck` would save the 106 MB upload (a few ms) but needs an + image identity in the interface and another 106 MB of device memory per photo; not done. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`, quiet machine): the decoder 33 ms warm with the + uploads and the read-back (by FLOP count about a third of it kernels, the 288² convolution ~8 ms at ~12 TFLOP/s; + the rest transfers), first use 0.09–0.17 s. Per prompt in the app (`--app`, against `--cpu-masks`): a Describe on a + photo already analyzed 1.9–2.2 s → 1.04–1.06 s, the first on a photo 2.0–2.1 s → 1.11–1.12 s (2.5 s → 1.65 s with + the first load); under load (~15, parallel builds) 1.9 s → 1.1–1.2 s. With the CPU-side text cache and one-pass box + bias as well: a new prompt on an analyzed photo ~0.7 s, a prompt used before 0.45–0.46 s. What remains is in candle + on the CPU: the DETR decoder (~0.4 s) and, for a new prompt, the CLIP text encoder (~0.25 s). +- Accuracy (`tests/it/sam3_mask_decoder.rs`; both models share one GPU accelerator, so only the mask decoder differs): + against the decoder transcribed with candle's tensor ops in f64, the GPU's instance features are within max rel + 4.2e-6, mean abs 1.7e-7; candle's own f32 decoder is 1.1e-3–1.5e-3 / 2e-4 from it, all of that from its GroupNorm's + f32 sums over 2.6 M numbers per group (with those in f64 the f32 transcription is within 1.1e-6). So GPU vs candle, + all 200 queries' mask logits: max rel 1.0e-3–1.7e-3; the same instances, Describe mask IoU 1.0 ("person", "sky", + "the red car" on the photo of `tools/sam3_reference.py`). Kernel unit tests (`src/sam3/pixel/tests.rs`): the + up-sampling + level (odd sizes), GroupNorm + ReLU (cut-off chunks, a mean of 50, 1–8 groups), a two-stage small + decoder (up-sampling → convolution at every border → GroupNorm) against f64 loops, and the size checks. +- Not done: masks only for the queries above the threshold (`merge` keeps sigmoid(logit) · sigmoid(presence) > 0.5). + `Sam3::detect` returns all 200 and the reference test (`crates/segment/tests/reference.rs`) checks the + best-scoring query's mask, which need not pass the threshold; with `rows` it is a matter of passing fewer of them. + +### SAM 3 on the GPU: device memory in all +With every part on the GPU (after a photo's analysis and a first Describe): the backbone's 1.8 GB of f32 weights and +0.2 GB of work buffers, both necks ~245 MB, the DETR encoder 38 MB of weights and 80 MB of work buffers, the mask +decoder 6 MB and 282 MB: ~2.7 GB of device memory, ~1.8 GB when the backbone falls back to f16 weights. The parts +after the backbone load on first use, each on its own; one that runs out of memory (or fails otherwise) stays in +candle on the CPU from then on (`Sam3::detr_fallback`, `Sam3::mask_fallback`, the necks per kind) and the others stay +on the GPU. Settings ▸ Performance ▸ AI masks ▸ Run on: CPU keeps all of it off the GPU. + ## Open items - WebGPU in the browser build (async init, single device per canvas). - Sky/Subject heuristics (replaced by the segmenter in M12); the ProRAW local tone map. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index ea357161ef..d933d180de 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -10,7 +10,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra |---|---|---|---|---|---|---| | GPU for display and editing | Metal / DX12, "Use GPU for display / image processing / export" | wgpu Metal: geometry, resize, blur, WB, NR, guided filter, dehaze, masks, finish; CPU fallback per render | DX12 only (Vulkan opt-in, #136) | Vulkan (CPU ↔ GPU equivalence verified on an AMD Radeon 8060S, RADV) | CPU only (no WebGPU yet) | 🟡 defringe, spot removal, heuristic masks, long brushes and high-bit exports stay on CPU | | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | -| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | +| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on GPU when faster (CPU-only setting) | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, DX12), the rest of the heads on CPU (untested on DX12 so far); faces GPU / CPU | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, Vulkan), the rest of the heads on CPU (a photo's analysis ~0.6 s on an RTX 5070 vs ~33 s on a Ryzen 9 3900X, a description ~0.5–0.7 s vs ~4.5 s); faces GPU / CPU | — | 🟡 no Core ML / Neural Engine / DirectML; SAM 3's click decoder, text encoder and DETR decoder on CPU outside macOS | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | | Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | ✅ the profile Windows Color System assigns to the window's monitor, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop (HDR, Auto Color Management) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | @@ -50,6 +50,9 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Date | Change | Summary | |---|---|---| | 2026-10-20 | minor | Monitor profile: Windows reads the window's monitor profile from Windows Color System (`crates/wincolor`), sRGB while Windows colour-manages the desktop; verified on Windows 11 by setting and clearing a Display P3 profile while the app ran. Remaining monitor-profile work 4–8 h → 2–4 h | +| 2026-10-17 | minor | AI on GPU: SAM 3's text detector mask decoder also runs on the GPU through wgpu on Windows and Linux (a description ~0.5–0.7 s with the text cache and box bias of the same change) | +| 2026-10-17 | minor | AI on GPU: SAM 3's necks and DETR encoder also run on the GPU through wgpu on Windows and Linux | +| 2026-10-17 | minor | AI on GPU: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback; follows the GPU switches); faces run on the GPU when faster | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index d2316d17bc..87d17c999e 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -86,8 +86,11 @@ Before changing records, the importer attempts to save source image records, dec verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is best-effort: a size limit or write failure produces a warning and does not prevent photo import. -Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is -capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total +Unchanged source data reuses its existing archive. History-step and snapshot settings that Lightroom +Classic 13 and later store compressed are decoded into it; one that can't be decoded, or past 32 MiB of +them in one table, is archived without its settings, with a warning. Other opaque SQL BLOBs are skipped. Each archive is +capped at 32 MiB (uncompressed and on disk); one past that with its history-step and snapshot settings is +saved without them, with a warning, and skipped only when still too big. At most eight archives and 128 MiB total are retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. `Interop/lightroom-index.json` records imported identities. Source catalogs and originals are never overwritten. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9b2af76fad..694ef9b6dd 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -100,7 +100,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-ALLPHOTOS | All photos | P0 | ✅ | `cmd:library.source`, `crates/ui-egui/src/panels/left.rs` | | | LR-LIB-RECENT-ADDED | Recently added | P1 | ✅ | `cmd:library.source` (`recentlyAdded`), `crates/engine/src/view.rs` (`RECENT_DAYS`) | photos imported in the 30 days up to the latest import, newest import first, grouped by import day | | 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); album commands only take photos the library has (`album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` drop ids it lacks) and `album.addPhotos` with nothing to add (all photos already in, or none left) records no undo step and leaves redo alone; `album.toggleTarget` with none left changes nothing (`added` is null, no toast) | +| 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`, `crates/ui-egui/src/tests/drag_contract.rs` | photos dragged from the grid onto an album row are added to it: the dragged label says how many it adds, and the toast how many were there already (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); album commands only take photos the library has (`album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` drop ids it lacks) and `album.addPhotos` with nothing to add (all photos already in, or none left) records no undo step and leaves redo alone; `album.toggleTarget` with none left changes nothing (`added` is null, no toast) | | 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; 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 | @@ -300,7 +300,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) | | LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) | | LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) | -| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | +| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle; the remote worker retries listener accept errors after 100 ms (#2574), isolating client failures; it is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | | LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | @@ -473,7 +473,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | | LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output. From process V13 global Shadows eases off at large amounts (`finish::tone_slider`, +100 at 0.43 of V6), fitted to 56 Lightroom exports of real Canon portrait edits at Shadows +40 to +100; with negative Texture and the Global wheel, mean ΔE on those exports 9.5 → 9.0. Global Highlights stays linear: on those edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's Highlights response close to linear and dependent on the frame's content (#3923), so that coverage-dependent strength, and smaller Shadows amounts, remain open. | -| LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (adds the selection, with a count badge while dragging); sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | +| LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/tests/drag_contract.rs`, `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (the dragged label says how many photos it adds, or that they are all there already, and a drop then does nothing, with no undo step; a drop that finds some there says so in its toast); a smart album, an album folder and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason, on the label and in the toast; Esc gives up any drag (photos, albums, sidebar sections, keywords) and does nothing else; sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | | LR-BEHAV-SIDEBAR-COLLAPSE | Collapsible left-sidebar sections | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`section`, `section_header`), `crates/ui-egui/src/sidebar.rs` (`SidebarLayout`), `crates/ui-egui/src/tests/panels.rs` | click the Albums, Local, By Date, Folders or Keywords header (or drive `ui.clickWidget` `sidebarSection:`) to fold or unfold the section; a chevron before the title shows the state; the choice is kept across restarts (`sidebar` in the UI state; the `collapsedSidebar` list of older settings files is still read). the click itself is UI-only, like the By Date / Keywords disclosure triangles, and `cmd:view.sidebarSection` `{section, collapsed}` folds and unfolds for agents; photos dropped on a folded Albums section have no target | @@ -481,7 +481,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menus/menubar.rs`, `crates/ui-egui/src/tests/panels.rs` | View ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden | | LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests/panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before:
\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another | | LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests/panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:`, with View ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button | -| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests/panels.rs` | drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | +| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/src/tests/panel_restore.rs` | closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it in the same frame, at the same width and scroll position, or leaves it hidden if it was (`UiState::leave_tool`); drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | | LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests/empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. Files dragged over the window dim it and a card says what dropping will do; a drop of photos or folders opens the same import review as File ▸ Import | | LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | | | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | @@ -612,7 +612,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-FULLSCREEN | Full-screen preview — F | P1 | ✅ | `cmd:view.fullScreenPreview` | | | KEY-LIGHTSOUT | Lights Out — Shift+L (Classic's L is Linear Gradient here) | P2 | ✅ | `cmd:view.lightsOut` | On → Dim (80 %) → Off; Esc turns the lights on | | KEY-GRID | Grid — G | P0 | ✅ | `cmd:view.gridToggle`, `cmd:view.photoGrid` | G toggles Photo Grid ↔ Square Grid; both View menu rows show its live shortcut (including remapping/unbinding), with direct grid bindings taking priority; menu clicks still choose the named grid (#2500) | -| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info` | | +| KEY-INFO | Info — I | P0 | ✅ | `cmd:panel.info`, `crates/ui-egui/src/tests/panel_restore.rs` | pressing I again brings back exactly what the right column showed before (Edit, Masks…; closed stays closed); every panel key and button does the same (`UiState::toggle_panel`) | | KEY-KEYWORDS | Keywords — K | P0 | ✅ | `cmd:panel.keywords` | | | KEY-CLIPBOARD | Copy / paste edit settings — ⌘C / ⌘V | P0 | ✅ | `cmd:develop.copy`, `cmd:develop.paste`, `crates/ui-egui/src/shortcuts.rs` (`matches`) | ⌘X has nothing to cut outside text fields; on Windows and Linux, where the windowing layer sends Ctrl+C / Ctrl+V as clipboard events rather than key presses, those run the shortcuts too (⇧Insert pastes plainly); there Ctrl+V only arrives while the system clipboard holds text (egui-winit drops it otherwise), so with an empty clipboard Paste Settings needs the menu | | KEY-UNDOREDO | Undo / redo — ⌘Z / ⇧⌘Z | P0 | ✅ | `cmd:edit.undo`, `cmd:edit.redo` | | @@ -688,7 +688,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-HELP | Help — F1 | P2 | ✅ | `cmd:app.help` | | | KEY-VIDEO-PLAY | Play/pause video — Space | P1 | ⬜ | | | | KEY-ESC | Leave tool / view — Esc | P0 | ✅ | `cmd:view.back`, `crates/ui-egui/src/icons.rs` (`navigation_arrowheads_have_both_halves`), `crates/ui-egui/src/tests/crop_tool.rs` | top-bar navigation arrowheads render both halves at 1× and 2× scale; in the crop tool Esc closes the tool first (the crop stays), the next Esc goes back to the grid; Esc that ends an edit in a text field does nothing else | -| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking back to Edit (edits apply live, as in Lightroom) | +| KEY-COMMIT | Commit tool — Return | P1 | ✅ | `cmd:tool.done` | Return closes Crop / Remove / Red Eye / Masking and goes back to the panel shown before the tool, the right column hidden again if it was (edits apply live, as in Lightroom) | | KEY-DELETE-PIN | Delete selected pin — ⌫ | P0 | ✅ | `cmd:mask.delete`, `cmd:spot.delete` | ⌫ deletes the active mask (Masking) or the selected spot (Remove), never the photo while retouching | | KEY-HIDEPINS | Hide pins — H | P2 | 🟡 | `cmd:view.toolOverlay`, `cmd:view.maskPins`, `cmd:panel.remove`, `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/tests/tool_overlay.rs`, `crates/ui-egui/src/tests/keymap.rs` (`h_toggles_the_mask_pins_while_masking`, `h_while_masking_does_not_open_remove`, `h_opens_remove_when_another_panel_is_active`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`, `h_keeps_its_binding_in_the_full_screen_preview`, `h_keeps_its_binding_when_the_masking_panel_is_not_exposed`) | ⇧H cycles the Tool Overlay (Auto → Always → Selected → Never) for spot and mask pins; also View ▸ Tool Overlay and the Remove / Masking panels (#224). In the visible Masking panel an unmodified H itself toggles the mask pins (the same switch as View ▸ Show Mask Pins) and does not open Remove; the toggle yields only to an explicit assignment of H itself, and a Remove key reassigned to anything else still opens Remove there. Outside Masking — and wherever no panel shows (the full-screen preview, a minimized or hidden panel) — H keeps its own binding (Remove, by default). Remove's spot pins have no H hide toggle (⇧H only), so the row is partial | @@ -706,11 +706,11 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders; VIDEO records match the Videos filter, with reimport repairing older image classification while keeping edits and memberships; a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891). Lightroom catalog backups (`Backups//.zip`) import directly: the `.lrcat` is streamed (ZIP64 included) into a private folder in the library, CRC-checked, read and deleted; the zip is only read; `Backups/` or a dated folder given to Open Library offers that import (asking which zip when `Backups/` holds several); collections are matched by the catalog's `Adobe_storeProviderID`, so a backup adds no collection twice (`crates/engine/src/lightroom_backup.rs`, issue #2592) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders; VIDEO records match the Videos filter, with reimport repairing older image classification while keeping edits and memberships; a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped, except the compressed history-step and snapshot settings of Lightroom Classic 13 and later, which are decoded into the archive (an archive too big with them is kept without them). Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891). Lightroom catalog backups (`Backups//.zip`) import directly: the `.lrcat` is streamed (ZIP64 included) into a private folder in the library, CRC-checked, read and deleted; the zip is only read; `Backups/` or a dated folder given to Open Library offers that import (asking which zip when `Backups/` holds several); collections are matched by the catalog's `Adobe_storeProviderID`, so a backup adds no collection twice (`crates/engine/src/lightroom_backup.rs`, issue #2592) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/catalog/src/opened_folder.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680); a library is written only to the folder it was opened from: the folder's device and inode number are recorded when it opens and checked before every write of the catalog, its log, the settings, the lock note and the thumbnail cache (a folder that holds exactly the lock note this session wrote (a note holds a value no other lock's note has) counts as the same folder, and so does one with the same inode number and the same creation time under another device number (a drive or share mounted again), or on the same device when no two creation times that are both known differ (an inode number is given again to a folder made later); so saving goes on after a drive or share is mounted again, also on file systems that number their folders anew at every mount; a copy of the folder made while the library was open holds that note and counts too, and the log in it is appended to only while it is the log this session wrote, else a snapshot replaces it), so a share mounted over the library's folder, or a folder put in its place, is refused with the reason (nothing is written, the changes are kept in memory as unsaved, and saving goes on when the folder is back, a preference that could not be saved being written with the next one; issue #3240; on Windows only that a folder is still there is checked; on every system `Originals/` (copies, and what is done to the photos in it), Smart Previews, `focus-scanned.bin`, `Interop/` and the other files beside the catalog are still written by path); a Move import removes its originals only once the catalog log is on disk; dropping the lock removes only the owner note it wrote itself, with the bytes it wrote, from the folder it locked or one that holds that note | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290); the library last opened that is missing at launch (moved, or on a drive or network share that isn't connected) opens the can't-open window (Try Again, Choose Another, Continue Without Saving, Quit) instead of a new library with demo photos in its place (`apps/lightcraft/src/tests.rs`: `a_remembered_library_missing_at_launch_is_reported_not_made_anew`, issue #3239); a library's `catalog.snap` or folder given at launch (a double-click in the file manager) opens that library, through the usual launch path (lock check), makes it the library in use and is never imported; a second library argument gets a notice | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`), `crates/ui-egui/src/tests/move_folder.rs` | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken); Move Folder To… (here and in Folders) asks for the destination in a folder dialog that doesn't hold up the window (issue #3140); the rows of the standard places themselves (Pictures, Desktop, Downloads, Home) offer neither Rename Folder… nor Move Folder To…, while the folders inside them and the ones kept with Browse Folder… do, starting from their real name; `folder.rename` and `folder.move` refuse the home folder and its Pictures, Desktop and Downloads for every caller | -| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge, except on a row indented so far that its count (or colour dot) would cover its name: that count follows the name, wholly past the edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, which is kept only once the move has started, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | +| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge, except on a row indented so far that its count (or colour dot) would cover its name: that count follows the name, wholly past the edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 files to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 files to “Porto”?”, Don't ask again, which is kept only once the move has started, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) | | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/dialogs/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 48 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration, Same Content as Another Photo: another photo of the library has the file's content under another name or in another folder, a Duplicate's `:dup` key included; virtual copies, photos in Recently Deleted and ones only browsed in Local neither match nor count; a photo with no content hash on record never matches (photos taken over from a Lightroom catalog have none until Photo ▸ Reload from Disk reads it); kept up to date as twins are deleted, restored, removed or reloaded with other content, by a content index (`Catalog::has_same_content`) that also marks a photo's twins as touched, so album counts and views follow the edit), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/widgets/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/widgets/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents; rules and groups are reordered from a grip at the start of each row (`crates/ui-egui/src/dialogs/rules_editor/rules_move.rs`, `crates/ui-egui/src/dialogs/rules_editor/rules_reorder.rs`, `crates/ui-egui/src/tests/rules_reorder.rs`): dragging it shows a line where the row would land and Esc gives the drag up, a group can't be dropped inside itself or where groups would nest deeper than three levels (a not-allowed cursor and the reason), a group a move leaves empty goes away; from the keyboard, Tab to the grip, then ↑ / ↓ move the row one place (out of a group at its ends), → into the group next to it and ← out of its group, the focus staying on the moved row; the grip is named for its place (“Rule 2 of 4: Rating is ≥ 3. Move with the arrow keys”), and OK saves the order shown, as the same one undo step | | LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | | @@ -718,7 +718,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), 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, `>` and `<` mark a hierarchy as `\|` does (`animal > dog` and `dog < animal` are both `animal\|dog`), 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. As in Enter Keywords, `>` and `<` in a typed name mark a hierarchy as `\|` does, unless the name as written is a keyword the library has. 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 dragged label says how many photos get it; when all have it, it says so and a drop does nothing); a keyword dragged over itself or what is inside it shows the not-allowed cursor and says why; Esc gives up a drag. 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, `>` and `<` mark a hierarchy as `\|` does (`animal > dog` and `dog < animal` are both `animal\|dog`), 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. As in Enter Keywords, `>` and `<` in a typed name mark a hierarchy as `\|` does, unless the name as written is a keyword the library has. 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 @@ -824,7 +824,9 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-27 | minor | LRC-LIB-PREVIEWS: the loupe shows built and prepared previews instead of rendering again, builds skip what is there and Build Previews with one photo open builds the view; LRC-PERF-PREP new (🟡): preparing photos in the background per mode | | 2026-10-27 | minor | Culling speed: LR-IMP-LOCAL browsing shows the first photos within a second; LR-IMP-PREVIEW-READ a CR3's smallest covering JPEG, plain sRGB JPEGs straight to 8-bit, camera-JPEG thumbnails kept; LR-VIEW-DETAIL camera previews made ahead of the step, “Camera preview” label, camera JPEG first at 100 %; statuses unchanged | | 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped | +| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker retries transient listener accept errors after 100 ms; client failures remain isolated; feature counts unchanged | | 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) | +| 2026-10-26 | minor | LR-BEHAV-PANEL-RESIZE, KEY-INFO: closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it, hidden if it was hidden, at the same width and scroll position; a panel key or button (I, M, C, H…) pressed again puts back exactly what the right column showed before it (Edit → I → I = Edit, closed → I → I = closed); status unchanged (✅) | | 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca | | 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged | | 2026-10-25 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K / Ctrl+Alt+Shift+K (`dialog.keywordShortcut`, Set Keyword Shortcut) and ⇧K (`keyword.toggleShortcut`) add and remove the keyword shortcut's keywords; Keyword Shortcut leaves LRC-LIB-KEYWORDS' Not yet list; status counts unchanged (KEYC-METADATA stays 🟡) | @@ -848,6 +850,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | patch | LR-META-LOCATION: Info GPS text validates the complete decimal/DMS expression, axis markers and component ranges before metadata changes; readiness and feature counts unchanged | +| 2026-10-24 | patch | LRC-LIB-CATALOG-IMPORT: the recovery archive keeps the compressed history-step and snapshot settings of Lightroom Classic 13 and later; an archive too big with them is kept without them; status and counts unchanged | | 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | | 2026-10-24 | patch | Integration batch 43: Integrated main 98702b5c, preserving the new fail-closed GPS metadata check for Original export. Watermark geometry/orientation and HDR JPEG size-limit fixes remain in their shared helpers; no feature-count changes. | | 2026-10-23 | minor | LR-FILT-FLAG, LRC-LIB-FILTERBAR: the filter bar's flag toggles combine (any of them, `library.filter` `flags`), issue #2588; status and counts unchanged | @@ -886,6 +889,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-19 | patch | LR-VIEW-ZOOM: the slow slider-drag verdict is described as per photo and control, as the code keys it; status unchanged | | 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-18 | patch | Four revision rows (LR-PROF-CAMERACOLOR, LR-IMP-FORMATS) that had landed in the A. Import table moved here; no status changes | | 2026-10-18 | patch | Export regression integration (maintenance): Graphic watermarks honour EXIF rotation/mirroring through the shared `read_graphic` path and keep their aspect ratio when fitted to the output. HDR JPEG `limitKb` includes the gain map and metadata. Refreshed onto main fb7ac08b, retaining upstream export bounds, colour metadata, JPEG encoding and opaque RGB/real-alpha handling (#1691); no feature-count or readiness estimate changes. | | 2026-10-18 | patch | LR-META-XMP: Lightroom's profile and version bookkeeping (`CompatibleVersion`, profile digests, lens profile identity, `CropConstrainToUnitSquare`, default-strength lens profile scales) is no longer reported as unimported XMP; status unchanged (✅) | | 2026-10-17 | minor | MENU-VIEW-DETAIL, MENU-VIEW-EDIT, MENU-VIEW-CLIPPING, MENU-VIEW-MASKOVERLAY, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-BEFOREAFTER, LR-VIEW-FOCUSPOINT: menu labels renamed: switches are named for what they show (Photo Counts, Focus Point, Clipping, Mask Overlay, All Mask Overlays, Mask Pins, Layout Image), View ▸ Detail is Detail View, Window ▸ Edit is Edit Panel, Compare Before and After is Before/After Side by Side, Clear Preview Cache is Discard Preview Cache; shortcuts and commands unchanged; statuses unchanged | @@ -900,6 +904,8 @@ 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 | minor | LR-PROF-CAMERACOLOR: a photo no look fits keeps its camera profile's colour instead of the neutral fallback; status unchanged (🟡) | +| 2026-10-16 | minor | LR-PROF-CAMERACOLOR: camera profiles carry a pooled tone curve that continues each photo's own past its JPEG's range; 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-22 | patch | LR-PROF-IMPORT: a real CC0 D750 profile (matrix-only, dual illuminant) and its chart NEFs are a pinned test corpus; against Lightroom Classic 15.6 mean ΔE2000 3.8 / 3.4; status unchanged (✅) | | 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | @@ -909,6 +915,10 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-12 | minor | Calibrated Contrast and Blacks; mark the measured but incomplete Light controls partial and retain V2 Whites | | 2026-10-16 | minor | KEY-TOGGLEZOOM: Space held over a tool on the photo is the view's hand (click zooms, drag pans, the tool gets neither), a tap still toggles; a held Space toggles once (issue #1895); status unchanged | | 2026-10-16 | patch | LRC-LIB-CATALOG-IMPORT: VIDEO records appear in the Videos filter; reimport repairs older classification with edits, memberships and undo preserved (#1940, filter issue only). Status and summary counts unchanged. | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's text detector mask decoder runs on the GPU through wgpu too (with the cached prompt features and the one-pass box bias: a description ~2 s → ~0.5–0.7 s with an RTX 5070); status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's two necks and the text detector's DETR encoder also run on the GPU (wgpu) outside macOS: a photo's analysis ~0.6 s, a description ~2 s on an RTX 5070; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: Run on: Automatic / CPU for AI masks (`segment.settings`), CPU on every platform incl. macOS; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback, the GPU switches), where it runs shows in Settings and `segment.model.status`; 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 (✅) | @@ -1081,3 +1091,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-VIEW-FILMSTRIP, LR-LIB-VIRTUALCOPY, LR-LIB-STACK, LR-LIB-LABEL, LRC-LIB-MISSING: one thumbnail overlay for the justified grid, the square grid and the filmstrip (`thumb.rs`): the filmstrip gains the copy tag, a clickable stack badge, the placeholder, the failure mark and the label dot; the failure mark explains itself on hover; the justified grid's tinted label footer is gone; marks degrade on narrow thumbnails; the rating is read out without an English plural; statuses unchanged (✅) | | 2026-10-17 | minor | LR-PREF-INTERFACE: grid badges set to Stars on hover (the default, formerly "When rated or hovered") keep flags and colour labels on every tile but show the stars and the edited mark only on the hovered or selected photo (before, any rated photo wore the whole badge bar); Always / Never unchanged; 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 | +| 2026-10-17 | minor | LR-BEHAV-DRAGDROP: Esc gives up a photo drag (and only the drag); album rows say how many photos a drop adds or that they are there already (a no-op drop changes nothing); smart albums, album folders and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason; the Keyword List says how many photos get a keyword and refuses a keyword dropped inside itself; LR-LIB-ALBUM and LRC-LIB-KEYWORDS text updated; status unchanged (✅) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02955c52a9..027e0286fe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -94,7 +94,7 @@ search embeddings; generative remove runs in Adobe's cloud. | 2026-10-12 | minor | Epson ERF decoded (raw-parity.md): 240 models verified, 229 preview-only; shares and rounded numbers unchanged | | Subject / Sky / Background masks | classical heuristics; the file's own DNG semantic mattes | 🟡 | | People (faces, body, hair, skin…) and Landscape masks | — | ⬜ | -| Object / Describe masks | SAM 3 in pure Rust (Metal / CPU); opt-in 3.4 GB download, no mirror configured | 🟡 | +| Object / Describe masks | SAM 3 in pure Rust (Metal on macOS; elsewhere the image encoder, necks and text detector's DETR encoder and mask decoder on the GPU through wgpu, the rest of the heads on the CPU, CPU fallback); opt-in 3.4 GB download, no mirror configured | 🟡 | | Depth range mask, Lens Blur | Lens Blur keeps the subject (or any mask, e.g. an Object mask) sharp and blurs the rest with disc bokeh and Boost; no depth map yet, so no focal range or depth range mask | 🟡 | | AI Denoise | Bayer only, built-in classical denoiser out of the box, optional user-installed weights, pure-Rust CPU / GPU | 🟡 | | Raw Details, Super Resolution | — | ⬜ | @@ -309,6 +309,9 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | 2026-10-19 | patch | Stability note: tests run in CI on Linux x64 (every PR) as well as FreeBSD; macOS and Windows remain (gap 9) | | 2026-10-19 | minor | Localization ~55% → ~64% (mean of the 12 key languages): Indonesian (`id`) catalog, every message but What's New; full target 61.2% → 61.5% (still ~61%) | | 2026-10-19 | patch | Platforms: the Windows installer is no longer listed as unverified (the 0.9.1 x64 MSI is tested on Windows 11; a confirmation after uninstalling from Settings → Apps, #892, remains); #790 noted as fixed in 0.9.1; percentages and hours unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's text detector mask decoder also on the GPU outside macOS; status unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's necks and text detector's encoder also on the GPU outside macOS; status unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback); status and numbers unchanged | | 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | | 2026-10-12 | minor | UI/UX remaining 34–58 h → 32–54 h (canvas tools by keyboard); headline numbers unchanged | | 2026-10-14 | minor | Merge and HDR: merge 100% → 88% (LR-MERGE-HDR ✅ → 🟡 after testing on real 67 MP brackets; gap 29); area percentages unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index a3a5d2d120..6cfe0de31f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -171,6 +171,12 @@ - Importing a backup of a catalog you already imported no longer adds every collection a second time: collections are matched by the catalog's own id, which its backups keep, instead of by the catalog file's path. +## 2026-11-04 +### Remote SAM worker recovers from accept errors +- A transient connection-accept error is logged and retried after a short pause, so one failed accept no longer + stops the remote Metal worker (#2574). Startup validation and bind failures still report an error. +### Reference View's empty state paints on every platform +- Its instruction now uses the supported menu arrow symbol, avoiding a missing-glyph panic while the view is drawn. ## 2026-10-30 ### Lightroom catalogs with a print inside a collection import their collections @@ -400,6 +406,14 @@ on macOS 15 and later, and Minimize All, Zoom All and Arrange in Front while Option is held. +## 2026-10-26 + +### Panels come back as they were +- Close Masking, Crop, Remove or Red Eye and the panel you came from is there again, at the same width and scroll + position, and the photo doesn't move; if the panel was hidden, it stays hidden. Pressing a panel key a second time + (I for Info, M for Masking, C for Crop, H for Remove) or its tool-strip button puts back exactly what the right + column showed before: Edit → I → I is Edit again, Masks → I → I is Masks, and a closed panel stays closed. + ## 2026-10-25 ### Import from Folder… offers the photos you browsed in Local @@ -518,6 +532,18 @@ - Folders that could not be listed completely or whose time can't be read, and files you add one by one, are checked as before. +### Drag and drop says what a drop will do +- Photos dragged over an album now say how many a drop adds ("Add 2 photos to “Garden”"), or "Already in “Garden”" + when it holds them all, in which case letting go does nothing at all (no undo step, no message). When some are there + already, the message after the drop says how many. Over the Keyword List, the label says how many photos get the + keyword, or that they all have it. +- Rows that can't take photos now show it instead of staying silent: a smart album, an album folder and the Keywords + in the sidebar show the not-allowed cursor while photos are over them, and letting go says why and where to drop + instead (Edit Smart Album…, an album inside the folder, the Keyword List). +- A keyword dragged over itself or over a keyword inside it shows the not-allowed cursor and says "Can't go inside + itself". +- Esc gives up a drag of photos, as it already did for albums, sidebar sections and keywords: that press ends the drag and does nothing else + (it does not also close a dialog, leave full screen or light back on). A drag started before entering full screen or a slideshow now ends with the mouse button, so Esc works there again. ### A right-click on a text field while you carry photos opens no menu - While you drag photos from the grid, a right-click on a text field, such as the search box, opens no Cut, Copy and Paste menu. Before, the menu opened over the field the photos were on. Right-clicking a field without a drag works @@ -562,7 +588,6 @@ reads them back as the same keywords. A sidecar written by an earlier version is put right the next time it is saved. - ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for @@ -609,6 +634,14 @@ Rating is ≥ 3. Move with the arrow keys". - OK saves the rules in the order shown, in one undo step like any other change to the rules. +### Lightroom catalog import keeps the settings of each history step +- Importing a Lightroom Classic catalog saves its history steps and snapshots in a recovery archive in the library. + For catalogs from Lightroom Classic 13 and later, the archive kept each step's name and date but not its + settings, because those versions store them compressed. They are now decoded and kept. A step whose settings + can't be read is kept without them, with a warning, and the import goes on. +- When an archive with the history settings would be too big (over 32 MiB), it is now saved without them, with a + warning, instead of not at all. + ## 2026-10-23 ### AI Denoise works out of the box @@ -918,6 +951,16 @@ Before, every rated photo wore the badge bar, which in a mostly rated library made it look like Always. Pick and reject flags and colour labels stay on every thumbnail. Always and Never work as before. +### Searching a big library keeps up with your typing +- Typing in the library search stalls less on a library of hundreds of thousands of photos. The search used to + lower-case a photo's file name, title, caption, camera, lens, location, format, every keyword and the names of the + people on its faces again for each photo and each letter you typed. It now keeps that text, makes it the first time + you search, and keeps it up to date as you edit titles, captions, keywords, people and file names. Smart albums with + a Text rule keep their own text the same + way, made the first time such an album is counted or shown. Which photos match is unchanged. On a test library of + 312 000 photos, finding the photos for a word took about 50 ms where it took 120 to 160 ms. The first search makes + the text, which takes a fraction of a second and about 32 MB of memory at that size; a Text rule's text is another + 33 MB. Searches with `camera:`, `lens:` or `name:` gain less (about 70 ms became about 60 ms). ### Selection rings you can see in the light themes - The active photo's white outline vanished on Silver and Paper's light grid, and told the active photo from the other selected ones by lightness alone. Now the active photo has a heavier ring (3 pt, with a thin line against the photo so @@ -1109,6 +1152,17 @@ ## 2026-10-16 +### Dark raws keep their camera's colour and tone +- A raw whose camera JPEG is too dark (or too colourless) to fit a look to no longer drops its camera profile's + colour for the dull neutral fallback: it keeps the profile's colour, with the JPEG's tone curve when one fits, else + the default tone curve. Photos of profiled cameras that were underexposed and pushed back up keep their colour: on + NIKON D780 frames 3.7 EV under with a local profile, from about 40% of the properly exposed frame's colourfulness + to about 95%. +- `lightcraft-cli calibrate` now also learns the camera's tone curve from all the photos it reads, and a profile + made with it carries the curve. A photo of that camera follows its own JPEG's curve as far as that JPEG shows it + and the camera's curve beyond, so an underexposed shot pushed back up matches a properly exposed one in + brightness instead of coming out 4–7 L* darker. Profiles made before keep working; refit them to get the curve. + ### 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