From 53d0a137d045595ff8c494850f8ce9ccf03a3994 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Wed, 4 Nov 2026 23:07:57 +0100 Subject: [PATCH 01/10] LRC-LIB-PEOPLE: persistently ignore and restore selected faces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revive Daniel Spruce’s implementation from #2416 (8b53dad2), ported to current main and catalog format 12. Retain original face data with catalog-only batch history, paginated restoration, redetection suppression and localized review controls. Add migration/replay/compaction, atomic-batch and stale-selection regressions. Validation: cargo xtask ci passed all eight gates on macOS/Apple M2 with Rust 1.95.0 and CRAFT_FONTS_DIR. Synthetic English/German screenshots inspected; contributor tested bulk ignore and repeated detection on real photos. External-data skips documented in the PR. Fixes #1873 Co-Authored-By: Daniel Spruce Assisted-by: OpenAI GPT-6.1 Sol --- crates/catalog/src/journal.rs | 3 +- crates/catalog/src/tests_format_version.rs | 47 ++- crates/engine/src/cmd/face_detect.rs | 17 +- crates/engine/src/cmd/face_recognize.rs | 99 ++++- crates/engine/src/cmd/library/specs.rs | 6 +- crates/engine/src/lib.rs | 51 ++- crates/engine/src/tests/face_recognize.rs | 120 ++++++ crates/engine/src/tests/xmp.rs | 139 +++++++ crates/meta/src/lib.rs | 2 + crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/cs.json | 20 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/de.json | 20 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/es.json | 24 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fi.json | 21 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/fr.json | 20 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/id.json | 23 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/it.json | 20 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ja.json | 24 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/ka.json | 20 +- crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pl.json | 24 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/pt-br.json | 24 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/ru.json | 20 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/sv.json | 21 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/uk.json | 24 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/vi.json | 20 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hans.json | 24 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/locales/zh-hant.json | 24 +- crates/ui-egui/src/app/frame.rs | 8 + crates/ui-egui/src/dialogs/rename.rs | 4 +- crates/ui-egui/src/menus/run.rs | 11 + crates/ui-egui/src/menus/ui_commands.rs | 1 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/ignored_faces.rs | 429 ++++++++++++++++++++ crates/ui-egui/src/panels/people.rs | 14 +- crates/ui-egui/src/panels/person.rs | 280 ++++++++++++- crates/ui-egui/src/panels/unnamed.rs | 22 +- crates/ui-egui/src/state.rs | 6 + crates/ui-egui/src/tests/rename_person.rs | 25 ++ docs/faces.md | 28 ++ docs/gaps.md | 3 + docs/parity-checklist.md | 3 +- docs/whats-new.md | 9 + 58 files changed, 1683 insertions(+), 69 deletions(-) create mode 100644 crates/ui-egui/src/panels/ignored_faces.rs diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index b50a6d52ebf..dc420cfc641 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -54,6 +54,7 @@ //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | //! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) | //! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` | +//! | 12 | persistent ignored faces | `RegionKind::IgnoredFace` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -78,7 +79,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 11; +pub const VERSION: u32 = 12; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index ada41383070..a6f88466603 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -28,6 +28,49 @@ fn snapshot_version(m: &MemStore) -> u64 { v["version"].as_u64().unwrap() } +/// Existing catalogs upgrade before accepting ignored regions, retaining face metadata. +#[test] +fn legacy_faces_upgrade_without_losing_assignments_or_boxes() { + let (mut base, _, _) = legacy_parts(); + let id = base.photos().next().unwrap().id; + let mut meta = base.photo(id).unwrap().meta.clone(); + meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Person".into()), + description: Some("retained".into()), + }]; + base.apply(Op::SetMeta { id, meta: Box::new(meta.clone()) }).unwrap(); + for version in [9, 10, 11] { + let m = MemStore::new(); + m.set( + SNAPSHOT, + format!("{{\"format\":\"lightcraft-catalog\",\"version\":{version},\"seq\":3,\"catalog\":{}}}\n", base.to_snapshot()).into_bytes(), + ); + let (mut journal, mut catalog, report) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(report.upgraded_from, Some(version)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + assert!(snapshot_version(&m) > 11, "older builds must refuse the format before decoding ignored faces"); + assert_eq!(catalog.photo(id).unwrap().meta, meta); + + let mut ignored = meta.clone(); + ignored.regions[0].kind = lightcraft_meta::RegionKind::IgnoredFace; + let op = Op::SetMeta { id, meta: Box::new(ignored.clone()) }; + catalog.apply(op.clone()).unwrap(); + journal.append(&[op]).unwrap(); + drop(journal); + // Both log replay and a subsequent compaction retain the ignored state and metadata. + let (mut journal, reopened, report) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(report.upgraded_from, None); + assert_eq!(report.replayed, 1); + assert_eq!(reopened.photo(id).unwrap().meta, ignored); + journal.snapshot(&reopened).unwrap(); + drop(journal); + let (_, compacted, _) = Journal::open(Box::new(m)).unwrap(); + assert_eq!(compacted.photo(id).unwrap().meta, ignored); + } +} + #[test] fn v1_library_loads_and_is_upgraded() { let (base, log, full) = legacy_parts(); @@ -238,8 +281,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 11; + /// v12: the persisted `RegionKind::IgnoredFace` value in metadata regions. + const NEWEST_FIELDS: u32 = 12; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 711bebb102f..81fa7e03108 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -232,8 +232,9 @@ fn overlaps_existing(f: &Face, regions: &[Region]) -> bool { }) } +/// Recognize replaceable detector results while retaining explicitly ignored regions. pub(crate) fn is_detected(r: &Region) -> bool { - r.description.as_deref().is_some_and(|d| d.starts_with(MARK)) + r.kind != RegionKind::IgnoredFace && r.description.as_deref().is_some_and(|d| d.starts_with(MARK)) } /// The photo as the faces see it: upright, uncropped, default settings, as 8-bit RGB with its size, its long edge at @@ -246,6 +247,7 @@ pub(crate) fn render_rgb(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: Ok((rgb, image.width, image.height)) } +/// Detect selected photos and commit new face regions without automatic sidecar writes. fn detect(s: &mut Session, p: &Value) -> Result { let apply = p.get("apply").and_then(Value::as_bool).unwrap_or(true); let defaults = Options::default(); @@ -290,9 +292,7 @@ fn detect(s: &mut Session, p: &Value) -> Result { } let applied = !ops.is_empty(); if applied { - s.commit("Detect Faces", Op::Batch { ops })?; - // regions are not written to XMP, so a sidecar must not be rewritten for this - s.skip_auto_write = true; + s.commit_catalog_only("Detect Faces", Op::Batch { ops })?; } Ok(json!({"detector": LABEL, "applied": applied, "photos": results, "ms": started.elapsed().as_secs_f64() * 1000.0})) } @@ -331,6 +331,15 @@ mod tests { Region { rect: lightcraft_geom::Rect { x0, y0, x1, y1 }, kind: RegionKind::Face, name: Some("Ann".into()), description: None } } + #[test] + fn ignored_detections_are_retained_and_suppress_overlapping_redetection() { + let mut ignored = region(0.4, 0.2, 0.6, 0.5); + ignored.kind = RegionKind::IgnoredFace; + ignored.description = Some(format!("{MARK}{LABEL}")); + assert!(!is_detected(&ignored)); + assert!(overlaps_existing(&face(0.4, 0.2, 0.6, 0.5), &[ignored])); + } + #[test] fn a_detection_on_an_existing_region_is_not_a_new_face() { let existing = [region(0.40, 0.20, 0.60, 0.50), region(0.10, 0.10, 0.20, 0.20)]; diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index 15519fc7575..52d1b91730f 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -27,6 +27,78 @@ fn name_param(p: &Value, c: &str) -> Result> { Ok(name) } +/// Validate the whole selection before changing its ignored state in one catalog-only undo step. +fn ignore_faces(s: &mut Session, p: &Value) -> Result { + use lightcraft_meta::RegionKind; + const C: &str = "faces.ignore"; + let ignored = match p.get("ignored") { + None => true, + Some(value) => value.as_bool().ok_or_else(|| bad(C, "ignored must be true or false"))?, + }; + let faces = p["faces"].as_array().ok_or_else(|| bad(C, "missing faces"))?; + if faces.is_empty() || faces.len() > 100_000 { + return Err(bad(C, "select between 1 and 100000 faces")); + } + let mut edits: std::collections::BTreeMap = Default::default(); + let mut seen = std::collections::HashSet::new(); + for face in faces { + let id = lightcraft_catalog::PhotoId(face["photo"].as_u64().ok_or_else(|| bad(C, "missing photo"))?); + let index = face["index"].as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "invalid face index"))?; + if !seen.insert((id, index)) { + continue; + } + let photo = s.catalog.photo(id).filter(|p| p.in_library()).ok_or_else(|| bad(C, "photo is no longer in the library"))?; + let region = photo.meta.regions.get(index).ok_or_else(|| bad(C, "face no longer exists"))?; + let expected = if ignored { RegionKind::Face } else { RegionKind::IgnoredFace }; + if region.kind != expected { + return Err(bad(C, "a selected face changed; reload the faces and try again")); + } + if let Some(rect) = face.get("rect") { + let rect: lightcraft_geom::Rect = serde_json::from_value(rect.clone()).map_err(|_| bad(C, "invalid reviewed rectangle"))?; + if rect != region.rect { + return Err(bad(C, "a selected face changed; reload the faces and try again")); + } + } + let meta = edits.entry(id).or_insert_with(|| photo.meta.clone()); + if let Some(region) = meta.regions.get_mut(index) { + region.kind = if ignored { RegionKind::IgnoredFace } else { RegionKind::Face }; + } + } + let count = seen.len(); + s.commit_catalog_only( + if ignored { "Ignore Faces" } else { "Restore Ignored Faces" }, + Op::Batch { ops: edits.into_iter().map(|(id, meta)| Op::SetMeta { id, meta: Box::new(meta) }).collect() }, + )?; + Ok(json!({"changed": count, "ignored": ignored})) +} + +/// List one bounded page of retained ignored regions in catalog order, without a recognition model. +fn ignored_faces(s: &mut Session, p: &Value) -> Result { + const C: &str = "faces.ignored"; + let offset = match p.get("offset") { + None => 0, + Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "offset must be a nonnegative index"))?, + }; + let limit = match p.get("limit") { + None => 1000, + Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "limit must be between 1 and 5000"))?, + }; + if !(1..=5000).contains(&limit) { + return Err(bad(C, "limit must be between 1 and 5000")); + } + let mut faces = Vec::new(); + let mut total = 0usize; + for photo in s.catalog.photos().filter(|p| p.in_library()) { + for (index, region) in photo.meta.regions.iter().enumerate().filter(|(_, r)| r.kind == lightcraft_meta::RegionKind::IgnoredFace) { + if total >= offset && faces.len() < limit { + faces.push(json!({"photo": photo.id.0, "index": index, "rect": region.rect, "view": s.face_view(photo.id, region.rect)})); + } + total = total.saturating_add(1); + } + } + Ok(json!({"total": total, "offset": offset, "faces": faces})) +} + /// Give a face region its name. Naming makes the face yours: a later "Detect Faces" run no longer replaces it. fn apply_name(region: &mut lightcraft_meta::Region, name: &Option) { region.name = name.clone(); @@ -73,8 +145,7 @@ fn name_faces(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "none of those faces exist")); } let photos = ops.len(); - s.commit(if name.is_some() { "Name Faces" } else { "Clear Face Names" }, Op::Batch { ops })?; - s.skip_auto_write = true; + s.commit_catalog_only(if name.is_some() { "Name Faces" } else { "Clear Face Names" }, Op::Batch { ops })?; Ok(json!({"named": named, "photos": photos, "name": name})) } @@ -88,8 +159,7 @@ fn set_name(s: &mut Session, p: &Value) -> Result { let mut meta = s.catalog.photo(id).ok_or_else(|| bad(C, "no such photo"))?.meta.clone(); let region = meta.regions.get_mut(index).ok_or_else(|| bad(C, "no such region"))?; apply_name(region, &name); - s.commit(if name.is_some() { "Name Face" } else { "Clear Face Name" }, Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; + s.commit_catalog_only(if name.is_some() { "Name Face" } else { "Clear Face Name" }, Op::SetMeta { id, meta: Box::new(meta) })?; Ok(json!({"id": id.0, "index": index, "name": name})) } @@ -135,7 +205,7 @@ fn rename_person(s: &mut Session, p: &Value) -> Result { let Some(ph) = s.catalog.photo(id) else { continue }; let mut indexes = Vec::new(); for (i, r) in ph.meta.regions.iter().enumerate() { - if r.kind != lightcraft_meta::RegionKind::Face { + if !matches!(r.kind, lightcraft_meta::RegionKind::Face | lightcraft_meta::RegionKind::IgnoredFace) { continue; } let Some(n) = r.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; @@ -171,8 +241,7 @@ fn rename_person(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("{to} is already another person; pass merge: true to combine them"))); } let photos = ops.len(); - s.commit(if other { "Merge People" } else { "Rename Person" }, Op::Batch { ops })?; - s.skip_auto_write = true; + s.commit_catalog_only(if other { "Merge People" } else { "Rename Person" }, Op::Batch { ops })?; if s.filter.person.as_deref().is_some_and(|n| n.trim().to_lowercase() == from_key) { s.filter.person = Some(to.clone()); } @@ -352,7 +421,7 @@ mod imp { fn needs_search(s: &Session, photo: &Photo) -> bool { photo.in_library() && !photo.is_video() - && !photo.meta.regions.iter().any(|r| r.kind == RegionKind::Face) + && !photo.meta.regions.iter().any(|r| matches!(r.kind, RegionKind::Face | RegionKind::IgnoredFace)) && !s.faces.scanned.contains(photo.id.0) && !s.faces.scan_failed.contains(&photo.id.0) } @@ -383,7 +452,7 @@ mod imp { } let Some(photo) = s.catalog.photo(id) else { return }; // the user (or an import) got there first: leave their faces alone - if photo.meta.regions.iter().any(|r| r.kind == RegionKind::Face) { + if photo.meta.regions.iter().any(|r| matches!(r.kind, RegionKind::Face | RegionKind::IgnoredFace)) { return; } let mut meta = photo.meta.clone(); @@ -1129,8 +1198,20 @@ mod imp { } } +/// Register face review queries and explicit catalog-only identity mutations. pub fn specs() -> Vec { vec![ + cmd!( + "faces.ignore", + "Ignore Faces", + [], + None, + "{faces: [{photo, index, rect?}], ignored?: true} — persistently ignore blurry or false faces, or restore them; one undo step; originals are untouched", + super::always, + ignore_faces + ), + cmd!(query "faces.ignored", "Ignored Faces", [], None, + "{offset?: 0, limit?: 1000} → {total, offset, faces} — review ignored faces in catalog order, including named faces excluded from matching; limit is 1..5000", super::always, ignored_faces), cmd!( "faces.index", "Index Faces", diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b99e97c0548..5eb49be1894 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -614,8 +614,7 @@ pub fn specs() -> Vec { return Err(bad("photo.removeRegion", "no such region")); } let gone = meta.regions.remove(index); - s.commit("Remove Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; + s.commit_catalog_only("Remove Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; Ok(json!({"removed": gone.name})) } ), @@ -648,8 +647,7 @@ pub fn specs() -> Vec { let mut meta = s.catalog.photo(id).ok_or_else(|| bad(C, "no such photo"))?.meta.clone(); let region = meta.regions.get_mut(index).ok_or_else(|| bad(C, "no such region"))?; region.rect = lightcraft_geom::Rect { x0, y0, x1, y1 }; - s.commit("Resize Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; - s.skip_auto_write = true; + s.commit_catalog_only("Resize Face Box", Op::SetMeta { id, meta: Box::new(meta) })?; Ok(json!({"rect": {"x0": x0, "y0": y0, "x1": x1, "y1": y1}})) } ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 704602e4beb..007839c6af2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -136,6 +136,8 @@ pub type Result = std::result::Result; pub struct UndoEntry { pub label: String, pub op: Op, + /// This history step must never automatically write metadata beside the originals. + pub(crate) catalog_only: bool, /// A folder to rename on disk (`from` → `to`) before `op` is applied: Rename / Move Folder /// (whose `op` relinks the photos inside). Never overwrites; refused when `to` exists. An /// empty `to` removes the (empty) folder `from`, an empty `from` creates `to` (Create Folder). @@ -271,9 +273,11 @@ pub struct Session { /// Exact filesystem repairs from discarded history; catalog inverses stay discarded. pub(crate) pending_sidecar_repairs: Vec, pub interaction: Option, - /// Set by a command whose change must not rewrite the photo's XMP sidecar even with auto-write on - /// (a catalog-only edit of data the sidecar writer does not emit); consumed when the command ends. + /// Explicit sidecar suppression for imports/background work; consumed when the command ends. + /// Face history uses catalog_only_changes instead, so mixed commands retain ordinary writes. pub(crate) skip_auto_write: bool, + /// Catalog-only log records emitted within the current outer command (not prior pending work). + catalog_only_changes: usize, /// The order of Reload from Disk runs, so an older one finishing late is dropped ([`cmd::reload`]). pub(crate) reload_tickets: cmd::reload::Tickets, /// Photos whose automatic XMP sidecar write failed (their folder offline, read-only or full), written again by @@ -477,6 +481,7 @@ impl Session { pending_sidecar_repairs: Vec::new(), interaction: None, skip_auto_write: false, + catalog_only_changes: 0, reload_tickets: Default::default(), unsaved_sidecars: Default::default(), denoise: Default::default(), @@ -592,6 +597,8 @@ impl Session { // last-resort guard: a panic in a command is that command's error, not a crash let r = guard::catch(&format!("`{id}`"), || f(self)).unwrap_or_else(|e| Err(EngineError::Other(e))); self.depth -= 1; + // Count caller changes before automatic version bookkeeping adds its own records. + let command_changes = self.pending_log.len().saturating_sub(log_start); if self.depth == 0 && was_active.is_some() && self.active() != was_active { self.previous_active = was_active; if let Some(left) = was_active { @@ -608,7 +615,8 @@ impl Session { } } if self.depth == 0 { - let skip = std::mem::take(&mut self.skip_auto_write); + let catalog_only = std::mem::take(&mut self.catalog_only_changes); + let skip = std::mem::take(&mut self.skip_auto_write) || (catalog_only > 0 && catalog_only == command_changes); if r.is_ok() && !skip && self.xmp.auto_write && self.interaction.is_none() && self.pending_log.len() > log_start { self.auto_write_sidecars_since(log_start); } @@ -643,7 +651,14 @@ impl Session { let fwd = op.clone(); let inv = self.apply_through(op, Catalog::apply_new)?; self.pending_log.push(fwd); - self.undo.push(UndoEntry { label: label.to_string(), op: inv, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }); + self.undo.push(UndoEntry { + label: label.to_string(), + op: inv, + catalog_only: false, + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }); self.commits = self.commits.wrapping_add(1); if self.undo.len() > 1000 { let mut dropped = self.undo.remove(0); @@ -655,6 +670,20 @@ impl Session { Ok(()) } + /// Commit catalog metadata with history that suppresses automatic sidecar writes, + /// including subsequent Undo/Redo, when the whole command is catalog-only. Direct calls + /// do not leak command-scoped suppression. + pub(crate) fn commit_catalog_only(&mut self, label: &str, op: Op) -> Result<()> { + self.commit(label, op)?; + if let Some(entry) = self.undo.last_mut() { + entry.catalog_only = true; + } + if self.depth > 0 { + self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + } + Ok(()) + } + /// [`Catalog::apply`] for what brings back what was (an undo or a redo). fn apply_catalog(&mut self, op: Op) -> Result { self.apply_through(op, Catalog::apply) @@ -767,10 +796,12 @@ impl Session { return; } let tail = self.undo.split_off(self.undo.len() - n); + let catalog_only = tail.iter().all(|entry| entry.catalog_only); let ops = tail.into_iter().rev().map(|e| e.op).collect(); self.undo.push(UndoEntry { label: label.to_string(), op: Op::Batch { ops }, + catalog_only, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -783,10 +814,12 @@ impl Session { Ok(()) } + /// Undo the latest step using the real filesystem; retain the step if applying it fails. pub fn undo_step(&mut self) -> Result { self.undo_step_with(&rename::RealFs) } + /// Undo a catalog/filesystem step while preserving its sidecar-write policy and retry state. pub(crate) fn undo_step_with(&mut self, fs: &dyn rename::MoveFs) -> Result { let mut e = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let redo = match self.apply_with_files(&mut e, fs) { @@ -797,10 +830,14 @@ impl Session { } }; self.show_undone(&e.op); + if self.depth > 0 && e.catalog_only { + self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + } self.pending_log.push(e.op); self.redo.push(UndoEntry { label: e.label.clone(), op: redo, + catalog_only: e.catalog_only, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -808,10 +845,12 @@ impl Session { Ok(e.label) } + /// Redo the latest undone step using the real filesystem without changing its history policy. pub fn redo_step(&mut self) -> Result { self.redo_step_with(&rename::RealFs) } + /// Redo a catalog/filesystem step with the same sidecar-write policy as the original operation. pub(crate) fn redo_step_with(&mut self, fs: &dyn rename::MoveFs) -> Result { let mut e = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let undo = match self.apply_with_files(&mut e, fs) { @@ -822,10 +861,14 @@ impl Session { } }; self.show_undone(&e.op); + if self.depth > 0 && e.catalog_only { + self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + } self.pending_log.push(e.op); self.undo.push(UndoEntry { label: e.label.clone(), op: undo, + catalog_only: e.catalog_only, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), diff --git a/crates/engine/src/tests/face_recognize.rs b/crates/engine/src/tests/face_recognize.rs index f6ca8749403..9d69a3b919d 100644 --- a/crates/engine/src/tests/face_recognize.rs +++ b/crates/engine/src/tests/face_recognize.rs @@ -477,6 +477,104 @@ fn many_faces_are_named_in_one_undo_step() { let _ = std::fs::remove_dir_all(&d); } +/// Ignoring is atomic, persists on reopen and can be restored without a recognition model. +#[test] +fn ignored_faces_survive_reopening_and_can_be_restored() { + let d = temp("ignore"); + let lib = d.join("library"); + let (mut s, _) = setup(&d, 64); + s.open_library(&lib, true).unwrap(); + let (a, b) = two_photos(&s); + set_regions(&mut s, a, vec![region(0.1, Some("Person"))]); + set_regions(&mut s, b, vec![region(0.1, None)]); + s.execute("faces.index", &json!({"budgetMs": 0})).unwrap(); + s.faces.index.insert(a.0, ®ion(0.1, None).rect, unit64(&[(0, 1.0)])); + s.faces.index.insert(b.0, ®ion(0.1, None).rect, unit64(&[(0, 1.0)])); + let faces = json!([{"photo": a.0,"index":0,"rect":region(0.1,None).rect}, {"photo":b.0,"index":0,"rect":region(0.1,None).rect}]); + let before = s.undo.len(); + assert!(s.execute("faces.ignore", &json!({"faces": faces, "ignored": "false"})).is_err()); + let mut stale = faces.clone(); + stale[1]["rect"] = json!(region(0.3, None).rect); + assert!(s.execute("faces.ignore", &json!({"faces":stale})).is_err()); + assert_eq!(s.undo.len(), before); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::Face); + s.execute("faces.ignore", &json!({"faces":faces})).unwrap(); + assert_eq!(s.undo.len(), before + 1); + assert_eq!(s.execute("faces.unnamed", &json!({})).unwrap()["total"], 0); + assert_eq!(s.execute("faces.person", &json!({"name":"Person"})).unwrap()["total"], 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::Face); + s.execute("faces.ignore", &json!({"faces":faces})).unwrap(); + s.close_library().unwrap(); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 2); + s.execute("faces.ignore", &json!({"faces":faces,"ignored":false})).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 0); + let restored = &s.catalog.photo(a).unwrap().meta.regions[0]; + assert_eq!(restored.name.as_deref(), Some("Person")); + assert_eq!(restored.rect, region(0.1, None).rect); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&d); +} + +/// Invalid targets do not partially apply; duplicate targets are one change and one undo step. +#[test] +fn ignoring_a_batch_validates_every_face_and_deduplicates_targets() { + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().unwrap().id; + let regions = vec![region(0.1, None), region(0.4, Some("Person"))]; + set_regions(&mut s, id, regions.clone()); + let before = s.undo.len(); + for params in [ + json!({"faces": []}), + json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": 99}]}), + json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": -1}]}), + json!({"faces": [{"photo": id.0, "index": 0}, {"photo": 987_654, "index": 0}]}), + json!({"faces": [{"photo": id.0, "index": 0}], "ignored": false}), + ] { + assert!(s.execute("faces.ignore", ¶ms).is_err(), "{params}"); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions, regions); + assert_eq!(s.undo.len(), before); + } + let response = s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": 0}]})).unwrap(); + assert_eq!(response["changed"], 1); + assert_eq!(s.undo.len(), before + 1); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions[0].kind, RegionKind::IgnoredFace); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions[1], regions[1]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions, regions); +} + +/// Multiple valid ignore batches can exceed the old whole-library cap; every page stays available. +#[test] +fn ignored_faces_pages_beyond_100000_and_uses_indexed_views() { + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().unwrap().id; + let loose = region(0.1, None).rect; + let tight = region(0.2, None).rect; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions = vec![Region { rect: loose, kind: RegionKind::IgnoredFace, name: None, description: None }; 100_001]; + s.catalog.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + s.faces.index.insert_with_view(id.0, &loose, unit64(&[(0, 1.0)]), &tight); + + let first = s.execute("faces.ignored", &json!({"limit": 2})).unwrap(); + assert_eq!(first["total"], 100_001); + assert_eq!(first["offset"], 0); + assert_eq!(first["faces"].as_array().unwrap().len(), 2); + assert_eq!(first["faces"][0]["rect"], json!(loose)); + assert_eq!(first["faces"][0]["view"], json!(tight)); + let last = s.execute("faces.ignored", &json!({"offset": 100_000, "limit": 2})).unwrap(); + assert_eq!(last["total"], 100_001); + assert_eq!(last["faces"].as_array().unwrap().len(), 1); + assert_eq!(last["faces"][0]["index"], 100_000); + assert!(s.execute("faces.ignored", &json!({"offset": 100_001})).unwrap()["faces"].as_array().unwrap().is_empty()); + for params in [json!({"limit": 0}), json!({"limit": 5001}), json!({"limit": -1}), json!({"offset": -1})] { + assert!(s.execute("faces.ignored", ¶ms).is_err(), "{params}"); + } +} + #[test] fn unnamed_faces_come_with_look_alikes_together_and_the_name_the_named_ones_suggest() { let d = temp("unnamed"); @@ -691,3 +789,25 @@ fn rename_person_covers_more_than_the_person_query_and_rejects_bad_input() { assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].name.as_deref(), Some("Bea")); assert_eq!(s.catalog.photo(local).unwrap().meta.regions[0].name.as_deref(), Some("Ada")); } + +/// Retained assignments follow renames and merges while their regions remain ignored. +#[test] +fn ignored_assignments_follow_person_renames_and_merges_without_restoring_faces() { + let mut s = Session::with_demo(); + let (a, b) = two_photos(&s); + set_regions(&mut s, a, vec![region(0.1, Some("Ann"))]); + set_regions(&mut s, b, vec![region(0.1, Some("Ann")), region(0.5, Some("Bea"))]); + let face = json!([{ "photo": a.0, "index": 0 }]); + s.execute("faces.ignore", &json!({"faces": face})).unwrap(); + s.execute("faces.renamePerson", &json!({"from": "Ann", "to": "Ada"})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::IgnoredFace); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].name.as_deref(), Some("Ada")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].name.as_deref(), Some("Ann")); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.execute("faces.renamePerson", &json!({"from": "Ada", "to": "Bea"})).is_err()); + s.execute("faces.renamePerson", &json!({"from": "Ada", "to": "Bea", "merge": true})).unwrap(); + s.execute("faces.ignore", &json!({"faces": face, "ignored": false})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].name.as_deref(), Some("Bea")); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::Face); +} diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index a9314c21738..fa05a60ed24 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -75,6 +75,145 @@ fn only(s: &Session) -> PhotoId { s.catalog.photos().next().unwrap().id } +/// Face metadata history preserves original bytes, sidecars and every developed-state marker. +#[test] +fn face_history_never_writes_sidecars_or_marks_photos_edited() { + use lightcraft_meta::{Region, RegionKind}; + let src = temp_dir("face-history"); + for (file, seed) in [("a.png", 3), ("b.png", 9)] { + write_png(&src.join(file), seed); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let mut ids: Vec<_> = s.catalog.photos().map(|p| p.id).collect(); + ids.sort(); + assert_eq!(ids.len(), 2, "the bulk fixture must contain distinct photo contents"); + let rect = lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }; + for id in &ids { + let mut meta = s.catalog.photo(*id).unwrap().meta.clone(); + meta.regions = vec![Region { rect, kind: RegionKind::Face, name: None, description: None }]; + s.commit("setup", lightcraft_catalog::Op::SetMeta { id: *id, meta: Box::new(meta) }).unwrap(); + } + s.execute("photo.saveMetadataToFile", &json!({"ids":[ids[0].0]})).unwrap(); + let sidecar = src.join("a.xmp"); + let bytes = std::fs::read(&sidecar).unwrap(); + let originals: Vec<_> = ["a.png", "b.png"].iter().map(|n| std::fs::read(src.join(n)).unwrap()).collect(); + s.execute("library.xmpPreferences", &json!({"autoWrite":true})).unwrap(); + let faces: Vec<_> = ids.iter().map(|id| json!({"photo":id.0,"index":0})).collect(); + for (command, params) in [ + ("faces.nameFaces", json!({"faces":faces,"name":"Person"})), + ("faces.ignore", json!({"faces":faces})), + ("faces.ignore", json!({"faces":faces,"ignored":false})), + ("faces.renamePerson", json!({"from":"Person","to":"Renamed"})), + ("faces.nameFaces", json!({"faces":faces,"name":null})), + ("faces.setName", json!({"id":ids[0].0,"index":0,"name":"One"})), + ("photo.setRegion", json!({"id":ids[0].0,"index":0,"rect":{"x0":0.2,"y0":0.2,"x1":0.5,"y1":0.5}})), + ("photo.removeRegion", json!({"id":ids[0].0,"index":0})), + ] { + s.execute(command, ¶ms).unwrap(); + for history in [None, Some("edit.undo"), Some("edit.redo")] { + if let Some(history) = history { + s.execute(history, &json!({})).unwrap(); + } + assert_eq!(std::fs::read(&sidecar).unwrap(), bytes, "{command} {history:?}"); + assert!(!src.join("b.xmp").exists(), "{command} {history:?}"); + for (i, id) in ids.iter().enumerate() { + let p = s.catalog.photo(*id).unwrap(); + assert!(!p.is_edited()); + assert!(p.edited.is_none()); + assert!(p.history.is_empty()); + assert!(p.versions.is_empty()); + assert_eq!(std::fs::read(src.join(if i == 0 { "a.png" } else { "b.png" })).unwrap(), originals[i]); + } + } + } + // Merging a catalog-only face step with a normal rating step must still allow XMP writes. + s.execute("photo.rate", &json!({"ids":[ids[0].0],"rating":5})).unwrap(); + s.merge_undo(2, "mixed metadata"); + assert!(!s.undo.last().unwrap().catalog_only); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(ids[0]).unwrap().rating, 0); + let packet = std::fs::read_to_string(&sidecar).unwrap(); + assert!(packet.contains("0")); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(std::fs::read_to_string(&sidecar).unwrap().contains("5")); + // Direct history API calls must not leave a suppression flag for an unrelated next command. + s.execute("faces.setName", &json!({"id":ids[1].0,"index":0,"name":"Direct"})).unwrap(); + s.undo_step().unwrap(); + s.execute("photo.rate", &json!({"ids":[ids[1].0],"rating":3})).unwrap(); + assert!(src.join("b.xmp").is_file()); + let _ = std::fs::remove_dir_all(src); +} + +/// A nested face edit/history step must not suppress an ordinary change in either order. +#[test] +fn mixed_face_commands_preserve_ordinary_sidecar_writes() { + use lightcraft_catalog::Op; + use lightcraft_meta::{Region, RegionKind}; + for (case, action) in ["faces.ignore", "edit.undo", "edit.redo"].into_iter().enumerate() { + for ordinary_first in [false, true] { + let src = temp_dir(&format!("mixed-face-{case}-{ordinary_first}")); + write_png(&src.join("face.png"), 7); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = only(&s); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.regions = vec![Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }, + kind: RegionKind::Face, + name: None, + description: None, + }]; + s.commit("setup", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let faces = json!({"faces": [{"photo": id.0, "index": 0}]}); + if action != "faces.ignore" { + s.execute("faces.ignore", &faces).unwrap(); + } + if action == "edit.redo" { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + s.execute_fn("mixed face and rating", |s| { + // System metadata preserves the history stack needed by Undo/Redo; the face + // edit cases also cover ordinary undoable commits inside execute_fn. + let ordinary = |s: &mut Session| { + let op = Op::SetRating { id, rating: 5 }; + if action == "faces.ignore" { s.commit("rating", op) } else { s.apply_system(op) } + }; + if ordinary_first { + ordinary(s)?; + } + let empty = json!({}); + s.execute(action, if action == "faces.ignore" { &faces } else { &empty })?; + s.execute("faces.ignored", &json!({}))?; + if !ordinary_first { + ordinary(s)?; + } + Ok(json!({})) + }) + .unwrap(); + let sidecar = src.join("face.xmp"); + let packet = std::fs::read(&sidecar).unwrap(); + assert!(String::from_utf8_lossy(&packet).contains("5"), "{action}, first={ordinary_first}"); + let ignored = s.catalog.photo(id).unwrap().meta.regions[0].kind == RegionKind::IgnoredFace; + assert_eq!(ignored, action != "edit.undo"); + // Several nested catalog-only records still suppress writes, and neither policy + // leaks into a later outer command. + s.execute_fn("only face changes", |s| { + for state in [!ignored, ignored] { + s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}], "ignored": state}))?; + } + Ok(json!({})) + }) + .unwrap(); + assert_eq!(std::fs::read(&sidecar).unwrap(), packet); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": 3})).unwrap(); + assert!(std::fs::read_to_string(&sidecar).unwrap().contains("3")); + let _ = std::fs::remove_dir_all(src); + } + } +} + #[test] fn save_delete_library_reimport_restores_edits() { let src = temp_dir("roundtrip-src"); diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index a6c36bb8463..c748d52ba05 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -76,6 +76,8 @@ pub struct Region { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum RegionKind { Face, + /// Explicitly ignored in the catalog; kept to prevent redetection and allow restoration. + IgnoredFace, Pet, Focus, BarCode, diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index e65ad627ef8..bb80216f7ec 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}", "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", "{name} is installed": "{name} je nainstalován", - "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto" + "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto", + "Ignored faces: {total} · Selected: {selected}": "Ignorované obličeje: {total} · Vybráno: {selected}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 0b142df5e6f..7343d0be19e 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2457,5 +2457,23 @@ "Set up name suggestions…": "Nastavit návrhy jmen…", "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", - "Bottom bar": "Dolní lišta" + "Bottom bar": "Dolní lišta", + "Ignored faces": "Ignorované obličeje", + "Ignored faces…": "Ignorované obličeje…", + "Ignored Faces": "Ignorované obličeje", + "Refresh ignored faces": "Obnovit seznam ignorovaných obličejů", + "Clear selection": "Zrušit výběr", + "Restore selected faces": "Obnovit vybrané obličeje", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Kliknutím vyberete obličeje nebo zrušíte výběr. Shift-kliknutí rozšíří akci na rozsah. Obnovení zachová původní jméno a rámeček.", + "No ignored faces.": "Žádné ignorované obličeje.", + "Ignored face": "Ignorovaný obličej", + "✓ Selected": "✓ Vybráno", + "Not selected": "Nevybráno", + "Done selecting": "Dokončit výběr", + "Select faces…": "Vybrat obličeje…", + "Ignore selected faces": "Ignorovat vybrané obličeje", + "Ignore face (blurry / not a face)": "Ignorovat obličej (rozmazaný / není obličej)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Kliknutím vyberete obličeje nebo zrušíte výběr. Shift-kliknutí rozšíří akci na rozsah. Dvojitým kliknutím otevřete fotografii.", + "Ignore Faces": "Ignorovat obličeje", + "Restore Ignored Faces": "Obnovit ignorované obličeje" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 70ced171146..225bb272965 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Die Bereichsanordnung konnte nicht wiederhergestellt werden: {error}", "Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}", "{name} is installed": "{name} ist installiert", - "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet" + "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet", + "Ignored faces: {total} · Selected: {selected}": "Ignorierte Gesichter: {total} · Ausgewählt: {selected}" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 552ce68016c..32e499aa78d 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3489,5 +3489,23 @@ "Top bar": "Obere Leiste", "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "Ignored faces": "Ignorierte Gesichter", + "Ignored faces…": "Ignorierte Gesichter…", + "Ignored Faces": "Ignorierte Gesichter", + "Refresh ignored faces": "Ignorierte Gesichter aktualisieren", + "Clear selection": "Auswahl aufheben", + "Restore selected faces": "Ausgewählte Gesichter wiederherstellen", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Gesichter durch Klicken auswählen oder abwählen. Umschalt-Klick erweitert die Aktion auf einen Bereich. Beim Wiederherstellen bleiben Name und Rahmen erhalten.", + "No ignored faces.": "Keine ignorierten Gesichter.", + "Ignored face": "Ignoriertes Gesicht", + "✓ Selected": "✓ Ausgewählt", + "Not selected": "Nicht ausgewählt", + "Done selecting": "Auswahl beenden", + "Select faces…": "Gesichter auswählen…", + "Ignore selected faces": "Ausgewählte Gesichter ignorieren", + "Ignore face (blurry / not a face)": "Gesicht ignorieren (unscharf / kein Gesicht)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Gesichter durch Klicken auswählen oder abwählen. Umschalt-Klick erweitert die Aktion auf einen Bereich. Ein Doppelklick öffnet ein Foto.", + "Ignore Faces": "Gesichter ignorieren", + "Restore Ignored Faces": "Ignorierte Gesichter wiederherstellen" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 7b697e946bc..a931a1222fc 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "No se pudo restablecer la disposición de paneles: {error}", "Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}", "{name} is installed": "{name} está instalado", - "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado" + "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado", + "Ignored faces: {total} · Selected: {selected}": "Rostros ignorados: {total} · Seleccionados: {selected}" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b82a2612565..5234bb52390 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2409,5 +2409,27 @@ "Top bar": "Barra superior", "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "Ignored faces": "Rostros ignorados", + "Previous page": "Página anterior", + "Next page": "Página siguiente", + "Page": "Página", + "Ignored faces…": "Rostros ignorados…", + "Ignored Faces": "Rostros ignorados", + "Refresh ignored faces": "Actualizar rostros ignorados", + "Select all": "Seleccionar todo", + "Clear selection": "Borrar selección", + "Restore selected faces": "Restaurar rostros seleccionados", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Haz clic para seleccionar o deseleccionar rostros. Mayús-clic extiende la acción a un intervalo. Al restaurar se conservan el nombre y el recuadro originales.", + "No ignored faces.": "No hay rostros ignorados.", + "Ignored face": "Rostro ignorado", + "✓ Selected": "✓ Seleccionado", + "Not selected": "No seleccionado", + "Done selecting": "Terminar selección", + "Select faces…": "Seleccionar rostros…", + "Ignore selected faces": "Ignorar rostros seleccionados", + "Ignore face (blurry / not a face)": "Ignorar rostro (borroso / no es un rostro)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Haz clic para seleccionar o deseleccionar rostros. Mayús-clic extiende la acción a un intervalo. Haz doble clic para abrir una foto.", + "Ignore Faces": "Ignorar rostros", + "Restore Ignored Faces": "Restaurar rostros ignorados" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 720519a1cc8..24e95764436 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -317,5 +317,6 @@ "Panel layout could not be restored: {error}": "Paneelien asettelua ei voitu palauttaa: {error}", "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", "{name} is installed": "{name} on asennettu", - "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä" + "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä", + "Ignored faces: {total} · Selected: {selected}": "Ohitetut kasvot: {total} · Valittu: {selected}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index df80342abe7..92bacf8f39c 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2368,5 +2368,24 @@ "Set up name suggestions…": "Määritä nimiehdotukset…", "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", - "Bottom bar": "Alapalkki" + "Bottom bar": "Alapalkki", + "Ignored faces": "Ohitetut kasvot", + "Select all": "Valitse kaikki", + "Ignored faces…": "Ohitetut kasvot…", + "Ignored Faces": "Ohitetut kasvot", + "Refresh ignored faces": "Päivitä ohitetut kasvot", + "Clear selection": "Tyhjennä valinta", + "Restore selected faces": "Palauta valitut kasvot", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Valitse kasvot tai poista valinta napsauttamalla. Vaihto-napsautus laajentaa toiminnon alueelle. Palauttaminen säilyttää alkuperäisen nimen ja kehyksen.", + "No ignored faces.": "Ei ohitettuja kasvoja.", + "Ignored face": "Ohitetut kasvot", + "✓ Selected": "✓ Valittu", + "Not selected": "Ei valittu", + "Done selecting": "Lopeta valitseminen", + "Select faces…": "Valitse kasvot…", + "Ignore selected faces": "Ohita valitut kasvot", + "Ignore face (blurry / not a face)": "Ohita kasvot (epätarkat / eivät kasvot)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Valitse kasvot tai poista valinta napsauttamalla. Vaihto-napsautus laajentaa toiminnon alueelle. Kaksoisnapsautus avaa kuvan.", + "Ignore Faces": "Ohita kasvot", + "Restore Ignored Faces": "Palauta ohitetut kasvot" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 3aa21669713..34ba746bc4a 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "La disposition des panneaux n'a pas pu être restaurée : {error}", "Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}", "{name} is installed": "{name} est installé", - "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée" + "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée", + "Ignored faces: {total} · Selected: {selected}": "Visages ignorés : {total} · Sélectionnés : {selected}" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index e513e217def..a9920919528 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3592,5 +3592,23 @@ "Top bar": "Barre supérieure", "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "Ignored faces": "Visages ignorés", + "Ignored faces…": "Visages ignorés…", + "Ignored Faces": "Visages ignorés", + "Refresh ignored faces": "Actualiser les visages ignorés", + "Clear selection": "Effacer la sélection", + "Restore selected faces": "Restaurer les visages sélectionnés", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Cliquez pour sélectionner ou désélectionner des visages. Maj-clic étend cette action à une plage. La restauration conserve le nom et le cadre d’origine.", + "No ignored faces.": "Aucun visage ignoré.", + "Ignored face": "Visage ignoré", + "✓ Selected": "✓ Sélectionné", + "Not selected": "Non sélectionné", + "Done selecting": "Terminer la sélection", + "Select faces…": "Sélectionner des visages…", + "Ignore selected faces": "Ignorer les visages sélectionnés", + "Ignore face (blurry / not a face)": "Ignorer le visage (flou / faux visage)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Cliquez pour sélectionner ou désélectionner des visages. Maj-clic étend cette action à une plage. Un double-clic ouvre une photo.", + "Ignore Faces": "Ignorer les visages", + "Restore Ignored Faces": "Restaurer les visages ignorés" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22eb2d49e3c..35e7cd36a39 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -320,5 +320,6 @@ "{name} is installed and in use: face recognition is on": "{name} sudah terinstal dan digunakan: pengenalan wajah aktif", "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}", + "Ignored faces: {total} · Selected: {selected}": "Wajah yang diabaikan: {total} · Dipilih: {selected}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 7f5e56e1cec..63934940a49 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2382,5 +2382,26 @@ "Set up name suggestions…": "Siapkan saran nama…", "Top bar": "Bilah atas", "Tool strip": "Bilah alat", - "Bottom bar": "Bilah bawah" + "Bottom bar": "Bilah bawah", + "Ignored faces": "Wajah yang diabaikan", + "Previous page": "Halaman sebelumnya", + "Next page": "Halaman berikutnya", + "Page": "Halaman", + "Ignored faces…": "Wajah yang diabaikan…", + "Ignored Faces": "Wajah yang Diabaikan", + "Refresh ignored faces": "Segarkan wajah yang diabaikan", + "Clear selection": "Hapus pilihan", + "Restore selected faces": "Pulihkan wajah yang dipilih", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Klik wajah untuk memilih atau membatalkan pilihan. Shift-klik memperluas tindakan ke suatu rentang. Pemulihan mempertahankan nama dan kotak asli.", + "No ignored faces.": "Tidak ada wajah yang diabaikan.", + "Ignored face": "Wajah yang diabaikan", + "✓ Selected": "✓ Dipilih", + "Not selected": "Tidak dipilih", + "Done selecting": "Selesai memilih", + "Select faces…": "Pilih wajah…", + "Ignore selected faces": "Abaikan wajah yang dipilih", + "Ignore face (blurry / not a face)": "Abaikan wajah (buram / bukan wajah)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Klik wajah untuk memilih atau membatalkan pilihan. Shift-klik memperluas tindakan ke suatu rentang. Klik dua kali membuka foto.", + "Ignore Faces": "Abaikan Wajah", + "Restore Ignored Faces": "Pulihkan Wajah yang Diabaikan" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 729c27a0f19..a6ff1de3b86 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Non è stato possibile ripristinare la disposizione dei pannelli: {error}", "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", "{name} is installed": "{name} è installato", - "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo" + "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo", + "Ignored faces: {total} · Selected: {selected}": "Volti ignorati: {total} · Selezionati: {selected}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index c77a85b41f4..8d7c6f9ae56 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2575,5 +2575,23 @@ "Unit": "Unità", "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", - "Bottom bar": "Barra inferiore" + "Bottom bar": "Barra inferiore", + "Ignored faces": "Volti ignorati", + "Ignored faces…": "Volti ignorati…", + "Ignored Faces": "Volti ignorati", + "Refresh ignored faces": "Aggiorna volti ignorati", + "Clear selection": "Cancella selezione", + "Restore selected faces": "Ripristina volti selezionati", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Fai clic per selezionare o deselezionare i volti. Maiusc-clic estende l’azione a un intervallo. Il ripristino mantiene il nome e il riquadro originali.", + "No ignored faces.": "Nessun volto ignorato.", + "Ignored face": "Volto ignorato", + "✓ Selected": "✓ Selezionato", + "Not selected": "Non selezionato", + "Done selecting": "Termina selezione", + "Select faces…": "Seleziona volti…", + "Ignore selected faces": "Ignora volti selezionati", + "Ignore face (blurry / not a face)": "Ignora volto (sfocato / non è un volto)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Fai clic per selezionare o deselezionare i volti. Maiusc-clic estende l’azione a un intervallo. Un doppio clic apre una foto.", + "Ignore Faces": "Ignora volti", + "Restore Ignored Faces": "Ripristina volti ignorati" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index b25ef539782..f841a6c21a1 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "パネル配置を復元できませんでした:{error}", "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", "{name} is installed": "{name} をインストールしました", - "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです" + "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", + "Ignored faces: {total} · Selected: {selected}": "無視した顔: {total} · 選択済み: {selected}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 72ed66ad206..c2560284682 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2407,5 +2407,27 @@ "Top bar": "上部バー", "Tool strip": "ツールバー", "Bottom bar": "下部バー", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "Ignored faces": "無視した顔", + "Previous page": "前のページ", + "Next page": "次のページ", + "Page": "ページ", + "Ignored faces…": "無視した顔…", + "Ignored Faces": "無視した顔", + "Refresh ignored faces": "無視した顔を更新", + "Select all": "すべて選択", + "Clear selection": "選択を解除", + "Restore selected faces": "選択した顔を復元", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "クリックで顔を選択または選択解除します。Shiftキーを押しながらクリックすると範囲に適用します。復元すると元の名前と枠が保持されます。", + "No ignored faces.": "無視した顔はありません。", + "Ignored face": "無視した顔", + "✓ Selected": "✓ 選択済み", + "Not selected": "未選択", + "Done selecting": "選択を終了", + "Select faces…": "顔を選択…", + "Ignore selected faces": "選択した顔を無視", + "Ignore face (blurry / not a face)": "顔を無視(ぼやけている/顔ではない)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "クリックで顔を選択または選択解除します。Shiftキーを押しながらクリックすると範囲に適用します。ダブルクリックで写真を開きます。", + "Ignore Faces": "顔を無視", + "Restore Ignored Faces": "無視した顔を復元" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 612178c0e83..de6f69d2293 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -323,5 +323,6 @@ "Panel layout could not be restored: {error}": "პანელების განლაგების აღდგენა ვერ მოხერხდა: {error}", "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", - "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია" + "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "Ignored faces: {total} · Selected: {selected}": "უგულებელყოფილი სახეები: {total} · მონიშნული: {selected}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e9d0ba8b055..12e49ead215 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3678,5 +3678,23 @@ "Top bar": "ზედა ზოლი", "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "Ignored faces": "უგულებელყოფილი სახეები", + "Ignored faces…": "უგულებელყოფილი სახეები…", + "Ignored Faces": "უგულებელყოფილი სახეები", + "Refresh ignored faces": "უგულებელყოფილი სახეების განახლება", + "Clear selection": "მონიშვნის გასუფთავება", + "Restore selected faces": "მონიშნული სახეების აღდგენა", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "დააწკაპუნეთ სახის მოსანიშნად ან მონიშვნის გასაუქმებლად. Shift-დაწკაპუნება მოქმედებას დიაპაზონზე ავრცელებს. აღდგენა თავდაპირველ სახელსა და ჩარჩოს ინარჩუნებს.", + "No ignored faces.": "უგულებელყოფილი სახეები არ არის.", + "Ignored face": "უგულებელყოფილი სახე", + "✓ Selected": "✓ მონიშნულია", + "Not selected": "არ არის მონიშნული", + "Done selecting": "მონიშვნის დასრულება", + "Select faces…": "სახეების მონიშვნა…", + "Ignore selected faces": "მონიშნული სახეების უგულებელყოფა", + "Ignore face (blurry / not a face)": "სახის უგულებელყოფა (ბუნდოვანია / სახე არ არის)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "დააწკაპუნეთ სახის მოსანიშნად ან მონიშვნის გასაუქმებლად. Shift-დაწკაპუნება მოქმედებას დიაპაზონზე ავრცელებს. ორმაგი დაწკაპუნება ფოტოს ხსნის.", + "Ignore Faces": "სახეების უგულებელყოფა", + "Restore Ignored Faces": "უგულებელყოფილი სახეების აღდგენა" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e5d3e8d068c..a9164d30f0c 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Nie udało się przywrócić układu paneli: {error}", "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", "{name} is installed": "{name} jest zainstalowany", - "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone" + "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone", + "Ignored faces: {total} · Selected: {selected}": "Ignorowane twarze: {total} · Zaznaczone: {selected}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 6d1eeb7dadf..0b3dfbc1e18 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2334,5 +2334,27 @@ "Set up name suggestions…": "Skonfiguruj propozycje imion…", "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", - "Bottom bar": "Dolny pasek" + "Bottom bar": "Dolny pasek", + "Ignored faces": "Ignorowane twarze", + "Previous page": "Poprzednia strona", + "Next page": "Następna strona", + "Page": "Strona", + "Ignored faces…": "Ignorowane twarze…", + "Ignored Faces": "Ignorowane twarze", + "Refresh ignored faces": "Odśwież ignorowane twarze", + "Select all": "Zaznacz wszystko", + "Clear selection": "Wyczyść zaznaczenie", + "Restore selected faces": "Przywróć zaznaczone twarze", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Kliknij, aby zaznaczyć twarze lub usunąć zaznaczenie. Shift-kliknięcie rozszerza działanie na zakres. Przywrócenie zachowuje pierwotną nazwę i ramkę.", + "No ignored faces.": "Brak ignorowanych twarzy.", + "Ignored face": "Ignorowana twarz", + "✓ Selected": "✓ Zaznaczono", + "Not selected": "Nie zaznaczono", + "Done selecting": "Zakończ zaznaczanie", + "Select faces…": "Zaznacz twarze…", + "Ignore selected faces": "Ignoruj zaznaczone twarze", + "Ignore face (blurry / not a face)": "Ignoruj twarz (rozmyta / nie jest twarzą)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Kliknij, aby zaznaczyć twarze lub usunąć zaznaczenie. Shift-kliknięcie rozszerza działanie na zakres. Dwukrotne kliknięcie otwiera zdjęcie.", + "Ignore Faces": "Ignoruj twarze", + "Restore Ignored Faces": "Przywróć ignorowane twarze" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 83d5a37518e..1b7a8c8f09e 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Não foi possível restaurar a disposição dos painéis: {error}", "Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}", "{name} is installed": "{name} está instalado", - "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado" + "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado", + "Ignored faces: {total} · Selected: {selected}": "Rostos ignorados: {total} · Selecionados: {selected}" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 821bc56ff3c..74bef577142 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2253,5 +2253,27 @@ "Top bar": "Barra superior", "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "Ignored faces": "Rostos ignorados", + "Previous page": "Página anterior", + "Next page": "Próxima página", + "Page": "Página", + "Ignored faces…": "Rostos ignorados…", + "Ignored Faces": "Rostos ignorados", + "Refresh ignored faces": "Atualizar rostos ignorados", + "Select all": "Selecionar tudo", + "Clear selection": "Limpar seleção", + "Restore selected faces": "Restaurar rostos selecionados", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Clique para selecionar ou desmarcar rostos. Shift-clique estende a ação a um intervalo. A restauração mantém o nome e a caixa originais.", + "No ignored faces.": "Nenhum rosto ignorado.", + "Ignored face": "Rosto ignorado", + "✓ Selected": "✓ Selecionado", + "Not selected": "Não selecionado", + "Done selecting": "Concluir seleção", + "Select faces…": "Selecionar rostos…", + "Ignore selected faces": "Ignorar rostos selecionados", + "Ignore face (blurry / not a face)": "Ignorar rosto (desfocado / não é um rosto)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Clique para selecionar ou desmarcar rostos. Shift-clique estende a ação a um intervalo. Um clique duplo abre uma foto.", + "Ignore Faces": "Ignorar rostos", + "Restore Ignored Faces": "Restaurar rostos ignorados" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 02f8126d966..8d96ed8215b 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Не удалось восстановить расположение панелей: {error}", "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", "{name} is installed": "Модель {name} установлена", - "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено" + "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", + "Ignored faces: {total} · Selected: {selected}": "Игнорируемые лица: {total} · Выбрано: {selected}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index db51744bfa9..c7ce556e60d 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2615,5 +2615,23 @@ "Top bar": "Верхняя панель", "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "Ignored faces": "Игнорируемые лица", + "Ignored faces…": "Игнорируемые лица…", + "Ignored Faces": "Игнорируемые лица", + "Refresh ignored faces": "Обновить игнорируемые лица", + "Clear selection": "Снять выделение", + "Restore selected faces": "Восстановить выбранные лица", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Нажмите, чтобы выбрать лицо или снять выделение. Shift и щелчок расширяют действие на диапазон. Восстановление сохраняет исходные имя и рамку.", + "No ignored faces.": "Нет игнорируемых лиц.", + "Ignored face": "Игнорируемое лицо", + "✓ Selected": "✓ Выбрано", + "Not selected": "Не выбрано", + "Done selecting": "Завершить выбор", + "Select faces…": "Выбрать лица…", + "Ignore selected faces": "Игнорировать выбранные лица", + "Ignore face (blurry / not a face)": "Игнорировать лицо (размыто / не лицо)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Нажмите, чтобы выбрать лицо или снять выделение. Shift и щелчок расширяют действие на диапазон. Двойной щелчок открывает фото.", + "Ignore Faces": "Игнорировать лица", + "Restore Ignored Faces": "Восстановить игнорируемые лица" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b2..899c829ed0f 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -320,5 +320,6 @@ "{name} is installed and in use: face recognition is on": "{name} är installerad och används: ansiktsigenkänning är på", "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", - "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}" + "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}", + "Ignored faces: {total} · Selected: {selected}": "Ignorerade ansikten: {total} · Markerade: {selected}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 4c4267d5231..3103ad09c50 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2471,5 +2471,24 @@ "The Tags button lists placeholders for the template, such as {date} or {seq}. Each file is renamed on disk along with its XMP sidecar; a name that is taken gets -1, -2…": "Knappen Taggar visar platshållare för mallen, till exempel {date} eller {seq}. Varje fil byter namn på disken tillsammans med sin XMP-sidofil; ett namn som redan finns får -1, -2…", "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", - "Bottom bar": "Nedre fältet" + "Bottom bar": "Nedre fältet", + "Ignored faces": "Ignorerade ansikten", + "Page": "Sida", + "Ignored faces…": "Ignorerade ansikten…", + "Ignored Faces": "Ignorerade ansikten", + "Refresh ignored faces": "Uppdatera ignorerade ansikten", + "Clear selection": "Rensa markering", + "Restore selected faces": "Återställ markerade ansikten", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Klicka på ansikten för att markera eller avmarkera. Skift-klick utökar åtgärden till ett intervall. Återställning behåller det ursprungliga namnet och rutan.", + "No ignored faces.": "Inga ignorerade ansikten.", + "Ignored face": "Ignorerat ansikte", + "✓ Selected": "✓ Markerat", + "Not selected": "Inte markerat", + "Done selecting": "Klar med markering", + "Select faces…": "Markera ansikten…", + "Ignore selected faces": "Ignorera markerade ansikten", + "Ignore face (blurry / not a face)": "Ignorera ansikte (suddigt / inte ett ansikte)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Klicka på ansikten för att markera eller avmarkera. Skift-klick utökar åtgärden till ett intervall. Dubbelklick öppnar ett foto.", + "Ignore Faces": "Ignorera ansikten", + "Restore Ignored Faces": "Återställ ignorerade ansikten" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 1bdab6dc342..73571f92990 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "Не вдалося відновити розташування панелей: {error}", "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", "{name} is installed": "{name} установлено", - "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено" + "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", + "Ignored faces: {total} · Selected: {selected}": "Ігноровані обличчя: {total} · Вибрано: {selected}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 085be4f7e42..b8de0aa16f3 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2405,5 +2405,27 @@ "Top bar": "Верхня панель", "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "Ignored faces": "Ігноровані обличчя", + "Previous page": "Попередня сторінка", + "Next page": "Наступна сторінка", + "Page": "Сторінка", + "Ignored faces…": "Ігноровані обличчя…", + "Ignored Faces": "Ігноровані обличчя", + "Refresh ignored faces": "Оновити ігноровані обличчя", + "Select all": "Вибрати все", + "Clear selection": "Скасувати вибір", + "Restore selected faces": "Відновити вибрані обличчя", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Натисніть, щоб вибрати обличчя або скасувати вибір. Shift-клацання поширює дію на діапазон. Відновлення зберігає початкові ім’я та рамку.", + "No ignored faces.": "Немає ігнорованих облич.", + "Ignored face": "Ігнороване обличчя", + "✓ Selected": "✓ Вибрано", + "Not selected": "Не вибрано", + "Done selecting": "Завершити вибір", + "Select faces…": "Вибрати обличчя…", + "Ignore selected faces": "Ігнорувати вибрані обличчя", + "Ignore face (blurry / not a face)": "Ігнорувати обличчя (розмите / не обличчя)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Натисніть, щоб вибрати обличчя або скасувати вибір. Shift-клацання поширює дію на діапазон. Подвійне клацання відкриває фото.", + "Ignore Faces": "Ігнорувати обличчя", + "Restore Ignored Faces": "Відновити ігноровані обличчя" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index dbf1d28db51..7058865e4bf 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -317,5 +317,6 @@ "Panel layout could not be restored: {error}": "Không thể khôi phục bố cục bảng: {error}", "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", "{name} is installed": "{name} đã được cài đặt", - "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật" + "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật", + "Ignored faces: {total} · Selected: {selected}": "Khuôn mặt đã bỏ qua: {total} · Đã chọn: {selected}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index dd93d0485c6..2e832905f4a 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2696,5 +2696,23 @@ "Set up name suggestions…": "Thiết lập gợi ý tên…", "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", - "Bottom bar": "Thanh dưới cùng" + "Bottom bar": "Thanh dưới cùng", + "Ignored faces": "Khuôn mặt đã bỏ qua", + "Ignored faces…": "Khuôn mặt đã bỏ qua…", + "Ignored Faces": "Khuôn mặt đã bỏ qua", + "Refresh ignored faces": "Làm mới khuôn mặt đã bỏ qua", + "Clear selection": "Bỏ chọn tất cả", + "Restore selected faces": "Khôi phục khuôn mặt đã chọn", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "Nhấp vào khuôn mặt để chọn hoặc bỏ chọn. Giữ Shift và nhấp để mở rộng thao tác cho một dải. Khôi phục giữ nguyên tên và khung ban đầu.", + "No ignored faces.": "Không có khuôn mặt đã bỏ qua.", + "Ignored face": "Khuôn mặt đã bỏ qua", + "✓ Selected": "✓ Đã chọn", + "Not selected": "Chưa chọn", + "Done selecting": "Chọn xong", + "Select faces…": "Chọn khuôn mặt…", + "Ignore selected faces": "Bỏ qua khuôn mặt đã chọn", + "Ignore face (blurry / not a face)": "Bỏ qua khuôn mặt (mờ / không phải khuôn mặt)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Nhấp vào khuôn mặt để chọn hoặc bỏ chọn. Giữ Shift và nhấp để mở rộng thao tác cho một dải. Nhấp đúp để mở ảnh.", + "Ignore Faces": "Bỏ qua khuôn mặt", + "Restore Ignored Faces": "Khôi phục khuôn mặt đã bỏ qua" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 900d30b4280..a0217ed1b77 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "无法恢复面板布局:{error}", "Panel move was not applied: {error}": "面板移动未应用:{error}", "{name} is installed": "{name} 已安装", - "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启" + "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", + "Ignored faces: {total} · Selected: {selected}": "已忽略的人脸:{total} · 已选择:{selected}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 5f138b6f9c9..48519cc1ddf 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2408,5 +2408,27 @@ "Set up name suggestions…": "设置姓名建议…", "Top bar": "顶部栏", "Tool strip": "工具栏", - "Bottom bar": "底部栏" + "Bottom bar": "底部栏", + "Ignored faces": "已忽略的人脸", + "Previous page": "上一页", + "Next page": "下一页", + "Page": "页", + "Ignored faces…": "已忽略的人脸…", + "Ignored Faces": "已忽略的人脸", + "Refresh ignored faces": "刷新已忽略的人脸", + "Select all": "全选", + "Clear selection": "清除选择", + "Restore selected faces": "恢复所选人脸", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "单击以选择或取消选择人脸。按住 Shift 单击可将操作扩展到一个范围。恢复时保留原始姓名和边框。", + "No ignored faces.": "没有已忽略的人脸。", + "Ignored face": "已忽略的人脸", + "✓ Selected": "✓ 已选择", + "Not selected": "未选择", + "Done selecting": "完成选择", + "Select faces…": "选择人脸…", + "Ignore selected faces": "忽略所选人脸", + "Ignore face (blurry / not a face)": "忽略人脸(模糊/并非人脸)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "单击以选择或取消选择人脸。按住 Shift 单击可将操作扩展到一个范围。双击打开照片。", + "Ignore Faces": "忽略人脸", + "Restore Ignored Faces": "恢复已忽略的人脸" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index a451e955d5a..43659ab1fc1 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -320,5 +320,6 @@ "Panel layout could not be restored: {error}": "無法還原面板配置:{error}", "Panel move was not applied: {error}": "面板移動未套用:{error}", "{name} is installed": "{name} 已安裝", - "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟" + "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", + "Ignored faces: {total} · Selected: {selected}": "已忽略的臉孔:{total} · 已選取:{selected}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 275accbeb0f..e3514e2d151 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2408,5 +2408,27 @@ "Top bar": "頂部列", "Tool strip": "工具列", "Bottom bar": "底部列", - "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)" + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "Ignored faces": "已忽略的臉孔", + "Previous page": "上一頁", + "Next page": "下一頁", + "Page": "頁", + "Ignored faces…": "已忽略的臉孔…", + "Ignored Faces": "已忽略的臉孔", + "Refresh ignored faces": "重新整理已忽略的臉孔", + "Select all": "全選", + "Clear selection": "清除選取", + "Restore selected faces": "還原所選臉孔", + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.": "按一下以選取或取消選取臉孔。按住 Shift 按一下可將操作延伸至一個範圍。還原時保留原始姓名與外框。", + "No ignored faces.": "沒有已忽略的臉孔。", + "Ignored face": "已忽略的臉孔", + "✓ Selected": "✓ 已選取", + "Not selected": "未選取", + "Done selecting": "完成選取", + "Select faces…": "選取臉孔…", + "Ignore selected faces": "忽略所選臉孔", + "Ignore face (blurry / not a face)": "忽略臉孔(模糊/並非臉孔)", + "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "按一下以選取或取消選取臉孔。按住 Shift 按一下可將操作延伸至一個範圍。按兩下開啟照片。", + "Ignore Faces": "忽略臉孔", + "Restore Ignored Faces": "還原已忽略的臉孔" } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 0080fa3504d..e960a4b14c9 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -306,6 +306,14 @@ impl LightcraftApp { if self.shown_library == Some(generation) { return; } + if self.shown_library.is_some() { + self.ui.ignored_faces = None; + self.ui.person_selection = Default::default(); + self.ui.unnamed_selected.clear(); + self.ui.unnamed_anchor = None; + self.caches.unnamed = None; + self.caches.person_page = None; + } self.shown_library = Some(generation); if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { let path = l.dir.to_string_lossy().into_owned(); diff --git a/crates/ui-egui/src/dialogs/rename.rs b/crates/ui-egui/src/dialogs/rename.rs index 8632daf412f..68044b7e7f5 100644 --- a/crates/ui-egui/src/dialogs/rename.rs +++ b/crates/ui-egui/src/dialogs/rename.rs @@ -70,7 +70,9 @@ pub(super) fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, let mut needs_merge = false; if !from_key.is_empty() { for photo in cat.photos().filter(|p| p.in_library()) { - for region in photo.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) { + for region in + photo.meta.regions.iter().filter(|r| matches!(r.kind, lightcraft_meta::RegionKind::Face | lightcraft_meta::RegionKind::IgnoredFace)) + { let Some(name) = region.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue }; let key = name.to_lowercase(); if key == from_key { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f8..9918120c528 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -353,6 +353,7 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(json!({"show": app.ui.face_boxes})) } "view.people" => { + app.ui.ignored_faces = None; // Everyone; the page just left stays one click away (the chip next to the title) if let Some(name) = app.ui.person_page.take() { app.ui.last_person = Some(name); @@ -362,6 +363,7 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(json!({"people": app.session.catalog.people().len()})) } "view.person" => { + app.ui.ignored_faces = None; // {name}: one person's page in the People view: their faces, and the faces that look like them let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else { return Some(Err("view.person: missing `name`".into())); @@ -371,6 +373,13 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val app.ui.person_page = Some(name.to_string()); Ok(json!({"person": name})) } + "view.ignoredFaces" => { + app.ui.view = ViewMode::People; + app.ui.person_page = None; + app.ui.ignored_faces = Some(crate::panels::ignored_faces::View::default()); + app.ui.unnamed_selected.clear(); + Ok(json!({})) + } "view.survey" => { app.ui.view = ViewMode::Survey; Ok(json!({"photos": crate::panels::compare::survey_photos(app).len()})) @@ -1508,6 +1517,8 @@ fn view_back_command(app: &mut LightcraftApp, ctx: &egui::Context) -> Result>>, + total: usize, + offset: usize, + selected: HashSet<(u64, usize)>, + revision: Option, + anchor: Option<(usize, bool)>, + error: Option, +} + +impl View { + /// Refresh after catalog/history changes and discard potentially stale selection keys. + pub(crate) fn invalidate(&mut self) { + *self = Self::default(); + } + + /// Move to another bounded page, dropping selections whose review entries are no longer shown. + fn page(&mut self, offset: usize) { + self.faces = None; + self.selected.clear(); + self.anchor = None; + self.error = None; + self.offset = offset; + } +} + +/// Read a retained catalog region's stable review key. +fn key(face: &Value) -> Option<(u64, usize)> { + Some((face["photo"].as_u64()?, usize::try_from(face["index"].as_u64()?).ok()?)) +} + +/// Show retained crops without loading a recognition model or constructing unnamed groups. +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let Some(mut view) = app.ui.ignored_faces.take() else { return }; + let t = crate::theme::Tokens::get(ui.ctx()); + if view.revision.is_some_and(|revision| revision != app.session.catalog.revision) { + view.invalidate(); + } + view.revision = Some(app.session.catalog.revision); + let mut back = false; + egui::Frame::NONE.inner_margin(16).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + let button = crate::widgets::arrow_button(ui, crate::i18n::tr("People"), crate::icons::Icon::ChevronLeft, true); + register(ui, "ignoredFaces:back", button.rect); + back = button.clicked(); + ui.heading(crate::i18n::tr("Ignored faces")); + let button = ui.button(crate::i18n::tr("Refresh ignored faces")); + register(ui, "ignoredFaces:refresh", button.rect); + if button.clicked() { + view.invalidate(); + } + }); + if view.faces.is_none() && view.error.is_none() { + view.revision = Some(app.session.catalog.revision); + match app.session.execute("faces.ignored", &json!({"offset": view.offset, "limit": PAGE_SIZE})) { + Ok(response) => { + view.total = response["total"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or_default(); + view.faces = Some(std::sync::Arc::new(response["faces"].as_array().cloned().unwrap_or_default())); + } + Err(error) => view.error = Some(error.to_string()), + } + } + if let Some(error) = &view.error { + ui.label(error); + } + let faces = view.faces.clone().unwrap_or_default(); + let mut restore = false; + ui.horizontal_wrapped(|ui| { + ui.label(crate::i18n::tr_format!("Ignored faces: {total} · Selected: {selected}", total = view.total, selected = view.selected.len())); + let button = ui.button(crate::i18n::tr("Select all")); + register(ui, "ignoredFaces:selectAll", button.rect); + if button.clicked() { + view.selected.extend(faces.iter().filter_map(key)); + } + let button = ui.button(crate::i18n::tr("Clear selection")); + register(ui, "ignoredFaces:clear", button.rect); + if button.clicked() { + view.selected.clear(); + view.anchor = None; + } + let button = ui.add_enabled(!view.selected.is_empty(), egui::Button::new(crate::i18n::tr("Restore selected faces"))); + register(ui, "ignoredFaces:restore", button.rect); + restore = button.clicked(); + }); + let mut requested_page = None; + if view.total > PAGE_SIZE { + ui.horizontal(|ui| { + let previous = ui.add_enabled(view.offset > 0, egui::Button::new(crate::i18n::tr("Previous page"))); + register(ui, "ignoredFaces:previous", previous.rect); + if previous.clicked() { + requested_page = Some(view.offset.saturating_sub(PAGE_SIZE)); + } + ui.label(format!("{} {} / {}", crate::i18n::tr("Page"), view.offset / PAGE_SIZE + 1, view.total.div_ceil(PAGE_SIZE))); + let next = ui.add_enabled(view.offset.saturating_add(faces.len()) < view.total, egui::Button::new(crate::i18n::tr("Next page"))); + register(ui, "ignoredFaces:next", next.rect); + if next.clicked() { + requested_page = Some(view.offset.saturating_add(PAGE_SIZE)); + } + }); + } + if let Some(offset) = requested_page { + view.page(offset); + return; + } + ui.label(crate::i18n::tr( + "Click faces to select or deselect. Shift-click extends that action to a range. Restoration keeps the original name and box.", + )); + if restore { + let selected: Vec<_> = faces.iter().filter(|f| key(f).is_some_and(|k| view.selected.contains(&k))).cloned().collect(); + match app.run("faces.ignore", json!({"faces": selected, "ignored": false})) { + Ok(_) => view.invalidate(), + Err(error) => view.error = Some(error), + } + return; + } + if faces.is_empty() { + ui.label(crate::i18n::tr("No ignored faces.")); + } + let edge = super::people::card_edge(app.ui.thumb_size); + let cols = ((ui.available_width() + 12.0) / (edge + 12.0)).floor().max(1.0) as usize; + let mut shown = 0; + egui::ScrollArea::vertical().show_rows(ui, edge + 32.0, faces.len().div_ceil(cols), |ui, rows| { + for row in rows { + ui.horizontal(|ui| { + for col in 0..cols { + let index = row.saturating_mul(cols).saturating_add(col); + let Some(face) = faces.get(index) else { break }; + let Some(face_key) = key(face) else { continue }; + let (area, _) = ui.allocate_exact_size(vec2(edge, edge + 24.0), Sense::hover()); + let image = Rect::from_min_size(area.min, vec2(edge, edge)); + let response = ui.interact(image, ui.scope_id().with(("ignored-face", face_key)), Sense::click()); + register(ui, format!("ignoredFaces:face:{index}"), image); + if let Ok(rect) = serde_json::from_value(face["view"].clone()) + && let Some(job) = app.session.face_job( + lightcraft_catalog::PhotoId(face_key.0), + rect, + (edge * ui.ctx().pixels_per_point()).ceil() as usize, + ) + && let Some(texture) = app.renderer.variant(job) + { + ui.painter().image(texture.tex.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + shown += 1; + if response.clicked() { + let (start, selecting) = + view.anchor.filter(|_| ui.input(|i| i.modifiers.shift)).unwrap_or((index, !view.selected.contains(&face_key))); + for key in faces.get(start.min(index)..=start.max(index)).unwrap_or_default().iter().filter_map(key) { + if selecting { + view.selected.insert(key); + } else { + view.selected.remove(&key); + } + } + if !ui.input(|i| i.modifiers.shift) || view.anchor.is_none() { + view.anchor = Some((index, selecting)); + } + } + let selected = view.selected.contains(&face_key); + if selected { + super::grid::selection_ring(ui.painter(), &t, image, lightcraft_engine::SelectionState::Selected); + } + crate::widgets::announce_selected(&response, crate::i18n::tr("Ignored face"), selected); + ui.painter().text( + pos2(area.left(), image.bottom() + 12.0), + egui::Align2::LEFT_CENTER, + if selected { crate::i18n::tr("✓ Selected") } else { crate::i18n::tr("Not selected") }, + t.font(12.0), + t.text, + ); + } + }); + } + }); + app.renderer.want_variants(shown); + }); + if !back { + app.ui.ignored_faces = Some(view); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn screenshot_if_requested(h: &mut crate::headless::Headless, variable: &str) { + let Some(path) = std::env::var_os(variable) else { return }; + let timeout = std::time::Duration::from_secs(15); + let shot = h.snapshot(timeout); + let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); + let png = lightcraft_engine::export::encode_image( + &image, + &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, + ) + .unwrap(); + std::fs::write(path, png).unwrap(); + } + + /// The primary workflow: select an unnamed range, ignore it in one step, and restore it. + #[test] + fn unnamed_range_can_be_ignored_and_restored_as_batches() { + use lightcraft_meta::{Region, RegionKind}; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = (0..3) + .map(|i| Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 }, + kind: RegionKind::Face, + name: None, + description: Some("retained".into()), + }) + .collect(); + let original = meta.regions.clone(); + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.step(); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + for (index, shift) in [(0, false), (2, true)] { + let r = h.request("ui.clickWidget", json!({"id": format!("unnamed-face:{}:{index}", id.0), "shift": shift}), timeout); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + } + assert_eq!(h.app.ui.unnamed_selected.len(), 3); + screenshot_if_requested(&mut h, "LIGHTCRAFT_UNNAMED_SCREENSHOT"); + let before = h.app.session.undo.len(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignore"}), timeout)["ok"], true); + h.step(); + assert_eq!(h.app.session.undo.len(), before + 1); + assert!(h.app.ui.unnamed_selected.is_empty()); + assert!(h.app.session.catalog.photo(id).unwrap().meta.regions.iter().all(|r| r.kind == RegionKind::IgnoredFace)); + assert_eq!(h.app.session.execute("faces.unnamed", &json!({})).unwrap()["total"], 0); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); + h.app.run("edit.redo", json!({})).unwrap(); + h.app.run("view.ignoredFaces", json!({})).unwrap(); + h.settle(timeout); + screenshot_if_requested(&mut h, "LIGHTCRAFT_IGNORED_BATCH_SCREENSHOT"); + let before = h.app.session.undo.len(); + for widget in ["ignoredFaces:selectAll", "ignoredFaces:restore"] { + let r = h.request("ui.clickWidget", json!({"id": widget}), timeout); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + } + assert_eq!(h.app.session.undo.len(), before + 1); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); + } + + /// Removing a region must not transfer its selection to the face that takes its index. + #[test] + fn unnamed_selection_is_cleared_before_an_index_can_be_reused() { + use lightcraft_meta::{Region, RegionKind}; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = (0..2) + .map(|i| Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.3, y0: 0.2, x1: 0.3 + f64::from(i) * 0.3, y1: 0.5 }, + kind: RegionKind::Face, + name: None, + description: None, + }) + .collect(); + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.step(); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("unnamed-face:{}:0", id.0)}), timeout)["ok"], true); + h.step(); + assert_eq!(h.app.ui.unnamed_selected.len(), 1); + h.app.session.execute("photo.removeRegion", &json!({"id": id.0, "index": 0})).unwrap(); + h.step(); + assert!(h.app.ui.unnamed_selected.is_empty()); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[0].kind, RegionKind::Face); + assert!(!h.app.widgets.iter().any(|(id, _)| id == "unnamed:ignore")); + } + + /// A library over one page remains reviewable, and changing pages cannot restore stale selections. + #[test] + fn ignored_review_pages_and_restores_the_last_face() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + let region = lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.2, y0: 0.2, x1: 0.6, y1: 0.6 }, + kind: lightcraft_meta::RegionKind::IgnoredFace, + name: None, + description: None, + }; + meta.regions = vec![region; PAGE_SIZE + 1]; + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.step(); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignored"}), timeout)["ok"], true); + h.settle(timeout); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().len(), PAGE_SIZE); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().total, PAGE_SIZE + 1); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout)["ok"], true); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().selected.len(), PAGE_SIZE); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:next"}), timeout)["ok"], true); + h.step(); + let view = h.app.ui.ignored_faces.as_ref().unwrap(); + assert_eq!(view.offset, PAGE_SIZE); + assert_eq!(view.faces.as_ref().unwrap().len(), 1); + assert!(view.selected.is_empty()); + if let Some(path) = std::env::var_os("LIGHTCRAFT_IGNORED_PAGED_SCREENSHOT") { + let shot = h.snapshot(timeout); + let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); + let png = lightcraft_engine::export::encode_image( + &image, + &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, + ) + .unwrap(); + std::fs::write(path, png).unwrap(); + } + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout)["ok"], true); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:restore"}), timeout)["ok"], true); + h.step(); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[PAGE_SIZE].kind, lightcraft_meta::RegionKind::Face); + let view = h.app.ui.ignored_faces.as_ref().unwrap(); + assert_eq!(view.total, PAGE_SIZE); + assert_eq!(view.offset, 0); + assert_eq!(view.faces.as_ref().unwrap().len(), PAGE_SIZE); + } + + /// Restore a retained assignment through the actual panel without any recognition model. + #[test] + fn ignored_review_restores_without_a_model_and_back_returns_to_people() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + let rect = lightcraft_geom::Rect { x0: 0.2, y0: 0.2, x1: 0.6, y1: 0.6 }; + meta.regions = + vec![lightcraft_meta::Region { rect, kind: lightcraft_meta::RegionKind::IgnoredFace, name: Some("Person".into()), description: None }]; + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.step(); + h.app.run("app.language.german", json!({})).unwrap(); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + assert!(h.painted_text().iter().any(|text| text == "Ignorierte Gesichter…")); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignored"}), timeout)["ok"], true); + h.settle(timeout); + for label in [ + "Ignorierte Gesichter", + "Ignorierte Gesichter aktualisieren", + "Ignorierte Gesichter: 1 · Ausgewählt: 0", + "Ausgewählte Gesichter wiederherstellen", + ] { + assert!(h.painted_text().iter().any(|text| text == label), "missing translated label: {label}"); + } + for widget in ["ignoredFaces:selectAll", "ignoredFaces:restore"] { + let response = h.request("ui.clickWidget", json!({"id": widget}), timeout); + assert_eq!(response["ok"], true, "{response}"); + h.step(); + if widget == "ignoredFaces:selectAll" { + assert!(h.painted_text().iter().any(|text| text == "Ignorierte Gesichter: 1 · Ausgewählt: 1")); + } + } + let region = &h.app.session.catalog.photo(id).unwrap().meta.regions[0]; + assert_eq!(region.kind, lightcraft_meta::RegionKind::Face); + assert_eq!(region.name.as_deref(), Some("Person")); + assert_eq!(region.rect, rect); + assert_eq!(crate::i18n::history_label("Ignore Faces", &[]), "Gesichter ignorieren"); + assert_eq!(crate::i18n::history_label("Restore Ignored Faces", &[]), "Ignorierte Gesichter wiederherstellen"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().len(), 1); + h.app.run("edit.redo", json!({})).unwrap(); + h.step(); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().is_empty()); + h.app.run("edit.undo", json!({})).unwrap(); + h.step(); + // Direct session calls bypass the UI command hook, including library membership changes. + h.app.session.selection = lightcraft_engine::Selection::single(id); + let selected = h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout); + assert_eq!(selected["ok"], true); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().selected.len(), 1); + h.app.session.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + h.step(); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().is_empty()); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().selected.is_empty()); + h.app.session.execute("photo.restore", &json!({"ids": [id.0]})).unwrap(); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().len(), 1); + h.app.session.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}], "ignored": false})).unwrap(); + h.step(); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().is_empty()); + h.app.session.execute("edit.undo", &json!({})).unwrap(); + h.step(); + if let Some(path) = std::env::var_os("LIGHTCRAFT_IGNORED_SCREENSHOT") { + let inspected = h.request("ui.inspect", json!({}), timeout); + println!("Ignored-face review perf: {}", inspected["result"]["perf"]); + let shot = h.snapshot(timeout); + let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); + let png = lightcraft_engine::export::encode_image( + &image, + &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, + ) + .unwrap(); + std::fs::write(path, png).unwrap(); + } + h.app.run("view.back", json!({})).unwrap(); + assert!(h.app.ui.ignored_faces.is_none()); + h.app.run("app.language.english", json!({})).unwrap(); + } +} diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 18403d75df1..0bf456945ad 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -56,7 +56,12 @@ pub(super) fn fit(painter: &egui::Painter, text: &str, font: egui::FontId, max_w (1..chars.len()).rev().map(|n| chars[..n].iter().collect::() + "…").find(|s| width(s) <= max_w).unwrap_or_else(|| "…".to_string()) } +/// Show named people and unnamed crops, or dispatch the active face-review screen. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + if app.ui.ignored_faces.is_some() { + super::ignored_faces::show(app, ui); + return; + } if let Some(name) = app.ui.person_page.clone() { return super::person::show(app, ui, &name); } @@ -82,12 +87,17 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.painter().text(pos2(head.right() - PAD, head.center().y), Align2::RIGHT_CENTER, people.len().to_string(), t.font(13.0), t.text_dim); // until face recognition is set up: what it takes, and a button that does the next step super::faces::setup_banner(app, ui); + let ignored = ui.button(crate::i18n::tr("Ignored faces…")); + register(ui, "unnamed:ignored", ignored.rect); + if ignored.clicked() { + let _ = app.run("view.ignoredFaces", json!({})); + } // the filters narrowing the list (a date, a keyword…), removable here let chips = lightcraft_engine::filter_chips(&app.session.filter, &app.session.catalog); super::chips::show(app, ui, &chips); - // what is selected below, and the box to name it with - super::unnamed::naming_bar(app, ui); let unnamed = super::unnamed::faces(app, now); + // Refresh before accepting selection actions: region indices may have changed. + super::unnamed::naming_bar(app, ui); if people.is_empty() && unnamed.faces.is_empty() { let (title, body) = if chips.is_empty() { ("No people yet", "Face names written to XMP by Lightroom and other apps show up here, and faces found in your photos can be named.") diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 0b6b946aa1f..7076cd30d6d 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -16,6 +16,53 @@ use crate::widgets::register; const PAD: f32 = 20.0; const SECTION_H: f32 = 56.0; +#[derive(Clone, Debug, Default)] +pub struct Selection { + name: String, + active: bool, + faces: std::collections::HashSet<(u64, usize)>, + anchor: Option<(usize, bool)>, + before_click: Option, + revision: Option, +} + +#[derive(Clone, Debug)] +struct BeforeClick { + face: (u64, usize), + faces: std::collections::HashSet<(u64, usize)>, + anchor: Option<(usize, bool)>, +} + +/// A double-click opens the photo without retaining the first click's range/anchor changes. +fn click_confirmed(selection: &mut Selection, faces: &[Face], target: &Face, shift: bool, double: bool) { + if double { + if let Some(before) = selection.before_click.take().filter(|before| before.face == (target.photo, target.index)) { + selection.faces = before.faces; + selection.anchor = before.anchor; + } + } else { + selection.before_click = Some(BeforeClick { face: (target.photo, target.index), faces: selection.faces.clone(), anchor: selection.anchor }); + select_confirmed(selection, faces, target, shift); + } +} + +/// Repeat the anchor's include/exclude action over a range of confirmed faces. +fn select_confirmed(selection: &mut Selection, faces: &[Face], target: &Face, shift: bool) { + let Some(index) = faces.iter().position(|f| f.photo == target.photo && f.index == target.index) else { return }; + let key = (target.photo, target.index); + let (start, selecting) = selection.anchor.filter(|_| shift).unwrap_or((index, !selection.faces.contains(&key))); + for face in faces.get(start.min(index)..=start.max(index)).unwrap_or_default() { + if selecting { + selection.faces.insert((face.photo, face.index)); + } else { + selection.faces.remove(&(face.photo, face.index)); + } + } + if !shift || selection.anchor.is_none() { + selection.anchor = Some((index, selecting)); + } +} + /// One face: which photo, which of its regions, the box to show it by, and (for the "More" faces) how alike. #[derive(Clone, Debug, PartialEq)] pub struct Face { @@ -37,6 +84,7 @@ pub struct PersonPage { pub pending: usize, } +/// Parse a tile reference, preferring its detector-aligned display box over the catalog box. fn face_of(v: &Value) -> Option { let rect = |r: &Value| Some(lightcraft_geom::Rect { x0: r["x0"].as_f64()?, y0: r["y0"].as_f64()?, x1: r["x1"].as_f64()?, y1: r["y1"].as_f64()? }); Some(Face { @@ -82,9 +130,11 @@ fn page_for(app: &mut LightcraftApp, name: &str, now: f64) -> Arc { enum Hit { Nothing, Open, + OpenDouble, Confirm, ConfirmAbove, Dismiss, + Ignore, } /// The current, session-visible candidates at or above the selected score. The score, not the tile position, is the @@ -140,11 +190,26 @@ pub(crate) fn handle_bulk_key(app: &mut LightcraftApp, ctx: &egui::Context) -> b true } +/// Render confirmed faces and More suggestions with explicit selection and ignore actions. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let t = Tokens::get(ui.ctx()); let now = ui.input(|i| i.time); let page = page_for(app, name, now); let shown_name = if page.name.is_empty() { name.to_string() } else { page.name.clone() }; + if app.ui.person_selection.name != shown_name { + app.ui.person_selection = Selection { name: shown_name.clone(), ..Default::default() }; + } + let selection = &mut app.ui.person_selection; + if selection.revision.is_some_and(|revision| revision != app.session.catalog.revision) { + selection.faces.clear(); + selection.anchor = None; + selection.before_click = None; + } + selection.revision = Some(app.session.catalog.revision); + if !app.ui.person_selection.faces.is_empty() { + let valid: std::collections::HashSet<_> = page.confirmed.iter().map(|f| (f.photo, f.index)).collect(); + app.ui.person_selection.faces.retain(|key| valid.contains(key)); + } ui.add_space(8.0); ui.horizontal(|ui| { ui.add_space(PAD - 4.0); @@ -172,6 +237,50 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { }); }); ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + ui.add_space(PAD); + let active = app.ui.person_selection.active; + let button = ui.button(if active { crate::i18n::tr("Done selecting") } else { crate::i18n::tr("Select faces…") }); + register(ui, "person:selectFaces", button.rect); + if button.clicked() { + app.ui.person_selection.active = !active; + app.ui.person_selection.faces.clear(); + app.ui.person_selection.before_click = None; + app.ui.person_selection.anchor = None; + } + if app.ui.person_selection.active { + let all = ui.button(crate::i18n::tr("Select all")); + register(ui, "person:selectAll", all.rect); + if all.clicked() { + app.ui.person_selection.before_click = None; + app.ui.person_selection.faces.extend(page.confirmed.iter().map(|f| (f.photo, f.index))); + } + let clear = ui.button(crate::i18n::tr("Clear selection")); + register(ui, "person:clearSelection", clear.rect); + if clear.clicked() { + app.ui.person_selection.faces.clear(); + app.ui.person_selection.before_click = None; + app.ui.person_selection.anchor = None; + } + let count = app.ui.person_selection.faces.len(); + let ignore = ui.add_enabled(count > 0, egui::Button::new(crate::i18n::tr("Ignore selected faces"))); + register(ui, "person:ignoreSelected", ignore.rect); + if ignore.clicked() { + let faces: Vec<_> = app.ui.person_selection.faces.iter().map(|(photo, index)| json!({"photo": photo, "index": index})).collect(); + match app.run("faces.ignore", json!({"faces": faces})) { + Ok(_) => { + app.ui.person_selection.faces.clear(); + app.ui.person_selection.before_click = None; + app.ui.person_selection.anchor = None; + } + Err(error) => app.toast(ui.ctx(), error), + } + } + } + }); + if app.ui.person_selection.active { + ui.label(crate::i18n::tr("Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.")); + } if page.total == 0 { super::empty_message( ui, @@ -221,10 +330,27 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let Some(f) = page.confirmed.get(row * cols + col) else { break }; shown += 1; let min = area.min + vec2(PAD + col as f32 * (edge + super::people::TILE_GAP), PAD + row as f32 * row_h); - if let Hit::Open = - tile(app, ui, &TileSpec { r: Rect::from_min_size(min, vec2(edge, edge)), f, ppp, more: false, name: &shown_name, above_count: 0 }) - { - hit = Some((Hit::Open, f.clone())); + let action = tile( + app, + ui, + &TileSpec { r: Rect::from_min_size(min, vec2(edge, edge)), f, ppp, more: false, name: &shown_name, above_count: 0 }, + ); + if action == Hit::Ignore { + hit = Some((action, f.clone())); + } else if matches!(action, Hit::Open | Hit::OpenDouble) { + let double = action == Hit::OpenDouble; + if app.ui.person_selection.active { + click_confirmed(&mut app.ui.person_selection, &page.confirmed, f, ui.input(|i| i.modifiers.shift), double); + } + if !app.ui.person_selection.active || double { + hit = Some((Hit::Open, f.clone())); + } + } + if app.ui.person_selection.active && app.ui.person_selection.faces.contains(&(f.photo, f.index)) { + let rect = Rect::from_min_size(min, vec2(edge, edge)); + ui.painter().rect_stroke(rect.shrink(1.0), 3.0, Stroke::new(3.0, t.accent), StrokeKind::Inside); + ui.painter().rect_filled(Rect::from_min_size(min, vec2(24.0, 24.0)), 3.0, t.accent); + ui.painter().text(min + vec2(12.0, 12.0), Align2::CENTER_CENTER, "✓", t.font(16.0), Color32::WHITE); } } } @@ -260,6 +386,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { Hit::Confirm => hit = Some((Hit::Confirm, (*f).clone())), Hit::ConfirmAbove => hit = Some((Hit::ConfirmAbove, (*f).clone())), Hit::Dismiss => hit = Some((Hit::Dismiss, (*f).clone())), + Hit::Ignore => hit = Some((Hit::Ignore, (*f).clone())), _ => {} } } @@ -269,7 +396,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { }); if let Some((what, f)) = hit { match what { - Hit::Open => { + Hit::Open | Hit::OpenDouble => { let _ = app.run("library.select", json!({"ids": [f.photo], "active": f.photo})); let _ = app.run("view.detail", json!({})); // Escape comes back to this page; the People button to everyone, with this person next to its title @@ -284,6 +411,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { Hit::Dismiss => { app.ui.dismissed_faces.insert((f.photo, f.index)); } + Hit::Ignore => { + if let Err(error) = app.run("faces.ignore", json!({"faces": [{"photo": f.photo, "index": f.index}]})) { + app.toast(ui.ctx(), error); + } + } Hit::Nothing => {} } } @@ -333,6 +465,14 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { p.rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside); } let mut hit = Hit::Nothing; + resp.context_menu(|ui| { + let button = ui.button(crate::i18n::tr("Ignore face (blurry / not a face)")); + register(ui, "person:ignoreFace", button.rect); + if button.clicked() { + hit = Hit::Ignore; + ui.close(); + } + }); if more && hovered { // a check at the bottom right says a click confirms; × hides and ↑ names all above this score let badge = Rect::from_min_size(pos2(r.right() - 28.0, r.bottom() - 28.0), vec2(24.0, 24.0)); @@ -369,7 +509,9 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { } } else { let _ = resp.clone().on_hover_text(format!("{name} — click to open this photo")); - if resp.clicked() { + if resp.double_clicked() { + hit = Hit::OpenDouble; + } else if resp.clicked() { hit = Hit::Open; } } @@ -380,6 +522,132 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { mod tests { use super::*; + /// The suggested-face context menu must persist ignoring, without confirming the suggestion. + #[test] + fn more_face_context_menu_ignores_the_suggestion_with_one_undo() { + use std::time::Duration; + let t = Duration::from_secs(15); + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default()); + let ids: Vec<_> = app.session.catalog.photos().map(|p| p.id).take(2).collect(); + assert_eq!(ids.len(), 2); + let rect = lightcraft_geom::Rect { x0: 0.2, y0: 0.2, x1: 0.6, y1: 0.6 }; + for (i, id) in ids.iter().enumerate() { + let mut meta = app.session.catalog.photo(*id).unwrap().meta.clone(); + meta.regions = vec![lightcraft_meta::Region { + rect, + kind: lightcraft_meta::RegionKind::Face, + name: (i == 0).then(|| "Person".into()), + description: None, + }]; + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id: *id, meta: Box::new(meta) }).unwrap(); + } + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.step(); + h.app.run("view.person", json!({"name": "Person"})).unwrap(); + let page = PersonPage { + name: "Person".into(), + total: 1, + confirmed: vec![Face { photo: ids[0].0, index: 0, rect, score: 0.0 }], + more: vec![Face { photo: ids[1].0, index: 0, rect, score: 0.8 }], + ready: true, + pending: 0, + }; + h.app.caches.person_page = Some(("Person".into(), h.app.session.catalog.revision, h.app.caches.faces_indexed, h.time(), Arc::new(page))); + h.settle(t); + let menu = h.request("ui.clickWidget", json!({"id": format!("more-face:{}:0", ids[1].0), "button": "right"}), t); + assert_eq!(menu["ok"], true, "{menu}"); + h.step(); + if let Some(path) = std::env::var_os("LIGHTCRAFT_MORE_IGNORE_SCREENSHOT") { + let shot = h.snapshot(t); + let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); + let png = lightcraft_engine::export::encode_image( + &image, + &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, + ) + .unwrap(); + std::fs::write(path, png).unwrap(); + } + let undo = h.app.session.undo.len(); + let ignored = h.request("ui.clickWidget", json!({"id": "person:ignoreFace"}), t); + assert_eq!(ignored["ok"], true, "{ignored}"); + h.step(); + h.settle(t); + let photo = h.app.session.catalog.photo(ids[1]).unwrap(); + assert_eq!(photo.meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); + assert!(photo.meta.regions[0].name.is_none(), "ignoring must not confirm the suggested name"); + assert_eq!(photo.meta.regions[0].rect, rect); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(!h.app.widgets.iter().any(|(id, _)| id == &format!("more-face:{}:0", ids[1].0))); + assert_eq!(h.app.session.catalog.photo(ids[0]).unwrap().meta.regions[0].name.as_deref(), Some("Person")); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.photo(ids[1]).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::Face); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.photo(ids[1]).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); + } + + /// Double-click navigation restores the whole pre-click range and anchor on return. + #[test] + fn double_clicking_a_confirmed_face_preserves_selection_and_anchor() { + let timeout = std::time::Duration::from_secs(15); + for case in 0..3 { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let ids: Vec<_> = app.session.catalog.photos().take(4).map(|p| p.id).collect(); + for id in ids { + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Person".into()), + description: None, + }]; + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + } + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.app.run("view.person", json!({"name": "Person"})).unwrap(); + h.settle(timeout); + let faces = parse(&h.app.session.execute("faces.person", &json!({"name": "Person"})).unwrap()).confirmed; + assert_eq!(faces.len(), 4); + h.app.ui.person_selection.active = true; + select_confirmed(&mut h.app.ui.person_selection, &faces, &faces[0], false); + if case == 2 { + select_confirmed(&mut h.app.ui.person_selection, &faces, &faces[3], true); + select_confirmed(&mut h.app.ui.person_selection, &faces, &faces[1], false); + } + let before = h.app.ui.person_selection.clone(); + // Keep these two clicks separate from setup/navigation click bursts. + for _ in 0..60 { + h.step(); + } + let widget = format!("person-face:{}:{}", faces[3].photo, faces[3].index); + let params = json!({"id": widget, "shift": case != 0}); + assert_eq!(h.request("ui.clickWidget", params.clone(), timeout)["ok"], true); + h.step(); + assert_ne!(h.app.ui.person_selection.faces, before.faces); + assert_eq!(h.request("ui.clickWidget", params, timeout)["ok"], true); + h.step(); + assert_eq!(h.app.ui.view, crate::state::ViewMode::Detail, "case {case}"); + h.app.run("view.back", json!({})).unwrap(); + h.step(); + assert_eq!(h.app.ui.person_page.as_deref(), Some("Person")); + assert_eq!(h.app.ui.person_selection.faces, before.faces, "case {case}"); + assert_eq!(h.app.ui.person_selection.anchor, before.anchor, "case {case}"); + } + } + + /// Shift ranges repeat the anchor action for both inclusion and exclusion. + #[test] + fn confirmed_face_selection_extends_include_and_exclude_ranges() { + let faces: Vec<_> = + (0..4).map(|photo| Face { photo, index: 0, rect: lightcraft_geom::Rect { x0: 0.0, y0: 0.0, x1: 1.0, y1: 1.0 }, score: 0.0 }).collect(); + let mut selected = Selection::default(); + select_confirmed(&mut selected, &faces, &faces[0], false); + select_confirmed(&mut selected, &faces, &faces[3], true); + assert_eq!(selected.faces.len(), 4); + select_confirmed(&mut selected, &faces, &faces[1], false); + select_confirmed(&mut selected, &faces, &faces[3], true); + assert_eq!(selected.faces, std::collections::HashSet::from([(0, 0)])); + } + #[test] fn all_above_uses_score_including_later_ties_and_only_visible_faces() { let face = |photo, score| Face { photo, index: 0, rect: lightcraft_geom::Rect { x0: 0.0, y0: 0.0, x1: 1.0, y1: 1.0 }, score }; diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 7f42437b2ef..4baf80b3cc5 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -70,6 +70,13 @@ pub fn faces(app: &mut LightcraftApp, now: f64) -> Arc { } let v = app.session.execute("faces.unnamed", &json!({})).unwrap_or(Value::Null); let list = Arc::new(parse(&v)); + if app.caches.unnamed.as_ref().is_some_and(|(old, _, _, _)| *old != rev) { + // A removed region can leave another face at the same index. Do not transfer the + // reviewed selection to that face, even when its photo/index pair still exists. + app.ui.unnamed_selected.clear(); + app.ui.unnamed_anchor = None; + app.ui.unnamed_focus = false; + } // what was selected and has since been named (or removed) is no longer selected let present: std::collections::HashSet<(u64, usize)> = list.faces.iter().map(|f| (f.photo, f.index)).collect(); app.ui.unnamed_selected.retain(|k| present.contains(k)); @@ -127,6 +134,7 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { }; let mut submit: Option = None; let mut clear = false; + let mut ignore = false; ui.horizontal(|ui| { ui.add_space(super::people::PAD - 4.0); let n = selected.len(); @@ -151,6 +159,9 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { let c = ui.button(crate::i18n::tr("Clear")); register(ui, "unnamed:clear", c.rect); clear = c.clicked() || field.cancelled(); + let b = ui.button(crate::i18n::tr("Ignore selected faces")); + register(ui, "unnamed:ignore", b.rect); + ignore = b.clicked(); }); // the people already named, matching what is typed (a click names the faces) let typed = app.ui.unnamed_name.trim().to_lowercase(); @@ -170,7 +181,16 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { }); } } - if let Some(who) = submit { + if ignore { + let faces: Vec<_> = selected.iter().map(|(photo, index)| json!({"photo": photo, "index": index})).collect(); + match app.run("faces.ignore", json!({"faces": faces})) { + Ok(_) => { + app.ui.unnamed_selected.clear(); + app.ui.unnamed_anchor = None; + } + Err(error) => app.toast(ui.ctx(), error), + } + } else if let Some(who) = submit { name(app, &selected, &who); app.ui.unnamed_selected.clear(); app.ui.unnamed_name.clear(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6f4b42723fa..9081fe43ceb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -132,6 +132,8 @@ pub struct UiState { /// The person whose page the People view shows (their faces and the faces that look like them); `None`: everyone. #[serde(skip)] pub person_page: Option, + #[serde(skip)] + pub person_selection: crate::panels::person::Selection, /// The person page a photo in the loupe was opened from (`None`: the People view's unnamed faces), and that photo: /// Escape goes back there (not to the grid). #[serde(skip)] @@ -156,6 +158,8 @@ pub struct UiState { pub unnamed_anchor: Option, #[serde(skip)] pub unnamed_focus: bool, + #[serde(skip)] + pub ignored_faces: Option, /// Local sidebar locations hidden with “Remove from Local” (folders on disk are untouched). pub hidden_locations: Vec, /// Copies opened in an external editor this session (reloaded when the window is focused @@ -433,6 +437,7 @@ impl Default for UiState { collapsed_sidebar: Vec::new(), name_edit: None, person_page: None, + person_selection: Default::default(), person_from: None, last_person: None, cull_burst: None, @@ -441,6 +446,7 @@ impl Default for UiState { unnamed_name: String::new(), unnamed_anchor: None, unnamed_focus: false, + ignored_faces: None, hidden_locations: Vec::new(), dragging_control: None, alt_held: false, diff --git a/crates/ui-egui/src/tests/rename_person.rs b/crates/ui-egui/src/tests/rename_person.rs index 4ad1f5871e9..b2efe698ff0 100644 --- a/crates/ui-egui/src/tests/rename_person.rs +++ b/crates/ui-egui/src/tests/rename_person.rs @@ -136,3 +136,28 @@ fn rename_person_asks_before_merging() { assert_eq!(stored(&h, ids[0])[0].as_deref(), Some("Jane Doe")); assert_eq!(stored(&h, ids[1])[0].as_deref(), Some("John Roe")); } + +/// A retained ignored assignment still requires the normal person-merge confirmation. +#[test] +fn rename_person_dialog_confirms_a_merge_with_an_ignored_assignment() { + let mut h = demo(); + let ids: Vec<_> = h.app.session.catalog.photos().map(|p| p.id).take(2).collect(); + name_faces(&mut h, ids[0], vec![face(0.1, "Jane Doe")]); + let mut ignored = face(0.3, "John Roe"); + ignored.kind = lightcraft_meta::RegionKind::IgnoredFace; + name_faces(&mut h, ids[1], vec![ignored]); + open_people(&mut h); + h.app.run("view.person", json!({"name": "Jane Doe"})).unwrap(); + h.step(); + click(&mut h, "person:rename"); + let Some(Dialog::RenamePerson { to, .. }) = &mut h.app.ui.dialog else { panic!("missing rename dialog") }; + *to = "John Roe".into(); + h.step(); + click(&mut h, "button:dialogOk"); + assert!(h.app.ui.dialog.is_some()); + click(&mut h, "check:personMerge"); + click(&mut h, "button:dialogOk"); + assert!(h.app.ui.dialog.is_none()); + assert_eq!(stored(&h, ids[0])[0].as_deref(), Some("John Roe")); + assert_eq!(h.app.session.catalog.photo(ids[1]).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); +} diff --git a/docs/faces.md b/docs/faces.md index 07909a18f47..54d0c1e58bd 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -327,6 +327,34 @@ with an equal or higher similarity score. Its tooltip names the person and shows Hover a suggestion or focus it with the keyboard and press `A` for the same action. The batch is one undo step; suggestions below that score, previously confirmed faces and hidden suggestions stay as they were. Nothing is named without this explicit action. + +Renaming or merging a person updates names retained on ignored faces while keeping them ignored. Restoring them uses the updated name. + +For blurry crops or false detections, use **Ignore selected faces** in the +Unnamed faces naming bar, or a person's selection toolbar. A person's face tiles (including More) +also offer **Ignore face (blurry / not a face)** on right-click. Ignoring is persistent, catalog-only, +and one undo step per batch. Ignored crops disappear from People, recognition work, +and the confirmed examples used for matching. Their boxes remain in the catalog to suppress an +overlapping detection on future scans. Nothing is deleted from the original photo. + +Open **Ignored faces…** from People, select faces, then **Restore selected +faces** to include them again. Restoration preserves the original box, name and description; a +restored crop returns to the appropriate People view. This review works without +a recognition model installed. Controls and review counts follow the selected interface language. When there are more than 1,000 ignored faces, use **Previous page** and **Next page** to review all of them; selection is cleared when changing pages. The tiles use the same indexed detector crops as People. Open directly with `view.ignoredFaces`. Commands: `faces.ignore {faces: [{photo, index, rect?}], ignored?: true}` +and `faces.ignored {offset?: 0, limit?: 1000}` (at most 5,000 per page; returns the library-wide `total` and page `faces`). Supplying `rect` protects against stale selections; invalid batches change nothing. + +Select all in ignored-face review selects the current page only. On a person's page it selects the displayed confirmed faces (up to 5,000), not hidden results. + +Double-clicking a confirmed face opens its photo and preserves the prior selection and range anchor when returning to the person page. + +Face naming, ignore/restore, and face-box edits remain catalog-only through +Undo and Redo, even when automatic XMP writing is enabled. They do not mark photos as developed +or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Selections are cleared so stale region indices cannot be reused. A command combining face changes or their Undo/Redo with ordinary metadata changes still writes the ordinary metadata when automatic XMP writing is enabled. + +Ignored faces require **catalog format 12**. Opening an existing library (format 11 or earlier) upgrades its +catalog automatically, preserving existing face assignments and boxes. Older builds then +refuse the newer format instead of trying to decode it as an older catalog. + **Show photos** puts their photos in the grid; **‹ People** or Escape goes back. "More" only holds faces the scan has already embedded, so it fills in as the scan goes; it shows faces scoring above four fifths of the model's suggestion bar, since you look at each one before anything is named. diff --git a/docs/gaps.md b/docs/gaps.md index 535479fa10a..d9508d44a7d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -61,6 +61,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-11-04: persistent ignore/restore for individual and selected faces (#1873), with catalog-only Undo/Redo and paginated review without a recognition model. People remains partial: separated unnamed clusters and per-person rejection are not included; no ranked gap or headline count closes. + - 2026-10-29: the import review has a remembered 80–320 pt thumbnail-size slider, density-aware previews and bounded visible retention (#2237, part of #2056). Small sources do not reconstruct the same preview job every frame. The pre-import loupe and keyboard culling remain open in #2056; no ranked gap or headline feature count closes. - 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. @@ -90,6 +92,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | LRC-LIB-PEOPLE: persistent multi-select ignore/restore, format-12 upgrade and model-independent review; People remains partial and ranked gaps/counts are 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/parity-checklist.md b/docs/parity-checklist.md index dfab7f6bdee..e81ed851f07 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -714,7 +714,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), a Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied | | LRC-LIB-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 +| LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `cmd:faces.ignore`, `cmd:faces.ignored`, `cmd:view.ignoredFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/ui-egui/src/panels/ignored_faces.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`). Persistent ignore/restore retains boxes and names, suppresses redetection and matching, and is one catalog-only Undo/Redo step per batch; catalog format 12 upgrades older libraries. Ignored review works without a recognition model, pages across the full library, and uses indexed crops. No clusters with separators between groups or persistent per-person rejection. | | LRC-LIB-COMMENTS | Comments panel | P2 | ⬜ | | | | LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`) | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`) | | LRC-LIB-MISSING | Missing files & relink | P1 | ✅ | `cmd:library.missing`, `cmd:photo.relink`, `cmd:library.findMissing`, `cmd:file.findMissing`, `cmd:photo.locate`, `crates/engine/src/cmd/missing.rs` (`checked_path`), `crates/ui-egui/src/missing_sweep.rs`, `crates/ui-egui/src/panels/left.rs` (`locate_missing_item`) | File → Find Missing Photos… (anywhere in a folder: same name, size and content hash; renamed files by size + content hash; same name and size alone only when unambiguous — look-alikes are skipped and reported; searched on a worker thread, one undo step), photo menu → Locate Missing File…; a folder or disk row's Locate Missing Files… chooses its new location and scopes the same recursive background finder to that folder and its subfolders. Unreadable files show "!" in the grid and a reason in the loupe; undo never moves files. Missing Photos in the sidebar (counted on a worker thread; the view, the Info panel, the grid's context menu and thumbnails read file availability from a cache a worker thread fills, so an offline NAS never stalls a frame); it covers library photos only — Local browse records are never checked, for the count, the view, `library.missing` and Find Missing alike; `library.missing` from the control channel or `mcp --connect` checks the files on a worker thread (a "Missing Photos" row in the activity stack, ✕ stops it) and answers when it ends, so a large library on a network share never stalls the window; the same request meanwhile shares the running check | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | LRC-LIB-PEOPLE: persistent multi-select ignore/restore, format-12 upgrade and model-independent paginated review; partial status and 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-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 | diff --git a/docs/whats-new.md b/docs/whats-new.md index ba7c55b8436..5138e7810aa 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,14 @@ # What's new in LightCraft +## 2026-11-04 + +### Keep unwanted faces out of People +- Select one or several faces in Unnamed faces and choose **Ignore selected faces**. A person's page also offers + selection controls and a face's right-click **Ignore face** action. Ignored faces stay out of recognition suggestions + across launches; their photos, face boxes and names are retained. **Ignored faces…** in People lets you review and + restore them, without a recognition model. Each ignore or restore batch is one Undo step and does not write XMP. + Existing libraries upgrade to catalog format 12; older builds cannot open an upgraded library. + ## 2026-10-30 ### Lens distortion correction for the Sony A7 III From a49c88a8505b0a02cb4c54118e7010f666bdf7ef Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Thu, 5 Nov 2026 00:14:54 +0100 Subject: [PATCH 02/10] LRC-LIB-PEOPLE: preserve ignored faces through XMP rereads and review state Address the eight CodeRabbit findings on #3757. Reconcile local ignored regions when reading foreign XMP, retain confirmed selections and ignored-review pages across unrelated catalog changes, validate navigation before mutation, announce selected confirmed tiles, use the shared context-menu wrapper, and wrap the naming toolbar. Add XMP reread/Undo/Redo/reopen, navigation, unrelated-region/index-reuse and AccessKit regressions. Exercise batch ignore/restore in English and German at the minimum 900x560 window size, and prove ignored candidates and named exemplars are excluded from recognition suggestions. Validation: cargo xtask ci passed all eight gates with CRAFT_FONTS_DIR (152 external-data skips). Synthetic screenshots inspected; ignored-review headless ui.inspect updateMs 0.474, logicMs 0.005 on Apple M2. Assisted-by: OpenAI GPT-6.1 Sol --- crates/engine/src/cmd/face_recognize.rs | 9 ++ crates/engine/src/sidecar.rs | 21 ++- crates/engine/src/tests/xmp.rs | 39 +++++ crates/ui-egui/src/menus/run.rs | 4 +- crates/ui-egui/src/panels/ignored_faces.rs | 157 +++++++++++++++------ crates/ui-egui/src/panels/person.rs | 92 +++++++++++- crates/ui-egui/src/panels/unnamed.rs | 2 +- docs/faces.md | 2 +- 8 files changed, 272 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index 52d1b91730f..e89c3a22578 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -1161,6 +1161,15 @@ mod imp { assert!(r.items[0]["score"].as_f64().unwrap() > r.items[1]["score"].as_f64().unwrap()); assert_eq!(similar(&mut s, "ann", 1).items.len(), 1, "capped"); assert!(similar(&mut s, "nobody", 10).items.is_empty()); + // The positive control above produces both candidates. Ignoring a candidate excludes + // that exact pair; ignoring Ann's only exemplar must exclude the remaining candidate. + s.execute("faces.ignore", &json!({"faces": [{"photo": b.0, "index": 0}]})).unwrap(); + let pairs = |r: Similar| r.items.iter().map(|i| (i["photo"].as_u64().unwrap(), i["index"].as_u64().unwrap())).collect::>(); + assert_eq!(pairs(similar(&mut s, "ann", 10)), vec![(c.0, 0)]); + s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}]})).unwrap(); + assert!(pairs(similar(&mut s, "ann", 10)).is_empty()); + s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}], "ignored": false})).unwrap(); + assert_eq!(pairs(similar(&mut s, "ann", 10)), vec![(c.0, 0)], "restoring the exemplar restores its suggestion"); let _ = std::fs::remove_dir_all(&d); } } diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 252dd911a68..94a59e339ee 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -200,7 +200,8 @@ pub fn parse_sidecar(xmp: &str, target: crate::crs::Target) -> std::result::Resu keywords: (!m.keywords.is_empty() || !m.hierarchical_keywords.is_empty()) .then(|| lightcraft_catalog::keywords::from_file(&m.keywords, &m.hierarchical_keywords)), // A sidecar that has `mwg-rs:Regions` at all (even an empty list) was written by an app that - // knows about regions, so it's authoritative: its list, empty or not, replaces the catalog's. + // knows about regions, so it's authoritative for ordinary regions: its list, empty or not, + // replaces those in the catalog. Local ignored-face decisions are reconciled in merge_into. // One without it (most writers, LightCraft's own included, which keeps another app's // `mwg-rs:Regions` byte for byte but never writes one) says nothing about regions, and the // photo's are kept. @@ -334,7 +335,23 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool { m.keywords = k.clone(); } if let Some(r) = &sc.regions { - m.regions = r.clone(); + // Ignore is a local catalog decision, not represented by MWG XMP. Foreign lists remain + // authoritative for ordinary regions, but must neither restore nor delete ignored faces. + let mut regions = r.clone(); + for ignored in m.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::IgnoredFace) { + let same_box = |r: &&mut lightcraft_meta::Region| { + r.kind == lightcraft_meta::RegionKind::Face + && [r.rect.x0 - ignored.rect.x0, r.rect.y0 - ignored.rect.y0, r.rect.x1 - ignored.rect.x1, r.rect.y1 - ignored.rect.y1] + .iter() + .all(|delta| delta.abs() <= 1e-6) + }; + if let Some(region) = regions.iter_mut().find(same_box) { + *region = ignored.clone(); + } else { + regions.push(ignored.clone()); + } + } + m.regions = regions; } let develop = match &sc.develop { Some(DevelopPatch::Full(s)) => (**s).clone(), diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index fa05a60ed24..0c0b0346a42 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -656,6 +656,45 @@ const MWG_REGIONS: &str = r#" "#; +/// Local rejections survive foreign region replacement, including explicit removal in XMP. +#[test] +fn rereading_xmp_preserves_ignored_regions_and_other_metadata() { + let src = temp_dir("ignored-reread"); + write_png(&src.join("portrait.png"), 9); + let path = src.join("portrait.xmp"); + std::fs::write(&path, MWG_REGIONS).unwrap(); + let mut s = Session::new().with_fs(); + let library = src.join("library"); + s.open_library(&library, true).unwrap(); + s.execute("library.import", &json!({"paths": [src.join("portrait.png").to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}]})).unwrap(); + let ignored = s.catalog.photo(id).unwrap().meta.regions.clone(); + let empty = MWG_REGIONS.replacen("", "", 1); + let absent = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata::default(), None); + let moved = MWG_REGIONS.replace("stArea:x=\"0.5\"", "stArea:x=\"0.2\""); + for packet in [MWG_REGIONS, MWG_REGIONS, &empty, &absent, &moved] { + std::fs::write(&path, packet).unwrap(); + let read = s.execute("photo.readMetadataFromFile", &json!({})).unwrap(); + assert!(read["failed"].as_array().unwrap().is_empty(), "{read}"); + let regions = &s.catalog.photo(id).unwrap().meta.regions; + assert_eq!(regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::IgnoredFace).cloned().collect::>(), ignored); + assert_eq!(regions.len(), if packet == moved { 2 } else { 1 }); + assert_eq!(std::fs::read_to_string(&path).unwrap(), packet); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions, ignored); + s.execute("edit.redo", &json!({})).unwrap(); + } + s.close_library().unwrap(); + drop(s); + let mut reopened = Session::new().with_fs(); + reopened.open_library(&library, false).unwrap(); + assert_eq!(reopened.execute("faces.ignored", &json!({})).unwrap()["total"], 1); + assert_eq!(reopened.catalog.photo(id).unwrap().meta.regions.iter().find(|r| r.kind == lightcraft_meta::RegionKind::IgnoredFace), ignored.first()); + reopened.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&src); +} + /// A face region written by Lightroom (MWG-RS) into a sidecar reaches `Photo.meta.regions` on /// import — the same path real catalogs use, exercised end to end rather than just at the parser. #[test] diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 9918120c528..efe95abe6db 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -363,11 +363,11 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(json!({"people": app.session.catalog.people().len()})) } "view.person" => { - app.ui.ignored_faces = None; // {name}: one person's page in the People view: their faces, and the faces that look like them let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else { return Some(Err("view.person: missing `name`".into())); }; + app.ui.ignored_faces = None; app.ui.view = ViewMode::People; app.ui.person_from = None; app.ui.person_page = Some(name.to_string()); @@ -375,9 +375,11 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val } "view.ignoredFaces" => { app.ui.view = ViewMode::People; + app.ui.person_from = None; app.ui.person_page = None; app.ui.ignored_faces = Some(crate::panels::ignored_faces::View::default()); app.ui.unnamed_selected.clear(); + app.ui.unnamed_anchor = None; Ok(json!({})) } "view.survey" => { diff --git a/crates/ui-egui/src/panels/ignored_faces.rs b/crates/ui-egui/src/panels/ignored_faces.rs index 5423e7c0ebe..be7cc4b617a 100644 --- a/crates/ui-egui/src/panels/ignored_faces.rs +++ b/crates/ui-egui/src/panels/ignored_faces.rs @@ -45,7 +45,29 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let Some(mut view) = app.ui.ignored_faces.take() else { return }; let t = crate::theme::Tokens::get(ui.ctx()); if view.revision.is_some_and(|revision| revision != app.session.catalog.revision) { - view.invalidate(); + // Refetch on catalog changes, but only discard selection when the displayed entries + // change. Background detections elsewhere must not move the review back to page one. + match app.session.execute("faces.ignored", &json!({"offset": view.offset, "limit": PAGE_SIZE})) { + Ok(response) => { + let faces = response["faces"].as_array().cloned().unwrap_or_default(); + view.total = response["total"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or_default(); + if view.faces.as_deref() != Some(&faces) { + view.selected.clear(); + view.anchor = None; + } + view.faces = Some(std::sync::Arc::new(faces)); + view.error = None; + if view.offset >= view.total && view.offset > 0 { + view.page(view.total.saturating_sub(1) / PAGE_SIZE * PAGE_SIZE); + } + } + Err(error) => { + view.selected.clear(); + view.anchor = None; + view.faces = None; + view.error = Some(error.to_string()); + } + } } view.revision = Some(app.session.catalog.revision); let mut back = false; @@ -193,6 +215,29 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { mod tests { use super::*; + #[test] + fn ignored_navigation_discards_old_destinations_but_invalid_person_preserves_review() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let id = app.session.catalog.photos().next().unwrap().id.0; + app.ui.person_from = Some((Some("Earlier".into()), id)); + app.ui.unnamed_selected.insert((id, 0)); + app.ui.unnamed_anchor = Some(42); + app.run("view.ignoredFaces", json!({})).unwrap(); + assert!(app.ui.person_from.is_none()); + assert!(app.ui.unnamed_selected.is_empty()); + assert!(app.ui.unnamed_anchor.is_none()); + app.ui.ignored_faces.as_mut().unwrap().offset = PAGE_SIZE; + for params in [json!({}), json!({"name": " "}), json!({"name": 5})] { + assert!(app.run("view.person", params).is_err()); + assert_eq!(app.ui.ignored_faces.as_ref().unwrap().offset, PAGE_SIZE); + } + app.run("view.detail", json!({})).unwrap(); + app.run("view.back", json!({})).unwrap(); + assert_eq!(app.ui.view, crate::state::ViewMode::PhotoGrid); + app.run("view.person", json!({"name": "Person"})).unwrap(); + assert!(app.ui.ignored_faces.is_none()); + } + fn screenshot_if_requested(h: &mut crate::headless::Headless, variable: &str) { let Some(path) = std::env::var_os(variable) else { return }; let timeout = std::time::Duration::from_secs(15); @@ -210,52 +255,60 @@ mod tests { #[test] fn unnamed_range_can_be_ignored_and_restored_as_batches() { use lightcraft_meta::{Region, RegionKind}; - let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); - let id = app.session.catalog.photos().next().unwrap().id; - let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); - meta.regions = (0..3) - .map(|i| Region { - rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 }, - kind: RegionKind::Face, - name: None, - description: Some("retained".into()), - }) - .collect(); - let original = meta.regions.clone(); - app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); - let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); - let timeout = std::time::Duration::from_secs(15); - h.step(); - h.app.run("view.people", json!({})).unwrap(); - h.settle(timeout); - for (index, shift) in [(0, false), (2, true)] { - let r = h.request("ui.clickWidget", json!({"id": format!("unnamed-face:{}:{index}", id.0), "shift": shift}), timeout); - assert_eq!(r["ok"], true, "{r}"); + for language in ["english", "german"] { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + app.run(&format!("app.language.{language}"), json!({})).unwrap(); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = (0..3) + .map(|i| Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 }, + kind: RegionKind::Face, + name: None, + description: Some("retained".into()), + }) + .collect(); + let original = meta.regions.clone(); + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + // At this width the naming controls must wrap for Ignore to remain clickable. + let mut h = crate::headless::Headless::new(app, crate::window_place::MIN_SIZE, 1.0); + let timeout = std::time::Duration::from_secs(15); h.step(); - } - assert_eq!(h.app.ui.unnamed_selected.len(), 3); - screenshot_if_requested(&mut h, "LIGHTCRAFT_UNNAMED_SCREENSHOT"); - let before = h.app.session.undo.len(); - assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignore"}), timeout)["ok"], true); - h.step(); - assert_eq!(h.app.session.undo.len(), before + 1); - assert!(h.app.ui.unnamed_selected.is_empty()); - assert!(h.app.session.catalog.photo(id).unwrap().meta.regions.iter().all(|r| r.kind == RegionKind::IgnoredFace)); - assert_eq!(h.app.session.execute("faces.unnamed", &json!({})).unwrap()["total"], 0); - h.app.run("edit.undo", json!({})).unwrap(); - assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); - h.app.run("edit.redo", json!({})).unwrap(); - h.app.run("view.ignoredFaces", json!({})).unwrap(); - h.settle(timeout); - screenshot_if_requested(&mut h, "LIGHTCRAFT_IGNORED_BATCH_SCREENSHOT"); - let before = h.app.session.undo.len(); - for widget in ["ignoredFaces:selectAll", "ignoredFaces:restore"] { - let r = h.request("ui.clickWidget", json!({"id": widget}), timeout); - assert_eq!(r["ok"], true, "{r}"); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + for (index, shift) in [(0, false), (2, true)] { + let r = h.request("ui.clickWidget", json!({"id": format!("unnamed-face:{}:{index}", id.0), "shift": shift}), timeout); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + } + assert_eq!(h.app.ui.unnamed_selected.len(), 3); + screenshot_if_requested( + &mut h, + if language == "german" { "LIGHTCRAFT_UNNAMED_GERMAN_SCREENSHOT" } else { "LIGHTCRAFT_UNNAMED_SCREENSHOT" }, + ); + let before = h.app.session.undo.len(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignore"}), timeout)["ok"], true); h.step(); + assert_eq!(h.app.session.undo.len(), before + 1); + assert!(h.app.ui.unnamed_selected.is_empty()); + assert!(h.app.session.catalog.photo(id).unwrap().meta.regions.iter().all(|r| r.kind == RegionKind::IgnoredFace)); + assert_eq!(h.app.session.execute("faces.unnamed", &json!({})).unwrap()["total"], 0); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); + h.app.run("edit.redo", json!({})).unwrap(); + h.app.run("view.ignoredFaces", json!({})).unwrap(); + h.settle(timeout); + screenshot_if_requested(&mut h, "LIGHTCRAFT_IGNORED_BATCH_SCREENSHOT"); + let before = h.app.session.undo.len(); + for widget in ["ignoredFaces:selectAll", "ignoredFaces:restore"] { + let r = h.request("ui.clickWidget", json!({"id": widget}), timeout); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + } + assert_eq!(h.app.session.undo.len(), before + 1); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); + h.app.run("app.language.english", json!({})).unwrap(); } - assert_eq!(h.app.session.undo.len(), before + 1); - assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions, original); } /// Removing a region must not transfer its selection to the face that takes its index. @@ -321,6 +374,22 @@ mod tests { assert_eq!(view.offset, PAGE_SIZE); assert_eq!(view.faces.as_ref().unwrap().len(), 1); assert!(view.selected.is_empty()); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout)["ok"], true); + h.step(); + h.app.session.execute("photo.rate", &json!({"ids": [id.0], "rating": 3})).unwrap(); + h.step(); + let view = h.app.ui.ignored_faces.as_ref().unwrap(); + assert_eq!(view.offset, PAGE_SIZE, "an unrelated catalog revision keeps the page"); + assert_eq!(view.selected.len(), 1, "and its selection"); + let other = h.app.session.catalog.photos().find(|p| p.id != id).unwrap().id; + let mut meta = h.app.session.catalog.photo(other).unwrap().meta.clone(); + let mut detected = h.app.session.catalog.photo(id).unwrap().meta.regions[0].clone(); + detected.kind = lightcraft_meta::RegionKind::Face; + meta.regions.push(detected); + h.app.session.commit("background detections", lightcraft_catalog::Op::SetMeta { id: other, meta: Box::new(meta) }).unwrap(); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().offset, PAGE_SIZE); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().selected.len(), 1); if let Some(path) = std::env::var_os("LIGHTCRAFT_IGNORED_PAGED_SCREENSHOT") { let shot = h.snapshot(timeout); let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 7076cd30d6d..3d297460676 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -23,7 +23,7 @@ pub struct Selection { faces: std::collections::HashSet<(u64, usize)>, anchor: Option<(usize, bool)>, before_click: Option, - revision: Option, + confirmed: Vec, } #[derive(Clone, Debug)] @@ -200,12 +200,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { app.ui.person_selection = Selection { name: shown_name.clone(), ..Default::default() }; } let selection = &mut app.ui.person_selection; - if selection.revision.is_some_and(|revision| revision != app.session.catalog.revision) { + // A background scan can change the catalog without changing this person's face identities. + // Compare the confirmed list, not the global revision; changed indices/boxes still reset it. + if selection.confirmed != page.confirmed { selection.faces.clear(); selection.anchor = None; selection.before_click = None; + selection.confirmed = page.confirmed.clone(); } - selection.revision = Some(app.session.catalog.revision); if !app.ui.person_selection.faces.is_empty() { let valid: std::collections::HashSet<_> = page.confirmed.iter().map(|f| (f.photo, f.index)).collect(); app.ui.person_selection.faces.retain(|key| valid.contains(key)); @@ -443,7 +445,11 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { let t = Tokens::get(ui.ctx()); let salt = if more { "more-face" } else { "person-face" }; let resp = ui.interact(r, egui::Id::unique((salt, f.photo, f.index)), Sense::click()); - crate::widgets::announce(&resp, name.to_string()); + if more { + crate::widgets::announce(&resp, name.to_string()); + } else { + crate::widgets::announce_selected(&resp, name.to_string(), app.ui.person_selection.faces.contains(&(f.photo, f.index))); + } register(ui, format!("{salt}:{}:{}", f.photo, f.index), r); // the × is added after the tile, so it wins where they overlap let x_rect = Rect::from_min_size(pos2(r.right() - 24.0, r.top() + 4.0), vec2(20.0, 20.0)); @@ -465,7 +471,7 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { p.rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside); } let mut hit = Hit::Nothing; - resp.context_menu(|ui| { + crate::widgets::context_menu(&resp, |ui| { let button = ui.button(crate::i18n::tr("Ignore face (blurry / not a face)")); register(ui, "person:ignoreFace", button.rect); if button.clicked() { @@ -585,6 +591,82 @@ mod tests { assert_eq!(h.app.session.catalog.photo(ids[1]).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); } + /// Confirmed tiles expose both states to screen readers, not only their names. + #[test] + fn confirmed_tiles_announce_selection() { + use egui_kittest::{Harness, kittest::NodeT}; + for selected in [false, true] { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + if selected { + app.ui.person_selection.faces.insert((99, 0)); + } + let h = Harness::builder().build_ui_state( + |ui, app: &mut LightcraftApp| { + let face = Face { photo: 99, index: 0, rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }, score: 0.0 }; + tile( + app, + ui, + &TileSpec { + r: Rect::from_min_size(ui.cursor().min, vec2(100.0, 100.0)), + f: &face, + ppp: 1.0, + more: false, + name: "Person", + above_count: 0, + }, + ); + }, + app, + ); + let node = h.root().children_recursive().find(|n| n.accesskit_node().label().as_deref() == Some("Person")).unwrap(); + assert_eq!( + node.accesskit_node().toggled(), + Some(if selected { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False }) + ); + } + } + + /// An unrelated catalog revision keeps selection, but a different face at the same index does not. + #[test] + fn confirmed_selection_survives_unrelated_changes_but_not_reused_indices() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = (0..2) + .map(|i| lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.3, y0: 0.1, x1: 0.3 + f64::from(i) * 0.3, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Person".into()), + description: None, + }) + .collect(); + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.app.run("view.person", json!({"name": "Person"})).unwrap(); + h.settle(timeout); + h.app.ui.person_selection.active = true; + let faces = h.app.ui.person_selection.confirmed.clone(); + select_confirmed(&mut h.app.ui.person_selection, &faces, &faces[0], false); + h.app.session.execute("photo.rate", &json!({"ids": [id.0], "rating": 4})).unwrap(); + h.step(); + assert_eq!(h.app.ui.person_selection.faces.len(), 1); + assert!(h.app.ui.person_selection.anchor.is_some()); + let other = h.app.session.catalog.photos().find(|p| p.id != id).unwrap().id; + let mut meta = h.app.session.catalog.photo(other).unwrap().meta.clone(); + let mut detected = h.app.session.catalog.photo(id).unwrap().meta.regions[0].clone(); + detected.name = None; + meta.regions.push(detected); + h.app.session.commit("background detections", lightcraft_catalog::Op::SetMeta { id: other, meta: Box::new(meta) }).unwrap(); + h.step(); + assert_eq!(h.app.ui.person_selection.faces.len(), 1); + assert!(h.app.ui.person_selection.anchor.is_some()); + h.app.session.execute("photo.removeRegion", &json!({"id": id.0, "index": 0})).unwrap(); + h.step(); + assert!(h.app.ui.person_selection.faces.is_empty()); + assert!(h.app.ui.person_selection.anchor.is_none()); + } + /// Double-click navigation restores the whole pre-click range and anchor on return. #[test] fn double_clicking_a_confirmed_face_preserves_selection_and_anchor() { diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 4baf80b3cc5..647d32ef7ad 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -135,7 +135,7 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mut submit: Option = None; let mut clear = false; let mut ignore = false; - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { ui.add_space(super::people::PAD - 4.0); let n = selected.len(); ui.label(RichText::new(if n == 1 { "1 face selected".to_string() } else { format!("{n} faces selected") }).color(t.text)); diff --git a/docs/faces.md b/docs/faces.md index 54d0c1e58bd..dc89d0b83de 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -349,7 +349,7 @@ Double-clicking a confirmed face opens its photo and preserves the prior selecti Face naming, ignore/restore, and face-box edits remain catalog-only through Undo and Redo, even when automatic XMP writing is enabled. They do not mark photos as developed -or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Selections are cleared so stale region indices cannot be reused. A command combining face changes or their Undo/Redo with ordinary metadata changes still writes the ordinary metadata when automatic XMP writing is enabled. +or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Unrelated changes preserve the page and selection; changed review entries clear selections so stale region indices cannot be reused. Reading XMP retains local ignored regions, even when the foreign region list omits them; matching boxes keep their original ignored data. A command combining face changes or their Undo/Redo with ordinary metadata changes still writes the ordinary metadata when automatic XMP writing is enabled. Ignored faces require **catalog format 12**. Opening an existing library (format 11 or earlier) upgrades its catalog automatically, preserving existing face assignments and boxes. Older builds then From aae8309f91e056897d07d68d67b9c8992c75ad31 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Thu, 5 Nov 2026 00:31:11 +0100 Subject: [PATCH 03/10] LRC-LIB-PEOPLE: retain unnamed selections and scope accessible toggles Validate selected unnamed face keys against unchanged boxes on every refetch instead of clearing them for unrelated catalog revisions. Preserve the positional anchor only while ordering and boxes remain unchanged; clear focus once selection is empty. Keep the stale-index protection. Only announce confirmed tiles as toggles in explicit selection mode. Extend AccessKit coverage to inactive/active modes and both selection memberships; add rating/background-detection/index-reuse coverage for unnamed selections. Validation: focused UI tests and all eight cargo xtask ci gates passed with craft-fonts; 152 external-data skips unchanged. Minimum-size synthetic UI snapshot inspected. Assisted-by: OpenAI GPT-6.1 Sol --- crates/ui-egui/src/panels/person.rs | 11 +++--- crates/ui-egui/src/panels/unnamed.rs | 58 +++++++++++++++++++++++++--- 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 3d297460676..5e0ec46db08 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -445,10 +445,10 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { let t = Tokens::get(ui.ctx()); let salt = if more { "more-face" } else { "person-face" }; let resp = ui.interact(r, egui::Id::unique((salt, f.photo, f.index)), Sense::click()); - if more { - crate::widgets::announce(&resp, name.to_string()); - } else { + if !more && app.ui.person_selection.active { crate::widgets::announce_selected(&resp, name.to_string(), app.ui.person_selection.faces.contains(&(f.photo, f.index))); + } else { + crate::widgets::announce(&resp, name.to_string()); } register(ui, format!("{salt}:{}:{}", f.photo, f.index), r); // the × is added after the tile, so it wins where they overlap @@ -595,8 +595,9 @@ mod tests { #[test] fn confirmed_tiles_announce_selection() { use egui_kittest::{Harness, kittest::NodeT}; - for selected in [false, true] { + for (active, selected) in [(false, false), (false, true), (true, false), (true, true)] { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + app.ui.person_selection.active = active; if selected { app.ui.person_selection.faces.insert((99, 0)); } @@ -621,7 +622,7 @@ mod tests { let node = h.root().children_recursive().find(|n| n.accesskit_node().label().as_deref() == Some("Person")).unwrap(); assert_eq!( node.accesskit_node().toggled(), - Some(if selected { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False }) + active.then_some(if selected { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False }) ); } } diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 647d32ef7ad..3cded8ace8e 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -70,12 +70,21 @@ pub fn faces(app: &mut LightcraftApp, now: f64) -> Arc { } let v = app.session.execute("faces.unnamed", &json!({})).unwrap_or(Value::Null); let list = Arc::new(parse(&v)); - if app.caches.unnamed.as_ref().is_some_and(|(old, _, _, _)| *old != rev) { - // A removed region can leave another face at the same index. Do not transfer the - // reviewed selection to that face, even when its photo/index pair still exists. - app.ui.unnamed_selected.clear(); - app.ui.unnamed_anchor = None; - app.ui.unnamed_focus = false; + if let Some((_, _, _, old)) = &app.caches.unnamed { + // Keep selections across unrelated edits and background detections, but never transfer + // one to a different box that reuses its photo/index pair. Validate every refetch, since + // recognition can also change display boxes/order without a catalog revision. + let before: std::collections::HashMap<_, _> = old.faces.iter().map(|f| ((f.photo, f.index), f.view)).collect(); + let current: std::collections::HashMap<_, _> = list.faces.iter().map(|f| ((f.photo, f.index), f.view)).collect(); + app.ui.unnamed_selected.retain(|key| matches!((before.get(key), current.get(key)), (Some(a), Some(b)) if a == b)); + // The anchor refers to a position, not a face key. Rating/suggestion changes keep it; + // changed ordering or geometry invalidates it before another Shift-click can use it. + if !old.faces.iter().map(|f| (f.photo, f.index, f.view)).eq(list.faces.iter().map(|f| (f.photo, f.index, f.view))) { + app.ui.unnamed_anchor = None; + } + if app.ui.unnamed_selected.is_empty() { + app.ui.unnamed_focus = false; + } } // what was selected and has since been named (or removed) is no longer selected let present: std::collections::HashSet<(u64, usize)> = list.faces.iter().map(|f| (f.photo, f.index)).collect(); @@ -303,6 +312,43 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize mod tests { use super::*; + #[test] + fn selected_unnamed_faces_survive_unrelated_changes_but_not_index_reuse() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let ids: Vec<_> = app.session.catalog.photos().take(2).map(|p| p.id).collect(); + let regions: Vec<_> = (0..2) + .map(|i| lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.3, y0: 0.1, x1: 0.3 + f64::from(i) * 0.3, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: None, + description: None, + }) + .collect(); + let mut meta = app.session.catalog.photo(ids[0]).unwrap().meta.clone(); + meta.regions = regions.clone(); + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id: ids[0], meta: Box::new(meta) }).unwrap(); + let list = faces(&mut app, 0.0); + click(&mut app, &list, 0, false); + assert!(app.ui.unnamed_focus); + app.session.execute("photo.rate", &json!({"ids": [ids[0].0], "rating": 3})).unwrap(); + faces(&mut app, 1.0); + assert!(app.ui.unnamed_selected.contains(&(ids[0].0, 0))); + assert_eq!(app.ui.unnamed_anchor, Some(0)); + assert!(app.ui.unnamed_focus); + let mut meta = app.session.catalog.photo(ids[1]).unwrap().meta.clone(); + meta.regions = regions; + app.session.commit("background detections", lightcraft_catalog::Op::SetMeta { id: ids[1], meta: Box::new(meta) }).unwrap(); + faces(&mut app, 2.0); + assert!(app.ui.unnamed_selected.contains(&(ids[0].0, 0))); + assert!(app.ui.unnamed_anchor.is_none(), "a positional anchor cannot outlive a changed list"); + assert!(app.ui.unnamed_focus); + app.session.execute("photo.removeRegion", &json!({"id": ids[0].0, "index": 0})).unwrap(); + faces(&mut app, 3.0); + assert!(app.ui.unnamed_selected.is_empty()); + assert!(app.ui.unnamed_anchor.is_none()); + assert!(!app.ui.unnamed_focus); + } + #[test] fn the_engines_answer_becomes_a_list_and_odd_entries_are_left_out() { let v = json!({ From 13707a787203100c18c00045ef67ea3f8f9787b8 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Thu, 5 Nov 2026 00:49:02 +0100 Subject: [PATCH 04/10] LRC-LIB-PEOPLE: identify selected unnamed faces by catalog geometry Retain the catalog rect separately from the detector-aligned display view. Validate selections and range anchors using the catalog geometry so recognition crop refinements do not discard valid selections, focus or anchors. Keep view for rendering. Extend the regression to refresh a changed display crop without a catalog revision, then verify background additions and index reuse. Parser coverage asserts both geometries remain distinct. Validation: focused unnamed and headless ignored-face tests plus all eight cargo xtask ci gates passed with craft-fonts; 152 external-data skips unchanged. Minimum-size synthetic screenshot reinspected. Assisted-by: OpenAI GPT-6.1 Sol --- crates/ui-egui/src/panels/unnamed.rs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 3cded8ace8e..7ac50a31eda 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -19,6 +19,8 @@ use crate::widgets::register; pub struct UnnamedFace { pub photo: u64, pub index: usize, + /// Catalog geometry identifies the region even when recognition refines its display crop. + pub rect: lightcraft_geom::Rect, pub view: lightcraft_geom::Rect, pub suggestion: Option, } @@ -43,6 +45,7 @@ fn face_of(v: &Value) -> Option { Some(UnnamedFace { photo: v["photo"].as_u64()?, index: usize::try_from(v["index"].as_u64()?).ok()?, + rect: rect_of(&v["rect"])?, view: rect_of(&v["view"]).or_else(|| rect_of(&v["rect"]))?, suggestion: v["suggestion"]["name"].as_str().map(str::to_string), }) @@ -74,12 +77,12 @@ pub fn faces(app: &mut LightcraftApp, now: f64) -> Arc { // Keep selections across unrelated edits and background detections, but never transfer // one to a different box that reuses its photo/index pair. Validate every refetch, since // recognition can also change display boxes/order without a catalog revision. - let before: std::collections::HashMap<_, _> = old.faces.iter().map(|f| ((f.photo, f.index), f.view)).collect(); - let current: std::collections::HashMap<_, _> = list.faces.iter().map(|f| ((f.photo, f.index), f.view)).collect(); + let before: std::collections::HashMap<_, _> = old.faces.iter().map(|f| ((f.photo, f.index), f.rect)).collect(); + let current: std::collections::HashMap<_, _> = list.faces.iter().map(|f| ((f.photo, f.index), f.rect)).collect(); app.ui.unnamed_selected.retain(|key| matches!((before.get(key), current.get(key)), (Some(a), Some(b)) if a == b)); // The anchor refers to a position, not a face key. Rating/suggestion changes keep it; // changed ordering or geometry invalidates it before another Shift-click can use it. - if !old.faces.iter().map(|f| (f.photo, f.index, f.view)).eq(list.faces.iter().map(|f| (f.photo, f.index, f.view))) { + if !old.faces.iter().map(|f| (f.photo, f.index, f.rect)).eq(list.faces.iter().map(|f| (f.photo, f.index, f.rect))) { app.ui.unnamed_anchor = None; } if app.ui.unnamed_selected.is_empty() { @@ -335,15 +338,28 @@ mod tests { assert!(app.ui.unnamed_selected.contains(&(ids[0].0, 0))); assert_eq!(app.ui.unnamed_anchor, Some(0)); assert!(app.ui.unnamed_focus); + // A recognition-driven cache refresh changes only the display crop, not the catalog + // revision or region. Seed the prior display crop and expire its embedding-count stamp. + let revision = app.session.catalog.revision; + let (_, indexed, _, cached) = app.caches.unnamed.as_mut().unwrap(); + *indexed = indexed.saturating_add(1); + let old_view = lightcraft_geom::Rect { x0: 0.12, y0: 0.12, x1: 0.28, y1: 0.38 }; + Arc::make_mut(cached).faces[0].view = old_view; + let refreshed = faces(&mut app, 5.0); + assert_eq!(app.session.catalog.revision, revision); + assert_ne!(refreshed.faces[0].view, old_view, "the display crop was refreshed"); + assert!(app.ui.unnamed_selected.contains(&(ids[0].0, 0))); + assert_eq!(app.ui.unnamed_anchor, Some(0)); + assert!(app.ui.unnamed_focus); let mut meta = app.session.catalog.photo(ids[1]).unwrap().meta.clone(); meta.regions = regions; app.session.commit("background detections", lightcraft_catalog::Op::SetMeta { id: ids[1], meta: Box::new(meta) }).unwrap(); - faces(&mut app, 2.0); + faces(&mut app, 6.0); assert!(app.ui.unnamed_selected.contains(&(ids[0].0, 0))); assert!(app.ui.unnamed_anchor.is_none(), "a positional anchor cannot outlive a changed list"); assert!(app.ui.unnamed_focus); app.session.execute("photo.removeRegion", &json!({"id": ids[0].0, "index": 0})).unwrap(); - faces(&mut app, 3.0); + faces(&mut app, 7.0); assert!(app.ui.unnamed_selected.is_empty()); assert!(app.ui.unnamed_anchor.is_none()); assert!(!app.ui.unnamed_focus); @@ -364,6 +380,7 @@ mod tests { assert_eq!((list.total, list.ordered, list.ready, list.faces.len()), (9, true, true, 2)); assert_eq!(list.faces[0].suggestion.as_deref(), Some("Jane Doe")); assert_eq!(list.faces[0].view.x0, 0.12, "the view box is used when there is one"); + assert_eq!(list.faces[0].rect.x0, 0.1, "the catalog box identifies the region independently of its display crop"); assert_eq!((list.faces[1].view.x0, list.faces[1].suggestion.clone()), (0.1, None), "else the face's own box"); for bad in [Value::Null, json!([]), json!({"faces": 5, "total": -1})] { assert_eq!(parse(&bad), Unnamed::default(), "{bad}"); From dbbd474a99e4cb734c4a4ffe77587cd52199dfee Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Thu, 5 Nov 2026 08:03:12 +0100 Subject: [PATCH 05/10] LRC-LIB-PEOPLE: retain per-photo XMP policy in mixed history Replace command-wide face-write suppression with per-log-record policies and positive sidecar targets retained across repeated history merges. Mixed commands and Undo/Redo leave face-only photos untouched while ordinary changes still write their own photos. Clear transient policies with command and log/library lifecycles. Regression coverage: two photos, both operation orders, nested commands, face ignore/restore and Undo/Redo, unchanged externally edited sidecars, absent sidecars, repeated history merging and later ordinary writes. All 43 focused XMP tests and all eight cargo xtask ci gates passed with craft-fonts and Metal; 152 external-data skips documented. The previously published web-test adjustment is unchanged. Assisted-by: OpenAI GPT-6.1 Sol --- crates/engine/src/lib.rs | 59 ++++++++++++------- crates/engine/src/library.rs | 3 + crates/engine/src/sidecar.rs | 9 ++- crates/engine/src/tests/xmp.rs | 101 ++++++++++++++++++++++++++++++++- docs/faces.md | 2 +- 5 files changed, 149 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index af2cc7b98a7..943e7a37a58 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -137,8 +137,9 @@ pub type Result = std::result::Result; pub struct UndoEntry { pub label: String, pub op: Op, - /// This history step must never automatically write metadata beside the originals. - pub(crate) catalog_only: bool, + /// Automatic XMP targets retained through merged history. None uses the operation's targets; + /// Some(empty) is catalog-only, and a mixed step lists only its ordinary-change photos. + pub(crate) sidecar_photos: Option>, /// A folder to rename on disk (`from` → `to`) before `op` is applied: Rename / Move Folder /// (whose `op` relinks the photos inside). Never overwrites; refused when `to` exists. An /// empty `to` removes the (empty) folder `from`, an empty `from` creates `to` (Create Folder). @@ -275,10 +276,11 @@ pub struct Session { pub(crate) pending_sidecar_repairs: Vec, pub interaction: Option, /// Explicit sidecar suppression for imports/background work; consumed when the command ends. - /// Face history uses catalog_only_changes instead, so mixed commands retain ordinary writes. + /// Face history instead keeps a policy per operation, so mixed commands retain ordinary writes. pub(crate) skip_auto_write: bool, - /// Catalog-only log records emitted within the current outer command (not prior pending work). - catalog_only_changes: usize, + /// Overrides for log records emitted in the current outer command, indexed in pending_log. + /// Absent records use op_photos; empty targets suppress only that record, not its neighbours. + sidecar_policies: std::collections::HashMap>, /// The order of Reload from Disk runs, so an older one finishing late is dropped ([`cmd::reload`]). pub(crate) reload_tickets: cmd::reload::Tickets, /// Photos whose automatic XMP sidecar write failed (their folder offline, read-only or full), written again by @@ -482,7 +484,7 @@ impl Session { pending_sidecar_repairs: Vec::new(), interaction: None, skip_auto_write: false, - catalog_only_changes: 0, + sidecar_policies: Default::default(), reload_tickets: Default::default(), unsaved_sidecars: Default::default(), denoise: Default::default(), @@ -598,8 +600,6 @@ impl Session { // last-resort guard: a panic in a command is that command's error, not a crash let r = guard::catch(&format!("`{id}`"), || f(self)).unwrap_or_else(|e| Err(EngineError::Other(e))); self.depth -= 1; - // Count caller changes before automatic version bookkeeping adds its own records. - let command_changes = self.pending_log.len().saturating_sub(log_start); if self.depth == 0 && was_active.is_some() && self.active() != was_active { self.previous_active = was_active; if let Some(left) = was_active { @@ -616,11 +616,11 @@ impl Session { } } if self.depth == 0 { - let catalog_only = std::mem::take(&mut self.catalog_only_changes); - let skip = std::mem::take(&mut self.skip_auto_write) || (catalog_only > 0 && catalog_only == command_changes); + let skip = std::mem::take(&mut self.skip_auto_write); if r.is_ok() && !skip && self.xmp.auto_write && self.interaction.is_none() && self.pending_log.len() > log_start { self.auto_write_sidecars_since(log_start); } + self.sidecar_policies.clear(); } if self.depth == 0 && self.library.is_some() { // Make the command durable before reporting success (natively: handed to the catalog @@ -656,7 +656,7 @@ impl Session { self.undo.push(UndoEntry { label: label.to_string(), op: inv, - catalog_only: false, + sidecar_photos: None, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -673,15 +673,15 @@ impl Session { } /// Commit catalog metadata with history that suppresses automatic sidecar writes, - /// including subsequent Undo/Redo, when the whole command is catalog-only. Direct calls + /// including subsequent Undo/Redo, independently of other operations in the command. Direct calls /// do not leak command-scoped suppression. pub(crate) fn commit_catalog_only(&mut self, label: &str, op: Op) -> Result<()> { self.commit(label, op)?; if let Some(entry) = self.undo.last_mut() { - entry.catalog_only = true; + entry.sidecar_photos = Some(Vec::new()); } if self.depth > 0 { - self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + self.sidecar_policies.insert(self.pending_log.len().saturating_sub(1), Vec::new()); } Ok(()) } @@ -798,12 +798,22 @@ impl Session { return; } let tail = self.undo.split_off(self.undo.len() - n); - let catalog_only = tail.iter().all(|entry| entry.catalog_only); + // Keep the positive write targets, not a single all-or-nothing flag: a face-only photo + // must stay excluded even when another photo in this batch has an ordinary edit. + let mut sidecar_photos = Vec::new(); + for entry in &tail { + match &entry.sidecar_photos { + Some(ids) => sidecar_photos.extend(ids), + None => sidecar::op_photos(&entry.op, &mut sidecar_photos), + } + } + sidecar_photos.sort_unstable(); + sidecar_photos.dedup(); let ops = tail.into_iter().rev().map(|e| e.op).collect(); self.undo.push(UndoEntry { label: label.to_string(), op: Op::Batch { ops }, - catalog_only, + sidecar_photos: Some(sidecar_photos), folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -832,14 +842,16 @@ impl Session { } }; self.show_undone(&e.op); - if self.depth > 0 && e.catalog_only { - self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + if self.depth > 0 + && let Some(ids) = &e.sidecar_photos + { + self.sidecar_policies.insert(self.pending_log.len(), ids.clone()); } self.pending_log.push(e.op); self.redo.push(UndoEntry { label: e.label.clone(), op: redo, - catalog_only: e.catalog_only, + sidecar_photos: e.sidecar_photos, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -863,14 +875,16 @@ impl Session { } }; self.show_undone(&e.op); - if self.depth > 0 && e.catalog_only { - self.catalog_only_changes = self.catalog_only_changes.saturating_add(1); + if self.depth > 0 + && let Some(ids) = &e.sidecar_photos + { + self.sidecar_policies.insert(self.pending_log.len(), ids.clone()); } self.pending_log.push(e.op); self.undo.push(UndoEntry { label: e.label.clone(), op: undo, - catalog_only: e.catalog_only, + sidecar_photos: e.sidecar_photos, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -963,6 +977,7 @@ impl Session { /// Ops applied since the last call, for the op-log store. pub fn drain_log(&mut self) -> Vec { + self.sidecar_policies.clear(); std::mem::take(&mut self.pending_log) } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index bbe590fd3f0..bedfe8aa25d 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -553,6 +553,7 @@ impl Session { self.redo.clear(); self.interaction = None; self.pending_log.clear(); + self.sidecar_policies.clear(); self.selection = Selection::default(); self.source = LibrarySource::All; self.library_folder = None; @@ -703,6 +704,7 @@ impl Session { } lib.retry_at = None; self.pending_log.clear(); + self.sidecar_policies.clear(); lib.last_error = None; } poll_compaction(lib); @@ -816,6 +818,7 @@ impl Session { // the snapshot holds the queued ops: they are saved, never append them again log::info!("library: {unlogged} queued change(s) saved in the closing snapshot"); self.pending_log.clear(); + self.sidecar_policies.clear(); lib.unsaved_error = None; lib.retry_at = None; lib.last_error = None; diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 94a59e339ee..1034170fec3 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -941,8 +941,15 @@ impl Session { pub(crate) fn auto_write_sidecars_since(&mut self, log_start: usize) { let mut ids = Vec::new(); if let Some(ops) = self.pending_log.get(log_start..) { - ops.iter().for_each(|o| op_photos(o, &mut ids)); + for (offset, op) in ops.iter().enumerate() { + match self.sidecar_policies.get(&log_start.saturating_add(offset)) { + Some(targets) => ids.extend(targets), + None => op_photos(op, &mut ids), + } + } } + ids.sort_unstable(); + ids.dedup(); self.auto_write_sidecar_ids(ids); } diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 0c0b0346a42..28fb6a2dff4 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -130,7 +130,7 @@ fn face_history_never_writes_sidecars_or_marks_photos_edited() { // Merging a catalog-only face step with a normal rating step must still allow XMP writes. s.execute("photo.rate", &json!({"ids":[ids[0].0],"rating":5})).unwrap(); s.merge_undo(2, "mixed metadata"); - assert!(!s.undo.last().unwrap().catalog_only); + assert_eq!(s.undo.last().unwrap().sidecar_photos.as_deref(), Some(&[ids[0]][..])); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(ids[0]).unwrap().rating, 0); let packet = std::fs::read_to_string(&sidecar).unwrap(); @@ -214,6 +214,105 @@ fn mixed_face_commands_preserve_ordinary_sidecar_writes() { } } +/// A face-only edit must not rewrite an unrelated photo's externally changed XMP, even +/// inside a nested mixed command or a repeatedly merged history step in either direction. +#[test] +fn mixed_face_operations_write_only_the_ordinary_photos() { + use lightcraft_catalog::{Op, Source}; + use lightcraft_meta::{Metadata, Region, RegionKind}; + for action in ["faces.ignore", "edit.undo", "edit.redo"] { + for ordinary_first in [false, true] { + let src = temp_dir(&format!("mixed-two-photos-{action}-{ordinary_first}")); + write_png(&src.join("a.png"), 3); + write_png(&src.join("b.png"), 9); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let photo = |name: &str| { + s.catalog + .photos() + .find(|p| matches!(&p.source, Source::File { path } if Path::new(path).file_name().is_some_and(|n| n == name))) + .unwrap() + .id + }; + let (a, b) = (photo("a.png"), photo("b.png")); + let mut meta = s.catalog.photo(a).unwrap().meta.clone(); + meta.regions = vec![Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.4, y1: 0.4 }, + kind: RegionKind::Face, + name: None, + description: None, + }]; + s.commit("setup", Op::SetMeta { id: a, meta: Box::new(meta) }).unwrap(); + let faces = json!({"faces": [{"photo": a.0, "index": 0}]}); + if action != "faces.ignore" { + s.execute("faces.ignore", &faces).unwrap(); + } + if action == "edit.redo" { + s.execute("edit.undo", &json!({})).unwrap(); + } + // This editor has not read the new external title. Any accidental auto-write of + // A would replace that owned field with the stale catalog value. + let external = lightcraft_meta::write_xmp(&Metadata { title: Some("External editor's newer title".into()), ..Default::default() }, None); + std::fs::write(src.join("a.xmp"), &external).unwrap(); + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + s.execute_fn("outer mixed", |s| { + s.execute_fn("inner mixed", |s| { + let ordinary = |s: &mut Session| { + let op = Op::SetRating { id: b, rating: 5 }; + if action == "faces.ignore" { s.commit("rating", op) } else { s.apply_system(op) } + }; + if ordinary_first { + ordinary(s)?; + } + let empty = json!({}); + s.execute(action, if action == "faces.ignore" { &faces } else { &empty })?; + if !ordinary_first { + ordinary(s)?; + } + Ok(json!({})) + }) + }) + .unwrap(); + let check = |s: &Session, rating: u8| { + assert_eq!(std::fs::read(src.join("a.xmp")).unwrap(), external.as_bytes(), "{action}, ordinary_first={ordinary_first}"); + assert_eq!(s.catalog.photo(b).unwrap().rating, rating); + assert!(std::fs::read_to_string(src.join("b.xmp")).unwrap().contains(&format!("{rating}"))); + }; + check(&s, 5); + if action == "faces.ignore" { + s.merge_undo(2, "face A and rating B"); + // Merge an already mixed entry again; the positive write targets must survive. + s.execute("photo.rate", &json!({"ids": [b.0], "rating": 3})).unwrap(); + s.merge_undo(2, "merged again"); + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + check(&s, 0); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::Face); + s.execute("edit.redo", &json!({})).unwrap(); + check(&s, 3); + assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::IgnoredFace); + } + } + // The opposite face transition in a mixed command must not create a missing XMP + // either (not merely preserve bytes when a sidecar already exists). + std::fs::remove_file(src.join("a.xmp")).unwrap(); + let ignored = s.catalog.photo(a).unwrap().meta.regions[0].kind == RegionKind::IgnoredFace; + s.execute_fn("mixed restore or ignore", |s| { + s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}], "ignored": !ignored}))?; + s.commit("rating", Op::SetRating { id: b, rating: 2 })?; + Ok(json!({})) + }) + .unwrap(); + assert!(!src.join("a.xmp").exists()); + assert!(std::fs::read_to_string(src.join("b.xmp")).unwrap().contains("2")); + // A later ordinary change in A must not inherit the previous suppression. + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 4})).unwrap(); + assert!(std::fs::read_to_string(src.join("a.xmp")).unwrap().contains("4")); + let _ = std::fs::remove_dir_all(src); + } + } +} + #[test] fn save_delete_library_reimport_restores_edits() { let src = temp_dir("roundtrip-src"); diff --git a/docs/faces.md b/docs/faces.md index dc89d0b83de..1d2aa49a4f9 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -349,7 +349,7 @@ Double-clicking a confirmed face opens its photo and preserves the prior selecti Face naming, ignore/restore, and face-box edits remain catalog-only through Undo and Redo, even when automatic XMP writing is enabled. They do not mark photos as developed -or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Unrelated changes preserve the page and selection; changed review entries clear selections so stale region indices cannot be reused. Reading XMP retains local ignored regions, even when the foreign region list omits them; matching boxes keep their original ignored data. A command combining face changes or their Undo/Redo with ordinary metadata changes still writes the ordinary metadata when automatic XMP writing is enabled. +or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Unrelated changes preserve the page and selection; changed review entries clear selections so stale region indices cannot be reused. Reading XMP retains local ignored regions, even when the foreign region list omits them; matching boxes keep their original ignored data. Mixed commands and merged Undo/Redo write XMP only for photos with ordinary metadata or develop changes; photos with face-only changes keep their sidecars untouched. If both kinds of changes affect the same photo, its ordinary change still triggers the normal metadata write. Ignored faces require **catalog format 12**. Opening an existing library (format 11 or earlier) upgrades its catalog automatically, preserving existing face assignments and boxes. Older builds then From be4a7205c9180598b2e65afc7432cadb7f1c6beb Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Thu, 5 Nov 2026 14:08:09 +0100 Subject: [PATCH 06/10] LRC-LIB-PEOPLE: leave web CPU-reference correction in its own PR Restore wire.rs to upstream main, removing the unrelated render-test adjustment from the face PR diff as requested in review. The CPU-reference correction remains independently reviewable in #3782; no product code or face behavior changes. Validation: fmt, all 39 web library tests under Nextest with retries off, 48 XMP tests and five ignored-face UI tests pass. Verified wire.rs is byte-for-byte unchanged from origin/main. No full CI pass is claimed: upstream #3788 and the default-runner #3778 issue remain documented. Publish this face-integration scope cleanup under the contributor-authorized baseline-failure exception; no tests are removed or assertions relaxed. Assisted-by: OpenAI GPT-6.1 Sol --- apps/lightcraft-web/src/wire.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 2f4c0044f04..bad3507783d 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -455,12 +455,7 @@ mod tests { let mut core = WorkerCore::default(); assert_eq!(core.needs_original(&wire), None, "demo scenes are generated"); let a = core.render(&wire, None).unwrap(); - // A web worker renders on the CPU. Compare its serialized job bit-for-bit with the - // engine's CPU pipeline, not job.run(), which may now render thumbnails on the GPU - // after another test initializes it (CPU/GPU rounding can differ by an LSB). - // The window round-trip test above separately checks the native GPU-capable job. - let source = job.source.load_source().unwrap(); - let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info), &job.settings, &job.request); + let b = job.run().rendered.unwrap(); assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height)); assert_eq!(a.image.data, b.image.data); assert_eq!(a.histogram, b.histogram); From 624d124483864987cde0728573f322146c807936 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Fri, 6 Nov 2026 06:18:21 +0100 Subject: [PATCH 07/10] LRC-LIB-PEOPLE: clear dismissed suggestions when switching libraries Reset dismissed_faces with the other library-scoped face-review state so reused photo/region ids cannot hide unrelated More suggestions in the next library. Seed and assert the dismissed set in the synthetic library-switch regression; reproduced its failure before adding the reset. Remove the unrelated three-line filmstrip override from the stop-and-retry Find Similar test, restoring that function to main. Keep only the face-state library-switch regression in this test file's PR diff. Golden baseline changes remain separate in #3801. Validation: the library-switch regression passes after the fix, as do all nine person-panel and five ignored-review tests. Formatting, ui-egui clippy --all-targets -D warnings, parity and diff checks pass. Targeted validation only; earlier full feature-integration evidence remains tied to 48489f1a. Assisted-by: OpenAI GPT-6.1 Sol --- crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/tests/find_similar.rs | 5 ++--- docs/faces.md | 2 +- docs/gaps.md | 1 + docs/parity-checklist.md | 1 + 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 52d937eab54..424502ea227 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -332,6 +332,7 @@ impl LightcraftApp { crate::find_similar::library_changed(self); self.ui.ignored_faces = None; self.ui.person_selection = Default::default(); + self.ui.dismissed_faces.clear(); self.ui.unnamed_selected.clear(); self.ui.unnamed_anchor = None; self.caches.unnamed = None; diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index cae2ce5b069..5d0bf7b2b0a 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -152,9 +152,6 @@ fn a_second_search_waits_for_the_first() { fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() { let (mut h, drive) = app_on_a_slow_drive(GUARD); h.app.ui.view = ViewMode::Detail; - // Count search reads, not races with filmstrip prefetch warming the same source cache. - // This test has no active photo: hide the filmstrip so only the real search reads files. - h.app.ui.filmstrip = false; h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); // stopped while the searched photo is being read: that one read is all it does assert!(h.step_until(T, |_| drive.reads.load(Ordering::SeqCst) == 1), "the first read never started"); @@ -298,6 +295,7 @@ fn another_library_stops_the_search_and_gets_nothing_from_it() { let dir = std::env::temp_dir().join(format!("lc-ui-similar-other-{}", std::process::id())); // The library-switch hook must invalidate face review as well as cancel the old search. h.app.ui.ignored_faces = Some(Default::default()); + h.app.ui.dismissed_faces.insert((1, 0)); h.app.ui.unnamed_selected.insert((1, 0)); h.app.ui.unnamed_anchor = Some(0); let revision = h.app.session.catalog.revision; @@ -307,6 +305,7 @@ fn another_library_stops_the_search_and_gets_nothing_from_it() { h.app.session.open_library(&dir, false).unwrap(); h.step(); assert!(h.app.ui.ignored_faces.is_none()); + assert!(h.app.ui.dismissed_faces.is_empty()); assert!(h.app.ui.unnamed_selected.is_empty()); assert!(h.app.ui.unnamed_anchor.is_none()); assert!(h.app.caches.unnamed.is_none()); diff --git a/docs/faces.md b/docs/faces.md index 8a9bd2a489e..c84ea365b56 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -321,7 +321,7 @@ by its own box. In **People**, a click on a person opens their page: **only cropped faces**, never whole photos. First the faces named with their name (a click opens that photo), then **More**: the unnamed faces that look like them, most alike first. Click one -to confirm it (that names the face, as one undo step, and it moves up into their faces), or × to hide it for this session. +to confirm it (that names the face, as one undo step, and it moves up into their faces), or × to hide it for this session. Switching libraries clears these temporary dismissals, so another library's suggestions are not hidden. The `↑` control at the top left of a suggested face confirms that face and every currently shown, non-hidden suggestion with an equal or higher similarity score. Its tooltip names the person and shows the number of faces before you act. Hover a suggestion or focus it with the keyboard and press `A` for the same action. The batch is one undo step; diff --git a/docs/gaps.md b/docs/gaps.md index cf31fa5442b..0e41abd18ed 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -97,6 +97,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-11-04 | minor | Gap 6 closed: Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`), OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM; OM / Olympus fully working 6% → 81%) | | 2026-11-05 | patch | LRC-LIB-PEOPLE: use catalog format 13 after shared segmentation grids took format 12 on main; upgrades preserve faces and masks, including earlier face-branch format-12 libraries; no ranked gap/count change | | 2026-11-05 | patch | LRC-LIB-PEOPLE: guard person-page individual and bulk ignore with the catalog rectangle; a stale selection leaves replacement faces untouched; People stays partial and ranked gaps/counts are unchanged | +| 2026-11-06 | patch | LRC-LIB-PEOPLE: switching libraries also clears temporary dismissed suggestions, so reused photo/region ids do not hide another library's faces; no ranked gap/count change | | 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged | | 2026-11-04 | minor | LRC-LIB-PEOPLE: persistent multi-select ignore/restore, format-12 upgrade and model-independent review; People remains partial and ranked gaps/counts are unchanged | | 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 | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index bcf16aa9e05..34e3f72769b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -804,6 +804,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-11-04 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Olympus compressed ORF bitstream decoder implemented (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 and E-M10 Mark III verified on CC0 files; 58 bodies newly unlocked (78 total across Olympus and OM) | | 2026-11-05 | patch | LRC-LIB-PEOPLE: catalog format 13 for ignored faces after main's format-12 shared segmentation grids; mask/face upgrade and replay/compaction coverage, status and counts unchanged | | 2026-11-05 | patch | LRC-LIB-PEOPLE: both person-page ignore actions carry the catalog rectangle so a stale page cannot ignore a replacement at the same region index; detector crops stay display-only; status and counts unchanged | +| 2026-11-06 | patch | LRC-LIB-PEOPLE: clear temporary dismissed suggestions on library switches alongside face-review state; reused ids cannot hide suggestions in the next library; status and counts unchanged | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | | 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | | 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) | From e1d67f67decc1865a2e5bdd8718a1fdd9969b878 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Mon, 9 Nov 2026 21:38:43 +0100 Subject: [PATCH 08/10] 1873: harden persistent face review --- crates/catalog/src/tests_format_version.rs | 41 +++++ crates/engine/src/cmd/face_detect.rs | 14 +- crates/engine/src/cmd/face_recognize.rs | 94 +++++++----- crates/engine/src/errors.rs | 21 +++ crates/engine/src/ignored_faces_index.rs | 78 ++++++++++ crates/engine/src/lib.rs | 8 +- crates/engine/src/tests/face_recognize.rs | 168 ++++++++++++++++++++- crates/engine/src/tests/xmp.rs | 64 +++++--- crates/mcp/src/backend.rs | 29 +++- crates/mcp/src/headless.rs | 15 +- crates/mcp/src/tests.rs | 28 ++++ crates/mcp/src/tools.rs | 18 ++- crates/ui-egui/src/control.rs | 13 +- crates/ui-egui/src/panels/ignored_faces.rs | 100 +++++++++++- crates/ui-egui/src/panels/person.rs | 18 +-- crates/ui-egui/src/panels/unnamed.rs | 31 +++- docs/faces.md | 32 +++- docs/gaps.md | 1 + docs/parity-checklist.md | 1 + 19 files changed, 674 insertions(+), 100 deletions(-) create mode 100644 crates/engine/src/ignored_faces_index.rs diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 5670f111e30..051b47f2557 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -28,6 +28,47 @@ fn snapshot_version(m: &MemStore) -> u64 { v["version"].as_u64().unwrap() } +/// Hand-written old wire payload: never generated by the serializer under test. Only fields +/// present before ignored faces are stated; omitted optional fields exercise legacy defaults. +#[test] +fn frozen_legacy_face_and_mask_payloads_upgrade_and_replay() { + const BODY: &str = r#"{"photos":{"1":{"id":1,"source":{"type":"demo","scene":1},"file_name":"old.jpg","format":"JPEG","width":4,"height":3,"imported":"2026-01-01","meta":{"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.4,"y1":0.6},"kind":"Face","name":"Legacy person","description":"retained"}]},"develop":{"masks":[{"id":1,"components":[{"shape":{"kind":"object","hint":[],"seg":{"side":1,"data":"YwAA"}}}]}]}}},"albums":{},"next_photo":2,"next_album":1}"#; + for version in [9, 10, 11, 12] { + let body = if version == 12 { + BODY.replace("\"data\":\"YwAA\"", "\"grid\":0").replacen("{\"photos\"", "{\"grids\":[\"YwAA\"],\"photos\"", 1) + } else { + BODY.to_string() + }; + let store = MemStore::new(); + store.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{version},\"seq\":0,\"catalog\":{body}}}").into_bytes()); + let (mut journal, mut catalog, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(report.upgraded_from, Some(version)); + assert_eq!(snapshot_version(&store), u64::from(VERSION)); + let photo = catalog.photo(PhotoId(1)).unwrap(); + let mut logits = Vec::new(); + photo.develop.visit_seg_masks(&mut |seg| logits.push(seg.logits())); + assert_eq!(logits, vec![Some(vec![0.0])]); + let mut meta = photo.meta.clone(); + assert_eq!(meta.regions.len(), 1); + assert_eq!(meta.regions[0].kind, lightcraft_meta::RegionKind::Face); + assert_eq!(meta.regions[0].rect, lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.4, y1: 0.6 }); + assert_eq!(meta.regions[0].name.as_deref(), Some("Legacy person")); + assert_eq!(meta.regions[0].description.as_deref(), Some("retained")); + meta.regions[0].kind = lightcraft_meta::RegionKind::IgnoredFace; + let op = Op::SetMeta { id: PhotoId(1), meta: Box::new(meta.clone()) }; + catalog.apply(op.clone()).unwrap(); + journal.append(&[op]).unwrap(); + drop(journal); + let (mut journal, replayed, _) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().meta, meta); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().develop, catalog.photo(PhotoId(1)).unwrap().develop); + journal.snapshot(&replayed).unwrap(); + drop(journal); + let (_, compacted, _) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(compacted.to_snapshot(), replayed.to_snapshot()); + } +} + /// Existing catalogs upgrade before accepting ignored regions, retaining face metadata. #[test] fn legacy_faces_upgrade_without_losing_assignments_or_boxes() { diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 81fa7e03108..a43cb83ce28 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -290,13 +290,19 @@ fn detect(s: &mut Session, p: &Value) -> Result { } results.push(json!({"id": id.0, "faces": faces.iter().map(face_json).collect::>()})); } - let applied = !ops.is_empty(); - if applied { - s.commit_catalog_only("Detect Faces", Op::Batch { ops })?; - } + let applied = commit_detections(s, ops)?; Ok(json!({"detector": LABEL, "applied": applied, "photos": results, "ms": started.elapsed().as_secs_f64() * 1000.0})) } +/// The detector and synthetic regressions share the actual commit path, including XMP policy. +pub(crate) fn commit_detections(s: &mut Session, ops: Vec) -> Result { + if ops.is_empty() { + return Ok(false); + } + s.commit_catalog_only("Detect Faces", Op::Batch { ops })?; + Ok(true) +} + pub fn specs() -> Vec { vec![ cmd!( diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index e89c3a22578..d4633a3a7f8 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -11,7 +11,11 @@ use lightcraft_catalog::Op; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd}; -use crate::{Result, Session}; +use crate::{FaceErrorCode, FaceErrorDetails, Result, Session}; + +fn face_error(cmd: &'static str, code: FaceErrorCode, field: &'static str, target: Option, msg: &str) -> crate::EngineError { + crate::EngineError::FaceRequest { cmd, details: FaceErrorDetails { code, field, target }, msg: msg.into() } +} /// The `name` parameter of the naming commands: a name, or none (`null`, empty) to clear it. fn name_param(p: &Value, c: &str) -> Result> { @@ -31,33 +35,37 @@ fn name_param(p: &Value, c: &str) -> Result> { fn ignore_faces(s: &mut Session, p: &Value) -> Result { use lightcraft_meta::RegionKind; const C: &str = "faces.ignore"; + let invalid = |field, target, msg| face_error(C, FaceErrorCode::InvalidInput, field, target, msg); let ignored = match p.get("ignored") { None => true, - Some(value) => value.as_bool().ok_or_else(|| bad(C, "ignored must be true or false"))?, + Some(value) => value.as_bool().ok_or_else(|| invalid("ignored", None, "ignored must be true or false"))?, }; - let faces = p["faces"].as_array().ok_or_else(|| bad(C, "missing faces"))?; + let faces = p["faces"].as_array().ok_or_else(|| invalid("faces", None, "missing faces"))?; if faces.is_empty() || faces.len() > 100_000 { - return Err(bad(C, "select between 1 and 100000 faces")); + return Err(invalid("faces", None, "select between 1 and 100000 faces")); } let mut edits: std::collections::BTreeMap = Default::default(); let mut seen = std::collections::HashSet::new(); - for face in faces { - let id = lightcraft_catalog::PhotoId(face["photo"].as_u64().ok_or_else(|| bad(C, "missing photo"))?); - let index = face["index"].as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "invalid face index"))?; - if !seen.insert((id, index)) { - continue; - } - let photo = s.catalog.photo(id).filter(|p| p.in_library()).ok_or_else(|| bad(C, "photo is no longer in the library"))?; - let region = photo.meta.regions.get(index).ok_or_else(|| bad(C, "face no longer exists"))?; - let expected = if ignored { RegionKind::Face } else { RegionKind::IgnoredFace }; - if region.kind != expected { - return Err(bad(C, "a selected face changed; reload the faces and try again")); + for (target, face) in faces.iter().enumerate() { + let target = Some(target); + let id = lightcraft_catalog::PhotoId(face["photo"].as_u64().ok_or_else(|| invalid("photo", target, "missing photo"))?); + let index = face["index"].as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("index", target, "invalid face index"))?; + let rect = face.get("rect").ok_or_else(|| invalid("rect", target, "missing reviewed rectangle"))?; + let rect: lightcraft_geom::Rect = serde_json::from_value(rect.clone()).map_err(|_| invalid("rect", target, "invalid reviewed rectangle"))?; + let photo = s + .catalog + .photo(id) + .filter(|p| p.in_library()) + .ok_or_else(|| face_error(C, FaceErrorCode::MissingPhoto, "photo", target, "photo is no longer in the library"))?; + let region = + photo.meta.regions.get(index).ok_or_else(|| face_error(C, FaceErrorCode::MissingFace, "index", target, "face no longer exists"))?; + if rect != region.rect || !matches!(region.kind, RegionKind::Face | RegionKind::IgnoredFace) { + return Err(face_error(C, FaceErrorCode::StaleSelection, "rect", target, "a selected face changed; reload the faces and try again")); } - if let Some(rect) = face.get("rect") { - let rect: lightcraft_geom::Rect = serde_json::from_value(rect.clone()).map_err(|_| bad(C, "invalid reviewed rectangle"))?; - if rect != region.rect { - return Err(bad(C, "a selected face changed; reload the faces and try again")); - } + let desired = if ignored { RegionKind::IgnoredFace } else { RegionKind::Face }; + // Validate even duplicate/no-op targets: retries must not bypass identity checks. + if region.kind == desired || !seen.insert((id, index)) { + continue; } let meta = edits.entry(id).or_insert_with(|| photo.meta.clone()); if let Some(region) = meta.regions.get_mut(index) { @@ -65,38 +73,41 @@ fn ignore_faces(s: &mut Session, p: &Value) -> Result { } } let count = seen.len(); - s.commit_catalog_only( - if ignored { "Ignore Faces" } else { "Restore Ignored Faces" }, - Op::Batch { ops: edits.into_iter().map(|(id, meta)| Op::SetMeta { id, meta: Box::new(meta) }).collect() }, - )?; + if count > 0 { + s.commit_catalog_only( + if ignored { "Ignore Faces" } else { "Restore Ignored Faces" }, + Op::Batch { ops: edits.into_iter().map(|(id, meta)| Op::SetMeta { id, meta: Box::new(meta) }).collect() }, + )?; + } Ok(json!({"changed": count, "ignored": ignored})) } /// List one bounded page of retained ignored regions in catalog order, without a recognition model. fn ignored_faces(s: &mut Session, p: &Value) -> Result { const C: &str = "faces.ignored"; + let invalid = |field, msg| face_error(C, FaceErrorCode::InvalidInput, field, None, msg); let offset = match p.get("offset") { None => 0, - Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "offset must be a nonnegative index"))?, + Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("offset", "offset must be a nonnegative index"))?, }; let limit = match p.get("limit") { None => 1000, - Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(C, "limit must be between 1 and 5000"))?, + Some(value) => value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| invalid("limit", "limit must be between 1 and 5000"))?, }; if !(1..=5000).contains(&limit) { - return Err(bad(C, "limit must be between 1 and 5000")); + return Err(invalid("limit", "limit must be between 1 and 5000")); } let mut faces = Vec::new(); - let mut total = 0usize; - for photo in s.catalog.photos().filter(|p| p.in_library()) { - for (index, region) in photo.meta.regions.iter().enumerate().filter(|(_, r)| r.kind == lightcraft_meta::RegionKind::IgnoredFace) { - if total >= offset && faces.len() < limit { - faces.push(json!({"photo": photo.id.0, "index": index, "rect": region.rect, "view": s.face_view(photo.id, region.rect)})); - } - total = total.saturating_add(1); + let generation = s.library_generation(); + let (total, keys) = s.ignored_faces_index.page(&s.catalog, generation, offset, limit); + for (id, index) in keys { + if let Some(region) = s.catalog.photo(id).and_then(|photo| photo.meta.regions.get(index)) { + faces.push(json!({"photo": id.0, "index": index, "rect": region.rect, "view": s.face_view(id, region.rect), "name": region.name, "description": region.description})); } } - Ok(json!({"total": total, "offset": offset, "faces": faces})) + Ok( + json!({"total": total, "offset": offset, "limit": limit, "hasNext": offset.saturating_add(faces.len()) < total, "revision": s.catalog.revision, "faces": faces}), + ) } /// Give a face region its name. Naming makes the face yours: a later "Detect Faces" run no longer replaces it. @@ -1163,12 +1174,15 @@ mod imp { assert!(similar(&mut s, "nobody", 10).items.is_empty()); // The positive control above produces both candidates. Ignoring a candidate excludes // that exact pair; ignoring Ann's only exemplar must exclude the remaining candidate. - s.execute("faces.ignore", &json!({"faces": [{"photo": b.0, "index": 0}]})).unwrap(); + let reviewed = |id| json!({"faces": [{"photo": id, "index": 0, "rect": region(0.1, None).rect}]}); + s.execute("faces.ignore", &reviewed(b.0)).unwrap(); let pairs = |r: Similar| r.items.iter().map(|i| (i["photo"].as_u64().unwrap(), i["index"].as_u64().unwrap())).collect::>(); assert_eq!(pairs(similar(&mut s, "ann", 10)), vec![(c.0, 0)]); - s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}]})).unwrap(); + s.execute("faces.ignore", &reviewed(a.0)).unwrap(); assert!(pairs(similar(&mut s, "ann", 10)).is_empty()); - s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}], "ignored": false})).unwrap(); + let mut restore = reviewed(a.0); + restore["ignored"] = json!(false); + s.execute("faces.ignore", &restore).unwrap(); assert_eq!(pairs(similar(&mut s, "ann", 10)), vec![(c.0, 0)], "restoring the exemplar restores its suggestion"); let _ = std::fs::remove_dir_all(&d); } @@ -1215,12 +1229,12 @@ pub fn specs() -> Vec { "Ignore Faces", [], None, - "{faces: [{photo, index, rect?}], ignored?: true} — persistently ignore blurry or false faces, or restore them; one undo step; originals are untouched", + "{faces: [{photo, index, rect}], ignored?: boolean (default true)} → {changed, ignored} — ignore or restore 1..100000 reviewed faces atomically; rect must equal catalog geometry, not the display crop. Duplicate identities count once; already-desired states succeed without an undo step. Stale or invalid targets reject the whole batch. Changes are one catalog-only undo step; originals and sidecars stay untouched. Requires catalog format 13; older libraries upgrade on open. Restore large libraries in page-sized batches from faces.ignored", super::always, ignore_faces ), cmd!(query "faces.ignored", "Ignored Faces", [], None, - "{offset?: 0, limit?: 1000} → {total, offset, faces} — review ignored faces in catalog order, including named faces excluded from matching; limit is 1..5000", super::always, ignored_faces), + "{offset?: 0, limit?: 1000} → {total, offset, limit, hasNext, revision, faces: [{photo, index, rect, view, name, description}]} — review ignored faces in catalog order without a model; limit is 1..5000. Offsets describe the current catalog revision, not a snapshot across edits; after a mutation refresh the page and clamp its offset to the last valid page. Restore pages with faces.ignore using ignored:false and their catalog rect", super::always, ignored_faces), cmd!( "faces.index", "Index Faces", diff --git a/crates/engine/src/errors.rs b/crates/engine/src/errors.rs index beb4cefb465..02d4b5b3627 100644 --- a/crates/engine/src/errors.rs +++ b/crates/engine/src/errors.rs @@ -6,6 +6,25 @@ use crate::EngineError; +/// Stable failure reasons for persistent face review commands, independent of message wording. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum FaceErrorCode { + InvalidInput, + MissingPhoto, + MissingFace, + StaleSelection, +} + +/// The parameter and, for a batch, entry that failed validation. No targets have been changed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize)] +pub struct FaceErrorDetails { + pub code: FaceErrorCode, + pub field: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, +} + /// A model a feature needs and LightCraft downloads only when the person agrees. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AiModel { @@ -21,6 +40,7 @@ pub enum ErrorKind { UnknownCommand, Disabled, BadParams, + FaceRequest(FaceErrorDetails), Catalog, NotSaved, LibraryInUse, @@ -39,6 +59,7 @@ impl EngineError { Self::UnknownCommand(_) => ErrorKind::UnknownCommand, Self::Disabled(..) => ErrorKind::Disabled, Self::BadParams { .. } => ErrorKind::BadParams, + Self::FaceRequest { details, .. } => ErrorKind::FaceRequest(*details), Self::Catalog(_) => ErrorKind::Catalog, Self::NotSaved(_) => ErrorKind::NotSaved, Self::LibraryInUse(_) => ErrorKind::LibraryInUse, diff --git a/crates/engine/src/ignored_faces_index.rs b/crates/engine/src/ignored_faces_index.rs new file mode 100644 index 00000000000..e8bb2c78fdf --- /dev/null +++ b/crates/engine/src/ignored_faces_index.rs @@ -0,0 +1,78 @@ +//! Derived ignored-region keys. Never serialized; changes are followed photo by photo. +use std::collections::BTreeMap; + +use lightcraft_catalog::{Aspects, Catalog, PhotoId}; + +#[derive(Default)] +pub(crate) struct Index { + stamp: Option<(u64, u64)>, + photos: BTreeMap>, + total: usize, + #[cfg(test)] + pub scanned: usize, +} + +impl Index { + fn update(&mut self, catalog: &Catalog, id: PhotoId) { + #[cfg(test)] + { + self.scanned += 1; + } + if let Some(old) = self.photos.remove(&id) { + self.total = self.total.saturating_sub(old.len()); + } + let Some(photo) = catalog.photo(id).filter(|photo| photo.in_library()) else { return }; + let keys: Vec<_> = photo + .meta + .regions + .iter() + .enumerate() + .filter(|(_, region)| region.kind == lightcraft_meta::RegionKind::IgnoredFace) + .map(|(index, _)| index) + .collect(); + self.total = self.total.saturating_add(keys.len()); + if !keys.is_empty() { + self.photos.insert(id, keys); + } + } + + pub fn page(&mut self, catalog: &Catalog, generation: u64, offset: usize, limit: usize) -> (usize, Vec<(PhotoId, usize)>) { + let stamp = (generation, catalog.revision); + if self.stamp != Some(stamp) { + let changes = self.stamp.filter(|(g, _)| *g == generation).and_then(|(_, revision)| { + let aspects = catalog.aspects_since(revision)?; + if aspects.any_of(Aspects::META.with(Aspects::PRESENCE)) { catalog.touched_since(revision) } else { Some(Vec::new()) } + }); + match changes { + Some(ids) => { + for id in ids { + self.update(catalog, id); + } + } + None => { + self.photos.clear(); + self.total = 0; + for photo in catalog.photos() { + self.update(catalog, photo.id); + } + } + } + self.stamp = Some(stamp); + } + // Skip whole photos (and slice within one), not every preceding face on a late page. + let mut skip = offset; + let mut keys = Vec::with_capacity(limit); + for (id, indices) in &self.photos { + if skip >= indices.len() { + skip -= indices.len(); + continue; + } + keys.extend(indices.get(skip..).unwrap_or_default().iter().take(limit.saturating_sub(keys.len())).map(|index| (*id, *index))); + skip = 0; + if keys.len() == limit { + break; + } + } + (self.total, keys) + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 369dfff535c..e498c3a85a6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod files; mod focus_scan; pub mod fonts; pub mod guard; +mod ignored_faces_index; pub mod import; mod import_move; pub mod lens_profiles; @@ -91,7 +92,7 @@ pub mod walk; use std::sync::Arc; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use errors::{AiModel, ErrorKind}; +pub use errors::{AiModel, ErrorKind, FaceErrorCode, FaceErrorDetails}; pub use fonts::{CRAFT_FONTS, CraftFont}; use lightcraft_catalog::{Catalog, Filter, Op, PhotoId, Sort}; use lightcraft_develop::DevelopSettings; @@ -108,6 +109,9 @@ pub enum EngineError { Disabled(String, String), #[error("invalid parameters for `{cmd}`: {msg}")] BadParams { cmd: String, msg: String }, + /// Atomic validation failure in `faces.ignore` or `faces.ignored`. + #[error("invalid parameters for `{cmd}`: {msg}")] + FaceRequest { cmd: &'static str, details: FaceErrorDetails, msg: String }, #[error("{0}")] Catalog(#[from] lightcraft_catalog::CatalogError), /// The command's change is applied (in memory, undoable) but its journal records could not @@ -234,6 +238,7 @@ static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64: pub struct Session { library_generation: u64, + pub(crate) ignored_faces_index: ignored_faces_index::Index, /// Auto Sync: edits to the active photo also change the other selected photos (the settings /// that changed, nothing else). pub auto_sync: bool, @@ -473,6 +478,7 @@ impl Session { pub fn new() -> Session { Session { library_generation: LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + ignored_faces_index: Default::default(), auto_sync: false, catalog: Catalog::new(), source: LibrarySource::All, diff --git a/crates/engine/src/tests/face_recognize.rs b/crates/engine/src/tests/face_recognize.rs index 9d69a3b919d..2d6a27e12b2 100644 --- a/crates/engine/src/tests/face_recognize.rs +++ b/crates/engine/src/tests/face_recognize.rs @@ -492,13 +492,22 @@ fn ignored_faces_survive_reopening_and_can_be_restored() { s.faces.index.insert(b.0, ®ion(0.1, None).rect, unit64(&[(0, 1.0)])); let faces = json!([{"photo": a.0,"index":0,"rect":region(0.1,None).rect}, {"photo":b.0,"index":0,"rect":region(0.1,None).rect}]); let before = s.undo.len(); + s.flush_log().unwrap(); + let log = std::fs::read(lib.join("catalog.log")).unwrap(); assert!(s.execute("faces.ignore", &json!({"faces": faces, "ignored": "false"})).is_err()); let mut stale = faces.clone(); stale[1]["rect"] = json!(region(0.3, None).rect); assert!(s.execute("faces.ignore", &json!({"faces":stale})).is_err()); + s.flush_log().unwrap(); + assert_eq!(std::fs::read(lib.join("catalog.log")).unwrap(), log, "invalid batches append no journal records"); assert_eq!(s.undo.len(), before); assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::Face); s.execute("faces.ignore", &json!({"faces":faces})).unwrap(); + s.flush_log().unwrap(); + let log = std::fs::read(lib.join("catalog.log")).unwrap(); + assert_eq!(s.execute("faces.ignore", &json!({"faces":faces})).unwrap()["changed"], 0); + s.flush_log().unwrap(); + assert_eq!(std::fs::read(lib.join("catalog.log")).unwrap(), log, "no-op retries append no journal records"); assert_eq!(s.undo.len(), before + 1); assert_eq!(s.execute("faces.unnamed", &json!({})).unwrap()["total"], 0); assert_eq!(s.execute("faces.person", &json!({"name":"Person"})).unwrap()["total"], 0); @@ -519,6 +528,81 @@ fn ignored_faces_survive_reopening_and_can_be_restored() { let _ = std::fs::remove_dir_all(&d); } +/// Missing/stale identities fail, but retrying a completed transition does not edit history. +#[test] +fn ignore_requires_reviewed_geometry_and_retries_are_noops() { + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().unwrap().id; + let original = region(0.1, Some("Person")); + set_regions(&mut s, id, vec![original.clone()]); + let before = s.undo.len(); + assert!(s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}]})).is_err()); + assert_eq!(s.undo.len(), before); + let params = json!({"faces": [{"photo": id.0, "index": 0, "rect": original.rect}]}); + assert_eq!(s.execute("faces.ignore", ¶ms).unwrap()["changed"], 1); + let (revision, undo, redo) = (s.catalog.revision, s.undo.len(), s.redo.len()); + assert_eq!(s.execute("faces.ignore", ¶ms).unwrap()["changed"], 0); + assert_eq!((s.catalog.revision, s.undo.len(), s.redo.len()), (revision, undo, redo)); + let restored = json!({"faces": params["faces"], "ignored": false}); + assert_eq!(s.execute("faces.ignore", &restored).unwrap()["changed"], 1); + assert_eq!(s.execute("faces.ignore", &restored).unwrap()["changed"], 0); + let before = s.undo.len(); + set_regions(&mut s, id, vec![region(0.5, None)]); + assert!(s.execute("faces.ignore", ¶ms).is_err()); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions[0], region(0.5, None)); + assert_eq!(s.undo.len(), before + 1); +} + +#[test] +fn face_review_errors_have_stable_codes_fields_and_atomic_targets() { + use crate::{ErrorKind, FaceErrorCode as Code, FaceErrorDetails}; + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().unwrap().id; + let original = region(0.1, None); + set_regions(&mut s, id, vec![original.clone()]); + let face = json!({"photo": id.0, "index": 0, "rect": original.rect}); + let mut missing_photo = face.clone(); + missing_photo["photo"] = json!(987_654); + let mut missing_face = face.clone(); + missing_face["index"] = json!(10); + let mut stale = face.clone(); + stale["rect"] = json!(region(0.5, None).rect); + let before = (s.catalog.revision, s.undo.len(), s.redo.len(), s.catalog.to_snapshot()); + for (command, params, code, field, target) in [ + ("faces.ignore", json!({"faces": [face], "ignored": "false"}), Code::InvalidInput, "ignored", None), + ("faces.ignore", json!({"faces": [{"photo": id.0, "index": 0}]}), Code::InvalidInput, "rect", Some(0)), + ("faces.ignore", json!({"faces": [face, missing_photo]}), Code::MissingPhoto, "photo", Some(1)), + ("faces.ignore", json!({"faces": [face, missing_face]}), Code::MissingFace, "index", Some(1)), + ("faces.ignore", json!({"faces": [face, stale]}), Code::StaleSelection, "rect", Some(1)), + ("faces.ignored", json!({"limit": 5001}), Code::InvalidInput, "limit", None), + ("faces.ignored", json!({"offset": -1}), Code::InvalidInput, "offset", None), + ] { + let error = s.execute(command, ¶ms).unwrap_err(); + assert_eq!(error.kind(), ErrorKind::FaceRequest(FaceErrorDetails { code, field, target }), "{error}"); + assert_eq!((s.catalog.revision, s.undo.len(), s.redo.len(), s.catalog.to_snapshot()), before); + } +} + +#[test] +fn ignore_mixed_noops_and_changes_counts_only_transitions_and_preserves_redo() { + let mut s = Session::with_demo(); + let id = s.catalog.photos().next().unwrap().id; + let mut ignored = region(0.1, Some("Person")); + ignored.kind = RegionKind::IgnoredFace; + let ordinary = region(0.5, None); + set_regions(&mut s, id, vec![ignored.clone(), ordinary.clone()]); + let noop = json!({"faces": [{"photo": id.0, "index": 0, "rect": ignored.rect}]}); + let both = json!({"faces": [noop["faces"][0], {"photo": id.0, "index": 1, "rect": ordinary.rect}]}); + let undo = s.undo.len(); + assert_eq!(s.execute("faces.ignore", &both).unwrap()["changed"], 1); + assert_eq!(s.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions, [ignored, ordinary]); + let before = (s.catalog.revision, s.undo.len(), s.redo.len()); + assert_eq!(s.execute("faces.ignore", &noop).unwrap()["changed"], 0); + assert_eq!((s.catalog.revision, s.undo.len(), s.redo.len()), before); +} + /// Invalid targets do not partially apply; duplicate targets are one change and one undo step. #[test] fn ignoring_a_batch_validates_every_face_and_deduplicates_targets() { @@ -529,22 +613,28 @@ fn ignoring_a_batch_validates_every_face_and_deduplicates_targets() { let before = s.undo.len(); for params in [ json!({"faces": []}), - json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": 99}]}), - json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": -1}]}), - json!({"faces": [{"photo": id.0, "index": 0}, {"photo": 987_654, "index": 0}]}), - json!({"faces": [{"photo": id.0, "index": 0}], "ignored": false}), + json!({"faces": [{"photo": id.0, "index": 0, "rect": regions[0].rect}, {"photo": id.0, "index": 99, "rect": regions[0].rect}]}), + json!({"faces": [{"photo": id.0, "index": 0, "rect": regions[0].rect}, {"photo": id.0, "index": -1}]}), + json!({"faces": [{"photo": id.0, "index": 0, "rect": regions[0].rect}, {"photo": 987_654, "index": 0}]}), + json!({"faces": vec![Value::Null; 100_001]}), + json!({"faces": [{"photo": id.0, "index": 0, "rect": regions[0].rect}, {"photo": id.0, "index": 0, "rect": regions[1].rect}]}), ] { assert!(s.execute("faces.ignore", ¶ms).is_err(), "{params}"); assert_eq!(s.catalog.photo(id).unwrap().meta.regions, regions); assert_eq!(s.undo.len(), before); } - let response = s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}, {"photo": id.0, "index": 0}]})).unwrap(); + let face = json!({"photo": id.0, "index": 0, "rect": regions[0].rect}); + let response = s.execute("faces.ignore", &json!({"faces": [face, face]})).unwrap(); assert_eq!(response["changed"], 1); assert_eq!(s.undo.len(), before + 1); assert_eq!(s.catalog.photo(id).unwrap().meta.regions[0].kind, RegionKind::IgnoredFace); assert_eq!(s.catalog.photo(id).unwrap().meta.regions[1], regions[1]); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(id).unwrap().meta.regions, regions); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let (revision, undo) = (s.catalog.revision, s.undo.len()); + assert!(s.execute("faces.ignore", &json!({"faces": [face]})).is_err()); + assert_eq!((s.catalog.revision, s.undo.len()), (revision, undo)); } /// Multiple valid ignore batches can exceed the old whole-library cap; every page stays available. @@ -562,6 +652,8 @@ fn ignored_faces_pages_beyond_100000_and_uses_indexed_views() { let first = s.execute("faces.ignored", &json!({"limit": 2})).unwrap(); assert_eq!(first["total"], 100_001); assert_eq!(first["offset"], 0); + assert_eq!(first["limit"], 2); + assert_eq!(first["hasNext"], true); assert_eq!(first["faces"].as_array().unwrap().len(), 2); assert_eq!(first["faces"][0]["rect"], json!(loose)); assert_eq!(first["faces"][0]["view"], json!(tight)); @@ -569,12 +661,76 @@ fn ignored_faces_pages_beyond_100000_and_uses_indexed_views() { assert_eq!(last["total"], 100_001); assert_eq!(last["faces"].as_array().unwrap().len(), 1); assert_eq!(last["faces"][0]["index"], 100_000); + assert_eq!(last["hasNext"], false); + let scanned = s.ignored_faces_index.scanned; + s.execute("faces.ignored", &json!({"limit": 1})).unwrap(); + assert_eq!(s.ignored_faces_index.scanned, scanned, "paging must not scan the catalog again"); + s.execute("photo.rate", &json!({"ids": [id.0], "rating": 2})).unwrap(); + s.execute("faces.ignored", &json!({"limit": 1})).unwrap(); + assert_eq!(s.ignored_faces_index.scanned, scanned, "rating changes no ignored faces"); assert!(s.execute("faces.ignored", &json!({"offset": 100_001})).unwrap()["faces"].as_array().unwrap().is_empty()); for params in [json!({"limit": 0}), json!({"limit": 5001}), json!({"limit": -1}), json!({"offset": -1})] { assert!(s.execute("faces.ignored", ¶ms).is_err(), "{params}"); } } +#[test] +fn ignored_index_follows_direct_edits_history_and_membership() { + let mut s = Session::with_demo(); + let (a, b) = two_photos(&s); + set_regions(&mut s, a, vec![region(0.1, Some("Person"))]); + set_regions(&mut s, b, vec![region(0.1, None)]); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 0); + let scanned = s.ignored_faces_index.scanned; + let params = json!({"faces": [{"photo": a.0, "index": 0, "rect": region(0.1, None).rect}]}); + s.execute("faces.ignore", ¶ms).unwrap(); + let page = s.execute("faces.ignored", &json!({})).unwrap(); + assert_eq!(page["total"], 1); + assert_eq!(page["faces"][0]["name"], "Person"); + assert_eq!(s.ignored_faces_index.scanned, scanned + 1, "only the affected photo is scanned"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 0); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 1); + s.execute("photo.delete", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 0); + s.execute("photo.restore", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 1); + // An unknown revision forces a safe rebuild, not a stale answer. + s.catalog.revision += 1; + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 1); + let d = temp("ignored-index-switch"); + s.open_library(&d, false).unwrap(); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 0); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(d); +} + +/// Timings are evidence, not a flaky wall-clock assertion. Scan counts prove warm paging work. +#[test] +fn ignored_index_large_catalog_paging_does_not_rescan_regions() { + let mut s = Session::with_demo(); + let mut photo = s.catalog.photos().next().unwrap().as_ref().clone(); + photo.meta.regions = vec![region(0.1, None); 5]; + photo.meta.regions[0].kind = RegionKind::IgnoredFace; + for n in 100..20_100 { + photo.id = lightcraft_catalog::PhotoId(n); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap(); + } + let started = std::time::Instant::now(); + let cold = s.execute("faces.ignored", &json!({"limit": 1000})).unwrap(); + let cold_ms = started.elapsed().as_secs_f64() * 1000.0; + assert_eq!(cold["total"], 20_000); + let scanned = s.ignored_faces_index.scanned; + let started = std::time::Instant::now(); + for offset in (0..20_000).step_by(1000) { + assert_eq!(s.execute("faces.ignored", &json!({"offset": offset})).unwrap()["faces"].as_array().unwrap().len(), 1000); + } + let warm_ms = started.elapsed().as_secs_f64() * 1000.0 / 20.0; + assert_eq!(s.ignored_faces_index.scanned, scanned); + println!("Ignored index: 20000 photos/100000 regions; cold page {cold_ms:.3} ms, warm page mean {warm_ms:.3} ms, photos rescanned 0"); +} + #[test] fn unnamed_faces_come_with_look_alikes_together_and_the_name_the_named_ones_suggest() { let d = temp("unnamed"); @@ -797,7 +953,7 @@ fn ignored_assignments_follow_person_renames_and_merges_without_restoring_faces( let (a, b) = two_photos(&s); set_regions(&mut s, a, vec![region(0.1, Some("Ann"))]); set_regions(&mut s, b, vec![region(0.1, Some("Ann")), region(0.5, Some("Bea"))]); - let face = json!([{ "photo": a.0, "index": 0 }]); + let face = json!([{ "photo": a.0, "index": 0, "rect": region(0.1, None).rect }]); s.execute("faces.ignore", &json!({"faces": face})).unwrap(); s.execute("faces.renamePerson", &json!({"from": "Ann", "to": "Ada"})).unwrap(); assert_eq!(s.catalog.photo(a).unwrap().meta.regions[0].kind, RegionKind::IgnoredFace); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index bd52b135c1c..b61f402b94e 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -75,6 +75,19 @@ fn only(s: &Session) -> PhotoId { s.catalog.photos().next().unwrap().id } +fn assert_face_history_untouched(s: &Session, src: &std::path::Path, ids: &[PhotoId], bytes: &[u8], originals: &[Vec]) { + assert_eq!(std::fs::read(src.join("a.xmp")).unwrap(), bytes); + assert!(!src.join("b.xmp").exists()); + for (i, id) in ids.iter().enumerate() { + let p = s.catalog.photo(*id).unwrap(); + assert!(!p.is_edited()); + assert!(p.edited.is_none()); + assert!(p.history.is_empty()); + assert!(p.versions.is_empty()); + assert_eq!(std::fs::read(src.join(if i == 0 { "a.png" } else { "b.png" })).unwrap(), originals[i]); + } +} + /// Face metadata history preserves original bytes, sidecars and every developed-state marker. #[test] fn face_history_never_writes_sidecars_or_marks_photos_edited() { @@ -99,7 +112,7 @@ fn face_history_never_writes_sidecars_or_marks_photos_edited() { let bytes = std::fs::read(&sidecar).unwrap(); let originals: Vec<_> = ["a.png", "b.png"].iter().map(|n| std::fs::read(src.join(n)).unwrap()).collect(); s.execute("library.xmpPreferences", &json!({"autoWrite":true})).unwrap(); - let faces: Vec<_> = ids.iter().map(|id| json!({"photo":id.0,"index":0})).collect(); + let faces: Vec<_> = ids.iter().map(|id| json!({"photo":id.0,"index":0,"rect":rect})).collect(); for (command, params) in [ ("faces.nameFaces", json!({"faces":faces,"name":"Person"})), ("faces.ignore", json!({"faces":faces})), @@ -111,21 +124,34 @@ fn face_history_never_writes_sidecars_or_marks_photos_edited() { ("photo.removeRegion", json!({"id":ids[0].0,"index":0})), ] { s.execute(command, ¶ms).unwrap(); + if command == "faces.ignore" { + let before = (s.catalog.revision, s.undo.len(), s.redo.len()); + assert_eq!(s.execute(command, ¶ms).unwrap()["changed"], 0); + assert_eq!((s.catalog.revision, s.undo.len(), s.redo.len()), before); + } for history in [None, Some("edit.undo"), Some("edit.redo")] { if let Some(history) = history { s.execute(history, &json!({})).unwrap(); } - assert_eq!(std::fs::read(&sidecar).unwrap(), bytes, "{command} {history:?}"); - assert!(!src.join("b.xmp").exists(), "{command} {history:?}"); - for (i, id) in ids.iter().enumerate() { - let p = s.catalog.photo(*id).unwrap(); - assert!(!p.is_edited()); - assert!(p.edited.is_none()); - assert!(p.history.is_empty()); - assert!(p.versions.is_empty()); - assert_eq!(std::fs::read(src.join(if i == 0 { "a.png" } else { "b.png" })).unwrap(), originals[i]); - } + assert_face_history_untouched(&s, &src, &ids, &bytes, &originals); + } + } + // No detector/model dependency: synthetic results use the production detector's commit path. + let before_detection = s.catalog.photo(ids[0]).unwrap().meta.regions.clone(); + let mut meta = s.catalog.photo(ids[0]).unwrap().meta.clone(); + meta.regions.push(Region { rect, kind: RegionKind::Face, name: None, description: Some("Detected by synthetic test".into()) }); + let after_detection = meta.regions.clone(); + s.execute_fn("faces.detect", |s| { + crate::cmd::face_detect::commit_detections(s, vec![lightcraft_catalog::Op::SetMeta { id: ids[0], meta: Box::new(meta) }])?; + Ok(json!({})) + }) + .unwrap(); + for history in [None, Some("edit.undo"), Some("edit.redo")] { + if let Some(command) = history { + s.execute(command, &json!({})).unwrap(); } + assert_eq!(&s.catalog.photo(ids[0]).unwrap().meta.regions, if history == Some("edit.undo") { &before_detection } else { &after_detection }); + assert_face_history_untouched(&s, &src, &ids, &bytes, &originals); } // Merging a catalog-only face step with a normal rating step must still allow XMP writes. s.execute("photo.rate", &json!({"ids":[ids[0].0],"rating":5})).unwrap(); @@ -165,7 +191,8 @@ fn mixed_face_commands_preserve_ordinary_sidecar_writes() { description: None, }]; s.commit("setup", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); - let faces = json!({"faces": [{"photo": id.0, "index": 0}]}); + let rect = s.catalog.photo(id).unwrap().meta.regions[0].rect; + let faces = json!({"faces": [{"photo": id.0, "index": 0, "rect": rect}]}); if action != "faces.ignore" { s.execute("faces.ignore", &faces).unwrap(); } @@ -201,7 +228,7 @@ fn mixed_face_commands_preserve_ordinary_sidecar_writes() { // leaks into a later outer command. s.execute_fn("only face changes", |s| { for state in [!ignored, ignored] { - s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}], "ignored": state}))?; + s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0, "rect": rect}], "ignored": state}))?; } Ok(json!({})) }) @@ -243,7 +270,8 @@ fn mixed_face_operations_write_only_the_ordinary_photos() { description: None, }]; s.commit("setup", Op::SetMeta { id: a, meta: Box::new(meta) }).unwrap(); - let faces = json!({"faces": [{"photo": a.0, "index": 0}]}); + let rect = s.catalog.photo(a).unwrap().meta.regions[0].rect; + let faces = json!({"faces": [{"photo": a.0, "index": 0, "rect": rect}]}); if action != "faces.ignore" { s.execute("faces.ignore", &faces).unwrap(); } @@ -298,7 +326,7 @@ fn mixed_face_operations_write_only_the_ordinary_photos() { std::fs::remove_file(src.join("a.xmp")).unwrap(); let ignored = s.catalog.photo(a).unwrap().meta.regions[0].kind == RegionKind::IgnoredFace; s.execute_fn("mixed restore or ignore", |s| { - s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0}], "ignored": !ignored}))?; + s.execute("faces.ignore", &json!({"faces": [{"photo": a.0, "index": 0, "rect": rect}], "ignored": !ignored}))?; s.commit("rating", Op::SetRating { id: b, rating: 2 })?; Ok(json!({})) }) @@ -767,7 +795,8 @@ fn rereading_xmp_preserves_ignored_regions_and_other_metadata() { s.open_library(&library, true).unwrap(); s.execute("library.import", &json!({"paths": [src.join("portrait.png").to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); - s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}]})).unwrap(); + let rect = s.catalog.photo(id).unwrap().meta.regions[0].rect; + s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0, "rect": rect}]})).unwrap(); let ignored = s.catalog.photo(id).unwrap().meta.regions.clone(); let empty = MWG_REGIONS.replacen("", "", 1); let absent = lightcraft_meta::write_xmp(&lightcraft_meta::Metadata::default(), None); @@ -921,7 +950,8 @@ fn rereading_rotated_xmp_keeps_ignored_faces_upright_without_duplicates() { s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); let id = only(&s); assert_on_the_upright_face(&s, id, "import"); - s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}]})).unwrap(); + let rect = s.catalog.photo(id).unwrap().meta.regions[0].rect; + s.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0, "rect": rect}]})).unwrap(); let ignored = s.catalog.photo(id).unwrap().meta.regions.clone(); assert_eq!(ignored[0].kind, lightcraft_meta::RegionKind::IgnoredFace); for _ in 0..3 { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index a621f403723..bd9b9b6a4d5 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -14,6 +14,11 @@ const MAX_REPLY: usize = 64 * 1024 * 1024; pub trait Backend { /// Call one method. `Ok` carries the `result`, `Err` the error message. fn call(&mut self, method: &str, params: Value) -> Result; + /// Optional structured validation details for the last call; consumed once. Existing + /// backends and string-only errors keep their contract unchanged. + fn take_error_details(&mut self) -> Option { + None + } /// True when a real UI is attached (`ui.inspect`, `ui.clickWidget`, `ui.pointer` … work). fn has_ui(&self) -> bool; /// Short human description ("headless", "remote 127.0.0.1:7980"). @@ -30,19 +35,20 @@ pub struct Remote { addr: String, conn: Option<(BufReader, TcpStream)>, next_id: u64, + error_details: Option, } impl Remote { /// Connect to `addr` (e.g. `127.0.0.1:7980`), failing fast when nothing is listening. pub fn connect(addr: &str) -> std::io::Result { - let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 }; + let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, error_details: None }; r.reconnect()?; Ok(r) } /// A remote that connects on first use (the app may start after the MCP server). pub fn lazy(addr: &str) -> Self { - Self { addr: addr.to_string(), conn: None, next_id: 1 } + Self { addr: addr.to_string(), conn: None, next_id: 1, error_details: None } } pub fn addr(&self) -> &str { @@ -150,7 +156,12 @@ fn is_idle_close(reply: &Value) -> bool { } impl Backend for Remote { + fn take_error_details(&mut self) -> Option { + self.error_details.take() + } + fn call(&mut self, method: &str, params: Value) -> Result { + self.error_details = None; let id = self.next_id; self.next_id += 1; let line = json!({"id": id, "method": method, "params": params}).to_string(); @@ -191,6 +202,7 @@ impl Backend for Remote { if v.get("ok").and_then(Value::as_bool) == Some(true) { Ok(v.get("result").cloned().unwrap_or(Value::Null)) } else { + self.error_details = v.get("errorDetails").filter(|v| v.is_object()).cloned(); Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string()) } } @@ -240,6 +252,19 @@ mod tests { assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock, "request was resent on a new connection"); } + #[test] + fn remote_keeps_optional_face_error_details_but_preserves_the_error_string() { + with_reply( + br#"{"id":1,"ok":false,"error":"reload faces","errorDetails":{"code":"staleSelection","field":"rect","target":2}} +"#, + |remote, result| { + assert_eq!(result, Err("reload faces".into())); + assert_eq!(remote.take_error_details(), Some(json!({"code":"staleSelection","field":"rect","target":2}))); + assert!(remote.take_error_details().is_none()); + }, + ); + } + #[test] fn mismatched_reply_id_is_rejected_without_resending() { with_reply(b"{\"id\":999,\"ok\":true,\"result\":\"unrelated\"}\n", |remote, result| { diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 11de9141730..b1abdc76566 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -14,6 +14,7 @@ use crate::backend::{Backend, ProgressHook}; pub struct Headless { pub session: Session, progress: Option, + error_details: Option, } impl Drop for Headless { @@ -38,7 +39,7 @@ impl Default for Headless { impl Headless { pub fn new(session: Session) -> Self { - Self { session, progress: None } + Self { session, progress: None, error_details: None } } /// A headless session with the procedurally generated demo library. @@ -116,11 +117,16 @@ impl Headless { } impl Backend for Headless { + fn take_error_details(&mut self) -> Option { + self.error_details.take() + } + fn set_progress(&mut self, hook: Option) { self.progress = hook; } fn call(&mut self, method: &str, params: Value) -> Result { + self.error_details = None; let p = if params.is_null() { json!({}) } else { params }; match method { "engine.execute" | "ui.menu.invoke" | "command" => { @@ -129,7 +135,12 @@ impl Backend for Headless { if id == "app.export" { return self.export(¶ms); } - self.session.execute(id, ¶ms).map_err(|e| e.to_string()) + self.session.execute(id, ¶ms).map_err(|e| { + if let lightcraft_engine::ErrorKind::FaceRequest(details) = e.kind() { + self.error_details = Some(json!(details)); + } + e.to_string() + }) } "engine.commands" => { let mut v: Vec = self.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7cc61a31863..2d1c61f3086 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -51,6 +51,34 @@ fn errors() { assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("unknown command")); } +#[test] +fn face_review_errors_keep_details_for_tools_and_batches_without_leaking() { + let mut b = Headless::new(lightcraft_engine::Session::with_demo()); + for (tool, args) in [ + ("cmd_faces_ignore", json!({"faces": []})), + ("command_run", json!({"id": "faces.ignore", "params": {"faces": []}})), + ("run_command", json!({"command": "faces.ignore", "params": {"faces": []}})), + ] { + let result = call_tool(&mut b, tool, &args); + assert!(result.is_error); + assert_eq!(result.structured.as_ref().unwrap()["errorDetails"], json!({"code": "invalidInput", "field": "faces"})); + assert!(result.content[0]["text"].as_str().unwrap().contains("select between")); + } + let result = call_tool( + &mut b, + "command_batch", + &json!({"stop_on_error": false, "steps": [ + {"id": "faces.ignored", "params": {"limit": 0}}, {"id": "no.such"} + ]}), + ); + assert!(result.is_error); + let structured = result.structured.unwrap(); + assert_eq!(structured["results"][0]["errorDetails"], json!({"code": "invalidInput", "field": "limit"})); + assert!(structured["results"][1].get("errorDetails").is_none()); + assert!(call_tool(&mut b, "no.such", &json!({})).structured.is_none()); + assert!(!call_tool(&mut b, "cmd_faces_ignored", &json!({})).is_error); +} + #[test] fn tools_list_has_helpers_and_every_command() { let mut s = server(); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 1c7ae37011d..4717036ceae 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -599,6 +599,18 @@ fn obj(args: &Value, keys: &[&str]) -> Value { /// Run one tool. pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { + // Never attach details left by a previous tool call to this tool's own validation error. + let _ = b.take_error_details(); + let mut result = call_tool_inner(b, name, args); + if result.is_error + && let Some(details) = b.take_error_details() + { + result.structured = Some(json!({"error": result.content.first().and_then(|v| v["text"].as_str()), "errorDetails": details})); + } + result +} + +fn call_tool_inner(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { let args = if args.is_null() { &json!({}) } else { args }; if !args.is_object() { return ToolResult::error("tool arguments must be an object"); @@ -652,7 +664,11 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { } Err(e) => { failed += 1; - results.push(json!({"ok": false, "error": e})); + let mut result = json!({"ok": false, "error": e}); + if let Some(details) = b.take_error_details() { + result["errorDetails"] = details; + } + results.push(result); if stop { break; } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b24..e99b30e03ff 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -351,9 +351,18 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); return started; } - let r = app.run(id, params); + let r = app.run_typed(id, params); ctx.request_repaint(); - wrap(r) + match r { + Ok(v) => ok(v), + Err(e) => { + let mut reply = failure(&e); + if let lightcraft_engine::ErrorKind::FaceRequest(details) = e.kind { + reply["errorDetails"] = json!(details); + } + Outcome::Done(reply) + } + } } "engine.commands" => ok(all_commands(app)), "ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_entries(app)).unwrap_or_default()), diff --git a/crates/ui-egui/src/panels/ignored_faces.rs b/crates/ui-egui/src/panels/ignored_faces.rs index 2b5eb05c642..01cc61ff001 100644 --- a/crates/ui-egui/src/panels/ignored_faces.rs +++ b/crates/ui-egui/src/panels/ignored_faces.rs @@ -11,15 +11,22 @@ const PAGE_SIZE: usize = 1000; #[derive(Clone, Debug, Default)] pub struct View { faces: Option>>, + views: Vec>, total: usize, offset: usize, selected: HashSet<(u64, usize)>, revision: Option, + index_stamp: Option<(u64, u64)>, anchor: Option<(usize, bool)>, error: Option, } impl View { + fn set_faces(&mut self, faces: Vec) { + self.views = faces.iter().map(|face| serde_json::from_value(face["view"].clone()).ok()).collect(); + self.faces = Some(std::sync::Arc::new(faces)); + } + /// Refresh after catalog/history changes and discard potentially stale selection keys. pub(crate) fn invalidate(&mut self) { *self = Self::default(); @@ -28,6 +35,7 @@ impl View { /// Move to another bounded page, dropping selections whose review entries are no longer shown. fn page(&mut self, offset: usize) { self.faces = None; + self.views.clear(); self.selected.clear(); self.anchor = None; self.error = None; @@ -44,7 +52,17 @@ fn key(face: &Value) -> Option<(u64, usize)> { pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let Some(mut view) = app.ui.ignored_faces.take() else { return }; let t = crate::theme::Tokens::get(ui.ctx()); - if view.revision.is_some_and(|revision| revision != app.session.catalog.revision) { + let index_stamp = (app.caches.faces_epoch, app.caches.faces_indexed); + let regions_changed = view.revision.is_some_and(|revision| { + revision != app.session.catalog.revision + && app + .session + .catalog + .aspects_since(revision) + .is_none_or(|aspects| aspects.any_of(lightcraft_catalog::Aspects::META.with(lightcraft_catalog::Aspects::PRESENCE))) + }); + let crops_changed = view.index_stamp.is_some_and(|stamp| stamp != index_stamp); + if regions_changed || crops_changed { // Refetch on catalog changes, but only discard selection when the displayed entries // change. Background detections elsewhere must not move the review back to page one. match app.session.execute("faces.ignored", &json!({"offset": view.offset, "limit": PAGE_SIZE})) { @@ -55,7 +73,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { view.selected.clear(); view.anchor = None; } - view.faces = Some(std::sync::Arc::new(faces)); + view.set_faces(faces); view.error = None; if view.offset >= view.total && view.offset > 0 { view.page(view.total.saturating_sub(1) / PAGE_SIZE * PAGE_SIZE); @@ -70,6 +88,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } view.revision = Some(app.session.catalog.revision); + view.index_stamp = Some(index_stamp); let mut back = false; egui::Frame::NONE.inner_margin(16).show(ui, |ui| { ui.horizontal_wrapped(|ui| { @@ -88,7 +107,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { match app.session.execute("faces.ignored", &json!({"offset": view.offset, "limit": PAGE_SIZE})) { Ok(response) => { view.total = response["total"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or_default(); - view.faces = Some(std::sync::Arc::new(response["faces"].as_array().cloned().unwrap_or_default())); + view.set_faces(response["faces"].as_array().cloned().unwrap_or_default()); } Err(error) => view.error = Some(error.to_string()), } @@ -141,7 +160,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if restore { let selected: Vec<_> = faces.iter().filter(|f| key(f).is_some_and(|k| view.selected.contains(&k))).cloned().collect(); match app.run("faces.ignore", json!({"faces": selected, "ignored": false})) { - Ok(_) => view.invalidate(), + Ok(_) => { + // Keep the review's place; the next frame clamps a now-empty last page. + view.page(view.offset); + } Err(error) => view.error = Some(error), } return; @@ -163,7 +185,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let image = Rect::from_min_size(area.min, vec2(edge, edge)); let response = ui.interact(image, ui.scope_id().with(("ignored-face", face_key)), Sense::click()); register(ui, format!("ignoredFaces:face:{index}"), image); - if let Ok(rect) = serde_json::from_value(face["view"].clone()) + if let Some(rect) = view.views.get(index).copied().flatten() && let Some(job) = app.session.face_job( lightcraft_catalog::PhotoId(face_key.0), rect, @@ -215,6 +237,23 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { mod tests { use super::*; + #[test] + fn control_face_errors_include_codes_and_fields_without_changing_the_string() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.step(); + let timeout = std::time::Duration::from_secs(15); + for method in ["engine.execute", "ui.menu.invoke", "command"] { + let response = h.request(method, json!({"command": "faces.ignore", "params": {"faces": []}}), timeout); + assert_eq!(response["ok"], false); + assert!(response["error"].as_str().unwrap().contains("select between")); + assert_eq!(response["errorDetails"], json!({"code": "invalidInput", "field": "faces"})); + } + let response = h.request("engine.execute", json!({"command": "no.such"}), timeout); + assert_eq!(response["ok"], false); + assert!(response.get("errorDetails").is_none()); + } + #[test] fn ignored_navigation_discards_old_destinations_but_invalid_person_preserves_review() { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); @@ -336,12 +375,53 @@ mod tests { h.step(); assert_eq!(h.app.ui.unnamed_selected.len(), 1); h.app.session.execute("photo.removeRegion", &json!({"id": id.0, "index": 0})).unwrap(); + // Inject an in-flight stale review: prevent the usual refresh for this click. The + // unnamed action must send its old reviewed box, not read the replacement's box. + h.app.caches.unnamed.as_mut().unwrap().0 = h.app.session.catalog.revision; + let before = (h.app.session.catalog.revision, h.app.session.undo.len()); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignore"}), timeout)["ok"], true); + h.step(); + assert_eq!((h.app.session.catalog.revision, h.app.session.undo.len()), before); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[0].kind, RegionKind::Face); + h.app.caches.unnamed.as_mut().unwrap().0 = h.app.session.catalog.revision.wrapping_sub(1); h.step(); assert!(h.app.ui.unnamed_selected.is_empty()); assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[0].kind, RegionKind::Face); assert!(!h.app.widgets.iter().any(|(id, _)| id == "unnamed:ignore")); } + fn check_range_clear_and_refresh(h: &mut crate::headless::Headless, timeout: std::time::Duration) { + for (index, shift) in [(0, false), (2, true)] { + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("ignoredFaces:face:{index}"), "shift": shift}), timeout)["ok"], true); + h.step(); + } + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().selected.len(), 3); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:clear"}), timeout)["ok"], true); + h.step(); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().selected.is_empty()); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().anchor.is_none()); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:face:0"}), timeout)["ok"], true); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:refresh"}), timeout)["ok"], true); + h.step(); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().selected.is_empty()); + } + + fn check_external_shrink(h: &mut crate::headless::Headless, id: lightcraft_catalog::PhotoId, timeout: std::time::Duration) { + // An external mutation (not Restore's own reset) shrinks the last page and takes + // the revision branch's clamp back to the final valid page. + h.app.session.execute("edit.undo", &json!({})).unwrap(); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:next"}), timeout)["ok"], true); + h.step(); + h.app.session.execute("photo.removeRegion", &json!({"id": id.0, "index": PAGE_SIZE})).unwrap(); + h.step(); + let view = h.app.ui.ignored_faces.as_ref().unwrap(); + assert_eq!((view.offset, view.total), (0, PAGE_SIZE)); + assert_eq!(view.faces.as_ref().unwrap().len(), PAGE_SIZE); + assert!(view.selected.is_empty()); + } + /// A library over one page remains reviewable, and changing pages cannot restore stale selections. #[test] fn ignored_review_pages_and_restores_the_last_face() { @@ -365,6 +445,7 @@ mod tests { h.settle(timeout); assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().len(), PAGE_SIZE); assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().total, PAGE_SIZE + 1); + check_range_clear_and_refresh(&mut h, timeout); assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout)["ok"], true); h.step(); assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().selected.len(), PAGE_SIZE); @@ -374,6 +455,12 @@ mod tests { assert_eq!(view.offset, PAGE_SIZE); assert_eq!(view.faces.as_ref().unwrap().len(), 1); assert!(view.selected.is_empty()); + for (widget, offset) in [("ignoredFaces:previous", 0), ("ignoredFaces:next", PAGE_SIZE)] { + assert_eq!(h.request("ui.clickWidget", json!({"id": widget}), timeout)["ok"], true); + h.step(); + assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().offset, offset); + assert!(h.app.ui.ignored_faces.as_ref().unwrap().selected.is_empty()); + } assert_eq!(h.request("ui.clickWidget", json!({"id": "ignoredFaces:selectAll"}), timeout)["ok"], true); h.step(); h.app.session.execute("photo.rate", &json!({"ids": [id.0], "rating": 3})).unwrap(); @@ -409,6 +496,7 @@ mod tests { assert_eq!(view.total, PAGE_SIZE); assert_eq!(view.offset, 0); assert_eq!(view.faces.as_ref().unwrap().len(), PAGE_SIZE); + check_external_shrink(&mut h, id, timeout); } /// Restore a retained assignment through the actual panel without any recognition model. @@ -474,7 +562,7 @@ mod tests { h.app.session.execute("photo.restore", &json!({"ids": [id.0]})).unwrap(); h.step(); assert_eq!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().len(), 1); - h.app.session.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0}], "ignored": false})).unwrap(); + h.app.session.execute("faces.ignore", &json!({"faces": [{"photo": id.0, "index": 0, "rect": rect}], "ignored": false})).unwrap(); h.step(); assert!(h.app.ui.ignored_faces.as_ref().unwrap().faces.as_ref().unwrap().is_empty()); h.app.session.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 99c2935ddaf..33ee775dfeb 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -24,6 +24,7 @@ pub struct Selection { anchor: Option<(usize, bool)>, before_click: Option, confirmed: Vec, + page: Option>, } #[derive(Clone, Debug)] @@ -201,15 +202,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let selection = &mut app.ui.person_selection; // A background scan can change the catalog without changing this person's face identities. // Compare the confirmed list, not the global revision; changed indices/boxes still reset it. - if selection.confirmed != page.confirmed { - selection.faces.clear(); - selection.anchor = None; - selection.before_click = None; - selection.confirmed = page.confirmed.clone(); - } - if !app.ui.person_selection.faces.is_empty() { - let valid: std::collections::HashSet<_> = page.confirmed.iter().map(|f| (f.photo, f.index)).collect(); - app.ui.person_selection.faces.retain(|key| valid.contains(key)); + if !selection.page.as_ref().is_some_and(|previous| Arc::ptr_eq(previous, &page)) { + if selection.confirmed != page.confirmed { + selection.faces.clear(); + selection.anchor = None; + selection.before_click = None; + selection.confirmed = page.confirmed.clone(); + } + selection.page = Some(page.clone()); } ui.add_space(8.0); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index c1940b35b94..03f066aa288 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -77,12 +77,18 @@ pub fn faces(app: &mut LightcraftApp, now: f64) -> Arc { // Keep selections across unrelated edits and background detections, but never transfer // one to a different box that reuses its photo/index pair. Validate every refetch, since // recognition can also change display boxes/order without a catalog revision. - let before: std::collections::HashMap<_, _> = old.faces.iter().map(|f| ((f.photo, f.index), f.rect)).collect(); - let current: std::collections::HashMap<_, _> = list.faces.iter().map(|f| ((f.photo, f.index), f.rect)).collect(); - app.ui.unnamed_selected.retain(|key| matches!((before.get(key), current.get(key)), (Some(a), Some(b)) if a == b)); + if !app.ui.unnamed_selected.is_empty() { + let before: std::collections::HashMap<_, _> = + old.faces.iter().filter(|f| app.ui.unnamed_selected.contains(&(f.photo, f.index))).map(|f| ((f.photo, f.index), f.rect)).collect(); + let current: std::collections::HashMap<_, _> = + list.faces.iter().filter(|f| app.ui.unnamed_selected.contains(&(f.photo, f.index))).map(|f| ((f.photo, f.index), f.rect)).collect(); + app.ui.unnamed_selected.retain(|key| matches!((before.get(key), current.get(key)), (Some(a), Some(b)) if a == b)); + } // The anchor refers to a position, not a face key. Rating/suggestion changes keep it; // changed ordering or geometry invalidates it before another Shift-click can use it. - if !old.faces.iter().map(|f| (f.photo, f.index, f.rect)).eq(list.faces.iter().map(|f| (f.photo, f.index, f.rect))) { + if app.ui.unnamed_anchor.is_some() + && !old.faces.iter().map(|f| (f.photo, f.index, f.rect)).eq(list.faces.iter().map(|f| (f.photo, f.index, f.rect))) + { app.ui.unnamed_anchor = None; } if app.ui.unnamed_selected.is_empty() { @@ -90,8 +96,10 @@ pub fn faces(app: &mut LightcraftApp, now: f64) -> Arc { } } // what was selected and has since been named (or removed) is no longer selected - let present: std::collections::HashSet<(u64, usize)> = list.faces.iter().map(|f| (f.photo, f.index)).collect(); - app.ui.unnamed_selected.retain(|k| present.contains(k)); + if app.caches.unnamed.is_none() && !app.ui.unnamed_selected.is_empty() { + let present: std::collections::HashSet<_> = list.faces.iter().map(|f| (f.photo, f.index)).collect(); + app.ui.unnamed_selected.retain(|k| present.contains(k)); + } app.caches.unnamed = Some((rev, indexed, now, list.clone())); list } @@ -194,7 +202,16 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } if ignore { - let faces: Vec<_> = selected.iter().map(|(photo, index)| json!({"photo": photo, "index": index})).collect(); + // Use the reviewed catalog geometry, never re-read it from the mutable catalog. + let faces: Vec<_> = app + .caches + .unnamed + .as_ref() + .into_iter() + .flat_map(|c| c.3.faces.iter()) + .filter(|face| app.ui.unnamed_selected.contains(&(face.photo, face.index))) + .map(|face| json!({"photo": face.photo, "index": face.index, "rect": face.rect})) + .collect(); match app.run("faces.ignore", json!({"faces": faces})) { Ok(_) => { app.ui.unnamed_selected.clear(); diff --git a/docs/faces.md b/docs/faces.md index c84ea365b56..0ff5a10fc0d 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -340,8 +340,34 @@ overlapping detection on future scans. Nothing is deleted from the original phot Open **Ignored faces…** from People, select faces, then **Restore selected faces** to include them again. Restoration preserves the original box, name and description; a restored crop returns to the appropriate People view. This review works without -a recognition model installed. Controls and review counts follow the selected interface language. When there are more than 1,000 ignored faces, use **Previous page** and **Next page** to review all of them; selection is cleared when changing pages. The tiles use the same indexed detector crops as People. Open directly with `view.ignoredFaces`. Commands: `faces.ignore {faces: [{photo, index, rect?}], ignored?: true}` -and `faces.ignored {offset?: 0, limit?: 1000}` (at most 5,000 per page; returns the library-wide `total` and page `faces`). Supplying `rect` protects against stale selections; invalid batches change nothing. Both ignore actions on a person's page send the catalog rectangle, not the detector's display crop, so a retained page cannot ignore another face that has taken the same region index. +a recognition model installed. Controls and review counts follow the selected interface language. When there are more than 1,000 ignored faces, use **Previous page** and **Next page** to review all of them; selection is cleared when changing pages. The tiles use the same indexed detector crops as People. Open directly with `view.ignoredFaces`. + +### Ignore/restore command contract + +- `faces.ignore {faces: [{photo, index, rect}], ignored?: boolean}` defaults to `ignored: true`; + `false` restores. Supply 1–100,000 entries. **Every entry requires the reviewed catalog `rect`, + not the detector-aligned `view` crop.** All UI callers use their cached reviewed geometry. +- Validation is atomic, including duplicate and already-desired targets: a missing photo/face, + changed box or invalid field rejects the whole batch, with no history step. Duplicates count + once; already-ignored/restored targets succeed with no change. The response is `{changed, ignored}`; + a wholly no-op retry does not change the revision or Undo/Redo stacks. +- `faces.ignored {offset?: 0, limit?: 1000}` accepts `limit` 1–5,000 and returns + `{total, offset, limit, hasNext, revision, faces: [{photo, index, rect, view, name, description}]}`. + Names/descriptions are retained values or `null`. Order is photo id, then region index. + The derived index follows changed photos; warm pages do not scan the whole library again. +- Offsets refer to the **current revision**, not an immutable snapshot. A region index is not a + stable cursor across removal/reordering. After restoring a page, refetch the **same offset** + (do not advance past entries shifted into it); clamp to `floor((total - 1) / limit) * limit`, + or zero for an empty list. Restore large libraries in page-sized batches until no entries remain. +- Validation failures have distinct codes: `invalidInput`, `missingPhoto` (including a photo + outside the library), `missingFace`, and `staleSelection`. Engine callers match + `ErrorKind::FaceRequest`; control replies preserve the existing string `error` and add + `errorDetails: {code, field, target?}`. `target` is the zero-based entry in `faces` and `field` + is its field (or a top-level parameter when `target` is absent). MCP tools preserve these + details in `structuredContent`, including per-step failures in `command_batch`. + +These commands require a build supporting catalog format 13 (discover them through +`engine.commands` / MCP `command_list`); they are not available in older builds. Select all in ignored-face review selects the current page only. On a person's page it selects the displayed confirmed faces (up to 5,000), not hidden results. @@ -349,7 +375,7 @@ Double-clicking a confirmed face opens its photo and preserves the prior selecti Face naming, ignore/restore, and face-box edits remain catalog-only through Undo and Redo, even when automatic XMP writing is enabled. They do not mark photos as developed -or add develop-history entries. The ignored-face review refreshes whenever the catalog revision changes, including direct-session commands and deletion/restoration. Unrelated changes preserve the page and selection; changed review entries clear selections so stale region indices cannot be reused. Reading XMP retains local ignored regions, even when the foreign region list omits them; matching boxes keep their original ignored data. Mixed commands and merged Undo/Redo write XMP only for photos with ordinary metadata or develop changes; photos with face-only changes keep their sidecars untouched. If both kinds of changes affect the same photo, its ordinary change still triggers the normal metadata write. +or add develop-history entries. Manual Detect Faces uses the same catalog-only commit/history policy. The ignored-face review refreshes for metadata/membership changes (including direct-session commands and deletion/restoration) and indexed-crop changes; unrelated ratings do not refetch the page. Unrelated changes preserve the page and selection; changed review entries clear selections so stale region indices cannot be reused. Reading XMP retains local ignored regions, even when the foreign region list omits them; matching boxes keep their original ignored data. Mixed commands and merged Undo/Redo write XMP only for photos with ordinary metadata or develop changes; photos with face-only changes keep their sidecars untouched. If both kinds of changes affect the same photo, its ordinary change still triggers the normal metadata write. Ignored faces require **catalog format 13**. Opening an existing library (format 12 or earlier) upgrades its catalog automatically, preserving existing face assignments and boxes. Older builds then diff --git a/docs/gaps.md b/docs/gaps.md index 673b196bad6..3e181dc57dd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -92,6 +92,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | LRC-LIB-PEOPLE: require reviewed boxes in every ignore action, make retries no-ops, expose retained metadata/page/error details, follow changed photos in a derived ignored-face index, and cover literal legacy masks/faces plus Detect Faces catalog-only history; partial status and counts unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-11-05 | patch | LRC-LIB-PEOPLE: use catalog format 13 after shared segmentation grids took format 12 on main; upgrades preserve faces and masks, including earlier face-branch format-12 libraries; no ranked gap/count change | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 25b48aa6787..cf900a9d960 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-09 | patch | LRC-LIB-PEOPLE: reviewed-rectangle validation in all ignore actions, idempotent retries, retained metadata and pagination/error details, incremental ignored-face queries, independent legacy wire payloads and Detect Faces/XMP history coverage; status and counts unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-11-05 | patch | LRC-LIB-PEOPLE: catalog format 13 for ignored faces after main's format-12 shared segmentation grids; mask/face upgrade and replay/compaction coverage, status and counts unchanged | From 526d4c7a4c1f9e3620c81f05cab07312fd958809 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Mon, 9 Nov 2026 22:31:19 +0100 Subject: [PATCH 09/10] 1873: reject incomplete unnamed ignore selections --- crates/engine/src/cmd/face_recognize.rs | 1 + crates/engine/src/ignored_faces_index.rs | 3 ++ crates/engine/src/tests/face_recognize.rs | 3 ++ crates/engine/src/tests/xmp.rs | 1 + crates/mcp/src/backend.rs | 1 + crates/mcp/src/tests.rs | 1 + crates/mcp/src/tools.rs | 1 + crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/panels/ignored_faces.rs | 4 ++ crates/ui-egui/src/panels/unnamed.rs | 55 ++++++++++++++++++++++ docs/faces.md | 2 + 27 files changed, 106 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/face_recognize.rs b/crates/engine/src/cmd/face_recognize.rs index d4633a3a7f8..4493d14909f 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd}; use crate::{FaceErrorCode, FaceErrorDetails, Result, Session}; +/// Keep validation reasons/locations stable while the message remains free to change. fn face_error(cmd: &'static str, code: FaceErrorCode, field: &'static str, target: Option, msg: &str) -> crate::EngineError { crate::EngineError::FaceRequest { cmd, details: FaceErrorDetails { code, field, target }, msg: msg.into() } } diff --git a/crates/engine/src/ignored_faces_index.rs b/crates/engine/src/ignored_faces_index.rs index e8bb2c78fdf..94b47f43425 100644 --- a/crates/engine/src/ignored_faces_index.rs +++ b/crates/engine/src/ignored_faces_index.rs @@ -13,6 +13,7 @@ pub(crate) struct Index { } impl Index { + /// Replace one photo's derived keys/count, including removal from the library. fn update(&mut self, catalog: &Catalog, id: PhotoId) { #[cfg(test)] { @@ -36,6 +37,8 @@ impl Index { } } + /// Follow catalog changes, then return a page in photo/region order. The command validates + /// `limit` (1..=5000) before calling. A cold/unknown-history rebuild is synchronous. pub fn page(&mut self, catalog: &Catalog, generation: u64, offset: usize, limit: usize) -> (usize, Vec<(PhotoId, usize)>) { let stamp = (generation, catalog.revision); if self.stamp != Some(stamp) { diff --git a/crates/engine/src/tests/face_recognize.rs b/crates/engine/src/tests/face_recognize.rs index 2d6a27e12b2..3045fb29d62 100644 --- a/crates/engine/src/tests/face_recognize.rs +++ b/crates/engine/src/tests/face_recognize.rs @@ -553,6 +553,7 @@ fn ignore_requires_reviewed_geometry_and_retries_are_noops() { assert_eq!(s.undo.len(), before + 1); } +/// Every validation category carries its parameter location and leaves the whole catalog intact. #[test] fn face_review_errors_have_stable_codes_fields_and_atomic_targets() { use crate::{ErrorKind, FaceErrorCode as Code, FaceErrorDetails}; @@ -583,6 +584,7 @@ fn face_review_errors_have_stable_codes_fields_and_atomic_targets() { } } +/// Mixed batches edit only transitions, while a no-op retry keeps a pending Redo intact. #[test] fn ignore_mixed_noops_and_changes_counts_only_transitions_and_preserves_redo() { let mut s = Session::with_demo(); @@ -674,6 +676,7 @@ fn ignored_faces_pages_beyond_100000_and_uses_indexed_views() { } } +/// Derived keys follow edits/history/membership and cannot leak across library generations. #[test] fn ignored_index_follows_direct_edits_history_and_membership() { let mut s = Session::with_demo(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index b61f402b94e..c7916d5698a 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -75,6 +75,7 @@ fn only(s: &Session) -> PhotoId { s.catalog.photos().next().unwrap().id } +/// Face-only commits/history must preserve both files and every develop-state marker. fn assert_face_history_untouched(s: &Session, src: &std::path::Path, ids: &[PhotoId], bytes: &[u8], originals: &[Vec]) { assert_eq!(std::fs::read(src.join("a.xmp")).unwrap(), bytes); assert!(!src.join("b.xmp").exists()); diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index bd9b9b6a4d5..a9ecd53bb8a 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -252,6 +252,7 @@ mod tests { assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock, "request was resent on a new connection"); } + /// Remote clients retain optional details without changing string-only error handling. #[test] fn remote_keeps_optional_face_error_details_but_preserves_the_error_string() { with_reply( diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2d1c61f3086..0a06b247d24 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -51,6 +51,7 @@ fn errors() { assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("unknown command")); } +/// Generated/alias tools and batches retain validation details, but later errors inherit none. #[test] fn face_review_errors_keep_details_for_tools_and_batches_without_leaking() { let mut b = Headless::new(lightcraft_engine::Session::with_demo()); diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 4717036ceae..e7eba6b8d28 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -610,6 +610,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { result } +/// Dispatch a tool; the outer wrapper attaches the backend's optional error details. fn call_tool_inner(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { let args = if args.is_null() { &json!({}) } else { args }; if !args.is_object() { diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index bc0b23e884d..ebffcb4ece3 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2490,5 +2490,6 @@ "Welcome": "Vítejte", "Next": "Další", "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" + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Některé vybrané tváře nejsou dostupné. Žádná tvář nebyla ignorována. Zrušte výběr a zkuste to znovu." } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 7e6f27b8aac..284e9875cba 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3525,5 +3525,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", "Welcome": "Willkommen", "Next": "Weiter", - "Get Started": "Loslegen" + "Get Started": "Loslegen", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Einige ausgewählte Gesichter sind nicht verfügbar. Es wurde nichts ignoriert. Hebe die Auswahl auf und versuche es erneut." } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 07249af9b66..478c9f4f948 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2448,5 +2448,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", "Welcome": "Bienvenido", "Next": "Siguiente", - "Get Started": "Empezar" + "Get Started": "Empezar", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Algunos rostros seleccionados no están disponibles. No se ha ignorado ninguno. Borra la selección e inténtalo de nuevo." } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index d3ce5e95a8e..753db2afae4 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2402,5 +2402,6 @@ "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Valitse kasvot tai poista valinta napsauttamalla. Vaihto-napsautus laajentaa toiminnon alueelle. Kaksoisnapsautus avaa kuvan.", "Ignore Faces": "Ohita kasvot", "Restore Ignored Faces": "Palauta ohitetut kasvot", - "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Jotkin valitut kasvot eivät ole käytettävissä. Mitään ei ohitettu. Tyhjennä valinta ja yritä uudelleen." } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 12964390f78..ebeabdb8d51 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3627,5 +3627,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", "Welcome": "Bienvenue", "Next": "Suivant", - "Get Started": "Commencer" + "Get Started": "Commencer", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Certains visages sélectionnés ne sont pas disponibles. Aucun n’a été ignoré. Effacez la sélection et réessayez." } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 4c2f1eca0bd..2af56bd6cc4 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2418,5 +2418,6 @@ "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Klik wajah untuk memilih atau membatalkan pilihan. Shift-klik memperluas tindakan ke suatu rentang. Klik dua kali membuka foto.", "Ignore Faces": "Abaikan Wajah", "Restore Ignored Faces": "Pulihkan Wajah yang Diabaikan", - "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Beberapa wajah yang dipilih tidak tersedia. Tidak ada yang diabaikan. Hapus pilihan dan coba lagi." } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5160ecfb814..a892d309511 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2608,5 +2608,6 @@ "Welcome": "Benvenuto", "Next": "Avanti", "Get Started": "Inizia", - "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Alcuni volti selezionati non sono disponibili. Nessun volto è stato ignorato. Cancella la selezione e riprova." } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 5fb233f9a04..a8e5d72ea21 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2446,5 +2446,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", "Welcome": "ようこそ", "Next": "次へ", - "Get Started": "始める" + "Get Started": "始める", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "選択した顔の一部を利用できません。どの顔も無視されていません。選択を解除して、もう一度お試しください。" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 3f87ed09f2a..b89d543b09d 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3710,5 +3710,6 @@ "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "დააწკაპუნეთ სახის მოსანიშნად ან მონიშვნის გასაუქმებლად. Shift-დაწკაპუნება მოქმედებას დიაპაზონზე ავრცელებს. ორმაგი დაწკაპუნება ფოტოს ხსნის.", "Ignore Faces": "სახეების უგულებელყოფა", "Restore Ignored Faces": "უგულებელყოფილი სახეების აღდგენა", - "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "ზოგიერთი არჩეული სახე მიუწვდომელია. არცერთი სახე არ იგნორირებულა. გააუქმეთ მონიშვნა და სცადეთ ხელახლა." } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 77db1b82bf8..b9d0fb12100 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2370,5 +2370,6 @@ "Welcome": "Witamy", "Next": "Dalej", "Get Started": "Zaczynamy", - "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Niektóre zaznaczone twarze są niedostępne. Żadna twarz nie została zignorowana. Wyczyść zaznaczenie i spróbuj ponownie." } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 1b40db15a68..f003b5b2036 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2292,5 +2292,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", "Welcome": "Bem-vindo", "Next": "Próximo", - "Get Started": "Começar" + "Get Started": "Começar", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Alguns rostos selecionados estão indisponíveis. Nenhum foi ignorado. Limpe a seleção e tente novamente." } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 3ef31ce90e0..073e0cb8196 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2650,5 +2650,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", "Welcome": "Добро пожаловать", "Next": "Далее", - "Get Started": "Начать" + "Get Started": "Начать", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Некоторые выбранные лица недоступны. Ни одно лицо не было проигнорировано. Снимите выделение и повторите попытку." } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 256badab582..4d55778306d 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2505,5 +2505,6 @@ "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Klicka på ansikten för att markera eller avmarkera. Skift-klick utökar åtgärden till ett intervall. Dubbelklick öppnar ett foto.", "Ignore Faces": "Ignorera ansikten", "Restore Ignored Faces": "Återställ ignorerade ansikten", - "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Vissa markerade ansikten är inte tillgängliga. Inga ansikten ignorerades. Rensa markeringen och försök igen." } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 0d75e91f8ba..3e4e68271b6 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2444,5 +2444,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", "Welcome": "Ласкаво просимо", "Next": "Далі", - "Get Started": "Почати" + "Get Started": "Почати", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Деякі вибрані обличчя недоступні. Жодне обличчя не було проігноровано. Зніміть виділення та спробуйте знову." } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 71a0cd1d2a3..a01ee9a6e11 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2729,5 +2729,6 @@ "Click faces to select or deselect. Shift-click extends that action to a range. Double-click opens a photo.": "Nhấp vào khuôn mặt để chọn hoặc bỏ chọn. Giữ Shift và nhấp để mở rộng thao tác cho một dải. Nhấp đúp để mở ảnh.", "Ignore Faces": "Bỏ qua khuôn mặt", "Restore Ignored Faces": "Khôi phục khuôn mặt đã bỏ qua", - "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" + "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", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Một số khuôn mặt đã chọn không khả dụng. Chưa có khuôn mặt nào bị bỏ qua. Hãy xóa lựa chọn rồi thử lại." } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 819b867bd14..82a815f36f3 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2447,5 +2447,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", "Welcome": "欢迎", "Next": "下一步", - "Get Started": "开始使用" + "Get Started": "开始使用", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "部分选中的人脸不可用。未忽略任何人脸。请清除选择后重试。" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index d7fe3f822b5..84e9b27473e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2448,5 +2448,6 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", "Welcome": "歡迎", "Next": "下一步", - "Get Started": "開始使用" + "Get Started": "開始使用", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "部分選取的人臉無法使用。未忽略任何人臉。請清除選取後重試。" } diff --git a/crates/ui-egui/src/panels/ignored_faces.rs b/crates/ui-egui/src/panels/ignored_faces.rs index 01cc61ff001..e2f91be4f49 100644 --- a/crates/ui-egui/src/panels/ignored_faces.rs +++ b/crates/ui-egui/src/panels/ignored_faces.rs @@ -22,6 +22,7 @@ pub struct View { } impl View { + /// Parse display geometry once, while retaining the reviewed command payload unchanged. fn set_faces(&mut self, faces: Vec) { self.views = faces.iter().map(|face| serde_json::from_value(face["view"].clone()).ok()).collect(); self.faces = Some(std::sync::Arc::new(faces)); @@ -237,6 +238,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { mod tests { use super::*; + /// Control aliases expose typed face failures without altering other command errors. #[test] fn control_face_errors_include_codes_and_fields_without_changing_the_string() { let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); @@ -390,6 +392,7 @@ mod tests { assert!(!h.app.widgets.iter().any(|(id, _)| id == "unnamed:ignore")); } + /// Exercise range selection and both explicit ways to discard that selection. fn check_range_clear_and_refresh(h: &mut crate::headless::Headless, timeout: std::time::Duration) { for (index, shift) in [(0, false), (2, true)] { assert_eq!(h.request("ui.clickWidget", json!({"id": format!("ignoredFaces:face:{index}"), "shift": shift}), timeout)["ok"], true); @@ -407,6 +410,7 @@ mod tests { assert!(h.app.ui.ignored_faces.as_ref().unwrap().selected.is_empty()); } + /// Removing the final page externally must clamp to the final valid page, not stay empty. fn check_external_shrink(h: &mut crate::headless::Headless, id: lightcraft_catalog::PhotoId, timeout: std::time::Duration) { // An external mutation (not Restore's own reset) shrinks the last page and takes // the revision branch's clamp back to the final valid page. diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 03f066aa288..6d2f6d4b07f 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -212,6 +212,11 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { .filter(|face| app.ui.unnamed_selected.contains(&(face.photo, face.index))) .map(|face| json!({"photo": face.photo, "index": face.index, "rect": face.rect})) .collect(); + // A partial cache must never turn the person's whole selection into a partial commit. + if faces.len() != app.ui.unnamed_selected.len() { + app.toast(ui.ctx(), crate::i18n::tr("Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.")); + return; + } match app.run("faces.ignore", json!({"faces": faces})) { Ok(_) => { app.ui.unnamed_selected.clear(); @@ -332,6 +337,56 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize mod tests { use super::*; + /// A partial cached selection must not become a successful partial Ignore batch. + #[test] + fn ignoring_an_incomplete_cached_selection_changes_nothing_and_keeps_the_selection() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let id = app.session.catalog.photos().next().unwrap().id; + let mut meta = app.session.catalog.photo(id).unwrap().meta.clone(); + meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.3, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: None, + description: None, + }]; + app.session.commit("setup", lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + let timeout = std::time::Duration::from_secs(15); + h.step(); + h.app.run("view.people", json!({})).unwrap(); + h.settle(timeout); + // Inject an inconsistent selection after the normal refresh/pruning has run. + h.app.ui.unnamed_selected.extend([(id.0, 0), (id.0, 99)]); + h.app.ui.unnamed_anchor = Some(0); + h.step(); + let before = (h.app.session.catalog.revision, h.app.session.undo.len(), h.app.ui.unnamed_selected.clone()); + assert_eq!(h.request("ui.clickWidget", json!({"id": "unnamed:ignore"}), timeout)["ok"], true); + h.step(); + assert_eq!((h.app.session.catalog.revision, h.app.session.undo.len(), h.app.ui.unnamed_selected.clone()), before); + assert_eq!(h.app.ui.unnamed_anchor, Some(0)); + assert_eq!(h.app.session.catalog.photo(id).unwrap().meta.regions[0].kind, lightcraft_meta::RegionKind::Face); + assert_eq!( + h.app.ui.toast.as_ref().unwrap().0, + crate::i18n::tr("Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.") + ); + capture_incomplete_selection_if_requested(&mut h, timeout); + } + + /// Capture the synthetic app through the same snapshot path as the other face-panel tests. + fn capture_incomplete_selection_if_requested(h: &mut crate::headless::Headless, timeout: std::time::Duration) { + let Some(path) = std::env::var_os("LIGHTCRAFT_INCOMPLETE_FACE_SELECTION_SCREENSHOT") else { return }; + let shot = h.snapshot(timeout); + let image = lightcraft_raster::Rgba8::from_fn(shot.size[0], shot.size[1], |x, y| shot.pixels[y * shot.size[0] + x].to_array()); + let png = lightcraft_engine::export::encode_image( + &image, + &lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }, + ) + .unwrap(); + std::fs::write(path, png).unwrap(); + let inspected = h.request("ui.inspect", json!({}), timeout); + println!("Incomplete face-selection perf: {}", inspected["result"]["perf"]); + } + #[test] fn selected_unnamed_faces_survive_unrelated_changes_but_not_index_reuse() { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); diff --git a/docs/faces.md b/docs/faces.md index 0ff5a10fc0d..3f63ea24365 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -351,6 +351,8 @@ a recognition model installed. Controls and review counts follow the selected in changed box or invalid field rejects the whole batch, with no history step. Duplicates count once; already-ignored/restored targets succeed with no change. The response is `{changed, ignored}`; a wholly no-op retry does not change the revision or Undo/Redo stacks. + If Unnamed faces cannot find every selected key in its reviewed cache, it refuses the entire + action, keeps the selection and asks you to clear/reselect; it never silently ignores a subset. - `faces.ignored {offset?: 0, limit?: 1000}` accepts `limit` 1–5,000 and returns `{total, offset, limit, hasNext, revision, faces: [{photo, index, rect, view, name, description}]}`. Names/descriptions are retained values or `null`. Order is photo id, then region index. From 200dae1404113982cff6e4b98f571e10b455ca39 Mon Sep 17 00:00:00 2001 From: Lars Ostwald Date: Sun, 29 Nov 2026 22:29:21 +0100 Subject: [PATCH 10/10] fix(ci): simplify culling, panel and brush predicates (#4897) --- crates/engine/src/cmd/cull.rs | 2 +- crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/panels/detail/brush.rs | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 325b7ffb520..6f922a2a112 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -115,7 +115,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let mut members: std::collections::BTreeMap> = Default::default(); let mut arranged: std::collections::BTreeMap> = Default::default(); for (i, r) in rows.iter().enumerate() { - if index.contains_key(&r.0) || !s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) { + if index.contains_key(&r.0) || s.catalog.photo(r.0).is_none_or(|ph| ph.deleted) { continue; } match kept[i] { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index f0a19797ec8..f261d54c912 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -732,7 +732,7 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va Some(other) => return Some(Err(format!("view.allPanels: `hide` must be true or false, not {other}"))), }; let u = &app.ui; - let hide = forced.unwrap_or(!u.all_panels_hidden() && !(u.no_panel_shown() && u.hidden_panels.is_none())); + let hide = forced.unwrap_or(!(u.all_panels_hidden() || u.no_panel_shown() && u.hidden_panels.is_none())); if hide { if !app.ui.no_panel_shown() { let u = &mut app.ui; diff --git a/crates/ui-egui/src/panels/detail/brush.rs b/crates/ui-egui/src/panels/detail/brush.rs index 09327720f2d..893ccb46d60 100644 --- a/crates/ui-egui/src/panels/detail/brush.rs +++ b/crates/ui-egui/src/panels/detail/brush.rs @@ -151,7 +151,8 @@ pub(super) fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui }; let (mods, secondary) = ui.input(|i| (i.modifiers, i.pointer.secondary_down())); if resp.drag_started() - && ((mods.ctrl && mods.alt) || (mods.alt && secondary)) + && mods.alt + && (mods.ctrl || secondary) && let Some(o) = ui.input(|i| i.pointer.press_origin()) { deselect_spot(app, right);