diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 39225b1a619..4f086dd71f3 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -69,6 +69,7 @@ //! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` | //! | 14 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! | 15 | per-photo denoiser selection | `DevelopSettings.enhance.denoise_model` | +//! | 16 | persistent ignored faces | `RegionKind::IgnoredFace` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -115,7 +116,8 @@ 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 = 15; +pub const VERSION: u32 = 16; +const DENOISER_PIN_VERSION: u32 = 15; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] @@ -661,7 +663,7 @@ impl Journal { // is appended: a snapshot in this format makes older builds refuse the library instead // of misreading ops or dropping fields they don't know. let older = (!report.created && snapshot_version != Some(VERSION)).then(|| snapshot_version.unwrap_or(0)); - if older.is_some() { + if older.is_some_and(|from| from < DENOISER_PIN_VERSION) { catalog.pin_legacy_denoise(resolve)?; } if let Some(at) = damaged_at { @@ -906,7 +908,7 @@ impl Journal { let mut seq = self.seq; for op in ops { seq = seq.checked_add(1).ok_or_else(|| CatalogError::Corrupt(format!("{LOG}: op counter overflow")))?; - let line = if self.behind.is_some() && has_denoiser_pin(op) { + let line = if self.behind.is_some_and(|from| from < DENOISER_PIN_VERSION) && has_denoiser_pin(op) { record(seq, serde_json::to_string(&ProtectedOp::PinnedDenoise { change: op }).unwrap_or_default()) } else { encode_record(seq, op) diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 43ab99fa1ae..9a18faad9a9 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -28,6 +28,190 @@ 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, 13] { + 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()); + } +} + +/// Format 13 belongs to Lens Blur on main. It must upgrade before an ignored face is written, +/// retaining both Lens Blur settings and face metadata (including earlier face-branch v13 data). +#[test] +fn v13_lens_blur_and_faces_upgrade_before_ignored_regions_are_written() { + 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":{"lens_blur":{"enabled":true,"amount":42,"boost":18,"focus_mask":1,"transition":27},"masks":[{"id":1,"adjust":{"lens_blur":31,"lens_blur_boost":17},"components":[{"shape":{"kind":"object","hint":[],"seg":{"side":1,"grid":0}}}]}]}}},"grids":["YwAA"],"albums":{},"next_photo":2,"next_album":1}"#; + for kind in [lightcraft_meta::RegionKind::Face, lightcraft_meta::RegionKind::IgnoredFace] { + let body = if kind == lightcraft_meta::RegionKind::IgnoredFace { + BODY.replace("\"kind\":\"Face\"", "\"kind\":\"IgnoredFace\"") + } else { + BODY.to_string() + }; + let store = MemStore::new(); + store.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":13,\"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(13)); + assert!(snapshot_version(&store) > 15, "main's reader must refuse ignored-face catalogs"); + let photo = catalog.photo(PhotoId(1)).unwrap(); + assert_eq!(photo.meta.regions[0].kind, kind); + assert_eq!(photo.meta.regions[0].name.as_deref(), Some("Legacy person")); + assert_eq!(photo.meta.regions[0].description.as_deref(), Some("retained")); + assert_eq!(photo.meta.regions[0].rect, lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.4, y1: 0.6 }); + let settings = photo.develop.clone(); + assert!(settings.lens_blur.enabled); + assert_eq!( + (settings.lens_blur.amount, settings.lens_blur.boost, settings.lens_blur.focus_mask, settings.lens_blur.transition), + (42.0, 18.0, Some(1), 27.0) + ); + assert_eq!((settings.masks[0].adjust.lens_blur, settings.masks[0].adjust.lens_blur_boost), (31.0, 17.0)); + let mut logits = Vec::new(); + settings.visit_seg_masks(&mut |seg| logits.push(seg.logits())); + assert_eq!(logits, vec![Some(vec![0.0])]); + let mut meta = photo.meta.clone(); + 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, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(report.replayed, 1); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().meta, meta); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().develop, settings); + journal.snapshot(&replayed).unwrap(); + drop(journal); + let (_, compacted, _) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(compacted.to_snapshot(), replayed.to_snapshot()); + } +} + +/// Main's format-14 snapshots and logs keep manually arranged bursts through the face-format +/// upgrade. Earlier face-branch format-14 catalogs also retain their ignores without gaining ranks. +#[test] +fn v14_burst_ranks_and_prior_ignores_survive_upgrade_replay_and_compaction() { + const BODY: &str = r#"{"photos":{"1":{"id":1,"source":{"type":"demo","scene":1},"file_name":"first.jpg","format":"JPEG","width":4,"height":3,"imported":"2026-01-01","develop":{},"analysis":{"sharpness":61,"clipped":0.01,"group":7,"best":false,"rank":2},"meta":{"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.4,"y1":0.6},"kind":"Face","name":"Retained person","description":"retained"}]}},"2":{"id":2,"source":{"type":"demo","scene":2},"file_name":"second.jpg","format":"JPEG","width":4,"height":3,"imported":"2026-01-01","develop":{},"analysis":{"sharpness":55,"clipped":0.02,"group":7,"best":false,"rank":1}}},"albums":{},"next_photo":3,"next_album":1}"#; + const ANALYSIS_OP: &str = r#"{"op":"setAnalysis","id":2,"analysis":{"sharpness":82,"clipped":0.03,"group":7,"best":true,"rank":0}}"#; + for prior_ignore in [false, true] { + let (body, analysis_op) = if prior_ignore { + ( + BODY.replacen("\"kind\":\"Face\"", "\"kind\":\"IgnoredFace\"", 1).replace(",\"rank\":2", "").replace(",\"rank\":1", ""), + ANALYSIS_OP.replace(",\"rank\":0", ""), + ) + } else { + (BODY.to_string(), ANALYSIS_OP.to_string()) + }; + let snapshot = format!("{{\"format\":\"lightcraft-catalog\",\"version\":14,\"seq\":2,\"catalog\":{body}}}").into_bytes(); + let log = format!("{{\"seq\":3,\"crc\":{},\"op\":{analysis_op}}}\n", crc32fast::hash(analysis_op.as_bytes())).into_bytes(); + let store = MemStore::new(); + store.set(SNAPSHOT, snapshot.clone()); + store.set(LOG, log.clone()); + let (mut journal, mut catalog, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((report.upgraded_from, report.replayed), (Some(14), 1)); + assert!(snapshot_version(&store) > 15, "main's format-15 reader must refuse ignored-face catalogs"); + let kept_snapshot = report.kept.iter().find(|name| name.starts_with("catalog.snap.v14-")).unwrap(); + let kept_log = report.kept.iter().find(|name| name.starts_with("catalog.log.v14-")).unwrap(); + assert_eq!((store.get(kept_snapshot), store.get(kept_log)), (Some(snapshot), Some(log))); + let first_analysis = Analysis { sharpness: 61.0, clipped: 0.01, group: Some(7), best: false, rank: (!prior_ignore).then_some(2) }; + let second_analysis = Analysis { sharpness: 82.0, clipped: 0.03, group: Some(7), best: true, rank: (!prior_ignore).then_some(0) }; + assert_eq!(catalog.photo(PhotoId(1)).unwrap().analysis, Some(first_analysis)); + assert_eq!(catalog.photo(PhotoId(2)).unwrap().analysis, Some(second_analysis)); + let mut meta = catalog.photo(PhotoId(1)).unwrap().meta.clone(); + assert_eq!(meta.regions[0].kind, if prior_ignore { lightcraft_meta::RegionKind::IgnoredFace } else { lightcraft_meta::RegionKind::Face }); + assert_eq!(meta.regions[0].name.as_deref(), Some("Retained person")); + assert_eq!(meta.regions[0].description.as_deref(), Some("retained")); + assert_eq!(meta.regions[0].rect, lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.4, y1: 0.6 }); + 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, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((report.upgraded_from, report.replayed), (None, 1)); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().meta, meta); + assert_eq!(replayed.photo(PhotoId(1)).unwrap().analysis, Some(first_analysis)); + assert_eq!(replayed.photo(PhotoId(2)).unwrap().analysis, Some(second_analysis)); + 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() { + 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, 12, 13] { + 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) > 15, "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(); @@ -219,6 +403,38 @@ fn v13_analysis_loads_unarranged_and_is_upgraded() { assert_eq!(again.photo(id).unwrap().analysis, Some(b)); } +#[test] +fn v15_upgrade_preserves_denoiser_choices_and_prior_ignored_faces() { + // Include an intentionally unpinned denoise edit: v15 already migrated the old global model, + // so opening v15 must not ask for it or pin the edit to it. + let body = r#"{"photos":{ + "1":{"id":1,"source":{"type":"demo","scene":1},"file_name":"pinned.jpg","format":"JPEG","width":4,"height":3,"imported":"2026-01-01", + "develop":{"enhance":{"denoise":25,"denoise_model":{"id":"custom","version":"2"}}}, + "meta":{"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.4,"y1":0.6},"kind":"IgnoredFace","name":"Retained"}]}}, + "2":{"id":2,"source":{"type":"demo","scene":2},"file_name":"default.jpg","format":"JPEG","width":4,"height":3,"imported":"2026-01-01", + "develop":{"enhance":{"denoise":40}}} + },"albums":{},"next_photo":3,"next_album":1}"#; + let snapshot = format!("{{\"format\":\"lightcraft-catalog\",\"version\":15,\"seq\":0,\"catalog\":{body}}}").into_bytes(); + let store = MemStore::new(); + store.set(SNAPSHOT, snapshot.clone()); + let (mut journal, catalog, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(report.upgraded_from, Some(15)); + assert_eq!(snapshot_version(&store), u64::from(VERSION)); + assert_eq!(store.get(&report.kept[0]), Some(snapshot)); + let pinned = catalog.photo(PhotoId(1)).unwrap(); + let pin = pinned.develop.enhance.denoise_model.as_ref().unwrap(); + assert_eq!((pin.id.as_str(), pin.version.as_str()), ("custom", "2")); + assert_eq!(pinned.meta.regions[0].kind, lightcraft_meta::RegionKind::IgnoredFace); + assert_eq!(pinned.meta.regions[0].name.as_deref(), Some("Retained")); + let default = catalog.photo(PhotoId(2)).unwrap(); + assert_eq!(default.develop.enhance.denoise, 40.0); + assert!(default.develop.enhance.denoise_model.is_none()); + journal.snapshot(&catalog).unwrap(); + drop(journal); + let (_, reopened, _) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(reopened.to_snapshot(), catalog.to_snapshot()); +} + #[test] fn v14_denoiser_is_pinned_during_upgrade_and_only_once() { let mut base = Catalog::new(); @@ -388,9 +604,10 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; + /// v16: `RegionKind::IgnoredFace` (v15: `Enhance.denoise_model`; v14: `Analysis.rank`; + /// v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; /// v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 15; + const NEWEST_FIELDS: u32 = 16; 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/catalog/src/tests_grids.rs b/crates/catalog/src/tests_grids.rs index 2a9724a048d..633000f5efa 100644 --- a/crates/catalog/src/tests_grids.rs +++ b/crates/catalog/src/tests_grids.rs @@ -136,6 +136,58 @@ fn v9_catalog_with_inline_grids_loads_and_is_upgraded() { assert!(rewritten.contains("\"grids\":["), "the shared table is in the file"); } +/// Format 12's shared-grid snapshots and the earlier face branch's inline format-12 snapshots +/// both upgrade before writing ignored faces. Face state and every settings holder survive. +#[test] +fn v12_shared_grids_and_faces_upgrade_without_losing_either() { + for shared in [false, true] { + for kind in [lightcraft_meta::RegionKind::Face, lightcraft_meta::RegionKind::IgnoredFace] { + let (mut live, _, id, blob) = masked_catalog(3); + let mut meta = live.photo(id).unwrap().meta.clone(); + meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.4, y1: 0.6 }, + kind, + name: Some("Person".into()), + description: Some("retained".into()), + }]; + live.apply(Op::SetMeta { id, meta: Box::new(meta.clone()) }).unwrap(); + let m = MemStore::new(); + if shared { + let (mut j, _, _) = open(&m); + j.snapshot(&live).unwrap(); + drop(j); + let mut snapshot: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap(); + snapshot["version"] = serde_json::json!(12); + assert_eq!(snapshot["catalog"]["grids"].as_array().unwrap().len(), 1); + m.set(SNAPSHOT, serde_json::to_vec(&snapshot).unwrap()); + } else { + m.set( + SNAPSHOT, + format!("{{\"format\":\"lightcraft-catalog\",\"version\":12,\"seq\":0,\"catalog\":{}}}\n", live.to_snapshot()).into_bytes(), + ); + } + let (mut j, mut loaded, report) = open(&m); + assert_eq!(report.upgraded_from, Some(12)); + assert!(snapshot_version(&m) > 15, "main's format-15 reader must refuse ignored-face snapshots"); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + let snapshot = String::from_utf8(m.get(SNAPSHOT).unwrap()).unwrap(); + assert_eq!(snapshot.match_indices(&blob).count(), 1, "the upgrade retains shared grids"); + + meta.regions[0].kind = lightcraft_meta::RegionKind::IgnoredFace; + let op = Op::SetMeta { id, meta: Box::new(meta) }; + loaded.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + drop(j); + let (mut j, replayed, _) = open(&m); + assert_eq!(replayed.to_snapshot(), loaded.to_snapshot(), "ignored state and masks survive log replay"); + j.snapshot(&replayed).unwrap(); + drop(j); + let (_, compacted, _) = open(&m); + assert_eq!(compacted.to_snapshot(), loaded.to_snapshot(), "ignored state and masks survive compaction"); + } + } +} + /// The op log is not deduplicated: every record keeps the grids inline (a log never carries the /// shared table), and replaying it rebuilds the same state. #[test] diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index af5ed21f20d..3bc11b9151a 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/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 5f042308454..d53db0ad1eb 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(); @@ -288,15 +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("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; - } + 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!( @@ -331,6 +337,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..7f72e44608a 100644 --- a/crates/engine/src/cmd/face_recognize.rs +++ b/crates/engine/src/cmd/face_recognize.rs @@ -11,7 +11,12 @@ use lightcraft_catalog::Op; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd}; -use crate::{Result, Session}; +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() } +} /// The `name` parameter of the naming commands: a name, or none (`null`, empty) to clear it. fn name_param(p: &Value, c: &str) -> Result> { @@ -27,6 +32,85 @@ 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 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(|| invalid("ignored", None, "ignored must be true or false"))?, + }; + let faces = p["faces"].as_array().ok_or_else(|| invalid("faces", None, "missing faces"))?; + if faces.is_empty() || faces.len() > 100_000 { + 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 (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")); + } + 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) { + region.kind = if ignored { RegionKind::IgnoredFace } else { RegionKind::Face }; + } + } + let count = seen.len(); + 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(|| 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(|| invalid("limit", "limit must be between 1 and 5000"))?, + }; + if !(1..=5000).contains(&limit) { + return Err(invalid("limit", "limit must be between 1 and 5000")); + } + let mut faces = Vec::new(); + 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, "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. fn apply_name(region: &mut lightcraft_meta::Region, name: &Option) { region.name = name.clone(); @@ -73,8 +157,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 +171,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 +217,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 +253,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 +433,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 +464,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(); @@ -1092,6 +1173,18 @@ 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. + 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", &reviewed(a.0)).unwrap(); + assert!(pairs(similar(&mut s, "ann", 10)).is_empty()); + 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); } } @@ -1129,8 +1222,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?: 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. After a sidecar refresh, reload the face list before submitting or retrying selections; region indices may have changed. Changes are one catalog-only undo step; originals and sidecars stay untouched. Requires catalog format 16; 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, 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/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 6db4fd0fcbf..9cc55bd4ab3 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -733,8 +733,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})) } ), @@ -767,8 +766,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/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..94b47f43425 --- /dev/null +++ b/crates/engine/src/ignored_faces_index.rs @@ -0,0 +1,81 @@ +//! 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 { + /// Replace one photo's derived keys/count, including removal from the library. + 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); + } + } + + /// 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) { + 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 760a6cd27d1..ffae9a1c741 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -46,6 +46,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; @@ -98,7 +99,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, CatalogError, Filter, Op, PhotoId, Sort}; use lightcraft_develop::DevelopSettings; @@ -115,6 +116,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 @@ -147,6 +151,9 @@ pub type Result = std::result::Result; pub struct UndoEntry { pub label: String, pub op: Op, + /// 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; a located folder, `on_disk: false`, renames nothing /// and only follows). Never overwrites; refused when `to` exists. An @@ -259,6 +266,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, @@ -312,9 +320,12 @@ 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 instead keeps a policy per operation, so mixed commands retain ordinary writes. pub(crate) skip_auto_write: bool, + /// 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 @@ -534,6 +545,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, @@ -562,6 +574,7 @@ impl Session { pending_sidecar_repairs: Vec::new(), interaction: None, skip_auto_write: false, + sidecar_policies: Default::default(), reload_tickets: Default::default(), unsaved_sidecars: Default::default(), denoise: Default::default(), @@ -755,6 +768,7 @@ impl Session { 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 @@ -809,7 +823,14 @@ impl Session { } } 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, + sidecar_photos: None, + 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); @@ -821,6 +842,24 @@ impl Session { failure.map_or(Ok(()), Err) } + /// Commit catalog metadata with history that suppresses automatic sidecar writes, + /// 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<()> { + let result = self.commit(label, op); + // A partially applied batch has a journal record and recovery step too; neither may + // lose the catalog-only policy just because the original command reported an error. + if result.is_ok() || matches!(&result, Err(EngineError::Catalog(CatalogError::PartlyApplied { .. }))) { + if let Some(entry) = self.undo.last_mut() { + entry.sidecar_photos = Some(Vec::new()); + } + if self.depth > 0 { + self.sidecar_policies.insert(self.pending_log.len().saturating_sub(1), Vec::new()); + } + } + result + } + /// [`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) @@ -953,10 +992,22 @@ impl Session { return; } let tail = self.undo.split_off(self.undo.len() - n); + // 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 }, + sidecar_photos: Some(sidecar_photos), folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -969,10 +1020,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) { @@ -988,10 +1041,16 @@ impl Session { } }; self.show_undone(&e.op); + 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, + sidecar_photos: e.sidecar_photos, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -1014,13 +1073,22 @@ impl Session { } op => Op::Batch { ops: std::iter::once(op).chain(std::mem::take(&mut e.retry_inverse)).collect() }, }; - Some(UndoEntry { label: e.label.clone(), op, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }) + Some(UndoEntry { + label: e.label.clone(), + op, + sidecar_photos: e.sidecar_photos.clone(), + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }) } + /// 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) { @@ -1034,10 +1102,16 @@ impl Session { } }; self.show_undone(&e.op); + 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, + sidecar_photos: e.sidecar_photos, folder: e.folder.as_ref().map(FolderMove::reversed), retry_inverse: Vec::new(), retry_sidecars: Vec::new(), @@ -1156,6 +1230,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 40559bfec67..738be934504 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -838,6 +838,7 @@ impl Session { self.gps_unconfirmed.clear(); self.interaction = None; self.pending_log.clear(); + self.sidecar_policies.clear(); self.selection = Selection::default(); self.source = LibrarySource::All; self.library_folder = None; @@ -1089,6 +1090,7 @@ impl Session { } lib.retry_at = None; self.pending_log.clear(); + self.sidecar_policies.clear(); lib.last_error = None; } poll_compaction(lib); @@ -1239,6 +1241,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 8937bb79e40..07b7c1ba2eb 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -206,7 +206,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. @@ -343,12 +344,29 @@ 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(); - // (the photo's size is the upright one) + // 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(); + // Foreign boxes must be upright before matching the catalog's already-upright ignored + // boxes. Never rotate a retained local ignore decision a second time. if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) { let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) }; - lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored); + lightcraft_meta::upright_regions(&mut regions, drawn_on, o, stored); + } + 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(), @@ -1306,8 +1324,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/face_recognize.rs b/crates/engine/src/tests/face_recognize.rs index 4a805b36dc1..99ebd8e95f4 100644 --- a/crates/engine/src/tests/face_recognize.rs +++ b/crates/engine/src/tests/face_recognize.rs @@ -523,6 +523,273 @@ 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(); + 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); + 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); +} + +/// Agent-visible help explains why a sidecar reread invalidates reviewed face identities. +#[test] +fn ignore_help_explains_reloading_after_sidecar_refresh() { + let commands = Session::new().commands(); + let ignore = commands.iter().find(|command| command.id == "faces.ignore").unwrap(); + assert!(ignore.params.contains("sidecar refresh"), "{}", ignore.params); + assert!(ignore.params.contains("reload the face list"), "{}", ignore.params); + assert!(ignore.params.contains("region indices may have changed"), "{}", ignore.params); +} + +/// 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); +} + +/// 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}; + 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); + } +} + +/// 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(); + 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() { + 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, "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 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. +#[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["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)); + 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_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}"); + } +} + +/// 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(); + 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"); @@ -737,3 +1004,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, "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); + 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/filesystem_history.rs b/crates/engine/src/tests/filesystem_history.rs index 94786a067b9..fc3333cf02a 100644 --- a/crates/engine/src/tests/filesystem_history.rs +++ b/crates/engine/src/tests/filesystem_history.rs @@ -583,7 +583,14 @@ fn a_partly_applied_step_whose_files_cannot_be_moved_back_keeps_what_is_left_of_ Op::SetRating { id: PhotoId(9_999), rating: 1 }, ], }; - let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + let entry = crate::UndoEntry { + label: "Broken".into(), + op: step, + sidecar_photos: None, + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }; if redo { s.redo.push(entry); } else { @@ -630,7 +637,14 @@ fn what_is_left_of_a_rollback_moves_no_file_that_is_already_back() { Op::SetRating { id: PhotoId(9_999), rating: 1 }, ], }; - let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + let entry = crate::UndoEntry { + label: "Broken".into(), + op: step, + sidecar_photos: None, + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }; if redo { s.redo.push(entry); } else { @@ -729,7 +743,14 @@ fn three_photos_whose_old_names_are_empty(redo: bool, through_rename: bool) { Op::SetRating { id: PhotoId(9_999), rating: 1 }, ], }; - let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + let entry = crate::UndoEntry { + label: "Broken".into(), + op: step, + sidecar_photos: None, + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }; if redo { s.redo.push(entry); } else { diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index c538ed60d2f..db35da34267 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -487,33 +487,43 @@ fn a_background_upgrade_says_where_what_it_was_is_kept() { fn a_batch_that_cannot_be_rolled_back_whole_is_journaled_and_undoable() { use lightcraft_catalog::{CatalogError, Op, PhotoId, Stack}; - let store = Flaky::default(); - let mut s = open(&store, true); - let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); - let stack = s.catalog.alloc_stack_id(); - s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); - s.persist().unwrap(); - let before = s.catalog.to_snapshot(); - - // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later - let batch = - Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; - let undo_steps = s.undo.len(); - let e = s.execute_fn("test.batch", |s| s.commit("Delete", batch).map(|()| json!({}))).unwrap_err(); - assert!(matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{e:?}"); - assert!(e.to_string().contains("partly"), "the error says the change stayed in part: {e}"); - let torn = s.catalog.to_snapshot(); - assert_ne!(torn, before, "the rollback went only part of the way"); - assert!(s.catalog.photo(ids[0]).is_some() && s.catalog.stack(stack).is_none()); - - // a restart in the middle finds what the session had - assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), torn, "the journal and the memory agree"); - assert_eq!(s.undo.len(), undo_steps + 1, "what is left of the batch is one undo step"); - - // undo finishes the rollback, and that too is journaled - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(s.catalog.to_snapshot(), before); - assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), before); + for catalog_only in [false, true] { + let store = Flaky::default(); + let mut s = open(&store, true); + let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + s.persist().unwrap(); + let before = s.catalog.to_snapshot(); + + // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later + let batch = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + let undo_steps = s.undo.len(); + let e = s + .execute_fn("test.batch", |s| { + let result = if catalog_only { s.commit_catalog_only("Delete", batch) } else { s.commit("Delete", batch) }; + result.map(|()| json!({})) + }) + .unwrap_err(); + assert!(matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{e:?}"); + assert!(e.to_string().contains("partly"), "the error says the change stayed in part: {e}"); + let torn = s.catalog.to_snapshot(); + assert_ne!(torn, before, "the rollback went only part of the way"); + assert!(s.catalog.photo(ids[0]).is_some() && s.catalog.stack(stack).is_none()); + + // a restart in the middle finds what the session had + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), torn, "the journal and the memory agree"); + assert_eq!(s.undo.len(), undo_steps + 1, "what is left of the batch is one undo step"); + let policy = catalog_only.then(Vec::new); + assert_eq!(s.undo.last().unwrap().sidecar_photos, policy, "a partial commit retains its sidecar policy"); + + // undo finishes the rollback, and that too is journaled + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.to_snapshot(), before); + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), before); + assert_eq!(s.redo.last().unwrap().sidecar_photos, policy, "finishing rollback retains the sidecar policy"); + } } /// An undo whose catalog step fails and cannot be rolled back whole is journaled as well, and what is left of it is a @@ -531,7 +541,14 @@ fn an_undo_step_that_cannot_be_rolled_back_whole_is_journaled_and_can_be_taken_b let before = s.catalog.to_snapshot(); let torn = Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; - s.undo.push(crate::UndoEntry { label: "Broken".into(), op: torn, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }); + s.undo.push(crate::UndoEntry { + label: "Broken".into(), + op: torn, + sidecar_photos: Some(Vec::new()), + folder: None, + retry_inverse: Vec::new(), + retry_sidecars: Vec::new(), + }); let (undo_len, redo_len) = (s.undo.len(), s.redo.len()); let e = s.execute("edit.undo", &json!({})).unwrap_err(); @@ -539,9 +556,11 @@ fn an_undo_step_that_cannot_be_rolled_back_whole_is_journaled_and_can_be_taken_b let torn_state = s.catalog.to_snapshot(); assert_ne!(torn_state, before); assert_eq!((s.undo.len(), s.redo.len()), (undo_len - 1, redo_len + 1), "the step is not left to fail again"); + assert_eq!(s.redo.last().unwrap().sidecar_photos, Some(Vec::new()), "partial history recovery stays catalog-only"); assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), torn_state, "the journal and the memory agree"); s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.undo.last().unwrap().sidecar_photos, Some(Vec::new()), "redo retains the recovery policy"); assert_eq!(s.catalog.to_snapshot(), before); assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), before); } @@ -590,7 +609,14 @@ fn a_partly_applied_undo_step_keeps_its_retry_inverses() { s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); let step = Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; - s.undo.push(crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: vec![fix.clone()], retry_sidecars: Vec::new() }); + s.undo.push(crate::UndoEntry { + label: "Broken".into(), + op: step, + sidecar_photos: None, + folder: None, + retry_inverse: vec![fix.clone()], + retry_sidecars: Vec::new(), + }); assert!(s.execute("edit.undo", &json!({})).is_err()); let Some(Op::Batch { ops }) = s.redo.last().map(|r| r.op.clone()) else { panic!("the step that takes it back is a batch") }; assert_eq!(ops.last(), Some(&fix)); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 8154af50b4a..41a3fbb816b 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -75,6 +75,273 @@ 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()); + 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() { + 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,"rect":rect})).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(); + 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_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(); + s.merge_undo(2, "mixed metadata"); + 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(); + 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 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(); + } + 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, "rect": rect}], "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); + } + } +} + +/// 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 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(); + } + 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, "rect": rect}], "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"); @@ -536,6 +803,46 @@ 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(); + 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); + 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] @@ -646,6 +953,44 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let _ = std::fs::remove_dir_all(&src); } +/// Stored-frame XMP is normalized before matching local ignores, without rotating the retained +/// catalog box again or reintroducing a duplicate ordinary face on successive metadata reads. +#[test] +fn rereading_rotated_xmp_keeps_ignored_faces_upright_without_duplicates() { + for embedded in [false, true] { + let src = temp_dir(&format!("ignored-stored-frame-{embedded}")); + let file = src.join("turned.jpg"); + write_turned_jpeg(&file, embedded.then_some(STORED_FRAME_REGIONS)); + let sidecar = src.join("turned.xmp"); + if !embedded { + std::fs::write(&sidecar, STORED_FRAME_REGIONS).unwrap(); + } + let original_bytes = std::fs::read(&file).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = only(&s); + assert_on_the_upright_face(&s, id, "import"); + 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 { + let read = s.execute("photo.readMetadataFromFile", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(read["failed"], json!([]), "{read}"); + assert_eq!(s.catalog.photo(id).unwrap().meta.regions, ignored); + assert_on_the_upright_face(&s, id, "ignored metadata reread"); + assert_eq!(s.execute("faces.ignored", &json!({})).unwrap()["total"], 1); + } + assert_eq!(std::fs::read(&file).unwrap(), original_bytes); + if embedded { + assert!(!sidecar.exists()); + } else { + assert_eq!(std::fs::read_to_string(sidecar).unwrap(), STORED_FRAME_REGIONS); + } + let _ = std::fs::remove_dir_all(src); + } +} + /// A sidecar that says nothing beside a photo whose file states an orientation isn't one the import counts: the /// file's orientation goes to a sidecar that said something, not into an empty one (#2674, #2589). #[test] diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index a621f403723..a9ecd53bb8a 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,20 @@ 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( + 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 b7aacc1174d..b54cd35f165 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 { @@ -43,7 +44,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. @@ -122,11 +123,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" => { @@ -135,7 +141,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 c8bab04803b..b265e43b2cd 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -51,6 +51,35 @@ 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()); + 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 d3002a13dcf..9c541692d4a 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -601,6 +601,19 @@ 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 +} + +/// 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() { return ToolResult::error("tool arguments must be an object"); @@ -654,7 +667,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/meta/src/convert.rs b/crates/meta/src/convert.rs index a9c7e789dd9..fec8570f1c4 100644 --- a/crates/meta/src/convert.rs +++ b/crates/meta/src/convert.rs @@ -1,4 +1,4 @@ -use crate::{FocusPoint, Metadata, Orientation, Rect, Region, XmpData}; +use crate::{FocusPoint, Metadata, Orientation, Rect, Region, RegionKind, XmpData}; pub(crate) fn rect_from_craft(r: craft_metadata::Rect) -> Rect { Rect { x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 } @@ -25,11 +25,27 @@ pub(crate) fn focus_to_craft(f: &FocusPoint) -> craft_metadata::FocusPoint { } pub(crate) fn region_from_craft(r: craft_metadata::Region) -> Region { - Region { rect: rect_from_craft(r.rect), kind: r.kind, name: r.name, description: r.description } + let kind = match r.kind { + craft_metadata::RegionKind::Face => RegionKind::Face, + craft_metadata::RegionKind::Pet => RegionKind::Pet, + craft_metadata::RegionKind::Focus => RegionKind::Focus, + craft_metadata::RegionKind::BarCode => RegionKind::BarCode, + craft_metadata::RegionKind::Other(value) => RegionKind::Other(value), + }; + Region { rect: rect_from_craft(r.rect), kind, name: r.name, description: r.description } } -pub(crate) fn region_to_craft(r: &Region) -> craft_metadata::Region { - craft_metadata::Region { rect: rect_to_craft(r.rect), kind: r.kind.clone(), name: r.name.clone(), description: r.description.clone() } +/// Catalog-only regions must not become ordinary regions in interchange/export metadata. +pub(crate) fn region_to_craft(r: &Region) -> Option { + let kind = match &r.kind { + RegionKind::Face => craft_metadata::RegionKind::Face, + RegionKind::IgnoredFace => return None, + RegionKind::Pet => craft_metadata::RegionKind::Pet, + RegionKind::Focus => craft_metadata::RegionKind::Focus, + RegionKind::BarCode => craft_metadata::RegionKind::BarCode, + RegionKind::Other(value) => craft_metadata::RegionKind::Other(value.clone()), + }; + Some(craft_metadata::Region { rect: rect_to_craft(r.rect), kind, name: r.name.clone(), description: r.description.clone() }) } pub(crate) fn from_craft(m: craft_metadata::Metadata) -> Metadata { @@ -121,7 +137,7 @@ pub(crate) fn to_craft(m: &Metadata) -> craft_metadata::Metadata { hierarchical_keywords: m.hierarchical_keywords.clone(), rating: m.rating, label: m.label.clone(), - regions: m.regions.iter().map(region_to_craft).collect(), + regions: m.regions.iter().filter_map(region_to_craft).collect(), focus: m.focus.as_ref().map(focus_to_craft), fuji_recipe: None, } @@ -131,3 +147,51 @@ pub(crate) fn xmp_from_craft(d: craft_metadata::XmpData) -> XmpData { let lc_settings = d.properties.get("lc:settings").and_then(|v| v.first()).cloned(); XmpData { metadata: from_craft(d.metadata), lc_settings, properties: d.properties, values: d.values } } + +#[cfg(test)] +mod tests { + use super::{from_craft, region_from_craft, region_to_craft, to_craft}; + use crate::{Metadata, Rect, Region, RegionKind}; + + fn region(kind: RegionKind) -> Region { + Region { rect: Rect { x0: 0.1, y0: 0.2, x1: 0.4, y1: 0.6 }, kind, name: Some("Person".into()), description: Some("retained".into()) } + } + + /// Every interchange kind, including unknown text, keeps its type, box, name and description. + #[test] + fn shared_regions_round_trip_without_changing_their_kind_or_geometry() { + for kind in [ + RegionKind::Face, + RegionKind::Pet, + RegionKind::Focus, + RegionKind::BarCode, + RegionKind::Other("IgnoredFace".into()), + RegionKind::Other(String::new()), + ] { + let r = region(kind); + assert_eq!(region_from_craft(region_to_craft(&r).unwrap()), r); + } + } + + /// Export conversion omits ignores without mutating their catalog wire representation. + #[test] + fn ignored_faces_stay_in_the_catalog_not_shared_metadata() { + let ignored = region(RegionKind::IgnoredFace); + let metadata = Metadata { + title: Some("Other metadata".into()), + regions: vec![region(RegionKind::Face), ignored.clone(), region(RegionKind::Pet)], + ..Default::default() + }; + let before = serde_json::to_string(&metadata).unwrap(); + assert!(before.contains("\"kind\":\"IgnoredFace\"")); + let shared = to_craft(&metadata); + assert_eq!(shared.regions.len(), 2); + let read = from_craft(shared); + assert_eq!(read.regions, vec![metadata.regions[0].clone(), metadata.regions[2].clone()]); + assert_eq!(read.title, metadata.title); + assert_eq!(serde_json::to_string(&metadata).unwrap(), before); + assert_eq!(metadata.regions[1], ignored); + assert_eq!(serde_json::from_str::(&before).unwrap(), metadata); + assert_eq!(crate::write_xmp(&metadata, None), crate::write_xmp(&Metadata { regions: Vec::new(), ..metadata.clone() }, None)); + } +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 03605314a62..4fc72b7477c 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -26,7 +26,7 @@ mod xmp; pub use craft_metadata::DateTime; pub use craft_metadata::cr3; pub use craft_metadata::{Embedded, jpeg_segments, png_chunks, webp_chunks}; -pub use craft_metadata::{Flash, Gps, RegionKind}; +pub use craft_metadata::{Flash, Gps}; pub use craft_metadata::{GpxError, Match, TrackPoint, Tracklog, parse_gpx}; pub use craft_metadata::{TagRow, tag_rows}; @@ -91,6 +91,20 @@ pub struct Region { pub description: Option, } +/// `mwg-rs:Type`, plus the catalog-only ignore state. Keep this local so shared metadata +/// interchange cannot turn an ignored face back into an ordinary face. +#[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, + /// `mwg-rs:Type` was missing, empty, or a value we don't recognise. + Other(String), +} + /// Everything LightCraft shows or searches about a photo. All fields are optional; unknown = `None`/empty. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Metadata { diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index afd4435bb89..cf52d565582 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -322,6 +322,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Ignorované obličeje: {total} · Vybráno: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Fotografie importujete přes Soubor › Importovat fotografie… ({keys}).", "View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 67eabc903bc..abc72eac363 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2495,6 +2495,24 @@ "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", "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", "AI masks": "AI masky", "Device": "Zařízení", "Last photo": "Poslední fotka", @@ -2530,6 +2548,7 @@ "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", + "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Klíčová slova a předvolby se použijí jen u nových souborů, ne u fotografií, které už jsou v Místních souborech", "This album is in a loop, so it shows nothing": "Toto album je ve smyčce, a proto nic nezobrazuje", "It tests itself: change its rules (Edit Smart Album…)": "Testuje samo sebe: změňte jeho pravidla (Upravit inteligentní album…)", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 591920bdf87..ae642259af5 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -325,6 +325,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Ignorierte Gesichter: {total} · Ausgewählt: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index fda9bc920c2..45542023d67 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3553,6 +3553,24 @@ "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)", + "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", "AI masks": "KI-Masken", "Device": "Gerät", "Last photo": "Letztes Foto", @@ -3587,6 +3605,7 @@ "Welcome": "Willkommen", "Next": "Weiter", "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Stichwörter und Vorgaben gelten nur für neue Dateien, nicht für Fotos, die schon in „Lokal“ sind", "This album is in a loop, so it shows nothing": "Dieses Album ist in einem Kreis und zeigt deshalb nichts", "It tests itself: change its rules (Edit Smart Album…)": "Es prüft sich selbst: Ändere seine Regeln (Smart-Album bearbeiten…)", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 54b8c3c2f61..585fedcc2d3 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -325,6 +325,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Rostros ignorados: {total} · Seleccionados: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 4f51d68d423..5b38cd3d96c 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2450,6 +2450,28 @@ "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)", + "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", "AI masks": "Máscaras de IA", "Device": "Dispositivo", "Last photo": "Última foto", @@ -2484,6 +2506,7 @@ "Welcome": "Bienvenido", "Next": "Siguiente", "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Las palabras clave y los ajustes preestablecidos solo se aplican a archivos nuevos, no a fotos que ya están en Local", "This album is in a loop, so it shows nothing": "Este álbum está en un bucle, así que no muestra nada", "It tests itself: change its rules (Edit Smart Album…)": "Se comprueba a sí mismo: cambia sus reglas (Editar álbum inteligente…)", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 924fce580fd..652c4d80766 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -319,6 +319,7 @@ "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ä", + "Ignored faces: {total} · Selected: {selected}": "Ohitetut kasvot: {total} · Valittu: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia… ({keys}).", "View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 46082b14c32..22b3f377a7d 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2419,6 +2419,26 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "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", + "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.", "AI masks": "Tekoälymaskit", "Device": "Laite", "Last photo": "Viimeisin kuva", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 4eb8a1384e2..5b4c6a7f16b 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -325,6 +325,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Visages ignorés : {total} · Sélectionnés : {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index c2e04135746..01d4c5cf693 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3631,6 +3631,24 @@ "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)", + "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", "AI masks": "Masques IA", "Device": "Appareil", "Last photo": "Dernière photo", @@ -3665,6 +3683,7 @@ "Welcome": "Bienvenue", "Next": "Suivant", "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Les mots-clés et les préréglages ne s'appliquent qu'aux nouveaux fichiers, pas aux photos déjà dans Local", "This album is in a loop, so it shows nothing": "Cet album est pris dans une boucle : il n'affiche rien", "It tests itself: change its rules (Edit Smart Album…)": "Il se teste lui-même : modifiez ses règles (Modifier l'album intelligent…)", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index c492fcbb01e..37449452418 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -322,6 +322,7 @@ "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}", + "Ignored faces: {total} · Selected: {selected}": "Wajah yang diabaikan: {total} · Dipilih: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk", "Bring photos in with File › Import Photos… ({keys}).": "Masukkan foto melalui File › Impor foto… ({keys}).", "View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 80ff3ed7577..4b5033a6008 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2433,6 +2433,28 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "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", + "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.", "AI masks": "Masker AI", "Device": "Perangkat", "Last photo": "Foto terakhir", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 96a493f446e..ce545a375f9 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -322,6 +322,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Volti ignorati: {total} · Selezionati: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importa le foto con File › Importa foto… ({keys}).", "View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 292b13ec0e6..41950ee88fa 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2610,6 +2610,24 @@ "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", "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", "AI masks": "Maschere IA", "Device": "Dispositivo", "Last photo": "Ultima foto", @@ -2645,6 +2663,7 @@ "Next": "Avanti", "Get Started": "Inizia", "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Parole chiave e preset si applicano solo ai file nuovi, non alle foto già in Locale", "This album is in a loop, so it shows nothing": "Questo album è in un ciclo, quindi non mostra nulla", "It tests itself: change its rules (Edit Smart Album…)": "Verifica se stesso: modifica le sue regole (Modifica album smart…)", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 9138a78640c..06edce6bf39 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", "{name} is installed": "{name} をインストールしました", "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", + "Ignored faces: {total} · Selected: {selected}": "無視した顔: {total} · 選択済み: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)", "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index d154bb08351..8480abe170d 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2449,6 +2449,28 @@ "Tool strip": "ツールバー", "Bottom bar": "下部バー", "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": "無視した顔を復元", "AI masks": "AIマスク", "Device": "デバイス", "Last photo": "直前の写真", @@ -2483,6 +2505,7 @@ "Welcome": "ようこそ", "Next": "次へ", "Get Started": "始める", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "選択した顔の一部を利用できません。どの顔も無視されていません。選択を解除して、もう一度お試しください。", "Keywords and presets apply to new files only, not to photos already in Local": "キーワードとプリセットは新しいファイルにのみ適用され、すでにローカルにある写真には適用されません", "This album is in a loop, so it shows nothing": "このアルバムは循環しているため、何も表示されません", "It tests itself: change its rules (Edit Smart Album…)": "自分自身を条件にしています。条件を変更してください(スマートアルバムを編集…)", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46b74662cc6..312a436d950 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "Ignored faces: {total} · Selected: {selected}": "უგულებელყოფილი სახეები: {total} · მონიშნული: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ", "Bring photos in with File › Import Photos… ({keys}).": "ფოტოების შემოსატანად გამოიყენეთ ფაილი › ფოტოების იმპორტი… ({keys}).", "View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 5ecc1538b77..327a665b2bb 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3737,6 +3737,25 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "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": "უგულებელყოფილი სახეების აღდგენა", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "ზოგიერთი არჩეული სახე მიუწვდომელია. არცერთი სახე არ იგნორირებულა. გააუქმეთ მონიშვნა და სცადეთ ხელახლა.", "User Templates": "მომხმარებლის შაბლონები", "Delete Folder": "საქაღალდის წაშლა", "Folder name": "საქაღალდის სახელი", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index ded03cc37f9..4c92ffe921e 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -322,6 +322,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Ignorowane twarze: {total} · Zaznaczone: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Zdjęcia importujesz przez Plik › Importuj zdjęcia… ({keys}).", "View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 56bd9891ebf..10faa84e974 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2371,6 +2371,28 @@ "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", "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", "AI masks": "Maski AI", "Device": "Urządzenie", "Last photo": "Ostatnie zdjęcie", @@ -2408,6 +2430,7 @@ "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ęć", + "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Słowa kluczowe i ustawienia predefiniowane dotyczą tylko nowych plików, nie zdjęć, które już są w Lokalnych", "This album is in a loop, so it shows nothing": "Ten album jest w pętli, więc niczego nie pokazuje", "It tests itself: change its rules (Edit Smart Album…)": "Sprawdza samego siebie: zmień jego reguły (Edytuj album inteligentny…)", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index d6361782ef1..01064888915 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -325,6 +325,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Rostos ignorados: {total} · Selecionados: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 592de957bf2..3d02f36d20c 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2294,6 +2294,28 @@ "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)", + "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", "AI masks": "Máscaras de IA", "Device": "Dispositivo", "Last photo": "Última foto", @@ -2328,6 +2350,7 @@ "Welcome": "Bem-vindo", "Next": "Próximo", "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.", "Keywords and presets apply to new files only, not to photos already in Local": "Palavras-chave e predefinições valem só para arquivos novos, não para fotos que já estão em Local", "This album is in a loop, so it shows nothing": "Este álbum está em um ciclo, então não mostra nada", "It tests itself: change its rules (Edit Smart Album…)": "Ele testa a si mesmo: mude as regras dele (Editar álbum inteligente…)", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 37053b60f1d..8bd513172da 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", "{name} is installed": "Модель {name} установлена", "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", + "Ignored faces: {total} · Selected: {selected}": "Игнорируемые лица: {total} · Выбрано: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с", "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index dda0cd9bf30..d620883a9b9 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2656,6 +2656,24 @@ "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", "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": "Восстановить игнорируемые лица", "AI masks": "ИИ-маски", "Device": "Устройство", "Last photo": "Последнее фото", @@ -2690,6 +2708,7 @@ "Welcome": "Добро пожаловать", "Next": "Далее", "Get Started": "Начать", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Некоторые выбранные лица недоступны. Ни одно лицо не было проигнорировано. Снимите выделение и повторите попытку.", "Keywords and presets apply to new files only, not to photos already in Local": "Ключевые слова и пресеты применяются только к новым файлам, а не к фото, которые уже есть в «Локальных»", "This album is in a loop, so it shows nothing": "Этот альбом попал в цикл, поэтому ничего не показывает", "It tests itself: change its rules (Edit Smart Album…)": "Он проверяет сам себя: измените его условия (Изменить смарт-альбом…)", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index c84bcb2bddb..e084839b256 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -323,6 +323,7 @@ "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}", + "Ignored faces: {total} · Selected: {selected}": "Ignorerade ansikten: {total} · Markerade: {selected}", "Can't read this folder: {}": "Det går inte att läsa den här mappen: {}", "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft kan korrigera distorsion och vinjettering för många objektiv med hjälp av den öppna objektivdatabasen (lensfun, cirka {size} MB).", "No lens profile found for {}.": "Ingen objektivprofil hittades för {}.", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index a15af4747d1..84142dcce79 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2993,7 +2993,6 @@ "over one by one as they are used; the rest stay until the cache makes room.": "över en i taget när de används; resten ligger kvar tills cachen gör plats.", "overlays and the intro and ending screens, in view order.": "överlägg och intro- och slutskärmarna, i visningsordning.", "owns every shared sidecar name in the library: 2.4 s a write in that library, now under 1 s.": "äger varje delat sidecar-namn i biblioteket: 2,4 s per skrivning i det biblioteket, nu under 1 s.", - "Page": "Sida", "Page Options": "Sidalternativ", "Panasonic and Leica raws (RW2, RWL) are now corrected for lens distortion the way the camera corrects its own JPEG": "Raw-filer från Panasonic och Leica (RW2, RWL) korrigeras nu för objektivdistorsion på samma sätt som kameran korrigerar sin egen JPEG", "panel. Each is switched on on its own and has a background colour and, centred on it, your identity plate (the one": "panelen. Var och en slås på för sig och har en bakgrundsfärg och, centrerad på den, din namnskylt (den", @@ -3666,6 +3665,26 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "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", + "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.", "(Restore All is there too). The row used to bring every hidden location back at once (issue #2114).": "(Återställ alla finns också kvar). Raden brukade ta tillbaka alla dolda platser på en gång (ärende #2114).", "(View ▸ Zoom to Focus Point turns this off). Photos without a point zoom as before.": "(Visa → Zooma till fokuspunkt stänger av detta). Foton utan punkt zoomar som tidigare.", "**View ▸ Show Focus Point** (⌥F) draws the autofocus frame the camera recorded over the photo, in Detail, Compare": "**Visa → Visa fokuspunkt** (⌥F) ritar autofokusramen som kameran registrerade ovanpå fotot, i Detalj, Jämför", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 02d5708de01..c6cf8923e2f 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", "{name} is installed": "{name} установлено", "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", + "Ignored faces: {total} · Selected: {selected}": "Ігноровані обличчя: {total} · Вибрано: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с", "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 50b3c37ba21..13541532451 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2446,6 +2446,28 @@ "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", "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": "Відновити ігноровані обличчя", "AI masks": "ШІ-маски", "Device": "Пристрій", "Last photo": "Останнє фото", @@ -2480,6 +2502,7 @@ "Welcome": "Ласкаво просимо", "Next": "Далі", "Get Started": "Почати", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "Деякі вибрані обличчя недоступні. Жодне обличчя не було проігноровано. Зніміть виділення та спробуйте знову.", "Keywords and presets apply to new files only, not to photos already in Local": "Ключові слова та пресети застосовуються лише до нових файлів, а не до фото, що вже є в «Локальних»", "This album is in a loop, so it shows nothing": "Цей альбом потрапив у цикл, тому нічого не показує", "It tests itself: change its rules (Edit Smart Album…)": "Він перевіряє сам себе: змініть його правила (Редагувати смарт-альбом…)", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 75606d1563d..c3774821c5b 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -319,6 +319,7 @@ "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", + "Ignored faces: {total} · Selected: {selected}": "Khuôn mặt đã bỏ qua: {total} · Đã chọn: {selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây", "Bring photos in with File › Import Photos… ({keys}).": "Đưa ảnh vào bằng Tệp › Nhập ảnh… ({keys}).", "View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 5eba595eedb..f4c96c50291 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2745,6 +2745,25 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "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", + "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.", "AI masks": "Mặt nạ AI", "Device": "Thiết bị", "Last photo": "Ảnh gần nhất", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 1c4bee97fb4..a9802a34c84 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "面板移动未应用:{error}", "{name} is installed": "{name} 已安装", "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", + "Ignored faces: {total} · Selected: {selected}": "已忽略的人脸:{total} · 已选择:{selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒", "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 25495f0504a..5ae5f1e395d 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2449,6 +2449,28 @@ "Top bar": "顶部栏", "Tool strip": "工具栏", "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": "恢复已忽略的人脸", "AI masks": "AI 蒙版", "Device": "设备", "Last photo": "上一张照片", @@ -2483,6 +2505,7 @@ "Welcome": "欢迎", "Next": "下一步", "Get Started": "开始使用", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "部分选中的人脸不可用。未忽略任何人脸。请清除选择后重试。", "Keywords and presets apply to new files only, not to photos already in Local": "关键词和预设仅应用于新文件,不适用于已在“本地”中的照片", "This album is in a loop, so it shows nothing": "此相册处于循环中,因此不显示任何内容", "It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:请更改其规则(编辑智能相册…)", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 9222de8f8bf..071a6b3ab97 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -325,6 +325,7 @@ "Panel move was not applied: {error}": "面板移動未套用:{error}", "{name} is installed": "{name} 已安裝", "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", + "Ignored faces: {total} · Selected: {selected}": "已忽略的臉孔:{total} · 已選取:{selected}", "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒", "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 625de79bb27..7ad7a3acdb6 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2450,6 +2450,28 @@ "Tool strip": "工具列", "Bottom bar": "底部列", "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": "還原已忽略的臉孔", "AI masks": "AI 遮色片", "Device": "裝置", "Last photo": "上一張照片", @@ -2484,6 +2506,7 @@ "Welcome": "歡迎", "Next": "下一步", "Get Started": "開始使用", + "Some selected faces are unavailable. Nothing was ignored. Clear the selection and try again.": "部分選取的人臉無法使用。未忽略任何人臉。請清除選取後重試。", "Keywords and presets apply to new files only, not to photos already in Local": "關鍵字和預設集僅套用於新檔案,不適用於已在「本機」中的照片", "This album is in a loop, so it shows nothing": "此相簿處於循環中,因此不顯示任何內容", "It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:請變更其規則(編輯智慧型相簿…)", diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 287de18989b..66e016b9021 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -332,9 +332,17 @@ impl LightcraftApp { if self.shown_library == Some(generation) { return; } - // (the first library shown takes the place of none: nothing was searching another one) + // The first library shown replaces none; later switches invalidate both face review + // state and any similar-photo search belonging to the previous library. if self.shown_library.is_some() { 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; + self.caches.person_page = None; } self.shown_library = Some(generation); if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 91f0c6efd13..7163687a565 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -360,9 +360,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/dialogs/rename.rs b/crates/ui-egui/src/dialogs/rename.rs index a1b2ebf2c91..00bcc3a8cd3 100644 --- a/crates/ui-egui/src/dialogs/rename.rs +++ b/crates/ui-egui/src/dialogs/rename.rs @@ -166,7 +166,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 eac908100d9..458e1c08f2d 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -467,6 +467,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); @@ -543,11 +544,21 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val 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()); Ok(json!({"person": name})) } + "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" => { app.ui.view = ViewMode::Survey; Ok(json!({"photos": crate::panels::compare::survey_photos(app).len()})) @@ -795,7 +806,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; @@ -1771,6 +1782,8 @@ fn view_back_command(app: &mut LightcraftApp, ctx: &egui::Context) -> Result { /// Whether a press may become a drag (the host reads `drag_started` from the response). pub drag: bool, /// Whether the target reads as the selected one. - pub selected: bool, + pub selected: Option, /// How it takes part in input. pub mode: Mode, _lifetime: std::marker::PhantomData<&'a ()>, @@ -158,7 +158,7 @@ pub(crate) struct Target<'a> { impl<'a> Target<'a> { pub fn new(label: impl Into) -> Self { - Target { label: label.into(), tooltip: String::new(), drag: false, selected: false, mode: Mode::Control, _lifetime: std::marker::PhantomData } + Target { label: label.into(), tooltip: String::new(), drag: false, selected: None, mode: Mode::Control, _lifetime: std::marker::PhantomData } } pub fn tooltip(mut self, tooltip: impl Into) -> Self { @@ -178,7 +178,7 @@ impl<'a> Target<'a> { } pub fn selected(mut self, selected: bool) -> Self { - self.selected = selected; + self.selected = Some(selected); self } @@ -192,11 +192,11 @@ impl<'a> Target<'a> { /// Show a host-painted target over `rect`, named `key` for egui. The caller registers its automation name with /// `register_response` when the pass is a live one. pub(crate) fn target(ui: &mut Ui, key: impl Hash + std::fmt::Debug, rect: Rect, spec: Target<'_>) -> HostOutput { - let mut control = HostTarget { common: Common::new(), drag: spec.drag, mode: spec.mode } - .id(egui::Id::unique(key)) - .label(spec.label) - .selected(spec.selected) - .enabled(ui.is_enabled()); + let mut control = + HostTarget { common: Common::new(), drag: spec.drag, mode: spec.mode }.id(egui::Id::unique(key)).label(spec.label).enabled(ui.is_enabled()); + if let Some(selected) = spec.selected { + control = control.selected(selected); + } if !spec.tooltip.is_empty() { control = control.tooltip(spec.tooltip); } diff --git a/crates/ui-egui/src/panels/ignored_faces.rs b/crates/ui-egui/src/panels/ignored_faces.rs new file mode 100644 index 00000000000..7f8ae68d901 --- /dev/null +++ b/crates/ui-egui/src/panels/ignored_faces.rs @@ -0,0 +1,599 @@ +//! Model-independent review and restoration of persistent ignored face crops. +use std::collections::HashSet; + +use craft::ui::buttons::Button; +use craft::ui::contract::{Props as _, Show as _}; +use craft::ui::primitives::IconSpec; +use egui::{Color32, Rect, Sense, pos2, vec2}; +use serde_json::{Value, json}; + +use super::detail::host; +use crate::{LightcraftApp, widgets::register_response}; + +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 { + /// 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)); + } + + /// 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.views.clear(); + 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()?)) +} + +fn review_button(ui: &mut egui::Ui, id: &str, button: Button<'_>) -> bool { + let button = button.id_salt(id).show(ui); + if !host::live(ui) { + return false; + } + register_response(id, button.response.rect, &button.response); + button.clicked() +} + +/// 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()); + 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})) { + 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.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); + } + } + Err(error) => { + view.selected.clear(); + view.anchor = None; + view.faces = None; + view.error = Some(error.to_string()); + } + } + } + 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| { + let button = Button::new(crate::i18n::tr("People")).icon(IconSpec::glyph(&host::IconGlyph(crate::icons::Icon::ChevronLeft))); + back = review_button(ui, "ignoredFaces:back", button); + ui.heading(crate::i18n::tr("Ignored faces")); + if review_button(ui, "ignoredFaces:refresh", Button::new(crate::i18n::tr("Refresh ignored faces"))) { + 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.set_faces(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())); + if review_button(ui, "ignoredFaces:selectAll", Button::new(crate::i18n::tr("Select all"))) { + view.selected.extend(faces.iter().filter_map(key)); + } + if review_button(ui, "ignoredFaces:clear", Button::new(crate::i18n::tr("Clear selection"))) { + view.selected.clear(); + view.anchor = None; + } + let button = Button::new(crate::i18n::tr("Restore selected faces")).enabled(!view.selected.is_empty()); + restore = review_button(ui, "ignoredFaces:restore", button); + }); + let mut requested_page = None; + if view.total > PAGE_SIZE { + ui.horizontal(|ui| { + let previous = Button::new(crate::i18n::tr("Previous page")).enabled(view.offset > 0); + if review_button(ui, "ignoredFaces:previous", previous) { + 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 = Button::new(crate::i18n::tr("Next page")).enabled(view.offset.saturating_add(faces.len()) < view.total); + if review_button(ui, "ignoredFaces:next", next) { + 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(_) => { + // 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; + } + 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 = host::target( + ui, + ("ignored-face", face_key), + image, + host::Target::new(crate::i18n::tr("Ignored face")).selected(view.selected.contains(&face_key)), + ); + if host::live(ui) { + register_response(format!("ignoredFaces:face:{index}"), image, &response); + } + if let Some(rect) = view.views.get(index).copied().flatten() + && 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.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); + } + 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::*; + + /// 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()); + 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()); + 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); + 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}; + 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(); + 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(); + } + } + + /// 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(); + // 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")); + } + + /// 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); + 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()); + } + + /// 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. + 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() { + 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); + 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); + 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()); + 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(); + 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()); + 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); + check_external_shrink(&mut h, id, timeout); + } + + /// 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, "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(); + 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 4914aa92e70..ff6834f2944 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -58,7 +58,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); } @@ -89,12 +94,19 @@ 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 = Button::new(crate::i18n::tr("Ignored faces…")).id_salt("unnamed:ignored").show(ui); + if super::detail::host::live(ui) { + crate::widgets::register_response("unnamed:ignored", ignored.response.rect, &ignored.response); + 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 987ff45c112..75cf313d0da 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -19,7 +19,55 @@ use crate::widgets::register_response; const PAD: f32 = 20.0; const SECTION_H: f32 = 56.0; -/// One face: which photo, which of its regions, the box to show it by, and (for the "More" faces) how alike. +#[derive(Clone, Debug, Default)] +pub struct Selection { + name: String, + active: bool, + faces: std::collections::HashSet<(u64, usize)>, + anchor: Option<(usize, bool)>, + before_click: Option, + confirmed: Vec, + page: 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, its catalog box, and (for the "More" faces) how alike. #[derive(Clone, Debug, PartialEq)] pub struct Face { pub photo: u64, @@ -40,13 +88,13 @@ pub struct PersonPage { pub pending: usize, } +/// Keep the catalog box for commands; the detector-aligned display box is resolved when drawing. 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 { photo: v["photo"].as_u64()?, index: usize::try_from(v["index"].as_u64()?).ok()?, - // shown by the detector's box when the scan has one: every face equally close - rect: rect(&v["view"]).or_else(|| rect(&v["rect"]))?, + rect: rect(&v["rect"])?, score: v["score"].as_f64().unwrap_or(0.0) as f32, }) } @@ -85,9 +133,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 @@ -144,11 +194,27 @@ 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; + // 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.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| { ui.add_space(PAD - 4.0); @@ -192,6 +258,56 @@ 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 real = super::detail::host::live(ui); + let button = |ui: &mut egui::Ui, id, label, enabled| { + let button = Button::new(label).id_salt(id).enabled(enabled).show(ui); + if real { + register_response(id, button.response.rect, &button.response); + } + real && button.clicked() + }; + let active = app.ui.person_selection.active; + let label = if active { crate::i18n::tr("Done selecting") } else { crate::i18n::tr("Select faces…") }; + if button(ui, "person:selectFaces", label, true) { + 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 { + if button(ui, "person:selectAll", crate::i18n::tr("Select all"), true) { + app.ui.person_selection.before_click = None; + app.ui.person_selection.faces.extend(page.confirmed.iter().map(|f| (f.photo, f.index))); + } + if button(ui, "person:clearSelection", crate::i18n::tr("Clear selection"), true) { + 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(); + if button(ui, "person:ignoreSelected", crate::i18n::tr("Ignore selected faces"), count > 0) { + let faces: Vec<_> = page + .confirmed + .iter() + .filter(|face| app.ui.person_selection.faces.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.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, @@ -241,10 +357,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); } } } @@ -282,6 +415,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())), _ => {} } } @@ -291,7 +425,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 @@ -306,6 +440,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, "rect": f.rect}]})) { + app.toast(ui.ctx(), error); + } + } Hit::Nothing => {} } } @@ -338,7 +477,10 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { } else { format!("{name} — click to open this photo") }; - let resp = super::detail::host::target(ui, (salt, f.photo, f.index), r, host(name.to_string()).tooltip(tip)); + let target = host(name.to_string()).tooltip(tip); + let target = + if !more && app.ui.person_selection.active { target.selected(app.ui.person_selection.faces.contains(&(f.photo, f.index))) } else { target }; + let resp = super::detail::host::target(ui, (salt, f.photo, f.index), r, target); let real = super::detail::host::live(ui); if real { register_response(format!("{salt}:{}:{}", f.photo, f.index), r, &resp); @@ -367,7 +509,8 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { let hovered = resp.hovered() || x_resp.as_ref().is_some_and(|x| x.hovered()) || above_resp.as_ref().is_some_and(|x| x.hovered()); let p = ui.painter(); p.rect_filled(r, 3.0, t.canvas); - if let Some(job) = app.session.face_job(lightcraft_catalog::PhotoId(f.photo), f.rect, (r.width() * ppp).ceil() as usize) + let photo = lightcraft_catalog::PhotoId(f.photo); + if let Some(job) = app.session.face_job(photo, app.session.face_view(photo, f.rect), (r.width() * ppp).ceil() as usize) && let Some(tex) = app.renderer.variant(job) { p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); @@ -375,7 +518,6 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { if hovered { p.rect_stroke(r, 3.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Outside); } - let mut hit = Hit::Nothing; 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)); @@ -395,18 +537,34 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit { p.line_segment([pos2(ac.x - 4.0, ac.y - 1.0), pos2(ac.x, ac.y - 5.0)], arrow); p.line_segment([pos2(ac.x, ac.y - 5.0), pos2(ac.x + 4.0, ac.y - 1.0)], arrow); } + let mut ignore = false; + super::detail::host::context_menu(ui, &resp, name, |ui| { + let row = craft::ui::menu::MenuItem::new(crate::i18n::tr("Ignore face (blurry / not a face)")).id_salt("person:ignoreFace").show(ui); + if super::detail::host::live(ui) { + register_response("person:ignoreFace", row.response.rect, &row.response); + ignore = row.ran; + } + }); + if ignore { + return Hit::Ignore; + } if more { if x_resp.as_ref().is_some_and(|x| x.clicked()) { - hit = Hit::Dismiss; + Hit::Dismiss } else if above_resp.as_ref().is_some_and(|x| x.clicked()) { - hit = Hit::ConfirmAbove; + Hit::ConfirmAbove } else if resp.clicked() { - hit = Hit::Confirm; + Hit::Confirm + } else { + Hit::Nothing } + } else if resp.double_clicked() { + Hit::OpenDouble } else if resp.clicked() { - hit = Hit::Open; + Hit::Open + } else { + Hit::Nothing } - hit } #[cfg(test)] @@ -417,6 +575,275 @@ mod named_person_actions_tests; mod tests { use super::*; + #[test] + fn commands_keep_the_catalog_box_instead_of_the_detector_view() { + let catalog = lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.8, y1: 0.9 }; + let view = lightcraft_geom::Rect { x0: 0.3, y0: 0.2, x1: 0.6, y1: 0.6 }; + let face = json!({"photo": 1, "index": 0, "rect": catalog, "view": view}); + let page = parse(&json!({"confirmed": [face.clone()], "more": [face]})); + assert_eq!(page.confirmed[0].rect, catalog); + assert_eq!(page.more[0].rect, catalog); + assert!(face_of(&json!({"photo": 1, "index": 0, "view": view})).is_none(), "a display box cannot identify a catalog region"); + } + + /// Even a stale page handed to the UI must not let either ignore action target an index's + /// replacement. Deliberately retain the old response: normal revision refresh is a separate + /// defense, and must not mask a missing rectangle in either command payload. + #[test] + fn person_ignore_actions_reject_reused_indices_without_an_undo_step() { + use lightcraft_catalog::Op; + use lightcraft_meta::{Region, RegionKind}; + let timeout = std::time::Duration::from_secs(15); + for action in ["bulk", "confirmed", "more"] { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default()); + let ids: Vec<_> = app.session.catalog.photos().take(2).map(|photo| photo.id).collect(); + let rect = lightcraft_geom::Rect { x0: 0.1, y0: 0.1, x1: 0.3, y1: 0.4 }; + let replacement = lightcraft_geom::Rect { x0: 0.5, y0: 0.2, x1: 0.8, y1: 0.6 }; + for (i, id) in ids.iter().enumerate() { + let mut meta = app.session.catalog.photo(*id).unwrap().meta.clone(); + let name = (i != 0 || action != "more").then(|| "Person".into()); + meta.regions = vec![Region { rect, kind: RegionKind::Face, name, description: None }]; + if i == 0 { + meta.regions.push(Region { rect: replacement, ..meta.regions[0].clone() }); + } + app.session.commit("setup", Op::SetMeta { id: *id, meta: Box::new(meta) }).unwrap(); + } + let mut page = parse(&app.session.execute("faces.person", &json!({"name": "Person"})).unwrap()); + if action == "more" { + page.more = vec![Face { photo: ids[0].0, index: 0, rect, score: 0.8 }]; + page.ready = true; + } + app.session.execute("photo.removeRegion", &json!({"id": ids[0].0, "index": 0})).unwrap(); + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.app.run("view.person", json!({"name": "Person"})).unwrap(); + // Inject an old rendered response, independent of the normal revision invalidation. + 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(timeout); + let before: Vec<_> = ids.iter().map(|id| h.app.session.catalog.photo(*id).unwrap().meta.regions.clone()).collect(); + let undo = h.app.session.undo.len(); + if action == "bulk" { + h.app.ui.person_selection.active = true; + h.app.ui.person_selection.faces.extend(ids.iter().map(|id| (id.0, 0))); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "person:ignoreSelected"}), timeout)["ok"], true); + } else { + let prefix = if action == "more" { "more-face" } else { "person-face" }; + let opened = h.request("ui.clickWidget", json!({"id": format!("{prefix}:{}:0", ids[0].0), "button": "right"}), timeout); + assert_eq!(opened["ok"], true, "{opened}"); + h.step(); + assert_eq!(h.request("ui.clickWidget", json!({"id": "person:ignoreFace"}), timeout)["ok"], true); + } + h.step(); + for (id, regions) in ids.iter().zip(&before) { + assert_eq!(&h.app.session.catalog.photo(*id).unwrap().meta.regions, regions, "{action}: no selected face may change"); + } + assert_eq!(h.app.session.undo.len(), undo, "{action}: a refused stale action adds no undo step"); + } + } + + /// 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); + } + + /// 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 (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)); + } + 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(), + active.then_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() { + 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 88f419a9676..4de0aafc38e 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -21,6 +21,8 @@ use crate::theme::Tokens; 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, } @@ -45,6 +47,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), }) @@ -72,9 +75,33 @@ 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 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. + 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 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() { + 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)); + 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 } @@ -129,9 +156,10 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { }; let mut submit: Option = None; let mut clear = false; + let mut ignore = false; // Measuring must not publish targets or apply an action before the real pass. let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); - 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)); @@ -155,10 +183,13 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { submit = Some(chosen); } let c = Button::new(crate::i18n::tr("Clear")).id_salt("unnamed:clear").show(ui); + let b = Button::new(crate::i18n::tr("Ignore selected faces")).id_salt("unnamed:ignore").show(ui); if real { crate::widgets::register_response("unnamed:clear", c.response.rect, &c.response); + crate::widgets::register_response("unnamed:ignore", b.response.rect, &b.response); } clear = real && (c.clicked() || field.cancelled()); + ignore = real && b.clicked(); }); // the people already named, matching what is typed (a click names the faces) let typed = app.ui.unnamed_name.trim().to_lowercase(); @@ -180,7 +211,30 @@ pub fn naming_bar(app: &mut LightcraftApp, ui: &mut egui::Ui) { }); } } - if let Some(who) = submit { + if ignore { + // 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(); + // 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(); + 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(); @@ -316,6 +370,114 @@ mod unnamed_faces_port_tests; 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"]); + // Keep the same synthetic window's AccessKit output beside the image, so a visual + // inspection also checks the names, roles and states exposed to assistive technology. + let ctx = h.view.ctx.clone(); + ctx.enable_accesskit(); + let raw = crate::headless::HeadlessView::raw_input(h.size, h.pixels_per_point, h.time(), Vec::new()); + let output = ctx.run_ui(raw, |ui| h.app.ui(ui)); + let tree = output.platform_output.accesskit_update.expect("AccessKit was enabled for the captured window"); + std::fs::write(std::path::PathBuf::from(path).with_extension("accessibility.txt"), format!("{tree:#?}")).unwrap(); + } + + #[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); + // 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, 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, 7.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!({ @@ -331,6 +493,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}"); diff --git a/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs b/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs index c6787f58820..51af1466b4c 100644 --- a/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs +++ b/crates/ui-egui/src/panels/unnamed_faces_port_tests.rs @@ -33,20 +33,24 @@ impl Panel { description: None, }) .collect(); - app.session.commit("unnamed port fixture", lightcraft_catalog::Op::SetMeta { id: photo, meta: Box::new(meta) }).unwrap(); let list = Unnamed { total: 3, ready: true, ordered: true, - faces: (0..3) - .map(|index| UnnamedFace { + faces: meta + .regions + .iter() + .enumerate() + .map(|(index, region)| UnnamedFace { photo: photo.0, index, + rect: region.rect, view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.25, y1: 0.5 }, suggestion: None, }) .collect(), }; + app.session.commit("unnamed port fixture", lightcraft_catalog::Op::SetMeta { id: photo, meta: Box::new(meta) }).unwrap(); app.caches.unnamed = Some((app.session.catalog.revision, app.caches.faces_indexed, 0.0, Arc::new(list.clone()))); let view = HeadlessView::new(); app.install_framework(&view.ctx); @@ -172,7 +176,8 @@ fn unnamed_port_open_settings_only_when_detection_is_off_and_list_is_empty() { p.click("unnamed:openSettings"); assert_eq!(p.app.ui.dialog, Some(crate::state::Dialog::Settings { tab: "faces".into() })); p.app.ui.dialog = None; - let face = UnnamedFace { photo: 17, index: 3, view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 }, suggestion: None }; + let rect = lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 }; + let face = UnnamedFace { photo: 17, index: 3, rect, view: rect, suggestion: None }; p.list.faces.push(face); p.list.ordered = false; p.frame(vec![], Pass::Real); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 010194f99b9..92b04dd3557 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -169,6 +169,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)] @@ -196,6 +198,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 @@ -610,6 +614,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, @@ -619,6 +624,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, dragging_interaction: None, diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index d1828c4314b..2a5f535a84e 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -327,8 +327,23 @@ fn another_library_stops_the_search_and_gets_nothing_from_it() { h.step(); } 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; + let indexed = h.app.caches.faces_indexed; + h.app.caches.unnamed = Some((revision, indexed, h.time(), Arc::new(Default::default()))); + h.app.caches.person_page = Some(("Old Person".into(), revision, indexed, h.time(), Arc::new(Default::default()))); 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()); + assert!(h.app.caches.person_page.is_none()); drive.open.store(true, Ordering::SeqCst); let reply = answer(&mut h, &rx); assert_eq!(reply["ok"], false, "{reply}"); 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 2e988030ea7..0b76c1ae867 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -325,12 +325,77 @@ 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; 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`. + +### 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. + 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. + 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. +- After rereading sidecars, reload face lists before submitting or retrying ignore/restore + selections: region indices may have changed, so do not reuse the old `(photo, index, rect)` tuples. +- 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 16 (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. + +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. 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 16**, following format 15 for per-photo denoiser selection. +Opening an existing library (format 15 or earlier) upgrades its catalog automatically, +preserving per-photo denoiser settings, burst ranks, Lens Blur settings, existing face assignments and boxes, and ignore +decisions from earlier feature builds. The replaced snapshot and log are kept beside the catalog +as described in [catalog persistence](catalog-persistence.md). Older builds then +refuse the newer format instead of trying to decode it as an older catalog. + +The catalog keeps its own region kind for ignored faces. Conversion to shared metadata for +interchange/export omits ignored regions rather than turning them back into ordinary faces; +ordinary region types and unknown type strings retain their geometry and metadata. + **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 91132d9ad2e..899a27b0a96 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -63,6 +63,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. @@ -96,13 +98,22 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-29 | patch | LRC-LIB-PEOPLE: ignored faces move to catalog format 15 after main's format-14 culling ranks; upgrade, replay and compaction retain arranged bursts and prior ignored-face catalogs; no ranked gap/count change | | 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet | +| 2026-11-19 | patch | LRC-LIB-PEOPLE: clarify that clients reload face lists after a sidecar refresh before submitting or retrying reviewed selections; no ranked gap/count change | | 2026-11-16 | patch | Gap 16: the Map module's remaining parts landed (Info panel map, location filter with counts, saved locations, track logs, keys, menus and Settings ▸ Map); LR-MAP-MODULE 🟡; ranks and hours unchanged (Book, Slideshow and publish services remain) | +| 2026-11-14 | patch | LRC-LIB-PEOPLE: retain the catalog-only ignored region kind across the shared-metadata migration; interchange excludes ignored regions and preserves ordinary region types/geometry; no ranked gap/count change | +| 2026-11-11 | patch | LRC-LIB-PEOPLE: ignored faces use catalog format 14 after Lens Blur took format 13 on main; the upgrade preserves Lens Blur, shared masks and earlier ignore decisions; no ranked gap/count change | +| 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-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-23 | minor | Gap 3: process V13 eases global Shadows off at large amounts, and negative Texture and the Global grading wheel act less, fitted to 56 Lightroom exports of real Canon edits (mean ΔE 9.5 → 9.0, #523); the gap stays open and hours are unchanged | | 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 | +| 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 | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 3cccf0a6fbf..3f27b1720fa 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -724,7 +724,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 dragged label says how many photos get it; when all have it, it says so and a drop does nothing); a keyword dragged over itself or what is inside it shows the not-allowed cursor and says why; Esc gives up a drag. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), an Enter Keywords / Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords as text or as chips to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Enter Keywords (`keywordView:enter`, `field:enterKeywords`) shows the selection's keywords as text, commas between them and an asterisk after one only some selected photos have: Return or leaving the box applies the edit to the photos selected when it began as one undo step (a keyword left out comes off every one of them, a name typed goes to all of them, `>` and `<` mark a hierarchy as `\|` does (`animal > dog` and `dog < animal` are both `animal\|dog`), a marked keyword stays on the photos that have it and without its asterisk goes to all), Esc gives the edit up, another selection gives it up too, an asterisk after any other name is refused with the text kept, and containing keywords and synonyms stay out of the text (the rules for mixed keywords and for when an edit applies are LightCraft's own). Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:`; the highlight stays with its keyword when the library changes), Return or a click gives the highlighted one with the keywords typed before it and leaves the cursor in the box; with none highlighted Return gives what was typed, as before. As in Enter Keywords, `>` and `<` in a typed name mark a hierarchy as `\|` does, unless the name as written is a keyword the library has. A name the library doesn't have is announced as a new keyword, with the keyword it would go inside (`kwCompleteCreate`). The suggestions below no longer change while typing. A refused add says why and keeps the text. With several photos selected the box says how many its keywords are of (`keywordScope`); a chip's × is a target as tall as the chip and 22 pt wide that lights up on its own, and taking a keyword off several photos (× or the chip's menu) says which keyword, from how many photos, and that Edit ▸ Undo puts it back; a refused removal says why. Chips and their × show the keyboard focus. Edit Keyword Set (Keyword Set ▸ Edit Set…): a set's name and nine slots typed in place, empty slots kept so each keyword stays on its ⌥ key, a set renamed in place (`cmd:keyword.saveSet` `replace`) or saved as a new set (`new`, a taken name refused). File ▸ Import Keywords… / Export Keywords… (`cmd:keyword.import`, `cmd:keyword.export`): keyword list files in Lightroom Classic's format (tab-indented, `{synonym}`, `[left out of export]`), which Capture One, darktable, Bridge and Photo Supreme (its Formatted Vocabulary File) read and write too; import adds what is missing in one undo step, export names the keywords Capture One refuses (; , < >). The keyword shortcut (Set Keyword Shortcut, Use This as Keyword Shortcut, a + in the Keyword List, ⇧K) is under KEYC-METADATA. Not yet: synonyms in search, person keywords tied to faces, IPTC keywords in exported files (Piwigo, RawTherapee), hierarchy from digiKam / ACDSee / Microsoft XMP fields. In the Keyword List a keyword's empty box carries a dot when the selected photos have a keyword inside it (its tooltip names them), so a folded keyword shows that something in it is applied; a keyword list a file writes as one `dc:subject` / `lr:hierarchicalSubject` entry with a keyword a line is read as one keyword a line, a library already holding such a keyword is repaired when it opens, and the sidebar and Keyword List draw a name on one line (`crates/catalog/src/keywords.rs`, `crates/engine/src/tests/keyword_list.rs`, `crates/ui-egui/src/tests/keyword_sidebar.rs`) | | 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 ▸ 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 15 upgrades older libraries, retaining main's format-14 culling ranks, Lens Blur and shared mask grids. Person-page ignore actions send catalog rectangles to reject reused region indices. 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`), `crates/engine/src/cmd/similar.rs`, `crates/ui-egui/src/find_similar.rs` | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`); the app reads the photos on a worker thread under an activity row with ✕ | | 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`, `crates/catalog/src/model.rs` (`Photo::library_file`), `crates/ui-egui/src/missing_sweep.rs`, `crates/ui-egui/src/panels/left.rs` (`locate_missing_item`), `crates/ui-egui/src/thumb.rs` | 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 a warning icon in the grid and the filmstrip (widgets `badge:failed:`, `film:failed:`) whose tooltip says why and where to go (Locate Missing File… for a missing original, else Reload from Disk), 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 | @@ -810,7 +810,13 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-12-02 | patch | LRC-LIB-PEOPLE: catalog format 16 preserves format-15 per-photo denoiser settings and earlier ignored-face decisions; status and counts unchanged | | 2026-12-01 | patch | MENU-VIEW-MAP ✅ → 🟡: the Map view's commands moved from View ▸ Map to Window ▸ Map, beside the Map panel toggles, because View is at the 40-row menu limit; Map View (⌘⌥3) is there too | +| 2026-11-29 | patch | LRC-LIB-PEOPLE: catalog format 15 follows format-14 culling ranks; frozen legacy data checks preserve manual burst order and earlier ignored-face catalogs through upgrade, replay and compaction; status and counts unchanged | +| 2026-11-19 | patch | LRC-LIB-PEOPLE: command help and face API guidance explain reloading selections after sidecar refreshes can reorder region indices; status and counts unchanged | +| 2026-11-14 | patch | LRC-LIB-PEOPLE: explicit shared-metadata conversion preserves catalog-only ignored faces, ordinary region types and geometry; catalog format 14 and partial status/counts unchanged | +| 2026-11-11 | patch | LRC-LIB-PEOPLE: catalog format 14 follows main's format-13 Lens Blur; frozen legacy payloads and replay/compaction coverage preserve both Lens Blur settings and face metadata; status and counts unchanged | +| 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-27 | minor | LR-IMP-ADD-DIALOG / LR-IMP-MOVE: an optional backup folder (Backup to, `library.import` `backup`) gets a verified copy of each copied or moved file under the same folders and names as the destination; a move keeps the original of a photo whose backup failed; counts unchanged | | 2026-12-02 | minor | LR-MASK-BRUSH: a stroke's edge is feathered as one dab's is (process V16); status unchanged | | 2026-11-24 | minor | LR-MASK-BRUSH: process V15 makes Flow coverage per brush radius travelled, as Lightroom Classic's strokes measure on a grey card, live and committed, CPU and GPU (`masks::travel_flow`; `flow_is_coverage_per_radius_travelled_as_in_lightroom`); a stroke no longer builds up more when painted slowly; status unchanged (🟡: no A/B brushes) | @@ -834,6 +840,9 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged | | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | +| 2026-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-30 | patch | LR-BEHAV-TITLEBAR: the search box's padding around its text is the field's, not the title bar's: pressing there no longer moves the window on macOS, and a click there focuses the field (#2807); status counts unchanged | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | | 2026-12-03 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V17 renders Apple ProRAW in Lightroom Classic's fitted tone chain (#613, #4196); status unchanged | @@ -841,6 +850,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-11-06 | minor | LR-EDIT-DETAIL-CNR, LRC-DEV-PROCESS: process V6 takes colour noise reduction to the joint method on linear R−Y / B−Y (issue #815); status unchanged | | 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) | +| 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-11-02 | patch | LR-VIEW-SURVEY: the survey picks the column count that shows the most of its photos at their own shapes (four portrait photos side by side on a wide screen, not two by two) and centres an incomplete last row; when a photo leaves or joins, the others glide to their new places in 0.2 s and keep their renders (each photo keeps its render slot); status unchanged | | 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | | 2026-10-29 | minor | LR-PREF-LOCALSTORAGE, LRC-LIB-PREVIEWS: the preview cache stays uncapped and warns once per session when its drive has under 10 % or 20 GB free, with a button to Settings → Performance; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 39d5cc7e927..8d566a7944e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -214,6 +214,16 @@ process 5: new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current Process. See [process versions](process-versions.md). +## 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 16, retaining per-photo denoiser settings and manually arranged culling bursts; + older builds cannot open an upgraded library. + ## 2026-11-02 ### The Windows title bar is readable from the moment the window opens