diff --git a/Cargo.lock b/Cargo.lock index 037865f87f2..5fc4d1ad899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3987,6 +3987,7 @@ dependencies = [ name = "lightcraft-ui-egui" version = "0.18.0" dependencies = [ + "chrono", "craft-ui", "craft-update", "craft-window", @@ -4010,6 +4011,7 @@ dependencies = [ "log", "serde", "serde_json", + "sys-locale", "toml", "web-time", ] diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 7822bbed9a5..e03c5e12435 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -140,6 +140,15 @@ fn library_error(dir: &str, e: lightcraft_engine::EngineError) -> String { } fn main() -> ExitCode { + if std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new(lightcraft_engine::metadata_read::WORKER_ARG)) { + return match lightcraft_engine::metadata_read::worker_main() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error}"); + ExitCode::FAILURE + } + }; + } // `--features dhat-heap`: count allocations; the profile is written when `_heap` drops // (LIGHTCRAFT_DHAT_FILE, default dhat-heap.json). #[cfg(feature = "dhat-heap")] diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 613197459cd..c69e2c801e4 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -7,6 +7,29 @@ use serde_json::{Value, json}; use super::binary; +#[test] +fn metadata_worker_reads_sidecars_without_starting_the_cli() { + let input = tmp("metadata-worker.png"); + gradient_png(&input); + let sidecar = input.with_extension("xmp"); + std::fs::write(&sidecar, r#""#).unwrap(); + let mut child = Command::new(binary()) + .arg(lightcraft_engine::metadata_read::WORKER_ARG) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let request = json!({"path": input, "sidecar": {"naming": "stem", "owns_stem": true}}); + child.stdin.take().unwrap().write_all(request.to_string().as_bytes()).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(result["Ok"][0]["xmp"].as_array().unwrap().iter().any(|tag| tag["value"] == "Worker title"), "{result}"); + let _ = std::fs::remove_file(input); + let _ = std::fs::remove_file(sidecar); +} + #[test] fn contact_sheet_exports_pdf_and_protects_originals() { let input = tmp("contact-sheet-input.png"); diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 2f98abafe10..5061d112289 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -148,6 +148,16 @@ impl eframe::App for App { const EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); fn main() -> eframe::Result { + // A metadata read runs in a disposable copy of this process, before logging, preferences or + // the window are initialised. Its parent can terminate a filesystem call that misses a deadline. + if std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new(lightcraft_engine::metadata_read::WORKER_ARG)) { + let result = lightcraft_engine::metadata_read::worker_main(); + if let Err(error) = result { + eprintln!("{error}"); + std::process::exit(1); + } + return Ok(()); + } // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&lightcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { diff --git a/contributors/people.toml b/contributors/people.toml index 836a3d801f2..edee32a1b14 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -82,3 +82,6 @@ sync_github_name = true [people.Peaperfish] real_name = "Yule Wang" display_name = "Brian Wang" + +[people.pixelpuxel] +real_name = "Gabriel Schreiber" diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index 5ceacb9539e..8dee2046781 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -128,29 +128,8 @@ pub fn specs() -> Vec { }), cmd!(query "photo.allMetadata", "All Metadata", [], None, "{id?} → {exif: [{group, tag, name, value}], xmp: [{name, value}]} — every EXIF / TIFF / GPS tag of the file and its XMP properties", always, |s, p| { let id = photo_arg(s, p, "photo.allMetadata")?; - let ph = s.catalog.photo(id).ok_or_else(|| super::bad("photo.allMetadata", "no such photo"))?.clone(); - let lightcraft_catalog::Source::File { path } = &ph.source else { - return Ok(json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"})); - }; - let bytes = match &s.media.file_bytes { - Some(r) => r(path), - None => std::fs::read(path).map_err(|e| format!("{path}: {e}")), - } - .map_err(|e| super::bad("photo.allMetadata", e))?; - let exif: Vec = lightcraft_meta::file_tag_rows(&bytes) - .into_iter() - .map(|r| json!({"group": r.group, "tag": r.tag, "name": r.name, "value": r.value})) - .collect(); - // Keep sidecar precedence; reuse the loaded bytes for embedded XMP. - let packet = match s.sidecar_lookup(ph.id).find(path) { - Some(sc) => std::fs::read_to_string(sc).ok(), - None => lightcraft_meta::embedded(&bytes).xmp, - }; - let xmp: Vec = packet - .and_then(|x| lightcraft_meta::parse_xmp(&x).ok()) - .map(|d| d.properties.into_iter().filter(|(k, _)| !k.starts_with("lc:")).map(|(k, v)| json!({"name": k, "value": v.join("; ")})).collect()) - .unwrap_or_default(); - Ok(json!({"exif": exif, "xmp": xmp})) + crate::metadata_read::Request::new(s, id).and_then(|request| request.read()) + .map_err(|e| super::bad("photo.allMetadata", e)) }), cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| { let all: Vec = s.catalog.albums().cloned().collect(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 704602e4beb..bf585459e00 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -57,6 +57,7 @@ pub mod logging; pub mod media; pub mod memory; pub mod merge; +pub mod metadata_read; mod model_download; pub mod open_path; pub mod originals; @@ -1138,6 +1139,18 @@ impl Session { self.shelved_filter.is_some() } + /// Clear matching view rules from both the live filter and the filter put aside by Enable Filters. + pub fn clear_view_rules(&mut self, rules: &lightcraft_catalog::RuleSet) { + if self.filter.rule_set.as_ref() == Some(rules) { + self.filter.rule_set = None; + } + if let Some(filter) = &mut self.shelved_filter + && filter.rule_set.as_ref() == Some(rules) + { + filter.rule_set = None; + } + } + /// Photos shown in the grid/filmstrip for the current source, filter and sort. pub fn visible(&mut self) -> &[PhotoId] { let mut key = diff --git a/crates/engine/src/metadata_read.rs b/crates/engine/src/metadata_read.rs new file mode 100644 index 00000000000..1da9b72526d --- /dev/null +++ b/crates/engine/src/metadata_read.rs @@ -0,0 +1,166 @@ +//! A read-only metadata request that can be moved to a UI worker. + +use crate::{Session, merge::ByteReader, sidecar::SidecarLookup}; +use lightcraft_catalog::{PhotoId, Source}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// Private desktop subcommand used for a metadata read that the parent can terminate on timeout. +pub const WORKER_ARG: &str = "--metadata-read-worker"; + +type ReadResult = Result<(Value, Option), String>; + +#[derive(Serialize, Deserialize)] +struct WorkerInput { + path: String, + sidecar: SidecarLookup, +} + +/// A detached request for all readable EXIF and XMP attached to one catalog photo. +pub struct Request { + source: Source, + read: Option, + sidecar: SidecarLookup, +} + +impl Request { + /// Capture the photo source, custom byte reader and sidecar policy from the session. + pub fn new(session: &Session, id: PhotoId) -> Result { + let photo = session.catalog.photo(id).ok_or("no such photo")?; + Ok(Self { source: photo.source.clone(), read: session.media.file_bytes.clone(), sidecar: session.sidecar_lookup(id) }) + } + + /// Return metadata in the command API shape, including a sidecar warning when present. + pub fn read(self) -> Result { + let (mut value, warning) = self.read_with_diagnostics()?; + if let Some(warning) = warning + && let Some(fields) = value.as_object_mut() + { + fields.insert("warning".into(), Value::String(warning)); + } + Ok(value) + } + + /// Return metadata and a non-fatal sidecar warning as separate values for the UI. + pub fn read_with_diagnostics(self) -> ReadResult { + let Source::File { path } = self.source else { + return Ok((json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}), None)); + }; + read_file(path, self.read, self.sidecar) + } + + /// Read in a child process so a blocked filesystem call can be terminated at the deadline. + /// Custom readers stay in-process because their closures cannot cross a process boundary. + #[cfg(not(target_arch = "wasm32"))] + pub fn read_with_deadline(self, timeout: std::time::Duration) -> ReadResult { + if self.read.is_some() { + return self.read_with_diagnostics(); + } + let Source::File { path } = self.source else { + return Ok((json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}), None)); + }; + read_in_worker(WorkerInput { path, sidecar: self.sidecar }, timeout) + } +} + +/// Read and parse the original plus its chosen XMP sidecar, if one exists. +fn read_file(path: String, read: Option, sidecar: SidecarLookup) -> ReadResult { + let bytes = match read { + Some(read) => read(&path), + None => std::fs::read(&path).map_err(|e| format!("{path}: {e}")), + }?; + let exif: Vec = lightcraft_meta::file_tag_rows(&bytes) + .into_iter() + .map(|row| json!({"group": row.group, "tag": row.tag, "name": row.name, "value": row.value})) + .collect(); + let packet = match sidecar.find(&path) { + Some(sidecar) => std::fs::read_to_string(&sidecar).map(Some).map_err(|error| format!("{}: {error}", sidecar.display())), + None => Ok(lightcraft_meta::embedded(&bytes).xmp), + }; + let parsed = packet.and_then(|packet| packet.map(|xmp| lightcraft_meta::parse_xmp(&xmp).map_err(|error| format!("XMP: {error}"))).transpose()); + let warning = parsed.as_ref().err().cloned(); + let xmp: Vec = parsed + .ok() + .flatten() + .map(|d| { + d.properties + .into_iter() + .filter(|(key, _)| !key.starts_with("lc:")) + .map(|(key, values)| json!({"name": key, "value": values.join("; ")})) + .collect() + }) + .unwrap_or_default(); + Ok((json!({"exif": exif, "xmp": xmp}), warning)) +} + +/// Serve one request on standard input/output. The desktop app calls this before initialising UI. +#[cfg(not(target_arch = "wasm32"))] +pub fn worker_main() -> Result<(), String> { + let input: WorkerInput = serde_json::from_reader(std::io::stdin().lock()).map_err(|error| format!("metadata worker input: {error}"))?; + let result = read_file(input.path, None, input.sidecar); + serde_json::to_writer(std::io::stdout().lock(), &result).map_err(|error| format!("metadata worker output: {error}")) +} + +/// The task remains alive after the deadline until the killed child is confirmed stopped. This +/// preserves the read cap even on a filesystem whose kernel call is temporarily uninterruptible. +#[cfg(not(target_arch = "wasm32"))] +fn read_in_worker(input: WorkerInput, timeout: std::time::Duration) -> ReadResult { + use std::io::{Read as _, Write as _}; + use std::process::{Command, Stdio}; + + // Drop also covers failed pipe setup, writes and polling, which must not orphan a worker. + struct Worker(std::process::Child); + impl Drop for Worker { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let payload = serde_json::to_vec(&input).map_err(|error| format!("metadata worker input: {error}"))?; + let exe = std::env::current_exe().map_err(|error| format!("metadata worker executable: {error}"))?; + let mut worker = Worker( + Command::new(exe) + .arg(WORKER_ARG) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|error| format!("metadata worker: {error}"))?, + ); + let child = &mut worker.0; + let Some(mut stdin) = child.stdin.take() else { return Err("metadata worker has no input pipe".into()) }; + stdin.write_all(&payload).map_err(|error| format!("metadata worker input: {error}"))?; + drop(stdin); + let Some(mut stdout) = child.stdout.take() else { return Err("metadata worker has no output pipe".into()) }; + let output = std::thread::Builder::new() + .name("metadata-worker-output".into()) + .spawn(move || { + let mut bytes = Vec::new(); + stdout.read_to_end(&mut bytes).map(|_| bytes) + }) + .map_err(|error| format!("metadata worker output thread: {error}"))?; + let started = std::time::Instant::now(); + let mut timed_out = false; + loop { + match child.try_wait().map_err(|error| format!("metadata worker: {error}"))? { + Some(status) => { + let bytes = output + .join() + .map_err(|_| "metadata worker output thread stopped".to_owned())? + .map_err(|error| format!("metadata worker output: {error}"))?; + if timed_out { + return Err("metadata read timed out. Try Refresh.".into()); + } + if !status.success() { + return Err(format!("metadata worker stopped with {status}")); + } + return serde_json::from_slice(&bytes).map_err(|error| format!("metadata worker output: {error}"))?; + } + None if !timed_out && started.elapsed() >= timeout => { + timed_out = true; + let _ = child.kill(); + } + None => std::thread::sleep(std::time::Duration::from_millis(10)), + } + } +} diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 252dd911a68..2b10aa78a10 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -80,7 +80,7 @@ pub fn find_sidecar(original: &str, naming: SidecarNaming) -> Option { /// may read the shared stem sidecar (`IMG_0001.xmp`) of its stem. A photo that shares its stem /// with a file that owns that sidecar (see [`Session::sidecar_naming`]) reads its own `.xmp` /// and never the packet of the sibling that owns the stem one (issue #1523). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SidecarLookup { pub naming: SidecarNaming, /// False when another file with the same stem owns the stem sidecar. diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 8e7b77f42f3..8e8303a223a 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -27,6 +27,8 @@ egui = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +chrono = { workspace = true } +sys-locale = { version = "0.3", features = ["js"] } [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 552ce68016c..3cc180b818d 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1,4 +1,14 @@ { + "Waiting for an earlier metadata read to finish…": "Warte auf einen vorherigen Metadatenzugriff…", + "Metadata read timed out. Try Refresh.": "Zeitlimit beim Lesen der Metadaten erreicht. Versuche es mit Aktualisieren.", + "Refresh": "Aktualisieren", + "Keys": "Keys", + "Combine Albums": "Sammlungen verknüpfen", + "OR: any album": "ODER: beliebige Sammlung", + "AND: every album": "UND: jede Sammlung", + "First minus others": "Erste minus weitere", + "Only one album": "Nur in einer Sammlung", + "Cmd/Ctrl-click albums to combine. A plain click shows one album.": "Sammlungen mit Cmd/Strg-Klick verknüpfen. Ein einfacher Klick zeigt eine Sammlung.", " (library default)": " (Bibliotheksstandard)", " (inverted)": " (umgekehrt)", " · best of its burst": " · bestes Foto der Serie", diff --git a/crates/ui-egui/src/album_combination.rs b/crates/ui-egui/src/album_combination.rs new file mode 100644 index 00000000000..02ffe420d7c --- /dev/null +++ b/crates/ui-egui/src/album_combination.rs @@ -0,0 +1,161 @@ +//! Live set operations over albums, expressed as the catalog's existing smart-album rules. +//! Membership updates are reflected immediately, without duplicating or moving photos. + +use crate::LightcraftApp; +use lightcraft_catalog::rules::Match; +use lightcraft_catalog::{AlbumId, Rule, RuleSet}; +use lightcraft_engine::LibrarySource; +use serde_json::{Value, json}; + +pub const OPERATIONS: &[(&str, &str)] = + &[("union", "OR: any album"), ("intersection", "AND: every album"), ("difference", "First minus others"), ("exclusive", "Only one album")]; + +/// Build one catalog album-membership predicate. +fn field(id: u64, included: bool) -> Rule { + Rule::Field { field: "album".into(), op: if included { "is" } else { "isNot" }.into(), value: json!(id) } +} + +/// Translate a named set operation into the catalog's existing live rules. +fn rules(ids: &[u64], operation: &str) -> Result { + let (mode, rules) = match operation { + "union" => (Match::Any, ids.iter().map(|id| field(*id, true)).collect()), + "intersection" => (Match::All, ids.iter().map(|id| field(*id, true)).collect()), + "difference" => (Match::All, ids.iter().enumerate().map(|(i, id)| field(*id, i == 0)).collect()), + // For two albums this is XOR. With more albums, keep photos belonging to exactly one. + "exclusive" => ( + Match::Any, + ids.iter() + .map(|id| Rule::Group { group: RuleSet { mode: Match::All, rules: ids.iter().map(|other| field(*other, id == other)).collect() } }) + .collect(), + ), + _ => return Err("view.combineAlbums: unknown operation (union|intersection|difference|exclusive)".into()), + }; + Ok(RuleSet { mode, rules }) +} + +/// Remove only the rules installed by this view, preserving unrelated filters. +pub fn clear(app: &mut LightcraftApp) { + if let Some((ids, operation)) = app.ui.album_combination.take() + && let Ok(set) = rules(&ids, &operation) + { + app.session.clear_view_rules(&set); + } +} + +/// Whether the stored combination still exactly describes the current live view. +pub fn active(app: &LightcraftApp) -> bool { + app.ui.album_combination.as_ref().is_some_and(|(ids, op)| { + (2..=8).contains(&ids.len()) + && app.session.source == LibrarySource::All + && rules(ids, op).is_ok_and(|set| app.session.filter.rule_set.as_ref() == Some(&set)) + }) +} + +/// Validate and apply `view.combineAlbums`, returning the visible photo count. +pub fn command(app: &mut LightcraftApp, params: &Value) -> Result { + let values = params.get("ids").and_then(Value::as_array).ok_or("view.combineAlbums: ids must be an array")?; + if !(2..=8).contains(&values.len()) { + return Err("view.combineAlbums: choose 2 to 8 albums".into()); + } + let mut ids = Vec::new(); + for value in values { + let id = value.as_u64().ok_or("view.combineAlbums: invalid album id")?; + if app.session.catalog.album(AlbumId(id)).is_none_or(|a| a.folder) { + return Err(format!("view.combineAlbums: no album {id}")); + } + if !ids.contains(&id) { + ids.push(id); + } + } + if ids.len() < 2 { + return Err("view.combineAlbums: choose two distinct albums".into()); + } + let operation = match params.get("operation") { + None => "union", + Some(value) => value.as_str().ok_or("view.combineAlbums: operation must be a string")?, + }; + let set = rules(&ids, operation)?; + let problems = set.check(&app.session.catalog); + if !problems.is_empty() { + return Err(problems.iter().map(ToString::to_string).collect::>().join("; ")); + } + let preserve_filters = active(app) && app.ui.album_combination.as_ref().is_some_and(|(current, _)| current == &ids); + let filter = if preserve_filters { + // Changing only the operation keeps filters applied after the combination was opened. + json!({"ruleSet": set}) + } else { + // A source choice starts a fresh view; ordinary filters can be applied to the result next. + let filter = lightcraft_catalog::Filter { rule_set: Some(set), ..Default::default() }; + let mut filter = serde_json::to_value(filter).map_err(|e| e.to_string())?; + let fields = filter.as_object_mut().ok_or("view.combineAlbums: couldn't serialize the filter")?; + // These defaults are normally omitted by Filter's serializer. library.filter merges a + // partial payload, so spell them out to keep a previous Find Similar or multi-select + // filter from narrowing the new source view. + fields.insert("flags".into(), json!([])); + fields.insert("labels".into(), json!([])); + fields.insert("only".into(), json!([])); + fields.insert("onlyNone".into(), json!(false)); + filter + }; + app.session.source = LibrarySource::All; + app.session.execute("library.filter", &filter).map_err(|e| e.to_string())?; + if !preserve_filters { + app.ui.search.clear(); + } + app.ui.album_combination = Some((ids, operation.into())); + app.session.keep_active_in_view(); + Ok(json!({"count": app.session.visible().len(), "operation": operation})) +} + +/// A modifier-click adds or removes an album; a plain click still shows just that album. +pub fn toggle(app: &mut LightcraftApp, id: u64) { + let (mut ids, operation) = if active(app) { + app.ui.album_combination.clone().unwrap_or_default() + } else { + let ids = match app.session.source { + LibrarySource::Album(a) => vec![a.0], + _ => Vec::new(), + }; + (ids, "union".into()) + }; + if ids.contains(&id) { + ids.retain(|a| *a != id); + } else { + ids.push(id); + } + let result = if ids.len() >= 2 { + app.run("view.combineAlbums", json!({"ids": ids, "operation": operation})) + } else if let Some(id) = ids.first() { + app.run("library.source", json!({"kind": "album", "id": id})) + } else { + app.run("library.source", json!({"kind": "all"})) + }; + if let Err(e) = result { + app.toast(&app.tasks.repaint.clone().unwrap_or_default(), e); + } +} + +/// Draw operation choices and the ordered names of the albums being combined. +pub fn controls(app: &mut LightcraftApp, ui: &mut egui::Ui) { + if !active(app) { + return; + } + let Some((ids, mut operation)) = app.ui.album_combination.clone() else { return }; + let before = operation.clone(); + ui.label(crate::i18n::tr("Combine Albums")); + ui.horizontal_wrapped(|ui| { + for (id, label) in OPERATIONS { + let response = ui.selectable_value(&mut operation, (*id).into(), crate::i18n::tr(label)); + crate::widgets::register(ui, format!("albumOperation:{id}"), response.rect); + } + }); + let names: Vec<_> = ids.iter().filter_map(|id| app.session.catalog.album(AlbumId(*id))).map(|a| a.name.as_str()).collect(); + ui.label(names.join(" → ")); + ui.label(crate::i18n::tr("Cmd/Ctrl-click albums to combine. A plain click shows one album.")); + if before != operation + && let Err(e) = app.run("view.combineAlbums", json!({"ids": ids, "operation": operation})) + { + app.toast(ui.ctx(), e); + } + ui.separator(); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba91d2f717..de5d29c41fd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -38,6 +38,7 @@ impl LightcraftApp { native_menu: false, native_shortcuts: Default::default(), recording_shortcut: None, + metadata_panel: Default::default(), text_focus: false, headless_host: false, notices: vec![], @@ -212,7 +213,23 @@ impl LightcraftApp { } else { params }; - let r = self.session.execute(id, ¶ms).map_err(CommandError::from); + let combined = self.ui.album_combination.is_some(); + let mut r = self.session.execute(id, ¶ms).map_err(CommandError::from); + let member_removed = combined + && self + .ui + .album_combination + .as_ref() + .is_some_and(|(ids, _)| ids.iter().any(|id| self.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_none())); + if r.is_ok() && combined && (id == "library.source" || member_removed) { + crate::album_combination::clear(self); + self.session.keep_active_in_view(); + if id == "library.source" + && let Ok(result) = &mut r + { + *result = serde_json::json!({"count": self.session.visible().len()}); + } + } if r.is_ok() && matches!(id, "crop.aspect" | "crop.rotateAspect") { self.ui.crop_default_aspect = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("original") { Some(serde_json::json!("original")) diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 67b1fa176b2..d6369970a16 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -89,6 +89,7 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option) -> if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) { return Err("an import is running".into()); } + crate::album_combination::clear(app); let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string(); let subfolders = subfolders.unwrap_or_else(|| app.session.browse.as_ref().is_some_and(|b| b.subfolders)); let running = app.scan.as_ref().is_some_and(|t| t.browse) || app.import.as_ref().is_some_and(|t| t.browse); diff --git a/crates/ui-egui/src/dialogs/keymap.rs b/crates/ui-egui/src/dialogs/keymap.rs index d0d058afae8..f95b439897d 100644 --- a/crates/ui-egui/src/dialogs/keymap.rs +++ b/crates/ui-egui/src/dialogs/keymap.rs @@ -21,11 +21,10 @@ const SHOW_ALL: &str = "shortcuts-show-all"; pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; capture(app, ui.ctx()); - ui.set_min_width(560.0); let (search_id, all_id) = (egui::Id::unique(SEARCH), egui::Id::unique(SHOW_ALL)); let mut search: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); let mut show_all: bool = ui.data(|d| d.get_temp(all_id)).unwrap_or(false); - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let r = ui.add(egui::TextEdit::singleline(&mut search).hint_text(crate::i18n::tr("Search commands or keys")).desired_width(220.0)); register(ui, "field:shortcutsSearch", r.rect); let r = ui.checkbox(&mut show_all, crate::i18n::tr("Show commands without a shortcut")); @@ -63,18 +62,24 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { // a fixed height, so the dialog doesn't jump around while the search narrows the list // (shorter on a short window, so the dialog fits it) let h = crate::panels::dialogs::list_height(ui, 400.0); - egui::ScrollArea::vertical().max_height(h).min_scrolled_height(h).auto_shrink([false, false]).id_salt("shortcuts-list").show(ui, |ui| { - egui::Grid::new("shortcuts").striped(true).num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| { - for (b, sc) in &rows { - row(app, ui, t, b, sc.as_deref(), mac); - } - if rows.is_empty() { - ui.label(RichText::new(crate::i18n::tr("No matching commands")).color(t.text_dim)); - ui.end_row(); - } + egui::ScrollArea::both() + .max_width(ui.available_width()) + .max_height(h) + .min_scrolled_height(h) + .auto_shrink([false, false]) + .id_salt("shortcuts-list") + .show(ui, |ui| { + egui::Grid::new("shortcuts").striped(true).num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| { + for (b, sc) in &rows { + row(app, ui, t, b, sc.as_deref(), mac); + } + if rows.is_empty() { + ui.label(RichText::new(crate::i18n::tr("No matching commands")).color(t.text_dim)); + ui.end_row(); + } + }); + fixed_keys(app, ui, t, mac, &needle); }); - fixed_keys(app, ui, t, mac, &needle); - }); } /// `Cmd+Shift+Z` as menus show it (`⇧⌘Z` on macOS). diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 271b6e7c913..1f109cbf63e 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -52,6 +52,7 @@ pub const TABS: &[(&str, &str)] = &[ ("performance", "Performance"), ("display", "Display"), ("interface", "Interface"), + ("keys", "Keys"), ("slideshow", "Slideshow"), ("faces", "Faces"), ("denoise", "AI Denoise"), @@ -70,6 +71,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { "performance" => performance_tab(app, ui, &t), "display" => display_tab(app, ui, &t), "interface" => interface_tab(app, ui, &t), + "keys" => super::keymap::body(app, ui, &t), "slideshow" => slideshow_tab(app, ui, &t, true), "faces" => crate::panels::faces::settings_tab(app, ui, &t), "denoise" => crate::panels::denoise::settings_tab(app, ui, &t), diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 5e615bfbcbf..a6bf48d7246 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -78,6 +78,7 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result let previous_dir = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); let previous = previous_dir.as_ref().map(|d| d.to_string_lossy().into_owned()); app.session.close_library().map_err(|e| e.to_string())?; + crate::album_combination::clear(app); let opened = app.session.open_library(&dir, false).map(|_| ()).map_err(|e| format!("{path}: {e}")); app.lightroom_last = None; app.lightroom_result = None; diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 97cd8ac6914..ac28db2cef2 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -393,11 +393,12 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { style.font = t.font(12.0); // Tool and preset panels publish hover previews before the photo consumes them. let mut canvas = None; + let tools_label = if app.ui.right == crate::state::RightPanel::Metadata { "Metadata" } else { "Tools" }; let output = DockArea::new(egui::Id::unique("lightcraft-docking")).locked(workspace.locked).show_with_limits( ui, &workspace.layout, &style, - |panel| crate::i18n::tr(panel.label()).into(), + |panel| crate::i18n::tr(if *panel == Panel::Tools { tools_label } else { panel.label() }).into(), permissions, panel_limits, |ui, panel| match panel { @@ -412,7 +413,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { crate::panels::left::show(app, ui); } Panel::Tools => { - crate::widgets::announce_region(ui, egui::accesskit::Role::Complementary, crate::i18n::tr(Panel::Tools.label())); + crate::widgets::announce_region(ui, egui::accesskit::Role::Complementary, crate::i18n::tr(tools_label)); crate::widgets::register(ui, "panel:right_panel", ui.max_rect()); crate::panels::right::show(app, ui); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5e794f105c5..ab576982465 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -15,6 +15,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { ..craft_update::suite::LIGHTCRAFT }; +mod album_combination; pub mod brush_live; pub mod canvas_keys; mod command_error; @@ -165,6 +166,7 @@ pub struct LightcraftApp { /// The keyboard shortcuts editor is waiting for a key press for this command: no shortcut /// fires (the native menu bar drops its accelerators too) until it gets one or is cancelled. pub recording_shortcut: Option, + pub(crate) metadata_panel: panels::right::MetadataRuntime, /// A text field had the keyboard at the end of the last frame. egui drops the focus as Esc /// arrives, before the shortcuts are read, so this is how Esc there stays the field's own. pub text_focus: bool, diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 672c7cbccc7..36b6a33c840 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -304,6 +304,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "panel.versions", "panel.activity", "panel.info", + "panel.metadata", "panel.keywords", "---", "@Edit Sections", @@ -439,6 +440,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "panel.versions" => panel(RightPanel::Versions), "panel.activity" => panel(RightPanel::Activity), "panel.info" => panel(RightPanel::Info), + "panel.metadata" => panel(RightPanel::Metadata), "panel.keywords" => panel(RightPanel::Keywords), "panel.presets" => Some(u.presets), "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ec9835a39f8..5d3e3188a29 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -146,6 +146,9 @@ fn theme_command(app: &mut LightcraftApp, p: &Value) -> Result { /// Handle UI commands; `None` means "not a UI command — send it to the engine". pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option> { + if id == "view.combineAlbums" { + return Some(crate::album_combination::command(app, p)); + } if matches!(id, "ui.dock" | "ui.dock.reset") { return Some(crate::docking::command(app, id == "ui.dock.reset", p)); } @@ -964,6 +967,10 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val panel(app, ctx, RightPanel::Info, "Info"); Ok(Value::Null) } + "panel.metadata" => { + panel(app, ctx, RightPanel::Metadata, "Metadata"); + Ok(Value::Null) + } "panel.keywords" => { panel(app, ctx, RightPanel::Keywords, "Keywords"); Ok(Value::Null) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c803de71939..b5edb887803 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -131,6 +131,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("local.restoreHidden", "Show Hidden Local Locations", None, ""), // {on?}: the Info panel's Target Photo / Selected Photos choice (on = Selected Photos) ("view.infoSelectedPhotos", "Show Metadata for Selected Photos", None, ""), + // {ids: [albumId, ...], operation: union|intersection|difference|exclusive}; 2–8 albums. + ("view.combineAlbums", "Combine Albums", None, ""), ("view.fullScreenPreview", "Full Screen Preview", Some("F"), "View"), ("view.lightsOut", "Lights Out", Some("Shift+L"), "View"), ("view.enterFullScreen", "Enter Full Screen", Some("Cmd+Shift+F"), "View"), @@ -149,6 +151,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("panel.redeye", "Red Eye", None, "Window"), ("panel.presets", "Presets", Some("Shift+P"), "Window"), ("panel.info", "Info", Some("I"), "Window"), + ("panel.metadata", "Metadata", None, "Window"), ("panel.keywords", "Keywords", Some("K"), "Window"), // the Keywords panel with the cursor in its Add keyword box ("panel.addKeywords", "Add Keywords", Some("Cmd+K"), ""), diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index f9a2cf229f2..9717f11644a 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -5,6 +5,7 @@ use super::{Album, AlbumId, Align2, Icon, LibrarySource, LightcraftApp, Rect, Se /// Albums: the tree of albums and the folders they are sorted into. `reveal`: an album just made, /// whose folders open down to it. pub(super) fn albums_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, reveal: Option) { + crate::album_combination::controls(app, ui); let kids: AlbumKids = app.session.catalog.album_children_by_parent().into_iter().map(|(k, v)| (k, v.into_iter().cloned().collect())).collect(); let cat = &app.session.catalog; let mut open_to = Vec::new(); @@ -13,14 +14,20 @@ pub(super) fn albums_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, reveal: Op open_to.push(p); cur = cat.album(p).and_then(|a| a.parent); } - albums_tree(app, ui, &kids, None, 0.0, &open_to); + let combined = if crate::album_combination::active(app) { + app.ui.album_combination.as_ref().map(|(ids, _)| ids.clone()).unwrap_or_default() + } else { + Vec::new() + }; + albums_tree(app, ui, &kids, None, 0.0, (&open_to, &combined)); } /// The albums inside each folder (`None`: the top level), in the order they are listed. type AlbumKids = std::collections::HashMap, Vec>; /// `open_to`: folders forced open this frame (the way down to an album that was just made). -fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, parent: Option, indent: f32, open_to: &[AlbumId]) { +fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, parent: Option, indent: f32, selection: (&[AlbumId], &[u64])) { + let (open_to, combined) = selection; // 64 folders deep at most (16 points a level): a catalog that loops must not overflow the stack if indent > 64.0 * INDENT_STEP { return; @@ -58,10 +65,10 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare } folder_menu(app, &resp, a); if draw_open { - albums_tree(app, ui, all, Some(a.id), indent + INDENT_STEP, open_to); + albums_tree(app, ui, all, Some(a.id), indent + INDENT_STEP, selection); } } else { - let sel = app.session.source == LibrarySource::Album(a.id); + let sel = app.session.source == LibrarySource::Album(a.id) || combined.contains(&a.id.0); let icon = if a.is_smart() { Icon::SmartAlbum } else { Icon::Album }; // cached: a smart album's count scans the catalog let now = (app.session.clock)(); @@ -78,7 +85,8 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare .selected(sel) .indent(indent) .sense(Sense::click_and_drag()) - .show(app, ui); + .show(app, ui) + .on_hover_text(crate::i18n::tr("Cmd/Ctrl-click albums to combine. A plain click shows one album.")); if !problems.is_empty() { crate::widgets::register(ui, format!("albumProblem:{}", a.id.0), resp.rect); } @@ -103,7 +111,11 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare resp = resp.on_hover_text(tip); } if resp.clicked() { - let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0})); + if ui.input(|i| i.modifiers.command || i.modifiers.ctrl) { + crate::album_combination::toggle(app, a.id.0); + } else { + let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0})); + } } folder_menu(app, &resp, a); } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index b28445d5de1..7aacf0455a0 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -15,6 +15,8 @@ mod crop; mod history; mod info; mod keywords; +mod metadata; +pub(crate) use metadata::Runtime as MetadataRuntime; #[cfg(test)] use crop::aspect_label; @@ -87,6 +89,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::Masking => super::masking::show(app, ui, id), RightPanel::RedEye => red_eye(app, ui, id), RightPanel::Info => info(app, ui, id), + RightPanel::Metadata => metadata::show(app, ui, id), RightPanel::Keywords => keywords(app, ui, id), RightPanel::Versions => versions(app, ui, id), RightPanel::Activity => activity(app, ui, id), diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index 5810a0f2721..ad1e8dfd1e9 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -283,7 +283,8 @@ pub(crate) fn focus_text(f: Option<&lightcraft_meta::FocusPoint>) -> Option String { +/// Format a byte count compactly for the Info and Metadata panels. +pub(super) fn human_size(bytes: u64) -> String { match bytes { b if b >= 1 << 20 => format!("{:.1} MB", b as f64 / (1u64 << 20) as f64), b if b >= 1 << 10 => format!("{} KB", b >> 10), diff --git a/crates/ui-egui/src/panels/right/metadata.rs b/crates/ui-egui/src/panels/right/metadata.rs new file mode 100644 index 00000000000..e8dacb4b078 --- /dev/null +++ b/crates/ui-egui/src/panels/right/metadata.rs @@ -0,0 +1,365 @@ +//! Read-only metadata: prominent catalog fields immediately, full file tags on a worker. + +use super::{LightcraftApp, PhotoId, Tokens, header, padded, register}; +use serde_json::Value; +use std::sync::Arc; + +const TASK: &str = "Metadata panel"; +const MAX_READS: usize = 4; +const READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const TAGS_PER_PAGE: usize = 100; +type ReadResult = Result<(Value, Option), String>; + +#[derive(Default)] +pub(crate) struct Runtime { + key: Option<(u64, PhotoId, String)>, + result: Option, + page: usize, + started_at: Option, + attempt: Arc<()>, + locale: String, + queued: bool, +} + +/// Dispatch at most one read for the selected photo and accept only its current result. +fn load(app: &mut LightcraftApp, id: PhotoId) { + let Some(photo) = app.session.catalog.photo(id) else { return }; + let path = match &photo.source { + lightcraft_catalog::Source::File { path } => path.clone(), + _ => format!("demo:{}", id.0), + }; + let key = (app.session.library_generation(), id, path); + if app.metadata_panel.key.as_ref() != Some(&key) { + app.metadata_panel = Runtime { key: Some(key.clone()), locale: sys_locale::get_locale().unwrap_or_default(), ..Default::default() }; + } + if app.metadata_panel.result.is_some() { + return; + } + if app.metadata_panel.started_at.is_some_and(|start| start.elapsed() >= READ_TIMEOUT) { + // The OS may still own a blocking read. Keep counting that worker until it exits. + app.metadata_panel.result = Some(Err(crate::i18n::tr("Metadata read timed out. Try Refresh.").into())); + return; + } + if app.metadata_panel.started_at.is_some() { + return; + } + app.metadata_panel.queued = app.tasks.labels().iter().filter(|name| name.starts_with(TASK)).count() >= MAX_READS; + if app.metadata_panel.queued { + return; + } + let request = match lightcraft_engine::metadata_read::Request::new(&app.session, id) { + Ok(request) => request, + Err(error) => { + app.metadata_panel.result = Some(Err(error)); + return; + } + }; + let attempt = Arc::clone(&app.metadata_panel.attempt); + let result = crate::tasks::spawn( + app, + TASK, + None, + move || { + #[cfg(any(test, target_arch = "wasm32"))] + return request.read_with_diagnostics(); + #[cfg(all(not(test), not(target_arch = "wasm32")))] + request.read_with_deadline(READ_TIMEOUT) + }, + move |app, _, result| { + if Arc::ptr_eq(&app.metadata_panel.attempt, &attempt) + && app.metadata_panel.key.as_ref() == Some(&key) + && app.session.library_generation() == key.0 + { + app.metadata_panel.result = Some(result); + } + }, + ); + match result { + Ok(()) => app.metadata_panel.started_at = Some(web_time::Instant::now()), + Err(error) => app.metadata_panel.result = Some(Err(error)), + } +} + +/// Draw immediate catalog fields followed by asynchronously read file metadata. +pub(super) fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { + load(app, id); + let Some(photo) = app.session.catalog.photo(id).cloned() else { return }; + header(ui, "Metadata"); + padded(ui, |ui| { + let t = Tokens::get(ui.ctx()); + for (section, rows) in sections(&photo, &app.metadata_panel.locale) { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::tr(section)).font(t.semibold(12.5)).color(t.text)); + ui.add_space(4.0); + for (name, value) in rows { + row(ui, name, &value, &t); + } + if section == "File" + && let lightcraft_catalog::Source::File { path } = &photo.source + { + ui.label(egui::RichText::new(crate::i18n::tr("File Path")).size(11.5).color(t.text_dim)); + let response = ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text)).wrap().selectable(true)); + register(ui, "metadata:File Path", response.rect); + ui.horizontal_wrapped(|ui| { + if crate::widgets::text_button(ui, "metadataCopyPath", "Copy File Path", false).clicked() { + ui.ctx().copy_text(path.clone()); + } + let response = ui.add_enabled(app.services.reveal.is_some(), egui::Button::new(crate::i18n::tr(crate::menus::reveal_label()))); + register(ui, "button:metadataReveal", response.rect); + if response.clicked() + && let Err(error) = app.run("app.showInFinder", serde_json::json!({})) + { + app.toast(ui.ctx(), error); + } + }); + } + ui.add_space(8.0); + ui.separator(); + } + // Every populated catalog field, including structured focus and region information. + if let Ok(meta) = serde_json::to_value(&photo.meta) { + ui.label(egui::RichText::new(crate::i18n::tr("Catalog Metadata")).font(t.semibold(12.5))); + catalog_rows(ui, "", &meta, 0, &t); + } + ui.add_space(8.0); + ui.separator(); + ui.label(egui::RichText::new(crate::i18n::tr("All File Metadata")).font(t.semibold(12.5))); + if app.metadata_panel.result.is_some() && ui.button(crate::i18n::tr("Refresh")).clicked() { + app.metadata_panel.result = None; + app.metadata_panel.page = 0; + app.metadata_panel.started_at = None; + app.metadata_panel.attempt = Arc::new(()); + app.metadata_panel.locale = sys_locale::get_locale().unwrap_or_default(); + ui.ctx().request_repaint(); + } + match &app.metadata_panel.result { + None if app.metadata_panel.queued => { + ui.label(crate::i18n::tr("Waiting for an earlier metadata read to finish…")); + } + None => { + ui.label(crate::i18n::tr("Reading metadata…")); + } + Some(Err(error)) => { + ui.label(crate::i18n::tr("Original metadata unavailable")); + ui.add(egui::Label::new(error).wrap()); + } + Some(Ok((data, warning))) => { + if let Some(warning) = warning { + ui.add(egui::Label::new(warning).wrap()); + } + let tags = data["exif"].as_array().into_iter().flatten().chain(data["xmp"].as_array().into_iter().flatten()); + let count = tags.clone().count(); + let page = app.metadata_panel.page; + if count > TAGS_PER_PAGE { + ui.horizontal(|ui| { + if ui.add_enabled(page > 0, egui::Button::new("‹")).clicked() { + app.metadata_panel.page -= 1; + } + ui.label(format!("{} / {}", page + 1, count.div_ceil(TAGS_PER_PAGE))); + if ui.add_enabled(page + 1 < count.div_ceil(TAGS_PER_PAGE), egui::Button::new("›")).clicked() { + app.metadata_panel.page += 1; + } + }); + } + for tag in tags.skip(page * TAGS_PER_PAGE).take(TAGS_PER_PAGE) { + let group = tag["group"].as_str().unwrap_or("XMP"); + let name = tag["name"].as_str().unwrap_or(""); + let value = tag["value"].as_str().unwrap_or(""); + let value = tag_value(name, value, &app.metadata_panel.locale); + row(ui, &format!("{group} · {name}"), &value, &t); + } + if let Some(note) = data["note"].as_str() { + ui.label(crate::i18n::tr(note)); + } + } + } + }); +} + +/// Labels and values share the top edge and both align left, including wrapped rows. +/// Draw a wrapping, selectable label/value pair. +fn row(ui: &mut egui::Ui, name: &str, value: &str, t: &Tokens) { + ui.horizontal_top(|ui| { + let label_width = (ui.available_width() * 0.38).min(110.0); + ui.allocate_ui_with_layout(egui::vec2(label_width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_width(label_width); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr(name)).size(11.5).color(t.text_dim)).wrap()); + }); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + let response = ui.add(egui::Label::new(egui::RichText::new(value).size(12.0).color(t.text)).wrap().selectable(true)); + register(ui, format!("metadata:{name}"), response.rect); + }); + }); + ui.add_space(4.0); +} + +/// Flatten nested catalog metadata into labeled rows, with a recursion limit. +fn catalog_rows(ui: &mut egui::Ui, prefix: &str, value: &Value, depth: usize, t: &Tokens) { + if depth > 16 { + return; + } + match value { + Value::Null => {} + Value::String(text) if text.is_empty() => {} + Value::Object(fields) => { + for (key, value) in fields { + let name = if prefix.is_empty() { key.clone() } else { format!("{prefix}.{key}") }; + catalog_rows(ui, &name, value, depth + 1, t); + } + } + Value::Array(values) => { + for (index, value) in values.iter().enumerate() { + catalog_rows(ui, &format!("{prefix}.{}", index + 1), value, depth + 1, t); + } + } + Value::String(text) => row(ui, prefix, text, t), + _ => row(ui, prefix, &value.to_string(), t), + } +} + +/// Recognize date-bearing EXIF and XMP field names emitted by the metadata parser. +fn is_date_tag(name: &str) -> bool { + matches!( + name.rsplit(':').next(), + Some( + "DateTime" + | "DateTimeOriginal" + | "DateTimeDigitized" + | "CreateDate" + | "ModifyDate" + | "MetadataDate" + | "DateCreated" + | "GPSDateStamp" + | "GPS Date Stamp" + | "Date/Time Original" + | "Date/Time Digitized" + | "Date/Time Modified" + | "DateTimeCreated" + ) + ) +} + +/// Format recognized date fields while preserving every other metadata value literally. +fn tag_value(name: &str, value: &str, locale: &str) -> String { + if is_date_tag(name) { numeric_date(value, locale) } else { value.to_owned() } +} + +/// Convert supported numeric dates to the locale's day/month order and separators. +fn numeric_date(value: &str, locale: &str) -> String { + let tag = locale.to_ascii_lowercase().replace('_', "-"); + let date = if tag.starts_with("de") || ["ru", "fi", "cs", "pl", "sk"].iter().any(|s| tag.starts_with(s)) { + "%d.%m.%Y" + } else if tag == "en-us" { + "%m/%d/%Y" + } else if ["ja", "zh", "ko", "sv"].iter().any(|s| tag.starts_with(s)) { + "%Y-%m-%d" + } else { + "%d/%m/%Y" + }; + if let Ok(time) = chrono::DateTime::parse_from_rfc3339(value) { + return time.format(&format!("{date} %H:%M:%S %:z")).to_string(); + } + for pattern in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%d %H:%M:%S%.f", "%Y:%m:%d %H:%M:%S"] { + if let Ok(time) = chrono::NaiveDateTime::parse_from_str(value, pattern) { + return time.format(&format!("{date} %H:%M:%S")).to_string(); + } + } + for pattern in ["%Y-%m-%d", "%Y:%m:%d"] { + if let Ok(day) = chrono::NaiveDate::parse_from_str(value, pattern) { + return day.format(date).to_string(); + } + } + value.to_string() +} + +type Rows = Vec<(&'static str, String)>; + +/// Stable sections, with absent optional values omitted instead of empty editing boxes. +fn sections(p: &lightcraft_catalog::Photo, locale: &str) -> Vec<(&'static str, Rows)> { + let mut result = Vec::new(); + let mut file = + vec![("File Name", p.file_name.clone()), ("Format", p.format.to_uppercase()), ("Dimensions", format!("{} × {}", p.width, p.height))]; + if p.file_size > 0 { + file.push(("File Size", super::info::human_size(p.file_size))); + } + if let Some(captured) = &p.captured { + file.push(("Captured", numeric_date(captured, locale))); + } + result.push(("File", file)); + let m = &p.meta; + let mut camera = Vec::new(); + push(&mut camera, "Camera", &m.camera); + push(&mut camera, "Lens", &m.lens); + if let Some(f) = m.focal_mm { + camera.push(("Focal length", format!("{f:.1} mm"))); + } + push(&mut camera, "Shutter speed", &m.shutter); + if let Some(f) = m.aperture { + camera.push(("Aperture", format!("f/{f:.1}"))); + } + if let Some(iso) = m.iso { + camera.push(("ISO", iso.to_string())); + } + if let Some(text) = super::info::focus_text(m.focus.as_ref()) { + camera.push(("Focus", text)); + } + if !camera.is_empty() { + result.push(("Camera", camera)); + } + let mut description = Vec::new(); + for (name, value) in [ + ("Title", &m.title), + ("Caption", &m.caption), + ("Alt Text", &m.alt_text), + ("Extended Description", &m.extended_description), + ("Creator", &m.creator), + ("Copyright", &m.copyright), + ] { + push(&mut description, name, value); + } + if !m.keywords.is_empty() { + description.push(("Keywords", m.keywords.join(", "))); + } + if !description.is_empty() { + result.push(("Description", description)); + } + let mut location = Vec::new(); + for (name, value) in [("Location", &m.location), ("City", &m.city), ("State / Province", &m.state), ("Country", &m.country)] { + push(&mut location, name, value); + } + if let Some((lat, lon)) = m.gps { + location.push(("GPS", format!("{lat:.6}, {lon:.6}"))); + } + if !location.is_empty() { + result.push(("Location", location)); + } + result +} + +/// Add a non-empty optional field to a stable metadata section. +fn push(rows: &mut Rows, name: &'static str, value: &str) { + if !value.trim().is_empty() { + rows.push((name, value.to_string())); + } +} + +#[cfg(test)] +mod tests { + use super::numeric_date; + + #[test] + fn dates_follow_locale_with_two_digit_day_and_month() { + for name in ["Date/Time Original", "Date/Time Digitized", "Date/Time Modified"] { + assert_eq!(super::tag_value(name, "2014:01:01 11:48:16", "de_DE"), "01.01.2014 11:48:16"); + } + assert_eq!(super::tag_value("GPS Date Stamp", "2014:01:01", "de_DE"), "01.01.2014"); + assert_eq!(super::tag_value("dc:title", "2014:01:01", "de_DE"), "2014:01:01"); + assert_eq!(numeric_date("2014-01-01", "de_DE"), "01.01.2014"); + assert_eq!(numeric_date("2014-01-01T11:48:16", "de-DE"), "01.01.2014 11:48:16"); + assert_eq!(numeric_date("2014:01:01 11:48:16", "de_DE"), "01.01.2014 11:48:16"); + assert_eq!(numeric_date("2014-01-01T11:48:16+01:00", "de_DE"), "01.01.2014 11:48:16 +01:00"); + assert_eq!(numeric_date("2014-12-01", "en-US"), "12/01/2014"); + assert_eq!(numeric_date("2014-12-01", "en-GB"), "01/12/2014"); + assert_eq!(numeric_date("IMG_2014-01-01.JPG", "de_DE"), "IMG_2014-01-01.JPG"); + } +} diff --git a/crates/ui-egui/src/panels/strip.rs b/crates/ui-egui/src/panels/strip.rs index faf527be9af..c669da6bb22 100644 --- a/crates/ui-egui/src/panels/strip.rs +++ b/crates/ui-egui/src/panels/strip.rs @@ -27,10 +27,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ) .show(ui, |ui| { crate::widgets::announce_region(ui, egui::accesskit::Role::Toolbar, crate::i18n::tr("Tool strip")); + // Nine tools above and three below, with two one-point separators. + let button_height = BUTTON_H.min((ui.available_height() - 13.0 * GAP - 2.0) / 12.0).max(1.0); let has_photo = app.session.active().is_some(); ui.vertical_centered(|ui| { ui.spacing_mut().item_spacing.y = GAP; - let sz = vec2(t.strip_w, BUTTON_H); + let sz = vec2(t.strip_w, button_height); if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() { let _ = app.run("panel.presets", json!({})); } @@ -60,20 +62,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.dialog = Some(crate::state::Dialog::About); } }); - // bottom icons: two buttons and one gap tall, so Info ends at the bottom margin as + // bottom icons: three buttons and two gaps tall, so Info ends at the bottom margin as // Presets starts at the top one let bottom = ui.max_rect().bottom(); - let mut child = - ui.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_max( - egui::pos2(ui.max_rect().left(), bottom - (2.0 * BUTTON_H + GAP)), - ui.max_rect().right_bottom(), - ))); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_max( + egui::pos2(ui.max_rect().left(), bottom - (3.0 * button_height + 2.0 * GAP)), + ui.max_rect().right_bottom(), + ))); child.vertical_centered(|ui| { ui.spacing_mut().item_spacing.y = GAP; - let sz = vec2(t.strip_w, BUTTON_H); + let sz = vec2(t.strip_w, button_height); if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() { let _ = app.run("panel.keywords", json!({})); } + if icon_button(ui, "metadata", Icon::Album, sz, app.ui.right == RightPanel::Metadata, has_photo, "Metadata").clicked() { + let _ = app.run("panel.metadata", json!({})); + } if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() { let _ = app.run("panel.info", json!({})); } @@ -98,14 +102,16 @@ mod tests { let mut view = HeadlessView::new(); let mut widgets = vec![]; for frame in 0..3 { - let raw = HeadlessView::raw_input(vec2(300.0, 700.0), 1.0, frame as f64 / 60.0, vec![]); + let raw = HeadlessView::raw_input(vec2(300.0, crate::window_place::MIN_SIZE[1]), 1.0, frame as f64 / 60.0, vec![]); view.run(raw, |ui| show(&mut app, ui)); widgets = crate::widgets::take_registry(&view.ctx); } let rect = |id: &str| widgets.iter().find(|(w, _)| w == id).unwrap_or_else(|| panic!("{id} not registered")).1; - let (presets, keywords, info) = (rect("icon:presets"), rect("icon:keywords"), rect("icon:info")); - let (top, bottom) = (presets.top(), 700.0 - info.bottom()); + let (presets, keywords, metadata, info) = (rect("icon:presets"), rect("icon:keywords"), rect("icon:metadata"), rect("icon:info")); + let (top, bottom) = (presets.top(), crate::window_place::MIN_SIZE[1] - info.bottom()); assert!((top - bottom).abs() < 0.5, "Presets starts {top} below the top, Info ends {bottom} above the bottom"); - assert_eq!(info.top() - keywords.bottom(), GAP, "the bottom buttons are spaced like the top ones"); + assert!(rect("icon:more").bottom() <= keywords.top()); + assert_eq!(metadata.top() - keywords.bottom(), GAP); + assert_eq!(info.top() - metadata.bottom(), GAP, "the bottom buttons are spaced like the top ones"); } } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 07cfe8ba03b..bb784824d12 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -369,7 +369,9 @@ fn keyboard_owned(app: &LightcraftApp, ctx: &egui::Context) -> bool { pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { // Space held over a tool ends when the key is up, whoever has the keyboard by then crate::space_hand::tick(app, ctx); - if !matches!(app.ui.dialog, Some(crate::state::Dialog::Shortcuts)) { + let editing_keys = matches!(&app.ui.dialog, Some(crate::state::Dialog::Shortcuts)) + || matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "keys"); + if !editing_keys { app.recording_shortcut = None; } // Dialogs own their keys (including Esc and text editing); background photo actions wait. A diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6f4b42723fa..5eedeca4b16 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -47,6 +47,8 @@ pub struct UiState { pub view: ViewMode, pub left_panel: bool, pub right: RightPanel, + /// Transient multi-album view: ordered album ids and its set operation. + pub album_combination: Option<(Vec, String)>, /// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again. #[serde(skip)] pub right_hidden: RightPanel, @@ -394,6 +396,7 @@ impl Default for UiState { left_width: LEFT_WIDTH.default, right_width: RIGHT_WIDTH.default, right: RightPanel::Edit, + album_combination: None, right_hidden: RightPanel::None, presets: false, preset_thumbs: false, diff --git a/crates/ui-egui/src/state/view.rs b/crates/ui-egui/src/state/view.rs index 61100264751..04571fbf634 100644 --- a/crates/ui-egui/src/state/view.rs +++ b/crates/ui-egui/src/state/view.rs @@ -33,6 +33,8 @@ pub enum RightPanel { Activity, Keywords, Info, + /// Compact, read-only metadata for the active photo. + Metadata, /// The profile browser (part of Edit). Profiles, } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index d9705fdbdb7..966ef68a655 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -16,6 +16,7 @@ mod copy_paste_dialogs; mod crop_rotate; mod crop_tool; mod curve; +mod custom_workflow; mod date_picker; mod dialog_copy; mod dialog_fit; diff --git a/crates/ui-egui/src/tests/custom_workflow.rs b/crates/ui-egui/src/tests/custom_workflow.rs new file mode 100644 index 00000000000..9df0fc47c46 --- /dev/null +++ b/crates/ui-egui/src/tests/custom_workflow.rs @@ -0,0 +1,192 @@ +use super::fixtures::SyntheticLibrary; +use crate::headless::Headless; +use crate::state::{RightPanel, ViewMode}; +use serde_json::json; +use std::time::Duration; + +const T: Duration = Duration::from_secs(30); + +#[test] +fn metadata_panel_reads_sidecar_and_copies_complete_path() { + let fixture = SyntheticLibrary::new("metadata-file-tags"); + let app = fixture.app(); + let id = app.session.selection.active.unwrap(); + let lightcraft_catalog::Source::File { path } = &app.session.catalog.photo(id).unwrap().source else { panic!("file fixture") }; + let path = path.clone(); + std::fs::write( + std::path::Path::new(&path).with_extension("xmp"), + r#""#, + ).unwrap(); + let mut h = Headless::new(app, [1400.0, 1600.0], 1.0); + h.app.run("panel.metadata", json!({})).unwrap(); + assert!(h.settle(T)); + let text = h.painted_text(); + assert!(text.iter().any(|s| s == &path), "complete path: {text:?}"); + assert!(text.iter().any(|s| s == "Sidecar-only author"), "file metadata: {text:?}"); + assert!(text.iter().any(|s| s == "2014:01:01"), "literal XMP title: {text:?}"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:metadataCopyPath"}), T)["ok"], true); + h.step(); + assert_eq!(h.view.clipboard, path); +} + +#[test] +fn metadata_panel_follows_selection_without_edit_fields() { + let fixture = SyntheticLibrary::with_photos("metadata-panel", 2); + let mut h = Headless::new(fixture.app(), [1400.0, 900.0], 1.0); + let ids = h.app.session.visible_cloned(); + h.app.run("photo.setMeta", json!({"ids": [ids[0].0], "title": "First metadata title"})).unwrap(); + h.app.run("photo.setMeta", json!({"ids": [ids[1].0], "title": "Second metadata title"})).unwrap(); + h.app.run("library.select", json!({"ids": [ids[0].0]})).unwrap(); + h.app.run("panel.metadata", json!({})).unwrap(); + h.settle(T); + assert_eq!(h.app.ui.right, RightPanel::Metadata); + assert!(h.painted_text().iter().any(|s| s == "First metadata title")); + assert!(!h.app.widgets.iter().any(|(id, _)| id == "field:title" || id == "field:caption")); + h.app.run("library.select", json!({"ids": [ids[1].0]})).unwrap(); + h.step(); + h.step(); + assert!(h.painted_text().iter().any(|s| s == "Second metadata title")); + assert!(!h.painted_text().iter().any(|s| s == "First metadata title")); + let saved = serde_json::to_string(&h.app.ui).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap().right, RightPanel::Metadata); +} + +#[test] +fn settings_keys_records_space_and_grid_uses_it() { + let fixture = SyntheticLibrary::new("settings-keys"); + let mut h = Headless::new(fixture.app(), [1400.0, 900.0], 1.0); + h.app.ui.view = ViewMode::Detail; + h.app.run("app.settings", json!({"tab": "keys"})).unwrap(); + h.step(); + h.step(); + assert!(h.app.widgets.iter().any(|(id, _)| id == "field:shortcutsSearch")); + // The recorder must remain active while Settings owns the keyboard, just as in Help. + h.app.recording_shortcut = Some("view.gridToggle".into()); + assert_eq!(h.request("ui.key", json!({"key": "Space"}), T)["ok"], true); + h.step(); + h.step(); + assert_eq!(crate::shortcuts::shortcut_of(&h.app.ui.settings.keymap, "view.gridToggle"), Some("Space")); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert!(h.app.ui.dialog.is_some()); + h.app.ui.dialog = None; + h.step(); + assert_eq!(h.request("ui.key", json!({"key": "Space"}), T)["ok"], true); + h.step(); + h.step(); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + assert!(h.app.space_hand.is_none()); + let saved = serde_json::to_string(&h.app.ui).unwrap(); + let back: crate::UiState = serde_json::from_str(&saved).unwrap(); + assert_eq!(crate::shortcuts::shortcut_of(&back.settings.keymap, "view.gridToggle"), Some("Space")); +} + +#[test] +fn album_operations_are_live_and_plain_source_clears_them() { + let fixture = SyntheticLibrary::with_photos("album-operations", 3); + let mut app = fixture.app(); + let ids = app.session.visible_cloned(); + let a = app.run("album.create", json!({"name": "All"})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("album.create", json!({"name": "Children"})).unwrap()["id"].as_u64().unwrap(); + app.run("album.addPhotos", json!({"id": a, "ids": [ids[0].0, ids[1].0]})).unwrap(); + app.run("album.addPhotos", json!({"id": b, "ids": [ids[1].0, ids[2].0]})).unwrap(); + app.run("library.source", json!({"kind": "album", "id": a})).unwrap(); + app.session.filter.flags = vec![lightcraft_catalog::Flag::Reject]; + app.session.filter.labels = vec![lightcraft_catalog::ColorLabel::Red]; + app.session.filter.only = vec![ids[2]]; + app.session.filter.only_none = true; + app.run("view.combineAlbums", json!({"ids": [a, b]})).unwrap(); + assert!(app.session.filter.flags.is_empty()); + assert!(app.session.filter.labels.is_empty()); + assert!(app.session.filter.only.is_empty()); + assert!(!app.session.filter.only_none); + app.session.filter.text = "narrow".into(); + app.session.filter.flags = vec![lightcraft_catalog::Flag::Pick]; + app.session.filter.labels = vec![lightcraft_catalog::ColorLabel::Blue]; + app.session.filter.only = vec![ids[1]]; + app.session.filter.only_none = true; + app.ui.search = "narrow".into(); + app.run("view.combineAlbums", json!({"ids": [a, b], "operation": "intersection"})).unwrap(); + assert_eq!(app.session.filter.text, "narrow"); + assert_eq!(app.session.filter.flags, [lightcraft_catalog::Flag::Pick]); + assert_eq!(app.session.filter.labels, [lightcraft_catalog::ColorLabel::Blue]); + assert_eq!(app.session.filter.only, [ids[1]]); + assert!(app.session.filter.only_none); + assert_eq!(app.ui.search, "narrow"); + app.session.filter.text.clear(); + app.session.filter.flags.clear(); + app.session.filter.labels.clear(); + app.session.filter.only.clear(); + app.session.filter.only_none = false; + app.ui.search.clear(); + for (operation, expected) in + [("union", vec![ids[0], ids[1], ids[2]]), ("intersection", vec![ids[1]]), ("difference", vec![ids[0]]), ("exclusive", vec![ids[0], ids[2]])] + { + app.run("view.combineAlbums", json!({"ids": [a, b], "operation": operation})).unwrap(); + let visible = app.session.visible_cloned(); + assert_eq!(visible.len(), expected.len(), "{operation}"); + assert!(expected.iter().all(|id| visible.contains(id)), "{operation}"); + } + app.run("view.combineAlbums", json!({"ids": [a, b], "operation": "difference"})).unwrap(); + app.run("album.addPhotos", json!({"id": b, "ids": [ids[0].0]})).unwrap(); + assert!(app.session.visible_cloned().is_empty()); + let before = app.session.filter.clone(); + assert!(app.run("view.combineAlbums", json!({"ids": [a, 999999]})).is_err()); + assert!(app.run("view.combineAlbums", json!({"ids": [a, b], "operation": false})).is_err()); + assert_eq!(app.session.filter, before); + let result = app.run("library.source", json!({"kind": "album", "id": a})).unwrap(); + assert_eq!(result["count"], 2); + assert_eq!(app.session.visible_cloned().len(), 2); + assert!(!crate::album_combination::active(&app)); + app.run("view.combineAlbums", json!({"ids": [a, b]})).unwrap(); + app.run("library.toggleFilters", json!({})).unwrap(); + assert!(app.session.filters_off()); + app.run("album.delete", json!({"id": b})).unwrap(); + app.run("library.toggleFilters", json!({})).unwrap(); + assert!(!app.session.filters_off()); + assert!(app.ui.album_combination.is_none()); + assert!(app.session.filter.rule_set.is_none()); +} + +#[test] +fn command_click_album_row_combines_the_two_albums() { + let fixture = SyntheticLibrary::with_photos("album-command-click", 2); + let mut app = fixture.app(); + let a = app.run("album.create", json!({"name": "First album"})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("album.create", json!({"name": "Second album"})).unwrap()["id"].as_u64().unwrap(); + app.ui.left_panel = true; + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + assert!(h.settle(T)); + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("source:album:{a}")}), T)["ok"], true); + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("source:album:{b}"), "cmd": true}), T)["ok"], true); + assert!(crate::album_combination::active(&h.app)); + assert_eq!(h.app.ui.album_combination.as_ref().unwrap().0, [a, b]); +} + +#[test] +fn metadata_reads_for_another_photo_can_finish_before_a_slow_read() { + let fixture = SyntheticLibrary::with_photos("metadata-slow-read", 2); + let mut app = fixture.app(); + let ids = app.session.visible_cloned(); + let lightcraft_catalog::Source::File { path } = &app.session.catalog.photo(ids[0]).unwrap().source else { panic!("file fixture") }; + let slow_path = path.clone(); + let (release, wait) = std::sync::mpsc::channel(); + let wait = std::sync::Mutex::new(wait); + app.session.media.file_bytes = Some(std::sync::Arc::new(move |path| { + if path == slow_path { + let _ = wait.lock().unwrap().recv_timeout(T); + Err("slow original failed".into()) + } else { + Err("other original failed".into()) + } + })); + app.run("library.select", json!({"ids": [ids[0].0]})).unwrap(); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + h.app.run("panel.metadata", json!({})).unwrap(); + assert!(h.step_until(T, |h| h.app.tasks.labels().iter().any(|name| name.starts_with("Metadata panel")))); + h.app.run("library.select", json!({"ids": [ids[1].0]})).unwrap(); + assert!(h.step_until(T, |h| h.painted_text().iter().any(|text| text == "other original failed"))); + release.send(()).unwrap(); + assert!(h.settle(T)); + assert!(h.painted_text().iter().any(|text| text == "other original failed")); + assert!(!h.painted_text().iter().any(|text| text == "slow original failed")); +} diff --git a/docs/gaps.md b/docs/gaps.md index 535479fa10a..7babe1e1ed6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -61,6 +61,11 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-11-03: compact read-only Metadata sidebar, Settings → Keys and live album set operations + added as documented in [metadata-keys-albums.md](metadata-keys-albums.md). These extend + LR-META-INFO, LR-PREF-SHORTCUTS and LR-LIB-ALBUM without closing a ranked gap or changing + readiness estimates. + - 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. diff --git a/docs/metadata-keys-albums.md b/docs/metadata-keys-albums.md new file mode 100644 index 00000000000..ed13552181d --- /dev/null +++ b/docs/metadata-keys-albums.md @@ -0,0 +1,54 @@ +# Metadata, Keys and combined album views + +## Read-only Metadata panel + +Window → Metadata (`panel.metadata`) and the Metadata button in the right tool strip open a +compact two-column view of the active photo's catalog metadata. Selecting another photo updates +it immediately, in grids and Detail. The dock tab reads Metadata. Values can be selected and +copied; there are no metadata editing controls. Empty optional fields are omitted. The original +Info panel remains available for editing. + +The panel shows file details, capture date, camera and exposure settings, existing descriptive +metadata, keywords and location. File paths wrap in full and can be selected, copied with a +button or revealed in the platform file manager. Labels and values align at the left edge. +Dates use the system locale with two-digit days and months (for example, 01.01.2014 in Germany). +All populated catalog fields follow the prominent fields, then all EXIF and XMP tags supported +by LightCraft's metadata reader, including sidecar metadata. Original files are read on a worker +so offline originals do not block the UI; read errors are shown explicitly. Stale results from +a previous photo or library are discarded. Photo → All Metadata remains available separately. + +## Settings → Keys + +Settings → Keys embeds the same editor as Help → Keyboard Shortcuts. Search for a command, +click its shortcut and press the replacement. Escape cancels recording. Remove, restore one and +Reset All work as before, and assignments persist in `ui.json`. Commands without a declared +shortcut can also be shown and assigned. + +For example, search for Grid (`view.gridToggle`) and record Space. Space now switches to the +grid or cycles the grids instead of invoking its default zoom/hand action. G no longer invokes +Grid. The default bindings do not change until the user edits them. Reserved application keys +and the existing list of fixed contextual keys retain their current semantics. + +## Combine album views + +Select the first album, then Cmd-click (macOS) or Ctrl-click another album. Both sidebar rows +are selected and operation controls appear above the album tree: + +- OR: photos in any selected album, deduplicated. +- AND: photos in every selected album. +- First minus others: photos in the first album that are absent from all the others. +- Only one album: photos in exactly one selected album (XOR for two albums). + +The order of album names below the operation controls identifies the first album. A plain +click leaves the combination and shows one album normally. Modifier-click adds or removes an +album. Two to eight ordinary or smart albums can be combined. The command is +`view.combineAlbums {ids: [1, 2], operation: union|intersection|difference|exclusive}`. + +The view uses live catalog rules rather than copying or moving photos: changing album +membership immediately updates the result. Ordinary rating, keyword and other filters can +narrow it further. A new combination starts with a fresh filter. For example, All minus +Children hides photographs already assigned to Children, including offline references. + +Regression coverage: `crates/ui-egui/src/tests/custom_workflow.rs` checks selection-following +read-only metadata, recording Space from Settings and dispatching it, set-operation truth +tables, live membership and returning to a normal album source. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index dfab7f6bdee..e8812328899 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -11,6 +11,11 @@ The rows are maintained by hand; the summary block is generated (`cargo xtask pa `cargo xtask parity` (part of `cargo xtask ci`) checks that every command id, control id and path cited here still exists. Formerly docs/parity.md. +2026-11-03 additions to LR-META-INFO, LR-PREF-SHORTCUTS and LR-LIB-ALBUM: +`cmd:panel.metadata` opens a compact read-only sidebar; Settings → Keys reuses the editable +keymap; `cmd:view.combineAlbums` combines live album membership with union, intersection, +difference or exactly-one rules. See [behavior and tests](metadata-keys-albums.md). + - **Ids** come from the (local, gitignored) reference in `plan/lightroom/`: `LR-…` = feature catalog (03), `MENU-…` = menu items (04), `KEY-…` / `KEYC-…` = keyboard shortcuts (06, desktop / Classic), `LRC-…` = Classic extras (08). Ids are stable; never renumber.