From 561e5b25afc0e510be5e4920a12cee226ef0481f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 08:05:16 -0400 Subject: [PATCH 01/55] LR-BEHAV-BG-TASKS: a preview build asked for while another runs can wait in line for it Jobs that must not run side by side share a lane (`activity::Lane`; the preview lane first: Build Previews and background Build / Discard Smart Previews). With `queue: true` a build asked for while its lane is busy waits in line instead of being refused: it keeps what it was asked, with the photos written out, and `Session::start_waiting` (after every command, and every frame in the app) runs it under the id it had in line once the lane is free. `activity.list` lists waiting tasks after the running ones (`waiting`, `place`, `lane`); `activity.cancel` takes one out of the line, `all` empties it, and opening another library drops it. The line holds at most 100. Without `queue` the call is refused as before. The activity stack draws running tasks only. Co-Authored-By: Claude --- crates/engine/src/activity.rs | 290 +++++++++++++++++++++++++- crates/engine/src/cmd/activity.rs | 4 +- crates/engine/src/cmd/previews.rs | 144 +++++++++++-- crates/engine/src/lib.rs | 34 ++- crates/engine/src/library.rs | 5 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/task_queue.rs | 249 ++++++++++++++++++++++ crates/ui-egui/src/app/frame.rs | 2 + crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/panels/activity.rs | 3 +- crates/ui-egui/src/tests/activity.rs | 35 ++++ crates/ui-egui/src/tests/progress.rs | 3 + docs/background-tasks.md | 12 ++ docs/control-protocol.md | 6 +- 14 files changed, 751 insertions(+), 39 deletions(-) create mode 100644 crates/engine/src/tests/task_queue.rs diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a58..c7b4944ca46 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -7,14 +7,80 @@ //! check between files or photos: the guard adopts it ([`Cancel::Flag`]), so the stack's ✕, `activity.cancel` and the //! job's own Cancel all set the same atomic. Numbers are worded by the frontend from `done`, `total` and [`Unit`]; a //! detail set here is a name (a file, a model), never a sentence, so the frontend can translate everything else. +//! +//! Jobs that must not run side by side share a [`Lane`]. One asked for while its lane is busy can wait in line +//! ([`Activity::enqueue`]): it keeps what it was asked ([`Request`], the command and its parameters) and runs it +//! when the jobs ahead of it are over ([`crate::Session::start_waiting`]), planning its work then, not when it was +//! asked. Nothing waits across another library: the files may have changed meanwhile. use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use serde::Serialize; +use serde_json::Value; /// The longest label or detail kept, in characters (a file name can be anything). const MAX_TEXT: usize = 200; +/// The most tasks waiting in line, in all lanes. +pub const MAX_WAITING: usize = 100; + +/// Jobs that must not run side by side: one waits for those ahead of it to end. Kinds without a lane run as they +/// always did (and are refused while one of their kind runs, where that is the rule). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Lane { + /// Build Previews and Build / Discard Smart Previews: one preview build at a time (`Session::preview_build`). + Previews, +} + +impl Lane { + /// The lane of tasks of `kind` ([`TaskInfo::kind`]). + pub fn of(kind: &str) -> Option { + match kind { + "previews" | "smartPreviews" => Some(Lane::Previews), + _ => None, + } + } +} + +/// What a job was asked: the command and its parameters, with everything that depends on the moment (the +/// selection, the photos in view) written out, so that running it later does the same work. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + pub command: String, + pub params: Value, +} + +/// A task waiting in line ([`Activity::enqueue`]), as [`Activity::take_ready`] hands it over to be started. +#[derive(Debug)] +pub struct Waiting { + pub id: u64, + pub kind: &'static str, + pub label: String, + pub lane: Lane, + pub request: Request, + queued: web_time::Instant, +} + +impl Waiting { + fn info(&self, place: usize) -> TaskInfo { + TaskInfo { + id: self.id, + kind: self.kind, + label: self.label.clone(), + done: 0, + total: 0, + unit: Unit::Count, + detail: String::new(), + cancellable: true, + cancelling: false, + age_ms: millis(self.queued.elapsed()), + waiting: true, + place, + lane: Some(self.lane), + } + } +} /// The background tasks in flight. Cheap to clone (one `Arc`), so worker threads can hold it. #[derive(Clone, Default)] @@ -26,6 +92,10 @@ pub struct Activity { struct Inner { /// Oldest first. tasks: Mutex>>, + /// The tasks waiting in line, in the order they were asked for. + waiting: Mutex>, + /// The id the waiting task being started keeps (its kind, its id): see [`Activity::take_ready`]. + reserved: Mutex>, next: AtomicU64, } @@ -87,6 +157,11 @@ pub struct TaskInfo { /// Cancel was asked for; the job stops at its next check. pub cancelling: bool, pub age_ms: u64, + /// It waits in line for the tasks ahead of it in its lane (nothing done yet: `done` and `total` are 0). + pub waiting: bool, + /// Its place in its lane's line, from 1; 0 for a running task. + pub place: usize, + pub lane: Option, } struct Entry { @@ -162,7 +237,10 @@ impl Entry { detail: lock(&self.detail).clone(), cancellable: self.is_cancellable(), cancelling: self.is_cancelled(), - age_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + age_ms: millis(self.started.elapsed()), + waiting: false, + place: 0, + lane: Lane::of(self.kind), } } } @@ -171,7 +249,9 @@ impl Activity { /// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend /// translates it). pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard { - let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + // a task that waited in line keeps the id it had there + let reserved = lock(&self.inner.reserved).take_if(|(k, _)| *k == kind).map(|(_, id)| id); + let id = reserved.unwrap_or_else(|| self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1)); let cancel = match cancel { Cancel::No => None, Cancel::Yes => Some(Arc::new(AtomicBool::new(false))), @@ -194,29 +274,130 @@ impl Activity { TaskGuard { activity: self.clone(), entry } } - /// Every task in flight, oldest first. + /// Every task in flight, oldest first, then those waiting in line, in the order they were asked for. pub fn list(&self) -> Vec { - lock(&self.inner.tasks).iter().map(|e| e.info()).collect() - } - - /// Ask task `id` to stop (it stops at its next check). An unknown id (the task may have just ended) or a task - /// that can't be cancelled is an error. + let mut rows: Vec = lock(&self.inner.tasks).iter().map(|e| e.info()).collect(); + rows.extend(self.waiting()); + rows + } + + /// The tasks waiting in line, in the order they were asked for, each with its place in its lane. + pub fn waiting(&self) -> Vec { + let waiting = lock(&self.inner.waiting); + let mut ahead: Vec<(Lane, usize)> = Vec::new(); + waiting + .iter() + .map(|w| { + let place = match ahead.iter_mut().find(|(lane, _)| *lane == w.lane) { + Some((_, n)) => { + *n += 1; + *n + } + None => { + ahead.push((w.lane, 1)); + 1 + } + }; + w.info(place) + }) + .collect() + } + + /// Ask task `id` to stop (it stops at its next check), or take it out of the line if it waits. An unknown id + /// (the task may have just ended) or a task that can't be cancelled is an error. pub fn cancel(&self, id: u64) -> Result<(), String> { + { + let mut waiting = lock(&self.inner.waiting); + if let Some(at) = waiting.iter().position(|w| w.id == id) { + waiting.remove(at); + return Ok(()); + } + } let tasks = lock(&self.inner.tasks); let entry = tasks.iter().find(|e| e.id == id).ok_or_else(|| format!("no task {id}"))?; if entry.try_cancel() { Ok(()) } else { Err(format!("{} can't be cancelled", entry.label)) } } - /// Ask every cancellable task to stop; returns how many were asked. + /// Ask every cancellable task to stop, and empty the line (what waits would start as soon as they stopped); + /// returns how many were asked or taken out. pub fn cancel_all(&self) -> usize { + let dropped = std::mem::take(&mut *lock(&self.inner.waiting)).len(); let tasks = lock(&self.inner.tasks); - tasks.iter().filter(|e| e.try_cancel()).count() + dropped + tasks.iter().filter(|e| e.try_cancel()).count() } /// Tasks that quitting would cut short: cancellable ones not already stopping. pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Put a task of `kind` in line behind the others of its lane; it runs `request` when its turn comes. Returns + /// its id and its place in the line. A kind without a lane, or a line already [`MAX_WAITING`] long, is an error. + pub fn enqueue(&self, kind: &'static str, label: &str, request: Request) -> Result<(u64, usize), String> { + let lane = Lane::of(kind).ok_or_else(|| format!("{kind} tasks don't wait in line"))?; + let mut waiting = lock(&self.inner.waiting); + if waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} tasks are waiting already")); + } + let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + waiting.push(Waiting { id, kind, label: capped(label), lane, request, queued: web_time::Instant::now() }); + let place = waiting.iter().filter(|w| w.lane == lane).count(); + Ok((id, place)) + } + + /// Whether a task of `lane` runs now. + pub fn lane_busy(&self, lane: Lane) -> bool { + lock(&self.inner.tasks).iter().any(|e| Lane::of(e.kind) == Some(lane)) + } + + /// Whether a task waits in `lane`'s line. + pub fn lane_waiting(&self, lane: Lane) -> bool { + lock(&self.inner.waiting).iter().any(|w| w.lane == lane) + } + + /// Take the first waiting task whose lane is free out of the line, to be started now. The next task of its + /// kind started ([`Activity::start`]) keeps its id, until [`Activity::started`] says the attempt is over. + pub fn take_ready(&self) -> Option { + self.take_ready_if(|_| true) + } + + /// [`Activity::take_ready`] among the tasks whose request `runs` can run: each frontend starts what it knows how to + /// (the engine its commands, the app its own). Only the first in each lane's line is looked at: one the caller + /// can't run holds its lane, as it would if it had started. + pub fn take_ready_if(&self, runs: impl Fn(&Request) -> bool) -> Option { + let mut waiting = lock(&self.inner.waiting); + let mut held: Vec = lock(&self.inner.tasks).iter().filter_map(|e| Lane::of(e.kind)).collect(); + let mut at = None; + for (i, w) in waiting.iter().enumerate() { + if held.contains(&w.lane) { + continue; + } + if runs(&w.request) { + at = Some(i); + break; + } + held.push(w.lane); + } + let w = waiting.remove(at?); + *lock(&self.inner.reserved) = Some((w.kind, w.id)); + Some(w) + } + + /// The attempt to start the task [`Activity::take_ready`] handed over is over (it started, or it could not). + pub fn started(&self) { + *lock(&self.inner.reserved) = None; + } + + /// Another library was opened: what waited in line was about the old one's photos and folders, so the line + /// empties. Returns how many tasks waited. + pub fn library_changed(&self) -> usize { + std::mem::take(&mut *lock(&self.inner.waiting)).len() + } +} + +/// Milliseconds, saturating. +fn millis(d: std::time::Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -435,4 +616,93 @@ mod tests { std::thread::spawn(move || h.progress(3, 7)).join().unwrap(); assert_eq!((a.list()[0].done, a.list()[0].total), (3, 7)); } + + fn request(command: &str) -> Request { + Request { command: command.into(), params: serde_json::json!({}) } + } + + #[test] + fn a_task_of_a_kind_without_a_lane_does_not_wait() { + let a = Activity::default(); + let e = a.enqueue("export", "Exporting", request("x")).unwrap_err(); + assert!(e.contains("export"), "{e}"); + assert!(a.list().is_empty()); + } + + #[test] + fn the_line_is_bounded_and_lists_places_per_lane() { + let a = Activity::default(); + for place in 1..=MAX_WAITING { + assert_eq!(a.enqueue("previews", "P", request("x")).unwrap().1, place); + } + assert!(a.enqueue("smartPreviews", "S", request("x")).unwrap_err().contains("100")); + let rows = a.list(); + assert_eq!(rows.len(), MAX_WAITING); + assert!(rows.iter().all(|r| r.waiting && r.lane == Some(Lane::Previews))); + assert_eq!(rows.iter().map(|r| r.place).collect::>(), (1..=MAX_WAITING).collect::>()); + } + + #[test] + fn a_waiting_task_starts_when_its_lane_is_free_and_keeps_its_id() { + let a = Activity::default(); + let ahead = a.start("previews", "P", Cancel::Yes); + let (id, _) = a.enqueue("smartPreviews", "S", request("smart")).unwrap(); + assert!(a.lane_busy(Lane::Previews) && a.lane_waiting(Lane::Previews)); + assert!(a.take_ready().is_none(), "the lane is busy: one preview build at a time"); + drop(ahead); + assert!(!a.lane_busy(Lane::Previews)); + let w = a.take_ready().expect("the lane is free"); + assert_eq!((w.id, w.request.command.as_str()), (id, "smart")); + assert!(!a.lane_waiting(Lane::Previews)); + let g = a.start("smartPreviews", "S", Cancel::Yes); + a.started(); + assert_eq!(g.id(), id, "it keeps the id it had in line"); + assert!(!a.list()[0].waiting); + assert_ne!(a.start("export", "E", Cancel::Yes).id(), id); + } + + #[test] + fn an_attempt_that_did_not_start_a_task_gives_its_id_up() { + let a = Activity::default(); + let (id, _) = a.enqueue("previews", "P", request("x")).unwrap(); + let w = a.take_ready().unwrap(); + assert_eq!(w.id, id); + a.started(); // the command failed before starting anything + assert_ne!(a.start("previews", "P", Cancel::Yes).id(), id, "a later task of the kind doesn't take it"); + } + + #[test] + fn take_ready_if_skips_what_the_caller_cannot_run_but_keeps_its_lane_held() { + let a = Activity::default(); + a.enqueue("previews", "mine", request("engine")).unwrap(); + a.enqueue("previews", "next", request("engine")).unwrap(); + assert!(a.take_ready_if(|r| r.command == "other").is_none(), "the first in the lane isn't ours: it holds the lane"); + assert_eq!(a.take_ready_if(|_| true).map(|w| w.label), Some("mine".to_string())); + } + + #[test] + fn cancelling_a_waiting_task_removes_it_and_cancel_all_empties_the_line() { + let a = Activity::default(); + let _running = a.start("previews", "P", Cancel::Yes); + let (first, _) = a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("previews", "B", request("x")).unwrap(); + a.enqueue("smartPreviews", "C", request("x")).unwrap(); + a.cancel(first).unwrap(); + assert!(a.cancel(first).is_err()); + assert_eq!(a.waiting().iter().map(|t| (t.label.as_str(), t.place)).collect::>(), vec![("B", 1), ("C", 2)]); + assert_eq!(a.cancel_all(), 3, "the running one and the two that waited"); + assert!(a.waiting().is_empty() && !a.lane_waiting(Lane::Previews)); + } + + #[test] + fn a_library_change_empties_the_line() { + let a = Activity::default(); + let running = a.start("previews", "P", Cancel::Yes); + a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("smartPreviews", "B", request("x")).unwrap(); + assert_eq!(a.library_changed(), 2); + assert_eq!(a.list().len(), 1, "what runs goes on"); + drop(running); + assert!(a.take_ready().is_none()); + } } diff --git a/crates/engine/src/cmd/activity.rs b/crates/engine/src/cmd/activity.rs index ed4e8d35c73..3fa99b488a7 100644 --- a/crates/engine/src/cmd/activity.rs +++ b/crates/engine/src/cmd/activity.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Background Tasks", [], None, - "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first; total 0 = not known yet", + "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for a task of their lane (waiting: true, place: 1 = next in its lane, lane: previews; done and total 0); total 0 = not known yet", always, |s, _| Ok(json!({"tasks": s.activity.list()})) ), @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Cancel Background Task", [], None, - "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). An unknown id (it may have just finished) or a task that can't be cancelled is an error", + "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). A task waiting in line is taken out of it and never runs; all also empties the line. An unknown id (it may have just finished) or a task that can't be cancelled is an error", always, |s, p| { const C: &str = "activity.cancel"; diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index e1b33cc7144..34f13e4cf6b 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, str_param}; -use crate::activity::{Cancel, TaskGuard}; +use crate::activity::{Cancel, Lane, Request, TaskGuard}; use crate::media::{RenderJob, THUMB_SIZES}; use crate::{Result, Session}; @@ -69,18 +69,80 @@ pub(crate) fn jobs_for(s: &mut Session, id: lightcraft_catalog::PhotoId, edge: O if e >= thumb { view.into_iter().chain(grid).collect() } else { grid.into_iter().chain(view).collect() } } -/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). -fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { - let (kind, label) = match state.what { +/// The row in the activity stack of a build of `what` (as in [`PreviewBuild::what`]): its kind and its label. +fn row_of(what: &str) -> (&'static str, &'static str) { + match what { "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), - }; + } +} + +/// The build's row in the activity stack. +fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { + let (kind, label) = row_of(state.what); let task = s.activity.start(kind, label, Cancel::Flag(state.cancel.clone())); task.progress(0, state.total as u64); task } +/// A build's state and its row, which go together. However the build ends (it finishes, its worker panics, or the +/// worker can't be started) the state reads as finished first, and then the row goes: a build waiting in line starts +/// when the row is gone, and is refused if the state still said a build runs. A build that did not mark itself +/// finished did not end well: it says so, instead of reading as one that built nothing. +struct Running { + state: Arc, + task: TaskGuard, +} + +impl Drop for Running { + fn drop(&mut self) { + if !self.state.finished.load(Ordering::Relaxed) { + self.state + .error + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get_or_insert_with(|| "the build stopped unexpectedly".to_string()); + } + self.state.finished.store(true, Ordering::Relaxed); + } +} + +/// What a build of `ids` was asked, as it runs later (from the line): the photos written out (the selection or the +/// view may have changed by then), in the background (nothing waits for it then), and not queued again. +fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> Request { + let mut params = p.as_object().cloned().unwrap_or_default(); + for key in ["id", "queue", "wait"] { + params.remove(key); + } + params.insert("ids".into(), ids.iter().map(|id| id.0).collect()); + Request { command: command.into(), params: Value::Object(params) } +} + +/// The refusal of a build while another runs, unless the call asks to `queue`. +const REFUSED: &str = "a preview build is already running"; + +fn queue_param(p: &Value) -> bool { + p.get("queue").and_then(Value::as_bool).unwrap_or(false) +} + +fn build_running(s: &Session) -> bool { + s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) +} + +/// A build asked for with `queue`: while one runs (or others already wait) this one waits in line behind them → +/// `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. +fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, request: &Request) -> Option> { + if !build_running(s) && !s.activity.lane_waiting(Lane::Previews) { + return None; + } + if p.get("wait").and_then(Value::as_bool) == Some(true) { + return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); + } + let (kind, label) = row_of(what); + Some(s.activity.enqueue(kind, label, request.clone()).map(|(id, place)| json!({"queued": id, "place": place})).map_err(|e| bad(c, e))) +} + /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. @@ -282,31 +344,34 @@ fn build(s: &mut Session, p: &Value) -> Result { "full" | "1:1" => None, other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))), }; - if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + let queue = queue_param(p); + if !queue && build_running(s) { + return Err(bad(C, REFUSED)); } // explicit ids, else the selection, else everything in view let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; + if queue && let Some(queued) = wait_in_line(s, C, p, "", &request_for(C, p, &ids)) { + return queued; + } let jobs: Vec> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect(); #[cfg(test)] let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() }); #[cfg(not(test))] let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() }); s.preview_build = Some(state.clone()); - let task = task_for(s, &state); + let run = Running { task: task_for(s, &state), state: state.clone() }; let lanes = lanes(jobs.len(), edge.is_none()); let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); if wait { - run_all(jobs, &state, &task, lanes); + run_all(jobs, &run.state, &run.task, lanes); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) - let st = state.clone(); std::thread::Builder::new() .name("lc-build-previews".into()) - .spawn(move || run_all(jobs, &st, &task, lanes)) + .spawn(move || run_all(jobs, &run.state, &run.task, lanes)) .map_err(|e| bad(C, format!("could not start: {e}")))?; } Ok(state.json()) @@ -471,10 +536,15 @@ fn smart(s: &mut Session, p: &Value) -> Result { let dir = s.media.smart_dir.clone().ok_or_else(|| bad(C, "smart previews need a library on disk"))?; let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false); let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); - if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { - return Err(bad(C, "a preview build is already running")); + let queue = background && queue_param(p); + if background && !queue && build_running(s) { + return Err(bad(C, REFUSED)); } let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; + let what = if discard { "discarding smart previews" } else { "smart previews" }; + if queue && let Some(queued) = wait_in_line(s, C, p, what, &request_for(C, p, &ids)) { + return queued; + } let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -487,19 +557,17 @@ fn smart(s: &mut Session, p: &Value) -> Result { } let custom = s.smart_previews_dir.is_some(); if background { - let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); s.preview_build = Some(state.clone()); - let task = task_for(s, &state); - let st = state.clone(); + let run = Running { task: task_for(s, &state), state: state.clone() }; std::thread::Builder::new() .name("lc-smart-previews".into()) .spawn(move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&run.state, &run.task))) { log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + *run.state.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); } - st.finished.store(true, Ordering::Relaxed); + run.state.finished.store(true, Ordering::Relaxed); }) .map_err(|e| bad(C, format!("could not start: {e}")))?; return Ok(state.json()); @@ -640,7 +708,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool, queue?: bool} — build (or discard) the smart previews of the selected photos (else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews). A background one while a preview build runs is refused, or with queue waits in line for it, as library.buildPreviews does → {queued, place}", always, smart ), @@ -667,7 +735,7 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or `edge`) | full (1:1), ids?, wait?: bool} — render the grid thumbnail and loupe view of the selected photos (else all in view) into the preview cache, in the background unless `wait` → {total, done, failed, running}", + "{size?: standard (2048 px, or `edge`) | full (1:1), ids?, wait?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (else all in view) into the preview cache, in the background unless `wait` → {total, done, failed, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs", always, build ), @@ -716,4 +784,38 @@ mod tests { assert_eq!(r["total"], json!(ids.len())); assert_eq!(r["failed"], json!(0)); } + // Given a build whose worker dies (or can't start), the build reads as finished and its row goes, so that a + // build waiting in line starts instead of being refused as "already running" + #[test] + fn a_build_whose_worker_dies_reads_as_finished_before_its_row_goes() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: super::task_for(&s, &state), state: state.clone() }; + assert!(s.activity.lane_busy(crate::activity::Lane::Previews)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _run = run; + panic!("synthetic worker panic"); + })); + assert!(r.is_err()); + assert!(state.finished.load(Ordering::Relaxed)); + assert_eq!(state.error().as_deref(), Some("the build stopped unexpectedly"), "a crash is not a success that built nothing"); + assert!(!s.activity.lane_busy(crate::activity::Lane::Previews)); + } + + // Given a build that marked itself finished, its row going leaves no error + #[test] + fn a_build_that_finished_leaves_no_error() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: super::task_for(&s, &state), state: state.clone() }; + state.finished.store(true, Ordering::Relaxed); + drop(run); + assert!(state.error().is_none()); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..97a366216cc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -321,6 +321,8 @@ pub struct Session { /// Current time provider (ISO 8601); injectable for tests and wasm. pub clock: Box String + Send>, depth: u32, + /// [`Session::start_waiting`] is starting tasks (the commands it runs don't start more themselves). + starting_waiting: bool, /// Selected mask (Masking panel), by mask id. pub active_mask: Option, /// AI masks (SAM 3): the model and the last photo prepared for it. @@ -496,6 +498,7 @@ impl Session { media: media::MediaCache::default(), clock: Box::new(|| "2026-09-30T12:00:00".to_string()), depth: 0, + starting_waiting: false, active_mask: None, segmenter: segment::Segmenter::default(), active_spot: None, @@ -556,6 +559,15 @@ impl Session { /// Run a command by id. THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let r = self.dispatch(id, params, true); + // a task this command freed the lane of starts now, not at the next frame + self.start_waiting(); + r + } + + /// [`Session::execute`] without starting waiting tasks; `journal`: record the call when the command is journaled + /// (not for a task that waited: the call that asked for it is recorded already). + fn dispatch(&mut self, id: &str, params: &Value, journal: bool) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // a command that validates the photos a call names isn't held back by the selection if !(spec.explicit_targets && cmd::names_photos(params)) { @@ -563,13 +575,33 @@ impl Session { } let empty = Value::Object(Default::default()); let params = if params.is_null() { &empty } else { params }; - self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { + self.run_command(id, (journal && spec.journal).then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { // a shared parameter check ([`Session::targets`]) names the command it ran for EngineError::BadParams { cmd, msg } if cmd.is_empty() => EngineError::BadParams { cmd: id.to_string(), msg }, e => e, }) } + /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was + /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each + /// command; the app also calls it every frame, for a lane that frees while nothing is asked. + pub fn start_waiting(&mut self) { + if self.depth > 0 || self.starting_waiting { + return; + } + self.starting_waiting = true; + // (bounded: each turn takes one task out of a line that is at most this long) + for _ in 0..activity::MAX_WAITING { + let Some(w) = self.activity.take_ready() else { break }; + let r = self.dispatch(&w.request.command, &w.request.params, false); + self.activity.started(); + if let Err(e) = r { + log::warn!("{}: a task that waited could not start: {e}", w.request.command); + } + } + self.starting_waiting = false; + } + /// Run `f` as command `id` with what [`Session::execute`] does around every command: the /// panic guard, auto versions, XMP sidecar auto-write and the durable save (a failed save is /// `NotSaved`). Not journaled. The app's import task commits its batches this way. diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b358..edb06b8ea0e 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -475,6 +475,11 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; self.catalog = catalog; + // nor do tasks waiting in line carry over: they name the old library's photos and folders + let dropped = self.activity.library_changed(); + if dropped > 0 { + log::info!("library: {dropped} task(s) waiting in line were dropped with the old library"); + } // (nothing of the list the last library showed is this one's) self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..437cf10fc73 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -46,6 +46,7 @@ mod slide; mod slideshow_export; mod spots; mod sync; +mod task_queue; mod view_follow; pub(super) mod xmp; diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs new file mode 100644 index 00000000000..1eade863445 --- /dev/null +++ b/crates/engine/src/tests/task_queue.rs @@ -0,0 +1,249 @@ +//! Tasks waiting in line for their lane (see `crate::activity`), with the preview builds. +//! +//! Scenarios, in the words of an agent building previews for several shoots: +//! +//! * Build Previews while a build runs: without `queue` it is refused, as it always was. With `queue` it waits +//! behind the build, `activity.list` says it is next, and it builds the photos chosen when it was asked. +//! * It starts by itself when the build ahead of it ends. +//! * `activity.cancel` on it takes it out of the line: it never runs; `all` empties the line. +//! * The line is bounded. +//! * Another library: nothing waits for it. +//! +//! These go through commands and `activity.list` only, so that they describe what a control or MCP client sees. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::activity::{Cancel, MAX_WAITING, TaskGuard}; +use crate::cmd::previews::PreviewBuild; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-task-queue-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A preview build that holds the lane until [`release`]: its row runs, and the build reads as unfinished. +struct Hold { + _row: TaskGuard, + build: Arc, +} + +fn hold(s: &mut Session) -> Hold { + let build = Arc::new(PreviewBuild::default()); + s.preview_build = Some(build.clone()); + Hold { _row: s.activity.start("previews", "Building previews", Cancel::Yes), build } +} + +/// The held build ends as a real one does: finished first, then its row goes. +fn release(h: Hold) { + h.build.finished.store(true, Ordering::Release); + drop(h); +} + +/// Wait (at most a minute) until no task runs or waits. +fn settle(s: &mut Session) { + let t0 = std::time::Instant::now(); + loop { + // any command lets a waiting task whose lane is free start (the app's frame loop does too) + let rows = tasks(s); + if rows.is_empty() { + return; + } + assert!(t0.elapsed().as_secs() < 60, "tasks still listed: {rows:?}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + +fn tasks(s: &mut Session) -> Vec { + s.execute("activity.list", &json!({})).unwrap()["tasks"].as_array().cloned().unwrap_or_default() +} + +fn build_ids(s: &Session, n: usize) -> Vec { + s.catalog.photos().take(n).map(|p| p.id.0).collect() +} + +/// Given a preview build running and two photos chosen, when Build Previews is asked for with `queue`, then it waits +/// behind the build, first in line, with nothing done. When other photos are chosen meanwhile and the build ahead +/// ends, then it starts by itself and builds the two photos chosen when it was asked. +#[test] +fn a_build_asked_for_while_one_runs_waits_behind_it_and_builds_the_photos_chosen_then() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 3); + s.execute("library.select", &json!({"ids": [ids[0], ids[1]]})).unwrap(); + let h = hold(&mut s); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true})).unwrap(); + let id = r["queued"].as_u64().expect("an id while it waits"); + assert_eq!(r["place"], 1); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 2, "the running build, then the waiting one: {rows:?}"); + assert_eq!(rows[1]["id"], id); + assert_eq!((rows[1]["waiting"].as_bool(), rows[1]["place"].as_u64(), rows[1]["lane"].as_str()), (Some(true), Some(1), Some("previews"))); + assert_eq!((rows[1]["done"].as_u64(), rows[1]["total"].as_u64()), (Some(0), Some(0))); + assert_eq!(rows[1]["label"], "Building previews"); + assert_eq!((rows[0]["waiting"].as_bool(), rows[0]["place"].as_u64()), (Some(false), Some(0)), "the running one is not in line"); + s.execute("library.select", &json!({"ids": [ids[2]]})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(2), Some(2)), "{progress}"); + // the journal has the call that asked for it, once: starting it was not a second call + assert_eq!(s.journal.iter().filter(|(c, _)| c == "library.buildPreviews").count(), 1, "{:?}", s.journal); +} + +/// Given a preview build running, when a build is asked for without `queue`, then it is refused as before, and +/// nothing waits. +#[test] +fn a_build_asked_for_while_one_runs_is_refused_unless_it_asks_to_queue() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": false})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is listed"); + release(h); + assert!(tasks(&mut s).is_empty()); +} + +/// Given no build running, when a build is asked for with `queue`, then it starts at once, as one without it does. +#[test] +fn a_build_that_asks_to_queue_starts_at_once_when_nothing_is_ahead_of_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!((r["total"].as_u64(), r["done"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +/// Given a build waiting behind another, when `activity.cancel` is asked for it, then it leaves the line and never +/// runs. +#[test] +fn a_waiting_build_taken_out_of_the_line_never_runs() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + let id = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().unwrap(); + assert_eq!(s.execute("activity.cancel", &json!({"id": id})).unwrap()["cancelled"], 1); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is left"); + assert!(s.execute("activity.cancel", &json!({"id": id})).is_err(), "it is gone: an unknown id"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "no build started after the held one"); +} + +/// Given builds waiting, when every task is cancelled, then the line is empty and the count includes the waiting ones, +/// so that nothing starts as soon as the running build stops. +#[test] +fn cancelling_every_task_empties_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + } + assert_eq!(tasks(&mut s).len(), 3); + assert_eq!(s.execute("activity.cancel", &json!({"all": true})).unwrap()["cancelled"], 3, "the running one and the two waiting"); + assert_eq!(tasks(&mut s).len(), 1, "only the running (stopping) build is listed"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "nothing started after it"); +} + +/// Given a full line, when one more build is asked for, then it is refused and says why; the line is as it was. +#[test] +fn the_line_is_bounded() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + for place in 1..=MAX_WAITING { + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(r["place"].as_u64(), Some(place as u64)); + } + let e = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap_err().to_string(); + assert!(e.contains(&MAX_WAITING.to_string()), "{e}"); + assert_eq!(tasks(&mut s).len(), MAX_WAITING + 1); + s.execute("activity.cancel", &json!({"all": true})).unwrap(); + release(h); +} + +/// Build Smart Previews in the background waits in the same line (one preview build at a time). +#[test] +fn smart_previews_wait_behind_a_preview_build() { + let dir = temp_dir("smart"); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + let ids = build_ids(&s, 2); + let h = hold(&mut s); + let e = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true})).unwrap_err().to_string(); + assert!(e.contains("already running"), "{e}"); + let r = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true, "queue": true})).unwrap(); + assert!(r["queued"].is_u64(), "{r}"); + let rows = tasks(&mut s); + assert_eq!( + (rows[1]["kind"].as_str(), rows[1]["waiting"].as_bool(), rows[1]["lane"].as_str()), + (Some("smartPreviews"), Some(true), Some("previews")) + ); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + // (the demo photos aren't files, so it has nothing to build: that it ran at all is what counts) + assert_eq!(progress["what"], "smart previews", "{progress}"); + assert_eq!(progress["running"], false, "{progress}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two builds waiting, the first of which can't start (here: it was asked for a size no build accepts, as if what it +/// needs went away while it waited): the second still runs. +#[test] +fn a_build_that_can_not_start_does_not_hold_up_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}) }; + s.activity.enqueue("previews", "Building previews", bad).unwrap(); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(1), Some(1)), "{progress}"); +} + +/// `queue` with `wait` while a build runs: the call can't both wait in line and return when the build is done. +#[test] +fn a_build_that_would_wait_for_its_turn_and_its_end_is_refused() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true, "wait": true})).unwrap_err().to_string(); + assert!(e.contains("wait"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1); + release(h); +} + +/// Given a build waiting and one still running, when another library is opened, then nothing waits any more: the +/// build asked for was about the old library's photos. +#[test] +fn another_library_drops_what_waits() { + let dir = temp_dir("switch"); + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(tasks(&mut s).len(), 2); + s.open_library(&dir, false).unwrap(); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 1, "only the old library's running build: {rows:?}"); + assert_eq!(rows[0]["waiting"], false); + release(h); + settle(&mut s); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 6e92091c780..4eafa60c773 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -71,6 +71,8 @@ impl LightcraftApp { tasks::poll(self, ctx); updates_ui::tick(self, ctx); self.preview_build_status(ctx); + // a task waiting in line whose lane freed while nothing was asked starts now (commands start them too) + self.session.start_waiting(); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index caacbc59088..41fa664e93f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -148,7 +148,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "export": {"running": app.export.as_ref().map(crate::export_task::ExportTask::status), "last": app.last_export_result}, "import": app.import.as_ref().map(crate::import::ImportTask::status), "tasks": app.tasks.labels(), - // every long-running task in flight, as the activity stack shows them (`activity.list`) + // every long-running task in flight and every task waiting in line (`activity.list`); the stack draws the running ones "activity": app.session.activity.list(), // commands waiting on a native file dialog shown off the UI thread (`pick`) "fileDialogs": app.pending_picks.iter().map(|p| p.command.clone()).collect::>(), diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index dffdd1c4d33..0aadc198347 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -55,7 +55,8 @@ fn detail_line(t: &TaskInfo) -> String { /// Draw the stack (called every frame, after the panels and dialogs). pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { - let all = app.session.activity.list(); + // (a task waiting in line has nothing to show yet and no progress to draw: agents see it in `activity.list`) + let all: Vec = app.session.activity.list().into_iter().filter(|t| !t.waiting).collect(); if all.is_empty() { app.activity_expanded = false; return; diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 58873a6e2e9..40fd79c1152 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -110,6 +110,9 @@ fn count_text_by_unit() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; assert_eq!(count_text(&t), "3 of 25"); (t.done, t.total, t.unit) = (12 * 1_048_576, 340 * 1_048_576, Unit::Bytes); @@ -534,3 +537,35 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.run("library.compact", json!({})).is_err()); assert!(h.app.ui.toast.is_none()); } + +/// Given a preview build running and another waiting in line behind it, then the stack shows the running build only, +/// and the waiting one starts by itself, in a frame, when the build ahead of it ends. +#[test] +fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let build = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(build.clone()); + let running = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + let queued = h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + let waiting = queued["queued"].as_u64().expect("it waits"); + assert_eq!(h.app.session.activity.list().len(), 2); + wait_visible(&mut h); + assert!(has(&h, &format!("activity:row:{}", running.id()))); + assert!(!has(&h, &format!("activity:row:{waiting}")) && rows(&h) == 1, "a waiting task draws no row"); + // the lane frees with no command asked: the frame loop starts it + build.finished.store(true, Ordering::Release); + drop(running); + let t0 = std::time::Instant::now(); + while h.app.session.activity.list().iter().any(|t| t.id == waiting && t.label == "Building previews") && t0.elapsed() < T { + h.step(); + let started = h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)); + if started { + break; + } + } + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); +} diff --git a/crates/ui-egui/src/tests/progress.rs b/crates/ui-egui/src/tests/progress.rs index 09e9234a0c9..b0c9f6f7d4a 100644 --- a/crates/ui-egui/src/tests/progress.rs +++ b/crates/ui-egui/src/tests/progress.rs @@ -276,6 +276,9 @@ fn an_activity_bar_is_named_after_its_task() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width()); let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 0c9281dfc22..128bd60e3ce 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -49,6 +49,18 @@ guard.detail(&file_name); - **Quiet periodic work** shows no row: the auto-import folder listing runs every few seconds through `tasks::spawn(.., None, ..)`. +## Waiting in line + +Jobs that must not run side by side share a lane (`activity::Lane`; for now only the preview builds: Build Previews and +the background Build / Discard Smart Previews). A call that sets `queue: true` while its lane is busy does not fail: +`Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) +and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after +every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, +`place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out +of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names +belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is +busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged and the next in line goes on. + ## Examples in the code | Job | Where | Shows how to | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 36294c78756..fc0dccf4cc4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -79,7 +79,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list` (including tasks waiting in line, which have no row); the activity stack in the top-left corner shows the running ones, and a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply) | @@ -96,8 +96,8 @@ filmstrip is visible. | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | -| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | | `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` | From 0784cdc30eb7381517096d85f8977561478684b2 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 13:07:52 -0400 Subject: [PATCH 02/55] LR-BEHAV-BG-TASKS: a build replaced by the one waiting behind it is still announced A build that ends is replaced as the current build by the next one, which a waiting build now starts inside whatever command comes after the first ended. If the app had not yet announced the first, its toast, failed count and error were lost. Such a build is now kept (`Session::take_unreported_builds`, at most 16) until the app announces it once, and `PreviewBuild::reported` stops a build that was announced already from being kept. Co-Authored-By: Claude --- crates/engine/src/cmd/previews.rs | 19 ++++++++-- crates/engine/src/lib.rs | 20 +++++++++++ crates/ui-egui/src/app.rs | 53 ++++++++++++++++------------ crates/ui-egui/src/state.rs | 4 --- crates/ui-egui/src/tests/activity.rs | 26 ++++++++++++++ 5 files changed, 94 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 34f13e4cf6b..010c0b10a4a 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -25,6 +25,9 @@ pub struct PreviewBuild { /// Shared with the build's row in the activity stack (its ✕ sets it). pub cancel: Arc, pub finished: AtomicBool, + /// A frontend announced how it ended (the app's toast); one that ended and was not announced is kept when the next + /// build replaces it ([`Session::take_unreported_builds`]). + pub reported: AtomicBool, /// Damaged smart previews rebuilt (Build Smart Previews only). pub repaired: AtomicUsize, /// What is built ("" = previews; "smart previews" — Build Smart Previews runs the same way). @@ -108,6 +111,18 @@ impl Drop for Running { } } +/// Make `state` the session's current build. A build that ended and was not announced yet ([`PreviewBuild::reported`]) +/// is kept for the frontend to announce ([`Session::take_unreported_builds`]), so that starting the next one right +/// after it (as a build waiting in line does) does not lose its result, its failed count or its error. +fn set_current(s: &mut Session, state: Arc) { + if let Some(old) = s.preview_build.replace(state) + && old.finished.load(Ordering::Relaxed) + && !old.reported.load(Ordering::Relaxed) + { + s.keep_unreported_build(old); + } +} + /// What a build of `ids` was asked, as it runs later (from the line): the photos written out (the selection or the /// view may have changed by then), in the background (nothing waits for it then), and not queued again. fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> Request { @@ -358,7 +373,7 @@ fn build(s: &mut Session, p: &Value) -> Result { let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() }); #[cfg(not(test))] let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() }); - s.preview_build = Some(state.clone()); + set_current(s, state.clone()); let run = Running { task: task_for(s, &state), state: state.clone() }; let lanes = lanes(jobs.len(), edge.is_none()); let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); @@ -558,7 +573,7 @@ fn smart(s: &mut Session, p: &Value) -> Result { let custom = s.smart_previews_dir.is_some(); if background { let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); - s.preview_build = Some(state.clone()); + set_current(s, state.clone()); let run = Running { task: task_for(s, &state), state: state.clone() }; std::thread::Builder::new() .name("lc-smart-previews".into()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97a366216cc..6b123df2647 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -391,6 +391,9 @@ pub struct Session { pub slideshow_export: Option>, /// The last (or running) Build Previews. pub preview_build: Option>, + /// Builds that ended and were replaced by the next one before a frontend announced them + /// ([`Session::take_unreported_builds`]). + unreported_builds: Vec>, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). @@ -528,6 +531,7 @@ impl Session { folder_changes: None, activity: Default::default(), preview_build: None, + unreported_builds: Vec::new(), slideshow_export: None, import_defaults: import::ImportDefaults::default(), cache_mb: 0, @@ -582,6 +586,22 @@ impl Session { }) } + /// A build that ended is replaced by the next one before a frontend announced it: keep it (at most 16; the oldest + /// goes first) for [`Session::take_unreported_builds`]. + pub(crate) fn keep_unreported_build(&mut self, build: std::sync::Arc) { + const KEEP: usize = 16; + if self.unreported_builds.len() >= KEEP { + self.unreported_builds.remove(0); + } + self.unreported_builds.push(build); + } + + /// The builds that ended and were replaced before a frontend announced them, oldest first, once. The frontend + /// announces each (and sets its `reported`) like the current build's end. + pub fn take_unreported_builds(&mut self) -> Vec> { + std::mem::take(&mut self.unreported_builds) + } + /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each /// command; the app also calls it every frame, for a lane that frees while nothing is asked. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fa10210f0a3..04a15302cdc 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -361,32 +361,41 @@ impl LightcraftApp { panels::slideshow::tick(self, ctx, now); } - /// Announce the end of a Build Previews run. + /// Announce the end of a Build Previews run, and of those a build waiting in line replaced before it was announced + /// (in one toast, oldest first). A build is announced once: its `reported` flag says so, not where it lives. fn preview_build_status(&mut self, ctx: &egui::Context) { use std::sync::atomic::Ordering; - let Some(b) = self.session.preview_build.clone() else { return }; - let key = std::sync::Arc::as_ptr(&b) as usize; - if b.finished.load(Ordering::Relaxed) { - if self.ui.preview_build_seen != Some((key, true)) { - self.ui.preview_build_seen = Some((key, true)); - let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); - let plural = if done == 1 { "" } else { "s" }; - let mut msg = match (b.error(), b.what) { - (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), - (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), - (None, what) => { - crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) - } - }; - if failed > 0 { - msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); - } - self.toast(ctx, msg); + let mut ended = self.session.take_unreported_builds(); + match self.session.preview_build.clone() { + Some(b) if b.finished.load(Ordering::Relaxed) => ended.push(b), + Some(_) => { + // The activity stack shows the run while it works; poll for the end. + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } - } else { - // The activity stack shows the run while it works; poll for the end. - ctx.request_repaint_after(std::time::Duration::from_millis(250)); + None => {} + } + let msgs: Vec = ended.iter().filter(|b| !b.reported.swap(true, Ordering::Relaxed)).map(|b| Self::build_message(b)).collect(); + if !msgs.is_empty() { + self.toast(ctx, msgs.join("; ")); + } + } + + /// How a finished Build Previews run ended, as the toast words it. + fn build_message(b: &lightcraft_engine::cmd::previews::PreviewBuild) -> String { + use std::sync::atomic::Ordering; + let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); + let plural = if done == 1 { "" } else { "s" }; + let mut msg = match (b.error(), b.what) { + (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), + (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), + (None, what) => { + crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) + } + }; + if failed > 0 { + msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); } + msg } /// Announce when saving the library starts failing (changes then live only in memory and are diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 38b50902c50..6f458169bd7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -33,9 +33,6 @@ pub struct UiState { pub docking_version: u32, #[serde(default = "crate::i18n::default_language")] pub language: crate::i18n::Locale, - /// The Build Previews run last announced (its identity, finished?). - #[serde(skip)] - pub preview_build_seen: Option<(usize, bool)>, /// Saving the library is failing (announced with a toast; the top bar shows a warning until /// a later save succeeds). #[serde(skip)] @@ -361,7 +358,6 @@ impl Default for UiState { docking: None, docking_version: crate::docking::DOCKING_VERSION, language: crate::i18n::default_language(), - preview_build_seen: None, unsaved_seen: false, frame_rate: std::env::var("LIGHTCRAFT_FPS").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")), luminance_map_restore: None, diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 40fd79c1152..1868b8162ce 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -569,3 +569,29 @@ fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { } assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); } + +/// Given a build that ended and a build waiting behind it, when a command starts the waiting one before the frame that +/// announces the first, then the first one's end is still announced, and once. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_still_announced() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + first.done.store(2, Ordering::Relaxed); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + // a command in the same frame, before the app looks at the finished build + h.app.session.execute("activity.list", &json!({})).unwrap(); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build replaced it"); + h.step(); + assert!(first.reported.load(Ordering::Relaxed), "its end was announced"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("Previews ready for 2 photos"), "{toast}"); + assert!(h.app.session.take_unreported_builds().is_empty()); +} From 6dd303f2379a24022dfe0fc16b44c5aa7e8eff4a Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 20:28:19 -0400 Subject: [PATCH 03/55] LR-BEHAV-BG-TASKS: the frame that starts a waiting build looks at it before it ends The tick looked at the run in progress (to poll for its end) before it started the build waiting in line, so a build started by the tick was not polled until something else repainted: with the list closed, or in Full Screen Preview, the end of the build could go unannounced for a while. The tick now starts the waiting build first. --- crates/ui-egui/src/app.rs | 7 +++++++ crates/ui-egui/src/app/frame.rs | 4 +--- crates/ui-egui/src/tests/activity.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 04a15302cdc..9b8b3fcb07f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -361,6 +361,13 @@ impl LightcraftApp { panels::slideshow::tick(self, ctx, now); } + /// A task waiting in line whose lane freed while nothing was asked starts now (commands start them too); then the + /// run in progress is looked at, so that one started here is polled for its end from this frame on. + fn tick_preview_builds(&mut self, ctx: &egui::Context) { + self.session.start_waiting(); + self.preview_build_status(ctx); + } + /// Announce the end of a Build Previews run, and of those a build waiting in line replaced before it was announced /// (in one toast, oldest first). A build is announced once: its `reported` flag says so, not where it lives. fn preview_build_status(&mut self, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 4eafa60c773..0621cb01071 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -70,9 +70,7 @@ impl LightcraftApp { recheck::tick(self); tasks::poll(self, ctx); updates_ui::tick(self, ctx); - self.preview_build_status(ctx); - // a task waiting in line whose lane freed while nothing was asked starts now (commands start them too) - self.session.start_waiting(); + self.tick_preview_builds(ctx); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 1868b8162ce..1ea56f3e500 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -595,3 +595,31 @@ fn a_build_replaced_by_the_one_waiting_behind_it_is_still_announced() { assert!(toast.contains("Previews ready for 2 photos"), "{toast}"); assert!(h.app.session.take_unreported_builds().is_empty()); } + +/// Given a build that ended and a build waiting behind it, when the frame starts the waiting one, then the same frame +/// asks to be drawn again to see how it goes: nothing else repaints an idle window (the list is closed, or Full Screen +/// Preview hides it). +#[test] +fn the_frame_that_starts_a_waiting_build_asks_for_the_next_one() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + let ctx = egui::Context::default(); + // (a few empty passes let the context's own first-frame requests go by) + for _ in 0..4 { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint(), "an idle context asks for nothing"); + h.app.tick_preview_builds(&ctx); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build started"); + assert!(ctx.has_requested_repaint(), "and the frame asked to look at it again"); +} From ccd0a3b6ac7b913d9f7e78aaf61c2f6c2cb23fda Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 23:41:06 -0400 Subject: [PATCH 04/55] LR-BEHAV-BG-TASKS: a build asked for without queue does not go ahead of builds waiting in line Between the end of a build and the next command or frame the line holds builds that no one has started yet, and a build asked for without queue then started ahead of them (they waited behind it). It is refused as while a build runs. Build Previews and background Smart Previews. --- crates/engine/src/cmd/previews.rs | 11 ++++- crates/engine/src/tests/task_queue.rs | 69 +++++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 2 +- 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 010c0b10a4a..44c01678373 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -137,6 +137,11 @@ fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> /// The refusal of a build while another runs, unless the call asks to `queue`. const REFUSED: &str = "a preview build is already running"; +/// Builds wait in line ahead of one asked for now (not counting the line a build is being started from). +fn line_ahead(s: &Session) -> bool { + !s.starting_waiting && s.activity.lane_waiting(Lane::Previews) +} + fn queue_param(p: &Value) -> bool { p.get("queue").and_then(Value::as_bool).unwrap_or(false) } @@ -360,7 +365,9 @@ fn build(s: &mut Session, p: &Value) -> Result { other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))), }; let queue = queue_param(p); - if !queue && build_running(s) { + // (nor ahead of builds already waiting: the line starts them after this command, in the order asked; the build + // `start_waiting` is starting itself is not held back by the line it came out of) + if !queue && (build_running(s) || line_ahead(s)) { return Err(bad(C, REFUSED)); } // explicit ids, else the selection, else everything in view @@ -552,7 +559,7 @@ fn smart(s: &mut Session, p: &Value) -> Result { let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false); let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); let queue = background && queue_param(p); - if background && !queue && build_running(s) { + if background && !queue && (build_running(s) || line_ahead(s)) { return Err(bad(C, REFUSED)); } let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() }; diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs index 1eade863445..939c2d30428 100644 --- a/crates/engine/src/tests/task_queue.rs +++ b/crates/engine/src/tests/task_queue.rs @@ -247,3 +247,72 @@ fn another_library_drops_what_waits() { s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// Given a build that ended and a build waiting behind it, when the next command starts the waiting one before the +/// app announced the first, then the first is kept (once, with its counts) for the frontend to announce, and the +/// new build is the current one. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_kept_until_it_is_announced() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let first = h.build.clone(); + first.done.store(2, Ordering::Relaxed); + first.failed.store(1, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); // the command that ends up starting the waiting build + assert!(s.preview_build.as_ref().is_some_and(|b| !Arc::ptr_eq(b, &first)), "the waiting build is the current one"); + let kept = s.take_unreported_builds(); + assert_eq!(kept.len(), 1); + assert!(Arc::ptr_eq(&kept[0], &first)); + assert_eq!((kept[0].done.load(Ordering::Relaxed), kept[0].failed.load(Ordering::Relaxed)), (2, 1)); + assert!(s.take_unreported_builds().is_empty(), "once"); + settle(&mut s); +} + +/// A build the frontend announced already is not kept when the next one replaces it. +#[test] +fn a_build_that_was_announced_is_not_kept_when_the_next_one_replaces_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + h.build.reported.store(true, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); + assert!(s.take_unreported_builds().is_empty()); + settle(&mut s); +} + +/// Given a build that ended and a build waiting in line behind it that has not been started yet, when Build Previews is +/// asked for without `queue`, then it is refused, as it is while a build runs: it does not start ahead of the one +/// waiting, which the line starts after this command. +#[test] +fn a_build_asked_for_without_queue_does_not_go_ahead_of_one_waiting_in_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + // the build ends, and nothing has started the one waiting yet (no command or frame since) + release(running); + let refused = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256})).unwrap_err().to_string(); + assert!(refused.contains("preview build"), "{refused}"); + settle(&mut s); +} + +/// Given a build running and two builds waiting behind it, when the build ends, then both start in turn, each one when +/// the lane is free (the line is not "ahead" of the build it is starting). +#[test] +fn builds_waiting_in_line_all_start_in_turn() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + } + release(running); + settle(&mut s); + // the held build, and the first of the two, were replaced by the next: three builds ran in all + assert_eq!(s.take_unreported_builds().len(), 2, "both waiting builds started"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 9b8b3fcb07f..108583b7ae2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -363,7 +363,7 @@ impl LightcraftApp { /// A task waiting in line whose lane freed while nothing was asked starts now (commands start them too); then the /// run in progress is looked at, so that one started here is polled for its end from this frame on. - fn tick_preview_builds(&mut self, ctx: &egui::Context) { + pub(crate) fn tick_preview_builds(&mut self, ctx: &egui::Context) { self.session.start_waiting(); self.preview_build_status(ctx); } From 67a5f01565c890c6acef7190af7337cd2ab35ffb Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 27 Oct 2026 14:29:16 -0400 Subject: [PATCH 05/55] LR-BEHAV-BG-TASKS: tests: a started preview build ends before its test returns Co-Authored-By: Claude --- crates/ui-egui/src/tests/activity.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 1ea56f3e500..decbc472915 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -568,6 +568,7 @@ fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { } } assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); } /// Given a build that ended and a build waiting behind it, when a command starts the waiting one before the frame that @@ -594,6 +595,7 @@ fn a_build_replaced_by_the_one_waiting_behind_it_is_still_announced() { let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); assert!(toast.contains("Previews ready for 2 photos"), "{toast}"); assert!(h.app.session.take_unreported_builds().is_empty()); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); } /// Given a build that ended and a build waiting behind it, when the frame starts the waiting one, then the same frame @@ -622,4 +624,5 @@ fn the_frame_that_starts_a_waiting_build_asks_for_the_next_one() { h.app.tick_preview_builds(&ctx); assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build started"); assert!(ctx.has_requested_repaint(), "and the frame asked to look at it again"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); } From ff7a5fef33e71df037a3220d4e2909934a56b88b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 15 Oct 2026 16:46:34 -0400 Subject: [PATCH 06/55] LR-BEHAV-BG-TASKS: imports and Synchronize Folder wait for each other instead of refusing Imports and Synchronize Folder share the library lane (`Lane::Library`, kinds `import` and `sync`): each readies its files against the library as it is when it starts, so one asked for while the other runs now waits in line behind it and starts by itself, and a toast says it was queued. Their requests are the app's (`app:import`, `app:synchronize`); `Activity::take_ready_if` lets the engine pump leave them to `LightcraftApp::start_waiting`. A drop of photos while an import runs is no longer refused for that reason (it waits too); one while a scan runs or a review waits behind a dialog still is. A waiting import plans at its turn (duplicates checked then; a new album is made only once it adds a photo). A waiting Synchronize Folder scans its folder again (`SyncRescan`) and removes or relinks only the missing and moved photos its dialog showed; others are left alone and counted in its end message. It stops untouched, and says so, if another library opens while it scans or if its folder is gone. The dialog's own scan is kind `scan`, so it holds up nothing; Auto Import waits for the whole lane. Co-Authored-By: Claude --- crates/engine/src/activity.rs | 26 ++- crates/engine/src/cmd/activity.rs | 2 +- crates/engine/src/lib.rs | 4 +- crates/ui-egui/locales/cs-formats.json | 4 +- crates/ui-egui/locales/cs.json | 5 +- crates/ui-egui/locales/de-formats.json | 4 +- crates/ui-egui/locales/de.json | 5 +- crates/ui-egui/locales/es-formats.json | 4 +- crates/ui-egui/locales/es.json | 5 +- crates/ui-egui/locales/fi-formats.json | 4 +- crates/ui-egui/locales/fi.json | 5 +- crates/ui-egui/locales/fr-formats.json | 4 +- crates/ui-egui/locales/fr.json | 5 +- crates/ui-egui/locales/id-formats.json | 4 +- crates/ui-egui/locales/id.json | 5 +- crates/ui-egui/locales/it-formats.json | 4 +- crates/ui-egui/locales/it.json | 5 +- crates/ui-egui/locales/ja-formats.json | 4 +- crates/ui-egui/locales/ja.json | 5 +- crates/ui-egui/locales/ka-formats.json | 4 +- crates/ui-egui/locales/ka.json | 5 +- crates/ui-egui/locales/pl-formats.json | 4 +- crates/ui-egui/locales/pl.json | 5 +- crates/ui-egui/locales/pt-br-formats.json | 4 +- crates/ui-egui/locales/pt-br.json | 5 +- crates/ui-egui/locales/ru-formats.json | 4 +- crates/ui-egui/locales/ru.json | 5 +- crates/ui-egui/locales/sv-formats.json | 4 +- crates/ui-egui/locales/sv.json | 5 +- crates/ui-egui/locales/uk-formats.json | 4 +- crates/ui-egui/locales/uk.json | 5 +- crates/ui-egui/locales/vi-formats.json | 4 +- crates/ui-egui/locales/vi.json | 5 +- crates/ui-egui/locales/zh-hans-formats.json | 4 +- crates/ui-egui/locales/zh-hans.json | 5 +- crates/ui-egui/locales/zh-hant-formats.json | 4 +- crates/ui-egui/locales/zh-hant.json | 5 +- crates/ui-egui/src/app.rs | 46 +++- crates/ui-egui/src/app/frame.rs | 11 +- crates/ui-egui/src/app/input.rs | 2 +- crates/ui-egui/src/dialogs/import.rs | 6 +- crates/ui-egui/src/dialogs/import/scan.rs | 46 +++- crates/ui-egui/src/dialogs/import/task.rs | 104 ++++++--- .../src/dialogs/lightroom_destination.rs | 2 +- crates/ui-egui/src/drop_overlay.rs | 2 +- crates/ui-egui/src/headless.rs | 1 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/lightroom_import.rs | 2 +- crates/ui-egui/src/sync.rs | 199 ++++++++++++++++-- crates/ui-egui/src/tests/drop_import.rs | 35 ++- crates/ui-egui/src/tests/sync.rs | 148 +++++++++++-- docs/background-tasks.md | 21 +- docs/control-protocol.md | 4 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 12 ++ 55 files changed, 672 insertions(+), 161 deletions(-) diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index c7b4944ca46..45d0e59e04e 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -31,6 +31,9 @@ pub const MAX_WAITING: usize = 100; pub enum Lane { /// Build Previews and Build / Discard Smart Previews: one preview build at a time (`Session::preview_build`). Previews, + /// Imports and Synchronize Folder: each plans its work against the library as it is when it starts, so two side by + /// side could add the same file twice. Run by the app (the requests' commands are the app's, `app:…`). + Library, } impl Lane { @@ -38,6 +41,7 @@ impl Lane { pub fn of(kind: &str) -> Option { match kind { "previews" | "smartPreviews" => Some(Lane::Previews), + "import" | "sync" => Some(Lane::Library), _ => None, } } @@ -142,7 +146,7 @@ impl Unit { #[serde(rename_all = "camelCase")] pub struct TaskInfo { pub id: u64, - /// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`, + /// A stable id: `import`, `export`, `scan`, `sync`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`, /// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`. pub kind: &'static str, /// English; the frontend translates it. @@ -705,4 +709,24 @@ mod tests { drop(running); assert!(a.take_ready().is_none()); } + + /// The engine starts only the requests it can run; one it can't (an app import) holds its lane for the app, and a + /// later one in that lane never jumps it. Other lanes go on. + #[test] + fn each_frontend_starts_only_what_it_can_run_and_no_task_jumps_its_line() { + let a = Activity::default(); + let app = |p: u64| Request { command: "app:import".into(), params: serde_json::json!({ "n": p }) }; + let engine = |p: u64| Request { command: "library.import".into(), params: serde_json::json!({ "n": p }) }; + let (first, _) = a.enqueue("import", "Importing", app(1)).unwrap(); + let (second, _) = a.enqueue("import", "Importing", engine(2)).unwrap(); + let (previews, _) = a.enqueue("previews", "Building previews", request("library.buildPreviews")).unwrap(); + let engine_runs = |r: &Request| !r.command.starts_with("app:"); + assert_eq!(a.take_ready_if(engine_runs).map(|w| w.id), Some(previews), "the preview lane isn't held up"); + a.started(); + assert!(a.take_ready_if(engine_runs).is_none(), "the second import waits behind the first, which the app runs"); + assert_eq!(a.take_ready_if(|r| r.command.starts_with("app:")).map(|w| w.id), Some(first)); + a.started(); + assert_eq!(a.take_ready_if(engine_runs).map(|w| w.id), Some(second)); + assert_eq!(Lane::of("sync"), Some(Lane::Library)); + } } diff --git a/crates/engine/src/cmd/activity.rs b/crates/engine/src/cmd/activity.rs index 3fa99b488a7..a960c998fbd 100644 --- a/crates/engine/src/cmd/activity.rs +++ b/crates/engine/src/cmd/activity.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Background Tasks", [], None, - "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for a task of their lane (waiting: true, place: 1 = next in its lane, lane: previews; done and total 0); total 0 = not known yet", + "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for their lane (waiting: true, place 1 = next in its lane, lane: previews or library (imports and Synchronize Folder, which the app starts); they start by themselves when the tasks ahead end, keeping their id), in the order they were asked for; total 0 = not known yet", always, |s, _| Ok(json!({"tasks": s.activity.list()})) ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6b123df2647..b663508818d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -605,6 +605,8 @@ impl Session { /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each /// command; the app also calls it every frame, for a lane that frees while nothing is asked. + /// Requests that aren't engine commands (the app's own, `app:…`: an import, a Synchronize Folder) are left to the + /// app, which starts them the same way. pub fn start_waiting(&mut self) { if self.depth > 0 || self.starting_waiting { return; @@ -612,7 +614,7 @@ impl Session { self.starting_waiting = true; // (bounded: each turn takes one task out of a line that is at most this long) for _ in 0..activity::MAX_WAITING { - let Some(w) = self.activity.take_ready() else { break }; + let Some(w) = self.activity.take_ready_if(|r| find_command(&r.command).is_some()) else { break }; let r = self.dispatch(&w.request.command, &w.request.params, false); self.activity.started(); if let Err(e) = r { diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..48806ebd143 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}", "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", + "Queued: it starts after {n} more": "Ve frontě: začne po {n} dalších", + "{n} more missing, left alone: synchronize again to review them": "{n} dalších chybí, ponecháno beze změny: pro kontrolu synchronizujte znovu" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524d..af68f83b201 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -16,7 +16,6 @@ "= exactly": "= přesně", "A blank template keeps the original names.": "Prázdná šablona zachová původní názvy.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Fotografie v tomto zobrazení skrývá filtr: změňte jej nebo jej zrušte (Zobrazení → Zrušit filtry)", - "A folder is already being synchronized": "Již probíhá synchronizace složky", "A folder is being synchronized": "Probíhá synchronizace složky", "A keyword set needs a name": "Sada klíčových slov musí mít název", "A one-time download of about": "Jednorázové stažení přibližně", @@ -2408,5 +2407,7 @@ "Import dropped files without review": "Importovat přetažené soubory bez kontroly", "An import is running": "Import už běží", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", - "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky" + "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "Queued: it starts when the task ahead of it ends": "Ve frontě: začne, až skončí úloha před ní", + "Another library was opened: nothing was done": "Byla otevřena jiná knihovna: nic se neprovedlo" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..b47170de57e 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}", "Added {n} photo{}": "{n} Foto{} hinzugefügt", "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", + "Queued: it starts after {n} more": "In der Warteschlange: startet nach {n} weiteren", + "{n} more missing, left alone: synchronize again to review them": "{n} weitere fehlen und blieben unangetastet: zum Prüfen erneut synchronisieren" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782f..ed644215e58 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2070,7 +2070,6 @@ "Skipped: files that can't be read": "Übersprungen: Dateien, die nicht gelesen werden können", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Dieser Ordner ist nicht vorhanden: Er wurde verschoben oder umbenannt, oder sein Datenträger ist nicht verbunden.", "Relink photos whose file was renamed or moved": "Fotos neu verknüpfen, deren Datei umbenannt oder verschoben wurde", - "A folder is already being synchronized": "Es wird bereits ein Ordner synchronisiert", "Synchronizing…": "Wird synchronisiert…", "Relinked": "Neu verknüpft", "Removed": "Entfernt", @@ -3440,5 +3439,7 @@ "Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren", "An import is running": "Ein Import läuft", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", - "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst" + "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "Queued: it starts when the task ahead of it ends": "In der Warteschlange: startet, wenn die Aufgabe davor endet", + "Another library was opened: nothing was done": "Eine andere Bibliothek wurde geöffnet: es wurde nichts getan" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..cabf7433efa 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "No se pudo leer {name}: {e}", "Added {n} photo{}": "{n} foto{0} añadida{0}", "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", + "Queued: it starts after {n} more": "En cola: empieza tras {n} más", + "{n} more missing, left alone: synchronize again to review them": "Faltan {n} más, sin tocar: sincroniza de nuevo para revisarlas" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff2..03589c0dcc4 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2098,7 +2098,6 @@ "Skipped: files that can't be read": "Omitidos: archivos que no se pueden leer", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Esta carpeta no está: se movió o se le cambió el nombre, o su disco no está conectado.", "Relink photos whose file was renamed or moved": "Volver a vincular fotos cuyo archivo se renombró o movió", - "A folder is already being synchronized": "Ya se está sincronizando una carpeta", "Synchronizing…": "Sincronizando…", "Relinked": "Revinculadas", "Removed": "Quitadas", @@ -2358,5 +2357,7 @@ "Import dropped files without review": "Importar los archivos soltados sin revisión", "An import is running": "Hay una importación en curso", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", - "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos" + "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "Queued: it starts when the task ahead of it ends": "En cola: empieza cuando termine la tarea anterior", + "Another library was opened: nothing was done": "Se abrió otra biblioteca: no se hizo nada" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9f..72f65964852 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -305,5 +305,7 @@ "Drop to import {n} preset{}": "Pudota tuodaksesi esiasetuksia: {n}{:.0}", "Drop to review {n} item{} for import": "Pudota tarkistaaksesi ennen tuontia (kohteita: {n}){:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", - "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", + "Queued: it starts after {n} more": "Jonossa: alkaa {n} muun jälkeen", + "{n} more missing, left alone: synchronize again to review them": "{n} muuta puuttuu ja jätettiin ennalleen: synkronoi uudelleen tarkistaaksesi ne" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a36..f63b4b43cfb 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -21,7 +21,6 @@ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Tumma liuskekivitausta, jossa kunkin kuvan alla valotus, ISO ja polttoväli sekä kamera ja objektiivi.", "A face model uses the GPU only when a check shows it gives the same results faster.": "Kasvomalli käyttää GPU:ta vain, jos tarkistus osoittaa sen antavan samat tulokset nopeammin.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Suodatin piilottaa tämän näkymän kuvat: muuta sitä tai tyhjennä se (Näytä → Tyhjennä suodattimet)", - "A folder is already being synchronized": "Kansio on jo synkronoitumassa", "A folder is being synchronized": "Kansiota synkronoidaan", "A keyword set needs a name": "Avainsanajoukolle täytyy antaa nimi", "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Vaaleanharmaa seinä, valkoinen paspis ja pehmeä varjo; kuvateksti ja luokitus kuvan alla.", @@ -2327,5 +2326,7 @@ "Drop to open the face model": "Pudota avataksesi kasvomallin", "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", - "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta" + "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "Queued: it starts when the task ahead of it ends": "Jonossa: alkaa, kun sen edellä oleva tehtävä päättyy", + "Another library was opened: nothing was done": "Toinen kirjasto avattiin: mitään ei tehty" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..4b3326065b9 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Impossible de lire {name} : {e}", "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", - "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})" + "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", + "Queued: it starts after {n} more": "En file : démarre après {n} autres", + "{n} more missing, left alone: synchronize again to review them": "{n} autres manquantes, laissées telles quelles : synchronisez à nouveau pour les examiner" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda6..27179c32682 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1906,7 +1906,6 @@ "Skipped: files that can't be read": "Ignorés : fichiers illisibles", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Ce dossier est introuvable : il a été déplacé ou renommé, ou son disque n'est pas connecté.", "Relink photos whose file was renamed or moved": "Relier les photos dont le fichier a été renommé ou déplacé", - "A folder is already being synchronized": "Un dossier est déjà en cours de synchronisation", "Synchronizing…": "Synchronisation…", "Relinked": "Reliées", "Removed": "Retirées", @@ -2390,5 +2389,7 @@ "Checking recent libraries": "Vérification des bibliothèques récentes", "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", - "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :" + "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "Queued: it starts when the task ahead of it ends": "En file : démarre à la fin de la tâche précédente", + "Another library was opened: nothing was done": "Une autre bibliothèque a été ouverte : rien n’a été fait" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221e..d42faac7969 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -305,5 +305,7 @@ "Drop to review {n} item{} for import": "Jatuhkan untuk meninjau {n} item sebelum impor{:.0}", "Inside: {names}": "Di dalam: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", - "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", + "Queued: it starts after {n} more": "Dalam antrean: dimulai setelah {n} lagi", + "{n} more missing, left alone: synchronize again to review them": "{n} lagi hilang dan dibiarkan: sinkronkan lagi untuk memeriksanya" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb8..3073c328cbc 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -22,7 +22,6 @@ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Latar abu-abu gelap berisi eksposur, ISO, dan panjang fokus, lalu kamera dan lensa, di bawah setiap foto.", "A face model uses the GPU only when a check shows it gives the same results faster.": "Model wajah hanya menggunakan GPU jika pengujian menunjukkan hasilnya sama tetapi lebih cepat.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Filter menyembunyikan foto di tampilan ini: ubah atau hapus filternya (Tampilan → Hapus filter)", - "A folder is already being synchronized": "Sudah ada folder yang sedang disinkronkan", "A folder is being synchronized": "Folder sedang disinkronkan", "A keyword set needs a name": "Set kata kunci harus diberi nama", "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Dinding abu-abu muda dengan paspartu putih dan bayangan lembut; keterangan dan rating di bawah foto.", @@ -2339,5 +2338,7 @@ "Drop to open the face model": "Jatuhkan untuk membuka model wajah", "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", - "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan" + "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "Queued: it starts when the task ahead of it ends": "Dalam antrean: dimulai saat tugas di depannya selesai", + "Another library was opened: nothing was done": "Pustaka lain dibuka: tidak ada yang dilakukan" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..23650b47c58 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Impossibile leggere {name}: {e}", "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", + "Queued: it starts after {n} more": "In coda: parte dopo altre {n}", + "{n} more missing, left alone: synchronize again to review them": "Ne mancano altre {n}, lasciate com'erano: sincronizza di nuovo per esaminarle" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d15..1f143b04772 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2026,7 +2026,6 @@ "Skipped: files that can't be read": "Saltati: file che non si possono leggere", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Questa cartella non c'è: è stata spostata o rinominata, oppure il suo disco non è collegato.", "Relink photos whose file was renamed or moved": "Ricollega le foto il cui file è stato rinominato o spostato", - "A folder is already being synchronized": "Una cartella è già in sincronizzazione", "Synchronizing…": "Sincronizzazione in corso…", "Relinked": "Ricollegate", "Removed": "Rimosse", @@ -2361,5 +2360,7 @@ "Import dropped files without review": "Importa i file rilasciati senza revisione", "An import is running": "Un'importazione è in corso", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", - "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "Queued: it starts when the task ahead of it ends": "In coda: parte quando finisce l'attività precedente", + "Another library was opened: nothing was done": "È stata aperta un'altra libreria: non è stato fatto nulla" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..15853a927b0 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "{name} を読み取れませんでした: {e}", "Added {n} photo{}": "{n}枚を追加しました{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", - "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", + "Queued: it starts after {n} more": "キューに追加: あと {n} 件の後に開始します", + "{n} more missing, left alone: synchronize again to review them": "ほかに {n} 件が見つからず、そのままにしました: 確認するにはもう一度同期してください" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd7..f954190daeb 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1918,7 +1918,6 @@ "Skipped: files that can't be read": "スキップ: 読み込めないファイル", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "このフォルダが見つかりません。移動または名前の変更がされたか、ディスクが接続されていません。", "Relink photos whose file was renamed or moved": "ファイル名の変更や移動があった写真をリンクし直す", - "A folder is already being synchronized": "すでにフォルダを同期中です", "Synchronizing…": "同期中…", "Relinked": "リンクし直し", "Removed": "除去", @@ -2356,5 +2355,7 @@ "Import dropped files without review": "ドロップしたファイルを確認せずに読み込む", "An import is running": "読み込み中です", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", - "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください" + "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "Queued: it starts when the task ahead of it ends": "キューに追加: 前のタスクが終わると開始します", + "Another library was opened: nothing was done": "別のライブラリが開かれました: 何も行われていません" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..73ddac481ae 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "ვერ წაიკითხა {name}: {e}", "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", + "Queued: it starts after {n} more": "რიგშია: დაიწყება კიდევ {n}-ის შემდეგ", + "{n} more missing, left alone: synchronize again to review them": "კიდევ {n} აკლია და ხელუხლებლად დარჩა: გადასახედად ხელახლა მოახდინეთ სინქრონიზაცია" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c40770018..4db6010bd24 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -63,7 +63,6 @@ "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "ცვლილება, რომლის დისკზე შენახვაც ვერ ხერხდება (სავსე ან გამორთული დისკი), აღარ რჩება შეუმჩნეველი: ბრძანება იტყობინება", "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "ფანჯარაზე მაღალი დიალოგი აღარ გადის მის საზღვრებს გარეთ (ხარვეზი #781): 1366×768 ეკრანზე ექსპორტის დიალოგის სათაური", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "ფილტრი მალავს ამ ხედის ფოტოებს: შეცვალეთ ან გაასუფთავეთ იგი (ხედი → ფილტრების გასუფთავება)", - "A folder is already being synchronized": "საქაღალდე უკვე სინქრონიზდება", "A folder is being synchronized": "საქაღალდე სინქრონიზდება", "A keyword set needs a name": "საკვანძო სიტყვების ნაკრებს სახელი სჭირდება", "A label follows its folder when it is renamed or moved in LightCraft, together with the labels of the folders": "იარლიყი თავის საქაღალდეს მიჰყვება, როცა ის LightCraft-ში გადაერქმევა ან გადაიტანება, მასში მყოფი საქაღალდეების", @@ -2734,5 +2733,7 @@ "Import dropped files without review": "ჩაგდებული ფაილების იმპორტი გადახედვის გარეშე", "An import is running": "იმპორტი მიმდინარეობს", "An import is running. Drop photos when it has finished": "იმპორტი მიმდინარეობს. ფოტოები ჩააგდეთ, როცა დასრულდება", - "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი" + "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი", + "Queued: it starts when the task ahead of it ends": "რიგშია: დაიწყება, როცა წინა ამოცანა დასრულდება", + "Another library was opened: nothing was done": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..b7fe22f5cb7 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -305,5 +305,7 @@ "Added {n} photo{}": "Dodano zdjęcia: {n}{:.0}", "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", + "Queued: it starts after {n} more": "W kolejce: rozpocznie się po {n} kolejnych", + "{n} more missing, left alone: synchronize again to review them": "Brakuje jeszcze {n}, pozostawiono bez zmian: zsynchronizuj ponownie, aby je przejrzeć" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62ad..ad13a39be9b 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1858,7 +1858,6 @@ "Skipped: files that can't be read": "Pominięto: pliki, których nie można odczytać", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Ten folder nie istnieje: przeniesiono go, zmieniono nazwę albo odłączono dysk.", "Relink photos whose file was renamed or moved": "Połącz ponownie zdjęcia, których pliki przeniesiono lub przemianowano", - "A folder is already being synchronized": "Trwa już synchronizacja folderu", "Synchronizing…": "Synchronizowanie…", "Relinked": "Połączono ponownie", "Removed": "Usunięto", @@ -2283,5 +2282,7 @@ "Import dropped files without review": "Importuj upuszczone pliki bez przeglądu", "An import is running": "Import jest w toku", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", - "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia" + "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "Queued: it starts when the task ahead of it ends": "W kolejce: rozpocznie się po zakończeniu poprzedniego zadania", + "Another library was opened: nothing was done": "Otwarto inną bibliotekę: nic nie zrobiono" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..25c8a28b770 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Não foi possível ler {name}: {e}", "Added {n} photo{}": "{n} foto{0} adicionada{0}", "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", + "Queued: it starts after {n} more": "Na fila: começa depois de mais {n}", + "{n} more missing, left alone: synchronize again to review them": "Faltam mais {n}, deixadas como estavam: sincronize de novo para revisá-las" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b7..222fd260f62 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1916,7 +1916,6 @@ "Skipped: files that can't be read": "Ignorados: arquivos que não podem ser lidos", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Esta pasta não está lá: foi movida ou renomeada, ou o disco dela não está conectado.", "Relink photos whose file was renamed or moved": "Vincular de novo fotos cujo arquivo foi renomeado ou movido", - "A folder is already being synchronized": "Uma pasta já está sendo sincronizada", "Synchronizing…": "Sincronizando…", "Relinked": "Revinculadas", "Removed": "Removidas", @@ -2202,5 +2201,7 @@ "Import dropped files without review": "Importar arquivos soltos sem revisão", "An import is running": "Uma importação está em andamento", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", - "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos" + "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "Queued: it starts when the task ahead of it ends": "Na fila: começa quando a tarefa anterior terminar", + "Another library was opened: nothing was done": "Outra biblioteca foi aberta: nada foi feito" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..df0cff8badc 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Не удалось прочитать {name}: {e}", "Added {n} photo{}": "Добавлено фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", + "Queued: it starts after {n} more": "В очереди: начнётся после ещё {n}", + "{n} more missing, left alone: synchronize again to review them": "Не хватает ещё {n}, оставлены как есть: синхронизируйте снова, чтобы их просмотреть" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df045..fe8bfda9e90 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1628,7 +1628,6 @@ "Skipped: files that can't be read": "Пропущено: файлы, которые не удаётся прочитать", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Этой папки нет: её переместили или переименовали, либо её диск не подключён.", "Relink photos whose file was renamed or moved": "Повторно связать фото, файл которых переименован или перемещён", - "A folder is already being synchronized": "Папка уже синхронизируется", "Synchronizing…": "Синхронизация…", "Imported": "Импортированные", "Relinked": "Связано повторно", @@ -2349,5 +2348,7 @@ "Import dropped files without review": "Импортировать перетащенные файлы без проверки", "An import is running": "Импорт уже выполняется", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", - "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото" + "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "Queued: it starts when the task ahead of it ends": "В очереди: начнётся, когда закончится задача перед ней", + "Another library was opened: nothing was done": "Открыта другая библиотека: ничего не сделано" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c4..3493eda8222 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -305,5 +305,7 @@ "Drop to review {n} item{} for import": "Släpp för att granska {n} objekt före import{:.0}", "Inside: {names}": "Inuti: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", - "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", + "Queued: it starts after {n} more": "I kö: startar efter {n} till", + "{n} more missing, left alone: synchronize again to review them": "{n} fler saknas och lämnades orörda: synkronisera igen för att granska dem" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5d..76983ad20f6 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -32,7 +32,6 @@ "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "En ändring som inte kan sparas till disk (full eller urkopplad enhet) är inte längre tyst: kommandot rapporterar", "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "En mörk skifferbakgrund med exponering, ISO och brännvidd, sedan kamera och objektiv, under varje foto.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Ett filter döljer den här vyns foton: ändra det eller rensa det (Visa → Rensa filter)", - "A folder is already being synchronized": "En mapp synkroniseras redan", "A folder is being synchronized": "En mapp synkroniseras", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "en full enhet) räknas inte längre som byggd och Bygg smarta förhandsgranskningar ersätter den.", "A keyword set needs a name": "En nyckelordsuppsättning behöver ett namn", @@ -2429,5 +2428,7 @@ "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", - "Import dropped files without review": "Importera släppta filer utan granskning" + "Import dropped files without review": "Importera släppta filer utan granskning", + "Queued: it starts when the task ahead of it ends": "I kö: startar när uppgiften före är klar", + "Another library was opened: nothing was done": "Ett annat bibliotek öppnades: ingenting gjordes" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..209fdd16b83 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "Не вдалося прочитати {name}: {e}", "Added {n} photo{}": "Додано фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", + "Queued: it starts after {n} more": "У черзі: почнеться після ще {n}", + "{n} more missing, left alone: synchronize again to review them": "Бракує ще {n}, залишено як є: синхронізуйте знову, щоб їх переглянути" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe0..1f0a5f99f44 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2100,7 +2100,6 @@ "Skipped: files that can't be read": "Пропущено: файли, які не вдається прочитати", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "Цієї теки немає: її переміщено чи перейменовано, або її диск не під’єднано.", "Relink photos whose file was renamed or moved": "Перезв’язати фото, файл яких перейменовано чи переміщено", - "A folder is already being synchronized": "Тека вже синхронізується", "Synchronizing…": "Синхронізація…", "Relinked": "Перезв’язано", "Removed": "Прибрано", @@ -2354,5 +2353,7 @@ "Import dropped files without review": "Імпортувати перетягнуті файли без перегляду", "An import is running": "Імпорт уже виконується", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", - "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото" + "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "Queued: it starts when the task ahead of it ends": "У черзі: почнеться, коли завершиться попереднє завдання", + "Another library was opened: nothing was done": "Відкрито іншу бібліотеку: нічого не зроблено" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff060..ad050727993 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -305,5 +305,7 @@ "Drop to import {n} preset{}": "Thả để nhập {n} thiết lập sẵn{:.0}", "Drop to review {n} item{} for import": "Thả để xem lại {n} mục trước khi nhập{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", - "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", + "Queued: it starts after {n} more": "Trong hàng đợi: bắt đầu sau {n} tác vụ nữa", + "{n} more missing, left alone: synchronize again to review them": "Còn {n} mục bị thiếu được giữ nguyên: hãy đồng bộ hóa lại để xem xét" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81c..c71b2e3d5bd 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -26,7 +26,6 @@ "A blank template keeps the original names.": "Mẫu trống giữ tên gốc.", "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "Thay đổi không thể lưu ra đĩa (đĩa đầy hoặc đã rút) không còn im lặng: lệnh báo", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Bộ lọc đang ẩn ảnh trong chế độ xem này: đổi bộ lọc hoặc xóa (Xem → Xóa bộ lọc)", - "A folder is already being synchronized": "Một thư mục đang được đồng bộ", "A folder is being synchronized": "Một thư mục đang được đồng bộ", "A keyword set needs a name": "Bộ từ khóa cần một tên", "A library is open in one program at a time (issue #99): opening a library that LightCraft or `lightcraft-cli` already": "Một thư viện chỉ mở trong một chương trình tại một thời điểm (issue #99): mở thư viện mà LightCraft hoặc `lightcraft-cli` đã", @@ -2235,5 +2234,7 @@ "Drop to open the face model": "Thả để mở mô hình khuôn mặt", "Dropped Files": "Tệp đã thả", "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", - "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại" + "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", + "Queued: it starts when the task ahead of it ends": "Trong hàng đợi: bắt đầu khi tác vụ trước nó kết thúc", + "Another library was opened: nothing was done": "Đã mở thư viện khác: không có gì được thực hiện" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..f16499d8b53 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "无法读取 {name}:{e}", "Added {n} photo{}": "已添加 {n} 张照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", - "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", + "Queued: it starts after {n} more": "已加入队列:再过 {n} 个后开始", + "{n} more missing, left alone: synchronize again to review them": "还有 {n} 个缺失,未作处理:再次同步以检查它们" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a6251..e13758890f6 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1910,7 +1910,6 @@ "Skipped: files that can't be read": "已跳过:无法读取的文件", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "此文件夹不存在:它已被移动或重命名,或其磁盘未连接。", "Relink photos whose file was renamed or moved": "重新链接文件被重命名或移动的照片", - "A folder is already being synchronized": "已有文件夹正在同步", "Synchronizing…": "正在同步…", "Relinked": "已重新链接", "Removed": "已移除", @@ -2200,5 +2199,7 @@ "Import dropped files without review": "不经检查直接导入拖入的文件", "An import is running": "正在导入", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", - "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入" + "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "Queued: it starts when the task ahead of it ends": "已加入队列:前一个任务结束后开始", + "Another library was opened: nothing was done": "已打开另一个图库:未执行任何操作" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..5230ccec2ae 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -305,5 +305,7 @@ "Could not read {name}: {e}": "無法讀取 {name}:{e}", "Added {n} photo{}": "已加入 {n} 張照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", - "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", + "Queued: it starts after {n} more": "已加入佇列:再過 {n} 個後開始", + "{n} more missing, left alone: synchronize again to review them": "還有 {n} 個遺失,未作處理:再次同步以檢查它們" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec87..692f9c55919 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1916,7 +1916,6 @@ "Skipped: files that can't be read": "已略過:無法讀取的檔案", "This folder isn't there: it was moved or renamed, or its disk isn't connected.": "此資料夾不存在:它已被移動或重新命名,或其磁碟未連接。", "Relink photos whose file was renamed or moved": "重新連結檔案被重新命名或移動的照片", - "A folder is already being synchronized": "已有資料夾正在同步", "Synchronizing…": "正在同步…", "Relinked": "已重新連結", "Removed": "已移除", @@ -2157,5 +2156,7 @@ "Import dropped files without review": "不經檢查直接匯入拖放的檔案", "An import is running": "正在匯入", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", - "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入" + "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "Queued: it starts when the task ahead of it ends": "已加入佇列:前一個工作結束後開始", + "Another library was opened: nothing was done": "已開啟另一個圖庫:未執行任何操作" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 108583b7ae2..16060c29cb9 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -105,6 +105,7 @@ impl LightcraftApp { sync: None, sync_owns_changes: false, sync_run: None, + sync_queued: None, lightroom: None, lightroom_last: None, lightroom_result: None, @@ -286,6 +287,49 @@ impl LightcraftApp { r } + /// Say that a task waits in line at `place` of its lane: without it, asking for it seems to do nothing. + pub(crate) fn queued_toast(&mut self, place: u64) { + // (counted as its row counts: the waiting tasks ahead of it, after the running one) + let text = if place <= 1 { + i18n::tr("Queued: it starts when the task ahead of it ends").to_string() + } else { + i18n::tr_format!("Queued: it starts after {n} more", n = place - 1) + }; + let now = self.tick_now(); + self.ui.toast = Some((text, now + TOAST_SECONDS, None)); + } + + /// Start the tasks waiting in line whose lane is free: the engine's ([`lightcraft_engine::Session::start_waiting`]) + /// and the app's own (`app:import`, `app:synchronize`), each the way it was asked. One that can't start says why + /// in a toast; the next in line goes on. + fn start_waiting(&mut self, ctx: &egui::Context) { + self.session.start_waiting(); + // The app's own wait while its slots are taken, row or no row yet: an import set this frame (Auto Import, its + // row comes at the next tick), a synchronize, or a Local folder being read (it becomes an import when read). + let held = self.lightroom.is_some() + || self.import.is_some() + || self.sync_run.is_some() + || self.sync_queued.is_some() + || self.scan.as_ref().is_some_and(|t| t.browse); + if held { + return; + } + // (bounded: each turn takes one task out of a line that is at most this long) + for _ in 0..lightcraft_engine::activity::MAX_WAITING { + let Some(w) = self.session.activity.take_ready_if(|r| r.command.starts_with("app:")) else { break }; + let r = match w.request.command.as_str() { + import::IMPORT_REQUEST => import::start_request(self, ctx, &w.request), + sync::SYNC_REQUEST => sync::start_request(self, ctx, &w.request), + other => Err(format!("unknown request {other}")), + }; + self.session.activity.started(); + if let Err(e) = r { + log::warn!("{}: a task that waited could not start: {e}", w.request.command); + self.toast_error(ctx, e); + } + } + } + /// The remembered ratio belongs to the tool until the user starts editing the crop. pub(crate) fn crop_tool_aspect(&self) -> Option<(u32, u32)> { let photo = self.session.active()?; @@ -364,7 +408,7 @@ impl LightcraftApp { /// A task waiting in line whose lane freed while nothing was asked starts now (commands start them too); then the /// run in progress is looked at, so that one started here is polled for its end from this frame on. pub(crate) fn tick_preview_builds(&mut self, ctx: &egui::Context) { - self.session.start_waiting(); + self.start_waiting(ctx); self.preview_build_status(ctx); } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 0621cb01071..04874c8cc6a 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -59,6 +59,7 @@ impl LightcraftApp { merge::poll(self, ctx); import::poll_scan(self, ctx); sync::poll(self, ctx); + sync::poll_rescan(self, ctx); sync::poll_run(self, ctx); // Import commits batches and must not run twice in one host frame. The first layout pass // and a hidden logic tick both report pass index 0; a second pass reports 1. A wall-clock @@ -84,12 +85,8 @@ impl LightcraftApp { #[cfg(not(target_arch = "wasm32"))] if let Some(folder) = self.session.import_defaults.auto_folder.clone() { const LABEL: &str = "Auto Import"; - if now - self.ui.auto_import_at >= 3.0 - && self.import.is_none() - && self.sync_run.is_none() - && self.lightroom.is_none() - && !self.tasks.is_running(LABEL) - { + // (it waits for the whole library lane: what runs, rescans or waits there goes first) + if now - self.ui.auto_import_at >= 3.0 && !import::library_busy(self) && self.lightroom.is_none() && !self.tasks.is_running(LABEL) { self.ui.auto_import_at = now; let work = move || lightcraft_engine::cmd::library::list_auto_import_folder(&folder); let done = |app: &mut LightcraftApp, _ctx: &egui::Context, listing: Result, String>| { @@ -99,7 +96,7 @@ impl LightcraftApp { }; let p = serde_json::json!({"listing": listing, "start": false}); let Ok(r) = app.session.execute("library.autoImportScan", &p) else { return }; - let Some(mut params) = r.get("import").cloned().filter(|_| app.import.is_none()) else { return }; + let Some(mut params) = r.get("import").cloned().filter(|_| !import::library_busy(app)) else { return }; let paths: Vec = params["paths"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect(); if let Some(o) = params.as_object_mut() { diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 35b7991b485..ed9ffde9108 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -97,7 +97,7 @@ impl LightcraftApp { self.toast(ctx, crate::i18n::tr("Finish Lightroom catalog import before adding photos")); return; } - if import::running(self) { + if import::drop_blocked(self) { self.toast(ctx, crate::i18n::tr("An import is running")); return; } diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 8425c3ec965..bfddcc35503 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -9,6 +9,7 @@ //! one undo step. use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; +use lightcraft_engine::activity::{Lane, Request}; use lightcraft_engine::import::{ ImportCandidate, ImportUprightMode, ImportWarning, ImportWarningCode, ScanInput, ScanOutput, ScanProgress, scan_with, }; @@ -32,13 +33,14 @@ pub(crate) use body::grid_height; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, note_dialog_bottom}; +pub(crate) use scan::library_busy; +pub use scan::{IMPORT_REQUEST, ScanTask, browse, drop_blocked, open, poll_scan, running}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; -pub use scan::{ScanTask, browse, open, poll_scan, running}; #[cfg(test)] pub(crate) use scan::{stall_scan, stall_scan_of}; pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; -pub use task::{ImportTask, start, start_paths, tick}; +pub use task::{ImportTask, start, start_paths, start_request, tick}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 67b1fa176b2..43edb41ae91 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -1,5 +1,5 @@ use super::task::ImportTask; -use super::{ImportDialog, LightcraftApp, Ordering, ScanInput, ScanOutput, ScanProgress, Value, json, scan_with}; +use super::{ImportDialog, Lane, LightcraftApp, Ordering, Request, ScanInput, ScanOutput, ScanProgress, Value, json, scan_with}; /// A folder scan running on a worker thread (a network share can take minutes to read; the /// window must keep answering meanwhile). @@ -11,7 +11,7 @@ pub struct ScanTask { /// Open the review with this album chosen (an album's context menu ▸ Import…). pub album: Option, /// Browsing a folder (Local): the photos are read in place instead of opening the review. - pub(super) browse: bool, + pub(crate) browse: bool, /// What is being scanned (the review's source). sources: Vec, /// The scan's row in the activity stack (its ✕ and `activity.cancel` set `progress.cancel`). @@ -24,10 +24,31 @@ fn scan_guard(app: &LightcraftApp, progress: &ScanProgress, browse: bool) -> lig app.session.activity.start("scan", label, lightcraft_engine::activity::Cancel::Flag(progress.cancel.clone())) } -/// An import and a Synchronize Folder never run at once: each readies its files against the -/// library as it was when it started, so both could add the same file. -pub(crate) fn busy_synchronizing(app: &LightcraftApp) -> Result<(), String> { - if app.sync_run.is_some() { Err(crate::i18n::tr("A folder is being synchronized").to_string()) } else { Ok(()) } +/// The command of an import's request ([`Request`]): the app runs it ([`start_request`]), with its files and its +/// `library.import` params. +pub const IMPORT_REQUEST: &str = "app:import"; + +fn import_request(paths: &[String], params: &Value) -> Request { + Request { command: IMPORT_REQUEST.into(), params: json!({"paths": paths, "params": params}) } +} + +/// The library lane is taken: an import (or the reading of a Local folder) or a Synchronize Folder runs, or waits +/// to. Each readies its files against the library as it is when it starts, so two side by side could add the same +/// file: one asked for now waits in line ([`Lane::Library`]). +pub(crate) fn library_busy(app: &LightcraftApp) -> bool { + app.import.is_some() + || app.scan.as_ref().is_some_and(|t| t.browse) + || app.sync_run.is_some() + || app.sync_queued.is_some() + || app.session.activity.lane_busy(Lane::Library) + || app.session.activity.lane_waiting(Lane::Library) +} + +/// Put an import of `paths` with `params` in line behind what runs in the library lane, and say so. +pub(super) fn wait_in_line(app: &mut LightcraftApp, paths: &[String], params: &Value) -> Result { + let (id, place) = app.session.activity.enqueue("import", "Importing", import_request(paths, params))?; + app.queued_toast(place as u64); + Ok(json!({"queued": id, "place": place})) } /// Settings → Import → "Show the import review when a camera or card is connected", called with @@ -254,13 +275,20 @@ pub(crate) fn stall_scan_of(app: &mut LightcraftApp, browse: bool) -> Box bool { app.import.is_some() || app.scan.is_some() || app.review_pending.is_some() } +/// Whether any scan (the review's, or a Local folder browse) is running, or a finished scan's review waits for a +/// dialog to close, which a drop of photos must not replace: `open` refuses while a scan runs, and a browse that +/// finishes replaces `app.import`. A drop while an import runs is not refused: it waits in line ([`library_busy`]). +pub fn drop_blocked(app: &LightcraftApp) -> bool { + app.scan.is_some() || app.review_pending.is_some() +} + impl ScanTask { /// `{done, total}` for `ui.inspect` (total is 0 while the folders are still being listed). pub fn status(&self) -> Value { diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index e1f506d5b46..a66dfe9cd08 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -1,5 +1,7 @@ -use super::scan::{busy_synchronizing, running}; -use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json}; +use super::scan::wait_in_line; +use super::{ + ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Request, Value, drop_blocked, json, library_busy, +}; /// Files per batch in the browser build (each batch joins the catalog as it is ready, so the /// progress window updates); the desktop's worker uses [`lightcraft_engine::import::batch_size`]. @@ -193,15 +195,14 @@ impl ImportRun { } } -/// Start importing the dialog's checked files (the dialog's OK / `ui.dialog.confirm`). Refused while another -/// import runs: replacing `app.import` would stop its worker. +/// Start importing the dialog's checked files (the dialog's OK / `ui.dialog.confirm`). While the library lane is +/// taken (an import or a Synchronize Folder runs) it waits in line, and plans its work when its turn comes. pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result { - busy_synchronizing(app)?; if !d.in_library(app) { return Err("another library was opened since the photos were scanned: nothing was imported".into()); } // a browse scan that finishes starts its own import, replacing this one - if app.import.is_some() || app.scan.as_ref().is_some_and(|t| t.browse) { + if app.scan.as_ref().is_some_and(|t| t.browse) { return Err(crate::i18n::tr("An import is running").to_string()); } let queue = d.selected_paths(); @@ -209,9 +210,13 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result return Err("no photos selected".into()); } let undo0 = app.session.undo.len(); + let waits = library_busy(app); let mut album = d.album; - if album.is_none() && !d.new_album.trim().is_empty() { - let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?; + let new_album = d.new_album.trim(); + // (one that waits names its new album instead: it is made once the import adds a photo, so a waiting import taken + // out of the line leaves no empty album behind) + if album.is_none() && !new_album.is_empty() && !waits { + let r = app.session.execute("album.create", &json!({"name": new_album})).map_err(|e| e.to_string())?; album = r["id"].as_u64(); } let mode = match (d.copy, d.move_files) { @@ -225,6 +230,8 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result } if let Some(a) = album { params["album"] = json!(a); + } else if waits && !new_album.is_empty() { + params["albumName"] = json!(new_album); } if !d.preset.is_empty() { params["preset"] = json!(d.preset); @@ -247,50 +254,77 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result params["dng"] = json!(true); } } + // the review's thumbnails are done with, whether it runs now or later + app.renderer.forget_imports(); + if waits { + return wait_in_line(app, &queue, ¶ms); + } let total = queue.len(); app.import = Some(ImportTask::new(queue, params, undo0, false)); - app.renderer.forget_imports(); Ok(json!({"importing": total})) } -/// Start importing `paths` (files or folders) in the background, e.g. dropped on the window. +/// Start importing `paths` (files or folders) in the background, e.g. dropped on the window; in line, like +/// [`start`], while the library lane is taken. pub fn start_paths(app: &mut LightcraftApp, paths: Vec) -> Result { - busy_synchronizing(app)?; - if running(app) { + if drop_blocked(app) { return Err(crate::i18n::tr("An import is running").to_string()); } + let params = json!({"mode": "add"}); + if library_busy(app) { + return wait_in_line(app, &paths, ¶ms); + } let undo0 = app.session.undo.len(); let total = paths.len(); - app.import = Some(ImportTask::new(paths, json!({"mode": "add"}), undo0, false)); + app.import = Some(ImportTask::new(paths, params, undo0, false)); Ok(json!({"importing": total})) } +/// Start an import that waited in line (`request`, made by [`import_request`]): it plans its work now, against the +/// library as it is, under the id it had while it waited. +pub fn start_request(app: &mut LightcraftApp, ctx: &egui::Context, request: &Request) -> Result<(), String> { + let paths: Vec = + request.params["paths"].as_array().map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()).unwrap_or_default(); + if paths.is_empty() { + return Err("no files to import".into()); + } + if app.import.is_some() { + return Err("an import is running".into()); + } + let undo0 = app.session.undo.len(); + let mut task = ImportTask::new(paths, request.params["params"].clone(), undo0, false); + begin(app, ctx, &mut task)?; + app.import = Some(task); + Ok(()) +} + +/// Plan the import against the library as it is and start its worker, under a row in the activity stack. +fn begin(app: &mut LightcraftApp, ctx: &egui::Context, task: &mut ImportTask) -> Result<(), String> { + let mut p = task.params.clone(); + p["paths"] = json!(task.queue); + let (job, album, name) = lightcraft_engine::cmd::library::import_params(&app.session, &p) + .and_then(|req| Ok((lightcraft_engine::import::ImportJob::new(&mut app.session, req.opts)?, req.album, req.album_name))) + .map_err(|e| e.to_string())?; + let run = ImportRun::start(job, std::mem::take(&mut task.queue), album, name, ctx)?; + if task.auto { + task.keep_selection = Some(app.session.selection.clone()); + } + let label = if task.browse { "Reading folder" } else { "Importing" }; + task.guard = Some(app.session.activity.start("import", label, lightcraft_engine::activity::Cancel::Flag(run.cancel.clone()))); + task.run = Some(run); + Ok(()) +} + /// Advance the import in progress (called every frame): start its worker, then add the batches it /// has readied to the catalog. pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(mut task) = app.import.take() else { return }; - if task.run.is_none() { - let mut p = task.params.clone(); - p["paths"] = json!(task.queue); - let started = lightcraft_engine::cmd::library::import_params(&app.session, &p) - .and_then(|req| Ok((lightcraft_engine::import::ImportJob::new(&mut app.session, req.opts)?, req.album, req.album_name))) - .map_err(|e| e.to_string()) - .and_then(|(job, album, name)| ImportRun::start(job, std::mem::take(&mut task.queue), album, name, ctx)); - if task.auto { - task.keep_selection = Some(app.session.selection.clone()); - } - match started { - Ok(run) => { - let label = if task.browse { "Reading folder" } else { "Importing" }; - task.guard = Some(app.session.activity.start("import", label, lightcraft_engine::activity::Cancel::Flag(run.cancel.clone()))); - task.run = Some(run); - } - Err(e) => { - log::warn!("import: {e}"); - app.toast(ctx, crate::i18n::tr_format!("Import failed: {e}", e = e)); - return; - } - } + if task.run.is_none() + && let Err(e) = begin(app, ctx, &mut task) + { + log::warn!("import: {e}"); + app.toast(ctx, crate::i18n::tr_format!("Import failed: {e}", e = e)); + return; } ctx.request_repaint_after(std::time::Duration::from_millis(100)); let Some(run) = task.run.as_mut() else { return }; diff --git a/crates/ui-egui/src/dialogs/lightroom_destination.rs b/crates/ui-egui/src/dialogs/lightroom_destination.rs index 5fd781cfdd8..7009b0b76a6 100644 --- a/crates/ui-egui/src/dialogs/lightroom_destination.rs +++ b/crates/ui-egui/src/dialogs/lightroom_destination.rs @@ -115,7 +115,7 @@ fn busy(app: &LightcraftApp) -> Result<(), String> { if crate::lightroom_import::is_running(app) { return Err("a Lightroom catalog task is already running; wait for it to finish".into()); } - if app.import.is_some() || app.scan.is_some() { + if app.import.is_some() || app.scan.is_some() || crate::import::library_busy(app) { return Err("an import is running; wait for it to finish before importing a Lightroom catalog".into()); } Ok(()) diff --git a/crates/ui-egui/src/drop_overlay.rs b/crates/ui-egui/src/drop_overlay.rs index dfe8262c8c0..d2ac40229aa 100644 --- a/crates/ui-egui/src/drop_overlay.rs +++ b/crates/ui-egui/src/drop_overlay.rs @@ -52,7 +52,7 @@ fn lines(app: &LightcraftApp, paths: Vec, unknown: bool) -> Vec } else if !drop.photos.is_empty() && app.lightroom.is_some() && !cfg!(target_arch = "wasm32") { // the drop is refused while a Lightroom catalog import owns the catalog out.push(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string()); - } else if !drop.photos.is_empty() && crate::import::running(app) && !cfg!(target_arch = "wasm32") { + } else if !drop.photos.is_empty() && crate::import::drop_blocked(app) && !cfg!(target_arch = "wasm32") { out.push(crate::i18n::tr("An import is running. Drop photos when it has finished").to_string()); } else if !drop.photos.is_empty() { let n = drop.photos.len(); diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index ab49563cbb8..360b3726ee2 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -397,6 +397,7 @@ impl Headless { || self.app.scan.is_some() || self.app.sync.is_some() || self.app.sync_run.is_some() + || self.app.sync_queued.is_some() || self.app.import.is_some() || self.app.export.is_some() || self.app.session.denoise_busy() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bf57b341c6..d5d61a75fc1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -304,6 +304,8 @@ pub struct LightcraftApp { pub sync_owns_changes: bool, /// A Synchronize Folder at work in the background. pub sync_run: Option, + /// A Synchronize Folder that waited in line, scanning its folder again before it runs. + pub sync_queued: Option, /// A Lightroom catalog inspect/import in progress. pub lightroom: Option, /// Last terminal Lightroom result, exposed by the command's status/wait response. diff --git a/crates/ui-egui/src/lightroom_import.rs b/crates/ui-egui/src/lightroom_import.rs index 098c989d5cf..dbc81d17c7c 100644 --- a/crates/ui-egui/src/lightroom_import.rs +++ b/crates/ui-egui/src/lightroom_import.rs @@ -166,7 +166,7 @@ fn busy(app: &LightcraftApp) -> Result<(), String> { if app.lightroom.is_some() { return Err("a Lightroom catalog task is already running".into()); } - if app.import.is_some() || app.scan.is_some() { + if app.import.is_some() || app.scan.is_some() || crate::import::library_busy(app) { return Err("an import is running".into()); } Ok(()) diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 25d7cd84c5a..254db3d52a9 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -3,11 +3,16 @@ //! changed and what to do about it. Synchronize runs `folder.synchronize`, which acts on exactly //! the scan the dialog showed (see `lightcraft_engine::sync`). Both the scan and the run show a row in the activity //! stack (issue #345); its ✕ stops them like the dialog's Cancel. +//! +//! A Synchronize asked for while an import or another synchronize runs waits in line behind it (the library lane, +//! [`lightcraft_engine::activity::Lane::Library`]). When its turn comes it scans the folder again ([`SyncRescan`]) and +//! then runs as it was asked, but it removes or relinks only the photos its dialog showed: one that went missing +//! meanwhile was never shown to the person, so it is left alone, and the end says so. use std::sync::Arc; use std::sync::atomic::Ordering; -use lightcraft_engine::activity::{Cancel, TaskGuard}; +use lightcraft_engine::activity::{Cancel, Request, TaskGuard}; use lightcraft_engine::sync::{FolderChanges, SyncChoice, SyncCommit, SyncInput, SyncJob, SyncProgress, SyncStep, scan_with}; use serde_json::{Value, json}; @@ -58,7 +63,8 @@ pub fn open(app: &mut LightcraftApp, path: &str, name: &str, disk: bool) -> Resu std::thread::spawn(job); #[cfg(target_arch = "wasm32")] job(); - let guard = app.session.activity.start("sync", "Looking for changes", Cancel::Flag(progress.files.cancel.clone())); + // (kind `scan`, not `sync`: it only reads, and doesn't hold up an import) + let guard = app.session.activity.start("scan", "Looking for changes", Cancel::Flag(progress.files.cancel.clone())); guard.detail(name); app.sync = Some(SyncTask { path: path.to_string(), name: name.to_string(), progress, rx, guard }); let d = SyncChoice::default(); @@ -221,25 +227,37 @@ pub fn body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { /// thread at once ([`SyncRun`]); nothing is read from disk on the UI thread. A scan that went /// stale (the folder's photos changed meanwhile) is refused and made again, keeping the choices. /// A folder that is up to date has nothing to hand over: confirming it only closes the dialog. +/// While an import or another synchronize runs it waits in line instead ([`SyncRescan`]). pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { let Dialog::SynchronizeFolder { path, name, disk, counts: Some(counts), import_new, relink_moved, remove_missing, read_metadata, .. } = dlg else { return Err("the folder is still being scanned".into()); }; - // (before the busy checks: nothing is imported or written, so a running import or - // synchronize can't clash with it, and the dialog closes either way. Like every result the + // (before the line: nothing is imported or written, so a running import or + // synchronize can't clash with it and it has nothing to wait for; the dialog closes either way. Like every result the // dialog shows, it is the scan's: a file added since is found by the next Synchronize) if counts.up_to_date() { return Ok(json!({"upToDate": true})); } - if app.sync_run.is_some() { - return Err(crate::i18n::tr("A folder is already being synchronized").to_string()); - } + let choice = SyncChoice { import_new: *import_new, relink_moved: *relink_moved, remove_missing: *remove_missing, read_metadata: *read_metadata }; // (an import readies its files against the library as it was: both could add the same file) - if app.import.is_some() { - return Err(crate::i18n::tr("Wait for the import to finish").to_string()); + if crate::import::library_busy(app) { + // what the dialog showed: only these are removed or relinked, whenever the run comes + let shown = app + .session + .folder_changes + .as_ref() + .filter(|c| lightcraft_catalog::query::folder_key(&c.path) == lightcraft_catalog::query::folder_key(path)); + let (missing, moved): (Vec, Vec) = + shown.map(|c| (c.missing.iter().map(|m| m.id).collect(), c.moved.iter().map(|m| m.id).collect())).unwrap_or_default(); + let request = sync_request(path, name, *disk, choice, &missing, &moved); + if std::mem::take(&mut app.sync_owns_changes) { + app.session.folder_changes = None; + } + let (id, place) = app.session.activity.enqueue("sync", "Synchronizing folder", request)?; + app.queued_toast(place as u64); + return Ok(json!({"queued": id, "place": place})); } - let choice = SyncChoice { import_new: *import_new, relink_moved: *relink_moved, remove_missing: *remove_missing, read_metadata: *read_metadata }; app.sync_owns_changes = false; let started = match app.session.take_folder_changes(path) { Some(changes) => SyncJob::start(&mut app.session, changes, choice).map_err(|e| e.to_string()), @@ -259,6 +277,23 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { } }; let progress = Arc::new(SyncProgress::default()); + let guard = app.session.activity.start("sync", "Synchronizing folder", Cancel::Flag(progress.files.cancel.clone())); + guard.detail(name); + run(app, name, work, commit, progress, guard, 0); + Ok(json!({"started": true})) +} + +/// Hand the work of a synchronize to a worker thread, its steps committed between frames ([`poll_run`]). `left_alone`: +/// photos found missing (or moved) that its dialog never showed, said at the end. +fn run( + app: &mut LightcraftApp, + name: &str, + work: lightcraft_engine::sync::SyncWork, + commit: SyncCommit, + progress: Arc, + guard: TaskGuard, + left_alone: usize, +) { let crashed = Arc::new(std::sync::atomic::AtomicBool::new(false)); let (tx, rx) = std::sync::mpsc::channel(); let (p, c) = (progress.clone(), crashed.clone()); @@ -273,10 +308,138 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { std::thread::spawn(job); #[cfg(target_arch = "wasm32")] job(); + app.sync_run = Some(SyncRun { + name: name.to_string(), + progress, + crashed, + rx, + commit: Some(commit), + stopping: false, + not_saved: Vec::new(), + guard, + left_alone, + }); +} + +/// The command of a Synchronize Folder's request ([`Request`]): the app runs it ([`start_request`]). +pub const SYNC_REQUEST: &str = "app:synchronize"; + +/// What a synchronize was asked, to run it later in line or again: the folder, the dialog's choices, and the missing +/// and moved photos it showed (the only ones it may remove or relink). +fn sync_request(path: &str, name: &str, disk: bool, choice: SyncChoice, missing: &[u64], moved: &[u64]) -> Request { + Request { + command: SYNC_REQUEST.into(), + params: json!({ + "path": path, "name": name, "disk": disk, + "importNew": choice.import_new, "relinkMoved": choice.relink_moved, "removeMissing": choice.remove_missing, "readMetadata": choice.read_metadata, + "missing": missing, "moved": moved, + }), + } +} + +/// A synchronize that waited in line, scanning its folder again on a worker thread before it runs ([`poll_rescan`]). +pub struct SyncRescan { + name: String, + choice: SyncChoice, + /// The missing and moved photos its dialog showed. + missing: std::collections::HashSet, + moved: std::collections::HashSet, + /// The library it was asked in ([`lightcraft_engine::Session::library_generation`]): its photo ids mean nothing in + /// another one. + library: u64, + progress: Arc, + rx: std::sync::mpsc::Receiver, + /// Its row, from the line through the scan to the end of the run. + guard: TaskGuard, +} + +/// Start a synchronize that waited in line (`request`, made by [`sync_request`]): it scans the folder again, under the +/// row it had while it waited, and runs when the scan is in ([`poll_rescan`]). +pub fn start_request(app: &mut LightcraftApp, _ctx: &egui::Context, request: &Request) -> Result<(), String> { + let p = &request.params; + let path = p["path"].as_str().ok_or("no folder to synchronize")?; + let name = p["name"].as_str().unwrap_or(path).to_string(); + let flag = |k: &str| p[k].as_bool().unwrap_or(false); + let ids = |k: &str| p[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + let choice = SyncChoice { + import_new: flag("importNew"), + relink_moved: flag("relinkMoved"), + remove_missing: flag("removeMissing"), + read_metadata: flag("readMetadata"), + }; + let input = SyncInput::new(&mut app.session, path, flag("disk")).map_err(|e| e.to_string())?; + let progress = Arc::new(SyncProgress::default()); + let (tx, rx) = std::sync::mpsc::channel(); + let pr = progress.clone(); + let job = move || { + let _ = tx.send(scan_with(input, &pr)); + }; + #[cfg(not(target_arch = "wasm32"))] + std::thread::spawn(job); + #[cfg(target_arch = "wasm32")] + job(); let guard = app.session.activity.start("sync", "Synchronizing folder", Cancel::Flag(progress.files.cancel.clone())); - guard.detail(name); - app.sync_run = Some(SyncRun { name: name.clone(), progress, crashed, rx, commit: Some(commit), stopping: false, not_saved: Vec::new(), guard }); - Ok(json!({"started": true})) + guard.detail(&name); + let library = app.session.library_generation(); + app.sync_queued = Some(SyncRescan { name, choice, missing: ids("missing"), moved: ids("moved"), library, progress, rx, guard }); + Ok(()) +} + +/// Run the waiting synchronize once its scan is in (called every frame): only the missing and moved photos its dialog +/// showed are acted on. +pub fn poll_rescan(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some(task) = app.sync_queued.as_ref() else { return }; + let (done, total) = task.progress.counts(); + task.guard.progress(done as u64, total as u64); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + let got = task.rx.try_recv(); + if matches!(got, Err(std::sync::mpsc::TryRecvError::Empty)) && !task.guard.is_cancelled() { + return; + } + let Some(task) = app.sync_queued.take() else { return }; + let SyncRescan { name, choice, missing, moved, library, progress, guard, .. } = task; + if library != app.session.library_generation() { + // another library was opened while it scanned: its photos are not these + progress.files.cancel.store(true, Ordering::Relaxed); + app.toast(ctx, format!("{name}: {}", crate::i18n::tr("Another library was opened: nothing was done"))); + return; + } + let mut changes = match got { + _ if guard.is_cancelled() => { + progress.files.cancel.store(true, Ordering::Relaxed); + return; + } + Ok(c) => c, + Err(_) => { + // the scan's worker died (a panic, logged) + app.toast(ctx, crate::i18n::tr("Scan failed")); + return; + } + }; + if changes.offline { + let why = crate::i18n::tr("This folder isn't there: it was moved or renamed, or its disk isn't connected.").to_string(); + app.toast(ctx, format!("{name}: {why}")); + return; + } + // only what the person saw is removed or relinked; what they would have been asked about is said + let (missing_before, moved_before) = (changes.missing.len(), changes.moved.len()); + changes.missing.retain(|m| missing.contains(&m.id)); + changes.moved.retain(|m| moved.contains(&m.id)); + let left_alone = if choice.remove_missing { missing_before - changes.missing.len() } else { 0 } + + if choice.relink_moved { moved_before - changes.moved.len() } else { 0 }; + match SyncJob::start(&mut app.session, changes, choice) { + Ok((work, commit)) => { + // (a fresh count, the same ✕: its row's flag stops the run as it stopped the scan) + let run_progress = Arc::new(SyncProgress { + files: lightcraft_engine::import::ScanProgress { cancel: progress.files.cancel.clone(), ..Default::default() }, + ..Default::default() + }); + run(app, &name, work, commit, run_progress, guard, left_alone); + } + Err(e) => { + app.toast(ctx, format!("{name}: {e}")); + } + } } /// A synchronize at work: the file-system half on a worker thread, its steps committed here @@ -294,6 +457,8 @@ pub struct SyncRun { stopping: bool, /// Its row in the activity stack (its ✕ is Cancel). guard: TaskGuard, + /// Photos found missing or moved that its dialog never showed (a run that waited in line): left alone, and said. + left_alone: usize, } impl SyncRun { @@ -333,6 +498,7 @@ pub(crate) fn stall_run(app: &mut LightcraftApp, name: &str) -> Box 0 { + parts.push(crate::i18n::tr_format!("{n} more missing, left alone: synchronize again to review them", n = left_alone)); + } let text = if parts.is_empty() { crate::i18n::tr("The library is up to date with this folder.").to_string() } else { parts.join(" · ") }; if not_saved.is_empty() && !crashed { app.toast(ctx, format!("{name}: {text}")); diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 3d8031a69bd..a4094d8a1ee 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -822,18 +822,37 @@ fn a_waiting_review_never_replaces_a_running_import() { h.step(); let Some(review) = h.app.ui.dialog.clone() else { panic!("the review opens once the dialog is closed") }; assert!(matches!(review, Dialog::Import { .. })); - // an import that started anyway (a Local folder browse, say) is the one that runs + // an import that started anyway (a Local folder browse, say) is the one that runs: the review's OK waits behind it h.app.import = Some(crate::import::ImportTask::new(vec![dir.path("more")], json!({"mode": "add"}), 0, false)); - assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &review).is_err(), "the review's OK is refused"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &review); + assert!(r.as_ref().is_ok_and(|v| v["queued"].as_u64().is_some()), "the review's OK waits in line: {r:?}"); assert_eq!(h.app.import.as_ref().map(|t| t.total), Some(1), "the running import stays"); - assert!(h.step_until(SETTLE, |h| h.app.import.is_none()), "it runs to the end"); - assert_eq!(photos(&h), 1, "only the running import's photo arrives"); + assert!(h.step_until(SETTLE, |h| h.app.import.is_none() && h.app.session.activity.list().is_empty()), "both run to the end"); + assert_eq!(photos(&h), 3, "the running import's photo arrives, then the review's two"); } -/// A drop while an import runs would open a review whose OK replaces the running import: it is +/// Given an import that runs, when photos are dropped directly on the window, then they are not refused: they wait in +/// line behind it and are imported when it ends. +#[test] +fn a_direct_drop_while_an_import_runs_waits_in_line() { + let dir = Scratch::new("running-waits"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = true; + write_png(&dir.path("more/c.png"), 3); + // (held by a row of the lane, so that it can't finish between the frames of the drop) + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + drop_files(&mut h, &[dir.path("trip")], false); + assert_eq!(h.app.session.activity.waiting().iter().map(|t| t.kind).collect::>(), vec!["import"]); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.starts_with("Queued")), "{:?}", h.app.ui.toast); + drop(hold); + assert!(h.step_until(SETTLE, |h| h.app.import.is_none() && h.app.session.activity.list().is_empty()), "both run to the end"); + assert_eq!(photos(&h), 2, "the dropped folder's two photos"); +} + +/// A drop while a scan runs would open a review whose OK replaces the import the scan starts: it is /// refused instead, and the card says so. #[test] -fn a_drop_while_an_import_runs_is_refused() { +fn a_drop_while_a_scan_runs_is_refused() { let dir = Scratch::new("running"); let mut h = app(&dir); write_png(&dir.path("more/c.png"), 3); @@ -851,9 +870,9 @@ fn a_drop_while_an_import_runs_is_refused() { assert_eq!(photos(&h), 0); } -/// An import that is running stays the one that runs: a direct drop doesn't start a second. +/// A scan that is running stays the one that runs: a direct drop doesn't start a second import beside it. #[test] -fn a_direct_drop_while_an_import_runs_is_refused_too() { +fn a_direct_drop_while_a_scan_runs_is_refused_too() { let dir = Scratch::new("running-direct"); let mut h = app(&dir); h.app.ui.settings.import_dropped_directly = true; diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index 84cda586021..362f4c1a7f9 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -18,6 +18,12 @@ //! * While the folder is listed (minutes, on a network share), the scan's row says how many //! folders and files it has listed, with a bar that moves on its own, not "0 of 64085"; then it //! counts the files and photos checked. +//! * A Synchronize Folder and an import never run at once: one asked for while the other runs waits in line behind it +//! and starts by itself, planning its work then (an import checks for duplicates against the library as it is +//! when it starts; a synchronize scans the folder again). +//! * A synchronize that waited removes or relinks only the photos its dialog showed: a photo that went missing while +//! it waited stays, and the end says so. +//! * The dialog's own scan doesn't hold up an import: it only reads. use std::time::Duration; @@ -292,33 +298,137 @@ fn a_stopped_synchronize_says_it_was_stopped_and_stays_at_most_one_step() { assert!(h.app.session.undo.len() <= steps + 1, "what was done by then is at most one step"); } +fn sync_dialog(dir: &Scratch, remove_missing: bool) -> Dialog { + Dialog::SynchronizeFolder { + path: dir.path("trip"), + name: "trip".into(), + disk: false, + counts: Some(crate::state::SyncCounts { new: 1, ..Default::default() }), + import_new: true, + relink_moved: true, + remove_missing, + read_metadata: false, + } +} + +/// Every task done, nothing waiting. +fn idle(h: &Headless) -> bool { + h.app.sync_run.is_none() && h.app.import.is_none() && h.app.session.activity.list().is_empty() +} + +/// Given a synchronize running, when the same folder is dropped on the window, then the import waits in line behind +/// it and starts by itself once it ends, adding nothing twice (it plans its work then). The other way round: a +/// synchronize confirmed while an import runs waits for it, and then synchronizes. #[test] -fn a_synchronize_and_an_import_never_run_at_once() { +fn a_synchronize_and_an_import_wait_for_each_other() { let dir = Scratch::new("exclusive"); let mut h = changed_folder(&dir); open_and_scan(&mut h, &dir.path("trip")); let dlg = h.app.ui.dialog.take().expect("the dialog is open"); assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_ok()); // dropping the same folder on the window while the run works would add its files twice - let r = crate::import::start_paths(&mut h.app, vec![dir.path("trip")]); - assert!(r.is_err(), "no import while synchronizing: {r:?}"); - assert!(h.step_until(T, |h| h.app.sync_run.is_none())); + write_png(&dir.path("elsewhere/e.png"), 9); + let r = crate::import::start_paths(&mut h.app, vec![dir.path("trip"), dir.path("elsewhere/e.png")]).expect("it waits instead of being refused"); + let id = r["queued"].as_u64().unwrap_or_else(|| panic!("queued: {r}")); + let waiting = h.app.session.activity.waiting(); + assert_eq!(waiting.iter().map(|t| (t.id, t.kind, t.label.as_str())).collect::>(), vec![(id, "import", "Importing")]); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.starts_with("Queued")), "{:?}", h.app.ui.toast); + assert!(h.step_until(SETTLE, idle), "both ran"); + let c = h.app.session.catalog.photos().filter(|p| p.in_library() && p.file_name == "c.png").count(); + assert_eq!(c, 1, "the import found c already in the library when its turn came"); + assert!(in_library(&h).contains(&"e.png".to_string()), "and it ran: {:?}", in_library(&h)); // and the other way round: an import is running (no frame has run since it started) + write_png(&dir.path("trip/d.png"), 4); let r = crate::import::start_paths(&mut h.app, vec![dir.path("trip/a.png")]); - assert!(r.is_ok(), "{r:?}"); - assert!(h.app.import.is_some()); - let d = Dialog::SynchronizeFolder { - path: dir.path("trip"), - name: "trip".into(), - disk: false, - counts: Some(crate::state::SyncCounts { new: 1, ..Default::default() }), - import_new: true, - relink_moved: true, - remove_missing: false, - read_metadata: false, - }; - let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &d); - assert!(r.is_err() && h.app.sync_run.is_none(), "no synchronize while importing: {r:?}"); + assert!(r.as_ref().is_ok_and(|v| v.get("importing").is_some()), "{r:?}"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &sync_dialog(&dir, false)); + assert!(r.as_ref().is_ok_and(|v| v.get("queued").is_some()), "the synchronize waits: {r:?}"); + assert!(h.app.sync_run.is_none()); + assert!(h.step_until(SETTLE, idle), "both ran"); + assert!(in_library(&h).contains(&"d.png".to_string()), "the synchronize scanned the folder at its turn: {:?}", in_library(&h)); +} + +/// Given a synchronize that will remove the one missing photo its dialog showed (b), waiting behind an import, when +/// another photo of the folder (a) goes missing while it waits, then at its turn it removes b only: a stays, and the +/// end says one more is missing and was left alone. +#[test] +fn a_waiting_synchronize_removes_only_the_missing_photos_its_dialog_showed() { + let dir = Scratch::new("reviewed"); + let mut h = changed_folder(&dir); + open_and_scan(&mut h, &dir.path("trip")); + tick_remove_missing(&mut h); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg); + assert!(r.as_ref().is_ok_and(|v| v.get("queued").is_some()), "it waits for the import: {r:?}"); + std::fs::remove_file(dir.path("trip/a.png")).unwrap(); + drop(hold); + assert!(h.step_until(SETTLE, idle), "it ran"); + assert_eq!(in_library(&h), vec!["a.png", "c.png"], "b (shown) was removed, a (gone since) was not"); + let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); + assert!(said.contains("1 more missing"), "{said}"); +} + +/// Given a Local folder being read, when a synchronize is confirmed, then it waits: the read becomes an import when +/// it finishes, and the two would run side by side. +#[test] +fn a_synchronize_confirmed_while_a_local_folder_is_read_waits() { + let dir = Scratch::new("browse"); + let mut h = changed_folder(&dir); + let _scan = crate::import::stall_scan_of(&mut h.app, true); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &sync_dialog(&dir, false)); + assert!(r.as_ref().is_ok_and(|v| v.get("queued").is_some()), "{r:?}"); + assert!(h.app.sync_run.is_none()); + h.app.scan = None; +} + +/// Given a waiting synchronize that has started scanning its folder again, when another library is opened before the +/// scan is in, then it stops without touching the new library: its photo ids were the old library's. +#[test] +fn a_waiting_synchronize_never_acts_on_another_library() { + let dir = Scratch::new("switch"); + let mut h = changed_folder(&dir); + open_and_scan(&mut h, &dir.path("trip")); + tick_remove_missing(&mut h); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_ok_and(|v| v["queued"].as_u64().is_some()), "it waits"); + drop(hold); + // one frame: it starts scanning; the next library opens before the scan is looked at + assert!(h.step_until(T, |h| h.app.sync_queued.is_some()), "it started scanning again"); + h.app.session.open_library(dir.path("other"), false).unwrap(); + assert!(h.step_until(SETTLE, idle), "it ended"); + assert_eq!(h.app.session.catalog.photos().count(), 0, "nothing came into the new library, nothing was removed"); + let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); + assert!(said.contains("Another library was opened"), "{said}"); +} + +/// Given a synchronize waiting in line, when its folder is gone by its turn, then it ends saying so and changes +/// nothing. +#[test] +fn a_waiting_synchronize_whose_folder_went_away_says_so() { + let dir = Scratch::new("gone"); + let mut h = changed_folder(&dir); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &sync_dialog(&dir, false)); + assert!(r.is_ok_and(|v| v["queued"].as_u64().is_some()), "it waits"); + std::fs::rename(dir.path("trip"), dir.path("trip-away")).unwrap(); + drop(hold); + assert!(h.step_until(SETTLE, idle), "it ended"); + let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); + assert!(said.contains("isn't there"), "{said}"); + assert!(!in_library(&h).contains(&"c.png".to_string()), "{:?}", in_library(&h)); +} + +/// The dialog's scan only reads: an import dropped on the window while it scans starts at once. +#[test] +fn the_dialogs_scan_doesnt_hold_up_an_import() { + let dir = Scratch::new("scan-free"); + let mut h = changed_folder(&dir); + crate::sync::open(&mut h.app, &dir.path("trip"), "trip", false).unwrap(); + let r = crate::import::start_paths(&mut h.app, vec![dir.path("trip/c.png")]); + assert!(r.as_ref().is_ok_and(|v| v.get("importing").is_some()), "{r:?}"); + h.settle(SETTLE); } #[test] @@ -357,7 +467,7 @@ fn the_folders_scan_shows_a_row_and_its_cross_closes_the_dialog() { crate::sync::open(&mut h.app, &dir.path("trip"), "trip", false).unwrap(); let rows = h.app.session.activity.list(); assert_eq!(rows.len(), 1, "{rows:?}"); - assert_eq!((rows[0].kind, rows[0].label.as_str(), rows[0].detail.as_str()), ("sync", "Looking for changes", "trip")); + assert_eq!((rows[0].kind, rows[0].label.as_str(), rows[0].detail.as_str()), ("scan", "Looking for changes", "trip")); assert!(rows[0].cancellable); h.app.session.activity.cancel(rows[0].id).unwrap(); h.step(); diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 128bd60e3ce..2299e894dcd 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -51,15 +51,30 @@ guard.detail(&file_name); ## Waiting in line -Jobs that must not run side by side share a lane (`activity::Lane`; for now only the preview builds: Build Previews and -the background Build / Discard Smart Previews). A call that sets `queue: true` while its lane is busy does not fail: +Jobs that must not run side by side share a lane (`activity::Lane`). There are two so far: + +- **The preview lane:** Build Previews and the background Build / Discard Smart Previews, one preview build at a time. +- **The library lane:** imports (the import review's Import, files dropped on the window) and Synchronize Folder. + Each plans its work against the library as it is when it starts, so two side by side could add the same file. An + import asked for while the lane is taken is not refused any more: it waits and checks for duplicates against the + library as it is when its turn comes. A Synchronize Folder that waits scans its folder again at its turn, then + removes or relinks only the photos its dialog showed: one that went missing while it waited was never shown, so it + is left alone and the end says so ("1 more missing, left alone: synchronize again to review them"). If another + library is opened while it scans, or its folder is gone, it stops without doing anything and a toast says so. A + toast says it was queued when it was put in line. The dialog's own scan ("Looking for changes", kind `scan`) only + reads and holds up nothing. These requests are the app's (`app:import`, `app:synchronize`): the app starts them + (`LightcraftApp::start_waiting`, every frame), and the engine leaves them alone (`Activity::take_ready_if`). Auto + Import waits until nothing runs, rescans or waits in this lane. A drop while an import's review is open or a scan + runs is still refused. + +A call that sets `queue: true` while its lane is busy does not fail: `Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, `place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is -busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged and the next in line goes on. +busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged (the app's own, an import or a Synchronize Folder, also says why in a toast) and the next in line goes on. ## Examples in the code diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fc0dccf4cc4..b7f0e0c7e07 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -90,13 +90,13 @@ filmstrip is visible. | `ui.scroll` | `{dx, dy, source?, unit?, phase?, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms. `source` is `unknown` (default), `wheel`, `trackpad` or `momentum`; `unit` is `point` (default), `line` or `page`; `phase` is `move` (default), `start`, `end` or `cancel`. Wheel/line events drive the grid/filmstrip one-third wheel step and the loupe's notch zoom; trackpad/momentum phases drive kinetic scrolling and rubber-band boundaries. Invalid values are refused and queue nothing | | `ui.zoom` | `{factor}` | Pinch zoom at the current pointer (positive scale multiplier; 1 = unchanged). Position it first with `ui.move` or `ui.hoverWidget` | | `ui.set` | partial UI state, e.g. `{"view": "detail"}` | Resulting UI state | -| `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing) | +| `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing; the Import review and Synchronize Folder answer `{queued, place}` instead of `{importing}` / `{started}` while an import or a synchronize runs: the task waits in line and starts by itself) | | `ui.resize` | `{width, height}` | Resize the window | | `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"` or `"library"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it; the app puts its own imports and Synchronize Folder there, `lane: "library"`); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..78eee63fcbf 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder wait for each other instead of refusing; earlier: LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -461,7 +461,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list; an import and a Synchronize Folder never run at once: one asked for while the other runs waits in line and starts by itself (the library lane, `activity::Lane`). No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | @@ -959,3 +959,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | +| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and acts only on the photos its dialog showed; status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..6c330181bfb 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,18 @@ ## 2026-10-24 +### Imports and Synchronize Folder wait for each other +- An import confirmed (or photos dropped on the window) while a Synchronize Folder runs, or a Synchronize Folder + confirmed while an import runs, now waits in line and starts by itself when the other ends, with a message that it + was queued. Before, it was refused ("Wait for the import to finish", "A folder is being synchronized"). +- Photos dropped on the window, or an import review confirmed, while another import runs also wait in line instead of + being refused with "An import is running"; a drop is still refused while a folder is being scanned for the review. +- A waiting import checks for duplicates against the library as it is when its turn comes, so nothing is added twice. +- A waiting Synchronize Folder looks at its folder again when its turn comes. It removes or relinks only the photos + its dialog showed: one that went missing while it waited is left alone, and the message at the end says so. +- Nothing waits across another library: a Synchronize Folder that is still scanning when another library opens does + nothing. + ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for From a6f87cb3aa58c7abd6c33d764d6bf8a3753b8dd5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 18:26:28 -0400 Subject: [PATCH 07/55] =?UTF-8?q?LR-BEHAV-BG-TASKS:=20a=20task=20waiting?= =?UTF-8?q?=20in=20line=20shows=20in=20the=20activity=20stack,=20with=20?= =?UTF-8?q?=E2=9C=95=20to=20take=20it=20out?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On this base a task waiting in the library or preview lane showed only a "Queued" toast and could not be withdrawn. The activity stack now draws it at once (it was just asked for) as a row without a bar: its name, "Starts next" or "Starts after N more", and ✕ named "Remove from Queue: ", which runs `activity.cancel` (the engine takes a waiting task out of the line and leaves the running one alone). Co-Authored-By: Claude --- crates/ui-egui/locales/cs-formats.json | 4 ++- crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de-formats.json | 4 ++- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es-formats.json | 4 ++- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi-formats.json | 4 ++- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr-formats.json | 4 ++- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id-formats.json | 4 ++- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it-formats.json | 4 ++- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja-formats.json | 4 ++- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka-formats.json | 4 ++- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl-formats.json | 4 ++- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br-formats.json | 4 ++- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru-formats.json | 4 ++- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv-formats.json | 4 ++- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk-formats.json | 4 ++- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi-formats.json | 4 ++- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans-formats.json | 4 ++- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant-formats.json | 4 ++- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/panels/activity.rs | 28 ++++++++++------- crates/ui-egui/src/tests/activity.rs | 11 ++++--- crates/ui-egui/src/tests/drop_import.rs | 33 +++++++++++++++++++++ docs/background-tasks.md | 2 +- docs/parity-checklist.md | 6 ++-- docs/whats-new.md | 1 + 40 files changed, 148 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 48806ebd143..baca445ebb6 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", "Queued: it starts after {n} more": "Ve frontě: začne po {n} dalších", - "{n} more missing, left alone: synchronize again to review them": "{n} dalších chybí, ponecháno beze změny: pro kontrolu synchronizujte znovu" + "{n} more missing, left alone: synchronize again to review them": "{n} dalších chybí, ponecháno beze změny: pro kontrolu synchronizujte znovu", + "Starts after {n} more": "Začne po {n} dalších", + "Remove from Queue: {label}": "Odebrat z fronty: {label}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index af68f83b201..2ffc8846ee3 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2409,5 +2409,6 @@ "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", "Queued: it starts when the task ahead of it ends": "Ve frontě: začne, až skončí úloha před ní", - "Another library was opened: nothing was done": "Byla otevřena jiná knihovna: nic se neprovedlo" + "Another library was opened: nothing was done": "Byla otevřena jiná knihovna: nic se neprovedlo", + "Starts next": "Začne jako další" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index b47170de57e..c0aa7b83095 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", "Queued: it starts after {n} more": "In der Warteschlange: startet nach {n} weiteren", - "{n} more missing, left alone: synchronize again to review them": "{n} weitere fehlen und blieben unangetastet: zum Prüfen erneut synchronisieren" + "{n} more missing, left alone: synchronize again to review them": "{n} weitere fehlen und blieben unangetastet: zum Prüfen erneut synchronisieren", + "Starts after {n} more": "Startet nach {n} weiteren", + "Remove from Queue: {label}": "Aus der Warteschlange entfernen: {label}" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index ed644215e58..a809ebe4c3d 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3441,5 +3441,6 @@ "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", "Queued: it starts when the task ahead of it ends": "In der Warteschlange: startet, wenn die Aufgabe davor endet", - "Another library was opened: nothing was done": "Eine andere Bibliothek wurde geöffnet: es wurde nichts getan" + "Another library was opened: nothing was done": "Eine andere Bibliothek wurde geöffnet: es wurde nichts getan", + "Starts next": "Startet als Nächstes" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index cabf7433efa..405df93e588 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", "Queued: it starts after {n} more": "En cola: empieza tras {n} más", - "{n} more missing, left alone: synchronize again to review them": "Faltan {n} más, sin tocar: sincroniza de nuevo para revisarlas" + "{n} more missing, left alone: synchronize again to review them": "Faltan {n} más, sin tocar: sincroniza de nuevo para revisarlas", + "Starts after {n} more": "Empieza tras {n} más", + "Remove from Queue: {label}": "Quitar de la cola: {label}" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 03589c0dcc4..3dc670f7089 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2359,5 +2359,6 @@ "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", "Queued: it starts when the task ahead of it ends": "En cola: empieza cuando termine la tarea anterior", - "Another library was opened: nothing was done": "Se abrió otra biblioteca: no se hizo nada" + "Another library was opened: nothing was done": "Se abrió otra biblioteca: no se hizo nada", + "Starts next": "Empieza la siguiente" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 72f65964852..e6caa87a913 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", "Queued: it starts after {n} more": "Jonossa: alkaa {n} muun jälkeen", - "{n} more missing, left alone: synchronize again to review them": "{n} muuta puuttuu ja jätettiin ennalleen: synkronoi uudelleen tarkistaaksesi ne" + "{n} more missing, left alone: synchronize again to review them": "{n} muuta puuttuu ja jätettiin ennalleen: synkronoi uudelleen tarkistaaksesi ne", + "Starts after {n} more": "Alkaa {n} muun jälkeen", + "Remove from Queue: {label}": "Poista jonosta: {label}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index f63b4b43cfb..e818f109e0b 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2328,5 +2328,6 @@ "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", "Queued: it starts when the task ahead of it ends": "Jonossa: alkaa, kun sen edellä oleva tehtävä päättyy", - "Another library was opened: nothing was done": "Toinen kirjasto avattiin: mitään ei tehty" + "Another library was opened: nothing was done": "Toinen kirjasto avattiin: mitään ei tehty", + "Starts next": "Alkaa seuraavaksi" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 4b3326065b9..b3d7d0a92d7 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", "Queued: it starts after {n} more": "En file : démarre après {n} autres", - "{n} more missing, left alone: synchronize again to review them": "{n} autres manquantes, laissées telles quelles : synchronisez à nouveau pour les examiner" + "{n} more missing, left alone: synchronize again to review them": "{n} autres manquantes, laissées telles quelles : synchronisez à nouveau pour les examiner", + "Starts after {n} more": "Démarre après {n} autres", + "Remove from Queue: {label}": "Retirer de la file : {label}" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 27179c32682..ef1faa5f8d6 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2391,5 +2391,6 @@ "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", "Queued: it starts when the task ahead of it ends": "En file : démarre à la fin de la tâche précédente", - "Another library was opened: nothing was done": "Une autre bibliothèque a été ouverte : rien n’a été fait" + "Another library was opened: nothing was done": "Une autre bibliothèque a été ouverte : rien n’a été fait", + "Starts next": "Démarre ensuite" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index d42faac7969..22637a1805c 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", "Queued: it starts after {n} more": "Dalam antrean: dimulai setelah {n} lagi", - "{n} more missing, left alone: synchronize again to review them": "{n} lagi hilang dan dibiarkan: sinkronkan lagi untuk memeriksanya" + "{n} more missing, left alone: synchronize again to review them": "{n} lagi hilang dan dibiarkan: sinkronkan lagi untuk memeriksanya", + "Starts after {n} more": "Dimulai setelah {n} lagi", + "Remove from Queue: {label}": "Hapus dari antrean: {label}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 3073c328cbc..00d6d0753ec 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2340,5 +2340,6 @@ "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", "Queued: it starts when the task ahead of it ends": "Dalam antrean: dimulai saat tugas di depannya selesai", - "Another library was opened: nothing was done": "Pustaka lain dibuka: tidak ada yang dilakukan" + "Another library was opened: nothing was done": "Pustaka lain dibuka: tidak ada yang dilakukan", + "Starts next": "Dimulai berikutnya" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 23650b47c58..e5d958558d7 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", "Queued: it starts after {n} more": "In coda: parte dopo altre {n}", - "{n} more missing, left alone: synchronize again to review them": "Ne mancano altre {n}, lasciate com'erano: sincronizza di nuovo per esaminarle" + "{n} more missing, left alone: synchronize again to review them": "Ne mancano altre {n}, lasciate com'erano: sincronizza di nuovo per esaminarle", + "Starts after {n} more": "Parte dopo altre {n}", + "Remove from Queue: {label}": "Rimuovi dalla coda: {label}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 1f143b04772..28d4a80c322 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2362,5 +2362,6 @@ "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", "Queued: it starts when the task ahead of it ends": "In coda: parte quando finisce l'attività precedente", - "Another library was opened: nothing was done": "È stata aperta un'altra libreria: non è stato fatto nulla" + "Another library was opened: nothing was done": "È stata aperta un'altra libreria: non è stato fatto nulla", + "Starts next": "Parte subito dopo" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 15853a927b0..63366fe394c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", "Queued: it starts after {n} more": "キューに追加: あと {n} 件の後に開始します", - "{n} more missing, left alone: synchronize again to review them": "ほかに {n} 件が見つからず、そのままにしました: 確認するにはもう一度同期してください" + "{n} more missing, left alone: synchronize again to review them": "ほかに {n} 件が見つからず、そのままにしました: 確認するにはもう一度同期してください", + "Starts after {n} more": "あと {n} 件の後に開始します", + "Remove from Queue: {label}": "キューから削除: {label}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index f954190daeb..2709a330ca9 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2357,5 +2357,6 @@ "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", "Queued: it starts when the task ahead of it ends": "キューに追加: 前のタスクが終わると開始します", - "Another library was opened: nothing was done": "別のライブラリが開かれました: 何も行われていません" + "Another library was opened: nothing was done": "別のライブラリが開かれました: 何も行われていません", + "Starts next": "次に開始します" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 73ddac481ae..03b886141a2 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", "Queued: it starts after {n} more": "რიგშია: დაიწყება კიდევ {n}-ის შემდეგ", - "{n} more missing, left alone: synchronize again to review them": "კიდევ {n} აკლია და ხელუხლებლად დარჩა: გადასახედად ხელახლა მოახდინეთ სინქრონიზაცია" + "{n} more missing, left alone: synchronize again to review them": "კიდევ {n} აკლია და ხელუხლებლად დარჩა: გადასახედად ხელახლა მოახდინეთ სინქრონიზაცია", + "Starts after {n} more": "დაიწყება კიდევ {n}-ის შემდეგ", + "Remove from Queue: {label}": "რიგიდან ამოღება: {label}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 4db6010bd24..98f22f908f9 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2735,5 +2735,6 @@ "An import is running. Drop photos when it has finished": "იმპორტი მიმდინარეობს. ფოტოები ჩააგდეთ, როცა დასრულდება", "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი", "Queued: it starts when the task ahead of it ends": "რიგშია: დაიწყება, როცა წინა ამოცანა დასრულდება", - "Another library was opened: nothing was done": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა" + "Another library was opened: nothing was done": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა", + "Starts next": "დაიწყება შემდეგი" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index b7fe22f5cb7..c0a741cb28c 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", "Queued: it starts after {n} more": "W kolejce: rozpocznie się po {n} kolejnych", - "{n} more missing, left alone: synchronize again to review them": "Brakuje jeszcze {n}, pozostawiono bez zmian: zsynchronizuj ponownie, aby je przejrzeć" + "{n} more missing, left alone: synchronize again to review them": "Brakuje jeszcze {n}, pozostawiono bez zmian: zsynchronizuj ponownie, aby je przejrzeć", + "Starts after {n} more": "Rozpocznie się po {n} kolejnych", + "Remove from Queue: {label}": "Usuń z kolejki: {label}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index ad13a39be9b..da7a834f42b 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2284,5 +2284,6 @@ "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", "Queued: it starts when the task ahead of it ends": "W kolejce: rozpocznie się po zakończeniu poprzedniego zadania", - "Another library was opened: nothing was done": "Otwarto inną bibliotekę: nic nie zrobiono" + "Another library was opened: nothing was done": "Otwarto inną bibliotekę: nic nie zrobiono", + "Starts next": "Rozpocznie się jako następne" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 25c8a28b770..90a6c23d291 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", "Queued: it starts after {n} more": "Na fila: começa depois de mais {n}", - "{n} more missing, left alone: synchronize again to review them": "Faltam mais {n}, deixadas como estavam: sincronize de novo para revisá-las" + "{n} more missing, left alone: synchronize again to review them": "Faltam mais {n}, deixadas como estavam: sincronize de novo para revisá-las", + "Starts after {n} more": "Começa depois de mais {n}", + "Remove from Queue: {label}": "Remover da fila: {label}" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 222fd260f62..e210d177197 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2203,5 +2203,6 @@ "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", "Queued: it starts when the task ahead of it ends": "Na fila: começa quando a tarefa anterior terminar", - "Another library was opened: nothing was done": "Outra biblioteca foi aberta: nada foi feito" + "Another library was opened: nothing was done": "Outra biblioteca foi aberta: nada foi feito", + "Starts next": "Começa em seguida" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index df0cff8badc..0db7b87b32d 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", "Queued: it starts after {n} more": "В очереди: начнётся после ещё {n}", - "{n} more missing, left alone: synchronize again to review them": "Не хватает ещё {n}, оставлены как есть: синхронизируйте снова, чтобы их просмотреть" + "{n} more missing, left alone: synchronize again to review them": "Не хватает ещё {n}, оставлены как есть: синхронизируйте снова, чтобы их просмотреть", + "Starts after {n} more": "Начнётся после ещё {n}", + "Remove from Queue: {label}": "Убрать из очереди: {label}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index fe8bfda9e90..dabb4c10039 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2350,5 +2350,6 @@ "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", "Queued: it starts when the task ahead of it ends": "В очереди: начнётся, когда закончится задача перед ней", - "Another library was opened: nothing was done": "Открыта другая библиотека: ничего не сделано" + "Another library was opened: nothing was done": "Открыта другая библиотека: ничего не сделано", + "Starts next": "Начнётся следующей" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 3493eda8222..06ce7f8a7f0 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", "Queued: it starts after {n} more": "I kö: startar efter {n} till", - "{n} more missing, left alone: synchronize again to review them": "{n} fler saknas och lämnades orörda: synkronisera igen för att granska dem" + "{n} more missing, left alone: synchronize again to review them": "{n} fler saknas och lämnades orörda: synkronisera igen för att granska dem", + "Starts after {n} more": "Startar efter {n} till", + "Remove from Queue: {label}": "Ta bort från kön: {label}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76983ad20f6..16b96132f52 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2430,5 +2430,6 @@ "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", "Import dropped files without review": "Importera släppta filer utan granskning", "Queued: it starts when the task ahead of it ends": "I kö: startar när uppgiften före är klar", - "Another library was opened: nothing was done": "Ett annat bibliotek öppnades: ingenting gjordes" + "Another library was opened: nothing was done": "Ett annat bibliotek öppnades: ingenting gjordes", + "Starts next": "Startar härnäst" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 209fdd16b83..a86f38de075 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", "Queued: it starts after {n} more": "У черзі: почнеться після ще {n}", - "{n} more missing, left alone: synchronize again to review them": "Бракує ще {n}, залишено як є: синхронізуйте знову, щоб їх переглянути" + "{n} more missing, left alone: synchronize again to review them": "Бракує ще {n}, залишено як є: синхронізуйте знову, щоб їх переглянути", + "Starts after {n} more": "Почнеться після ще {n}", + "Remove from Queue: {label}": "Прибрати з черги: {label}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 1f0a5f99f44..cf2ff1448dd 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2355,5 +2355,6 @@ "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", "Queued: it starts when the task ahead of it ends": "У черзі: почнеться, коли завершиться попереднє завдання", - "Another library was opened: nothing was done": "Відкрито іншу бібліотеку: нічого не зроблено" + "Another library was opened: nothing was done": "Відкрито іншу бібліотеку: нічого не зроблено", + "Starts next": "Почнеться наступним" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index ad050727993..c03c61896f1 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", "Queued: it starts after {n} more": "Trong hàng đợi: bắt đầu sau {n} tác vụ nữa", - "{n} more missing, left alone: synchronize again to review them": "Còn {n} mục bị thiếu được giữ nguyên: hãy đồng bộ hóa lại để xem xét" + "{n} more missing, left alone: synchronize again to review them": "Còn {n} mục bị thiếu được giữ nguyên: hãy đồng bộ hóa lại để xem xét", + "Starts after {n} more": "Bắt đầu sau {n} tác vụ nữa", + "Remove from Queue: {label}": "Xóa khỏi hàng đợi: {label}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c71b2e3d5bd..9d127ff71a1 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2236,5 +2236,6 @@ "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", "Queued: it starts when the task ahead of it ends": "Trong hàng đợi: bắt đầu khi tác vụ trước nó kết thúc", - "Another library was opened: nothing was done": "Đã mở thư viện khác: không có gì được thực hiện" + "Another library was opened: nothing was done": "Đã mở thư viện khác: không có gì được thực hiện", + "Starts next": "Bắt đầu tiếp theo" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index f16499d8b53..4bb13622240 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", "Queued: it starts after {n} more": "已加入队列:再过 {n} 个后开始", - "{n} more missing, left alone: synchronize again to review them": "还有 {n} 个缺失,未作处理:再次同步以检查它们" + "{n} more missing, left alone: synchronize again to review them": "还有 {n} 个缺失,未作处理:再次同步以检查它们", + "Starts after {n} more": "再过 {n} 个后开始", + "Remove from Queue: {label}": "从队列中移除:{label}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index e13758890f6..afdb746b3f8 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2201,5 +2201,6 @@ "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", "Queued: it starts when the task ahead of it ends": "已加入队列:前一个任务结束后开始", - "Another library was opened: nothing was done": "已打开另一个图库:未执行任何操作" + "Another library was opened: nothing was done": "已打开另一个图库:未执行任何操作", + "Starts next": "接下来开始" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 5230ccec2ae..35a436c7c26 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -307,5 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", "Queued: it starts after {n} more": "已加入佇列:再過 {n} 個後開始", - "{n} more missing, left alone: synchronize again to review them": "還有 {n} 個遺失,未作處理:再次同步以檢查它們" + "{n} more missing, left alone: synchronize again to review them": "還有 {n} 個遺失,未作處理:再次同步以檢查它們", + "Starts after {n} more": "再過 {n} 個後開始", + "Remove from Queue: {label}": "從佇列中移除:{label}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 692f9c55919..006e49fc447 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2158,5 +2158,6 @@ "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", "Queued: it starts when the task ahead of it ends": "已加入佇列:前一個工作結束後開始", - "Another library was opened: nothing was done": "已開啟另一個圖庫:未執行任何操作" + "Another library was opened: nothing was done": "已開啟另一個圖庫:未執行任何操作", + "Starts next": "接下來開始" } diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index 0aadc198347..581bf56ea3a 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -1,7 +1,8 @@ //! The activity stack (issue #345): every long-running task in one place, floating in the top-left corner under the //! top bar while something runs — a row each with its name, a progress bar, what it is working on, and ✕ for the ones -//! that can be cancelled. The tasks come from the engine's registry ([`lightcraft_engine::activity`]); ✕ runs -//! `activity.cancel` like any other frontend would. +//! that can be cancelled. A task waiting in line behind another of its lane has a row too, at once: its name, when it +//! starts, and ✕ to take it out of the line. The tasks come from the engine's registry +//! ([`lightcraft_engine::activity`]); ✕ runs `activity.cancel` like any other frontend would. use egui::{Align, Layout, Margin, RichText, Sense, Stroke, pos2, vec2}; use lightcraft_engine::activity::{TaskInfo, Unit}; @@ -55,15 +56,16 @@ fn detail_line(t: &TaskInfo) -> String { /// Draw the stack (called every frame, after the panels and dialogs). pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { - // (a task waiting in line has nothing to show yet and no progress to draw: agents see it in `activity.list`) - let all: Vec = app.session.activity.list().into_iter().filter(|t| !t.waiting).collect(); + // (a task waiting in line has a row without a bar: its name, when it starts, and ✕) + let all: Vec = app.session.activity.list(); if all.is_empty() { app.activity_expanded = false; return; } // look again soon: a young task becomes due, bars move ctx.request_repaint_after(std::time::Duration::from_millis(100)); - let tasks: Vec<&TaskInfo> = all.iter().filter(|t| t.age_ms >= SHOW_AFTER_MS).collect(); + // a running task shows once it has run a while; one waiting in line was just asked for, so it shows now + let tasks: Vec<&TaskInfo> = all.iter().filter(|t| t.waiting || t.age_ms >= SHOW_AFTER_MS).collect(); if tasks.is_empty() { return; } @@ -116,7 +118,7 @@ pub(crate) fn cancel(app: &mut LightcraftApp, id: u64) { let _ = app.session.execute("activity.cancel", &json!({"id": id})); } -/// One task: name and ✕, the bar, the detail line. True when ✕ was clicked. +/// One task: name and ✕, the bar, the detail line (a waiting one: name and ✕, when it starts). True when ✕ was clicked. fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { let mut clicked = false; let r = ui.vertical(|ui| { @@ -131,14 +133,20 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { }); if cross { let (rect, resp) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::click()); - crate::widgets::announce(&resp, crate::i18n::tr("Cancel")); + let name = if task.waiting { tr_format!("Remove from Queue: {label}", label = tr(&task.label)) } else { tr("Cancel").to_string() }; + crate::widgets::announce(&resp, name.clone()); paint(ui.painter(), rect.shrink(2.0), Icon::Close, if resp.hovered() { t.text } else { t.icon }); register(ui, format!("activity:cancel:{}", task.id), rect); - clicked = resp.on_hover_text(tr("Cancel")).clicked(); + clicked = resp.on_hover_text(name).clicked(); } }); - bar(ui, task, width); - let line = detail_line(task); + let line = if task.waiting { + // (counted as the Queued toast counts: the waiting tasks ahead of it, after the running one) + if task.place <= 1 { tr("Starts next").to_string() } else { tr_format!("Starts after {n} more", n = task.place - 1) } + } else { + bar(ui, task, width); + detail_line(task) + }; if !line.is_empty() { ui.add(egui::Label::new(RichText::new(line).font(t.font(11.0)).color(t.text_dim)).truncate()); } diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index decbc472915..02505025d9c 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -538,10 +538,10 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.ui.toast.is_none()); } -/// Given a preview build running and another waiting in line behind it, then the stack shows the running build only, -/// and the waiting one starts by itself, in a frame, when the build ahead of it ends. +/// Given a preview build running and another waiting in line behind it, then the stack shows both (the waiting one +/// with ✕), and the waiting one starts by itself, in a frame, when the build ahead of it ends. #[test] -fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { +fn a_task_waiting_in_line_has_a_row_and_starts_when_the_lane_frees() { use lightcraft_engine::cmd::previews::PreviewBuild; use std::sync::atomic::Ordering; @@ -555,7 +555,10 @@ fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { assert_eq!(h.app.session.activity.list().len(), 2); wait_visible(&mut h); assert!(has(&h, &format!("activity:row:{}", running.id()))); - assert!(!has(&h, &format!("activity:row:{waiting}")) && rows(&h) == 1, "a waiting task draws no row"); + assert!( + has(&h, &format!("activity:row:{waiting}")) && has(&h, &format!("activity:cancel:{waiting}")) && rows(&h) == 2, + "a waiting task draws a row with ✕" + ); // the lane frees with no command asked: the frame loop starts it build.finished.store(true, Ordering::Release); drop(running); diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index a4094d8a1ee..76e1e28450e 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -849,6 +849,39 @@ fn a_direct_drop_while_an_import_runs_waits_in_line() { assert_eq!(photos(&h), 2, "the dropped folder's two photos"); } +/// Given an import that runs and two more waiting in line behind it, then each waiting one has a row saying when it +/// starts and a ✕ named for it; ✕ takes that one out of the line and leaves the running import alone. +#[test] +fn a_waiting_import_shows_a_row_and_its_cross_takes_it_out_of_the_line() { + let dir = Scratch::new("waiting-rows"); + let mut h = app(&dir); + h.app.ui.settings.import_dropped_directly = true; + write_png(&dir.path("more/c.png"), 3); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + drop_files(&mut h, &[dir.path("trip")], false); + drop_files(&mut h, &[dir.path("more")], false); + let waiting = h.app.session.activity.waiting(); + assert_eq!(waiting.len(), 2, "{waiting:?}"); + let (first, second) = (waiting[0].id, waiting[1].id); + for _ in 0..3 { + h.step(); + } + let drawn = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + assert!(drawn(&h, &format!("activity:row:{first}")) && drawn(&h, &format!("activity:row:{second}")), "a row each: {:?}", h.app.widgets); + assert!(said(&h, "Starts next") && said(&h, "Starts after 1 more"), "{:?}", h.painted_text()); + let cross = format!("activity:cancel:{second}"); + assert!(drawn(&h, &cross), "✕ on the waiting row"); + assert_eq!(h.request("ui.clickWidget", json!({"id": cross}), T)["ok"], true); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.app.session.activity.waiting().iter().map(|t| t.id).collect::>(), vec![first], "only the first still waits"); + assert!(!drawn(&h, &format!("activity:row:{second}")), "its row is gone"); + assert!(h.app.session.activity.list().iter().any(|t| !t.waiting && t.kind == "import"), "the running import is untouched"); + assert!(!hold.is_cancelled()); + drop(hold); +} + /// A drop while a scan runs would open a review whose OK replaces the import the scan starts: it is /// refused instead, and the card says so. #[test] diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 2299e894dcd..bbfc90ea45a 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -71,7 +71,7 @@ A call that sets `queue: true` while its lane is busy does not fail: `Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, -`place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out +`place`, `lane`); the activity stack in the app draws a waiting task too, at once, as a row without a bar ("Starts next" or "Starts after N more") with ✕, "Remove from Queue", which runs `activity.cancel`. `activity.cancel` takes a waiting task out of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged (the app's own, an import or a Synchronize Folder, also says why in a toast) and the next in line goes on. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 78eee63fcbf..74e1529d8a6 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder wait for each other instead of refusing; earlier: LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder wait for each other instead of refusing, and a waiting task shows in the activity stack with ✕ to remove it; earlier: LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -461,7 +461,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list; an import and a Synchronize Folder never run at once: one asked for while the other runs waits in line and starts by itself (the library lane, `activity::Lane`). No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list; an import and a Synchronize Folder never run at once: one asked for while the other runs waits in line and starts by itself (the library lane, `activity::Lane`); a task waiting in line has a row in the stack at once, with when it starts and ✕ (Remove from Queue) to take it out of the line. No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | @@ -959,4 +959,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | -| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and acts only on the photos its dialog showed; status unchanged (✅) | +| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and acts only on the photos its dialog showed; every waiting task has a row in the activity stack (when it starts, ✕ to remove it); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 6c330181bfb..f9e11d5d19c 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -8,6 +8,7 @@ was queued. Before, it was refused ("Wait for the import to finish", "A folder is being synchronized"). - Photos dropped on the window, or an import review confirmed, while another import runs also wait in line instead of being refused with "An import is running"; a drop is still refused while a folder is being scanned for the review. +- A task waiting in line shows in the activity stack at once: its name, "Starts next" or "Starts after N more", and ✕ to take it out of the line, so a mistaken one can be withdrawn. This holds for a waiting preview build too. - A waiting import checks for duplicates against the library as it is when its turn comes, so nothing is added twice. - A waiting Synchronize Folder looks at its folder again when its turn comes. It removes or relinks only the photos its dialog showed: one that went missing while it waited is left alone, and the message at the end says so. From 2eda69ab35c3e291d5d839811bd49dd097fc00cc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 18:47:35 -0400 Subject: [PATCH 08/55] LR-BEHAV-BG-TASKS: review fixes: Auto Import waits in line, a waiting synchronize reads only the sidecars its dialog showed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto Import's listing that comes in while the library lane is taken no longer drops the files (the engine has noted them as tried): they wait in line, quietly, as an Auto Import, and a full line leaves the folder to its next listing. A waiting Synchronize Folder reads sidecars of only the photos its dialog listed, like missing and moved ones, and the end says how many were left alone in words that fit all three ("Left alone: N"). A synchronize refused for a full line keeps what its dialog showed. Another library opening ends a waiting synchronize's rescan at once. The import review's OK waits behind a Local folder being read instead of being refused. Counts of 1 read correctly in cs, fr, it and pl. The ✕ names are tested. Co-Authored-By: Claude --- crates/engine/src/sync.rs | 19 +++-- crates/engine/src/tests/sync.rs | 15 ++++ crates/ui-egui/locales/cs-formats.json | 6 +- crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de-formats.json | 2 +- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es-formats.json | 2 +- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi-formats.json | 2 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr-formats.json | 6 +- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id-formats.json | 2 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it-formats.json | 6 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja-formats.json | 2 +- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka-formats.json | 2 +- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl-formats.json | 6 +- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br-formats.json | 2 +- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru-formats.json | 2 +- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv-formats.json | 2 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk-formats.json | 2 +- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi-formats.json | 2 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans-formats.json | 2 +- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant-formats.json | 2 +- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/app/frame.rs | 18 +--- crates/ui-egui/src/dialogs/import.rs | 2 +- crates/ui-egui/src/dialogs/import/scan.rs | 41 +++++++-- crates/ui-egui/src/dialogs/import/task.rs | 12 +-- crates/ui-egui/src/panels/activity.rs | 7 +- crates/ui-egui/src/sync.rs | 78 +++++++++++------ crates/ui-egui/src/tests/activity.rs | 4 + crates/ui-egui/src/tests/drop_import.rs | 66 +++++++++++++++ crates/ui-egui/src/tests/sync.rs | 93 ++++++++++++++++++++- docs/background-tasks.md | 14 ++-- docs/parity-checklist.md | 2 +- docs/whats-new.md | 11 ++- 48 files changed, 349 insertions(+), 134 deletions(-) diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index f20ad9c95ec..6f8be5cbadb 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -302,13 +302,13 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { } /// Whether a photo is the same as far as synchronizing goes: its file, its place in the library -/// and what a sidecar is compared with. Face and pet regions found in the background meanwhile -/// don't make a scan stale. +/// and what a sidecar is compared with. Face and pet regions and the focus point, which the +/// background searches fill in meanwhile, don't make a scan stale. fn same_for_sync(a: &Arc, b: &Arc) -> bool { if Arc::ptr_eq(a, b) { return true; } - let meta = |p: &Photo| lightcraft_catalog::Meta { regions: Vec::new(), ..p.meta.clone() }; + let meta = |p: &Photo| lightcraft_catalog::Meta { regions: Vec::new(), focus: None, ..p.meta.clone() }; (&a.source, a.deleted, a.local, a.copy_of, &a.content_hash, a.file_size, a.rating, a.flag, a.label, &a.captured, &a.edited, &a.develop) == (&b.source, b.deleted, b.local, b.copy_of, &b.content_hash, b.file_size, b.rating, b.flag, b.label, &b.captured, &b.edited, &b.develop) && meta(a) == meta(b) @@ -584,13 +584,18 @@ impl Session { if lightcraft_catalog::query::folder_key(&c.path) != lightcraft_catalog::query::folder_key(path) { return None; } - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + self.scan_is_current(&c).then_some(c) + } + + /// Whether the library still holds the photos `changes` saw in its folder, none of them changed since: a scan that + /// ran on a worker thread from a snapshot (a waiting synchronize's) is acted on only while this holds. + pub fn scan_is_current(&self, changes: &FolderChanges) -> bool { + let f = Filter { library_folder: Some(changes.path.clone()), ..Default::default() }; let mut now: Vec = self.catalog.query(&f, &Sort::default()); - let mut then: Vec = c.seen.iter().map(|p| p.id).collect(); + let mut then: Vec = changes.seen.iter().map(|p| p.id).collect(); now.sort(); then.sort(); - let unchanged = now == then && c.seen.iter().all(|p| self.catalog.photo(p.id).is_some_and(|q| same_for_sync(p, q))); - unchanged.then_some(c) + now == then && changes.seen.iter().all(|p| self.catalog.photo(p.id).is_some_and(|q| same_for_sync(p, q))) } } diff --git a/crates/engine/src/tests/sync.rs b/crates/engine/src/tests/sync.rs index 8b1ec4f6721..1eb651bca1f 100644 --- a/crates/engine/src/tests/sync.rs +++ b/crates/engine/src/tests/sync.rs @@ -566,6 +566,21 @@ fn face_regions_found_meanwhile_leave_the_scan_current() { assert_eq!(r["imported"], 1, "{r}"); } +#[test] +fn a_focus_point_found_meanwhile_leaves_the_scan_current() { + let dir = Scratch::new("focus"); + let mut s = library(&dir); + write_png(&dir.path("trip/c.png"), 3); + scan(&mut s, &dir.path("trip")); + // the background focus-point scan commits a point for a photo of the folder + let a = s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id; + let mut meta = s.catalog.photo(a).unwrap().meta.clone(); + meta.focus = Some(lightcraft_meta::FocusPoint { rect: Default::default(), mode: None, area: None, tracking: None }); + s.catalog.apply(lightcraft_catalog::Op::SetMeta { id: a, meta: Box::new(meta) }).unwrap(); + let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "scanned": true})).unwrap(); + assert_eq!(r["imported"], 1, "{r}"); +} + /// Synchronizing in halves, as the app does it: readied on the UI thread without touching the /// disk, the work (every file read) on a worker, each step committed back on the UI thread. fn sync_in_halves(s: &mut Session, path: &str, choice: crate::sync::SyncChoice) -> crate::sync::SyncReport { diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index baca445ebb6..0b49424366b 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -306,8 +306,8 @@ "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", - "Queued: it starts after {n} more": "Ve frontě: začne po {n} dalších", - "{n} more missing, left alone: synchronize again to review them": "{n} dalších chybí, ponecháno beze změny: pro kontrolu synchronizujte znovu", - "Starts after {n} more": "Začne po {n} dalších", + "Queued: it starts after {n} more": "Ve frontě: začne po dalších úlohách: {n}", + "Left alone: {n} (synchronize again to review them)": "Ponecháno: {n} (pro kontrolu synchronizujte znovu)", + "Starts after {n} more": "Začne po dalších úlohách: {n}", "Remove from Queue: {label}": "Odebrat z fronty: {label}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 2ffc8846ee3..5d83f25f8a5 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -16,7 +16,6 @@ "= exactly": "= přesně", "A blank template keeps the original names.": "Prázdná šablona zachová původní názvy.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Fotografie v tomto zobrazení skrývá filtr: změňte jej nebo jej zrušte (Zobrazení → Zrušit filtry)", - "A folder is being synchronized": "Probíhá synchronizace složky", "A keyword set needs a name": "Sada klíčových slov musí mít název", "A one-time download of about": "Jednorázové stažení přibližně", "A pen's pressure sets the size and flow of the brush": "Přítlak pera určuje velikost a tok štětce", @@ -2023,7 +2022,6 @@ "Visualize range": "Zobrazit rozsah", "Vivid": "Živé", "Vivid Pop": "Živé zvýraznění", - "Wait for the import to finish": "Počkejte na dokončení importu", "Waiting to start…": "Čekání na spuštění…", "Warm Film": "Teplý film", "Warm Glow": "Teplá záře", @@ -2410,5 +2408,6 @@ "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", "Queued: it starts when the task ahead of it ends": "Ve frontě: začne, až skončí úloha před ní", "Another library was opened: nothing was done": "Byla otevřena jiná knihovna: nic se neprovedlo", + "Photos of the folder changed while it was read: nothing was done": "Fotografie ve složce se během čtení změnily: nic se neprovedlo", "Starts next": "Začne jako další" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index c0aa7b83095..5b5b38fa33f 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", "Queued: it starts after {n} more": "In der Warteschlange: startet nach {n} weiteren", - "{n} more missing, left alone: synchronize again to review them": "{n} weitere fehlen und blieben unangetastet: zum Prüfen erneut synchronisieren", + "Left alone: {n} (synchronize again to review them)": "Unangetastet: {n} (zum Prüfen erneut synchronisieren)", "Starts after {n} more": "Startet nach {n} weiteren", "Remove from Queue: {label}": "Aus der Warteschlange entfernen: {label}" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index a809ebe4c3d..7038fcdeba9 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2078,8 +2078,6 @@ "Stopped": "Angehalten", "Stopped by an error (see the log)": "Durch einen Fehler angehalten (siehe Protokoll)", "Not saved": "Nicht gespeichert", - "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", - "Wait for the import to finish": "Warte, bis der Import abgeschlossen ist", "Appearance": "Erscheinungsbild", "Appearance Mode": "Erscheinungsmodus", "Sync with System": "Mit System synchronisieren", @@ -3442,5 +3440,6 @@ "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", "Queued: it starts when the task ahead of it ends": "In der Warteschlange: startet, wenn die Aufgabe davor endet", "Another library was opened: nothing was done": "Eine andere Bibliothek wurde geöffnet: es wurde nichts getan", + "Photos of the folder changed while it was read: nothing was done": "Fotos des Ordners haben sich beim Lesen geändert: es wurde nichts getan", "Starts next": "Startet als Nächstes" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 405df93e588..aad6ee5face 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", "Queued: it starts after {n} more": "En cola: empieza tras {n} más", - "{n} more missing, left alone: synchronize again to review them": "Faltan {n} más, sin tocar: sincroniza de nuevo para revisarlas", + "Left alone: {n} (synchronize again to review them)": "Sin tocar: {n} (sincroniza de nuevo para revisarlos)", "Starts after {n} more": "Empieza tras {n} más", "Remove from Queue: {label}": "Quitar de la cola: {label}" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 3dc670f7089..49d1d977d4c 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2106,8 +2106,6 @@ "Stopped": "Detenido", "Stopped by an error (see the log)": "Detenido por un error (ver el registro)", "Not saved": "Sin guardar", - "A folder is being synchronized": "Se está sincronizando una carpeta", - "Wait for the import to finish": "Esperar a que termine la importación", "Appearance": "Apariencia", "Appearance Mode": "Modo de apariencia", "Sync with System": "Sincronizar con el sistema", @@ -2360,5 +2358,6 @@ "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", "Queued: it starts when the task ahead of it ends": "En cola: empieza cuando termine la tarea anterior", "Another library was opened: nothing was done": "Se abrió otra biblioteca: no se hizo nada", + "Photos of the folder changed while it was read: nothing was done": "Las fotos de la carpeta cambiaron mientras se leía: no se hizo nada", "Starts next": "Empieza la siguiente" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index e6caa87a913..8e85c136fb2 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", "Queued: it starts after {n} more": "Jonossa: alkaa {n} muun jälkeen", - "{n} more missing, left alone: synchronize again to review them": "{n} muuta puuttuu ja jätettiin ennalleen: synkronoi uudelleen tarkistaaksesi ne", + "Left alone: {n} (synchronize again to review them)": "Jätetty ennalleen: {n} (synkronoi uudelleen tarkistaaksesi)", "Starts after {n} more": "Alkaa {n} muun jälkeen", "Remove from Queue: {label}": "Poista jonosta: {label}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e818f109e0b..09b3a15bf54 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -21,7 +21,6 @@ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Tumma liuskekivitausta, jossa kunkin kuvan alla valotus, ISO ja polttoväli sekä kamera ja objektiivi.", "A face model uses the GPU only when a check shows it gives the same results faster.": "Kasvomalli käyttää GPU:ta vain, jos tarkistus osoittaa sen antavan samat tulokset nopeammin.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Suodatin piilottaa tämän näkymän kuvat: muuta sitä tai tyhjennä se (Näytä → Tyhjennä suodattimet)", - "A folder is being synchronized": "Kansiota synkronoidaan", "A keyword set needs a name": "Avainsanajoukolle täytyy antaa nimi", "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Vaaleanharmaa seinä, valkoinen paspis ja pehmeä varjo; kuvateksti ja luokitus kuvan alla.", "A one-time download of about": "Kertaluonteinen lataus, noin", @@ -2146,7 +2145,6 @@ "Visualize range": "Havainnollista alue", "Vivid": "Eloisa", "Vivid Pop": "Eloisa pop", - "Wait for the import to finish": "Odota tuonnin valmistumista", "Waiting to start…": "Odotetaan käynnistymistä…", "Warm Film": "Lämmin filmi", "Warm Glow": "Lämmin hehku", @@ -2329,5 +2327,6 @@ "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", "Queued: it starts when the task ahead of it ends": "Jonossa: alkaa, kun sen edellä oleva tehtävä päättyy", "Another library was opened: nothing was done": "Toinen kirjasto avattiin: mitään ei tehty", + "Photos of the folder changed while it was read: nothing was done": "Kansion valokuvat muuttuivat lukemisen aikana: mitään ei tehty", "Starts next": "Alkaa seuraavaksi" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index b3d7d0a92d7..b8442d2131e 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -306,8 +306,8 @@ "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", - "Queued: it starts after {n} more": "En file : démarre après {n} autres", - "{n} more missing, left alone: synchronize again to review them": "{n} autres manquantes, laissées telles quelles : synchronisez à nouveau pour les examiner", - "Starts after {n} more": "Démarre après {n} autres", + "Queued: it starts after {n} more": "En file : démarre après {n} autre(s) tâche(s)", + "Left alone: {n} (synchronize again to review them)": "Laissés tels quels : {n} (synchronisez à nouveau pour les examiner)", + "Starts after {n} more": "Démarre après {n} autre(s) tâche(s)", "Remove from Queue: {label}": "Retirer de la file : {label}" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index ef1faa5f8d6..da8ab1885d1 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1914,8 +1914,6 @@ "Stopped": "Arrêté", "Stopped by an error (see the log)": "Arrêté par une erreur (voir le journal)", "Not saved": "Non enregistré", - "A folder is being synchronized": "Un dossier est en cours de synchronisation", - "Wait for the import to finish": "Attendez la fin de l'importation", "Show less": "Afficher moins", "Quit while tasks are running?": "Quitter pendant que des tâches sont en cours ?", "Exporting contact sheet": "Exportation de la planche-contact", @@ -2392,5 +2390,6 @@ "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", "Queued: it starts when the task ahead of it ends": "En file : démarre à la fin de la tâche précédente", "Another library was opened: nothing was done": "Une autre bibliothèque a été ouverte : rien n’a été fait", + "Photos of the folder changed while it was read: nothing was done": "Les photos du dossier ont changé pendant la lecture : rien n’a été fait", "Starts next": "Démarre ensuite" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 22637a1805c..c331f292705 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", "Queued: it starts after {n} more": "Dalam antrean: dimulai setelah {n} lagi", - "{n} more missing, left alone: synchronize again to review them": "{n} lagi hilang dan dibiarkan: sinkronkan lagi untuk memeriksanya", + "Left alone: {n} (synchronize again to review them)": "Dibiarkan: {n} (sinkronkan lagi untuk meninjau)", "Starts after {n} more": "Dimulai setelah {n} lagi", "Remove from Queue: {label}": "Hapus dari antrean: {label}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 00d6d0753ec..16131bb8e53 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -22,7 +22,6 @@ "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "Latar abu-abu gelap berisi eksposur, ISO, dan panjang fokus, lalu kamera dan lensa, di bawah setiap foto.", "A face model uses the GPU only when a check shows it gives the same results faster.": "Model wajah hanya menggunakan GPU jika pengujian menunjukkan hasilnya sama tetapi lebih cepat.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Filter menyembunyikan foto di tampilan ini: ubah atau hapus filternya (Tampilan → Hapus filter)", - "A folder is being synchronized": "Folder sedang disinkronkan", "A keyword set needs a name": "Set kata kunci harus diberi nama", "A light grey wall with a white mat and a soft shadow; the caption and the rating under the photo.": "Dinding abu-abu muda dengan paspartu putih dan bayangan lembut; keterangan dan rating di bawah foto.", "A one-time download of about": "Unduhan satu kali, sekitar", @@ -2139,7 +2138,6 @@ "Visualize range": "Visualisasikan rentang", "Vivid": "Cerah", "Vivid Pop": "Warna Hidup", - "Wait for the import to finish": "Tunggu hingga impor selesai", "Waiting to start…": "Menunggu untuk dimulai…", "Warm Film": "Film Hangat", "Warm Glow": "Hangat Bercahaya", @@ -2341,5 +2339,6 @@ "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", "Queued: it starts when the task ahead of it ends": "Dalam antrean: dimulai saat tugas di depannya selesai", "Another library was opened: nothing was done": "Pustaka lain dibuka: tidak ada yang dilakukan", + "Photos of the folder changed while it was read: nothing was done": "Foto di folder berubah saat dibaca: tidak ada yang dilakukan", "Starts next": "Dimulai berikutnya" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index e5d958558d7..52b73fc3788 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -306,8 +306,8 @@ "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", - "Queued: it starts after {n} more": "In coda: parte dopo altre {n}", - "{n} more missing, left alone: synchronize again to review them": "Ne mancano altre {n}, lasciate com'erano: sincronizza di nuovo per esaminarle", - "Starts after {n} more": "Parte dopo altre {n}", + "Queued: it starts after {n} more": "In coda: parte dopo altre attività ({n})", + "Left alone: {n} (synchronize again to review them)": "Lasciati invariati: {n} (sincronizza di nuovo per rivederli)", + "Starts after {n} more": "Parte dopo altre attività ({n})", "Remove from Queue: {label}": "Rimuovi dalla coda: {label}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 28d4a80c322..b467fadc7d7 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2034,8 +2034,6 @@ "Stopped": "Interrotto", "Stopped by an error (see the log)": "Interrotta da un errore (vedi il log)", "Not saved": "Non salvato", - "A folder is being synchronized": "Una cartella è in sincronizzazione", - "Wait for the import to finish": "Aspetta che l'importazione finisca", "Appearance": "Aspetto", "Appearance Mode": "Modalità aspetto", "Sync with System": "Segui il sistema", @@ -2363,5 +2361,6 @@ "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", "Queued: it starts when the task ahead of it ends": "In coda: parte quando finisce l'attività precedente", "Another library was opened: nothing was done": "È stata aperta un'altra libreria: non è stato fatto nulla", + "Photos of the folder changed while it was read: nothing was done": "Le foto della cartella sono cambiate durante la lettura: non è stato fatto nulla", "Starts next": "Parte subito dopo" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 63366fe394c..ff5030690b0 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", "Queued: it starts after {n} more": "キューに追加: あと {n} 件の後に開始します", - "{n} more missing, left alone: synchronize again to review them": "ほかに {n} 件が見つからず、そのままにしました: 確認するにはもう一度同期してください", + "Left alone: {n} (synchronize again to review them)": "そのまま: {n} 件(再度同期して確認してください)", "Starts after {n} more": "あと {n} 件の後に開始します", "Remove from Queue: {label}": "キューから削除: {label}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 2709a330ca9..6c97e1e93dd 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1926,8 +1926,6 @@ "Stopped": "停止しました", "Stopped by an error (see the log)": "エラーで停止しました(ログを参照)", "Not saved": "保存されていません", - "A folder is being synchronized": "フォルダを同期中です", - "Wait for the import to finish": "読み込みが終わるまでお待ちください", "Appearance": "外観", "Appearance Mode": "外観モード", "Sync with System": "システムと同期", @@ -2358,5 +2356,6 @@ "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", "Queued: it starts when the task ahead of it ends": "キューに追加: 前のタスクが終わると開始します", "Another library was opened: nothing was done": "別のライブラリが開かれました: 何も行われていません", + "Photos of the folder changed while it was read: nothing was done": "読み取り中にフォルダ内の写真が変更されました: 何も行われていません", "Starts next": "次に開始します" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 03b886141a2..ef610bd14cc 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", "Queued: it starts after {n} more": "რიგშია: დაიწყება კიდევ {n}-ის შემდეგ", - "{n} more missing, left alone: synchronize again to review them": "კიდევ {n} აკლია და ხელუხლებლად დარჩა: გადასახედად ხელახლა მოახდინეთ სინქრონიზაცია", + "Left alone: {n} (synchronize again to review them)": "უცვლელი დარჩა: {n} (გადასახედად თავიდან დაასინქრონეთ)", "Starts after {n} more": "დაიწყება კიდევ {n}-ის შემდეგ", "Remove from Queue: {label}": "რიგიდან ამოღება: {label}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 98f22f908f9..fc1bc2983f5 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -63,7 +63,6 @@ "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "ცვლილება, რომლის დისკზე შენახვაც ვერ ხერხდება (სავსე ან გამორთული დისკი), აღარ რჩება შეუმჩნეველი: ბრძანება იტყობინება", "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "ფანჯარაზე მაღალი დიალოგი აღარ გადის მის საზღვრებს გარეთ (ხარვეზი #781): 1366×768 ეკრანზე ექსპორტის დიალოგის სათაური", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "ფილტრი მალავს ამ ხედის ფოტოებს: შეცვალეთ ან გაასუფთავეთ იგი (ხედი → ფილტრების გასუფთავება)", - "A folder is being synchronized": "საქაღალდე სინქრონიზდება", "A keyword set needs a name": "საკვანძო სიტყვების ნაკრებს სახელი სჭირდება", "A label follows its folder when it is renamed or moved in LightCraft, together with the labels of the folders": "იარლიყი თავის საქაღალდეს მიჰყვება, როცა ის LightCraft-ში გადაერქმევა ან გადაიტანება, მასში მყოფი საქაღალდეების", "A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB": "ბიბლიოთეკა ათასობით პრესეტით (მთლიანად იმპორტირებული Lightroom-ის კოლექცია: 11 000 პრესეტი, 42 MB-იანი", @@ -2237,7 +2236,6 @@ "Visualize range": "დიაპაზონის ვიზუალიზაცია", "Vivid": "ცოცხალი", "Vivid Pop": "ცოცხალი და მკვეთრი", - "Wait for the import to finish": "დაელოდეთ იმპორტის დასრულებას", "Waiting to start…": "დაწყების მოლოდინში…", "Warm Film": "თბილი ფირი", "Warm Glow": "თბილი ნათება", @@ -2736,5 +2734,6 @@ "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი", "Queued: it starts when the task ahead of it ends": "რიგშია: დაიწყება, როცა წინა ამოცანა დასრულდება", "Another library was opened: nothing was done": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა", + "Photos of the folder changed while it was read: nothing was done": "საქაღალდის ფოტოები წაკითხვისას შეიცვალა: არაფერი გაკეთებულა", "Starts next": "დაიწყება შემდეგი" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index c0a741cb28c..ad311891b51 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -306,8 +306,8 @@ "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", - "Queued: it starts after {n} more": "W kolejce: rozpocznie się po {n} kolejnych", - "{n} more missing, left alone: synchronize again to review them": "Brakuje jeszcze {n}, pozostawiono bez zmian: zsynchronizuj ponownie, aby je przejrzeć", - "Starts after {n} more": "Rozpocznie się po {n} kolejnych", + "Queued: it starts after {n} more": "W kolejce: rozpocznie się po kolejnych zadaniach ({n})", + "Left alone: {n} (synchronize again to review them)": "Pominięto: {n} (zsynchronizuj ponownie, aby je sprawdzić)", + "Starts after {n} more": "Rozpocznie się po kolejnych zadaniach ({n})", "Remove from Queue: {label}": "Usuń z kolejki: {label}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index da7a834f42b..5195fa91cd1 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1866,8 +1866,6 @@ "Stopped": "Zatrzymano", "Stopped by an error (see the log)": "Zatrzymano z powodu błędu (zobacz dziennik)", "Not saved": "Nie zapisano", - "A folder is being synchronized": "Trwa synchronizacja folderu", - "Wait for the import to finish": "Poczekaj na zakończenie importu", "Show less": "Pokaż mniej", "Quit while tasks are running?": "Zakończyć, gdy trwają zadania?", "Exporting contact sheet": "Eksportowanie arkusza stykowego", @@ -2285,5 +2283,6 @@ "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", "Queued: it starts when the task ahead of it ends": "W kolejce: rozpocznie się po zakończeniu poprzedniego zadania", "Another library was opened: nothing was done": "Otwarto inną bibliotekę: nic nie zrobiono", + "Photos of the folder changed while it was read: nothing was done": "Zdjęcia w folderze zmieniły się podczas odczytu: nic nie zrobiono", "Starts next": "Rozpocznie się jako następne" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 90a6c23d291..4960090f14f 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", "Queued: it starts after {n} more": "Na fila: começa depois de mais {n}", - "{n} more missing, left alone: synchronize again to review them": "Faltam mais {n}, deixadas como estavam: sincronize de novo para revisá-las", + "Left alone: {n} (synchronize again to review them)": "Deixados como estavam: {n} (sincronize de novo para revisá-los)", "Starts after {n} more": "Começa depois de mais {n}", "Remove from Queue: {label}": "Remover da fila: {label}" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e210d177197..8d58d8e1082 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1924,8 +1924,6 @@ "Stopped": "Interrompido", "Stopped by an error (see the log)": "Interrompido por um erro (veja o log)", "Not saved": "Não salvo", - "A folder is being synchronized": "Uma pasta está sendo sincronizada", - "Wait for the import to finish": "Aguarde a importação terminar", "Appearance": "Aparência", "Appearance Mode": "Modo de aparência", "Sync with System": "Sincronizar com o sistema", @@ -2204,5 +2202,6 @@ "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", "Queued: it starts when the task ahead of it ends": "Na fila: começa quando a tarefa anterior terminar", "Another library was opened: nothing was done": "Outra biblioteca foi aberta: nada foi feito", + "Photos of the folder changed while it was read: nothing was done": "As fotos da pasta mudaram durante a leitura: nada foi feito", "Starts next": "Começa em seguida" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 0db7b87b32d..de63d603eac 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", "Queued: it starts after {n} more": "В очереди: начнётся после ещё {n}", - "{n} more missing, left alone: synchronize again to review them": "Не хватает ещё {n}, оставлены как есть: синхронизируйте снова, чтобы их просмотреть", + "Left alone: {n} (synchronize again to review them)": "Оставлено без изменений: {n} (синхронизируйте снова, чтобы проверить)", "Starts after {n} more": "Начнётся после ещё {n}", "Remove from Queue: {label}": "Убрать из очереди: {label}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index dabb4c10039..dd87893628b 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1637,8 +1637,6 @@ "Stopped": "Остановлено", "Stopped by an error (see the log)": "Остановлено из-за ошибки (см. журнал)", "Not saved": "Не сохранено", - "A folder is being synchronized": "Папка синхронизируется", - "Wait for the import to finish": "Дождитесь завершения импорта", "Appearance": "Оформление", "Appearance Mode": "Режим оформления", "Sync with System": "Как в системе", @@ -2351,5 +2349,6 @@ "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", "Queued: it starts when the task ahead of it ends": "В очереди: начнётся, когда закончится задача перед ней", "Another library was opened: nothing was done": "Открыта другая библиотека: ничего не сделано", + "Photos of the folder changed while it was read: nothing was done": "Фотографии в папке изменились во время чтения: ничего не сделано", "Starts next": "Начнётся следующей" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 06ce7f8a7f0..1e71f5f9a6c 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", "Queued: it starts after {n} more": "I kö: startar efter {n} till", - "{n} more missing, left alone: synchronize again to review them": "{n} fler saknas och lämnades orörda: synkronisera igen för att granska dem", + "Left alone: {n} (synchronize again to review them)": "Lämnade orörda: {n} (synkronisera igen för att granska dem)", "Starts after {n} more": "Startar efter {n} till", "Remove from Queue: {label}": "Ta bort från kön: {label}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 16b96132f52..9a6594fdad3 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -32,7 +32,6 @@ "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "En ändring som inte kan sparas till disk (full eller urkopplad enhet) är inte längre tyst: kommandot rapporterar", "A dark slate backdrop with the exposure, ISO and focal length, then the camera and lens, under each photo.": "En mörk skifferbakgrund med exponering, ISO och brännvidd, sedan kamera och objektiv, under varje foto.", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Ett filter döljer den här vyns foton: ändra det eller rensa det (Visa → Rensa filter)", - "A folder is being synchronized": "En mapp synkroniseras", "a full drive) no longer counts as built and Build Smart Previews replaces it.": "en full enhet) räknas inte längre som byggd och Bygg smarta förhandsgranskningar ersätter den.", "A keyword set needs a name": "En nyckelordsuppsättning behöver ett namn", "A library is open in one program at a time (issue #99): opening a library that LightCraft or `lightcraft-cli` already": "Ett bibliotek kan bara vara öppet i ett program åt gången (ärende #99): att öppna ett bibliotek som LightCraft eller `lightcraft-cli` redan", @@ -2335,7 +2334,6 @@ "Vivid": "Livfull", "Vivid Pop": "Livfull pop", "volumes (Linux, case-sensitive APFS) `img_1.JPG` next to `IMG_1.JPG` is a different photo and the renamed one gets": "volymer (Linux, skiftlägeskänslig APFS) är `img_1.JPG` bredvid `IMG_1.JPG` ett annat foto och det omdöpta får", - "Wait for the import to finish": "Vänta tills importen är klar", "Waiting to start…": "Väntar på att starta…", "Warm Film": "Varm film", "Warm Glow": "Varm glöd", @@ -2431,5 +2429,6 @@ "Import dropped files without review": "Importera släppta filer utan granskning", "Queued: it starts when the task ahead of it ends": "I kö: startar när uppgiften före är klar", "Another library was opened: nothing was done": "Ett annat bibliotek öppnades: ingenting gjordes", + "Photos of the folder changed while it was read: nothing was done": "Fotona i mappen ändrades medan den lästes: ingenting gjordes", "Starts next": "Startar härnäst" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index a86f38de075..045d654b817 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", "Queued: it starts after {n} more": "У черзі: почнеться після ще {n}", - "{n} more missing, left alone: synchronize again to review them": "Бракує ще {n}, залишено як є: синхронізуйте знову, щоб їх переглянути", + "Left alone: {n} (synchronize again to review them)": "Залишено без змін: {n} (синхронізуйте знову, щоб переглянути)", "Starts after {n} more": "Почнеться після ще {n}", "Remove from Queue: {label}": "Прибрати з черги: {label}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index cf2ff1448dd..b4798a7feaf 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2108,8 +2108,6 @@ "Stopped": "Зупинено", "Stopped by an error (see the log)": "Зупинено через помилку (див. журнал)", "Not saved": "Не збережено", - "A folder is being synchronized": "Тека синхронізується", - "Wait for the import to finish": "Дочекайтеся завершення імпорту", "Show less": "Показати менше", "Quit while tasks are running?": "Вийти, поки виконуються завдання?", "Exporting contact sheet": "Експорт аркуша мініатюр", @@ -2356,5 +2354,6 @@ "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", "Queued: it starts when the task ahead of it ends": "У черзі: почнеться, коли завершиться попереднє завдання", "Another library was opened: nothing was done": "Відкрито іншу бібліотеку: нічого не зроблено", + "Photos of the folder changed while it was read: nothing was done": "Фотографії в теці змінилися під час читання: нічого не зроблено", "Starts next": "Почнеться наступним" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index c03c61896f1..14bb4142c36 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", "Queued: it starts after {n} more": "Trong hàng đợi: bắt đầu sau {n} tác vụ nữa", - "{n} more missing, left alone: synchronize again to review them": "Còn {n} mục bị thiếu được giữ nguyên: hãy đồng bộ hóa lại để xem xét", + "Left alone: {n} (synchronize again to review them)": "Để nguyên: {n} (đồng bộ lại để xem xét)", "Starts after {n} more": "Bắt đầu sau {n} tác vụ nữa", "Remove from Queue: {label}": "Xóa khỏi hàng đợi: {label}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 9d127ff71a1..4bc0e984d81 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -26,7 +26,6 @@ "A blank template keeps the original names.": "Mẫu trống giữ tên gốc.", "A change that can't be saved to disk (full or unplugged drive) is no longer silent: the command reports": "Thay đổi không thể lưu ra đĩa (đĩa đầy hoặc đã rút) không còn im lặng: lệnh báo", "A filter is hiding this view's photos: change it, or clear it (View → Clear Filters)": "Bộ lọc đang ẩn ảnh trong chế độ xem này: đổi bộ lọc hoặc xóa (Xem → Xóa bộ lọc)", - "A folder is being synchronized": "Một thư mục đang được đồng bộ", "A keyword set needs a name": "Bộ từ khóa cần một tên", "A library is open in one program at a time (issue #99): opening a library that LightCraft or `lightcraft-cli` already": "Một thư viện chỉ mở trong một chương trình tại một thời điểm (issue #99): mở thư viện mà LightCraft hoặc `lightcraft-cli` đã", "A one-time download of about": "Tải một lần khoảng", @@ -1958,7 +1957,6 @@ "Visualize range": "Hiển thị dải", "Vivid": "Rực rỡ", "Vivid Pop": "Bật rực", - "Wait for the import to finish": "Đợi nhập hoàn tất", "Waiting to start…": "Đang chờ bắt đầu…", "Warm Film": "Phim ấm", "Warm Glow": "Ánh ấm", @@ -2237,5 +2235,6 @@ "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", "Queued: it starts when the task ahead of it ends": "Trong hàng đợi: bắt đầu khi tác vụ trước nó kết thúc", "Another library was opened: nothing was done": "Đã mở thư viện khác: không có gì được thực hiện", + "Photos of the folder changed while it was read: nothing was done": "Ảnh trong thư mục đã thay đổi trong lúc đọc: không có gì được thực hiện", "Starts next": "Bắt đầu tiếp theo" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 4bb13622240..fa961db45e2 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", "Queued: it starts after {n} more": "已加入队列:再过 {n} 个后开始", - "{n} more missing, left alone: synchronize again to review them": "还有 {n} 个缺失,未作处理:再次同步以检查它们", + "Left alone: {n} (synchronize again to review them)": "未处理:{n}(再次同步以查看)", "Starts after {n} more": "再过 {n} 个后开始", "Remove from Queue: {label}": "从队列中移除:{label}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index afdb746b3f8..2fc62f58bd2 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1918,8 +1918,6 @@ "Stopped": "已停止", "Stopped by an error (see the log)": "因错误而停止(见日志)", "Not saved": "未保存", - "A folder is being synchronized": "正在同步文件夹", - "Wait for the import to finish": "请等待导入完成", "Appearance": "外观", "Appearance Mode": "外观模式", "Sync with System": "与系统同步", @@ -2202,5 +2200,6 @@ "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", "Queued: it starts when the task ahead of it ends": "已加入队列:前一个任务结束后开始", "Another library was opened: nothing was done": "已打开另一个图库:未执行任何操作", + "Photos of the folder changed while it was read: nothing was done": "读取期间文件夹中的照片发生了变化:未执行任何操作", "Starts next": "接下来开始" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 35a436c7c26..b40a6592281 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -307,7 +307,7 @@ "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", "Queued: it starts after {n} more": "已加入佇列:再過 {n} 個後開始", - "{n} more missing, left alone: synchronize again to review them": "還有 {n} 個遺失,未作處理:再次同步以檢查它們", + "Left alone: {n} (synchronize again to review them)": "未處理:{n}(再次同步以檢視)", "Starts after {n} more": "再過 {n} 個後開始", "Remove from Queue: {label}": "從佇列中移除:{label}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 006e49fc447..2a99cb4b941 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1924,8 +1924,6 @@ "Stopped": "已停止", "Stopped by an error (see the log)": "因錯誤而停止(請見記錄)", "Not saved": "未儲存", - "A folder is being synchronized": "正在同步資料夾", - "Wait for the import to finish": "請等待匯入完成", "Appearance": "外觀", "Appearance Mode": "外觀模式", "Sync with System": "與系統同步", @@ -2159,5 +2157,6 @@ "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", "Queued: it starts when the task ahead of it ends": "已加入佇列:前一個工作結束後開始", "Another library was opened: nothing was done": "已開啟另一個圖庫:未執行任何操作", + "Photos of the folder changed while it was read: nothing was done": "讀取期間資料夾中的照片發生了變化:未執行任何操作", "Starts next": "接下來開始" } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 04874c8cc6a..51593276eaf 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -89,21 +89,9 @@ impl LightcraftApp { if now - self.ui.auto_import_at >= 3.0 && !import::library_busy(self) && self.lightroom.is_none() && !self.tasks.is_running(LABEL) { self.ui.auto_import_at = now; let work = move || lightcraft_engine::cmd::library::list_auto_import_folder(&folder); - let done = |app: &mut LightcraftApp, _ctx: &egui::Context, listing: Result, String>| { - let listing = match listing { - Ok(l) => l, - Err(e) => return log::debug!("auto import: {e}"), - }; - let p = serde_json::json!({"listing": listing, "start": false}); - let Ok(r) = app.session.execute("library.autoImportScan", &p) else { return }; - let Some(mut params) = r.get("import").cloned().filter(|_| !import::library_busy(app)) else { return }; - let paths: Vec = - params["paths"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect(); - if let Some(o) = params.as_object_mut() { - o.remove("paths"); - } - let undo0 = app.session.undo.len(); - app.import = Some(import::ImportTask::new(paths, params, undo0, false).auto()); + let done = |app: &mut LightcraftApp, _ctx: &egui::Context, listing: Result, String>| match listing { + Ok(listing) => import::auto_import_listed(app, listing), + Err(e) => log::debug!("auto import: {e}"), }; // listed every few seconds: quiet, no row in the activity stack if let Err(e) = tasks::spawn(self, LABEL, None, work, done) { diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index bfddcc35503..ab1f856e8d3 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -36,7 +36,7 @@ pub(crate) use body::{DIALOG_SIZE, note_dialog_bottom}; pub(crate) use scan::library_busy; pub use scan::{IMPORT_REQUEST, ScanTask, browse, drop_blocked, open, poll_scan, running}; #[cfg(not(target_arch = "wasm32"))] -pub(crate) use scan::cards_seen; +pub(crate) use scan::{auto_import_listed, cards_seen}; #[cfg(test)] pub(crate) use scan::{stall_scan, stall_scan_of}; pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 43edb41ae91..5f1661a585e 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -28,8 +28,8 @@ fn scan_guard(app: &LightcraftApp, progress: &ScanProgress, browse: bool) -> lig /// `library.import` params. pub const IMPORT_REQUEST: &str = "app:import"; -fn import_request(paths: &[String], params: &Value) -> Request { - Request { command: IMPORT_REQUEST.into(), params: json!({"paths": paths, "params": params}) } +fn import_request(paths: &[String], params: &Value, auto: bool) -> Request { + Request { command: IMPORT_REQUEST.into(), params: json!({"paths": paths, "params": params, "auto": auto}) } } /// The library lane is taken: an import (or the reading of a Local folder) or a Synchronize Folder runs, or waits @@ -44,13 +44,42 @@ pub(crate) fn library_busy(app: &LightcraftApp) -> bool { || app.session.activity.lane_waiting(Lane::Library) } -/// Put an import of `paths` with `params` in line behind what runs in the library lane, and say so. -pub(super) fn wait_in_line(app: &mut LightcraftApp, paths: &[String], params: &Value) -> Result { - let (id, place) = app.session.activity.enqueue("import", "Importing", import_request(paths, params))?; - app.queued_toast(place as u64); +/// Put an import of `paths` with `params` in line behind what runs in the library lane, and say so (an Auto Import +/// quietly: nobody asked for it). +pub(super) fn wait_in_line(app: &mut LightcraftApp, paths: &[String], params: &Value, auto: bool) -> Result { + let (id, place) = app.session.activity.enqueue("import", "Importing", import_request(paths, params, auto))?; + if !auto { + app.queued_toast(place as u64); + } Ok(json!({"queued": id, "place": place})) } +/// The watched folder was listed (Auto Import): import what is new in it, as an Auto Import. The engine has noted +/// those files as tried by now, so while the library lane is taken (it was free when the listing began) they wait in +/// line instead of being dropped. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn auto_import_listed(app: &mut LightcraftApp, listing: Vec<(String, u64)>) { + // no room in the line: leave the folder to its next listing, because the scan below notes its files as tried + if library_busy(app) && app.session.activity.waiting().len() >= lightcraft_engine::activity::MAX_WAITING { + return; + } + let p = json!({"listing": listing, "start": false}); + let Ok(r) = app.session.execute("library.autoImportScan", &p) else { return }; + let Some(mut params) = r.get("import").cloned() else { return }; + let paths: Vec = params["paths"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect(); + if let Some(o) = params.as_object_mut() { + o.remove("paths"); + } + if library_busy(app) { + if let Err(e) = wait_in_line(app, &paths, ¶ms, true) { + log::warn!("auto import: {e}"); + } + return; + } + let undo0 = app.session.undo.len(); + app.import = Some(ImportTask::new(paths, params, undo0, false).auto()); +} + /// Settings → Import → "Show the import review when a camera or card is connected", called with /// each device scan while it's on. The first look only notes the cards already in. A card that /// shows up after that opens Import from Device once nothing else is open, and a card that is diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index a66dfe9cd08..c38c221fc82 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -201,10 +201,6 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result if !d.in_library(app) { return Err("another library was opened since the photos were scanned: nothing was imported".into()); } - // a browse scan that finishes starts its own import, replacing this one - if app.scan.as_ref().is_some_and(|t| t.browse) { - return Err(crate::i18n::tr("An import is running").to_string()); - } let queue = d.selected_paths(); if queue.is_empty() { return Err("no photos selected".into()); @@ -257,7 +253,7 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result // the review's thumbnails are done with, whether it runs now or later app.renderer.forget_imports(); if waits { - return wait_in_line(app, &queue, ¶ms); + return wait_in_line(app, &queue, ¶ms, false); } let total = queue.len(); app.import = Some(ImportTask::new(queue, params, undo0, false)); @@ -272,7 +268,7 @@ pub fn start_paths(app: &mut LightcraftApp, paths: Vec) -> Result String { + if task.waiting { tr_format!("Remove from Queue: {label}", label = tr(&task.label)) } else { tr("Cancel").to_string() } +} + /// One task: name and ✕, the bar, the detail line (a waiting one: name and ✕, when it starts). True when ✕ was clicked. fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { let mut clicked = false; @@ -133,7 +138,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { }); if cross { let (rect, resp) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::click()); - let name = if task.waiting { tr_format!("Remove from Queue: {label}", label = tr(&task.label)) } else { tr("Cancel").to_string() }; + let name = cross_name(task); crate::widgets::announce(&resp, name.clone()); paint(ui.painter(), rect.shrink(2.0), Icon::Close, if resp.hovered() { t.text } else { t.icon }); register(ui, format!("activity:cancel:{}", task.id), rect); diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 254db3d52a9..db48585c6f3 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -6,8 +6,9 @@ //! //! A Synchronize asked for while an import or another synchronize runs waits in line behind it (the library lane, //! [`lightcraft_engine::activity::Lane::Library`]). When its turn comes it scans the folder again ([`SyncRescan`]) and -//! then runs as it was asked, but it removes or relinks only the photos its dialog showed: one that went missing -//! meanwhile was never shown to the person, so it is left alone, and the end says so. +//! then runs as it was asked, but it removes, relinks or reads sidecars of only the photos its dialog showed: one that +//! went missing, moved or got a sidecar update meanwhile was never shown to the person, so it is left alone, and the +//! end says so. use std::sync::Arc; use std::sync::atomic::Ordering; @@ -242,19 +243,23 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { let choice = SyncChoice { import_new: *import_new, relink_moved: *relink_moved, remove_missing: *remove_missing, read_metadata: *read_metadata }; // (an import readies its files against the library as it was: both could add the same file) if crate::import::library_busy(app) { - // what the dialog showed: only these are removed or relinked, whenever the run comes + // what the dialog showed: only these are removed, relinked or read, whenever the run comes let shown = app .session .folder_changes .as_ref() .filter(|c| lightcraft_catalog::query::folder_key(&c.path) == lightcraft_catalog::query::folder_key(path)); - let (missing, moved): (Vec, Vec) = - shown.map(|c| (c.missing.iter().map(|m| m.id).collect(), c.moved.iter().map(|m| m.id).collect())).unwrap_or_default(); - let request = sync_request(path, name, *disk, choice, &missing, &moved); + let shown = shown.map(|c| Shown { + missing: c.missing.iter().map(|m| m.id).collect(), + moved: c.moved.iter().map(|m| m.id).collect(), + metadata: c.metadata.iter().map(|m| m.id).collect(), + }); + let request = sync_request(path, name, *disk, choice, &shown.unwrap_or_default()); + // (the dialog's scan is let go only once the line has room: refused, the dialog stays open holding it) + let (id, place) = app.session.activity.enqueue("sync", "Synchronizing folder", request)?; if std::mem::take(&mut app.sync_owns_changes) { app.session.folder_changes = None; } - let (id, place) = app.session.activity.enqueue("sync", "Synchronizing folder", request)?; app.queued_toast(place as u64); return Ok(json!({"queued": id, "place": place})); } @@ -284,7 +289,7 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { } /// Hand the work of a synchronize to a worker thread, its steps committed between frames ([`poll_run`]). `left_alone`: -/// photos found missing (or moved) that its dialog never showed, said at the end. +/// photos found missing, moved or with a sidecar update that its dialog never showed, said at the end. fn run( app: &mut LightcraftApp, name: &str, @@ -324,15 +329,23 @@ fn run( /// The command of a Synchronize Folder's request ([`Request`]): the app runs it ([`start_request`]). pub const SYNC_REQUEST: &str = "app:synchronize"; -/// What a synchronize was asked, to run it later in line or again: the folder, the dialog's choices, and the missing -/// and moved photos it showed (the only ones it may remove or relink). -fn sync_request(path: &str, name: &str, disk: bool, choice: SyncChoice, missing: &[u64], moved: &[u64]) -> Request { +/// The photos a Synchronize Folder dialog listed: the only ones its run may act on if it waits in line. +#[derive(Default)] +struct Shown { + missing: Vec, + moved: Vec, + metadata: Vec, +} + +/// What a synchronize was asked, to run it later in line or again: the folder, the dialog's choices, and the missing, +/// moved and metadata-updated photos it showed (the only ones it may remove, relink or read). +fn sync_request(path: &str, name: &str, disk: bool, choice: SyncChoice, shown: &Shown) -> Request { Request { command: SYNC_REQUEST.into(), params: json!({ "path": path, "name": name, "disk": disk, "importNew": choice.import_new, "relinkMoved": choice.relink_moved, "removeMissing": choice.remove_missing, "readMetadata": choice.read_metadata, - "missing": missing, "moved": moved, + "missing": shown.missing, "moved": shown.moved, "metadata": shown.metadata, }), } } @@ -341,9 +354,10 @@ fn sync_request(path: &str, name: &str, disk: bool, choice: SyncChoice, missing: pub struct SyncRescan { name: String, choice: SyncChoice, - /// The missing and moved photos its dialog showed. + /// The missing, moved and metadata-updated photos its dialog showed. missing: std::collections::HashSet, moved: std::collections::HashSet, + metadata: std::collections::HashSet, /// The library it was asked in ([`lightcraft_engine::Session::library_generation`]): its photo ids mean nothing in /// another one. library: u64, @@ -381,23 +395,28 @@ pub fn start_request(app: &mut LightcraftApp, _ctx: &egui::Context, request: &Re let guard = app.session.activity.start("sync", "Synchronizing folder", Cancel::Flag(progress.files.cancel.clone())); guard.detail(&name); let library = app.session.library_generation(); - app.sync_queued = Some(SyncRescan { name, choice, missing: ids("missing"), moved: ids("moved"), library, progress, rx, guard }); + app.sync_queued = + Some(SyncRescan { name, choice, missing: ids("missing"), moved: ids("moved"), metadata: ids("metadata"), library, progress, rx, guard }); Ok(()) } -/// Run the waiting synchronize once its scan is in (called every frame): only the missing and moved photos its dialog -/// showed are acted on. +/// Run the waiting synchronize once its scan is in (called every frame): only the missing, moved and metadata-updated +/// photos its dialog showed are acted on. pub fn poll_rescan(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(task) = app.sync_queued.as_ref() else { return }; - let (done, total) = task.progress.counts(); - task.guard.progress(done as u64, total as u64); + // (how many folders and files were listed first: a count stuck at "0 of N" looks like a scan that stopped) + let (done, total, detail) = scan_row(&task.progress, &task.name); + task.guard.progress(done, total); + task.guard.detail(&detail); ctx.request_repaint_after(std::time::Duration::from_millis(100)); let got = task.rx.try_recv(); - if matches!(got, Err(std::sync::mpsc::TryRecvError::Empty)) && !task.guard.is_cancelled() { + // (another library opened: it ends at once, not when a scan of the old library's folder is done) + let stale = task.library != app.session.library_generation(); + if matches!(got, Err(std::sync::mpsc::TryRecvError::Empty)) && !task.guard.is_cancelled() && !stale { return; } let Some(task) = app.sync_queued.take() else { return }; - let SyncRescan { name, choice, missing, moved, library, progress, guard, .. } = task; + let SyncRescan { name, choice, missing, moved, metadata, library, progress, guard, .. } = task; if library != app.session.library_generation() { // another library was opened while it scanned: its photos are not these progress.files.cancel.store(true, Ordering::Relaxed); @@ -421,12 +440,20 @@ pub fn poll_rescan(app: &mut LightcraftApp, ctx: &egui::Context) { app.toast(ctx, format!("{name}: {why}")); return; } - // only what the person saw is removed or relinked; what they would have been asked about is said - let (missing_before, moved_before) = (changes.missing.len(), changes.moved.len()); + // (the library moved on while the folder was read, on a share that can take minutes: a photo it relinked or edited + // since is not removed or overwritten from a scan that did not see it) + if !app.session.scan_is_current(&changes) { + app.toast(ctx, format!("{name}: {}", crate::i18n::tr("Photos of the folder changed while it was read: nothing was done"))); + return; + } + // only what the person saw is removed, relinked or read; what they would have been asked about is said + let (missing_before, moved_before, metadata_before) = (changes.missing.len(), changes.moved.len(), changes.metadata.len()); changes.missing.retain(|m| missing.contains(&m.id)); changes.moved.retain(|m| moved.contains(&m.id)); + changes.metadata.retain(|m| metadata.contains(&m.id)); let left_alone = if choice.remove_missing { missing_before - changes.missing.len() } else { 0 } - + if choice.relink_moved { moved_before - changes.moved.len() } else { 0 }; + + if choice.relink_moved { moved_before - changes.moved.len() } else { 0 } + + if choice.read_metadata { metadata_before - changes.metadata.len() } else { 0 }; match SyncJob::start(&mut app.session, changes, choice) { Ok((work, commit)) => { // (a fresh count, the same ✕: its row's flag stops the run as it stopped the scan) @@ -457,7 +484,8 @@ pub struct SyncRun { stopping: bool, /// Its row in the activity stack (its ✕ is Cancel). guard: TaskGuard, - /// Photos found missing or moved that its dialog never showed (a run that waited in line): left alone, and said. + /// Photos found missing, moved or with a sidecar update that its dialog never showed (a run that waited in line): + /// left alone, and said. left_alone: usize, } @@ -571,7 +599,7 @@ pub fn poll_run(app: &mut LightcraftApp, ctx: &egui::Context) { parts.push(format!("{}: {e}", crate::i18n::tr("Not saved"))); } if left_alone > 0 { - parts.push(crate::i18n::tr_format!("{n} more missing, left alone: synchronize again to review them", n = left_alone)); + parts.push(crate::i18n::tr_format!("Left alone: {n} (synchronize again to review them)", n = left_alone)); } let text = if parts.is_empty() { crate::i18n::tr("The library is up to date with this folder.").to_string() } else { parts.join(" · ") }; if not_saved.is_empty() && !crashed { diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index 02505025d9c..411a8419169 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -559,6 +559,10 @@ fn a_task_waiting_in_line_has_a_row_and_starts_when_the_lane_frees() { has(&h, &format!("activity:row:{waiting}")) && has(&h, &format!("activity:cancel:{waiting}")) && rows(&h) == 2, "a waiting task draws a row with ✕" ); + let info = h.app.session.activity.waiting().remove(0); + assert_eq!(crate::panels::activity::cross_name(&info), "Remove from Queue: Building previews"); + let running_row = h.app.session.activity.list().into_iter().find(|t| !t.waiting).expect("the running build"); + assert_eq!(crate::panels::activity::cross_name(&running_row), "Cancel"); // the lane frees with no command asked: the frame loop starts it build.finished.store(true, Ordering::Release); drop(running); diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 76e1e28450e..09689ac59c9 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -831,6 +831,72 @@ fn a_waiting_review_never_replaces_a_running_import() { assert_eq!(photos(&h), 3, "the running import's photo arrives, then the review's two"); } +/// Given a Local folder being read, when an import review is confirmed, then its OK waits in line like any import +/// asked for while the lane is taken (it is not refused with "An import is running"), and runs when the read ends. +#[test] +fn a_review_confirmed_while_a_local_folder_is_read_waits_in_line() { + let dir = Scratch::new("review-browse"); + let mut h = app(&dir); + crate::import::open(&mut h.app, vec![dir.path("trip")]).unwrap(); + assert!(h.step_until(SETTLE, |h| h.app.scan.is_none()), "the scan ends"); + h.step(); + let Some(review) = h.app.ui.dialog.clone() else { panic!("the review is open") }; + let _browse = crate::import::stall_scan_of(&mut h.app, true); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &review); + assert!(r.as_ref().is_ok_and(|v| v["queued"].as_u64().is_some()), "the review's OK waits in line: {r:?}"); + h.app.scan = None; + assert!(h.step_until(SETTLE, |h| h.app.import.is_none() && h.app.session.activity.list().is_empty()), "it ran"); + assert_eq!(photos(&h), 2, "the review's two photos"); +} + +/// Given Auto Import's folder listing that comes in while another import runs, then what it found waits in line and +/// is imported when that import ends: the files are not offered again (the engine has noted them as tried). +#[test] +fn an_auto_import_that_finds_files_while_an_import_runs_waits_in_line() { + let dir = Scratch::new("auto-waits"); + let mut h = app(&dir); + write_png(&dir.path("watched/w.png"), 7); + let watched = dir.path("watched"); + h.app.session.import_defaults.auto_folder = Some(watched.clone()); + let listing = || lightcraft_engine::cmd::library::list_auto_import_folder(&watched).unwrap(); + // (a file is taken once its size has stayed the same between two listings) + crate::import::auto_import_listed(&mut h.app, listing()); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + crate::import::auto_import_listed(&mut h.app, listing()); + assert_eq!(h.app.session.activity.waiting().iter().map(|t| t.kind).collect::>(), vec!["import"], "it waits in line"); + assert!(h.app.ui.toast.is_none(), "an Auto Import is quiet: {:?}", h.app.ui.toast); + drop(hold); + assert!(h.step_until(SETTLE, |h| h.app.import.is_none() && h.app.session.activity.list().is_empty()), "it ran"); + assert_eq!(photos(&h), 1, "w.png came in"); +} + +/// Given a line that is full, when Auto Import's listing comes in while an import runs, then the folder is left to its +/// next listing (its files aren't noted as tried), and imported once there is room. +#[test] +fn an_auto_import_with_no_room_in_line_is_left_for_the_next_listing() { + use lightcraft_engine::activity::{Cancel, MAX_WAITING, Request}; + let dir = Scratch::new("auto-full"); + let mut h = app(&dir); + write_png(&dir.path("watched/w.png"), 7); + let watched = dir.path("watched"); + h.app.session.import_defaults.auto_folder = Some(watched.clone()); + let listing = || lightcraft_engine::cmd::library::list_auto_import_folder(&watched).unwrap(); + let hold = h.app.session.activity.start("import", "Importing", Cancel::Yes); + for _ in 0..MAX_WAITING { + h.app.session.activity.enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}) }).unwrap(); + } + crate::import::auto_import_listed(&mut h.app, listing()); + crate::import::auto_import_listed(&mut h.app, listing()); + assert_eq!(h.app.session.activity.waiting().len(), MAX_WAITING, "no room: nothing was added"); + h.app.session.activity.cancel_all(); + crate::import::auto_import_listed(&mut h.app, listing()); + crate::import::auto_import_listed(&mut h.app, listing()); + assert_eq!(h.app.session.activity.waiting().iter().map(|t| t.kind).collect::>(), vec!["import"], "now it waits in line"); + drop(hold); + assert!(h.step_until(SETTLE, |h| h.app.import.is_none() && h.app.session.activity.list().is_empty()), "it ran"); + assert_eq!(photos(&h), 1, "w.png came in"); +} + /// Given an import that runs, when photos are dropped directly on the window, then they are not refused: they wait in /// line behind it and are imported when it ends. #[test] diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index 362f4c1a7f9..d0d6bdbb380 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -21,8 +21,8 @@ //! * A Synchronize Folder and an import never run at once: one asked for while the other runs waits in line behind it //! and starts by itself, planning its work then (an import checks for duplicates against the library as it is //! when it starts; a synchronize scans the folder again). -//! * A synchronize that waited removes or relinks only the photos its dialog showed: a photo that went missing while -//! it waited stays, and the end says so. +//! * A synchronize that waited removes, relinks or reads sidecars of only the photos its dialog showed: a photo that +//! went missing, moved or got a sidecar update while it waited stays as it is, and the end says so. //! * The dialog's own scan doesn't hold up an import: it only reads. use std::time::Duration; @@ -366,7 +366,72 @@ fn a_waiting_synchronize_removes_only_the_missing_photos_its_dialog_showed() { assert!(h.step_until(SETTLE, idle), "it ran"); assert_eq!(in_library(&h), vec!["a.png", "c.png"], "b (shown) was removed, a (gone since) was not"); let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); - assert!(said.contains("1 more missing"), "{said}"); + assert!(said.contains("Left alone: 1"), "{said}"); +} + +/// A sidecar dated an hour from now, so that it is newer than the photo whatever the clock's grain. +fn write_sidecar(png: &str, rating: u8) { + let xmp = std::path::Path::new(png).with_extension("xmp"); + let body = format!( + r#" + +"# + ); + std::fs::write(&xmp, body).unwrap(); + let f = std::fs::File::options().write(true).open(&xmp).unwrap(); + f.set_modified(std::time::SystemTime::now() + Duration::from_secs(3600)).unwrap(); +} + +fn rating_of(h: &Headless, file: &str) -> u8 { + h.app.session.catalog.photos().find(|p| p.file_name == file).map(|p| p.rating).unwrap_or_else(|| panic!("no {file}")) +} + +/// Given a synchronize that will read the one sidecar update its dialog showed (a), waiting behind an import, when +/// another photo's sidecar (b) changes while it waits, then at its turn it reads a's sidecar only: reading replaces a +/// photo's rating, labels, metadata and edits, which nobody agreed to for b. The end says one more was left alone. +#[test] +fn a_waiting_synchronize_reads_only_the_sidecars_its_dialog_showed() { + let dir = Scratch::new("reviewed-meta"); + let mut h = imported_folder(&dir, || write_sidecar(&dir.path("trip/a.png"), 4)); + open_and_scan(&mut h, &dir.path("trip")); + assert_eq!(counts(&h).metadata, 1, "the dialog shows a's update"); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + let mut dlg = h.app.ui.dialog.take().expect("the dialog is open"); + if let Dialog::SynchronizeFolder { read_metadata, .. } = &mut dlg { + *read_metadata = true; + } + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg); + assert!(r.as_ref().is_ok_and(|v| v.get("queued").is_some()), "it waits for the import: {r:?}"); + write_sidecar(&dir.path("trip/b.png"), 5); + drop(hold); + assert!(h.step_until(SETTLE, idle), "it ran"); + assert_eq!((rating_of(&h, "a.png"), rating_of(&h, "b.png")), (4, 0), "a (shown) was read, b (changed since) was not"); + let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); + assert!(said.contains("Left alone: 1"), "{said}"); +} + +/// Given a line that is full, when a synchronize is confirmed while an import runs, then it is refused with the dialog +/// still holding what it showed: confirmed again once there is room, it removes the missing photo it listed. +#[test] +fn a_synchronize_refused_for_a_full_line_keeps_what_its_dialog_showed() { + use lightcraft_engine::activity::{MAX_WAITING, Request}; + let dir = Scratch::new("full-line"); + let mut h = changed_folder(&dir); + open_and_scan(&mut h, &dir.path("trip")); + tick_remove_missing(&mut h); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + for _ in 0..MAX_WAITING { + h.app.session.activity.enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}) }).unwrap(); + } + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_err(), "no room in the line"); + h.app.session.activity.cancel_all(); + assert!(h.app.session.activity.waiting().is_empty()); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg); + assert!(r.as_ref().is_ok_and(|v| v.get("queued").is_some()), "now it waits: {r:?}"); + drop(hold); + assert!(h.step_until(SETTLE, idle), "it ran"); + assert_eq!(in_library(&h), vec!["a.png", "c.png"], "b, which the dialog showed missing, was removed"); } /// Given a Local folder being read, when a synchronize is confirmed, then it waits: the read becomes an import when @@ -403,6 +468,28 @@ fn a_waiting_synchronize_never_acts_on_another_library() { assert!(said.contains("Another library was opened"), "{said}"); } +/// Given a waiting synchronize that has started scanning its folder again, when a photo of the folder changes before the +/// scan is in (the scan did not see it), then nothing is done and it says so: what the scan saw is not what is there. +#[test] +fn a_waiting_synchronize_does_nothing_on_a_scan_the_library_moved_past() { + let dir = Scratch::new("moved-past"); + let mut h = changed_folder(&dir); + open_and_scan(&mut h, &dir.path("trip")); + tick_remove_missing(&mut h); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_ok_and(|v| v["queued"].as_u64().is_some()), "it waits"); + drop(hold); + assert!(h.step_until(T, |h| h.app.sync_queued.is_some()), "it started scanning again"); + let a = h.app.session.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id; + let r = h.request("engine.execute", json!({"command": "photo.rate", "params": {"ids": [a.0], "rating": 3}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.step_until(SETTLE, idle), "it ended"); + assert_eq!(in_library(&h), vec!["a.png", "b.png"], "the missing b stays, c did not come in"); + let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); + assert!(said.contains("Photos of the folder changed while it was read"), "{said}"); +} + /// Given a synchronize waiting in line, when its folder is gone by its turn, then it ends saying so and changes /// nothing. #[test] diff --git a/docs/background-tasks.md b/docs/background-tasks.md index bbfc90ea45a..3fb29c840fb 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -58,14 +58,16 @@ Jobs that must not run side by side share a lane (`activity::Lane`). There are t Each plans its work against the library as it is when it starts, so two side by side could add the same file. An import asked for while the lane is taken is not refused any more: it waits and checks for duplicates against the library as it is when its turn comes. A Synchronize Folder that waits scans its folder again at its turn, then - removes or relinks only the photos its dialog showed: one that went missing while it waited was never shown, so it - is left alone and the end says so ("1 more missing, left alone: synchronize again to review them"). If another - library is opened while it scans, or its folder is gone, it stops without doing anything and a toast says so. A - toast says it was queued when it was put in line. The dialog's own scan ("Looking for changes", kind `scan`) only + removes, relinks or reads the sidecars of only the photos its dialog showed: one that went missing, moved or got a + sidecar update while it waited was never shown, so it is left alone and the end says so ("Left alone: 1 + (synchronize again to review them)"). If another library is opened while it scans, or its folder is gone, it stops + without doing anything and a toast says so (at once for a new library, even if the old folder's scan is still going). + A toast says it was queued when it was put in line. The dialog's own scan ("Looking for changes", kind `scan`) only reads and holds up nothing. These requests are the app's (`app:import`, `app:synchronize`): the app starts them (`LightcraftApp::start_waiting`, every frame), and the engine leaves them alone (`Activity::take_ready_if`). Auto - Import waits until nothing runs, rescans or waits in this lane. A drop while an import's review is open or a scan - runs is still refused. + Import lists its folder only when nothing runs, rescans or waits in this lane; files it finds after something + started meanwhile wait in line, quietly. A drop while a scan runs or an import's review waits behind a dialog is + still refused. A call that sets `queue: true` while its lane is busy does not fail: `Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 74e1529d8a6..e81674d5534 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -959,4 +959,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | -| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and acts only on the photos its dialog showed; every waiting task has a row in the activity stack (when it starts, ✕ to remove it); status unchanged (✅) | +| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and removes, relinks or reads only the photos its dialog showed; every waiting task has a row in the activity stack (when it starts, ✕ to remove it); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index f9e11d5d19c..4a8488ea4e6 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -7,11 +7,14 @@ confirmed while an import runs, now waits in line and starts by itself when the other ends, with a message that it was queued. Before, it was refused ("Wait for the import to finish", "A folder is being synchronized"). - Photos dropped on the window, or an import review confirmed, while another import runs also wait in line instead of - being refused with "An import is running"; a drop is still refused while a folder is being scanned for the review. -- A task waiting in line shows in the activity stack at once: its name, "Starts next" or "Starts after N more", and ✕ to take it out of the line, so a mistaken one can be withdrawn. This holds for a waiting preview build too. + being refused with "An import is running"; a drop is still refused while a folder is being scanned for the review or + read for the Local view, or while a finished scan's review waits behind another dialog. +- A task waiting in line shows in the activity stack at once: its name, "Starts next" or "Starts after N more", and ✕ + to take it out of the line, so a mistaken one can be withdrawn. This holds for a waiting preview build too. - A waiting import checks for duplicates against the library as it is when its turn comes, so nothing is added twice. -- A waiting Synchronize Folder looks at its folder again when its turn comes. It removes or relinks only the photos - its dialog showed: one that went missing while it waited is left alone, and the message at the end says so. +- A waiting Synchronize Folder looks at its folder again when its turn comes. It removes, relinks or reads sidecars of + only the photos its dialog showed: one that went missing, moved or got a sidecar update while it waited is left + alone, and the message at the end says how many ("Left alone: 1 (synchronize again to review them)"). - Nothing waits across another library: a Synchronize Folder that is still scanning when another library opens does nothing. From c20afd9df2c2a84bb83ffa1d1657bd3ee1f6edbf Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 23:46:07 -0400 Subject: [PATCH 09/55] LR-BEHAV-BG-TASKS: control-protocol.md says a waiting task has a row at once, with a way to take it out of the line --- docs/background-tasks.md | 6 ++++-- docs/control-protocol.md | 2 +- docs/parity-checklist.md | 4 ++-- docs/whats-new.md | 3 ++- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 3fb29c840fb..ca59147aab7 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -60,8 +60,10 @@ Jobs that must not run side by side share a lane (`activity::Lane`). There are t library as it is when its turn comes. A Synchronize Folder that waits scans its folder again at its turn, then removes, relinks or reads the sidecars of only the photos its dialog showed: one that went missing, moved or got a sidecar update while it waited was never shown, so it is left alone and the end says so ("Left alone: 1 - (synchronize again to review them)"). If another library is opened while it scans, or its folder is gone, it stops - without doing anything and a toast says so (at once for a new library, even if the old folder's scan is still going). + (synchronize again to review them)"). If another library is opened while it scans, its folder is gone, or a photo of the + folder is changed in the library (a rating, an edit) while it scans, it stops without doing anything and a toast says + so (at once for a new library, even if the old folder's scan is still going). The focus points and face regions the + background searches add don't count as changes. A toast says it was queued when it was put in line. The dialog's own scan ("Looking for changes", kind `scan`) only reads and holds up nothing. These requests are the app's (`app:import`, `app:synchronize`): the app starts them (`LightcraftApp::start_waiting`, every frame), and the engine leaves them alone (`Activity::take_ready_if`). Auto diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b7f0e0c7e07..7bfd2bd0217 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -79,7 +79,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list` (including tasks waiting in line, which have no row); the activity stack in the top-left corner shows the running ones, and a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why — see `docs/gpu-pipeline.md`), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file; OK = `button:noticeOk`), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list`, including tasks waiting in line; the activity stack in the top-left corner shows a running task once it is 0.5 s old and a waiting task at once (no bar, "Starts next" / "Starts after N more"), ids `activity:row:`, ✕ = `activity:cancel:` (on a waiting row: Remove from Queue), `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply) | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e81674d5534..becf361d7ee 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -70,7 +70,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`) | -| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | +| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build), while a folder is scanned for the review or while a review waits to open is refused with a toast, and the card says so; a drop while an import or a Synchronize Folder runs waits in line; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | | LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | @@ -959,4 +959,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | -| 2026-10-24 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and removes, relinks or reads only the photos its dialog showed; every waiting task has a row in the activity stack (when it starts, ✕ to remove it); status unchanged (✅) | +| 2026-10-25 | minor | LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder share the library lane: one asked for while the other runs waits in line instead of being refused; a waiting Synchronize Folder scans again and removes, relinks or reads only the photos its dialog showed; every waiting task has a row in the activity stack (when it starts, ✕ to remove it); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 4a8488ea4e6..bf1d93038b0 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -16,7 +16,8 @@ only the photos its dialog showed: one that went missing, moved or got a sidecar update while it waited is left alone, and the message at the end says how many ("Left alone: 1 (synchronize again to review them)"). - Nothing waits across another library: a Synchronize Folder that is still scanning when another library opens does - nothing. + nothing. It also does nothing, and says so, when a photo of its folder is changed in the library (a rating, an edit) + while it scans, because what it saw is no longer what is there. ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new From abc98ec6705fce175b0e574590549fe68ea2ebfa Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 27 Oct 2026 14:46:53 -0400 Subject: [PATCH 10/55] LR-BEHAV-BG-TASKS: tests: a waiting synchronize's scan is held open while the photo is changed Co-Authored-By: Claude --- crates/ui-egui/src/tests/sync.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index d0d6bdbb380..f50d5f2895e 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -479,11 +479,24 @@ fn a_waiting_synchronize_does_nothing_on_a_scan_the_library_moved_past() { let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); let dlg = h.app.ui.dialog.take().expect("the dialog is open"); assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_ok_and(|v| v["queued"].as_u64().is_some()), "it waits"); + // the scan reads the new file through a probe that waits for the gate: it starts before the rating and ends after it, + // however fast the machine is (a scan that ended within its first frame would run before the rating was made) + let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let g = gate.clone(); + h.app.session.media.file_probe = Some(std::sync::Arc::new(move |p: &str| { + let t0 = std::time::Instant::now(); + while !g.load(std::sync::atomic::Ordering::Acquire) && t0.elapsed() < Duration::from_secs(60) { + std::thread::sleep(Duration::from_millis(1)); + } + Ok(lightcraft_engine::media::ProbeInfo { width: 8, height: 8, format: "PNG".into(), content_hash: Some(p.to_string()), ..Default::default() }) + })); drop(hold); assert!(h.step_until(T, |h| h.app.sync_queued.is_some()), "it started scanning again"); let a = h.app.session.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id; let r = h.request("engine.execute", json!({"command": "photo.rate", "params": {"ids": [a.0], "rating": 3}}), T); assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.sync_queued.is_some(), "the scan is still going when the photo changed"); + gate.store(true, std::sync::atomic::Ordering::Release); assert!(h.step_until(SETTLE, idle), "it ended"); assert_eq!(in_library(&h), vec!["a.png", "b.png"], "the missing b stays, c did not come in"); let said = h.app.ui.toast.iter().map(|t| t.0.clone()).collect::(); From 04707a0eb1ee1eed8a18308745395aae3e977002 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 17:39:04 -0400 Subject: [PATCH 11/55] LR-BEHAV-MULTISELECT: several sidebar albums, keywords or folders are deleted, moved or labeled as one undo step (engine) album.delete and album.move take `ids`, keyword.delete and keyword.move take `keywords`, library.removeFolder and folder.label take `paths`. Each checks everything before it changes anything, is one step to undo, and names what it refuses. Engine only: no UI calls it yet. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/keywords.rs | 87 +++++++ crates/engine/src/cmd/keywords.rs | 62 ++++- crates/engine/src/cmd/library/specs.rs | 264 ++++++++++++++++---- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/batch_sidebar.rs | 301 +++++++++++++++++++++++ docs/parity-checklist.md | 5 +- 6 files changed, 660 insertions(+), 60 deletions(-) create mode 100644 crates/engine/src/tests/batch_sidebar.rs diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index d36ab11cd67..9851666bc75 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -442,6 +442,93 @@ impl Catalog { Ok(Op::Batch { ops }) } + /// [`Self::delete_keyword_ops`] for several keywords at once: one batch, so one undo step. + /// Unlike one keyword (which may be absent and then changes nothing), every keyword named must + /// exist, or the whole batch is refused. + pub fn delete_keywords_ops(&self, keywords: &[String]) -> Result { + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + if gone.is_empty() || gone.iter().any(String::is_empty) { + return Err(CatalogError::Invalid("empty keyword".into())); + } + // case folded once here, and each candidate once below, not once per pair + let folded: Vec = gone.iter().map(|g| g.to_lowercase()).collect(); + let under = |k: &str, p: &str| k == p || k.strip_prefix(p).is_some_and(|rest| rest.starts_with(SEP)); + let mut found = vec![false; folded.len()]; + let listed = self.keyword_list.values().map(|l| &l.path); + for k in listed.chain(self.photos().filter(|p| p.in_library()).flat_map(|p| p.meta.keywords.iter())) { + let k = k.to_lowercase(); + for (hit, p) in found.iter_mut().zip(&folded) { + *hit |= under(&k, p); + } + } + if let Some(i) = found.iter().position(|hit| !hit) { + return Err(CatalogError::Invalid(format!("no keyword “{}”", gone[i]))); + } + let goes = |k: &str| { + let k = k.to_lowercase(); + folded.iter().any(|p| under(&k, p)) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().filter(|x| !goes(x)).cloned().collect()); + ops.extend(self.list_ops(|list| list.retain(|_, l| !goes(&l.path)))); + Ok(Op::Batch { ops }) + } + + /// Move several keywords (each with the keywords below it) inside `parent`, or to the top + /// level (`None`), as one batch. Each keeps its name. Of a keyword and one below it only the + /// upper one moves (the lower goes with it). Nothing merges here: a name that is taken where + /// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole + /// move. Returns the batch and each move as `(from, to)`. + pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> { + let mut from: Vec = Vec::new(); + for k in keywords { + let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?; + if !from.iter().any(|f| same(f, &path)) { + from.push(path); + } + } + if from.is_empty() { + return Err(CatalogError::Invalid("no keyword to move".into())); + } + // the upper ones only + let all = from.clone(); + from.retain(|f| !all.iter().any(|o| !same(o, f) && is_under(f, o))); + let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p)); + if let Some(p) = &parent + && from.iter().any(|f| is_under(p, f)) + { + return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + } + let mut moves: Vec<(String, String)> = Vec::new(); + for f in &from { + let leaf = f.rsplit(SEP).next().unwrap_or(f); + let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}")); + if moves.iter().any(|(_, t)| same(t, &to)) { + return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time"))); + } + moves.push((f.clone(), to)); + } + // one that is there already stays; the others must find their name free + moves.retain(|(f, t)| !same(f, t)); + if let Some((_, taken)) = moves.iter().find(|(_, t)| self.has_keyword(t)) { + return Err(CatalogError::KeywordExists(taken.clone())); + } + // case folded once here and once per photo keyword, not once per pair + let folded_from: Vec = moves.iter().map(|(f, _)| f.to_lowercase()).collect(); + let moved = |k: &str| { + let k_folded = k.to_lowercase(); + moves.iter().zip(&folded_from).find_map(|((f, t), f_folded)| { + let under = k_folded == *f_folded || k_folded.strip_prefix(f_folded.as_str()).is_some_and(|rest| rest.starts_with(SEP)); + under.then(|| reparent(k, f, t)) + }) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().map(|k| moved(k).unwrap_or_else(|| k.clone())).collect()); + // (the moves touch apart parts of the list: each one's listings are its own) + for (f, t) in &moves { + ops.extend(self.list_move_ops(std::slice::from_ref(f), t)); + } + Ok((Op::Batch { ops }, moves)) + } + /// Merge several keywords (with their children) into `into`. pub fn merge_keywords_ops(&self, from: &[String], into: &str) -> Result { let into = clean(into); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 0e612227f1f..429f7b0a02e 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -66,6 +66,39 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo { } } +/// `keyword.move`'s `parent`: a keyword, or null for the top level. +fn move_parent(p: &Value) -> Result> { + match p.get("parent") { + Some(Value::String(k)) => Ok(Some(k.clone())), + Some(Value::Null) => Ok(None), + _ => Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), + } +} + +/// How many keywords one call may name (far more than a person chooses in a list). +const MAX_KEYWORDS: usize = 10_000; + +/// The keywords a command names in `keywords`: a list of them, each once (whatever its case), +/// none empty. +fn keyword_list(p: &Value, command: &str) -> Result> { + let list = p.get("keywords").and_then(Value::as_array).ok_or_else(|| bad(command, "`keywords` must be a list of keywords"))?; + if list.len() > MAX_KEYWORDS { + return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords"))); + } + let mut out: Vec = Vec::new(); + for k in list { + let k = + k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?; + if !out.iter().any(|o| lightcraft_catalog::keywords::same(o, &k)) { + out.push(k); + } + } + if out.is_empty() { + return Err(bad(command, "`keywords` names no keyword")); + } + Ok(out) +} + /// The keyword a command names (`keyword`), as the library writes it. fn named_keyword(s: &Session, p: &Value, command: &str) -> Result { let k = str_param(p, "keyword").ok_or_else(|| bad(command, "missing `keyword`"))?; @@ -488,15 +521,23 @@ pub fn specs() -> Vec { "Move Keyword", [], None, - "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`", + "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`. Several at once: {keywords: [keyword], parent} as one undo step (of a keyword and one below it the upper one moves); nothing merges then: a name that is taken, or two of them with one name, refuses the whole move", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let parent = move_parent(p)?; + let keywords = keyword_list(p, "keyword.move")?; + let (op, moves) = s + .catalog + .move_keywords_ops(&keywords, parent.as_deref()) + .map_err(|e| refused("keyword.move", e, ": moving would merge the two (move that one by itself, with merge: true)"))?; + let label = if moves.len() == 1 { "Move Keyword".to_string() } else { format!("Move {} Keywords", moves.len()) }; + return commit_keywords(s, &label, op, |k| { + Some(moves.iter().find(|(f, _)| is_under(k, f)).map_or_else(|| k.to_string(), |(f, t)| reparent(k, f, t))) + }); + } let from = named_keyword(s, p, "keyword.move")?; - let parent = match p.get("parent") { - Some(Value::String(k)) => Some(k.clone()), - Some(Value::Null) => None, - _ => return Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), - }; + let parent = move_parent(p)?; // where it lands, as the catalog spells it: a parent that doesn't exist yet is made let leaf = from.rsplit('|').next().unwrap_or(&from).to_string(); let to = match parent.as_deref().map(|k| s.catalog.keyword_path(k).unwrap_or_else(|| clean(k))).filter(|k| !k.is_empty()) { @@ -612,9 +653,16 @@ pub fn specs() -> Vec { "Delete Keyword", [], None, - "{keyword} — removes it (and the keywords below it) from every photo", + "{keyword} — removes it (and the keywords below it) from every photo. Several at once: {keywords: [keyword]}, as one undo step", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let keywords = keyword_list(p, "keyword.delete")?; + let op = s.catalog.delete_keywords_ops(&keywords).map_err(|e| bad("keyword.delete", e.to_string()))?; + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + let label = if gone.len() == 1 { "Delete Keyword".to_string() } else { format!("Delete {} Keywords", gone.len()) }; + return commit_keywords(s, &label, op, |f| (!gone.iter().any(|g| is_under(f, g))).then(|| f.to_string())); + } let k = str_param(p, "keyword").ok_or_else(|| bad("keyword.delete", "missing `keyword`"))?.to_string(); let op = s.catalog.delete_keyword_ops(&k).map_err(|e| bad("keyword.delete", e.to_string()))?; let c = clean(&k); diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index a2a842106ac..c73325b7ccd 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -6,8 +6,8 @@ use super::selection::{ opt_album_param, rotate, row_step, select_after_deletion, select_by, step, strs, }; use super::{ - Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey, - Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, + Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Session, Sort, + SortKey, Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, }; /// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote. @@ -29,6 +29,91 @@ fn next_seed(prev: u64, now: &str) -> u64 { (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1) } +/// `album.move` for several albums and folders (`ids`) at once: everything is checked first, then +/// they move as one undo step. +fn move_albums(s: &mut Session, p: &Value) -> Result { + const C: &str = "album.move"; + let ids = album_ids(p.get("ids").unwrap_or(&Value::Null), C)?; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, format!("no such album {}", gone.0))); + } + let parent = opt_album_param(p, "parent", C)?; + if let Some(folder) = parent + && !s.catalog.album(folder).is_some_and(|a| a.folder) + { + return Err(bad(C, format!("album {} is not a folder of albums", folder.0))); + } + // where `parent` sits: itself and the folders above it (a ring, in a damaged library, ends the walk) + let mut above: Vec = Vec::new(); + let mut cur = parent; + while let Some(c) = cur.filter(|c| !above.contains(c)) { + above.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + // of a folder and what is inside it, the folder moves + let inside_another = |id: AlbumId| { + let mut seen: Vec = Vec::new(); + let mut cur = s.catalog.album(id).and_then(|a| a.parent); + while let Some(c) = cur.filter(|c| !seen.contains(c)) { + if ids.contains(&c) { + return true; + } + seen.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + false + }; + let moving: Vec = ids.iter().copied().filter(|id| !inside_another(*id)).collect(); + for id in &moving { + let name = s.catalog.album(*id).map(|a| a.name.clone()).unwrap_or_default(); + if above.contains(id) { + return Err(bad(C, format!("“{name}” can't go inside itself"))); + } + } + let ops: Vec = moving.iter().map(|id| Op::MoveAlbum { id: *id, parent }).collect(); + let label = if moving.len() == 1 { "Move Album".to_string() } else { format!("Move {} Albums", moving.len()) }; + s.commit(&label, Op::Batch { ops })?; + Ok(json!({"moved": moving.len()})) +} + +/// How many albums or folders one call may name: far more than a person +/// chooses in a sidebar, and a bound on what one call can make the engine check. +pub(crate) const MAX_SOURCES: usize = 1000; + +/// A command's `ids`: album ids, each once (named twice, the last naming counts). +fn album_ids(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`ids` must be a list of album ids"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`ids` names more than {MAX_SOURCES} albums"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let id = AlbumId(x.as_u64().ok_or_else(|| bad(c, format!("`ids` must be a list of album ids, not {x}")))?); + out.retain(|o| *o != id); + out.push(id); + } + Ok(out) +} + +/// A command's `paths`: folder paths, each folder once (named twice, the last counts). +fn folder_paths(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`paths` must be a list of folder paths"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`paths` names more than {MAX_SOURCES} folders"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let path = x.as_str().ok_or_else(|| bad(c, format!("`paths` must be a list of folder paths, not {x}")))?; + let key = lightcraft_catalog::query::folder_key(path); + out.retain(|o| lightcraft_catalog::query::folder_key(o) != key); + out.push(path.to_string()); + } + Ok(out) +} + pub fn specs() -> Vec { vec![ // ---- view source / filter / sort @@ -128,35 +213,52 @@ pub fn specs() -> Vec { "Remove Folder from Library", [], None, - "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}", + "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}. Several at once: {paths: [path]}, still one undo step; one that can't be removed refuses the whole call", always, |s, p| { const C: &str = "library.removeFolder"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; - if lightcraft_catalog::query::folder_key(path).is_empty() { - return Err(bad(C, format!("{path}: not a folder"))); - } - if lightcraft_catalog::folders::is_startup_disk(path) { - return Err(bad(C, "choose a folder, not the whole startup disk")); - } - if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); - } - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - let ids = s.catalog.query(&f, &Sort::default()); - if ids.is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); } - if covers_other_disks(s, path, &ids) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); + // every folder is checked before a photo leaves; a photo in two of them leaves once + let mut ids: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for path in &paths { + let path = path.as_str(); + if path.trim().is_empty() || lightcraft_catalog::query::folder_key(path).is_empty() { + return Err(bad(C, format!("{path}: not a folder"))); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(bad(C, "choose a folder, not the whole startup disk")); + } + if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); + } + let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + let found = s.catalog.query(&f, &Sort::default()); + if found.is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if covers_other_disks(s, path, &found) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); + } + ids.extend(found.into_iter().filter(|id| seen.insert(*id))); } - mark_deleted(s, &ids, "Remove Folder from Library")?; - if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + let label = + if paths.len() == 1 { "Remove Folder from Library".to_string() } else { format!("Remove {} Folders from Library", paths.len()) }; + mark_deleted(s, &ids, &label)?; + let within = |c: &str| paths.iter().any(|path| lightcraft_catalog::query::folder_within(c, path)); + if s.filter.library_folder.as_deref().is_some_and(within) { s.filter.library_folder = None; } // a filter put aside by Enable Filters must not bring the removed folder back if let Some(f) = s.shelved_filter.as_mut() - && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) + && f.library_folder.as_deref().is_some_and(within) { f.library_folder = None; } @@ -164,7 +266,7 @@ pub fn specs() -> Vec { s.shelved_filter = None; } // the folder being shown is gone: back to everything, as for a deleted album - if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + if s.library_folder.as_deref().is_some_and(within) { s.library_folder = None; if s.source == LibrarySource::LibraryFolder { s.source = LibrarySource::All; @@ -180,26 +282,46 @@ pub fn specs() -> Vec { "Set Folder Color Label", [], None, - "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}", + "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}. Several at once: {paths: [path], label}, as one undo step", always, |s, p| { const C: &str = "folder.label"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); + } let label = match str_param(p, "label").ok_or_else(|| bad(C, "missing `label` (red|yellow|green|blue|purple|none)"))? { "none" => None, x => Some(ColorLabel::parse(x).ok_or_else(|| bad(C, format!("unknown label {x:?}")))?), }; - // taking a label off always works, also once the folder's photos are gone - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + let mut ops = Vec::new(); + for path in &paths { + if path.trim().is_empty() { + return Err(bad(C, "missing `path`")); + } + // taking a label off always works, also once the folder's photos are gone + let f = Filter { library_folder: Some(path.clone()), ..Default::default() }; + if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if label.is_some() || s.catalog.folder_record(path).is_some() { + ops.push(s.catalog.folder_label_op(path, label)); + } } - if label.is_none() && s.catalog.folder_record(path).is_none() { - return Ok(json!({"path": path, "label": label})); + let name = if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }; + match (ops.len(), ops.pop()) { + (0, _) | (_, None) => {} + (1, Some(op)) => s.commit(name, op)?, + (_, Some(last)) => { + ops.push(last); + s.commit(name, Op::Batch { ops })? + } } - let op = s.catalog.folder_label_op(path, label); - s.commit(if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }, op)?; - Ok(json!({"path": path, "label": label})) + if several { Ok(json!({"paths": paths, "label": label})) } else { Ok(json!({"path": paths.first(), "label": label})) } } ), cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| { @@ -926,11 +1048,22 @@ pub fn specs() -> Vec { "Delete Album", [], None, - "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step", + "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step. Several at once: {ids: [albumId]} → {deleted}, still one undo step; one that does not exist refuses the whole call", always, |s, p| { - let id = album_param(p, "id", "album.delete")?; - let folder = s.catalog.album(id).ok_or_else(|| bad("album.delete", "no such album"))?.folder; + const C: &str = "album.delete"; + let several = p.get("ids").is_some_and(|v| !v.is_null()); + let ids = match p.get("ids") { + Some(v) if several => album_ids(v, C)?, + _ => vec![album_param(p, "id", C)?], + }; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, if several { format!("no such album {}", gone.0) } else { "no such album".into() })); + } + let folder = ids.first().and_then(|id| s.catalog.album(*id)).is_some_and(|a| a.folder); let mut children = std::collections::BTreeMap::>::new(); for album in s.catalog.albums() { if let Some(parent) = album.parent { @@ -940,32 +1073,61 @@ pub fn specs() -> Vec { // Iterative traversal: even a malformed cycle is rejected before any change. // Reverse parent-first order removes children first; the batch inverse restores // parents first, including memberships, smart rules, covers and manual ordering. - let mut pending = vec![id]; let mut order = Vec::new(); let mut removed = std::collections::BTreeSet::new(); - while let Some(next) = pending.pop() { - if !removed.insert(next) { - return Err(bad("album.delete", "cycle in album folders")); + for id in &ids { + // inside one named before it: it goes with that one + if removed.contains(id) { + continue; } - order.push(next); - if let Some(nested) = children.remove(&next) { - pending.extend(nested); + let mut pending = vec![*id]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(next) = pending.pop() { + if !seen.insert(next) { + return Err(bad(C, "cycle in album folders")); + } + // one named before, now found inside this one: it is listed once, here + if removed.insert(next) { + order.push(next); + } else if let Some(at) = order.iter().position(|o| *o == next) { + let moved = order.remove(at); + order.push(moved); + } + if let Some(nested) = children.get(&next) { + pending.extend(nested.iter().copied()); + } } } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); - s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; + let label = match (ids.len(), folder) { + (1, true) => "Delete Folder".to_string(), + (1, false) => "Delete Album".to_string(), + (n, _) => format!("Delete {n} Albums"), + }; + s.commit(&label, Op::Batch { ops })?; if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { s.source = LibrarySource::All; } + if several { Ok(json!({"deleted": ids.len()})) } else { ok() } + } + ), + cmd!( + "album.move", + "Move Album", + [], + None, + "{id, parent?: folderId|null} — into a folder, or to the top level. Several at once: {ids: [albumId], parent} as one undo step (of a folder and an album inside it the folder moves); one that can't go there refuses the whole call", + always, + |s, p| { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return move_albums(s, p); + } + let id = album_param(p, "id", "album.move")?; + let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); + s.commit("Move Album", Op::MoveAlbum { id, parent })?; ok() } ), - cmd!("album.move", "Move Album", [], None, "{id, parent?: folderId|null}", always, |s, p| { - let id = album_param(p, "id", "album.move")?; - let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); - s.commit("Move Album", Op::MoveAlbum { id, parent })?; - ok() - }), cmd!( "album.reorder", "Reorder Album", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 37b300dbfc3..fff26dc4d3b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,6 +7,7 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +mod batch_sidebar; mod color; mod constrain_crop; mod crop_angle; diff --git a/crates/engine/src/tests/batch_sidebar.rs b/crates/engine/src/tests/batch_sidebar.rs new file mode 100644 index 00000000000..1568ae58e7c --- /dev/null +++ b/crates/engine/src/tests/batch_sidebar.rs @@ -0,0 +1,301 @@ +//! Acting on several sidebar rows at once: the commands a context menu runs when several albums, +//! folders or keywords are chosen. Each is one step to undo, checks everything before it changes +//! anything, and a refusal names what it refused. +//! +//! Scenarios: +//! - Given three albums, when two are deleted at once (`album.delete {ids}`), then both are gone, +//! the third stays, and one undo brings both back. +//! - Given a folder of albums and an album inside it both named, then deleting them deletes the +//! folder with what is in it, once. +//! - An album that does not exist among those to delete is refused by name, and nothing is deleted. +//! - Given two albums, when both are moved into a folder (`album.move {ids, parent}`), then both +//! are inside it, and one undo puts both back; a folder is not moved into itself, and then +//! nothing moves. +//! - Given keywords on photos, when several are deleted at once (`keyword.delete {keywords}`), +//! then every photo loses them and one undo gives them back; one that is no keyword refuses the +//! whole call and nothing is deleted (one keyword that is no keyword still changes nothing). +//! - Given several keywords, when they are moved inside another (`keyword.move {keywords, +//! parent}`), then each is nested there with its photos, as one undo step; a name that is taken +//! there, or two of them with one name, is refused and nothing moves. +//! - Given two folders of the library, when both are removed at once (`library.removeFolder +//! {paths}`), then their photos go to Recently Deleted as one undo step; one that is not a +//! folder of the library refuses the whole call. +//! - Given two folders, when both get a colour label at once (`folder.label {paths}`), then both +//! show it, and one undo takes both off. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::Session; + +fn photos(s: &mut Session, n: u64) -> Vec { + (1..=n) + .map(|day| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }) + .collect() +} + +fn album(s: &mut Session, params: serde_json::Value) -> u64 { + s.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap() +} + +fn has_album(s: &Session, id: u64) -> bool { + s.catalog.album(AlbumId(id)).is_some() +} + +fn parent_of(s: &Session, id: u64) -> Option { + s.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0) +} + +fn tag(s: &mut Session, id: u64, keywords: &[&str]) { + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = vec![PhotoId(id)]; + s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": keywords})).unwrap(); + s.selection.ids.clear(); +} + +fn keywords_of(s: &Session, id: u64) -> Vec { + let mut k = s.catalog.photo(PhotoId(id)).unwrap().meta.keywords.clone(); + k.sort(); + k +} + +fn undo(s: &mut Session) { + s.execute("edit.undo", &json!({})).unwrap(); +} + +#[test] +fn several_albums_are_deleted_as_one_step() { + let mut s = Session::new(); + let (a, b, c) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"})), album(&mut s, json!({"name": "C"}))); + let steps = s.undo.len(); + let r = s.execute("album.delete", &json!({"ids": [a, c]})).unwrap(); + assert_eq!(r["deleted"], 2); + assert_eq!((has_album(&s, a), has_album(&s, b), has_album(&s, c)), (false, true, false)); + assert_eq!(s.undo.len(), steps + 1, "one step"); + assert_eq!(s.undo.last().unwrap().label, "Delete 2 Albums"); + undo(&mut s); + assert!(has_album(&s, a) && has_album(&s, c)); +} + +#[test] +fn a_folder_and_an_album_inside_it_are_deleted_once() { + let mut s = Session::new(); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inside = album(&mut s, json!({"name": "Alps", "parent": folder})); + let other = album(&mut s, json!({"name": "Other"})); + s.execute("album.delete", &json!({"ids": [inside, folder, other]})).unwrap(); + assert!(!has_album(&s, folder) && !has_album(&s, inside) && !has_album(&s, other)); + undo(&mut s); + assert_eq!(parent_of(&s, inside), Some(folder), "back where it was"); + assert!(has_album(&s, other)); +} + +#[test] +fn deleting_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let steps = s.undo.len(); + let e = s.execute("album.delete", &json!({"ids": [a, 4242]})).unwrap_err().to_string(); + assert!(e.contains("4242"), "{e}"); + assert!(has_album(&s, a), "nothing was deleted"); + assert_eq!(s.undo.len(), steps); + for bad in [json!([]), json!("a"), json!([a, "b"])] { + assert!(s.execute("album.delete", &json!({"ids": bad})).is_err(), "{bad}"); + } + assert!(has_album(&s, a)); + // one alone, the way it always was + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert!(!has_album(&s, a)); + assert_eq!(s.undo.last().unwrap().label, "Delete Album"); +} + +#[test] +fn several_albums_move_into_a_folder_as_one_step() { + let mut s = Session::new(); + let (a, b) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"}))); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let steps = s.undo.len(); + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (Some(folder), Some(folder))); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Albums"); + undo(&mut s); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); + // back to the top level, both at once + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + s.execute("album.move", &json!({"ids": [a, b], "parent": null})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); +} + +#[test] +fn moving_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inner = album(&mut s, json!({"name": "Inner", "folder": true, "parent": folder})); + // a folder can't go inside itself or inside a folder it holds: then nothing moves + for parent in [folder, inner] { + let e = s.execute("album.move", &json!({"ids": [a, folder], "parent": parent})).unwrap_err().to_string(); + assert!(e.contains("Trips"), "the refusal names it: {e}"); + assert_eq!(parent_of(&s, a), None, "nothing moved"); + } + // into something that is not a folder, or not there + assert!(s.execute("album.move", &json!({"ids": [folder], "parent": a})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a], "parent": 4242})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a, 4242], "parent": folder})).is_err()); + assert_eq!(parent_of(&s, a), None); + // a folder and an album already inside it: the folder moves, and the album with it + let outer = album(&mut s, json!({"name": "Outer", "folder": true})); + let within = album(&mut s, json!({"name": "Within", "parent": inner})); + s.execute("album.move", &json!({"ids": [within, inner], "parent": outer})).unwrap(); + assert_eq!((parent_of(&s, inner), parent_of(&s, within)), (Some(outer), Some(inner))); +} + +#[test] +fn several_keywords_are_deleted_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach", "trips|italy"]); + tag(&mut s, ids[1], &["beach", "town"]); + let steps = s.undo.len(); + let r = s.execute("keyword.delete", &json!({"keywords": ["alps", "beach", "trips"]})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + assert_eq!(keywords_of(&s, ids[1]), vec!["town"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Delete 3 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach", "trips|italy"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); + // nothing named: refused, as is something that is no keyword + for bad in [json!([]), json!([""]), json!(7), json!(["alps", 7])] { + assert!(s.execute("keyword.delete", &json!({"keywords": bad})).is_err(), "{bad}"); + } + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); +} + +#[test] +fn deleting_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 1); + tag(&mut s, ids[0], &["alps", "trips|italy"]); + let steps = s.undo.len(); + let e = s.execute("keyword.delete", &json!({"keywords": ["alps", "nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("no keyword") && e.contains("nowhere"), "names the one that is missing: {e}"); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "trips|italy"]); + assert_eq!(s.undo.len(), steps); + // a keyword that is only the upper level of one, in another case, is there + s.execute("keyword.delete", &json!({"keywords": ["ALPS", "Trips"]})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + // one keyword that is not there is still a no-op, as before + let steps = s.undo.len(); + s.execute("keyword.delete", &json!({"keyword": "nowhere"})).unwrap(); + assert_eq!(s.undo.len(), steps); +} + +#[test] +fn several_keywords_move_inside_another_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach"]); + tag(&mut s, ids[1], &["beach", "places"]); + let steps = s.undo.len(); + let r = s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), vec!["places|alps", "places|beach"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["places", "places|beach"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); + // …and back out to the top level + s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + s.execute("keyword.move", &json!({"keywords": ["places|alps", "places|beach"], "parent": null})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); +} + +#[test] +fn moving_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "europe|alps", "beach", "asia|beach", "places"]); + let before = keywords_of(&s, ids[0]); + let steps = s.undo.len(); + // a name that is taken where they go: moving would merge the two, which is not done in a batch + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "alps"], "parent": "europe"})).unwrap_err().to_string(); + assert!(e.contains("europe|alps"), "names the one in the way: {e}"); + // two of them with one name + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "asia|beach"], "parent": "places"})).unwrap_err().to_string(); + assert!(e.to_lowercase().contains("beach"), "{e}"); + // inside one of themselves; one that is no keyword + assert!(s.execute("keyword.move", &json!({"keywords": ["places", "alps"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": ["alps", "nope"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": [], "parent": "places"})).is_err()); + assert_eq!(keywords_of(&s, ids[0]), before, "nothing moved"); + assert_eq!(s.undo.len(), steps); + // a keyword and one below it: the upper one moves, and the lower with it + s.execute("keyword.move", &json!({"keywords": ["europe|alps", "europe"], "parent": "places"})).unwrap(); + assert!(keywords_of(&s, ids[0]).contains(&"places|europe|alps".to_string())); +} + +fn add_file(s: &mut Session, path: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +fn deleted(s: &Session, id: u64) -> bool { + s.catalog.photo(PhotoId(id)).unwrap().deleted +} + +#[test] +fn several_folders_leave_the_library_as_one_step() { + let mut s = Session::new(); + let alps = add_file(&mut s, "/pics/2025/alps/a.jpg"); + let beach = add_file(&mut s, "/pics/2026/beach/c.jpg"); + let town = add_file(&mut s, "/pics/2026/town/d.jpg"); + let steps = s.undo.len(); + // refused as a whole when one is not a folder of the library + let e = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(!deleted(&s, alps)); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"]})).unwrap(); + assert_eq!(r["removed"], 2); + assert_eq!((deleted(&s, alps), deleted(&s, beach), deleted(&s, town)), (true, true, false)); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Remove 2 Folders from Library"); + undo(&mut s); + assert!(!deleted(&s, alps) && !deleted(&s, beach)); + // a folder and one inside it: each photo once + add_file(&mut s, "/pics/2025/alps/day1/b.jpg"); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps/day1", "/pics/2025/alps"]})).unwrap(); + assert_eq!(r["removed"], 2); +} + +#[test] +fn several_folders_get_a_colour_label_as_one_step() { + let mut s = Session::new(); + add_file(&mut s, "/pics/2025/alps/a.jpg"); + add_file(&mut s, "/pics/2026/beach/c.jpg"); + let label = |s: &Session, path: &str| s.catalog.folder_record(path).and_then(|r| r.label); + let steps = s.undo.len(); + let e = s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/nowhere"], "label": "red"})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(label(&s, "/pics/2025/alps").is_none(), "nothing was labelled"); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "red"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_some() && label(&s, "/pics/2026/beach").is_some()); + assert_eq!(s.undo.len(), steps + 1); + undo(&mut s); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); + // taking the labels off, both at once + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "blue"})).unwrap(); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "none"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 46aabad7371..865c1e0099c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-MULTISELECT: several sidebar albums, keywords or folders are deleted, moved or labeled as one undo step in the engine, no sidebar caller yet; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -457,7 +457,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`) | `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1026,3 +1026,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | +| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); status unchanged (✅) | From 7488ac076cf0aa69b6fab06cf8b23f2222ede7d0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 12:40:07 -0400 Subject: [PATCH 12/55] LR-BEHAV-MULTISELECT: batch keyword checks fold each path once and use sets move_keywords_ops and the keyword list of keyword.delete / keyword.move compared every pair of paths, lower-casing both each time. Each path is now folded once and looked up in a set, with the upper levels of a path checked at each separator. Same keywords refused or moved, same errors. --- crates/catalog/src/keywords.rs | 30 ++++++++++++++++++++---------- crates/engine/src/cmd/keywords.rs | 3 ++- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index 9851666bc75..072c0bbc5bf 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -10,7 +10,7 @@ //! photo has them, or given attributes ([`KeywordInfo`]: synonyms, export options, person). The //! tree is the keyword list together with the keywords photos carry. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use serde::{Deserialize, Serialize}; @@ -35,6 +35,12 @@ pub fn is_under(k: &str, parent: &str) -> bool { k == p || k.strip_prefix(&p).is_some_and(|rest| rest.starts_with(SEP)) } +/// The upper levels of a case folded keyword path, each as a prefix of it ending before a `|` +/// (`a|b|c` gives `a`, `a|b`), the way [`is_under`] sees them. +fn upper_levels(folded: &str) -> impl Iterator { + folded.match_indices(SEP).map(|(i, _)| &folded[..i]) +} + /// Replace the `from` prefix of `k` (which [`is_under`] `from`) with `to`. By levels, not bytes: /// `from` may be written in another case, which can change a letter's length (ẞ / ß). pub fn reparent(k: &str, from: &str, to: &str) -> String { @@ -479,30 +485,34 @@ impl Catalog { /// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole /// move. Returns the batch and each move as `(from, to)`. pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> { + // paths are case folded once and kept in sets: a batch of thousands stays linear let mut from: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); for k in keywords { let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?; - if !from.iter().any(|f| same(f, &path)) { + if seen.insert(path.to_lowercase()) { from.push(path); } } if from.is_empty() { return Err(CatalogError::Invalid("no keyword to move".into())); } - // the upper ones only - let all = from.clone(); - from.retain(|f| !all.iter().any(|o| !same(o, f) && is_under(f, o))); + // the upper ones only: a keyword goes when one of its upper levels is named too + from.retain(|f| !upper_levels(&f.to_lowercase()).any(|up| seen.contains(up))); + let upper: HashSet = from.iter().map(|f| f.to_lowercase()).collect(); let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p)); - if let Some(p) = &parent - && from.iter().any(|f| is_under(p, f)) - { - return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + if let Some(p) = &parent { + let p = p.to_lowercase(); + if upper.contains(&p) || upper_levels(&p).any(|up| upper.contains(up)) { + return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + } } let mut moves: Vec<(String, String)> = Vec::new(); + let mut names: HashSet = HashSet::new(); for f in &from { let leaf = f.rsplit(SEP).next().unwrap_or(f); let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}")); - if moves.iter().any(|(_, t)| same(t, &to)) { + if !names.insert(to.to_lowercase()) { return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time"))); } moves.push((f.clone(), to)); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 429f7b0a02e..7f3f94b6beb 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -86,10 +86,11 @@ fn keyword_list(p: &Value, command: &str) -> Result> { return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords"))); } let mut out: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); for k in list { let k = k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?; - if !out.iter().any(|o| lightcraft_catalog::keywords::same(o, &k)) { + if seen.insert(k.to_lowercase()) { out.push(k); } } From 5ab04d7ee1cb819a8981e5e1856c55901ef384cc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 12:42:24 -0400 Subject: [PATCH 13/55] LR-BEHAV-MULTISELECT: the parity row is partial until the sidebar calls the batch commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine commands exist but no sidebar row can choose several items yet, so the row is 🟡, not ✅ (usable end to end). Summary counts refreshed. --- docs/parity-checklist.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 865c1e0099c..06f6b32ea9f 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -49,13 +49,13 @@ cited here still exists. Formerly docs/parity.md. | U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) | | V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) | | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | -| X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | +| X. Cross-cutting behaviours (BEHAV) | 22 | 7 | 1 | 1 | 7/8 (88%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 420 | 66 | 57 | 35 | 195/203 (96%) | 146/161 (91%) | +| **Total** | 419 | 67 | 57 | 35 | 194/203 (96%) | 146/161 (91%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.4%** of 543 in-scope rows — P0 98.0% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.3%** of 543 in-scope rows — P0 97.8% of 203 · P1 94.4% of 161 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -457,7 +457,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | 🟡 | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/batch_sidebar.rs` | several albums, folders of albums, keywords or library folders chosen in the sidebar are deleted, moved or labeled as one undo step: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`; each checks everything first and names what it refuses (engine only, no sidebar caller yet); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1026,4 +1026,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | patch | LR-BEHAV-TITLEBAR: a dialog's backdrop leaves the integrated title bar undimmed, as a macOS sheet does (the bar's controls stay inactive, a click on it is not a click outside the dialog, dragging its empty space still moves the window); status unchanged (🟡) | | 2026-10-29 | minor | LR-MASK-OBJECTS: an Object / Describe selection's stored grid is enlarged along the photo's edges (fast guided filter of its logits by log luminance, a 1.5-cell window), so a raised Exposure no longer draws an outline around the subject (#3272); existing AI masks are 1–2 px tighter at edges; status unchanged (🟡) | | 2026-10-30 | patch | LR-MASK-COLORRANGE: a colour-range mask keeps its first 64 samples however it is loaded (sidecar `lc:settings`, presets, `develop.merge`, `render --settings`, catalog and history), not only through `mask.add` / `mask.update`, so a document with thousands can't stall a render or lose the GPU device (issue #2556); status unchanged (✅) | -| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); status unchanged (✅) | +| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); downgraded ✅ → 🟡 until they exist | From 880bf8dbe12a05125251db54ebbf060b2523935e Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 17:34:34 -0400 Subject: [PATCH 14/55] Sidebars: several albums, folders, keywords or dates can be shown at once (engine) library.source takes `ids` (albums) or `paths` (library folders) and library.filter takes `keywords`, `dates`, `libraryFolders` and `albums`: the grid shows the photos of any of them, each once. The single fields stay and count as one more of them. library.state lists what is shown; a deleted album or a folder that left the library leaves the others shown. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 9 +- crates/catalog/src/query.rs | 170 ++++++++-- crates/engine/src/cmd/browse.rs | 17 + crates/engine/src/cmd/keywords.rs | 26 +- crates/engine/src/cmd/library.rs | 1 + crates/engine/src/cmd/library/filters.rs | 36 ++- crates/engine/src/cmd/library/specs.rs | 186 ++++++++--- crates/engine/src/cmd/query.rs | 7 +- crates/engine/src/lib.rs | 162 ++++++++-- crates/engine/src/library.rs | 41 ++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/multi_source.rs | 389 +++++++++++++++++++++++ crates/engine/src/tests/organize.rs | 19 ++ crates/engine/src/view.rs | 31 +- docs/parity-checklist.md | 3 +- docs/whats-new.md | 7 + 16 files changed, 979 insertions(+), 126 deletions(-) create mode 100644 crates/engine/src/tests/multi_source.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 5a82d2a67d6..b1769e680be 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -599,8 +599,9 @@ impl Catalog { /// A loop through `filter`'s own album field (not its rules): smart album `owner` filtered to /// itself, or to an album that leads back to it. pub fn album_filter_problem(&self, filter: &Filter, owner: Option) -> Option { - let (a, owner) = (filter.album?, owner?); - (a == owner || self.album_reaches(a, owner)).then(|| rules::Problem { + let owner = owner?; + let a = filter.albums_wanted().into_iter().find(|a| *a == owner || self.album_reaches(*a, owner))?; + Some(rules::Problem { path: Vec::new(), field: Some("album".into()), issue: rules::Issue::AlbumLoop, @@ -638,9 +639,7 @@ impl Catalog { if rules.deleted { return Err(CatalogError::Invalid("smart album rules can't select deleted photos".into())); } - if let Some(a) = rules.album - && self.albums.get(&a).is_some_and(Album::is_smart) - { + if rules.albums_wanted().iter().any(|a| self.albums.get(a).is_some_and(Album::is_smart)) { return Err(CatalogError::Invalid("smart album rules can't reference another smart album".into())); } Ok(()) diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index efa62ea6d86..7668540cc11 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -43,16 +43,29 @@ pub struct Filter { pub kind: Option, pub edited: Option, pub album: Option, + /// More albums beside [`Filter::album`] (several albums chosen in the sidebar): a photo in any + /// of them matches; empty = no more. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub albums: Vec, /// Show "Recently Deleted" instead of the library. pub deleted: bool, /// Capture date prefix (`2026`, `2026-04`, `2026-04-12`). pub date: Option, + /// More capture date prefixes beside [`Filter::date`]: a photo of any of them matches. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub dates: Vec, /// A folder the library's photos were imported from: those photos and the ones imported from /// the folders inside it (see [`crate::folders`]). Photos only browsed in Local are never part /// of it, unlike [`Filter::folder`]. pub library_folder: Option, + /// More folders beside [`Filter::library_folder`]: a photo of any of them matches. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub library_folders: Vec, /// A keyword; hierarchical keywords match their children too (`travel` finds `travel|italy`). pub keyword: Option, + /// More keywords beside [`Filter::keyword`]: a photo with any of them matches. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub keywords: Vec, /// A person: photos with a named face region of this name (case-insensitive), as read from XMP. pub person: Option, pub camera: Option, @@ -150,7 +163,8 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 { /// What [`Filter::prepare`] works out once for a pass over many photos. pub(crate) struct Prepared { - root: Option, + /// The library folders' identities ([`Filter::library_roots`]): a photo in any of them. + roots: Vec, only: Option>, /// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]); /// `None` tests them as written. @@ -314,13 +328,16 @@ impl Filter { if let Some(e) = self.edited { v.push(if e { "edited".into() } else { "unedited".into() }); } + let (keywords, dates, folders) = (self.keywords_wanted().join(" or "), self.dates_wanted().join(" or "), self.library_folders_wanted()); + let folders = folders.join(" or "); + let some = |s: String| (!s.is_empty()).then_some(s); for (name, val) in [ - ("keyword", &self.keyword), + ("keyword", &some(keywords)), ("person", &self.person), ("camera", &self.camera), ("lens", &self.lens), - ("date", &self.date), - ("folder", &self.library_folder), + ("date", &some(dates)), + ("folder", &some(folders)), ("imported", &self.imported), ] { if let Some(x) = val { @@ -344,7 +361,7 @@ impl Filter { /// The albums this filter tests: its album field and its rules' Album rules. pub fn albums_tested(&self) -> Vec { - let mut out: Vec = self.album.into_iter().collect(); + let mut out: Vec = self.albums_wanted(); out.extend(self.rule_set.as_ref().map(crate::RuleSet::albums_tested).unwrap_or_default()); out } @@ -356,13 +373,13 @@ impl Filter { pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { // one photo: its rules are tested as written (ordering them would cost more than it saves) - self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None }) + self.matches_in(p, cat, &Prepared { roots: self.library_roots(), only: None, rules: None }) } /// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once /// (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared { - Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) } + Prepared { roots: self.library_roots(), only: None, rules: self.ordered_rules(cat) } } /// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None` @@ -376,21 +393,80 @@ impl Filter { } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than - /// once per photo: the library folder's identity, the `only` ids as a set and the rules in the + /// once per photo: the library folders' identities, the `only` ids as a set and the rules in the /// order to test them. pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared { Prepared { - root: self.library_root(), + roots: self.library_roots(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), rules: self.ordered_rules(cat), } } - /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. - fn library_root(&self) -> Option { + /// The albums a photo may be in: [`Filter::album`] and [`Filter::albums`], each once (in that + /// order); empty = no constraint. + pub fn albums_wanted(&self) -> Vec { + let mut out: Vec = Vec::new(); + for a in self.album.iter().chain(&self.albums) { + if !out.contains(a) { + out.push(*a); + } + } + out + } + + /// The keywords a photo may have: [`Filter::keyword`] and [`Filter::keywords`], each once + /// (whatever its case). + pub fn keywords_wanted(&self) -> Vec { + let mut out: Vec = Vec::new(); + for k in self.keyword.iter().chain(&self.keywords) { + if !out.iter().any(|o| crate::keywords::same(o, k)) { + out.push(k.clone()); + } + } + out + } + + /// The capture date prefixes a photo may have: [`Filter::date`] and [`Filter::dates`], each once. + pub fn dates_wanted(&self) -> Vec { + let mut out: Vec = Vec::new(); + for d in self.date.iter().chain(&self.dates) { + if !out.contains(d) { + out.push(d.clone()); + } + } + out + } + + /// The folders a photo may be in: [`Filter::library_folder`] and [`Filter::library_folders`], + /// as given, each once (by folder identity). A blank one is no folder. + pub fn library_folders_wanted(&self) -> Vec { + let mut out: Vec = Vec::new(); + let mut keys: Vec = Vec::new(); // as given: a folder may be named with spaces at its edge, and trimming would make it // another folder - self.library_folder.as_deref().filter(|d| !d.trim().is_empty()).map(folder_key) + for d in self.library_folder.iter().chain(&self.library_folders).filter(|d| !d.trim().is_empty()) { + let key = folder_key(d); + if !keys.contains(&key) { + keys.push(key); + out.push(d.clone()); + } + } + out + } + + /// The folders wanted ([`Filter::library_folders_wanted`]) as folder identities + /// ([`folder_key`]); empty without a choice. + fn library_roots(&self) -> Vec { + // (each folder's identity is worked out once: this runs per photo for a smart album) + let mut roots: Vec = Vec::new(); + for d in self.library_folder.iter().chain(&self.library_folders).filter(|d| !d.trim().is_empty()) { + let key = folder_key(d); + if !roots.contains(&key) { + roots.push(key); + } + } + roots } /// [`Filter::matches`] with what [`Filter::prepare`] works out done already, so a query over a @@ -449,9 +525,7 @@ impl Filter { _ => return false, } } - if let Some(a) = self.album - && !cat.album_contains(a, p) - { + if (self.album.is_some() || !self.albums.is_empty()) && !self.album.iter().chain(&self.albums).any(|a| cat.album_contains(*a, p)) { return false; } if let Some(from) = &self.date_from @@ -475,14 +549,12 @@ impl Filter { { return false; } - if let Some(d) = &self.date - && !p.captured.as_deref().is_some_and(|c| c.starts_with(d.as_str())) + if (self.date.is_some() || !self.dates.is_empty()) + && !p.captured.as_deref().is_some_and(|c| self.date.iter().chain(&self.dates).any(|d| c.starts_with(d.as_str()))) { return false; } - if let Some(root) = prepared.root.as_deref() - && !photo_in_root(p, root) - { + if !prepared.roots.is_empty() && !prepared.roots.iter().any(|root| photo_in_root(p, root)) { return false; } if let Some(d) = &self.imported @@ -495,8 +567,8 @@ impl Filter { { return false; } - if let Some(k) = &self.keyword - && !p.meta.keywords.iter().any(|x| crate::keywords::is_under(x, k)) + if (self.keyword.is_some() || !self.keywords.is_empty()) + && !p.meta.keywords.iter().any(|x| self.keyword.iter().chain(&self.keywords).any(|k| crate::keywords::is_under(x, k))) { return false; } @@ -750,6 +822,60 @@ pub fn folder_rest(path: &str, root: &str) -> Option> { Some(split_path(path, false).parts.into_iter().skip(depth).collect()) } +impl Catalog { + /// For each of `folders`, whether the library holds a photo imported from it or from a folder + /// inside it (one pass over the library, however many folders). + pub fn folders_holding(&self, folders: &[String]) -> Vec { + let roots: Vec = folders.iter().map(|d| folder_key(d)).collect(); + let mut holds = vec![false; roots.len()]; + let mut left = roots.len(); + for p in self.photos().filter(|p| !p.deleted) { + for (h, root) in holds.iter_mut().zip(&roots) { + if !*h && photo_in_root(p, root) { + *h = true; + left -= 1; + } + } + if left == 0 { + break; + } + } + holds + } + + /// For each of `folders`: whether the library holds a photo imported from it (or from a + /// folder inside it), and whether some of those photos are on a disk (not the startup disk) + /// the folder does not lie in, which makes it a way to several disks (`/Volumes`, `/mnt`…) + /// and not a folder of one. One pass over the library, however many folders. + pub fn folders_scan(&self, folders: &[String]) -> Vec { + let roots: Vec = folders.iter().map(|d| folder_key(d)).collect(); + let mut out = vec![FolderScan::default(); roots.len()]; + for p in self.photos().filter(|p| !p.deleted) { + let mut volume: Option> = None; + for (scan, root) in out.iter_mut().zip(&roots) { + if (scan.holds && scan.other_disks) || !photo_in_root(p, root) { + continue; + } + scan.holds = true; + let v = volume.get_or_insert_with(|| crate::folders::volume_of(p)); + if v.as_deref().is_some_and(|v| v != "/" && !key_within(root, v)) { + scan.other_disks = true; + } + } + } + out + } +} + +/// What [`Catalog::folders_scan`] finds for one folder. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FolderScan { + /// The library holds a photo imported from it or from a folder inside it. + pub holds: bool, + /// Some of its photos are on another disk than the one the folder lies in. + pub other_disks: bool, +} + /// Whether a library photo (not one only browsed in Local) lies in the folder whose /// [`folder_key`] is `root`. A plain POSIX path (no `\`, `.`, `..`, repeated or trailing /// separators) is its own identity, so it is read without building a key for it: the check runs diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 0eb126c40f7..677ffd000cd 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -485,12 +485,29 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result { pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { // a library folder chosen at or below it follows too, as a source or as a filter follow_library_folder(&mut s.library_folder, from, to); + for other in &mut s.also_library_folders { + let mut chosen = Some(std::mem::take(other)); + follow_library_folder(&mut chosen, from, to); + *other = chosen.unwrap_or_default(); + } follow_library_folder(&mut s.filter.library_folder, from, to); follow_library_folder(&mut s.filter.folder, from, to); if let Some(f) = s.shelved_filter.as_mut() { follow_library_folder(&mut f.library_folder, from, to); follow_library_folder(&mut f.folder, from, to); } + for other in &mut s.filter.library_folders { + let mut chosen = Some(std::mem::take(other)); + follow_library_folder(&mut chosen, from, to); + *other = chosen.unwrap_or_default(); + } + if let Some(f) = s.shelved_filter.as_mut() { + for other in &mut f.library_folders { + let mut chosen = Some(std::mem::take(other)); + follow_library_folder(&mut chosen, from, to); + *other = chosen.unwrap_or_default(); + } + } if let Some(b) = &mut s.browse && let Ok(rel) = Path::new(&b.path).strip_prefix(from) { diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 0e612227f1f..e602b9d619e 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -33,15 +33,27 @@ fn commit_keywords(s: &mut Session, label: &str, op: lightcraft_catalog::Op, fol if let Some(k) = s.filter.keyword.clone() { s.filter.keyword = follow(&k); } + // several keywords filtered by: each follows, one that is gone leaves + let follow_all = |keywords: &[String]| { + let mut kept: Vec = Vec::new(); + for k in keywords.iter().filter_map(|k| follow(k)) { + if !kept.iter().any(|o| lightcraft_catalog::keywords::same(o, &k)) { + kept.push(k); + } + } + kept + }; + s.filter.keywords = follow_all(&s.filter.keywords); // a filter put aside by Enable Filters follows the keyword too let mut gone_from_put_aside = false; - if let Some(f) = s.shelved_filter.as_mut() - && let Some(k) = f.keyword.clone() - { - f.keyword = follow(&k); - // the keyword was deleted: if that emptied the filter, nothing is left to bring back. The rating - // operator filters nothing without stars, so it alone does not count as something to bring back. - gone_from_put_aside = f.keyword.is_none() && (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default(); + if let Some(f) = s.shelved_filter.as_mut() { + if let Some(k) = f.keyword.clone() { + f.keyword = follow(&k); + // the keyword was deleted: if that emptied the filter, nothing is left to bring back. The rating + // operator filters nothing without stars, so it alone does not count as something to bring back. + gone_from_put_aside = f.keyword.is_none() && (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default(); + } + f.keywords = follow_all(&f.keywords); } if gone_from_put_aside { s.shelved_filter = None; diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4bf9654250e..6cd7167f38f 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -15,6 +15,7 @@ mod specs; pub(crate) use filters::covers_other_disks; pub use import::{ImportRequest, import_batch_done, import_params, list_auto_import_folder}; +pub(crate) use specs::MAX_SOURCES; pub use specs::specs; #[cfg(test)] diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index f0a3a504f34..736b462cc38 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -29,7 +29,8 @@ pub(super) fn merge_rules( let sets_rules = patch.get("ruleSet").is_some_and(|r| !r.is_null()); let mut problems = f.rule_set.as_ref().filter(|_| sets_rules).map(|r| r.check_for(cat, owner)).unwrap_or_default(); // and a loop through the album field the change sets - if patch.get("album").is_some_and(|a| !a.is_null()) { + let sets = |key: &str| patch.get(key).is_some_and(|a| !a.is_null()); + if sets("album") || sets("albums") { problems.extend(cat.album_filter_problem(&f, owner)); } if !problems.is_empty() { @@ -48,12 +49,33 @@ pub(crate) fn covers_other_disks(s: &Session, path: &str, ids: &[PhotoId]) -> bo .any(|v| v != "/" && !lightcraft_catalog::query::folder_within(path, &v)) } +/// A view of several albums can't be saved when one of them is a smart album (smart album rules +/// can't test another smart album): refuse up front, naming it, instead of letting the rules' +/// check say so without the cause. +pub(super) fn several_smart_refused(s: &Session, cmd: &str) -> Result<()> { + let shown = s.source_albums(); + if shown.len() < 2 { + return Ok(()); + } + match shown.iter().find_map(|a| s.catalog.album(*a).filter(|a| a.is_smart())) { + Some(smart) => Err(bad( + cmd, + format!( + "the view shows several albums and \"{}\" is a smart album: smart album rules can't test another smart album. Show only albums that aren't smart, or save the smart album's own view", + smart.name + ), + )), + None => Ok(()), + } +} + /// The current view (source + filter) as smart-album rules. Viewing a smart album starts from /// its rules with the filter bar's settings on top. pub(super) fn view_rules(s: &Session) -> lightcraft_catalog::Filter { use lightcraft_catalog::Filter; let smart = match s.source { - LibrarySource::Album(a) => s.catalog.album(a).and_then(|a| a.smart.as_deref().cloned()), + // (one smart album alone: among several albums shown it is one more album) + LibrarySource::Album(a) if s.also_albums.is_empty() => s.catalog.album(a).and_then(|a| a.smart.as_deref().cloned()), _ => None, }; match smart { @@ -76,8 +98,14 @@ pub(super) fn view_rules(s: &Session) -> lightcraft_catalog::Filter { None => { let mut f = s.source.to_filter(&s.filter, &s.catalog); f.deleted = false; - if s.source == LibrarySource::LibraryFolder { - f.library_folder = s.library_folder.clone(); + match s.source { + LibrarySource::LibraryFolder => { + f.library_folder = s.library_folder.clone(); + f.library_folders = s.also_library_folders.clone(); + } + // every album shown, not the filter's own + LibrarySource::Album(_) => f.albums = s.also_albums.clone(), + _ => {} } f } diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index c725ac216b8..3c94a6f27e7 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1,4 +1,4 @@ -use super::filters::{covers_other_disks, merge_rules, view_rules}; +use super::filters::{covers_other_disks, merge_rules, several_smart_refused, view_rules}; use super::gps::parse_gps; use super::import::{import_batch_done, import_params, list_auto_import_folder}; use super::selection::{ @@ -6,8 +6,8 @@ use super::selection::{ opt_album_param, rotate, row_step, select_after_deletion, select_by, step, strs, }; use super::{ - Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey, - Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, + Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Session, Sort, + SortKey, Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param, }; /// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote. @@ -29,6 +29,67 @@ fn next_seed(prev: u64, now: &str) -> u64 { (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1) } +/// How many albums or folders one `library.source` call may name: far more than a person +/// chooses in a sidebar, and a bound on what a caller can make each refresh test. +pub(crate) const MAX_SOURCES: usize = 1000; + +/// `library.source`'s `ids`: album ids, each once (named twice, the last naming counts). +fn source_album_ids(v: &Value) -> Result> { + const C: &str = "library.source"; + let list = v.as_array().ok_or_else(|| bad(C, "`ids` must be a list of album ids"))?; + if list.len() > MAX_SOURCES { + return Err(bad(C, format!("`ids` names more than {MAX_SOURCES} albums"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let id = AlbumId(x.as_u64().ok_or_else(|| bad(C, format!("`ids` must be a list of album ids, not {x}")))?); + out.retain(|o| *o != id); + out.push(id); + } + Ok(out) +} + +/// `library.source`'s `paths`: folder paths, each folder once (named twice, the last counts). +fn source_folder_paths(v: &Value) -> Result> { + const C: &str = "library.source"; + let list = v.as_array().ok_or_else(|| bad(C, "`paths` must be a list of folder paths"))?; + if list.len() > MAX_SOURCES { + return Err(bad(C, format!("`paths` names more than {MAX_SOURCES} folders"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let path = x.as_str().ok_or_else(|| bad(C, format!("`paths` must be a list of folder paths, not {x}")))?; + let key = lightcraft_catalog::query::folder_key(path); + out.retain(|o| lightcraft_catalog::query::folder_key(o) != key); + out.push(path.to_string()); + } + Ok(out) +} + +/// Whether `path` can be shown as a `libraryFolder` source: a folder (not the whole startup +/// disk, nor a way to several disks) the library holds photos of. +/// (One pass over the library for all of `paths`, however many.) +fn source_folders_check(s: &Session, paths: &[String]) -> Result<()> { + const C: &str = "library.source"; + for path in paths { + if path.trim().is_empty() || lightcraft_catalog::query::folder_key(path).is_empty() { + return Err(bad(C, "libraryFolder needs the `path` of a folder from library.folders")); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(bad(C, "the startup disk's path covers every disk: choose a folder in it")); + } + } + for (path, found) in paths.iter().zip(s.catalog.folders_scan(paths)) { + if !found.holds { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if found.other_disks { + return Err(bad(C, format!("{path} holds other disks as well: choose a disk or a folder on one"))); + } + } + Ok(()) +} + pub fn specs() -> Vec { vec![ // ---- view source / filter / sort @@ -37,47 +98,52 @@ pub fn specs() -> Vec { "Show Source", [], None, - "{kind: all|recentlyAdded|album|recentlyDeleted|picks|missing|libraryFolder, id?: albumId, path?: a path from library.folders (for libraryFolder)}", + "{kind: all|recentlyAdded|album|recentlyDeleted|picks|missing|libraryFolder, id?: albumId, path?: a path from library.folders (for libraryFolder), ids?: [albumId] or paths?: [path] to show several albums or several folders at once (the photos of any of them, each once; the last one named is the one single-album and single-folder actions take)}", always, |s, p| { + const C: &str = "library.source"; let kind = str_param(p, "kind").unwrap_or("all"); - s.source = match kind { - "all" => LibrarySource::All, - "recentlyAdded" => LibrarySource::RecentlyAdded, - "recentlyDeleted" => LibrarySource::RecentlyDeleted, - "picks" => LibrarySource::Picks, - "missing" => LibrarySource::Missing, + // everything is checked before anything changes: a refused call leaves the view + let (source, albums, folders) = match kind { + "all" => (LibrarySource::All, Vec::new(), Vec::new()), + "recentlyAdded" => (LibrarySource::RecentlyAdded, Vec::new(), Vec::new()), + "recentlyDeleted" => (LibrarySource::RecentlyDeleted, Vec::new(), Vec::new()), + "picks" => (LibrarySource::Picks, Vec::new(), Vec::new()), + "missing" => (LibrarySource::Missing, Vec::new(), Vec::new()), "album" => { - let a = album_param(p, "id", "library.source")?; - if s.catalog.album(a).is_none_or(|a| a.folder) { - return Err(bad("library.source", "no such album")); + let mut albums = match p.get("ids") { + None | Some(Value::Null) => vec![album_param(p, "id", C)?], + Some(v) => source_album_ids(v)?, + }; + if let Some(gone) = albums.iter().find(|a| s.catalog.album(**a).is_none_or(|a| a.folder)) { + let several = p.get("ids").is_some_and(|v| !v.is_null()); + return Err(bad(C, if several { format!("no such album {}", gone.0) } else { "no such album".into() })); } - // one album at a time: `to_filter` makes the album shown replace the filter's, and the - // filter bar has no album chip, so a left-over one would narrow the next source unseen + // the last one named is the one a single-album action takes + let Some(own) = albums.pop() else { return Err(bad(C, "`ids` names no album")) }; + // the albums of the source: albums left over in the filter would be ignored + s.filter.albums.clear(); s.filter.album = None; - LibrarySource::Album(a) + (LibrarySource::Album(own), albums, Vec::new()) } "libraryFolder" => { - let path = str_param(p, "path").filter(|d| !d.trim().is_empty() && !lightcraft_catalog::query::folder_key(d).is_empty()); - let path = path.ok_or_else(|| bad("library.source", "libraryFolder needs the `path` of a folder from library.folders"))?; - if lightcraft_catalog::folders::is_startup_disk(path) { - return Err(bad("library.source", "the startup disk's path covers every disk: choose a folder in it")); - } - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - let ids = s.catalog.query(&f, &Sort::default()); - if ids.is_empty() { - return Err(bad("library.source", format!("{path}: no photo in the library was imported from it"))); - } - if covers_other_disks(s, path, &ids) { - return Err(bad("library.source", format!("{path} holds other disks as well: choose a disk or a folder on one"))); - } - s.library_folder = Some(path.to_string()); - // one folder at a time: a folder filter left over would be ignored + let mut folders = match p.get("paths") { + None | Some(Value::Null) => vec![str_param(p, "path").unwrap_or_default().to_string()], + Some(v) => source_folder_paths(v)?, + }; + source_folders_check(s, &folders)?; + let Some(own) = folders.pop() else { return Err(bad(C, "`paths` names no folder")) }; + s.library_folder = Some(own); + // the folders of the source: a folder filter left over would be ignored s.filter.library_folder = None; - LibrarySource::LibraryFolder + s.filter.library_folders.clear(); + (LibrarySource::LibraryFolder, Vec::new(), folders) } - other => return Err(bad("library.source", format!("unknown source `{other}`"))), + other => return Err(bad(C, format!("unknown source `{other}`"))), }; + s.source = source; + s.also_albums = albums; + s.also_library_folders = folders; s.keep_active_in_view(); Ok(json!({"count": s.visible().len()})) } @@ -87,7 +153,7 @@ pub fn specs() -> Vec { "Filter", [], None, - "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, flags?: [pick|reject|none] (any of them; [] = no constraint), label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?}", + "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, flags?: [pick|reject|none] (any of them; [] = no constraint), label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?, keywords?: [keyword] / dates?: [date] / libraryFolders?: [path] / albums?: [albumId] (more of each beside the single one: a photo matching any of them is shown; [] clears)}", always, |s, p| { let mut v = serde_json::to_value(&s.filter).unwrap_or_default(); @@ -96,7 +162,21 @@ pub fn specs() -> Vec { let mut f = f; // a blank folder is no folder: no hidden "filters active" state f.library_folder = f.library_folder.filter(|d| !d.trim().is_empty()); - if f.library_folder.is_some() && s.source == LibrarySource::LibraryFolder { + f.library_folders.retain(|d| !d.trim().is_empty()); + f.keywords.retain(|k| !k.trim().is_empty()); + f.dates.retain(|d| !d.trim().is_empty()); + if let Some(n) = [f.albums.len(), f.library_folders.len(), f.keywords.len(), f.dates.len()].into_iter().find(|n| *n > MAX_SOURCES) { + return Err(bad( + "library.filter", + format!("{n} albums, folders, keywords or dates in one filter: at most {MAX_SOURCES} of each"), + )); + } + // (the source's albums are what is shown: albums in the filter would be ignored) + let sets_albums = p.get("albums").and_then(Value::as_array).is_some_and(|a| !a.is_empty()); + if sets_albums && matches!(s.source, LibrarySource::Album(_)) { + return Err(bad("library.filter", "albums are already shown (library.source): show another source first")); + } + if (f.library_folder.is_some() || !f.library_folders.is_empty()) && s.source == LibrarySource::LibraryFolder { return Err(bad("library.filter", "a folder is already shown (library.source): show another source first")); } // checked like a smart album's rules when this call sets them: an unknown field or a value @@ -154,19 +234,23 @@ pub fn specs() -> Vec { if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { s.filter.library_folder = None; } + s.filter.library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); + // of several folders shown, the others stay + s.also_library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); // a filter put aside by Enable Filters must not bring the removed folder back - if let Some(f) = s.shelved_filter.as_mut() - && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) - { - f.library_folder = None; + if let Some(f) = s.shelved_filter.as_mut() { + if f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + f.library_folder = None; + } + f.library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); } if s.shelved_filter.as_ref() == Some(&Filter::default()) { s.shelved_filter = None; } // the folder being shown is gone: back to everything, as for a deleted album if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { - s.library_folder = None; - if s.source == LibrarySource::LibraryFolder { + s.library_folder = s.also_library_folders.pop(); + if s.source == LibrarySource::LibraryFolder && s.library_folder.is_none() { s.source = LibrarySource::All; } } @@ -222,6 +306,7 @@ pub fn specs() -> Vec { // one folder at a time: the folder shown now wins over the one the filter had if s.source == LibrarySource::LibraryFolder { f.library_folder = None; + f.library_folders.clear(); } s.filter = f; } @@ -832,7 +917,10 @@ pub fn specs() -> Vec { } let rules = match p.get("rules") { Some(r) => merge_rules(&lightcraft_catalog::Filter::default(), r, "album.createSmart", &s.catalog, None)?, - None => view_rules(s), + None => { + several_smart_refused(s, "album.createSmart")?; + view_rules(s) + } }; let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); let id = s.catalog.alloc_album_id(); @@ -877,6 +965,7 @@ pub fn specs() -> Vec { let rules = if bool_or(p, "fromView", false) { // the view is saved as it is, but never as a loop (showing A, which tests this // album, and saving that view here would make it test itself) + several_smart_refused(s, "album.setRules")?; let view = view_rules(s); let loops: Vec = view .rule_set @@ -895,6 +984,7 @@ pub fn specs() -> Vec { } else { let replace = bool_or(p, "replace", false); let (folder, album) = (cur.library_folder.clone(), cur.album); + let (folders, albums) = (cur.library_folders.clone(), cur.albums.clone()); let base = if replace { Default::default() } else { cur }; let mut r = merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules", &s.catalog, Some(id))?; // the rules dialog has no folder field: replacing its rules keeps the folder @@ -907,6 +997,14 @@ pub fn specs() -> Vec { if replace && p.get("rules").and_then(|r| r.get("album")).is_none() { r.album = album; } + // …nor for the other folders and albums of a view of several, saved + // (`libraryFolders: []`, `albums: []` drop them) + if replace && p.get("rules").and_then(|r| r.get("libraryFolders")).is_none() { + r.library_folders = folders; + } + if replace && p.get("rules").and_then(|r| r.get("albums")).is_none() { + r.albums = albums; + } r }; let set = Op::SetAlbumRules { id, rules: Box::new(rules) }; @@ -958,8 +1056,10 @@ pub fn specs() -> Vec { } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; + // of several albums shown, the others stay + s.also_albums.retain(|a| !removed.contains(a)); if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { - s.source = LibrarySource::All; + s.source = s.also_albums.pop().map_or(LibrarySource::All, LibrarySource::Album); } ok() } diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index 8b964302484..2bf63923900 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -106,14 +106,13 @@ pub fn specs() -> Vec { })) }), cmd!(query "library.state", "Library State", [], None, "{}", always, |s, _| { - let label = match (s.source, s.library_folder.as_deref()) { - (LibrarySource::LibraryFolder, Some(path)) => lightcraft_catalog::folders::folder_label(path), - _ => s.source.label(&s.catalog), - }; let n = s.visible().len(); + let label = s.source_label(); Ok(json!({ "source": s.source, + "albums": s.source_albums().iter().map(|a| a.0).collect::>(), "libraryFolder": s.library_folder.as_ref().filter(|_| s.source == LibrarySource::LibraryFolder), + "libraryFolders": s.source_library_folders(), "sourceLabel": label, "filter": s.filter, "sort": s.sort, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 53077f95c62..8fdc4c3c325 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -93,7 +93,7 @@ use std::sync::Arc; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use errors::{AiModel, ErrorKind}; pub use fonts::{CRAFT_FONTS, CraftFont}; -use lightcraft_catalog::{Catalog, Filter, Op, PhotoId, Sort}; +use lightcraft_catalog::{AlbumId, Catalog, Filter, Op, PhotoId, Sort}; use lightcraft_develop::DevelopSettings; pub use media::{RenderJob, SourceLevel}; use serde_json::Value; @@ -311,6 +311,13 @@ pub struct Session { /// The folder the [`LibrarySource::LibraryFolder`] view shows: the library's photos imported /// from it and from the folders inside it. pub library_folder: Option, + /// The other albums shown beside the [`LibrarySource::Album`] source (several chosen in the + /// sidebar), in the order chosen: the grid shows the photos of any of them. Never the source's + /// own album; see [`Session::source_albums`]. + pub also_albums: Vec, + /// The other folders shown beside [`Session::library_folder`], likewise; see + /// [`Session::source_library_folders`]. + pub also_library_folders: Vec, /// Copied metadata (`photo.copyMetadata`): photo.setMeta params. pub meta_clipboard: Option, /// The photo that was active before the current one (Paste Settings from Previous). @@ -508,6 +515,8 @@ impl Session { meta_clipboard: None, browse: None, library_folder: None, + also_albums: Vec::new(), + also_library_folders: Vec::new(), previous_active: None, copy_groups: lightcraft_develop::SettingsGroup::default_copy(), presets: presets::PresetList::new(presets::builtin()), @@ -1177,8 +1186,14 @@ impl Session { /// Photos shown in the grid/filmstrip for the current source, filter and sort. pub fn visible(&mut self) -> &[PhotoId] { - let mut key = - (self.catalog.revision, format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.filter, self.sort, self.browse, self.library_folder)); + self.reconcile_sources(); + let mut key = ( + self.catalog.revision, + format!( + "{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", + self.source, self.filter, self.sort, self.browse, self.library_folder, self.also_albums, self.also_library_folders + ), + ); // What a held view is told apart by: what is shown and how, and for a smart album its rules (rules that were // changed ask something else). Not the checks of Missing Photos below: they fill the view in, they are // no other view. @@ -1204,6 +1219,10 @@ impl Session { // Use this same value to evaluate relative rules and stamp the result. let now = current_now.unwrap_or_else(|| (self.clock)()); lightcraft_catalog::rules::set_now(Some(now.clone())); + if self.source == LibrarySource::LibraryFolder && !self.also_library_folders.is_empty() && self.drop_empty_folders() { + // one of several folders shown lost its last photo: the others stay + return self.visible(); + } let f = self.view_filter(self.source, &self.filter); // A held view keeps the photos it shows that stopped matching what is asked of them (a smart album's // rules, a flag, the filter bar), as long as they are still where the view looks: in the library for @@ -1213,7 +1232,7 @@ impl Session { // cost for the hold) let holds = self.hold_view && (asks || self.filter != Filter::default()); let within = holds.then(|| { - if asks { + if asks && self.also_albums.is_empty() { self.view_filter(LibrarySource::All, &Filter::default()) } else if self.source == LibrarySource::RecentlyAdded { // (how far back it reaches was worked out for `f`: not a second pass over the library) @@ -1226,6 +1245,7 @@ impl Session { // its own order, Recently Added (how far back it reaches moves with every import), Missing Photos. let own_order = matches!(self.source, LibrarySource::Album(a) if self.sort.key == lightcraft_catalog::SortKey::CaptureDate && self.filter == Filter::default() + && self.also_albums.is_empty() && self.catalog.album(a).is_some_and(|al| !al.is_smart())); let whole = own_order || matches!(self.source, LibrarySource::RecentlyAdded | LibrarySource::Missing); // A view that asks about "the last N days" (itself, or through a smart album it looks into) changes @@ -1260,9 +1280,12 @@ impl Session { // an empty grid under the name of a folder that is gone from the sidebar self.source = LibrarySource::All; self.library_folder = None; + self.also_library_folders.clear(); return self.visible(); } if matches!(self.source, LibrarySource::Album(_)) + // several albums have no order of their own between them + && self.also_albums.is_empty() && self.sort.key == lightcraft_catalog::SortKey::CaptureDate && let LibrarySource::Album(a) = self.source && let Some(al) = self.catalog.album(a) @@ -1309,22 +1332,6 @@ impl Session { &self.visible } - /// `source` as a filter over `base` (the filter bar's, or none), with the folder it shows. - fn view_filter(&self, source: LibrarySource, base: &Filter) -> Filter { - let mut f = source.to_filter(base, &self.catalog); - if source == LibrarySource::Folder { - // no folder chosen: nothing (an empty path matches nothing) - let b = self.browse.clone().unwrap_or_default(); - f.folder = Some(b.path); - f.subfolders = b.subfolders; - } - if source == LibrarySource::LibraryFolder { - // no folder chosen: nothing (`.` names no folder) - f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); - } - f - } - /// Let go of what a held view kept: the view shows what matches now ([`Session::hold_view`]). pub fn refresh_view(&mut self) { self.base = None; @@ -1357,16 +1364,114 @@ impl Session { /// Whether the library still holds a photo imported from the folder a `LibraryFolder` source /// shows. fn folder_holds_photos(&self) -> bool { - let f = Filter { library_folder: self.library_folder.clone(), ..Default::default() }; + let f = Filter { library_folder: self.library_folder.clone(), library_folders: self.also_library_folders.clone(), ..Default::default() }; self.library_folder.is_some() && !self.catalog.query(&f, &Sort::default()).is_empty() } + /// `source` as a filter over `base` (the filter bar's, or none): what [`LibrarySource::to_filter`] gives, + /// with the folder a `Folder` or `LibraryFolder` source shows and the other albums and folders shown + /// beside the source's own. + fn view_filter(&self, source: LibrarySource, base: &Filter) -> Filter { + let mut f = source.to_filter(base, &self.catalog); + match source { + LibrarySource::Folder => { + // no folder chosen: nothing (an empty path matches nothing) + let b = self.browse.clone().unwrap_or_default(); + f.folder = Some(b.path); + f.subfolders = b.subfolders; + } + LibrarySource::LibraryFolder => { + // no folder chosen: nothing (`.` names no folder) + f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); + f.library_folders = self.also_library_folders.clone(); + } + // the source's albums, whatever albums the filter named + LibrarySource::Album(_) => f.albums = self.also_albums.clone(), + _ => {} + } + f + } + + /// What the source is called: an album's name, a folder's last two names, "3 albums" or + /// "2 folders" for several, else the source's own label. + pub fn source_label(&self) -> String { + match (self.source, self.library_folder.as_deref()) { + (LibrarySource::Album(_), _) if !self.also_albums.is_empty() => format!("{} albums", self.source_albums().len()), + (LibrarySource::LibraryFolder, Some(_)) if !self.also_library_folders.is_empty() => { + format!("{} folders", self.source_library_folders().len()) + } + (LibrarySource::LibraryFolder, Some(path)) => lightcraft_catalog::folders::folder_label(path), + _ => self.source.label(&self.catalog), + } + } + + /// The albums the grid shows the photos of: the [`LibrarySource::Album`] source's and the + /// others chosen with it, in the order chosen (the source's own last: it is the one a + /// single-album action takes). Empty for any other source. + pub fn source_albums(&self) -> Vec { + match self.source { + LibrarySource::Album(a) => self.also_albums.iter().copied().filter(|x| *x != a).chain([a]).collect(), + _ => Vec::new(), + } + } + + /// The folders a [`LibrarySource::LibraryFolder`] source shows: [`Session::library_folder`] + /// (last) and the others chosen with it. Empty for any other source. + pub fn source_library_folders(&self) -> Vec { + match (self.source, &self.library_folder) { + (LibrarySource::LibraryFolder, Some(f)) => self.also_library_folders.iter().cloned().chain([f.clone()]).collect(), + _ => Vec::new(), + } + } + + /// Keep "the other albums and folders shown" true to the source: none without an album or a + /// folder source, never the source's own, and no album that is gone. When the source's own + /// album is gone and others are shown, the last of them takes its place. + fn reconcile_sources(&mut self) { + if self.source != LibrarySource::LibraryFolder && !self.also_library_folders.is_empty() { + self.also_library_folders.clear(); + } + let LibrarySource::Album(a) = self.source else { + if !self.also_albums.is_empty() { + self.also_albums.clear(); + } + return; + }; + if self.also_albums.is_empty() { + return; + } + let cat = &self.catalog; + self.also_albums.retain(|x| *x != a && cat.album(*x).is_some()); + if self.catalog.album(a).is_none() + && let Some(next) = self.also_albums.pop() + { + self.source = LibrarySource::Album(next); + } + } + + /// Of several folders shown, let go of those the library holds no photo of any more; the + /// last one left that does becomes [`Session::library_folder`]. Returns whether any went. + /// (All of them empty: left as it is, for the caller to go back to All Photos.) + fn drop_empty_folders(&mut self) -> bool { + let all = self.source_library_folders(); + let holds = self.catalog.folders_holding(&all); + let mut kept: Vec = all.iter().zip(&holds).filter(|(_, h)| **h).map(|(f, _)| f.clone()).collect(); + if kept.len() == all.len() { + return false; + } + let Some(last) = kept.pop() else { return false }; + self.library_folder = Some(last); + self.also_library_folders = kept; + true + } + /// Photos in the current source (folder, album, …) before the filter bar and search narrow /// them; `None` where that is not a separate number (Missing Photos). pub fn source_total(&mut self) -> Option { if self.source == LibrarySource::Missing { return None; } + self.reconcile_sources(); if self.filter == Filter::default() && !self.hold_view { // nothing narrows the source: what the view lists is all of it, and is counted already (not a view // that holds photos that stopped matching: those are not of the source any more) @@ -1377,7 +1482,10 @@ impl Session { return Some(ids.len()); } } - let key = (self.catalog.revision, format!("{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder)); + let key = ( + self.catalog.revision, + format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.browse, self.library_folder, self.also_albums, self.also_library_folders), + ); let key_changed = self.total.as_ref().map(|total| &total.0) != Some(&key); let cached_minute = self.total.as_ref().and_then(|total| total.2.as_deref()); let current_now = cached_minute.map(|_| (self.clock)()); @@ -1387,15 +1495,7 @@ impl Session { // The source count can be requested before `visible`; bind it to the session's clock itself. let now = current_now.unwrap_or_else(|| (self.clock)()); lightcraft_catalog::rules::set_now(Some(now.clone())); - let mut f = self.source.to_filter(&Filter::default(), &self.catalog); - if self.source == LibrarySource::Folder { - let b = self.browse.clone().unwrap_or_default(); - f.folder = Some(b.path); - f.subfolders = b.subfolders; - } - if self.source == LibrarySource::LibraryFolder { - f.library_folder = Some(self.library_folder.clone().unwrap_or_else(|| ".".into())); - } + let f = self.view_filter(self.source, &Filter::default()); // (how many, not which: nothing to put in order) let n = self.catalog.count(&f); let clocked = filter_depends_on_clock(&f, &self.catalog); diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 2338d4f1a8f..40c7539277b 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -236,6 +236,11 @@ struct ViewFile { browse: Option, /// The folder a `libraryFolder` source shows. library_folder: Option, + /// The other albums and folders shown beside the source's own (several chosen at once). + #[serde(skip_serializing_if = "Vec::is_empty")] + also_albums: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + also_library_folders: Vec, // No filter: a library opens unfiltered. A date, keyword or person left over from the last session // would silently hide photos, with only a small badge to say so. sort: lightcraft_catalog::Sort, @@ -570,6 +575,8 @@ impl Session { self.selection = Selection::default(); self.source = LibrarySource::All; self.library_folder = None; + self.also_albums.clear(); + self.also_library_folders.clear(); if report.created && seed_demo { crate::demo::load(self); journal.snapshot(&self.catalog)?; @@ -636,13 +643,43 @@ impl Session { self.source = v.source; self.browse = v.browse; self.library_folder = v.library_folder.filter(|f| !f.trim().is_empty()); + // (albums that are gone, and folders without photos, leave when the view is first drawn) + // (each album once, as a call would have them) + let mut albums: Vec = Vec::new(); + for a in v.also_albums { + if !albums.contains(&a) { + albums.push(a); + } + } + albums.truncate(crate::cmd::library::MAX_SOURCES); + self.also_albums = albums; + // as a call would have them: folders only (not the startup disk), each once, not the source's own + let own = self.library_folder.as_deref().map(lightcraft_catalog::query::folder_key); + let mut keys: Vec = Vec::new(); + self.also_library_folders = v + .also_library_folders + .into_iter() + .filter(|f| !f.trim().is_empty() && !lightcraft_catalog::folders::is_startup_disk(f)) + .filter(|f| { + let key = lightcraft_catalog::query::folder_key(f); + let new = !key.is_empty() && Some(&key) != own.as_ref() && !keys.contains(&key); + keys.push(key); + new + }) + .take(crate::cmd::library::MAX_SOURCES) + .collect(); if self.source == LibrarySource::LibraryFolder { // a folder that is gone (or none): everything, not an empty grid - let f = lightcraft_catalog::Filter { library_folder: self.library_folder.clone(), ..Default::default() }; + let f = lightcraft_catalog::Filter { + library_folder: self.library_folder.clone(), + library_folders: self.also_library_folders.clone(), + ..Default::default() + }; let any = self.library_folder.is_some() && !self.catalog.query(&f, &lightcraft_catalog::Sort::default()).is_empty(); if !any { self.source = LibrarySource::All; self.library_folder = None; + self.also_library_folders.clear(); } } self.sort = v.sort; @@ -875,6 +912,8 @@ impl Session { browse: self.browse.clone(), // only while it is shown: a leftover would be a stale choice nobody made library_folder: self.library_folder.clone().filter(|_| self.source == LibrarySource::LibraryFolder), + also_albums: self.also_albums.clone().into_iter().filter(|_| matches!(self.source, LibrarySource::Album(_))).collect(), + also_library_folders: self.also_library_folders.clone().into_iter().filter(|_| self.source == LibrarySource::LibraryFolder).collect(), sort: self.sort, selection: self.selection.clone(), }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 632814334d8..c4aa93ad7d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -40,6 +40,7 @@ mod mask_effects; mod mask_geometry; mod merge; mod move_to_share; +mod multi_source; mod organize; mod persist; mod prefs; diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs new file mode 100644 index 00000000000..7d4d9f22c6c --- /dev/null +++ b/crates/engine/src/tests/multi_source.rs @@ -0,0 +1,389 @@ +//! Several albums, several folders, several keywords or several dates shown at once: what an +//! agent asks for today, and what Cmd/Ctrl+click and Shift+click in the sidebars will ask for +//! once that feature lands. The grid shows the photos of any of them, each once. +//! +//! Scenarios: +//! - Given two albums that share a photo, when both are shown (`library.source {kind: "album", +//! ids}`), then the grid lists their photos once each, and `library.state` names both. +//! - Given several albums shown, when one album is shown the usual way, then only that one is. +//! - Given several albums shown, when one of them is deleted, then the others stay shown; when +//! the last is deleted, the grid goes back to All Photos. +//! - An album that does not exist among those asked for is refused, and the view stays as it was. +//! - Given several albums shown, then the grid follows the sort, not one album's own order. +//! - Given two folders of the library, when both are shown (`paths`), then the grid lists the +//! photos of both; removing one from the library leaves the other shown. +//! - Given several keywords in the filter (`keywords`), then photos with any of them are shown; +//! a renamed keyword is followed, a deleted one leaves the filter, and one chip clears them all. +//! - Given several dates in the filter (`dates`), then photos taken on any of them are shown. +//! - Given several albums shown, when the view is saved as a smart album, then that album shows +//! the same photos. +//! - Several albums are still the source after the library is closed and opened again. +//! - Given a smart album saved from a view of several albums, when its rules are replaced in +//! the rules dialog, then it is still limited to all of those albums. +//! - Albums in the filter itself show as a chip that clears them, and are refused while an +//! album is the source (they would be ignored); the one album of the filter goes with it. +//! - Given several folders in the filter, when one is renamed on disk, then the filter follows. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::{LibrarySource, Session, filter_chips}; + +/// Photos `1..=n`, one a day from 2026-01-01 (so the newest has the highest id). +fn photos(s: &mut Session, n: u64) -> Vec { + (1..=n) + .map(|day| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }) + .collect() +} + +fn album(s: &mut Session, name: &str, ids: &[u64]) -> u64 { + let id = s.execute("album.create", &json!({"name": name})).unwrap()["id"].as_u64().unwrap(); + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = ids.iter().map(|i| PhotoId(*i)).collect(); + s.execute("album.addPhotos", &json!({"id": id, "ids": ids})).unwrap(); + s.selection.ids.clear(); + id +} + +/// What the grid shows, in id order. +fn shown(s: &mut Session) -> Vec { + let mut v: Vec = s.visible_cloned().iter().map(|p| p.0).collect(); + v.sort_unstable(); + v +} + +fn state(s: &mut Session) -> Value { + s.execute("library.state", &json!({})).unwrap() +} + +/// Two albums sharing photo 2: `(ids, a, b)`. +fn two_albums(s: &mut Session) -> (Vec, u64, u64) { + let ids = photos(s, 5); + let a = album(s, "Alps", &[ids[0], ids[1]]); + let b = album(s, "Beach", &[ids[1], ids[2]]); + (ids, a, b) +} + +#[test] +fn several_albums_show_the_photos_of_any_of_them_once() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + let r = s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + // the last one named is the one a single-album action takes + assert_eq!(s.source, LibrarySource::Album(AlbumId(b))); + assert_eq!(s.source_albums(), vec![AlbumId(a), AlbumId(b)]); + let st = state(&mut s); + assert_eq!(st["albums"], json!([a, b])); + assert_eq!(st["sourceLabel"], "2 albums"); + assert_eq!(s.source_total(), Some(3), "the count before the filter bar narrows it"); +} + +#[test] +fn showing_one_album_again_lets_go_of_the_others() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + assert_eq!(s.source_albums(), vec![AlbumId(a)]); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + // …and so does another kind of source + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + assert!(s.source_albums().is_empty()); + assert_eq!(shown(&mut s).len(), 5); + assert_eq!(state(&mut s)["albums"], json!([])); +} + +#[test] +fn an_album_named_twice_is_shown_once_and_one_alone_is_the_usual_source() { + let mut s = Session::new(); + let (_, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b, a]})).unwrap(); + assert_eq!(s.source_albums(), vec![AlbumId(b), AlbumId(a)], "the last naming is the one that counts"); + s.execute("library.source", &json!({"kind": "album", "ids": [a]})).unwrap(); + assert_eq!((s.source, s.source_albums()), (LibrarySource::Album(AlbumId(a)), vec![AlbumId(a)])); +} + +#[test] +fn a_deleted_album_leaves_the_others_shown() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + // the one single-album actions take goes: the other takes its place + s.execute("album.delete", &json!({"id": b})).unwrap(); + assert_eq!(s.source, LibrarySource::Album(AlbumId(a))); + assert_eq!(s.source_albums(), vec![AlbumId(a)]); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert_eq!(s.source, LibrarySource::All); + assert!(s.source_albums().is_empty()); + // undo brings an album back, not the view of it + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.source, LibrarySource::All); +} + +#[test] +fn an_album_that_is_not_there_is_refused_and_the_view_stays() { + let mut s = Session::new(); + let (ids, a, _) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + let e = s.execute("library.source", &json!({"kind": "album", "ids": [a, 9999]})).unwrap_err().to_string(); + assert!(e.contains("9999"), "the refusal names the album: {e}"); + assert_eq!(s.source_albums(), vec![AlbumId(a)]); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + for bad in [json!([]), json!("x"), json!([a, "x"]), json!([-1])] { + assert!(s.execute("library.source", &json!({"kind": "album", "ids": bad})).is_err(), "{bad}"); + } + assert_eq!(s.source_albums(), vec![AlbumId(a)]); +} + +#[test] +fn several_albums_follow_the_sort_not_an_album_s_own_order() { + let mut s = Session::new(); + let ids = photos(&mut s, 4); + // by hand: newest first in A + let a = album(&mut s, "A", &[ids[3], ids[0]]); + let b = album(&mut s, "B", &[ids[2], ids[1]]); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + s.execute("library.sort", &json!({"key": "captureDate", "ascending": true})).unwrap(); + let order: Vec = s.visible_cloned().iter().map(|p| p.0).collect(); + assert_eq!(order, ids); +} + +fn add_file(s: &mut Session, path: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +#[test] +fn several_folders_show_the_photos_of_any_of_them() { + let mut s = Session::new(); + let alps = add_file(&mut s, "/pics/2025/alps/a.jpg"); + let deep = add_file(&mut s, "/pics/2025/alps/day1/b.jpg"); + let beach = add_file(&mut s, "/pics/2026/beach/c.jpg"); + let other = add_file(&mut s, "/pics/2026/town/d.jpg"); + let r = s.execute("library.source", &json!({"kind": "libraryFolder", "paths": ["/pics/2025/alps", "/pics/2026/beach"]})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(shown(&mut s), vec![alps, deep, beach]); + assert_eq!(s.source, LibrarySource::LibraryFolder); + assert_eq!(s.source_library_folders(), vec!["/pics/2025/alps".to_string(), "/pics/2026/beach".to_string()]); + let st = state(&mut s); + assert_eq!(st["libraryFolders"], json!(["/pics/2025/alps", "/pics/2026/beach"])); + assert_eq!(st["libraryFolder"], "/pics/2026/beach", "the last one named is the one a single-folder action takes"); + assert_eq!(st["sourceLabel"], "2 folders"); + assert_eq!(s.source_total(), Some(3)); + // a folder with no photo of the library is refused, by name, and the view stays + let e = s.execute("library.source", &json!({"kind": "libraryFolder", "paths": ["/pics/2026/town", "/nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert_eq!(shown(&mut s), vec![alps, deep, beach]); + // one of the folders shown leaves the library: the other stays + s.execute("library.removeFolder", &json!({"path": "/pics/2026/beach"})).unwrap(); + assert_eq!(s.source_library_folders(), vec!["/pics/2025/alps".to_string()]); + assert_eq!(shown(&mut s), vec![alps, deep]); + // one folder the usual way lets go of the rest + s.execute("library.source", &json!({"kind": "libraryFolder", "paths": ["/pics/2025/alps", "/pics/2026/town"]})).unwrap(); + s.execute("library.source", &json!({"kind": "libraryFolder", "path": "/pics/2026/town"})).unwrap(); + assert_eq!(shown(&mut s), vec![other]); + assert_eq!(s.source_library_folders(), vec!["/pics/2026/town".to_string()]); +} + +fn tag(s: &mut Session, id: u64, keywords: &[&str]) { + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = vec![PhotoId(id)]; + s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": keywords})).unwrap(); + s.selection.ids.clear(); +} + +#[test] +fn several_keywords_show_the_photos_with_any_of_them() { + let mut s = Session::new(); + let ids = photos(&mut s, 4); + tag(&mut s, ids[0], &["alps"]); + tag(&mut s, ids[1], &["beach", "alps"]); + tag(&mut s, ids[2], &["trips|italy"]); + let r = s.execute("library.filter", &json!({"keywords": ["alps", "trips"]})).unwrap(); + assert_eq!(r["count"], 3, "a keyword stands for the keywords below it too"); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + // the single keyword is one more of them, not a second condition + s.execute("library.filter", &json!({"keyword": "beach", "keywords": ["trips"]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[1], ids[2]]); + // one chip, and clearing it clears them all + let chips = filter_chips(&s.filter, &s.catalog); + assert_eq!(chips.len(), 1); + assert_eq!(chips[0].label, "Keyword: beach or trips"); + s.execute("library.filter", &chips[0].clear.clone()).unwrap(); + assert_eq!(shown(&mut s).len(), 4); + assert!(s.filter.keyword.is_none() && s.filter.keywords.is_empty()); +} + +#[test] +fn several_keywords_follow_a_rename_and_lose_a_deleted_one() { + let mut s = Session::new(); + let ids = photos(&mut s, 3); + tag(&mut s, ids[0], &["alps"]); + tag(&mut s, ids[1], &["beach"]); + s.execute("library.filter", &json!({"keywords": ["alps", "beach"]})).unwrap(); + s.execute("keyword.rename", &json!({"from": "alps", "to": "mountains"})).unwrap(); + assert_eq!(s.filter.keywords, vec!["mountains".to_string(), "beach".to_string()]); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + s.execute("keyword.delete", &json!({"keyword": "beach"})).unwrap(); + assert_eq!(s.filter.keywords, vec!["mountains".to_string()]); + assert_eq!(shown(&mut s), vec![ids[0]]); +} + +#[test] +fn several_dates_show_the_photos_of_any_of_them() { + let mut s = Session::new(); + let ids = photos(&mut s, 5); + s.execute("library.filter", &json!({"dates": ["2026-01-02", "2026-01-04"]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[1], ids[3]]); + s.execute("library.filter", &json!({"date": "2026-01-05", "dates": ["2026-01-02"]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[1], ids[4]]); + let chips = filter_chips(&s.filter, &s.catalog); + assert_eq!(chips.len(), 1); + assert_eq!(chips[0].label, "Date: January 5, 2026 or January 2, 2026"); + s.execute("library.filter", &chips[0].clear.clone()).unwrap(); + assert_eq!(shown(&mut s).len(), 5); +} + +#[test] +fn several_albums_saved_as_a_smart_album_show_the_same_photos() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + let smart = s.execute("album.createSmart", &json!({"name": "Both"})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": smart})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + // …and follows what the albums hold + s.selection.ids = vec![PhotoId(ids[4])]; + s.execute("album.addPhotos", &json!({"id": a, "ids": [ids[4]]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2], ids[4]]); +} + +#[test] +fn several_albums_are_still_the_source_after_reopening() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let scratch = Scratch(std::env::temp_dir().join(format!("lc-multi-source-{}", std::process::id()))); + let dir = scratch.0.clone(); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let (_, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + let want = shown(&mut s); + s.save_view(); + drop(s); + let mut back = Session::new(); + back.open_library(&dir, false).unwrap(); + assert_eq!(back.source_albums(), vec![AlbumId(a), AlbumId(b)]); + assert_eq!(shown(&mut back), want); +} + +#[test] +fn replacing_the_rules_of_a_saved_view_keeps_all_its_albums() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + let smart = s.execute("album.createSmart", &json!({"name": "Both"})).unwrap()["id"].as_u64().unwrap(); + // what the rules dialog sends: its rules, in place of the ones before + s.execute("album.setRules", &json!({"id": smart, "replace": true, "rules": {"rating": 0}})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": smart})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]], "still both albums"); + // …unless the call says to drop them + s.execute("album.setRules", &json!({"id": smart, "replace": true, "rules": {"albums": []}})).unwrap(); + assert_eq!(shown(&mut s).len(), 2, "the one album left"); +} + +#[test] +fn albums_in_the_filter_show_as_a_chip_and_are_refused_beside_an_album_source() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.filter", &json!({"albums": [a, b]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + let chips = filter_chips(&s.filter, &s.catalog); + assert_eq!(chips.iter().map(|c| c.label.as_str()).collect::>(), vec!["Album: Alps or Beach"]); + s.execute("library.filter", &chips[0].clear.clone()).unwrap(); + assert_eq!(shown(&mut s).len(), 5); + // while an album is the source its albums are what is shown: more in the filter would be ignored + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + let e = s.execute("library.filter", &json!({"albums": [b]})).unwrap_err().to_string(); + assert!(e.contains("already shown"), "{e}"); + assert!(s.filter.albums.is_empty()); + // albums left in the filter go when an album becomes the source, and other filters still work + s.execute("library.source", &json!({"kind": "all"})).unwrap(); + s.execute("library.filter", &json!({"albums": [b]})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + assert!(s.filter.albums.is_empty()); + s.execute("library.filter", &json!({"rating": 0})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); +} + +#[test] +fn several_folders_in_the_filter_and_as_the_source_follow_a_renamed_folder() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = Scratch(std::env::temp_dir().join(format!("lc-multi-source-rename-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(dir.0.join("trip")).unwrap(); + std::fs::create_dir_all(dir.0.join("home")).unwrap(); + let at = |rel: &str| dir.0.join(rel).to_string_lossy().to_string(); + let key = lightcraft_catalog::query::folder_key; + let mut s = Session::new(); + add_file(&mut s, &format!("{}/a.jpg", at("trip"))); + add_file(&mut s, &format!("{}/b.jpg", at("home"))); + // as a filter + s.execute("library.filter", &json!({"libraryFolders": [at("trip"), at("home")]})).unwrap(); + s.execute("folder.rename", &json!({"path": at("trip"), "name": "holiday"})).unwrap(); + assert_eq!(s.filter.library_folders.iter().map(|f| key(f)).collect::>(), vec![key(&at("holiday")), key(&at("home"))]); + assert_eq!(s.visible().len(), 2, "still the photos of both"); + // as the source + s.execute("library.clearFilter", &json!({})).unwrap(); + s.execute("library.source", &json!({"kind": "libraryFolder", "paths": [at("holiday"), at("home")]})).unwrap(); + s.execute("folder.rename", &json!({"path": at("holiday"), "name": "trip"})).unwrap(); + assert_eq!(s.source_library_folders().iter().map(|f| key(f)).collect::>(), vec![key(&at("trip")), key(&at("home"))]); + assert_eq!(s.visible().len(), 2); +} + +#[test] +fn several_albums_follow_a_small_edit_instead_of_being_worked_out_whole() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + let (followed, whole) = (s.view_followed, s.view_worked_out); + s.selection.ids = [PhotoId(ids[1])].into_iter().collect(); + s.execute("photo.rate", &json!({"ids": [ids[1]], "rating": 5})).unwrap(); + s.selection.ids.clear(); + assert_eq!(shown(&mut s), vec![ids[0], ids[1], ids[2]]); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole), "several albums have no order of their own"); +} + +#[test] +fn a_single_album_left_in_the_filter_does_not_outlive_an_album_source() { + let mut s = Session::new(); + let (_, a, b) = two_albums(&mut s); + s.execute("library.filter", &json!({"album": a})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": b})).unwrap(); + assert_eq!(s.filter.album, None, "no chip for an album that limits nothing"); +} diff --git a/crates/engine/src/tests/organize.rs b/crates/engine/src/tests/organize.rs index efd345cc6cd..acd9110d021 100644 --- a/crates/engine/src/tests/organize.rs +++ b/crates/engine/src/tests/organize.rs @@ -102,6 +102,25 @@ fn smart_album_view_keeps_the_filter_bar_over_a_stale_rule() { assert!(r.rule_set.is_some(), "and so do the album's own rules"); } +/// A view of several albums with a smart one among them can't be saved: the refusal names it. +#[test] +fn saving_a_view_of_several_albums_with_a_smart_one_names_the_smart_album() { + let mut s = Session::with_demo(); + let plain = s.execute("album.create", &json!({"name": "Plain", "addSelected": false})).unwrap()["id"].as_u64().unwrap(); + let smart = s.execute("album.createSmart", &json!({"name": "Picks", "rules": {"flag": "pick"}})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "ids": [plain, smart]})).unwrap(); + let before = s.catalog.to_snapshot(); + let e = s.execute("album.createSmart", &json!({"name": "Both"})).unwrap_err().to_string(); + assert!(e.contains("\"Picks\" is a smart album"), "{e}"); + let e = s.execute("album.setRules", &json!({"id": smart, "fromView": true})).unwrap_err().to_string(); + assert!(e.contains("\"Picks\" is a smart album"), "{e}"); + assert_eq!(s.catalog.to_snapshot(), before, "nothing was saved"); + // plain albums alone still save + let other = s.execute("album.create", &json!({"name": "Other", "addSelected": false})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "ids": [plain, other]})).unwrap(); + s.execute("album.createSmart", &json!({"name": "Both"})).unwrap(); +} + #[test] fn virtual_copies_are_independent_and_persist() { let dir = temp_dir("vc"); diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 73ec0352b2b..3ec07783bc7 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -203,20 +203,35 @@ pub fn filter_chips(f: &Filter, cat: &Catalog) -> Vec { if let Some(e) = f.edited { add(if e { "Edited".into() } else { "Unedited".into() }, json!({"edited": Null})); } - for (name, key, val) in - [("Camera", "camera", &f.camera), ("Lens", "lens", &f.lens), ("Keyword", "keyword", &f.keyword), ("Person", "person", &f.person)] - { + for (name, key, val) in [("Camera", "camera", &f.camera), ("Lens", "lens", &f.lens)] { if let Some(x) = val { add(format!("{name}: {x}"), json!({key: Null})); } } - if let Some(d) = &f.date { - add(format!("Date: {}", date_label(d)), json!({"date": Null})); + // albums in the filter itself (an agent's; the albums of the source are not a filter) + let albums = f.albums_wanted(); + if !albums.is_empty() { + let names: Vec = albums.iter().map(|a| cat.album(*a).map_or_else(|| format!("album {}", a.0), |a| a.name.clone())).collect(); + add(format!("Album: {}", names.join(" or ")), json!({"album": Null, "albums": []})); } - if let Some(d) = f.library_folder.as_deref().filter(|d| !d.trim().is_empty()) { + // several of a kind (chosen together in the sidebar) are one chip: clearing it clears them all + let keywords = f.keywords_wanted(); + if !keywords.is_empty() { + add(format!("Keyword: {}", keywords.join(" or ")), json!({"keyword": Null, "keywords": []})); + } + if let Some(x) = &f.person { + add(format!("Person: {x}"), json!({"person": Null})); + } + let dates = f.dates_wanted(); + if !dates.is_empty() { + let names: Vec = dates.iter().map(|d| date_label(d)).collect(); + add(format!("Date: {}", names.join(" or ")), json!({"date": Null, "dates": []})); + } + let folders = f.library_folders_wanted(); + if !folders.is_empty() { // the last two names, so two folders called "Pictures" are told apart - let name = lightcraft_catalog::folders::folder_label(d); - add(format!("Folder: {name}"), json!({"libraryFolder": Null})); + let names: Vec = folders.iter().map(|d| lightcraft_catalog::folders::folder_label(d)).collect(); + add(format!("Folder: {}", names.join(" or ")), json!({"libraryFolder": Null, "libraryFolders": []})); } if let Some(d) = &f.imported { add(format!("Imported: {}", date_label(d)), json!({"imported": Null})); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 99381ec5f50..3f6ccc67a87 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -459,7 +459,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`) | `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs` | photos in the grid; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter, each photo shown once (the sidebars' Cmd/Ctrl+click and Shift+click that use it are a later change) | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1050,3 +1050,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | | 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | +| 2026-10-21 | minor | LR-BEHAV-MULTISELECT: `library.source` takes several albums (`ids`) or folders (`paths`) and `library.filter` several keywords, dates, folders or albums, each photo shown once; `album.setRules` with `replace` keeps a smart album's album and folders; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index c0b75f74c62..42e3e2b27a8 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -754,6 +754,13 @@ in Recently Deleted apart, since they are restored and their files stay where they are: "Move 2 Photos · Restore 1 Photo". +### Several albums, folders, keywords or dates shown at once (agents) +- `library.source` takes `ids` (albums) or `paths` (folders) and shows the photos of any of them, each once; + `library.filter` takes `keywords`, `dates`, `libraryFolders` and `albums`. The single fields stay and count as one + more of them. `library.state` lists `albums` and `libraryFolders`. Nothing on screen changes yet: the sidebars' + Cmd+click and Shift+click that use this come in a later change. +- `album.setRules` with `replace` keeps a smart album's album, as it already kept its folder (`album: null` drops + it), so editing a smart album saved from a view of several albums no longer loses them. ### Sharper resampling in HDR and panorama merges - Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a From 0a47547b8ba0b20f677218b0b6760dbf090c5109 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 10:48:58 -0400 Subject: [PATCH 15/55] Sidebars: gaps.md entry for the sidebar multi-selection still to wire (gap 30) --- docs/gaps.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/gaps.md b/docs/gaps.md index 08cebce09d7..71861fb0e50 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,6 +45,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | +| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): the albums, folders, keywords and dates sidebars show one entry at a time. Cmd/Ctrl+click and Shift+click to show several at once are not wired to `library.source` (`ids`, `paths`) and `library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), which agents already use | `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ for the engine part | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -127,6 +128,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-22 | patch | Issue #2519: PSD/PSB EXIF resource 1058 and XMP resource 1060 now use the common metadata extractor, and `.psb` files are accepted by import; no ranked gap or readiness count changes | | 2026-10-22 | minor | Gap 30 added: multi-select metadata editing — Info panel and All Metadata dialog show one photo's values with no mixed-value indication | | 2026-10-22 | patch | LR-MAP-TRACKLOG: GPX coordinate attributes and point text decode XML references; malformed / unknown references return errors; CDATA remains literal; ranked gaps unchanged | +| 2026-10-21 | minor | Gap 31 added: LR-BEHAV-MULTISELECT's engine part (several albums, folders, keywords or dates shown at once through `library.source` / `library.filter`) landed for agents; the sidebars' Cmd/Ctrl+click and Shift+click remain; ranked counts and beta total unchanged | | 2026-10-21 | minor | Gap 28 shrinks: F8 shows / hides the right panel (`view.rightPanel`); rating `[` `]`, flag cycling and F1 help were already bound, so the entry lists only filter-bar keys, Tab / ⇧Tab and F5; 2–4 h (was 4–8) | | 2026-10-20 | minor | Gap 22 shrinks (11–22 → 9–18 h): on Windows, previews follow the profile Windows Color System assigns to the window's monitor (sRGB while Windows colour-manages the desktop: HDR, Auto Color Management) | | 2026-10-20 | minor | #2362: import destination albums use the shared hierarchy/search picker instead of a flat name list; existing import workflows retained; ranked gaps/readiness counts unchanged | From b72bbc73e4a9b1e45a747f726dbaa710b5f86104 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 13:20:37 -0400 Subject: [PATCH 16/55] Sidebars: album.setRules says [] (not null) clears the list fields --- crates/engine/src/cmd/library/specs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 3c94a6f27e7..de876a97682 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -957,7 +957,7 @@ pub fn specs() -> Vec { "Edit Smart Album", [], None, - "{id, rules?: partial Filter merged onto the current rules (null clears a field), replace?: bool, fromView?: bool (use the current view), name?: also rename it (blank keeps the name) — one undo step, both or neither}", + "{id, rules?: partial Filter merged onto the current rules (null clears a single-value field; [] clears keywords/dates/libraryFolders/albums), replace?: bool, fromView?: bool (use the current view), name?: also rename it (blank keeps the name) — one undo step, both or neither}", always, |s, p| { let id = album_param(p, "id", "album.setRules")?; From f14eff315d081cc6470aaeaeb5f243178313af6b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 15:16:22 -0400 Subject: [PATCH 17/55] Sidebars: library.filter refuses a single album beside an album source --- crates/engine/src/cmd/library/specs.rs | 6 ++++-- crates/engine/src/tests/multi_source.rs | 5 +++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index de876a97682..9ec63634201 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -171,8 +171,10 @@ pub fn specs() -> Vec { format!("{n} albums, folders, keywords or dates in one filter: at most {MAX_SOURCES} of each"), )); } - // (the source's albums are what is shown: albums in the filter would be ignored) - let sets_albums = p.get("albums").and_then(Value::as_array).is_some_and(|a| !a.is_empty()); + // (the source's albums are what is shown: albums in the filter would be ignored, + // the single `album` too; null clears it and is fine) + let sets_albums = + p.get("albums").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) || p.get("album").is_some_and(|a| !a.is_null()); if sets_albums && matches!(s.source, LibrarySource::Album(_)) { return Err(bad("library.filter", "albums are already shown (library.source): show another source first")); } diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 7d4d9f22c6c..d6902d3620c 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -325,6 +325,11 @@ fn albums_in_the_filter_show_as_a_chip_and_are_refused_beside_an_album_source() let e = s.execute("library.filter", &json!({"albums": [b]})).unwrap_err().to_string(); assert!(e.contains("already shown"), "{e}"); assert!(s.filter.albums.is_empty()); + // the single `album` is ignored the same way; null still clears it + let e = s.execute("library.filter", &json!({"album": b})).unwrap_err().to_string(); + assert!(e.contains("already shown"), "{e}"); + assert_eq!(s.filter.album, None); + s.execute("library.filter", &json!({"album": null})).unwrap(); // albums left in the filter go when an album becomes the source, and other filters still work s.execute("library.source", &json!({"kind": "all"})).unwrap(); s.execute("library.filter", &json!({"albums": [b]})).unwrap(); From 69cbc60bfb8485e475b2ad3d55376fda0c91c49f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 18:39:53 -0400 Subject: [PATCH 18/55] Sidebars: a view of albums that are all gone shows All Photos, not an empty grid --- crates/engine/src/lib.rs | 16 +++++++--------- crates/engine/src/tests/multi_source.rs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8fdc4c3c325..dc4302de96f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1426,7 +1426,8 @@ impl Session { /// Keep "the other albums and folders shown" true to the source: none without an album or a /// folder source, never the source's own, and no album that is gone. When the source's own - /// album is gone and others are shown, the last of them takes its place. + /// album is gone and others are shown, the last of them takes its place; when none is left, + /// the view goes back to All Photos (not an empty grid). fn reconcile_sources(&mut self) { if self.source != LibrarySource::LibraryFolder && !self.also_library_folders.is_empty() { self.also_library_folders.clear(); @@ -1437,15 +1438,12 @@ impl Session { } return; }; - if self.also_albums.is_empty() { - return; - } let cat = &self.catalog; - self.also_albums.retain(|x| *x != a && cat.album(*x).is_some()); - if self.catalog.album(a).is_none() - && let Some(next) = self.also_albums.pop() - { - self.source = LibrarySource::Album(next); + if !self.also_albums.is_empty() { + self.also_albums.retain(|x| *x != a && cat.album(*x).is_some()); + } + if cat.album(a).is_none() { + self.source = self.also_albums.pop().map_or(LibrarySource::All, LibrarySource::Album); } } diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index d6902d3620c..626c384afee 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -130,6 +130,23 @@ fn a_deleted_album_leaves_the_others_shown() { assert_eq!(s.source, LibrarySource::All); } +#[test] +fn a_saved_view_of_albums_that_are_all_gone_shows_all_photos_not_an_empty_grid() { + let mut s = Session::new(); + let (ids, _, _) = two_albums(&mut s); + // what a restored view.json can hold when every album it names was deleted meanwhile + s.source = LibrarySource::Album(AlbumId(9998)); + s.also_albums = vec![AlbumId(9999)]; + assert_eq!(shown(&mut s).len(), ids.len()); + assert_eq!(s.source, LibrarySource::All); + assert!(s.source_albums().is_empty()); + // and the same for one album that is gone with none beside it + s.source = LibrarySource::Album(AlbumId(9999)); + s.also_albums.clear(); + assert_eq!(shown(&mut s).len(), ids.len()); + assert_eq!(s.source, LibrarySource::All); +} + #[test] fn an_album_that_is_not_there_is_refused_and_the_view_stays() { let mut s = Session::new(); From feb4d05110e6f39fb164fb22d8c3340babcfc4a1 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 20:25:13 -0400 Subject: [PATCH 19/55] Sidebars: an album filter put aside does not come back beside an album source; a date chip names every date in other languages; say that paths are library folders --- crates/engine/src/cmd/library/specs.rs | 7 ++++++- crates/engine/src/tests/multi_source.rs | 16 ++++++++++++++++ crates/ui-egui/src/panels/chips.rs | 9 ++++++++- crates/ui-egui/src/tests/panels.rs | 16 ++++++++++++++++ docs/whats-new.md | 5 +++-- 5 files changed, 49 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 9ec63634201..7ecca4709dd 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -121,7 +121,8 @@ pub fn specs() -> Vec { } // the last one named is the one a single-album action takes let Some(own) = albums.pop() else { return Err(bad(C, "`ids` names no album")) }; - // the albums of the source: albums left over in the filter would be ignored + // the albums of the source: the filter bar has no album chip, so albums left over in the + // filter would narrow the next source unseen (or be ignored) s.filter.albums.clear(); s.filter.album = None; (LibrarySource::Album(own), albums, Vec::new()) @@ -310,6 +311,10 @@ pub fn specs() -> Vec { f.library_folder = None; f.library_folders.clear(); } + // the album(s) shown are what the grid shows: albums in the filter would be ignored + if matches!(s.source, LibrarySource::Album(_)) { + f.albums.clear(); + } s.filter = f; } Ok(json!({"enabled": s.shelved_filter.is_none(), "count": s.visible().len()})) diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 626c384afee..5d9329d9b40 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -409,3 +409,19 @@ fn a_single_album_left_in_the_filter_does_not_outlive_an_album_source() { s.execute("library.source", &json!({"kind": "album", "id": b})).unwrap(); assert_eq!(s.filter.album, None, "no chip for an album that limits nothing"); } + +#[test] +fn albums_in_a_filter_put_aside_do_not_come_back_beside_an_album_source() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + // Given albums in the filter, put aside by Enable Filters, and an album then shown as the source + s.execute("library.filter", &json!({"albums": [b]})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + // When the filter is brought back + s.execute("library.toggleFilters", &json!({})).unwrap(); + // Then the albums stay out of it, as they do for a filter set while an album is shown + assert!(s.filter.albums.is_empty(), "{:?}", s.filter.albums); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + assert!(filter_chips(&s.filter, &s.catalog).is_empty()); +} diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index 19626bbfd3c..bdfae039dc0 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -47,7 +47,14 @@ fn prefixed_value(prefix: &str, value: &str, filter: &lightcraft_catalog::Filter use crate::i18n::{date_group_label, tr}; let date = match prefix { "Type" => return tr(value).to_string(), - "Date" => &filter.date, + "Date" => { + // every date of the chip, as the engine's label lists them + let dates = filter.dates_wanted(); + if dates.is_empty() { + return value.to_string(); + } + return dates.iter().map(|date| date_group_label(date, false)).collect::>().join(&format!(" {} ", tr("or"))); + } "Imported" => &filter.imported, _ => return value.to_string(), }; diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 54575499e21..342016c7a4b 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -2881,3 +2881,19 @@ fn the_histogram_clipping_buttons_stay_clear_of_the_hovered_scroll_bar() { // and the shadow one keeps the same inset from its edge assert!(((low.left() - hist.left()) - (hist.right() - high.right())).abs() < 0.5, "{low:?} {high:?} in {hist:?}"); } + +/// A date chip that names several dates (`date` with `dates`) names all of them in another +/// language too, not only the first. +#[test] +fn a_date_chip_names_every_date_in_another_language() { + use crate::i18n::{Locale, date_group_label, set_language}; + let s = lightcraft_engine::Session::new(); + let filter = lightcraft_catalog::Filter { date: Some("2026-01-05".into()), dates: vec!["2026-01-02".into()], ..Default::default() }; + let chips = lightcraft_engine::filter_chips(&filter, &s.catalog); + assert_eq!(chips.len(), 1); + set_language(Locale::De); + let label = crate::panels::chips::display_label(&chips[0], &filter, &s.catalog); + let dates = ["2026-01-05", "2026-01-02"].map(|d| date_group_label(d, false)); + set_language(Locale::En); + assert!(dates.iter().all(|d| label.contains(d.as_str())), "{label} names {dates:?}"); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index 42e3e2b27a8..f1f59b654aa 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -755,8 +755,9 @@ Photo". ### Several albums, folders, keywords or dates shown at once (agents) -- `library.source` takes `ids` (albums) or `paths` (folders) and shows the photos of any of them, each once; - `library.filter` takes `keywords`, `dates`, `libraryFolders` and `albums`. The single fields stay and count as one +- `library.source` takes `ids` (albums) or `paths` (folders of the library, as `library.folders` lists them, not a + browsed Local folder) and shows the photos of any of them, each once; `library.filter` takes `keywords`, `dates`, + `libraryFolders` and `albums`. The single fields stay and count as one more of them. `library.state` lists `albums` and `libraryFolders`. Nothing on screen changes yet: the sidebars' Cmd+click and Shift+click that use this come in a later change. - `album.setRules` with `replace` keeps a smart album's album, as it already kept its folder (`album: null` drops From 136a819733d8cd8e24dddc1c034091f35da4b181 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 07:53:28 -0400 Subject: [PATCH 20/55] Sidebars: deleting every keyword of the filter Enable Filters put aside leaves filtering on As for a single keyword: when keyword.delete empties the put-aside filter's keyword and keywords, and nothing else is left in it, the empty filter is dropped instead of staying put aside with nothing to bring back. --- crates/engine/src/cmd/keywords.rs | 10 +++-- crates/engine/src/tests/multi_source.rs | 49 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index e602b9d619e..8c1704f103e 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -47,13 +47,17 @@ fn commit_keywords(s: &mut Session, label: &str, op: lightcraft_catalog::Op, fol // a filter put aside by Enable Filters follows the keyword too let mut gone_from_put_aside = false; if let Some(f) = s.shelved_filter.as_mut() { + let held_keywords = f.keyword.is_some() || !f.keywords.is_empty(); if let Some(k) = f.keyword.clone() { f.keyword = follow(&k); - // the keyword was deleted: if that emptied the filter, nothing is left to bring back. The rating - // operator filters nothing without stars, so it alone does not count as something to bring back. - gone_from_put_aside = f.keyword.is_none() && (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default(); } f.keywords = follow_all(&f.keywords); + // every keyword it held was deleted: if that emptied the filter, nothing is left to bring back. The + // rating operator filters nothing without stars, so it alone does not count as something to bring back. + gone_from_put_aside = held_keywords + && f.keyword.is_none() + && f.keywords.is_empty() + && (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default(); } if gone_from_put_aside { s.shelved_filter = None; diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 5d9329d9b40..bf06e81c21b 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -258,6 +258,55 @@ fn several_keywords_follow_a_rename_and_lose_a_deleted_one() { assert_eq!(shown(&mut s), vec![ids[0]]); } +#[test] +fn deleting_every_keyword_of_a_filter_put_aside_leaves_filtering_on() { + let mut s = Session::new(); + let ids = photos(&mut s, 3); + tag(&mut s, ids[0], &["alps"]); + tag(&mut s, ids[1], &["beach"]); + s.execute("library.filter", &json!({"keywords": ["alps", "beach"]})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("keyword.delete", &json!({"keyword": "alps"})).unwrap(); + assert!(s.filters_off(), "one keyword is still put aside"); + s.execute("keyword.delete", &json!({"keyword": "beach"})).unwrap(); + assert!(!s.filters_off(), "an empty filter is not left put aside"); +} + +#[test] +fn a_filter_put_aside_with_other_criteria_survives_its_keywords_going() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps"]); + s.execute("library.filter", &json!({"keywords": ["alps"], "rating": 3})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("keyword.delete", &json!({"keyword": "alps"})).unwrap(); + assert!(s.filters_off()); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.rating, 3); +} + +#[test] +fn a_rating_operator_put_aside_survives_a_keyword_delete_that_does_not_touch_it() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps"]); + s.execute("library.filter", &json!({"ratingOp": "exactly"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("keyword.delete", &json!({"keyword": "alps"})).unwrap(); + assert!(s.filters_off(), "the filter put aside held no keyword, so the delete leaves it alone"); +} + +#[test] +fn a_rating_operator_without_stars_does_not_keep_the_emptied_filter_put_aside() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps"]); + s.execute("library.filter", &json!({"keywords": ["alps"], "ratingOp": "exactly"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("keyword.delete", &json!({"keyword": "alps"})).unwrap(); + assert!(!s.filters_off(), "only an operator with no stars is left: nothing to bring back"); +} + #[test] fn several_dates_show_the_photos_of_any_of_them() { let mut s = Session::new(); From da9b1110ea10f321f062d1f9b4b247ea2c925f6c Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 22:09:58 -0400 Subject: [PATCH 21/55] Sidebars: keyword, album and folder chips join their values with the language's own "or" --- crates/ui-egui/src/panels/chips.rs | 18 +++++++++++++++--- crates/ui-egui/src/tests/panels.rs | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index bdfae039dc0..f08ea336b6d 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -43,7 +43,7 @@ fn label_names(filter: &lightcraft_catalog::Filter, catalog: &lightcraft_catalog } /// The value of a `prefix: value` chip, localised. -fn prefixed_value(prefix: &str, value: &str, filter: &lightcraft_catalog::Filter) -> String { +fn prefixed_value(prefix: &str, value: &str, filter: &lightcraft_catalog::Filter, catalog: &lightcraft_catalog::Catalog) -> String { use crate::i18n::{date_group_label, tr}; let date = match prefix { "Type" => return tr(value).to_string(), @@ -56,7 +56,7 @@ fn prefixed_value(prefix: &str, value: &str, filter: &lightcraft_catalog::Filter return dates.iter().map(|date| date_group_label(date, false)).collect::>().join(&format!(" {} ", tr("or"))); } "Imported" => &filter.imported, - _ => return value.to_string(), + _ => return several_names(prefix, filter, catalog).map_or_else(|| value.to_string(), |names| names.join(&format!(" {} ", tr("or")))), }; date.as_ref().map_or_else(|| value.to_string(), |date| date_group_label(date, false)) } @@ -99,7 +99,7 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt return format!("{} {}", tr("Only"), crate::i18n::tr_format!("{n} photos", n = if filter.only_none { 0 } else { filter.only.len() })); } if let Some((prefix, value)) = chip.label.split_once(": ") { - return format!("{}: {}", tr(prefix), prefixed_value(prefix, value, filter)); + return format!("{}: {}", tr(prefix), prefixed_value(prefix, value, filter, catalog)); } if let Some(value) = chip.label.strip_prefix("Rating ") { return format!("{} {value}", tr("Rating")); @@ -107,6 +107,18 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt tr(&chip.label).to_string() } +/// The names a Keyword, Album or Folder chip lists, as the engine's `filter_chips` builds them, so +/// the caller can join them with the language's own "or". `None` for any other chip. +fn several_names(prefix: &str, filter: &lightcraft_catalog::Filter, catalog: &lightcraft_catalog::Catalog) -> Option> { + let names: Vec = match prefix { + "Keyword" => filter.keywords_wanted(), + "Folder" => filter.library_folders_wanted().iter().map(|d| lightcraft_catalog::folders::folder_label(d)).collect(), + "Album" => filter.albums_wanted().iter().map(|a| catalog.album(*a).map_or_else(|| format!("album {}", a.0), |a| a.name.clone())).collect(), + _ => return None, + }; + (!names.is_empty()).then_some(names) +} + /// Draws the strip; does nothing without chips. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { if chips.is_empty() { diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 342016c7a4b..72f93d95e97 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -2897,3 +2897,26 @@ fn a_date_chip_names_every_date_in_another_language() { set_language(Locale::En); assert!(dates.iter().all(|d| label.contains(d.as_str())), "{label} names {dates:?}"); } + +/// Keyword, album and folder chips that list several values join them with the language's own +/// "or", as the date and label chips do, not with the engine's English one. +#[test] +fn keyword_album_and_folder_chips_join_their_values_in_the_language_s_own_or() { + use crate::i18n::{Locale, set_language}; + let s = lightcraft_engine::Session::new(); + let filter = lightcraft_catalog::Filter { + keywords: vec!["alps".into(), "beach".into()], + albums: vec![lightcraft_catalog::AlbumId(901), lightcraft_catalog::AlbumId(902)], + library_folders: vec!["/lib/Trips".into(), "/lib/Work".into()], + ..Default::default() + }; + let chips = lightcraft_engine::filter_chips(&filter, &s.catalog); + assert_eq!(chips.len(), 3); + set_language(Locale::De); + let labels: Vec = chips.iter().map(|c| crate::panels::chips::display_label(c, &filter, &s.catalog)).collect(); + let or = Locale::De.tr("or"); + set_language(Locale::En); + for label in &labels { + assert!(label.contains(&format!(" {or} ")) && !label.contains(" or "), "{label} joins with {or:?}"); + } +} From eb91d95e901b1a87e9cb0d71c07fff8260a20022 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 08:37:48 -0400 Subject: [PATCH 22/55] Sidebars: a view of several albums with a smart one among them grays out New Smart Album from Filter, naming the smart album --- crates/engine/src/cmd/library/filters.rs | 34 +++++++++++------- crates/engine/src/tests/multi_source.rs | 24 +++++++++++++ crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/run.rs | 4 +++ crates/ui-egui/src/panels/filterbar.rs | 10 +++++- crates/ui-egui/src/panels/left/folders.rs | 7 +++- crates/ui-egui/src/panels/left/sections.rs | 6 +++- crates/ui-egui/src/shortcuts.rs | 5 +-- crates/ui-egui/src/tests/panels.rs | 41 ++++++++++++++++++++++ docs/whats-new.md | 5 +-- 10 files changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index 736b462cc38..b4765a3c0fe 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -53,19 +53,27 @@ pub(crate) fn covers_other_disks(s: &Session, path: &str, ids: &[PhotoId]) -> bo /// can't test another smart album): refuse up front, naming it, instead of letting the rules' /// check say so without the cause. pub(super) fn several_smart_refused(s: &Session, cmd: &str) -> Result<()> { - let shown = s.source_albums(); - if shown.len() < 2 { - return Ok(()); - } - match shown.iter().find_map(|a| s.catalog.album(*a).filter(|a| a.is_smart())) { - Some(smart) => Err(bad( - cmd, - format!( - "the view shows several albums and \"{}\" is a smart album: smart album rules can't test another smart album. Show only albums that aren't smart, or save the smart album's own view", - smart.name - ), - )), - None => Ok(()), + s.view_save_refusal().map_or(Ok(()), |why| Err(bad(cmd, why))) +} + +impl Session { + /// Why the current view can't be saved as smart-album rules (Create Smart Album from Filter, + /// Update Rules from Current Filter), or `None` when it can. The one check behind the menu + /// item's grey-out and the refusal of `album.createSmart` / `album.setRules {fromView}`. + pub fn view_save_refusal(&self) -> Option { + // (asked every frame by the menus: most views name no second album, so say so without a list) + if self.also_albums.is_empty() { + return None; + } + let shown = self.source_albums(); + if shown.len() < 2 { + return None; + } + let smart = shown.iter().find_map(|a| self.catalog.album(*a).filter(|a| a.is_smart()))?; + Some(format!( + "the view shows several albums and \"{}\" is a smart album: smart album rules can't test another smart album. Show only albums that aren't smart, or save the smart album's own view", + smart.name + )) } } diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index bf06e81c21b..d4412ba849c 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -474,3 +474,27 @@ fn albums_in_a_filter_put_aside_do_not_come_back_beside_an_album_source() { assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); assert!(filter_chips(&s.filter, &s.catalog).is_empty()); } + +#[test] +fn a_view_of_several_albums_with_a_smart_one_says_why_it_cannot_be_saved() { + let mut s = Session::new(); + let (_, a, b) = two_albums(&mut s); + let smart = s.execute("album.createSmart", &json!({"name": "Rated", "rules": {"rating": 1}})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + assert_eq!(s.view_save_refusal(), None); + s.execute("library.source", &json!({"kind": "album", "ids": [a, smart]})).unwrap(); + let why = s.view_save_refusal().expect("refused"); + assert!(why.contains("\"Rated\" is a smart album"), "{why}"); + // the commands refuse with that same sentence, and nothing is created or changed + let before = s.catalog.to_snapshot(); + for (cmd, params) in [("album.createSmart", json!({"name": "Both"})), ("album.setRules", json!({"id": smart, "fromView": true}))] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(&why), "{cmd}: {e}"); + } + assert_eq!(s.catalog.to_snapshot(), before); + // rules given in the call don't depend on the view + s.execute("album.createSmart", &json!({"name": "Explicit", "rules": {"rating": 2}})).unwrap(); + // one smart album alone is saved as its own rules + s.execute("library.source", &json!({"kind": "album", "id": smart})).unwrap(); + assert_eq!(s.view_save_refusal(), None); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b6b6c66c520..1e43d4264be 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -30,6 +30,7 @@ fn thumb_size_view(app: &LightcraftApp) -> bool { pub fn ui_enabled(app: &LightcraftApp, id: &str) -> bool { match id { "library.selectOnlyActive" => app.session.active().is_some(), + "dialog.newSmartAlbum" => app.session.view_save_refusal().is_none(), "view.thumbSizeUp" | "view.thumbSizeDown" => thumb_size_view(app), "dialog.contactSheet" | "app.contactSheet" | "dialog.print" | "app.print" => { !cfg!(target_arch = "wasm32") && app.session.active().is_some() && app.export.is_none() diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 9791f0cac3d..23baf05c926 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1139,6 +1139,10 @@ fn ui_commands_8(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va } "dialog.smartAlbum" => dialog_smart_album_command(app, id, p), "dialog.newSmartAlbum" => { + // (several albums with a smart one among them can't be saved: say why, as the engine does) + if let Some(why) = app.session.view_save_refusal() { + return Some(Err(why)); + } app.ui.dialog = Some(Dialog::NewSmartAlbum { name: p.get("name").and_then(Value::as_str).unwrap_or("").into(), parent: parent_param(p) }); Ok(Value::Null) } diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 9de3c4ef0d5..871a53d8263 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -259,8 +259,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // save / clear ui.add_space(14.0); let filtering = app.session.filter != Default::default(); - let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5)))); + let why_not = app.session.view_save_refusal(); + let save = ui.add_enabled( + filtering && why_not.is_none(), + egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5))), + ); register(ui, "button:filterSave", save.rect); + let save = match why_not { + Some(why) => save.on_disabled_hover_text(why), + None => save, + }; if save.clicked() { let _ = app.run("dialog.newSmartAlbum", json!({})); } diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 0dceb0df58a..9d420fc36b9 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -113,7 +113,12 @@ pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Al ("Create Smart Album from Filter…", "dialog.newSmartAlbum"), ("Create Folder…", "dialog.newFolder"), ] { - if ui.button(crate::i18n::tr(label)).clicked() { + // (a view that can't be saved as rules greys out the one that saves it, and says why) + let why_not = if command == "dialog.newSmartAlbum" { app.session.view_save_refusal() } else { None }; + let item = ui.add_enabled(why_not.is_none(), egui::Button::new(crate::i18n::tr(label))); + if let Some(why) = why_not { + item.on_disabled_hover_text(why); + } else if item.clicked() { let _ = app.run(command, json!({"parent": a.id.0})); ui.close(); } diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index b7a3ad39021..f8b3e0b66a5 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -363,7 +363,11 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { parent: None, }); } - if ui.button(crate::i18n::tr("Create Smart Album from Filter…")).clicked() { + let why_not = app.session.view_save_refusal(); + let from_filter = ui.add_enabled(why_not.is_none(), egui::Button::new(crate::i18n::tr("Create Smart Album from Filter…"))); + if let Some(why) = why_not { + from_filter.on_disabled_hover_text(why); + } else if from_filter.clicked() { app.ui.dialog = Some(crate::state::Dialog::NewSmartAlbum { name: String::new(), parent: None }); } if ui.button(crate::i18n::tr("Create Folder…")).clicked() { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 9ab12fe079b..a01c0007aef 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -590,9 +590,10 @@ fn fire_command(app: &mut LightcraftApp, ctx: &egui::Context, f: &str, rotate_fi up_down_key(app, ctx, f); return; } - // an export that can't start (e.g. no folder) says why instead of doing nothing + // an export that can't start (e.g. no folder), or a view that can't be saved as a smart + // album, says why instead of doing nothing if let Err(e) = app.run(f, json!({})) - && matches!(f, "app.export" | "app.exportPrevious") + && matches!(f, "app.export" | "app.exportPrevious" | "dialog.newSmartAlbum") { app.toast(ctx, e); } diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 72f93d95e97..884b970f1b0 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -2920,3 +2920,44 @@ fn keyword_album_and_folder_chips_join_their_values_in_the_language_s_own_or() { assert!(label.contains(&format!(" {or} ")) && !label.contains(" or "), "{label} joins with {or:?}"); } } + +/// Several albums shown with a smart one among them can't be saved as smart-album rules: the +/// File menu's "New Smart Album from Filter…" is greyed out, and running it says why (naming the +/// smart album) in the engine's own words; a single smart album alone still can be saved. +#[test] +fn new_smart_album_from_filter_is_greyed_out_for_several_albums_with_a_smart_one() { + let mut h = folders_app(&["/pics/trip/a.jpg"]); + let plain = h.app.run("album.create", json!({"name": "Alps"})).unwrap()["id"].as_u64().unwrap(); + let other = h.app.run("album.create", json!({"name": "Beach"})).unwrap()["id"].as_u64().unwrap(); + let smart = h.app.run("album.createSmart", json!({"name": "Rated", "rules": {"rating": 1}})).unwrap()["id"].as_u64().unwrap(); + let entry = |h: &Headless| crate::menus::menu_entries(&h.app).into_iter().find(|e| e.id == "dialog.newSmartAlbum").unwrap(); + h.app.run("library.source", json!({"kind": "album", "ids": [plain, other]})).unwrap(); + assert!(entry(&h).enabled, "plain albums can be saved"); + h.app.run("library.source", json!({"kind": "album", "ids": [plain, smart]})).unwrap(); + assert!(!entry(&h).enabled && !crate::menus::ui_enabled(&h.app, "dialog.newSmartAlbum")); + let from_menu = h.app.run("dialog.newSmartAlbum", json!({})).unwrap_err(); + assert!(from_menu.contains("\"Rated\" is a smart album"), "{from_menu}"); + assert!(h.app.ui.dialog.is_none(), "no dialog opened"); + let from_engine = h.app.run("album.createSmart", json!({"name": "X"})).unwrap_err(); + assert!(from_engine.contains(&from_menu), "one message for both: {from_engine} / {from_menu}"); + h.app.run("library.source", json!({"kind": "album", "id": smart})).unwrap(); + assert!(entry(&h).enabled, "a smart album alone is saved as its own rules"); +} + +/// The shortcut of "New Smart Album from Filter…" says why when the view can't be saved, instead of +/// doing nothing (where the window's menu doesn't own the shortcut). +#[test] +fn the_new_smart_album_shortcut_says_why_a_view_of_several_albums_cannot_be_saved() { + let mut h = folders_app(&["/pics/trip/a.jpg"]); + let plain = h.app.run("album.create", json!({"name": "Alps"})).unwrap()["id"].as_u64().unwrap(); + let smart = h.app.run("album.createSmart", json!({"name": "Rated", "rules": {"rating": 1}})).unwrap()["id"].as_u64().unwrap(); + h.app.run("library.source", json!({"kind": "album", "ids": [plain, smart]})).unwrap(); + h.app.native_shortcuts.clear(); + let r = h.request("ui.key", json!({"key": "N", "cmd": true, "alt": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("\"Rated\" is a smart album"), "{toast:?}"); + assert!(h.app.ui.dialog.is_none()); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index f1f59b654aa..b2714eb4957 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -758,8 +758,9 @@ - `library.source` takes `ids` (albums) or `paths` (folders of the library, as `library.folders` lists them, not a browsed Local folder) and shows the photos of any of them, each once; `library.filter` takes `keywords`, `dates`, `libraryFolders` and `albums`. The single fields stay and count as one - more of them. `library.state` lists `albums` and `libraryFolders`. Nothing on screen changes yet: the sidebars' - Cmd+click and Shift+click that use this come in a later change. + more of them. `library.state` lists `albums` and `libraryFolders`. The sidebars' Cmd+click and Shift+click that use + this come in a later change. When the albums shown include a smart album, New Smart Album from Filter… is grayed out + and says why, as `album.createSmart` does. - `album.setRules` with `replace` keeps a smart album's album, as it already kept its folder (`album: null` drops it), so editing a smart album saved from a view of several albums no longer loses them. From f448e325500c33f96d5f00057e16719217a78805 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 09:30:33 -0400 Subject: [PATCH 23/55] Sidebars: a folder filter put aside by Enable Filters follows its folder when it is moved --- crates/engine/src/tests/folders.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/engine/src/tests/folders.rs b/crates/engine/src/tests/folders.rs index 68775727685..f56b02a8331 100644 --- a/crates/engine/src/tests/folders.rs +++ b/crates/engine/src/tests/folders.rs @@ -262,6 +262,18 @@ fn following_a_folder_reads_both_spellings_the_same_way() { assert_eq!(s.filter.library_folder.as_deref(), Some("/elsewhere/b"), "other folders are left alone"); } +#[test] +fn a_folder_filter_put_aside_follows_the_folder_when_it_moves() { + // Enable Filters put a standalone `folder` criterion aside; moving the folder meanwhile must + // not leave the filter pointing at the old path when it comes back + let mut s = Session::new(); + s.execute("library.filter", &json!({"folder": "/a/b/sub"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + crate::cmd::browse::follow_folder(&mut s, "/a/b", "/a/c"); + s.execute("library.toggleFilters", &json!({})).unwrap(); + same_folder(s.filter.folder.as_deref(), "/a/c/sub", "the folder criterion put aside follows its folder"); +} + #[test] fn following_a_folder_keeps_the_case_of_the_subfolder_names() { // Windows compares folders in lower case; the name the user sees must not change with it From c90315264416eac65d751be80cefd7d3d4104173 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 18:53:42 -0400 Subject: [PATCH 24/55] Sidebars: the single album of a filter put aside does not come back beside an album source Enable Filters brought back the single `album` of a filter put aside, where the albums shown are what the grid shows: the filter bar then listed an Album chip that limited nothing. It is cleared with `albums`, as `library.source` does. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/specs.rs | 1 + crates/engine/src/tests/multi_source.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 7ecca4709dd..76d19a509d0 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -314,6 +314,7 @@ pub fn specs() -> Vec { // the album(s) shown are what the grid shows: albums in the filter would be ignored if matches!(s.source, LibrarySource::Album(_)) { f.albums.clear(); + f.album = None; } s.filter = f; } diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index d4412ba849c..737a8e2f803 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -475,6 +475,22 @@ fn albums_in_a_filter_put_aside_do_not_come_back_beside_an_album_source() { assert!(filter_chips(&s.filter, &s.catalog).is_empty()); } +#[test] +fn a_single_album_in_a_filter_put_aside_does_not_come_back_beside_an_album_source() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + // Given the single `album` of the filter, put aside by Enable Filters, and an album then shown as the source + s.execute("library.filter", &json!({"album": b})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + // When the filter is brought back + s.execute("library.toggleFilters", &json!({})).unwrap(); + // Then it stays out, as it does for a filter set while an album is shown: no chip that limits nothing + assert_eq!(s.filter.album, None); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + assert!(filter_chips(&s.filter, &s.catalog).is_empty()); +} + #[test] fn a_view_of_several_albums_with_a_smart_one_says_why_it_cannot_be_saved() { let mut s = Session::new(); From 7dcbf4214dd97adc1598280a8d62173eb8d1c144 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 20:08:36 -0400 Subject: [PATCH 25/55] Sidebars: deleting an album takes it out of the filter and the one put aside; a gone folder's All Photos is not narrowed by the folders of the filter CodeRabbit on #3106 (outside the diff): album.delete left the deleted album in `filter.album`, `filter.albums` and the filter put aside by Enable Filters, which then showed a chip for a gone album or an empty grid. And when the folder shown lost its last photo, the fall back to All Photos kept the folders of the filter (one applied from a preset while the folder was shown, where they were ignored), so All Photos stayed narrowed. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/library/specs.rs | 10 +++++++ crates/engine/src/lib.rs | 3 ++ crates/engine/src/tests/multi_source.rs | 40 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 76d19a509d0..ff45552c139 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1064,6 +1064,16 @@ pub fn specs() -> Vec { } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; + // an album chip of the filter, or of one put aside by Enable Filters, must not name a deleted album + s.filter.album = s.filter.album.filter(|a| !removed.contains(a)); + s.filter.albums.retain(|a| !removed.contains(a)); + if let Some(f) = s.shelved_filter.as_mut() { + f.album = f.album.filter(|a| !removed.contains(a)); + f.albums.retain(|a| !removed.contains(a)); + } + if s.shelved_filter.as_ref() == Some(&Filter::default()) { + s.shelved_filter = None; + } // of several albums shown, the others stay s.also_albums.retain(|a| !removed.contains(a)); if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dc4302de96f..05598ef08a3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1281,6 +1281,9 @@ impl Session { self.source = LibrarySource::All; self.library_folder = None; self.also_library_folders.clear(); + // folders of the filter were ignored while the folder was shown: they would narrow All Photos now + self.filter.library_folder = None; + self.filter.library_folders.clear(); return self.visible(); } if matches!(self.source, LibrarySource::Album(_)) diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 737a8e2f803..8c871fc792b 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -514,3 +514,43 @@ fn a_view_of_several_albums_with_a_smart_one_says_why_it_cannot_be_saved() { s.execute("library.source", &json!({"kind": "album", "id": smart})).unwrap(); assert_eq!(s.view_save_refusal(), None); } + +#[test] +fn deleting_an_album_takes_it_out_of_the_filter_and_the_filter_put_aside() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + let c = album(&mut s, "Cairo", &[ids[3]]); + // Given albums in the filter: the single one and several + s.execute("library.filter", &json!({"album": c, "albums": [a, b, c]})).unwrap(); + // When one is deleted + s.execute("album.delete", &json!({"id": c})).unwrap(); + // Then the filter does not name it: no chip for a gone album + assert_eq!(s.filter.album, None); + assert_eq!(s.filter.albums, vec![AlbumId(a), AlbumId(b)]); + // and the same for the filter put aside by Enable Filters, which must not bring it back + s.execute("library.toggleFilters", &json!({})).unwrap(); + s.execute("album.delete", &json!({"id": b})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + assert_eq!(s.filter.albums, vec![AlbumId(a)]); + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); +} + +#[test] +fn folders_of_a_filter_do_not_narrow_the_all_photos_a_gone_folder_falls_back_to() { + let mut s = Session::new(); + let alps = add_file(&mut s, "/pics/2025/alps/a.jpg"); + let beach = add_file(&mut s, "/pics/2026/beach/c.jpg"); + let city = add_file(&mut s, "/pics/2027/city/d.jpg"); + s.execute("library.source", &json!({"kind": "libraryFolder", "paths": ["/pics/2025/alps"]})).unwrap(); + // Given a preset naming folders, applied while a folder is shown (library.filter would refuse it) + s.filter.library_folder = Some("/pics/2026/beach".into()); + s.filter.library_folders = vec!["/pics/2026/beach".into()]; + // When the folder shown loses its last photo + s.execute("library.select", &json!({"ids": [alps]})).unwrap(); + s.execute("photo.delete", &json!({"ids": [alps]})).unwrap(); + // Then everything is shown, not what the stale folders of the filter leave + assert_eq!(shown(&mut s), vec![beach, city]); + assert_eq!(s.source, LibrarySource::All); + assert_eq!(s.filter.library_folder, None); + assert!(s.filter.library_folders.is_empty()); +} From 7ca98fe164abc5d08cc409458bde79e194959474 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 19:49:27 -0500 Subject: [PATCH 26/55] LR-BEHAV-MULTISELECT: round of 3 Nov: a filter naming a smart album says why it can't be saved, deleting albums or folders leaves what's left right - view_save_refusal looks at the albums the filter names, and refuses a smart album among them, naming it. - library.filter refuses an album id this call names that no album has (`no such album N`), as library.source does. - album.delete and library.removeFolder drop the filter put aside only when the deletion emptied it, the rating operator alone not counting (drop_emptied_shelf). - album.delete keeps the active photo in the grid when a shown album went. - Hold View of several albums: the exception for a smart album among them is documented (hold_view, library.holdView, What's New, parity row) and pinned by a test. --- crates/engine/src/cmd/browse.rs | 1 + crates/engine/src/cmd/library/filters.rs | 32 +++++-- crates/engine/src/cmd/library/specs.rs | 26 +++-- crates/engine/src/lib.rs | 3 + crates/engine/src/tests/hold_view.rs | 27 ++++++ crates/engine/src/tests/multi_source.rs | 117 +++++++++++++++++++++++ docs/parity-checklist.md | 2 +- docs/whats-new.md | 4 +- 8 files changed, 196 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 677ffd000cd..ac726371120 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -491,6 +491,7 @@ pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { *other = chosen.unwrap_or_default(); } follow_library_folder(&mut s.filter.library_folder, from, to); + // (the standalone `folder` criterion, as the one put aside below) follow_library_folder(&mut s.filter.folder, from, to); if let Some(f) = s.shelved_filter.as_mut() { follow_library_folder(&mut f.library_folder, from, to); diff --git a/crates/engine/src/cmd/library/filters.rs b/crates/engine/src/cmd/library/filters.rs index b4765a3c0fe..1658396e43f 100644 --- a/crates/engine/src/cmd/library/filters.rs +++ b/crates/engine/src/cmd/library/filters.rs @@ -49,27 +49,47 @@ pub(crate) fn covers_other_disks(s: &Session, path: &str, ids: &[PhotoId]) -> bo .any(|v| v != "/" && !lightcraft_catalog::query::folder_within(path, &v)) } -/// A view of several albums can't be saved when one of them is a smart album (smart album rules -/// can't test another smart album): refuse up front, naming it, instead of letting the rules' -/// check say so without the cause. +/// A view can't be saved as smart-album rules when it names a smart album beside another album, or in the +/// filter at all (smart album rules can't test another smart album): refuse up front, naming it, instead of +/// letting the rules' check say so without the cause. pub(super) fn several_smart_refused(s: &Session, cmd: &str) -> Result<()> { s.view_save_refusal().map_or(Ok(()), |why| Err(bad(cmd, why))) } +/// Drops the filter put aside by Enable Filters when a deletion emptied it: nothing is left to bring back, and +/// Enable Filters must not stay off for it. `before` is what was put aside before the deletion, so a filter the +/// deletion did not touch stays put aside, whatever it holds. The rating operator filters nothing without stars, +/// so it alone does not count (`keyword.delete` reads it the same way). +pub(super) fn drop_emptied_shelf(s: &mut Session, before: Option<&lightcraft_catalog::Filter>) { + use lightcraft_catalog::Filter; + let emptied = |f: &Filter| (Filter { rating_op: Default::default(), ..f.clone() }) == Filter::default(); + if s.shelved_filter.as_ref() != before && s.shelved_filter.as_ref().is_some_and(emptied) { + s.shelved_filter = None; + } +} + impl Session { /// Why the current view can't be saved as smart-album rules (Create Smart Album from Filter, /// Update Rules from Current Filter), or `None` when it can. The one check behind the menu /// item's grey-out and the refusal of `album.createSmart` / `album.setRules {fromView}`. pub fn view_save_refusal(&self) -> Option { - // (asked every frame by the menus: most views name no second album, so say so without a list) - if self.also_albums.is_empty() { + // (asked every frame by the menus: most views name no album beyond the source's own, so say so without a list) + if self.also_albums.is_empty() && self.filter.album.is_none() && self.filter.albums.is_empty() { return None; } + let smart_among = |albums: &[AlbumId]| albums.iter().find_map(|a| self.catalog.album(*a).filter(|a| a.is_smart())); + // an album the filter names is saved as the rules' album, one smart album alone as well + if let Some(smart) = smart_among(&self.filter.albums_wanted()) { + return Some(format!( + "the filter names \"{}\", a smart album: smart album rules can't test another smart album. Take it out of the filter, or show it and save its own view", + smart.name + )); + } let shown = self.source_albums(); if shown.len() < 2 { return None; } - let smart = shown.iter().find_map(|a| self.catalog.album(*a).filter(|a| a.is_smart()))?; + let smart = smart_among(&shown)?; Some(format!( "the view shows several albums and \"{}\" is a smart album: smart album rules can't test another smart album. Show only albums that aren't smart, or save the smart album's own view", smart.name diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index ff45552c139..71eac2c6388 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1,4 +1,4 @@ -use super::filters::{covers_other_disks, merge_rules, several_smart_refused, view_rules}; +use super::filters::{covers_other_disks, drop_emptied_shelf, merge_rules, several_smart_refused, view_rules}; use super::gps::parse_gps; use super::import::{import_batch_done, import_params, list_auto_import_folder}; use super::selection::{ @@ -179,6 +179,12 @@ pub fn specs() -> Vec { if sets_albums && matches!(s.source, LibrarySource::Album(_)) { return Err(bad("library.filter", "albums are already shown (library.source): show another source first")); } + // an album this call names is there: an id nothing has is an error, not an empty grid, as in + // `library.source` (one left in the filter from before, an undone Create Album, is not this call's) + let mut named = f.albums.iter().copied().filter(|_| p.get("albums").is_some()).chain(f.album.filter(|_| p.get("album").is_some())); + if let Some(gone) = named.find(|a| s.catalog.album(*a).is_none()) { + return Err(bad("library.filter", format!("no such album {}", gone.0))); + } if (f.library_folder.is_some() || !f.library_folders.is_empty()) && s.source == LibrarySource::LibraryFolder { return Err(bad("library.filter", "a folder is already shown (library.source): show another source first")); } @@ -241,15 +247,14 @@ pub fn specs() -> Vec { // of several folders shown, the others stay s.also_library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); // a filter put aside by Enable Filters must not bring the removed folder back + let shelved_before = s.shelved_filter.clone(); if let Some(f) = s.shelved_filter.as_mut() { if f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { f.library_folder = None; } f.library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); } - if s.shelved_filter.as_ref() == Some(&Filter::default()) { - s.shelved_filter = None; - } + drop_emptied_shelf(s, shelved_before.as_ref()); // the folder being shown is gone: back to everything, as for a deleted album if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { s.library_folder = s.also_library_folders.pop(); @@ -364,7 +369,7 @@ pub fn specs() -> Vec { "Hold View Until Refreshed", ["View"], None, - "{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing", + "{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Of several albums shown, a photo stays only while one of them still has it: one that stops matching the rules of a smart album among them goes at once unless another album shown has it. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing", always, |s, p| { let on = match p.get("on") { @@ -1067,18 +1072,23 @@ pub fn specs() -> Vec { // an album chip of the filter, or of one put aside by Enable Filters, must not name a deleted album s.filter.album = s.filter.album.filter(|a| !removed.contains(a)); s.filter.albums.retain(|a| !removed.contains(a)); + let shelved_before = s.shelved_filter.clone(); if let Some(f) = s.shelved_filter.as_mut() { f.album = f.album.filter(|a| !removed.contains(a)); f.albums.retain(|a| !removed.contains(a)); } - if s.shelved_filter.as_ref() == Some(&Filter::default()) { - s.shelved_filter = None; - } + drop_emptied_shelf(s, shelved_before.as_ref()); // of several albums shown, the others stay + let was_shown = s.source_albums().iter().any(|a| removed.contains(a)); s.also_albums.retain(|a| !removed.contains(a)); if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { s.source = s.also_albums.pop().map_or(LibrarySource::All, LibrarySource::Album); } + // the photo looked at may have been in a shown album that went only, so not in the grid now: as when + // another source is shown (an album the grid does not show leaves the selection alone) + if was_shown && s.selection.active.is_some() { + s.keep_active_in_view(); + } ok() } ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 05598ef08a3..0900e537964 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -249,6 +249,9 @@ pub struct Session { visible_clock_minute: Option, /// A view holds the photos it shows until it is refreshed (`library.holdView`): an edit that makes a photo stop /// matching a smart album's rules, Picks or the filter bar leaves it where it is. Off: the photo goes at once. + /// Several albums shown hold a photo only while one of them has it (the view looks in the albums shown, a smart + /// album among them asked live): a photo that stops matching that smart album's rules goes at once, unless another + /// album shown has it. pub hold_view: bool, /// The view last worked out, the catalog's revision then, and the photos in it before stacks are arranged. /// A small edit is followed from it: only the photos the edit touched are asked about again and put at their diff --git a/crates/engine/src/tests/hold_view.rs b/crates/engine/src/tests/hold_view.rs index f30d08c4e07..b234034bd3e 100644 --- a/crates/engine/src/tests/hold_view.rs +++ b/crates/engine/src/tests/hold_view.rs @@ -241,3 +241,30 @@ fn relative_clock_held_view_keeps_expired_photos_admits_new_matches_and_refreshe s.execute("library.refresh", &json!({})).unwrap(); assert_eq!(s.visible_cloned(), vec![ids[1]], "explicit refresh releases the expired photo"); } + +#[test] +fn a_held_view_of_several_albums_keeps_a_photo_only_while_one_of_them_has_it() { + // The view looks in the albums shown, a smart album among them asked live: a photo that stops matching its rules + // stays only if another album shown has it. Either album may be the source (the last one named is). + for names in [["Rated", "Plain"], ["Plain", "Rated"]] { + // Given a smart album of the photos rated 3 or more and a plain album that has the second of them, shown together, held + let mut s = Session::with_demo(); + let ids: Vec = s.visible_cloned().iter().take(2).map(|p| p.0).collect(); + s.execute("library.select", &json!({"ids": ids})).unwrap(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + let plain = s.execute("album.create", &json!({"name": "Plain"})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.addPhotos", &json!({"id": plain, "ids": [ids[1]]})).unwrap(); + let smart = s.execute("album.createSmart", &json!({"name": "Rated", "rules": {"rating": 3}})).unwrap()["id"].as_u64().unwrap(); + let named: Vec = names.iter().map(|n| if *n == "Rated" { smart } else { plain }).collect(); + s.execute("library.source", &json!({"kind": "album", "ids": named})).unwrap(); + hold(&mut s); + let shown = s.visible_cloned(); + assert!(ids.iter().all(|id| shown.contains(&PhotoId(*id))), "{names:?}: both are shown"); + // When both are rated under the smart album's rules + s.execute("photo.rate", &json!({"rating": 1})).unwrap(); + // Then the one the plain album has stays, and the one only the smart album had goes at once + let left = s.visible_cloned(); + assert!(left.contains(&PhotoId(ids[1])), "{names:?}: the plain album still has it"); + assert!(!left.contains(&PhotoId(ids[0])), "{names:?}: no album shown has it now"); + } +} diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 8c871fc792b..9f6b0285b6c 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -554,3 +554,120 @@ fn folders_of_a_filter_do_not_narrow_the_all_photos_a_gone_folder_falls_back_to( assert_eq!(s.filter.library_folder, None); assert!(s.filter.library_folders.is_empty()); } + +#[test] +fn a_filter_naming_a_smart_album_says_why_it_cannot_be_saved() { + let mut s = Session::new(); + let (_, a, _) = two_albums(&mut s); + let smart = s.execute("album.createSmart", &json!({"name": "Rated", "rules": {"rating": 1}})).unwrap()["id"].as_u64().unwrap(); + // Given the filter of All Photos names an album that is not smart, Then the view is saved as rules + s.execute("library.filter", &json!({"albums": [a]})).unwrap(); + assert_eq!(s.view_save_refusal(), None); + // When it names a smart album (among others, or alone as the single album), Then the refusal names it + for filter in [json!({"albums": [a, smart]}), json!({"albums": [], "album": smart})] { + s.execute("library.filter", &filter).unwrap(); + let why = s.view_save_refusal().expect("refused"); + assert!(why.contains("\"Rated\" is a smart album") || why.contains("\"Rated\", a smart album"), "{why}"); + // and the commands refuse with that sentence, saving nothing + let before = s.catalog.to_snapshot(); + let e = s.execute("album.createSmart", &json!({"name": "Both"})).unwrap_err().to_string(); + assert!(e.contains(&why), "{e}"); + assert_eq!(s.catalog.to_snapshot(), before); + } + // the smart album shown alone as the source is still saved as its own rules + s.execute("library.clearFilter", &json!({})).unwrap(); + s.execute("library.source", &json!({"kind": "album", "id": smart})).unwrap(); + assert_eq!(s.view_save_refusal(), None); +} + +#[test] +fn library_filter_refuses_an_album_that_is_not_there_and_the_filter_stays() { + let mut s = Session::new(); + let (ids, a, _) = two_albums(&mut s); + s.execute("library.filter", &json!({"albums": [a]})).unwrap(); + for params in [json!({"albums": [a, 9999]}), json!({"album": 9999})] { + let e = s.execute("library.filter", ¶ms).unwrap_err().to_string(); + assert!(e.contains("9999"), "the refusal names the album: {e}"); + assert_eq!(s.filter.albums, vec![AlbumId(a)], "{params}: refused, nothing changed"); + assert_eq!(s.filter.album, None); + } + assert_eq!(shown(&mut s), vec![ids[0], ids[1]]); + // an album left in the filter that is gone now (an undone Create Album) blocks no other change + let c = album(&mut s, "Cairo", &[ids[3]]); + s.execute("library.filter", &json!({"albums": [a, c]})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("library.filter", &json!({"rating": 0})).unwrap(); + // clearing the albums and the single album stays possible + s.execute("library.filter", &json!({"albums": [], "album": null})).unwrap(); + assert!(s.filter.albums.is_empty()); +} + +#[test] +fn deleting_the_album_of_a_filter_put_aside_leaves_filtering_on_when_only_the_rating_operator_is_left() { + let mut s = Session::new(); + let (_, a, b) = two_albums(&mut s); + s.execute("library.filter", &json!({"albums": [a], "ratingOp": "exactly"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + // another album goes: the filter put aside is not touched + s.execute("album.delete", &json!({"id": b})).unwrap(); + assert!(s.filters_off()); + // the album it names goes: an operator with no stars filters nothing, there is nothing to bring back + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert!(!s.filters_off()); + // a filter put aside with only an operator, which no deletion touched, stays put aside + s.execute("library.filter", &json!({"ratingOp": "exactly"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + let c = s.execute("album.create", &json!({"name": "Cairo"})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.delete", &json!({"id": c})).unwrap(); + assert!(s.filters_off()); +} + +#[test] +fn removing_the_folder_of_a_filter_put_aside_leaves_filtering_on_when_only_the_rating_operator_is_left() { + let mut s = Session::new(); + add_file(&mut s, "/pics/2025/alps/a.jpg"); + add_file(&mut s, "/pics/2026/beach/c.jpg"); + s.execute("library.filter", &json!({"libraryFolder": "/pics/2025/alps", "ratingOp": "exactly"})).unwrap(); + s.execute("library.toggleFilters", &json!({})).unwrap(); + // another folder goes: the filter put aside is not touched + s.execute("library.removeFolder", &json!({"path": "/pics/2026/beach"})).unwrap(); + assert!(s.filters_off()); + // the folder it names goes: nothing is left to bring back but an operator with no stars + s.execute("library.removeFolder", &json!({"path": "/pics/2025/alps"})).unwrap(); + assert!(!s.filters_off()); +} + +#[test] +fn deleting_one_of_several_shown_albums_moves_the_active_photo_into_what_is_left() { + let mut s = Session::new(); + // Alps {0, 1} and Beach {1, 2}, both shown + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + // Given the active photo is in the album that goes only + s.execute("library.select", &json!({"ids": [ids[0]]})).unwrap(); + // When Alps is deleted + s.execute("album.delete", &json!({"id": a})).unwrap(); + // Then the grid shows Beach and the active photo is one of its photos, not one nobody can see + let left = shown(&mut s); + assert_eq!(left, vec![ids[1], ids[2]]); + assert!(s.active().is_some_and(|p| left.contains(&p.0)), "{:?}", s.active()); + // a photo still in view stays the active one + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + s.execute("library.select", &json!({"ids": [ids[1]]})).unwrap(); + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(ids[1]))); + // and with no active photo, none is picked + let (_, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b]})).unwrap(); + s.selection = Default::default(); + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert_eq!(s.active(), None); + // an album the grid does not show leaves the selection alone, also a photo the grid does not show + let (ids, a, b) = two_albums(&mut s); + s.execute("library.source", &json!({"kind": "album", "id": a})).unwrap(); + s.execute("library.select", &json!({"ids": [ids[2]]})).unwrap(); + s.execute("album.delete", &json!({"id": b})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(ids[2]))); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 3f6ccc67a87..967071273c7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -459,7 +459,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs` | photos in the grid; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter, each photo shown once (the sidebars' Cmd/Ctrl+click and Shift+click that use it are a later change) | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs` | photos in the grid; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter, each photo shown once (the sidebars' Cmd/Ctrl+click and Shift+click that use it are a later change); with Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | diff --git a/docs/whats-new.md b/docs/whats-new.md index b2714eb4957..6a1fbcc1c51 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -760,7 +760,9 @@ `libraryFolders` and `albums`. The single fields stay and count as one more of them. `library.state` lists `albums` and `libraryFolders`. The sidebars' Cmd+click and Shift+click that use this come in a later change. When the albums shown include a smart album, New Smart Album from Filter… is grayed out - and says why, as `album.createSmart` does. + and says why, as `album.createSmart` does. So does a filter that names a smart album. +- With View ▸ Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it: a + photo that stops matching the rules of a smart album among them goes at once, unless another album shown has it. - `album.setRules` with `replace` keeps a smart album's album, as it already kept its folder (`album: null` drops it), so editing a smart album saved from a view of several albums no longer loses them. From 89fe24f56e065e1fec1bdb34a83132c33ad3f7aa Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 19:52:57 -0500 Subject: [PATCH 27/55] LR-BEHAV-MULTISELECT: the revision row and What's New lines for the round of 3 Nov --- docs/parity-checklist.md | 1 + docs/whats-new.md | 3 +++ 2 files changed, 4 insertions(+) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 967071273c7..ca828f06212 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1051,3 +1051,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | | 2026-10-21 | minor | LR-BEHAV-MULTISELECT: `library.source` takes several albums (`ids`) or folders (`paths`) and `library.filter` several keywords, dates, folders or albums, each photo shown once; `album.setRules` with `replace` keeps a smart album's album and folders; statuses unchanged | +| 2026-11-03 | patch | LR-BEHAV-MULTISELECT: a view whose filter names a smart album can't be saved as smart-album rules, and New Smart Album from Filter… is grayed out saying which album it is (a smart album's rules can't test another one); `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does; deleting an album or a folder drops the filter put aside by Enable Filters when only the rating operator is left of it, and deleting a shown album moves the active photo into what is left; Hold View of several albums with a smart album among them is documented as it behaves (a photo stays only while one of them has it); statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 6a1fbcc1c51..9e86af7a06a 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -763,6 +763,9 @@ and says why, as `album.createSmart` does. So does a filter that names a smart album. - With View ▸ Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it: a photo that stops matching the rules of a smart album among them goes at once, unless another album shown has it. +- `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does. Deleting a shown + album moves the active photo into what is left. A filter put aside by Enable Filters that a deleted album or folder + leaves with only the rating operator is dropped, as one a deleted keyword leaves. - `album.setRules` with `replace` keeps a smart album's album, as it already kept its folder (`album: null` drops it), so editing a smart album saved from a view of several albums no longer loses them. From 4c7163c44eb9de8fe08d0b1c34401efadf9cf471 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 13:55:20 -0400 Subject: [PATCH 28/55] LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars The left panel's Albums, Folders, Keywords and By Date and the Keyword List call the model of #2707: a click chooses a row alone, Cmd/Ctrl+click adds it or takes it away, Shift+click takes the rows between. What is chosen is what the grid shows (library.source ids/paths, library.filter keywords/dates of #1153); the Keyword List's picks stay in the interface. Carries the act hunk of #777 (a refused command says why), which this PR's clicks use. Parents: #1153 792ebf1f7e and #2707 6ffa75d2a5. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs-formats.json | 4 +- crates/ui-egui/locales/de-formats.json | 4 +- crates/ui-egui/locales/es-formats.json | 4 +- crates/ui-egui/locales/fi-formats.json | 4 +- crates/ui-egui/locales/fr-formats.json | 4 +- crates/ui-egui/locales/id-formats.json | 4 +- crates/ui-egui/locales/it-formats.json | 4 +- crates/ui-egui/locales/ja-formats.json | 4 +- crates/ui-egui/locales/ka-formats.json | 4 +- crates/ui-egui/locales/pl-formats.json | 4 +- crates/ui-egui/locales/pt-br-formats.json | 4 +- crates/ui-egui/locales/ru-formats.json | 4 +- crates/ui-egui/locales/sv-formats.json | 4 +- crates/ui-egui/locales/uk-formats.json | 4 +- crates/ui-egui/locales/vi-formats.json | 4 +- crates/ui-egui/locales/zh-hans-formats.json | 4 +- crates/ui-egui/locales/zh-hant-formats.json | 4 +- crates/ui-egui/src/app.rs | 47 +- crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/i18n.rs | 7 + crates/ui-egui/src/lib.rs | 63 + crates/ui-egui/src/menus/files.rs | 6 +- crates/ui-egui/src/menus/menubar.rs | 9 +- crates/ui-egui/src/multi_select.rs | 231 ++ crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/dialogs.rs | 2653 +++++++++++++++++++ crates/ui-egui/src/panels/filterbar.rs | 11 +- crates/ui-egui/src/panels/grid.rs | 2 + crates/ui-egui/src/panels/keyword_list.rs | 21 +- crates/ui-egui/src/panels/keywording.rs | 2 +- crates/ui-egui/src/panels/side_select.rs | 225 ++ crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/multi_select.rs | 387 +++ docs/gaps.md | 3 +- docs/parity-checklist.md | 3 +- docs/whats-new.md | 13 + 37 files changed, 3713 insertions(+), 46 deletions(-) create mode 100644 crates/ui-egui/src/multi_select.rs create mode 100644 crates/ui-egui/src/panels/dialogs.rs create mode 100644 crates/ui-egui/src/panels/side_select.rs create mode 100644 crates/ui-egui/src/tests/multi_select.rs diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 77c37c84fc2..4f2b401ccc3 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -325,5 +325,7 @@ "View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).", "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", + "{n} albums": "Alba: {n}", + "{n} folders": "Složky: {n}" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 7e78396a1ca..85a573538f6 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet", "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", - "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys})." + "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", + "{n} albums": "{n} Alben", + "{n} folders": "{n} Ordner" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 77d40f0ec0d..c8d029dacb7 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado", "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", - "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys})." + "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", + "{n} albums": "{n} álbumes", + "{n} folders": "{n} carpetas" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 31f6c32b5d4..e5d43578f2b 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -322,5 +322,7 @@ "View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).", "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", + "{n} albums": "{n} albumia", + "{n} folders": "{n} kansiota" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ba6bcc7b0f9..db5aceb98bf 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée", "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", - "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys})." + "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", + "{n} albums": "{n} albums", + "{n} folders": "{n} dossiers" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7bd027cc352..18218280d63 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -325,5 +325,7 @@ "View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", + "{n} albums": "{n} album", + "{n} folders": "{n} folder" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 922bac810df..c9967b0bae4 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -325,5 +325,7 @@ "View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", + "{n} albums": "{n} album", + "{n} folders": "{n} cartelle" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 9f7dd3fe7cc..ebaf0566115 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", - "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。" + "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", + "{n} albums": "{n}個のアルバム", + "{n} folders": "{n}個のフォルダ" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index b13dc07d30d..cf05948c2f5 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -328,5 +328,7 @@ "View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).", "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", + "{n} albums": "ალბომები: {n}", + "{n} folders": "საქაღალდეები: {n}" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index f03219ae1eb..af654a30171 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -325,5 +325,7 @@ "View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).", "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", + "{n} albums": "Albumy: {n}", + "{n} folders": "Foldery: {n}" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 4227fe328a9..f7b24ef1c32 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado", "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", - "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys})." + "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", + "{n} albums": "{n} álbuns", + "{n} folders": "{n} pastas" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 24134de9440..7107471bfcb 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", - "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys})." + "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", + "{n} albums": "Альбомы: {n}", + "{n} folders": "Папки: {n}" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 124fcb3a182..0406151a900 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -325,5 +325,7 @@ "View › Detail View ({keys}).": "Visa › Detaljvy ({keys}).", "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", + "{n} albums": "{n} album", + "{n} folders": "{n} mappar" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index d30091f2d2b..a0870bd4eb8 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", - "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys})." + "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", + "{n} albums": "Альбоми: {n}", + "{n} folders": "Теки: {n}" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d6c686c3b54..81a956e5074 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -322,5 +322,7 @@ "View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).", "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", + "{n} albums": "{n} album", + "{n} folders": "{n} thư mục" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 1d5f27c5764..a8d1ae73d34 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", - "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。" + "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", + "{n} albums": "{n} 个相册", + "{n} folders": "{n} 个文件夹" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 51fb1109ae4..102e4a9ddaa 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -326,5 +326,7 @@ "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", - "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。" + "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", + "{n} albums": "{n} 個相簿", + "{n} folders": "{n} 個資料夾" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 74425972d80..2b08fc7893c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,10 +3,10 @@ use super::services::Services; use super::state::{GestureFrame, InjectedDrop, InjectedPress}; use super::{ AiModel, Caches, CommandError, ControlRequest, ControlResponse, ErrorKind, GESTURE_TIMEOUT_MS, LightcraftApp, MAX_PENDING_GESTURES, - MAX_PENDING_SHOTS, MAX_SHOT_BYTES, MAX_SHOT_TOTAL_BYTES, MAX_TEXTURE_SIDE, PendingGesture, PendingShot, Perf, Receiver, SCREEN_PROFILE, - SCREENSHOT_FALLBACK_MS, SCREENSHOT_SETTLE_MS, SHOT_FORCE_BUSY_MS, SHOT_SETTLE_FRAMES, SHOT_SETTLE_MS, Sender, Session, ShotGeometry, - TOAST_SECONDS, UiState, Value, docking, drop_overlay, export_task, focus_scan, frame_rate, headless, i18n, import, lightroom_import, menus, - merge, panels, pick, recheck, render, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, + MAX_PENDING_SHOTS, MAX_SHOT_BYTES, MAX_SHOT_TOTAL_BYTES, MAX_TEXTURE_SIDE, PendingGesture, PendingShot, Perf, REFUSAL_SECONDS, Receiver, Refusal, + SCREEN_PROFILE, SCREENSHOT_FALLBACK_MS, SCREENSHOT_SETTLE_MS, SHOT_FORCE_BUSY_MS, SHOT_SETTLE_FRAMES, SHOT_SETTLE_MS, Sender, Session, + ShotGeometry, TOAST_SECONDS, UiState, Value, docking, drop_overlay, export_task, focus_scan, frame_rate, headless, i18n, import, + lightroom_import, menus, merge, panels, pick, recheck, render, shortcuts, slideshow_export, state, sync, tasks, theme, updates_ui, widgets, }; mod control; @@ -194,19 +194,40 @@ impl LightcraftApp { } } - /// Run a UI or engine command by id. The single entry point for every frontend path. + /// Run a UI or engine command by id. The single entry point for every frontend path: the + /// error comes back in full and nothing is shown, for agents (the control channel) and for + /// code that deals with the answer itself. A widget acting for the person uses [`Self::act`]. pub fn run(&mut self, id: &str, params: Value) -> Result { - self.run_typed(id, params).map_err(|e| e.message) + self.run_told(id, params).map_err(|refusal| refusal.error) } /// [`LightcraftApp::run`], keeping what kind of error a refusal is: for code that decides on it /// (offer a model's download, treat a cancel as one) instead of reading the message. pub fn run_typed(&mut self, id: &str, params: Value) -> Result { + self.run_told(id, params).map_err(|refusal| CommandError { message: refusal.error, kind: refusal.kind }) + } + + /// Run a command for the person at the interface (a click, a drop, a key): when it is + /// refused, a toast says why, so no widget has to pass that on by hand (or forget to). + /// `None` when it was refused: say a success of your own only on `Some`, or it writes over + /// the reason. A widget says which of `act` and [`Self::run`] it means: `run` shows nothing. + pub fn act(&mut self, id: &str, params: Value) -> Option { + match self.run_told(id, params) { + Ok(v) => Some(v), + Err(refusal) => { + self.ui.toast = Some((refusal.why, self.tick_now() + REFUSAL_SECONDS, None)); + None + } + } + } + + /// [`Self::run`], keeping what a refusal says to a person apart from the whole error. + fn run_told(&mut self, id: &str, params: Value) -> Result { if let Some(r) = menus::run_ui_command(self, id, ¶ms) { if r.is_ok() { - docking::reveal_command(self, id)?; + docking::reveal_command(self, id).map_err(Refusal::plain)?; } - return r.map_err(CommandError::from); + return r.map_err(Refusal::plain); } let params = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("toggle") @@ -217,7 +238,7 @@ impl LightcraftApp { } else { params }; - let r = self.session.execute(id, ¶ms).map_err(CommandError::from); + let r = self.session.execute(id, ¶ms).map_err(Refusal::from); 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")) @@ -280,11 +301,11 @@ impl LightcraftApp { self.ui.toast = Some((text, now + TOAST_SECONDS, label)); } match &r { - Err(e) => { - log::warn!("{id}: {e}"); - self.ui.status = e.message.clone(); + Err(refusal) => { + log::warn!("{id}: {}", refusal.error); + self.ui.status = refusal.error.clone(); // no detector yet: offer it (its terms first) instead of only saying so - if id == "faces.detect" && e.kind == ErrorKind::ModelMissing(AiModel::FaceDetector) { + if id == "faces.detect" && refusal.kind == ErrorKind::ModelMissing(AiModel::FaceDetector) { panels::faces::offer_detector(self); } } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a9138..baef834beda 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -290,6 +290,7 @@ impl LightcraftApp { // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI // phase, not the hidden-capable `logic` tick (plan §4.5 / migration input contract). panels::library_problem::logic(self, ctx); + panels::side_select::frame(self); if self.fonts_ready && !updates_ui::blocks_input(self) { shortcuts::handle(self, ctx); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c9e0e6aead5..8b9369dde25 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -392,6 +392,13 @@ pub fn source_label(source: lightcraft_engine::LibrarySource, catalog: &lightcra /// two names (`photos/travel`; the folder's name is the user's and stays verbatim). pub fn source_title(session: &lightcraft_engine::Session) -> String { match (session.source, session.library_folder.as_deref()) { + // several chosen at once in the sidebar + (lightcraft_engine::LibrarySource::Album(_), _) if !session.also_albums.is_empty() => { + tr_format!("{n} albums", n = session.source_albums().len()) + } + (lightcraft_engine::LibrarySource::LibraryFolder, Some(_)) if !session.also_library_folders.is_empty() => { + tr_format!("{n} folders", n = session.source_library_folders().len()) + } (lightcraft_engine::LibrarySource::LibraryFolder, Some(path)) => lightcraft_catalog::folders::folder_label(path), (source, _) => source_label(source, &session.catalog), } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1b34105562..54312c2a2cf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -108,6 +108,69 @@ pub use services::{ use state::{GestureFrame, InjectedPress}; const TOAST_SECONDS: f64 = 1.4; +/// How long a toast saying why a command was refused stays: a sentence to read, as +/// [`LightcraftApp::toast_error`]'s. +const REFUSAL_SECONDS: f64 = 6.0; + +/// A command that didn't run: the whole error (for agents, the log and the status) and what it +/// says to the person who asked (the reason, without the command's id). +pub(crate) struct Refusal { + error: String, + why: String, + /// What kind of error it is, for code that decides on it ([`LightcraftApp::run_typed`]). + kind: ErrorKind, +} + +impl Refusal { + /// An error that is already text (the interface's own commands). Mostly words for a person + /// as they are; a command that wraps an engine command hands on the engine's error already + /// turned into text, and of that only the reason is for the person. `error` stays whole. + fn plain(error: String) -> Refusal { + let why = engine_reason(&error).map(sentence).unwrap_or_else(|| error.clone()); + Refusal { why, error, kind: ErrorKind::Other } + } +} + +/// A sentence starts with a capital, whatever the command wrote. Only when it starts with a word: +/// a file name or a path ("img_0012.jpg is a virtual copy", "photos/a.jpg: …") is someone's +/// spelling and stays as it is, and so does a letter whose capital is not one letter (ß). +fn sentence(why: &str) -> String { + let first_word = why.split_whitespace().next().unwrap_or_default().trim_end_matches([',', ':', ';']); + let mut letters = why.chars(); + match letters.next() { + Some(first) if first_word.chars().all(char::is_alphabetic) && first.to_uppercase().count() == 1 => { + first.to_uppercase().chain(letters).collect() + } + _ => why.to_string(), + } +} + +/// The reason in an [`EngineError`](lightcraft_engine::EngineError) that is already text: what +/// follows ``command `id` is not available right now: `` or ``invalid parameters for `id`: `` +/// (its `Disabled` and `BadParams` formats). `None` for anything else, including text that only +/// begins like one: the id must be a command's (letters, digits, `.`, `_`, `-`) between the +/// backticks, so the reason is cut at the first separator and may hold colons and backticks. +fn engine_reason(error: &str) -> Option<&str> { + const SHAPES: [(&str, &str); 2] = [("command `", "` is not available right now: "), ("invalid parameters for `", "`: ")]; + SHAPES.iter().find_map(|(before, after)| { + let (id, reason) = error.strip_prefix(before)?.split_once(after)?; + let is_id = !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + (is_id && !reason.trim().is_empty()).then_some(reason) + }) +} + +impl From for Refusal { + fn from(e: lightcraft_engine::EngineError) -> Refusal { + use lightcraft_engine::EngineError; + let why = match &e { + EngineError::Disabled(_, why) => why.clone(), + EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + }; + Refusal { error: e.to_string(), why: sentence(&why), kind: e.kind() } + } +} + /// The `path` of a display profile read from the screen rather than chosen as a file. pub const SCREEN_PROFILE: &str = "screen"; diff --git a/crates/ui-egui/src/menus/files.rs b/crates/ui-egui/src/menus/files.rs index d75282e5778..29b54477bf2 100644 --- a/crates/ui-egui/src/menus/files.rs +++ b/crates/ui-egui/src/menus/files.rs @@ -3,9 +3,13 @@ use super::{Dialog, LightcraftApp, Value, json}; /// The Delete key in an album: a normal album loses the selected photos (`album.removePhotos`), /// which stay in the library and their folder; a smart album keeps them (its rules decide) and /// says so. True when the key was handled here, false outside albums (then it deletes the photos -/// from the library). Photo ▸ Delete Photo still deletes from the library everywhere. +/// from the library). Photo ▸ Delete Photo still deletes from the library everywhere. With several +/// albums shown there is no telling which one is meant, so the key is the photos' there too. pub fn delete_in_album(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { let lightcraft_engine::LibrarySource::Album(aid) = app.session.source else { return false }; + if !app.session.also_albums.is_empty() { + return false; + } let Some(album) = app.session.catalog.album(aid) else { return false }; if album.is_smart() { app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo")); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index b73729a9131..4f23fae95b6 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -375,10 +375,13 @@ fn host_supports(app: &LightcraftApp, id: &str) -> bool { } } -/// The library shows an album that holds its photos (not a smart album, not a folder of albums). +/// The library shows one album that holds its photos (not a smart album, not a folder of albums, +/// not several albums at once: Remove from Album would take the photos out of the one chosen last). pub(crate) fn in_normal_album(app: &LightcraftApp) -> bool { match app.session.source { - lightcraft_engine::LibrarySource::Album(a) => app.session.catalog.album(a).is_some_and(|a| !a.folder && !a.is_smart()), + lightcraft_engine::LibrarySource::Album(a) => { + app.session.also_albums.is_empty() && app.session.catalog.album(a).is_some_and(|a| !a.folder && !a.is_smart()) + } _ => false, } } @@ -836,7 +839,7 @@ fn node(app: &LightcraftApp, e: &MenuEntry) -> MenuNode { let shortcut = match e.id.as_str() { "view.photoGrid" | "view.squareGrid" => shortcut.or_else(|| crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "view.gridToggle")), "album.removePhotos" => delete_key, - "photo.delete" if matches!(app.session.source, lightcraft_engine::LibrarySource::Album(_)) => None, + "photo.delete" if matches!(app.session.source, lightcraft_engine::LibrarySource::Album(_)) && app.session.also_albums.is_empty() => None, _ => shortcut, }; item(&e.id, Value::Null, live_label(app, &e.id, &e.label), shortcut, e.enabled, checked(app, &e.id)) diff --git a/crates/ui-egui/src/multi_select.rs b/crates/ui-egui/src/multi_select.rs new file mode 100644 index 00000000000..80188b7749e --- /dev/null +++ b/crates/ui-egui/src/multi_select.rs @@ -0,0 +1,231 @@ +//! Choosing several rows of a list at once: Cmd/Ctrl+click adds a row or takes it away, +//! Shift+click takes every row from the row last clicked without Shift (else the row chosen last) +//! to this one. One rule for the sidebars' lists (albums, folders, keywords, dates, the Keyword +//! List), so they all answer the same way. +//! +//! The rows chosen are kept in the order chosen; the last of them is the one an action for a +//! single row takes (Rename…, Edit…). +//! +//! It is the model for LR-BEHAV-MULTISELECT's sidebar multi-select (the albums, folders, keywords +//! and dates lists and the Keyword List); `panels::side_select` calls it for the clicks, and +//! [`targets`] is for the menus that act on several rows (a later change). It keeps no egui state +//! (only `egui::Modifiers` says which keys were held) and calls no engine code. + +/// What a click asks for, by the keys held with it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Click { + /// Choose this row alone. + Plain, + /// Cmd/Ctrl: add this row to those chosen, or take it away. + Toggle, + /// Shift: the rows from the anchor to this one, instead of what was chosen. + Range, + /// Cmd/Ctrl+Shift: the rows from the anchor to this one, added to what was chosen. + AddRange, +} + +impl Click { + pub fn of(m: egui::Modifiers) -> Click { + match (m.shift, m.command) { + (true, true) => Click::AddRange, + (true, false) => Click::Range, + (false, true) => Click::Toggle, + (false, false) => Click::Plain, + } + } +} + +/// The rows chosen after a click, and where the next Shift+click starts from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Chosen { + /// In the order chosen; the last is the one a single-row action takes. + pub keys: Vec, + pub anchor: Option, +} + +/// What a click on the row `at` makes of the rows `chosen`. `rows` are the list's rows as drawn, +/// top to bottom: every row of an open level (also one a frame skipped drawing because it was +/// scrolled out of view), and none inside a closed level, so a range never takes rows that are +/// folded away; `anchor` is the row last clicked without Shift; `same` tells two rows' keys alike. +/// +/// A range needs its anchor among `rows`: without one (nothing clicked yet, or it was folded +/// away) Shift+click chooses the row alone, like a plain click. +pub fn click(rows: &[K], chosen: &[K], anchor: Option<&K>, at: &K, how: Click, same: &dyn Fn(&K, &K) -> bool) -> Chosen { + let alone = || Chosen { keys: vec![at.clone()], anchor: Some(at.clone()) }; + match how { + Click::Plain => alone(), + Click::Toggle => { + let mut keys: Vec = chosen.to_vec(); + let before = keys.len(); + keys.retain(|k| !same(k, at)); + if keys.len() == before { + keys.push(at.clone()); + } + Chosen { keys, anchor: Some(at.clone()) } + } + Click::Range | Click::AddRange => { + let index = |k: &K| rows.iter().position(|r| same(r, k)); + let (Some(from), Some(to)) = (anchor.and_then(index), index(at)) else { return alone() }; + let mut keys: Vec = if how == Click::AddRange { chosen.to_vec() } else { Vec::new() }; + // from the anchor towards the row clicked, so that one is the last chosen + let range: Vec<&K> = if from <= to { + rows.get(from..=to).unwrap_or_default().iter().collect() + } else { + rows.get(to..=from).unwrap_or_default().iter().rev().collect() + }; + for k in range { + keys.retain(|x| !same(x, k)); + keys.push(k.clone()); + } + Chosen { keys, anchor: anchor.cloned() } + } + } +} + +/// What a context menu opened on the row `at` acts on: every row chosen when `at` is one of +/// several chosen, else that row alone (the rows chosen stay as they are either way). +pub fn targets(chosen: &[K], at: &K, same: &dyn Fn(&K, &K) -> bool) -> Vec { + if chosen.len() > 1 && chosen.iter().any(|k| same(k, at)) { chosen.to_vec() } else { vec![at.clone()] } +} + +/// One list's rows as drawn, for Shift+click: `seen` while a frame draws them, `rows` of the +/// frame before (what the person clicked on), and the anchor. +#[derive(Clone, Debug)] +pub struct ListRows { + seen: Vec, + rows: Vec, + pub anchor: Option, +} + +impl Default for ListRows { + fn default() -> Self { + ListRows { seen: Vec::new(), rows: Vec::new(), anchor: None } + } +} + +impl ListRows { + /// A new frame: the rows of the last one are what a click now is on. + pub fn begin_frame(&mut self) { + std::mem::swap(&mut self.rows, &mut self.seen); + self.seen.clear(); + } + /// A row of this frame, in drawing order. + pub fn saw(&mut self, key: K) { + self.seen.push(key); + } + /// The rows a click is on: the last frame's. + pub fn rows(&self) -> &[K] { + &self.rows + } + /// A click on `at` with `how`, among the rows drawn; remembers the anchor. + pub fn click(&mut self, chosen: &[K], at: &K, how: Click, same: &dyn Fn(&K, &K) -> bool) -> Vec { + // a range starts from a row that is chosen: the one last clicked while it still is, else + // the one chosen last (chosen by a menu, an agent or the last session, or after what was + // clicked stopped being shown) + let anchor = self.anchor.as_ref().filter(|a| chosen.iter().any(|c| same(c, a))).or(chosen.last()); + let out = click(&self.rows, chosen, anchor, at, how, same); + self.anchor = out.anchor; + out.keys + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ROWS: [&str; 6] = ["a", "b", "c", "d", "e", "f"]; + fn eq(a: &&str, b: &&str) -> bool { + a == b + } + fn go(chosen: &[&'static str], anchor: Option<&'static str>, at: &'static str, how: Click) -> (Vec<&'static str>, Option<&'static str>) { + let out = click(&ROWS, chosen, anchor.as_ref(), &at, how, &eq); + (out.keys, out.anchor) + } + + #[test] + fn the_keys_held_say_what_a_click_asks_for() { + use egui::Modifiers as M; + assert_eq!(Click::of(M::NONE), Click::Plain); + assert_eq!(Click::of(M::COMMAND), Click::Toggle); + assert_eq!(Click::of(M::SHIFT), Click::Range); + assert_eq!(Click::of(M::SHIFT | M::COMMAND), Click::AddRange); + // Alt alone asks for nothing special + assert_eq!(Click::of(M::ALT), Click::Plain); + } + + #[test] + fn a_plain_click_chooses_the_row_alone() { + assert_eq!(go(&["a", "c"], Some("a"), "e", Click::Plain), (vec!["e"], Some("e"))); + assert_eq!(go(&["a", "c"], Some("a"), "c", Click::Plain), (vec!["c"], Some("c")), "also one of several chosen"); + } + + #[test] + fn cmd_click_adds_a_row_or_takes_it_away() { + assert_eq!(go(&["a"], Some("a"), "c", Click::Toggle), (vec!["a", "c"], Some("c"))); + assert_eq!(go(&["a", "c"], Some("c"), "a", Click::Toggle), (vec!["c"], Some("a"))); + assert_eq!(go(&["a"], Some("a"), "a", Click::Toggle), (vec![], Some("a")), "the last one can be taken away too"); + } + + #[test] + fn shift_click_takes_the_rows_from_the_anchor() { + // downwards and upwards; the row clicked is the last chosen, and the anchor stays + assert_eq!(go(&["b"], Some("b"), "e", Click::Range), (vec!["b", "c", "d", "e"], Some("b"))); + assert_eq!(go(&["e"], Some("e"), "c", Click::Range), (vec!["e", "d", "c"], Some("e"))); + // a second Shift+click from the same anchor replaces the first range + assert_eq!(go(&["b", "c", "d", "e"], Some("b"), "c", Click::Range), (vec!["b", "c"], Some("b"))); + // …and what was chosen elsewhere goes + assert_eq!(go(&["f", "b"], Some("b"), "c", Click::Range), (vec!["b", "c"], Some("b"))); + } + + #[test] + fn cmd_shift_click_adds_the_range_to_what_was_chosen() { + assert_eq!(go(&["a", "d"], Some("d"), "f", Click::AddRange), (vec!["a", "d", "e", "f"], Some("d"))); + // a row already chosen is not chosen twice, and the row clicked is still the last + assert_eq!(go(&["e", "c"], Some("c"), "e", Click::AddRange), (vec!["c", "d", "e"], Some("c"))); + } + + #[test] + fn a_range_without_an_anchor_in_sight_chooses_the_row_alone() { + assert_eq!(go(&[], None, "c", Click::Range), (vec!["c"], Some("c"))); + // the anchor was folded away since (not among the rows drawn) + assert_eq!(go(&["x"], Some("x"), "c", Click::Range), (vec!["c"], Some("c"))); + // a row that is not drawn (a stale click) chooses itself and nothing else + assert_eq!(go(&["a"], Some("a"), "zz", Click::AddRange), (vec!["zz"], Some("zz"))); + // the anchor is the row clicked: that row alone, anchor kept + assert_eq!(go(&["b", "c"], Some("b"), "b", Click::Range), (vec!["b"], Some("b"))); + // no rows drawn at all + let none: [&str; 0] = []; + assert_eq!(click(&none, &["a"], Some(&"a"), &"c", Click::Range, &eq).keys, vec!["c"]); + } + + #[test] + fn a_menu_acts_on_the_rows_chosen_only_when_opened_on_one_of_them() { + assert_eq!(targets(&["a", "c"], &"c", &eq), vec!["a", "c"]); + assert_eq!(targets(&["a", "c"], &"e", &eq), vec!["e"], "another row: that row alone"); + assert_eq!(targets(&["a"], &"a", &eq), vec!["a"]); + assert_eq!(targets(&[], &"a", &eq), vec!["a"]); + } + + #[test] + fn a_list_s_clicks_are_on_the_rows_of_the_frame_before() { + let mut l: ListRows<&str> = ListRows::default(); + for r in ROWS { + l.saw(r); + } + // nothing drawn before this frame: no range yet + assert_eq!(l.click(&[], &"b", Click::Plain, &eq), vec!["b"]); + l.begin_frame(); + for r in ["a", "b", "e", "f"] { + l.saw(r); // c and d folded away, but this frame is not the one clicked on + } + assert_eq!(l.click(&["b"], &"d", Click::Range, &eq), vec!["b", "c", "d"]); + // the row clicked is not chosen any more (All Photos was shown since): a range does not + // start from it; it starts from what is chosen now, or the row is chosen alone + assert_eq!(l.click(&["f"], &"d", Click::Range, &eq), vec!["f", "e", "d"]); + assert_eq!(l.click(&[], &"c", Click::Range, &eq), vec!["c"]); + assert_eq!(l.click(&["c"], &"b", Click::Plain, &eq), vec!["b"]); + l.begin_frame(); + assert_eq!(l.rows(), ["a", "b", "e", "f"]); + assert_eq!(l.click(&["b"], &"e", Click::Range, &eq), vec!["b", "e"], "rows folded away are not taken"); + } +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ed9c45fb5d8..7287de19833 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -26,6 +26,7 @@ pub mod presets; pub mod profiles; pub mod right; pub mod second; +pub mod side_select; pub mod slideshow; pub mod strip; pub mod topbar; diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs new file mode 100644 index 00000000000..bca593f3682 --- /dev/null +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -0,0 +1,2653 @@ +//! Modal dialogs (new album, rename, create preset, choose settings to copy, export, about, shortcuts). + +use lightcraft_develop::{ControlSpec, Section, SettingsGroup, Track}; +use serde_json::json; + +use crate::LightcraftApp; +use crate::state::Dialog; +use crate::theme::Tokens; + +/// Rows the Rename dialog previews. +const RENAME_PREVIEW_ROWS: usize = 6; + +/// The Rename dialog's preview: its first rows (`None` while being planned) and how many files +/// are renamed. Which names are taken is checked on disk, which can block on a slow drive, so the +/// rows are planned on a worker thread, and only when the template, start number, photos or +/// catalog change — never once per frame. +pub(crate) fn rename_preview( + app: &mut LightcraftApp, + ctx: &egui::Context, + template: &str, + start: usize, +) -> (Option>, usize) { + use std::hash::{Hash, Hasher}; + type Rows = std::sync::Arc>>>; + let ids = app.session.selected(); + let photos = lightcraft_engine::rename::rename_photos(&app.session.catalog, &ids); + let total = photos.len(); + let mut h = std::collections::hash_map::DefaultHasher::new(); + (template, start, app.session.catalog.revision, &ids).hash(&mut h); + let key = h.finish(); + let id = egui::Id::unique("rename-preview-rows"); + let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id)) + && k == key + { + return (read(&rows), total); + } + let rows: Rows = Default::default(); + let first: Vec<_> = photos.into_iter().take(RENAME_PREVIEW_ROWS).collect(); + let (out, template, repaint) = (rows.clone(), template.to_string(), ctx.clone()); + let exists = app.session.media.availability.probe(); + let work = move || { + let plans = lightcraft_engine::rename::plan_rename_photos(&first, &template, start, &|f| exists(f)); + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(plans); + repaint.request_repaint(); + }; + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = std::thread::Builder::new().name("lc-rename-preview".into()).spawn(work) { + log::warn!("rename preview: {e}"); + } + #[cfg(target_arch = "wasm32")] + work(); + ctx.data_mut(|d| d.insert_temp(id, (key, rows.clone()))); + (read(&rows), total) +} + +/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever +/// its shape, with the watermark drawn on it as the file will have it at size `resize` (`None` = +/// full size). On a worker thread, once per photo, catalog change and size step, the cached +/// thumbnail comes first (at once, a little soft) and then a render at the preview's own pixel size +/// replaces it. The watermark is redrawn on a copy only when it, the output size or the picture +/// changes, which is quick at this size, so the preview follows the sliders. +fn watermark_preview( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + wm: &lightcraft_engine::export::Watermark, + resize: Option, +) { + use std::hash::{Hash, Hasher}; + // (pictures received so far: 1 the thumbnail, 2 the sharp render; the latest, or why none came) + type Base = std::sync::Arc>)>>; + type Shown = (u64, u8, lightcraft_engine::export::Watermark, usize, egui::TextureHandle); + let t = Tokens::get(ui.ctx()); + let Some(&id) = app.session.selected().first() else { return }; + let Some(photo) = app.session.catalog.photo(id).cloned() else { return }; + let (out_w, out_h) = lightcraft_engine::export::output_size(&photo, &lightcraft_engine::export::ExportOptions { resize, ..Default::default() }); + let export_short = out_w.min(out_h); + // pixels across the dialog, in steps so a scroll bar or a point of layout doesn't re-render + let step = 128.0; + let px = ((ui.available_width() * ui.ctx().pixels_per_point() / step).ceil() * step).clamp(step, 2048.0) as usize; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (id, app.session.catalog.revision, px).hash(&mut h); + let key = h.finish(); + let ctx = ui.ctx().clone(); + let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown")); + let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) { + Some((k, base)) if k == key => base, + _ => { + let base: Base = Default::default(); + // the thumbnail, then as wide as the dialog (a tall photo up to three times that high) + let jobs: Vec<_> = [app.session.thumb_job(id, 512), app.session.render_job(id, px, px * 3, false, true)].into_iter().flatten().collect(); + // the web build has no worker thread: a full render there would hold up the page + #[cfg(target_arch = "wasm32")] + let jobs: Vec<_> = jobs.into_iter().take(1).collect(); + if jobs.is_empty() { + *base.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (1, Some(Err("no such photo".into()))); + } else { + let (out, repaint) = (base.clone(), ctx.clone()); + let work = move || { + for job in jobs { + // (a panic in the render is its failure: `RenderJob::run`) + let r = job.run().rendered.map(|r| r.image); + let mut got = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // a failed sharp render keeps the thumbnail + if r.is_ok() || !matches!(got.1, Some(Ok(_))) { + *got = (got.0.saturating_add(1), Some(r)); + repaint.request_repaint(); + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = std::thread::Builder::new().name("lc-watermark-preview".into()).spawn(work) { + log::warn!("watermark preview: {e}"); + } + #[cfg(target_arch = "wasm32")] + work(); + } + ctx.data_mut(|d| d.insert_temp(base_id, (key, base.clone()))); + base + } + }; + let shown = ctx.data(|d| d.get_temp::(shown_id)); + let stage = base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0; + let tex = match shown { + Some((k, g, w, s, tex)) if k == key && g == stage && &w == wm && s == export_short => tex, + _ => { + let photo_px = match &base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 { + Some(Ok(img)) => Ok(img.clone()), + Some(Err(e)) => Err(Some(e.clone())), + None => Err(None), + }; + let mut img = match photo_px { + Ok(img) => img, + Err(e) => { + let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" }; + let r = ui + .horizontal(|ui| { + if e.is_none() { + crate::progress::spinner(ui, 12.0); + } + ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)) + }) + .inner; + if let Some(e) = e { + r.on_hover_text(e); + } + return; + } + }; + lightcraft_engine::export::draw_watermark_preview(&mut img, wm, export_short); + // shown through the monitor profile like every other preview + if let Some(d) = app.renderer.display() + && let Err(e) = d.profile.from_srgb(&mut img) + { + log::warn!("display profile: {e}"); + } + let color = std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &img.as_bytes())); + let tex = match shown { + Some((.., mut tex)) => { + tex.set(color, egui::TextureOptions::LINEAR); + tex + } + None => ctx.load_texture("export-wm-preview", color, egui::TextureOptions::LINEAR), + }; + ctx.data_mut(|d| d.insert_temp(shown_id, (key, stage, wm.clone(), export_short, tex.clone()))); + tex + } + }; + let size = tex.size_vec2(); + let scale = ui.available_width() / size.x.max(1.0); + let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner; + crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect); +} + +/// About dialog tabs: (widget id suffix, label). The credits come from `crate::credits`. +pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", "Contributors"), ("models", "Models")]; + +/// Help ▸ What's New (docs/whats-new.md). +pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md"); + +/// The import review and Settings keep window ids of their own, so the size each is given +/// doesn't carry over to the other dialogs. +fn window_id(dialog: &Dialog) -> egui::Id { + egui::Id::unique(match dialog { + Dialog::Import { .. } => "lightcraft-import-dialog", + Dialog::Print => "lightcraft-print-dialog", + Dialog::Settings { .. } => "lightcraft-settings-dialog", + _ => "lightcraft-dialog", + }) +} + +/// Block the underlying panels from the first frame, before the window establishes its modal +/// layer. Close background menus on entry; popups subsequently opened inside the dialog stay usable. +pub(crate) fn prepare(app: &LightcraftApp, ui: &mut egui::Ui) { + let Some(dialog) = &app.ui.dialog else { return }; + ui.disable(); + let layer = egui::LayerId::new(egui::Order::Middle, window_id(dialog)); + if ui.ctx().memory(|m| m.top_modal_layer()) != Some(layer) { + egui::Popup::close_all(ui.ctx()); + } +} + +/// Draw the open dialog. `blocked` is true when a quit prompt or settings notice was on screen at +/// the start of this frame: the dialog is still drawn (its state is preserved), but none of its raw +/// keyboard/backdrop handling may act. The caller freezes `blocked` for the whole frame so the +/// click or key that dismisses the prompt cannot also reach the dialog drawn after it. The +/// blocking library-problem/launch-list window gets the same raw-input treatment while it is +/// actually on screen over this dialog; ordinary dialogs without that window keep their normal +/// Escape and outside-click behaviour. +pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { + let Some(mut dlg) = app.ui.dialog.clone() else { return }; + let at_start = dlg.clone(); + let library_blocks = crate::panels::library_problem::blocks_dialog_input(app); + let raw_blocked = blocked || library_blocks; + // Esc with a popup open in the dialog (a dropdown, a date picker's calendar) closes the popup + // only: claimed before the dialog is drawn, since the popup is gone once it has handled the key + if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && egui::Popup::is_any_open(ctx) { + crate::widgets::take_escape(ctx); + } + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + // The backdrop is an area below the dialog window (a bare `Middle` layer painter would be + // painted after every area — i.e. over the dialog too). + egui::Area::new(egui::Id::unique("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| { + ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140)); + }); + let mut close = false; + let mut confirm = false; + // Return presses OK in a dialog without a text field of its own (Lightroom's default button); + // a widget that has the keyboard focus (a text field, a button or checkbox reached with Tab) + // takes Return itself. Consumed before the dialog is drawn, so nothing else sees it too. + if !raw_blocked + && return_confirms(&dlg) + && ctx.memory(|m| m.focused().is_none()) + && !egui::Popup::is_any_open(ctx) + && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) + { + confirm = true; + } + let title: String = match &dlg { + Dialog::TextPrompt { title, .. } => title.as_str(), + Dialog::NewAlbum { folder: true, .. } => "Create Folder", + Dialog::NewAlbum { .. } => "Create Album", + Dialog::RenameAlbum { .. } => "Rename Album", + Dialog::Rename { .. } => "Rename Photos", + Dialog::Import { .. } => "Import Photos", + Dialog::LightroomResult { .. } => "Lightroom Catalog Import", + Dialog::LabelNames { .. } => "Edit Color Label Names", + Dialog::CaptureTime { .. } => "Edit Capture Time", + Dialog::RenameKeyword { .. } => "Rename Keyword", + Dialog::RenamePerson { .. } => "Rename Person", + Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag", + Dialog::KeywordTag { .. } => "Edit Keyword Tag", + Dialog::DeleteKeyword { .. } => "Delete Keyword", + Dialog::MoveKeyword { .. } => "Merge Keywords", + Dialog::KeywordSet { .. } => "Edit Keyword Set", + Dialog::MergeKeywords { .. } => "Merge Keywords", + Dialog::NewSmartAlbum { .. } => "Create Smart Album", + Dialog::AllMetadata { .. } => "All Metadata", + Dialog::SystemInfo { .. } => "System Info", + Dialog::DenoiseModel { .. } => "AI Denoise Model", + Dialog::FaceModel { info, .. } if info["download"].is_string() => "Download Face Model", + Dialog::FaceModel { .. } => "Add Face Model", + Dialog::WhatsNew => "What's New", + Dialog::Cull { .. } => "Assisted Culling", + Dialog::SmartRules { id: None, .. } => "New Smart Album", + Dialog::SmartRules { .. } => "Edit Smart Album", + Dialog::AutoStack { .. } => "Auto-Stack by Capture Time", + Dialog::CreatePreset { .. } => "Create Preset", + Dialog::CopySettings { .. } => "Choose Edit Settings to Copy", + Dialog::PasteSettings { .. } => "Paste Selected Settings", + Dialog::Export { .. } => "Export", + Dialog::ContactSheet { .. } => "Contact Sheet PDF", + Dialog::SlideshowExport { .. } => "Export Slideshow", + Dialog::Print => "Print", + Dialog::Merge { opts } => opts.title(), + Dialog::Settings { .. } => "Settings", + Dialog::ConfirmDelete { .. } => "Delete Photos", + Dialog::MovePhotos { .. } => "Move Photos", + Dialog::LightroomCatalog { .. } => "Lightroom Classic Catalog", + Dialog::LightroomDestination { .. } => "Import Lightroom Catalog", + Dialog::SaveEffect { .. } => "New Effect Preset", + Dialog::ManageEffects { .. } => "Manage Effect Presets", + Dialog::DeleteEffects { names } if names.len() == 1 => "Delete Effect Preset", + Dialog::DeleteEffects { .. } => "Delete Effect Presets", + Dialog::RemoveFolder { disk: true, .. } => "Remove Disk from Library", + Dialog::RemoveFolder { .. } => "Remove Folder from Library", + Dialog::SynchronizeFolder { .. } => "Synchronize Folder", + // (nothing to download from in this build: the dialog explains the manual install) + Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model", + Dialog::SamModel { .. } => "Download the SAM 3 Model?", + Dialog::About => "About LightCraft", + Dialog::Shortcuts => "Keyboard Shortcuts", + Dialog::ViewOptions => "View Options", + } + .to_string(); + let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(16, 12)); + // The import review can be resized (its photo grid takes the room); it keeps a window id of its + // own so the size it is given doesn't carry over to the other dialogs. Its content scrolls + // rather than growing the window when the options below the grid get taller (e.g. Copy). + let import = matches!(dlg, Dialog::Import { .. }); + // The Print dialog sizes itself to the window and scrolls its settings column on its own. + let print = matches!(dlg, Dialog::Print); + let window_id = window_id(&dlg); + // Every other dialog fits the window (#781): its options scroll when they don't, and the title + // bar and the button row stay outside the scroll area. The room they take is measured on the + // previous frame (a guess on the first one). + let chrome_id = window_id.with("chrome"); + let chrome = ctx.data(|d| d.get_temp::(chrome_id)).unwrap_or(DIALOG_CHROME_GUESS); + // Settings keeps its top edge, and the widest it has been, while tabs of different sizes are shown, so its tab + // row stays where it is (centred like the others, the row jumped with each tab's height) + let settings = matches!(dlg, Dialog::Settings { .. }); + let top = (screen.height() * 0.08).clamp(DIALOG_SCREEN_MARGIN, 96.0); + let body_max = + if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome } + .max(DIALOG_MIN_BODY); + let widest_id = window_id.with("widest"); + let widest = if settings { ctx.data(|d| d.get_temp::(widest_id)).unwrap_or(0.0).min(screen.width() * 0.9) } else { 0.0 }; + let mut content_w = 0.0f32; + let mut body_h = None; + // before the window: drawing it closes a dropdown the click lands outside of + let popup_was_open = egui::Popup::is_any_open(ctx); + let shown = egui::Window::new(crate::i18n::tr(&title)).id(window_id) + .collapsible(false) + .resizable(import) + .vscroll(import) + .resize(|r| if import { r.default_height(crate::import::DIALOG_SIZE[1]) } else { r }) + .frame(frame) + .anchor(if settings { egui::Align2::CENTER_TOP } else { egui::Align2::CENTER_CENTER }, [0.0, if settings { top } else { 0.0 }]) + .min_width(widest) + .default_width(match dlg { + Dialog::Import { .. } => crate::import::DIALOG_SIZE[0], + Dialog::SmartRules { .. } => 680.0, + Dialog::AllMetadata { .. } => 620.0, + Dialog::Print => 1100.0, + Dialog::FaceModel { .. } => 460.0, + Dialog::LightroomCatalog { .. } => 440.0, + Dialog::LightroomDestination { .. } => 480.0, + Dialog::ManageEffects { .. } => 560.0, + _ => 380.0, + }) + .show(ctx, |ui| { + // Disabled, not skipped: the dialog keeps its layout and state, but a raw event in the + // first prompt frame cannot toggle a checkbox or press a button underneath it. The + // blocking library window gets the same treatment: it owns input while it is on screen, + // so the dialog behind it must not take focus or accept typed text either. + if raw_blocked { + ui.disable(); + } + ui.spacing_mut().item_spacing.y = 8.0; + body_h = dialog_body(ui, (!import && !print).then_some(title.as_str()), body_max, |ui| match &mut dlg { + Dialog::AutoStack { gap } => { + ui.label(egui::RichText::new(crate::i18n::tr("Stack photos taken within this time of each other:")).color(t.text_label)); + let r = ui.add( + egui::Slider::new(gap, 0.0..=86400.0) + .logarithmic(true) + .smallest_positive(1.0) + .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) + .custom_parser(crate::panels::dialogs::parse_gap), + ); + crate::widgets::named(r, crate::i18n::tr("Stack photos taken within this time of each other:")); + let preview = app.session.execute("stack.auto", &json!({"gap": *gap, "preview": true})).unwrap_or_default(); + let scope = if app.session.selection.ids.len() > 1 { "the selected photos" } else { "the photos in view" }; + ui.label( + egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), + ); + } + Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + let n = app.session.selection.ids.len(); + let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; + ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); + ui.add_space(6.0); + let r = ui.add(egui::Slider::new(reject_below, 0.0..=80.0).text(crate::i18n::tr("Reject below focus")).step_by(1.0)); + crate::widgets::register(ui, "field:cullReject", r.rect); + ui.label(egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 { "Blurry photos below the score are flagged as rejects." } else { "0: nothing is rejected." })).color(t.text_dim)); + let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); + crate::widgets::register(ui, "check:cullPick", r.rect); + ui.add_space(6.0); + // the sliders drag over the usual range; their value fields take whatever + // `photo.analyze` accepts (a gap of 0 s to a day, a similarity of 0 to 1) + let r = ui.add( + egui::Slider::new(burst_gap, 1.0..=600.0) + .logarithmic(true) + .smallest_positive(1.0) + .clamping(egui::SliderClamping::Never) + .text(crate::i18n::tr("Burst: shots at most this far apart")) + .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) + .custom_parser(crate::panels::dialogs::parse_gap), + ); + crate::widgets::register(ui, "field:cullGap", r.rect); + let r = ui.add( + egui::Slider::new(similarity, 0.70..=0.99) + .clamping(egui::SliderClamping::Never) + .text(crate::i18n::tr("Burst: how alike (loose … strict)")) + // a typed 0.995 is kept (whole hundredths would round it to 1.00) + .step_by(0.001) + .min_decimals(2) + .max_decimals(3), + ); + crate::widgets::register(ui, "field:cullSimilar", r.rect); + clamp_cull_burst(burst_gap, similarity); + ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); + } + Dialog::WhatsNew => { + egui::ScrollArea::vertical().max_height(list_height(ui, 460.0)).auto_shrink([false, true]).show(ui, |ui| { + for line in WHATS_NEW.lines() { + let l = line.trim_end(); + if let Some(h) = l.strip_prefix("### ") { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + } else if let Some(h) = l.strip_prefix("## ") { + ui.add_space(8.0); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); + } else if l.starts_with("# ") || l.is_empty() { + } else if let Some(b) = l.strip_prefix("- ") { + ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label)); + } else { + ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label)); + } + } + }); + } + Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::model_dialog(app, ui, &t, info, accepted), + Dialog::FaceModel { info, accepted, .. } => crate::panels::faces::model_dialog(app, ui, &t, info, accepted), + Dialog::LightroomResult { summary, library, details, .. } => { + ui.label(summary.as_str()); + ui.add_space(8.0); + if let Some(library) = library { + ui.label(crate::i18n::tr("Destination library")); + ui.add(egui::Label::new(library.as_str()).wrap().selectable(true)); + ui.label(crate::i18n::tr("Lightroom catalogs import into the open library; no separate catalog folder is created.")); + } else { + ui.label(crate::i18n::tr("These photos are only in memory. Open a library on disk and import the catalog again to save them.")); + } + for detail in details.iter() { + ui.add(egui::Label::new(detail).wrap().selectable(true)); + } + } + Dialog::SystemInfo { rows } => { + egui::Grid::new("sysinfo").num_columns(2).spacing([16.0, 4.0]).striped(true).show(ui, |ui| { + for (k, v) in rows.iter() { + ui.label(egui::RichText::new(crate::i18n::tr(k)).color(t.text_dim)); + ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); + ui.end_row(); + } + }); + if ui.button(crate::i18n::tr("Copy to Clipboard")).clicked() { + let text: String = rows.iter().map(|(k, v)| format!("{k}: {v}\n")).collect(); + ui.ctx().copy_text(text); + } + } + Dialog::AllMetadata { title, rows, search } => { + ui.label(egui::RichText::new(title.as_str()).color(t.text_label)); + let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(search).hint_text(crate::i18n::tr("Filter fields")).desired_width(f32::INFINITY)), crate::i18n::tr("Filter fields")); + crate::widgets::register(ui, "field:metadataSearch", r.rect); + let q = search.trim().to_lowercase(); + let keep = |n: &str, v: &str| q.is_empty() || n.to_lowercase().contains(&q) || v.to_lowercase().contains(&q); + let mut groups: Vec<(String, Vec<(String, String)>)> = Vec::new(); + for row in rows["exif"].as_array().into_iter().flatten() { + let (g, n, v) = (row["group"].as_str().unwrap_or(""), row["name"].as_str().unwrap_or(""), row["value"].as_str().unwrap_or("")); + if !keep(n, v) { + continue; + } + match groups.iter_mut().find(|(x, _)| x == g) { + Some((_, list)) => list.push((n.into(), v.into())), + None => groups.push((g.into(), vec![(n.into(), v.into())])), + } + } + let xmp: Vec<(String, String)> = rows["xmp"] + .as_array() + .into_iter() + .flatten() + .map(|r| (r["name"].as_str().unwrap_or("").to_string(), r["value"].as_str().unwrap_or("").to_string())) + .filter(|(n, v)| keep(n, v)) + .collect(); + if !xmp.is_empty() { + groups.push(("XMP".into(), xmp)); + } + egui::ScrollArea::vertical().max_height(list_height(ui, 440.0)).auto_shrink([false, true]).show(ui, |ui| { + if groups.is_empty() { + ui.label(egui::RichText::new(crate::i18n::tr(rows["note"].as_str().unwrap_or("No metadata found"))).color(t.text_dim)); + } + for (g, list) in &groups { + ui.add_space(6.0); + ui.label(egui::RichText::new(g).font(t.semibold(12.5)).color(t.text)); + egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { + for (n, v) in list { + ui.label(egui::RichText::new(n).color(t.text_dim)); + ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); + ui.end_row(); + } + }); + } + }); + } + Dialog::SmartRules { id, name, rules, .. } => { + let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name")); + crate::widgets::register(ui, "field:smartName", r.rect); + ui.add_space(6.0); + // the folder an album made from a folder view carries is not in the editor, but it counts + let folder = id.and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))).and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone())); + // problems, count and albums: cached until the catalog or the rules change (not per frame) + let now = (app.session.clock)(); + let view = app.caches.rules_view(&app.session.catalog, rules, *id, folder, &now); + let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; + egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { + crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); + }); + let n = view.count; + ui.add_space(4.0); + if view.problems.is_empty() { + ui.label( + egui::RichText::new(crate::i18n::tr_format!("{n} photo{} match · updates automatically as photos change", if n == 1 { "" } else { "s" }, n = n)) + .color(t.text_dim), + ); + } else { + ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.caution)); + } + } + Dialog::NewSmartAlbum { name, .. } => { + if dialog_field(ui, "field:smartAlbumName", name, "Name") { + confirm = true; + } + let rules = app.session.view_rules(); + // counted when the library or the rules change (or, for "in the last…" rules, the minute), not every frame + let now = (app.session.clock)(); + let minute = if rules.depends_on_now() { now.get(..16).unwrap_or(&now) } else { "" }; + let n = app.caches.dialog_count(&app.session.catalog, ("smartAlbum", format!("{rules:?}"), minute), || { + lightcraft_catalog::rules::set_now(Some(now.clone())); + app.session.catalog.query(&rules, &Default::default()).len() + }); + ui.label(egui::RichText::new(crate::i18n::tr_format!("Matches: {}", crate::i18n::filter_label(&rules, &app.session.catalog))).color(t.text_label)); + ui.label( + egui::RichText::new(crate::i18n::tr_format!("{n} photo{} now · updates automatically as photos change", if n == 1 { "" } else { "s" }, n = n)) + .color(t.text_dim), + ); + } + Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => { + let n = app.session.selected().len(); + field(ui, "Change", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (i, (label, m)) in [("Set date & time", "set"), ("Shift by", "shift"), ("Time zone", "zone")].iter().enumerate() { + if crate::widgets::text_button(ui, &format!("captureMode-{i}"), label, mode == m).clicked() { + *mode = m.to_string(); + } + } + }); + let params = match mode.as_str() { + "set" => { + field(ui, "New time", |ui| { + let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00").desired_width(f32::INFINITY)); + crate::widgets::register(ui, "field:captureTime", r.rect); + }); + json!({"time": time}) + } + "shift" => { + field(ui, "Shift", |ui| { + ui.add(egui::DragValue::new(days).suffix(" d")); + ui.add(egui::DragValue::new(hours).suffix(" h")); + ui.add(egui::DragValue::new(minutes).suffix(" min")); + }); + json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}) + } + _ => { + field(ui, "Hours", |ui| ui.add(egui::DragValue::new(zone).range(-26.0..=26.0).speed(0.25).fixed_decimals(2))); + json!({"hours": zone}) + } + }; + // preview on the active photo (the others move by the same amount) + let active = app.session.active().and_then(|id| app.session.catalog.photo(id)).map(|p| (p.file_name.clone(), p.date().to_string())); + if let Some((name, cur)) = active { + let delta = match mode.as_str() { + "set" => lightcraft_catalog::dates::normalize_iso(time) + .and_then(|t| Some(lightcraft_catalog::dates::iso_seconds(&t)? - lightcraft_catalog::dates::iso_seconds(&cur)?)), + "shift" => params["shift"].as_i64(), + _ => Some((*zone as f64 * 3600.0).round() as i64), + }; + // the photo's own time is the problem (a Lightroom catalog's capture time + // is copied verbatim), not what was typed + let unreadable = lightcraft_catalog::dates::shift_iso(&cur, 0).is_none(); + let after = match (mode.as_str(), unreadable && n == 1) { + // alone, it simply gets the time typed (photo.setCaptureTime repairs it) + ("set", true) => lightcraft_catalog::dates::normalize_iso(time), + _ => delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)), + }; + ui.label( + egui::RichText::new(match after { + Some(a) => format!("{name}: {} → {}", cur.replace('T', " "), a.replace('T', " ")), + None if unreadable && !(mode == "set" && n == 1) => crate::i18n::tr("The active photo's capture time can't be read").to_string(), + None => "Enter a date as YYYY-MM-DD HH:MM:SS".into(), + }) + .color(t.text_label), + ); + } + if n > 1 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("All {n} selected photos move by the same amount.", n = n)).color(t.text_dim)); + } + } + Dialog::LabelNames { names, save_as } => { + names.resize(5, String::new()); + // start from a set + let sets = lightcraft_engine::cmd::manage::label_sets_json(&app.session); + field(ui, "Set", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for set in sets["sets"].as_array().into_iter().flatten() { + let name = set["name"].as_str().unwrap_or_default(); + if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false).clicked() { + *names = set["names"].as_array().into_iter().flatten().map(|n| n.as_str().unwrap_or_default().to_string()).collect(); + } + } + }); + for (i, l) in lightcraft_catalog::ColorLabel::ALL.iter().enumerate() { + let colour = format!("{l:?}"); + field(ui, &colour, |ui| { + let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); + ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); + let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut names[i]).hint_text(colour.as_str()).desired_width(f32::INFINITY)), crate::i18n::tr(&colour)); + crate::widgets::register(ui, format!("field:labelName-{}", colour.to_lowercase()), te.rect); + }); + } + field(ui, "Save as set", |ui| { + let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(save_as).hint_text(crate::i18n::tr("Optional name")).desired_width(f32::INFINITY)), crate::i18n::tr("Save as set")); + crate::widgets::register(ui, "field:labelSetName", te.rect); + }); + ui.label( + egui::RichText::new(crate::i18n::tr("Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.")) + .color(t.text_dim), + ); + } + Dialog::Rename { template, start } => { + let n = app.session.selected().len(); + ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); + let template_id = egui::Id::unique("rename-template"); + let tags_open = field(ui, "Template", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let w = crate::import::tag_field_width(ui); + let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(template).id(template_id).hint_text("{name}").desired_width(w)), crate::i18n::tr("Template")); + crate::widgets::register(ui, "field:renameTemplate", r.rect); + crate::import::tag_toggle(ui, "renameTemplate") + }); + if tags_open { + crate::import::tag_help(ui, "renameTemplate", template, template_id); + } + crate::import::unknown_tags_warning(ui, template); + field(ui, "Presets", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (i, (label, tpl)) in + [("Name", "{name}"), ("Date–Name", "{date}_{name}"), ("Title–Seq", "{title}-{seq:3}"), ("Custom–Seq", "Photo-{seq:3}")].iter().enumerate() + { + if crate::widgets::text_button(ui, &format!("renamePreset-{i}"), label, template == tpl).clicked() { + *template = tpl.to_string(); + } + } + }); + field(ui, "Start at", |ui| ui.add(egui::DragValue::new(start).range(0..=999_999))); + ui.label( + egui::RichText::new(crate::i18n::tr("Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…")) + .color(t.text_dim), + ); + let (preview, total) = rename_preview(app, ui.ctx(), template, *start as usize); + match &preview { + Some(rows) => { + egui::Grid::new("rename-preview").num_columns(3).spacing([8.0, 2.0]).show(ui, |ui| { + for pl in rows { + ui.label(egui::RichText::new(&pl.from).color(t.text_dim)); + let (arrow, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); + crate::icons::paint(ui.painter(), arrow, crate::icons::Icon::ChevronRight, t.text_dim); + ui.label(egui::RichText::new(&pl.to).color(t.text)); + ui.end_row(); + } + }); + } + None => { + ui.horizontal(|ui| { + crate::progress::spinner(ui, 12.0); + ui.label(egui::RichText::new(crate::i18n::tr("Checking names…")).color(t.text_dim)); + }); + } + } + let more = total.saturating_sub(RENAME_PREVIEW_ROWS); + if more > 0 { + ui.label(egui::RichText::new(crate::i18n::tr_format!("… and {more} more", more = more)).color(t.text_dim)); + } + } + Dialog::RenamePerson { from, to, merge } => { + let submitted = dialog_field(ui, "field:personName", to, "Name"); + let plan = person_rename_plan(&app.session.catalog, from, to); + if !plan.needs_merge { + *merge = false; + } + if submitted && plan.block.is_none() && (!plan.needs_merge || *merge) { + confirm = true; + } + if let Some(why) = plan.block { + ui.label(egui::RichText::new(crate::i18n::tr(why)).color(t.caution)); + } else { + ui.label( + egui::RichText::new(crate::i18n::tr_format!( + "Renames {n} face{} across the library. The files are not changed.", + if plan.faces == 1 { "" } else { "s" }, + n = plan.faces + )) + .color(t.text_dim), + ); + } + if plan.needs_merge { + ui.label( + egui::RichText::new(crate::i18n::tr_format!("“{to}” is already a person. Combining them makes one person; Undo separates them again.", to = to.trim())) + .color(t.caution), + ); + let r = ui.checkbox(merge, crate::i18n::tr("Combine with the existing person")); + crate::widgets::register(ui, "check:personMerge", r.rect); + } + } + Dialog::RenameKeyword { from, to } => { + let n = app.caches.dialog_count(&app.session.catalog, ("renameKeyword", from.as_str()), || { + app.session.catalog.photos().filter(|p| p.meta.keywords.iter().any(|k| lightcraft_catalog::keywords::is_under(k, from))).count() + }); + if dialog_field(ui, "field:keywordName", to, "New name") { + confirm = true; + } + ui.label( + egui::RichText::new(crate::i18n::tr_format!("Renames “{from}” on {n} photo{} (keywords below it too). Use | for levels, e.g. Travel|Italy. An existing name merges the two.", + if n == 1 { "" } else { "s" }, from = from, n = n)) + .color(t.text_dim), + ); + } + Dialog::MergeKeywords { from, into } => { + ui.label(egui::RichText::new(crate::i18n::tr_format!("Replace {} with:", from.iter().map(|f| format!("“{f}”")).collect::>().join(", "))).color(t.text_label)); + if dialog_field(ui, "field:keywordInto", into, "Keyword") { + confirm = true; + } + let options: Vec = app + .caches + .suggestions(&app.session.catalog, from, into, 12) + .iter() + .filter(|k| !from.iter().any(|f| lightcraft_catalog::keywords::is_under(k, f))) + .cloned() + .collect(); + ui.horizontal_wrapped(|ui| { + for k in options { + if ui.add(egui::Button::new(egui::RichText::new(&k).color(t.text_label)).corner_radius(10.0)).clicked() { + *into = k; + } + } + }); + } + Dialog::TextPrompt { value, hint, .. } => { + if dialog_field(ui, "field:prompt", value, hint) { + confirm = true; + } + } + Dialog::NewAlbum { name, folder, include_selected, .. } => { + if dialog_field(ui, "field:albumName", name, "Name") { + confirm = true; + } + // as in Lightroom, the option is only there when something is selected + if !*folder && !app.session.selected().is_empty() { + ui.add_space(6.0); + let r = ui.checkbox(include_selected, crate::i18n::tr("Include selected photos")); + crate::widgets::register(ui, "check:albumIncludeSelected", r.rect); + } + } + Dialog::RenameAlbum { name, .. } => { + if dialog_field(ui, "field:albumName", name, "Name") { + confirm = true; + } + } + Dialog::CreatePreset { name, group, groups } => { + crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Preset name")).desired_width(f32::INFINITY)), crate::i18n::tr("Preset name")); + crate::widgets::named(ui.add(egui::TextEdit::singleline(group).hint_text(crate::i18n::tr("Group")).desired_width(f32::INFINITY)), crate::i18n::tr("Group")); + ui.label(egui::RichText::new(crate::i18n::tr("Settings to include")).color(t.text_dim)); + group_checklist(ui, "presetInclude", groups); + } + Dialog::CopySettings { groups } => group_checklist(ui, "copyGroup", groups), + Dialog::PasteSettings { groups } => { + let n = app.session.selected().len(); + ui.label( + egui::RichText::new(crate::i18n::tr_format!("Paste into {n} photo{} — only settings that were copied are pasted", if n == 1 { "" } else { "s" }, n = n)) + .color(t.text_dim), + ); + group_checklist(ui, "pasteGroup", groups); + } + Dialog::SlideshowExport { settings } => slideshow_export_body(app, ui, settings), + Dialog::ContactSheet { options } => { + options.columns = options.columns.clamp(1, 8); + options.rows = options.rows.clamp(1, 10); + let n = app.session.selected().len(); + ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows))); + field(ui, "Paper", |ui| { + let c = crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { + ui.selectable_value(&mut options.paper, "a4".into(), "A4"); + ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); + }); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper")); + }); + ui.checkbox(&mut options.landscape, crate::i18n::tr("Landscape")); + field(ui, "Columns", |ui| { ui.add(egui::DragValue::new(&mut options.columns).range(1..=8)); }); + field(ui, "Rows", |ui| { ui.add(egui::DragValue::new(&mut options.rows).range(1..=10)); }); + ui.checkbox(&mut options.captions, crate::i18n::tr("Filename captions")); + ui.label(crate::i18n::tr("150 dpi · sRGB · current edits · fit without cropping")); + ui.label(crate::i18n::tr("Choose a PDF destination after confirming. Print the PDF from your viewer.")); + } + Dialog::Export { opts, full_size, resize, preset_name, limit_kb, dir } => { + use lightcraft_engine::export::{ExportFormat as F, MetadataPolicy as M, SharpenAmount as A, SharpenFor as S}; + let n = app.session.selection.ids.len().max(1); + ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); + // Preset: load a built-in or saved set of options into the dialog + field(ui, "Preset", |ui| { + let mut chosen = None; + let c = crate::widgets::combo_box("exportPreset").width(220.0).selected_text(crate::i18n::tr("Choose…")).show_ui(ui, |ui| { + let mut builtin = true; + for (p, b) in app.session.all_export_presets() { + if builtin && !b { + ui.separator(); + } + builtin = b; + if ui.selectable_label(false, crate::i18n::builtin_label(&p.name, b)).clicked() { + chosen = Some(p.name); + } + } + }); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Preset")); + crate::widgets::register(ui, "combo:exportPreset", c.response.rect); + if let Some(name) = chosen + && let Ok(params) = app.session.export_params(&json!({"preset": name})) + { + let o = lightcraft_engine::export::ExportOptions::from_json(¶ms); + *full_size = o.resize.is_none(); + *resize = o.resize.unwrap_or_default(); + *limit_kb = o.limit_kb.unwrap_or(0); + *opts = o; + } + }); + ui.add_space(4.0); + let before = opts.format; + // "Rendered DNG" is a DNG option (below), not a format of its own in this list + let mut shown = if opts.format == F::RenderedDng { F::Dng } else { opts.format }; + choices( + ui, + "Format", + "exportFormat", + &[(F::Jpeg, "JPEG"), (F::Png, "PNG"), (F::Tiff, "TIFF"), (F::Psd, "PSD"), (F::Webp, "WebP"), (F::Avif, "AVIF"), (F::Jxl, "JPEG XL"), (F::Dng, "DNG"), (F::Original, "Original files")], + &mut shown, + ); + if shown != opts.format && !(shown == F::Dng && opts.format == F::RenderedDng) { + opts.format = shown; + } + if matches!(opts.format, F::Dng | F::RenderedDng) { + choices(ui, "DNG of", "exportDngKind", &[(F::Dng, "Raw data"), (F::RenderedDng, "Rendered photo")], &mut opts.format); + } + if !opts.format.is_rendered() { + let note = if opts.format == F::Dng { + "Raw photos as DNG, with the edits embedded. Size, color and output options don't apply." + } else { + "The original files, unchanged, each with an XMP sidecar holding its edits." + }; + ui.label(egui::RichText::new(note).color(t.text_dim)); + } + if opts.format != before { + // each format starts at its own default depth (TIFF 16-bit, others 8-bit) + opts.bit_depth = None; + } + let rendered = opts.format.is_rendered(); + let depths = lightcraft_engine::export::ExportOptions::bit_depths(opts.format); + if rendered && depths.len() > 1 { + let mut bd = opts.bit_depth.filter(|b| depths.iter().any(|d| d.0 == *b)).unwrap_or(depths[0].0); + choices(ui, "Bit depth", "exportBitDepth", depths, &mut bd); + opts.bit_depth = Some(bd); + } + if matches!(opts.format, F::Jpeg | F::Tiff | F::Avif | F::Png | F::Jxl) { + let tip = crate::i18n::tr("Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float"); + ui.checkbox(&mut opts.hdr, crate::i18n::tr("HDR output")).on_hover_text(tip); + if opts.hdr && !opts.hdr_output() { + ui.label(egui::RichText::new(crate::i18n::tr("HDR TIFF needs 32-bit float.")).color(t.text_dim)); + } + if opts.hdr && opts.format == F::Avif { + use lightcraft_engine::export::HdrCurve as H; + choices(ui, "HDR curve", "exportHdrCurve", &[(H::Pq, "PQ"), (H::Hlg, "HLG")], &mut opts.hdr_transfer); + } + } + if !rendered { + } else if opts.format == F::Avif && opts.hdr { + let label = if opts.hdr_transfer == lightcraft_engine::export::HdrCurve::Hlg { + crate::i18n::tr("Color space: Rec. 2020 HLG (HDR AVIF)") + } else { + crate::i18n::tr("Color space: Rec. 2020 PQ (HDR AVIF)") + }; + ui.label(egui::RichText::new(label).color(t.text_dim)); + } else if opts.format == F::Png && opts.hdr { + ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ, 16-bit (HDR PNG)")).color(t.text_dim)) + .on_hover_text(crate::i18n::tr("Viewers that don't read the PNG cICP chunk show PQ values as sRGB: flat and washed out. For a picture that looks right everywhere, use JPEG (gain map).")); + } else if opts.format == F::Jxl && opts.hdr { + ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ (HDR JPEG XL)")).color(t.text_dim)); + } else if opts.format == F::Avif { + ui.label(egui::RichText::new(crate::i18n::tr("Color space: sRGB (AVIF)")).color(t.text_dim)); + } else { + use lightcraft_engine::export::OutputSpace as C; + choices( + ui, + "Color space", + "exportColorSpace", + &[ + (C::Srgb, "sRGB"), + (C::DisplayP3, "P3"), + (C::AdobeRgb, "Adobe RGB"), + (C::ProPhoto, "ProPhoto"), + (C::Rec2020, "Rec.2020"), + ], + &mut opts.color_space, + ); + if opts.effective_space() != opts.color_space { + let note = "Lossy JPEG XL writes Adobe RGB and ProPhoto as Rec. 2020; choose Lossless to keep them."; + ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)); + } + } + if opts.format == F::Jxl { + let tip = "Mathematically lossless: every pixel is kept exactly (larger files)"; + ui.checkbox(&mut opts.jxl_lossless, crate::i18n::tr("Lossless")).on_hover_text(crate::i18n::tr(tip)); + } + if matches!(opts.format, F::Jpeg | F::Avif) || (opts.format == F::Jxl && !opts.jxl_lossless) { + let mut q = opts.quality as f64; + if num(ui, &QUALITY, &mut q) { + opts.quality = q as u8; + } + } + if opts.format == F::Jxl { + use lightcraft_engine::export::JxlEffort as E; + choices(ui, "Effort", "exportJxlEffort", &[(E::Fast, "Fast"), (E::Normal, "Normal")], &mut opts.jxl_effort); + let tip = "Shows a coarse version first and refines it as the file loads"; + ui.checkbox(&mut opts.jxl_progressive, crate::i18n::tr("Progressive")).on_hover_text(crate::i18n::tr(tip)); + } + if opts.format == F::Jpeg { + let mut k = *limit_kb as f64; + if num(ui, &LIMIT_KB, &mut k) { + *limit_kb = k as u32; + } + } + if rendered { + export_size(ui, full_size, resize, &mut opts.ppi); + } + if rendered { + choices( + ui, + "Sharpen", + "exportSharpen", + &[(S::None, "None"), (S::Screen, "Screen"), (S::Matte, "Matte"), (S::Glossy, "Glossy")], + &mut opts.sharpen, + ); + if opts.sharpen != S::None { + choices( + ui, + "Amount", + "exportSharpenAmount", + &[(A::Low, "Low"), (A::Standard, "Standard"), (A::High, "High")], + &mut opts.sharpen_amount, + ); + } + } + if rendered { + choices( + ui, + "Metadata", + "exportMetadata", + &[(M::All, "All"), (M::AllExceptCamera, "No camera"), (M::Copyright, "Copyright"), (M::None, "None")], + &mut opts.metadata, + ); + if !matches!(opts.metadata, M::None | M::Copyright) { + ui.checkbox(&mut opts.remove_location, crate::i18n::tr("Remove location info")); + } + let mut wm_on = opts.watermark.is_some(); + if ui.checkbox(&mut wm_on, crate::i18n::tr("Watermark")).changed() { + opts.watermark = wm_on.then(|| lightcraft_engine::export::Watermark { text: "© ".into(), ..Default::default() }); + } + let wm_shown = opts.watermark.clone(); + if let Some(wm) = &wm_shown { + watermark_preview(app, ui, wm, (!*full_size).then_some(*resize)); + } + if let Some(wm) = &mut opts.watermark { + // text, or a graphic (a logo with transparency) + let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::(egui::Id::unique("wm-graphic"))).unwrap_or(false); + let before = graphic; + choices(ui, "Style", "exportWmStyle", &[(false, "Text"), (true, "Graphic")], &mut graphic); + if graphic != before { + ui.data_mut(|d| d.insert_temp(egui::Id::unique("wm-graphic"), graphic)); + if !graphic { + wm.image.clear(); + } + } + if graphic { + field(ui, "Graphic", |ui| { + trailing_button_row(ui, |ui| { + if app.services.pick_files.is_some() + && crate::widgets::text_button(ui, "exportWmChoose", crate::i18n::tr("Choose…"), false).clicked() + && let Some(f) = app.services.pick_files.as_mut().and_then(|pick| pick().into_iter().next()) + { + wm.image = f; + } + crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut wm.image).hint_text("logo.png").desired_width(ui.available_width())), crate::i18n::tr("Image")); + }); + }); + let mut width = wm.image_width as f64 * 100.0; + if num(ui, &WM_IMAGE_WIDTH, &mut width) { + wm.image_width = (width / 100.0) as f32; + } + } else { + choices(ui, app.ui.language.tr("Text direction"), "exportWmOrientation", &[(false, app.ui.language.tr("Horizontal text")), (true, app.ui.language.tr("Vertical text"))], &mut wm.vertical); + field(ui, "Text", |ui| { + crate::widgets::named(ui.add(egui::TextEdit::multiline(&mut wm.text).desired_rows(2).hint_text(crate::i18n::tr("© Your Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Text")) + }); + } + choices( + ui, + "Position", + "exportWmAnchor", + &WM_POSITIONS, + &mut wm.anchor, + ); + choices(ui, "Rotate", "exportWmRotation", &[(0u16, "0°"), (90, "90°"), (180, "180°"), (270, "270°")], &mut wm.rotation); + let mut size = wm.size as f64 * 100.0; + if !graphic && num(ui, &WM_SIZE, &mut size) { + wm.size = (size / 100.0) as f32; + } + let mut op = wm.opacity as f64 * 100.0; + if num(ui, &WM_OPACITY, &mut op) { + wm.opacity = (op / 100.0) as f32; + } + // like Lightroom Classic: a margin from the side edges and one from the top and bottom + // edges, each unused (greyed) when the position is centred along that axis + use lightcraft_engine::export::Anchor as P; + let across = !matches!(wm.anchor, P::Top | P::Center | P::Bottom); + if let Some(v) = crate::widgets::slider(ui, &WM_INSET_X, wm.inset_x as f64 * 100.0, across, None).value { + wm.inset_x = (v / 100.0) as f32; + } + let down = !matches!(wm.anchor, P::Left | P::Center | P::Right); + if let Some(v) = crate::widgets::slider(ui, &WM_INSET_Y, wm.inset_y as f64 * 100.0, down, None).value { + wm.inset_y = (v / 100.0) as f32; + } + if !graphic { + ui.checkbox(&mut wm.shadow, crate::i18n::tr("Shadow")); + } + } + if opts.watermark != wm_shown { + // the preview above was drawn with the old settings + ui.ctx().request_repaint(); + } + } + ui.add_space(4.0); + if opts.format == F::Tiff { + use lightcraft_engine::export::TiffCompression as Z; + choices(ui, "Compression", "exportTiffCompression", &[(Z::None, "None"), (Z::Lzw, "LZW"), (Z::Deflate, "ZIP")], &mut opts.tiff_compression); + } + if opts.format == F::Dng { + use lightcraft_engine::export::DngCompression as Z; + choices(ui, "Compression", "exportDngCompression", &[(Z::Lossless, "Lossless"), (Z::Deflate, "ZIP"), (Z::Uncompressed, "None"), (Z::Lossy, "Lossy")], &mut opts.dng_compression); + } + let naming_id = egui::Id::unique("export-naming"); + let tags_open = field(ui, "File name", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let w = crate::import::tag_field_width(ui); + crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.naming).id(naming_id).hint_text("{name}-{seq} · {date} · {title} · {folder}").desired_width(w)), crate::i18n::tr("File name")); + crate::import::tag_toggle(ui, "exportNaming") + }); + if tags_open { + crate::import::tag_help(ui, "exportNaming", &mut opts.naming, naming_id); + } + crate::import::unknown_tags_warning(ui, &opts.naming); + if opts.naming.contains("{seq") { + let mut v = opts.start_number as f64; + if num(ui, &START_NUMBER, &mut v) { + opts.start_number = v as u32; + } + } + // like Lightroom Classic's Export To: one folder, or each photo's own folder (not on + // the web, where originals live in the browser's storage, not in folders) + use lightcraft_engine::export::DestinationMode as D; + if !cfg!(target_arch = "wasm32") || opts.destination_mode != D::SpecificFolder { + choices( + ui, + "Export to", + "exportDestinationMode", + &[(D::SpecificFolder, "Specific folder"), (D::SameAsOriginal, "Same folder as original photo")], + &mut opts.destination_mode, + ); + } + if opts.destination_mode == D::SpecificFolder { + field(ui, "Folder", |ui| { + trailing_button_row(ui, |ui| { + if app.services.pick_folder.is_some() + && crate::widgets::text_button(ui, "exportChooseFolder", crate::i18n::tr("Choose…"), false).clicked() + && let Some(pick) = app.services.pick_folder.as_mut() + && let Some(d) = pick() + { + *dir = d; + } + crate::widgets::named(ui.add(egui::TextEdit::singleline(dir).desired_width(ui.available_width())), crate::i18n::tr("Folder")); + }); + }); + } + field(ui, "Subfolder", |ui| { + crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.subfolder).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), crate::i18n::tr("Subfolder")) + }); + use lightcraft_engine::export::Conflict as K; + choices( + ui, + "If file exists", + "exportConflict", + &[(K::Unique, "Add number"), (K::Overwrite, "Overwrite"), (K::Skip, "Skip")], + &mut opts.conflict, + ); + // After export: Apple Photos imports the files written (macOS only) + #[cfg(target_os = "macos")] + { + let r = ui.checkbox(&mut opts.add_to_photos, crate::i18n::tr("Add to Apple Photos")); + crate::widgets::register(ui, "exportAddToPhotos", r.rect); + if opts.add_to_photos { + field(ui, "Album", |ui| { + crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.photos_album).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), crate::i18n::tr("Album")) + }); + ui.label( + egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")) + .size(11.0) + .color(t.text_dim), + ); + } + } + // nowhere to add them: a setting carried over from a Mac is dropped, not refused + #[cfg(not(target_os = "macos"))] + { + opts.add_to_photos = false; + } + ui.add_space(4.0); + field(ui, "Save preset", |ui| { + trailing_button_row(ui, |ui| { + let named = !preset_name.trim().is_empty(); + if crate::widgets::text_button(ui, "exportSavePreset", crate::i18n::tr("Save"), false).clicked() && named { + let params = export_dialog_params(opts, *full_size, resize, *limit_kb); + match app.run("export.savePreset", json!({"name": preset_name.trim(), "params": params})) { + Ok(_) => { + app.toast(ui.ctx(), crate::i18n::tr_format!("Saved export preset “{}”", preset_name.trim())); + preset_name.clear(); + } + Err(e) => app.toast(ui.ctx(), e), + } + } + crate::widgets::named(ui.add(egui::TextEdit::singleline(preset_name).hint_text(crate::i18n::tr("Preset name")).desired_width(ui.available_width())), crate::i18n::tr("Preset name")); + }); + }); + } + Dialog::Merge { opts } => crate::merge::body(app, ui, opts), + Dialog::Import { opts } => crate::import::body(app, ui, opts), + // (Settings is never taller than `body_max`, so the scroll area round it never + // scrolls: its tab bar stays put and its pages scroll by themselves) + Dialog::Settings { tab } => crate::panels::settings::window(app, ui, tab, body_max), + Dialog::SamModel { error, .. } => sam_model_body(app, ui, error.as_deref()), + Dialog::KeywordTag { + editing, + name, + parent, + inside, + synonyms, + include_on_export, + export_containing, + export_synonyms, + person, + add_to_selected, + .. + } => { + ui.label(egui::RichText::new(crate::i18n::tr("Keyword Name")).color(t.text_dim)); + // several fields: the name takes the focus when the dialog opens, not after + let r = crate::text_field::TextField::singleline("field:keywordTagName", name) + .hint(crate::i18n::tr("Keyword Name")) + .width(f32::INFINITY) + .select_on_focus(true) + .show(ui); + if ui.is_enabled() && just_opened(ui, "keyword-tag") { + r.response.request_focus(); + } + if r.ending == Some(crate::text_field::Ending::Return) { + confirm = true; + } + ui.add_space(4.0); + ui.label(egui::RichText::new(crate::i18n::tr("Synonyms")).color(t.text_dim)); + // Return in either field creates (or saves) the keyword + let r = crate::text_field::TextField::singleline("field:keywordSynonyms", synonyms) + .hint(crate::i18n::tr("Separated by commas")) + .width(f32::INFINITY) + .show(ui); + if r.ending == Some(crate::text_field::Ending::Return) { + confirm = true; + } + ui.add_space(6.0); + if editing.is_none() { + if let Some(p) = parent { + let r = ui.checkbox(inside, crate::i18n::tr_format!("Put inside “{parent}”", parent = p.replace('|', " › "))); + crate::widgets::register(ui, "check:keywordInside", r.rect); + } + let n = app.session.selection.ids.len(); + let r = ui.add_enabled(n > 0, egui::Checkbox::new(add_to_selected, crate::i18n::tr("Add to Selected Photos"))); + crate::widgets::register(ui, "check:keywordAddToSelected", r.rect); + ui.add_space(4.0); + } + ui.label(egui::RichText::new(crate::i18n::tr("Keyword Tag Options")).color(t.text_dim)); + for (on, label, id) in [ + (include_on_export, "Include on Export", "check:keywordIncludeOnExport"), + (export_containing, "Export Containing Keywords", "check:keywordExportContaining"), + (export_synonyms, "Export Synonyms", "check:keywordExportSynonyms"), + (person, "Person", "check:keywordPerson"), + ] { + let r = ui.checkbox(on, crate::i18n::tr(label)); + crate::widgets::register(ui, id, r.rect); + } + } + Dialog::KeywordSet { replaces, name, slots, as_new } => { + ui.label(egui::RichText::new(crate::i18n::tr("Set name")).color(t.text_dim)); + let r = crate::text_field::TextField::singleline("field:keywordSetName", name) + .hint(crate::i18n::tr("Set name")) + .width(f32::INFINITY) + .select_on_focus(true) + .show(ui); + if ui.is_enabled() && just_opened(ui, "keyword-set") { + r.response.request_focus(); + } + let mut returned = r.ending == Some(crate::text_field::Ending::Return); + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::tr("Keywords (⌥1–⌥9)")).color(t.text_dim)); + slots.resize(9, String::new()); + // equal columns of a set width (the window is still finding its own) + let w = 130.0; + egui::Grid::new("keyword-set-slots").num_columns(3).min_col_width(w).spacing([6.0, 4.0]).show(ui, |ui| { + for (i, slot) in slots.iter_mut().enumerate() { + let r = crate::text_field::TextField::singleline(&format!("field:keywordSetSlot:{}", i + 1), slot) + .hint(format!("⌥{}", i + 1)) + .width(w) + .show(ui); + returned |= r.ending == Some(crate::text_field::Ending::Return); + if i % 3 == 2 { + ui.end_row(); + } + } + }); + if replaces.is_some() { + ui.add_space(6.0); + let r = ui.checkbox(as_new, crate::i18n::tr("Save as a new set")); + crate::widgets::register(ui, "check:keywordSetAsNew", r.rect); + } + // Return in any field saves the set + if returned { + confirm = true; + } + } + Dialog::MoveKeyword { keyword, parent } => { + let name = keyword.rsplit('|').next().unwrap_or(keyword); + match parent { + Some(p) => ui.label(crate::i18n::tr_format!( + "“{parent}” has a “{name}” already. Merge the two?", + parent = p.replace('|', " › "), + name = name + )), + None => ui.label(crate::i18n::tr_format!("There is a “{name}” at the top level already. Merge the two?", name = name)), + }; + ui.label(egui::RichText::new(crate::i18n::tr("Their photos and the keywords below them come together under one keyword.")).color(t.text_dim)); + } + Dialog::DeleteKeyword { keyword, count } => { + let name = keyword.replace('|', " › "); + ui.label(crate::i18n::tr_format!("Delete the keyword “{name}”?", name = name)); + ui.label( + egui::RichText::new(if *count == 0 { + crate::i18n::tr("No photo has it; the keywords below it go too.").to_string() + } else { + crate::i18n::tr_format!( + "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.", + if *count == 1 { "" } else { "s" }, + count = count + ) + }) + .color(t.text_dim), + ); + } + Dialog::SaveEffect { name, group, fields, amount, brush } => { + if crate::panels::mask_effects::save_body(app, ui, name, group, fields, amount, brush) { + confirm = true; + } + } + Dialog::ManageEffects { search, selected, rename, confirm_delete, new_group } => { + crate::panels::mask_effects::manage_body(app, ui, search, selected, rename, confirm_delete, new_group) + } + Dialog::DeleteEffects { names } => { + let what = match names.as_slice() { + [one] => crate::i18n::tr_format!("Delete the effect preset “{name}”?", name = one), + _ => crate::i18n::tr_format!("Delete these {n} effect presets?", n = names.len()), + }; + ui.label(what); + ui.label(egui::RichText::new(crate::i18n::tr("Masks keep their sliders. Export presets first to keep a copy.")).color(t.text_dim)); + } + Dialog::ConfirmDelete { count } => { + let what = if *count == 1 { crate::i18n::tr("this photo").to_string() } else { crate::i18n::tr_format!("these {count} photos", count = count) }; + ui.label(crate::i18n::tr_format!("Move {what} to Recently Deleted?", what = what)); + ui.label(egui::RichText::new(crate::i18n::tr("They can be restored from Recently Deleted until it is emptied.")).color(t.text_dim)); + } + Dialog::MovePhotos { ids, name, dont_ask, .. } => { + let n = ids.len(); + ui.label(crate::i18n::tr_format!("Move {n} photo{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); + ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim)); + ui.add_space(4.0); + let c = ui.checkbox(dont_ask, crate::i18n::tr("Don't ask again")); + crate::widgets::register(ui, "check:moveDontAsk", c.rect); + c.on_hover_text(crate::i18n::tr("Settings → Confirm before moving photos to another folder on disk turns it back on")); + } + d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d), + Dialog::LightroomCatalog { folder, catalog } => { + ui.label(crate::i18n::tr("This is a Lightroom catalog, not a LightCraft library. Import it into a LightCraft library instead?")); + ui.label(egui::RichText::new(catalog.as_deref().unwrap_or(folder.as_str())).color(t.text_dim)); + // (the import then asks where the catalog goes, unless Settings says to merge, #2672) + let asks = app.ui.settings.lightroom_import == crate::state::LightroomImport::Ask + && app.session.library.as_ref().is_some_and(|l| l.on_disk); + let what = if asks { + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library." + } else { + "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now." + }; + ui.label(egui::RichText::new(crate::i18n::tr(what)).color(t.text_dim)); + } + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d), + Dialog::RemoveFolder { name, count, path, disk } => { + ui.label(crate::i18n::tr_format!( + "Remove “{name}” and its {count} photo{} from the library?", + if *count == 1 { "" } else { "s" }, + name = name, + count = count + )); + ui.label(egui::RichText::new(path.as_str()).color(t.text_dim)); + let scope = if *disk { "All the photos imported from this disk are included." } else { "That includes the photos in the folders inside it." }; + ui.label(egui::RichText::new(crate::i18n::tr(scope)).color(t.text_dim)); + ui.label( + egui::RichText::new(crate::i18n::tr("They move to Recently Deleted and can be restored; no file on disk is touched.")) + .color(t.text_dim), + ); + } + Dialog::About => { + ui.set_min_width(680.0); + let tab_id = egui::Id::unique("about_tab"); + let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (i, (id, label)) in ABOUT_TABS.iter().enumerate() { + if crate::widgets::text_button(ui, &format!("aboutTab-{id}"), label, usize::from(tab) == i).clicked() { + tab = u8::try_from(i).unwrap_or(0); + } + } + }); + ui.data_mut(|d| d.insert_temp(tab_id, tab)); + ui.separator(); + match tab { + 1 => crate::credits::contributors_ui(app, ui), + 2 => crate::credits::models_ui(ui), + _ => { + ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text)); + ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION"))); + ui.label(crate::i18n::tr_format!( + "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", + crate::theme::font_credits(app.chinese_font.is_some()) + )); + ui.add_space(10.0); + let r = crate::button::Button::new("Join the ArtCraft Discord") + .primary() + .large() + .min_width(260.0) + .widget("button:aboutDiscord") + .tooltip(crate::links::DISCORD) + .show(ui); + if r.clicked() { + let _ = crate::links::open(app, crate::links::DISCORD); + } + ui.add_space(6.0); + for (label, url) in [ + ("LightCraft website", crate::links::APP_PAGE), + ("Source code on GitHub", crate::links::GITHUB), + ("ArtCraft — more creative apps", crate::links::WEBSITE), + ] { + let r = ui.link(crate::i18n::tr(label)).on_hover_text(url); + if r.clicked() { + let _ = crate::links::open(app, url); + } + } + } + } + } + Dialog::Shortcuts => crate::panels::keymap::body(app, ui, &t), + Dialog::ViewOptions => crate::panels::settings::view_options(app, ui, &t), + Dialog::Print => crate::print_view::body(app, ui, &t), + }); + ui.add_space(4.0); + // the confirm on the right with Cancel to its left (macOS and GNOME's order), filled with + // the accent when it is the dialog's primary action. The row spans the width the window + // gives its content this frame (its default width, or its content's if wider), so it + // reaches the edge without widening the window. + let row_w = ui.available_width().max(ui.min_rect().width()).max(1.0); + let row_h = ui.spacing().interact_size.y; + ui.allocate_ui_with_layout(egui::vec2(row_w, row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| { + // a model file LightCraft cannot use has nothing to confirm, nor has a dialog that + // only shows something (one Close, no Cancel / OK) + let unusable_model = matches!(&dlg, Dialog::DenoiseModel { info, .. } | Dialog::FaceModel { info, .. } if info["kind"] == "unsupported"); + let informational = unusable_model || matches!(dlg, Dialog::LightroomResult { first: None, .. }) || only_shows(&dlg); + let sam = &app.session.segmenter; + let (sam_installed, sam_running, sam_failed) = (sam.installed(), sam.download_status().running, sam.download_status().error.is_some()); + // no download location in this build: nothing to offer but the manual install + let sam_nowhere = sam_by_hand(sam); + let cancel = match &dlg { + Dialog::SamModel { .. } if sam_running || sam_installed || sam_nowhere => "Close", + Dialog::SamModel { .. } => "Not Now", + Dialog::LightroomResult { .. } => "Close", + _ => "Cancel", + }; + let add_label; + let ok = match &dlg { + Dialog::Import { opts } => { + let n = opts.selected_paths().len(); + let verb = if opts.copy && opts.move_files { "Move" } else { "Import" }; + add_label = crate::i18n::tr_format!("{verb} {n} Photo{}", if n == 1 { "" } else { "s" }, verb = crate::i18n::tr(verb), n = n); + add_label.as_str() + } + Dialog::LightroomResult { first: Some(_), .. } => "Show in Library", + Dialog::ContactSheet { .. } => "Choose PDF…", + Dialog::SlideshowExport { .. } => "Export…", + Dialog::Print => "Print to PDF…", + Dialog::Merge { .. } => "Merge", + Dialog::DenoiseModel { info, .. } if info["download"].is_string() => "Accept & Download", + Dialog::DenoiseModel { .. } => "Install", + Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download", + Dialog::FaceModel { .. } if !informational => "Install", + Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } => "Delete", + Dialog::SaveEffect { .. } => "Create", + Dialog::MovePhotos { .. } => "Move", + // (not "Merge": that is photo merging, HDR / panorama, in some languages) + Dialog::MoveKeyword { .. } => "Merge Keywords", + Dialog::KeywordSet { .. } => "Save", + Dialog::KeywordTag { editing: None, .. } => "Create", + Dialog::KeywordTag { .. } => "Save", + Dialog::RemoveFolder { .. } => "Remove", + Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), + Dialog::SynchronizeFolder { .. } if informational => "Close", + Dialog::SynchronizeFolder { .. } => "Synchronize", + Dialog::SamModel { then: Some(_), .. } if sam_installed => "Continue", + Dialog::SamModel { .. } if sam_installed || sam_running || sam_nowhere => "", + Dialog::SamModel { error, .. } if error.is_some() || sam_failed => "Try Again", + Dialog::SamModel { .. } => "Download", + Dialog::RenamePerson { from, to, .. } if person_rename_plan(&app.session.catalog, from, to).needs_merge => "Merge", + _ if informational => "Close", + _ => "OK", + }; + // installing waits for the licence to be accepted + // (and Synchronize waits for the scan) + let rename_blocked = match &dlg { + Dialog::RenamePerson { from, to, merge } => { + let plan = person_rename_plan(&app.session.catalog, from, to); + plan.block.is_some() || (plan.needs_merge && !*merge) + } + _ => false, + }; + let can_confirm = !rename_blocked + && (informational + || !matches!( + &dlg, + Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. } + ) + // smart-album rules that can't mean anything wait to be fixed + && !matches!(&dlg, Dialog::SmartRules { id, rules, .. } if !rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).is_empty())); + let primary = !informational && can_confirm && confirm_style(&dlg) == ConfirmStyle::Primary; + use crate::button::{Button, Kind}; + // (each kind of dialog its own buttons: the keyboard's place doesn't carry from a + // dialog to the one it opens) + let kind = std::mem::discriminant(&dlg); + let cancel_button = Button::new(cancel).widget("button:dialogCancel").id_salt(kind).min_width(72.0); + let ok_button = Button::new(ok) + .kind(if primary { Kind::Primary } else { Kind::Secondary }) + .enabled(can_confirm) + .widget("button:dialogOk") + .id_salt(kind) + .min_width(72.0); + // (Cancel first, then the confirm: the keyboard goes through them as the eye does) + let gap = ui.spacing().item_spacing.x; + let mut buttons_w = 0.0; + if !informational { + buttons_w += cancel_button.desired_size(ui).x + gap; + } + if !ok.is_empty() { + buttons_w += ok_button.desired_size(ui).x; + } + ui.add_space((ui.available_width() - buttons_w).max(0.0)); + if !informational && cancel_button.show(ui).clicked() { + close = true; + } + let r = (!ok.is_empty()).then(|| ok_button.show(ui)); + if r.is_some_and(|r| r.clicked()) { + if informational { + close = true; + } else { + confirm = true; + } + } + }); + if import { + crate::import::note_dialog_bottom(ui); + } + content_w = ui.min_rect().width(); + }); + if settings && content_w > widest + 0.5 { + ctx.data_mut(|d| d.insert_temp(widest_id, content_w)); + } + if let Some(w) = &shown { + // (the import review keeps its hand-picked photos however the click lands) + if !raw_blocked && app.ui.settings.close_dialogs_outside && !import && clicked_backdrop(ctx, w.response.rect, popup_was_open) { + close = true; + } else if raw_blocked { + // A press made under the prompt or library window must not be remembered as a + // backdrop press for a release that arrives after that covering window goes away. + ctx.data_mut(|d| d.remove_temp::(egui::Id::unique("dialog-backdrop-press"))); + } + } + if let Some(w) = shown { + ctx.memory_mut(|m| m.set_modal_layer(w.response.layer_id)); + if let Some(body_h) = body_h { + let measured = (w.response.rect.height() - body_h).max(0.0); + if (measured - chrome).abs() > 0.5 { + ctx.data_mut(|d| d.insert_temp(chrome_id, measured)); + ctx.request_repaint(); + } + } + ctx.move_to_top(w.response.layer_id); + crate::widgets::register_response("dialog:window", w.response.rect, &w.response); + } + // (while the shortcuts editor records a key, it takes Esc itself to cancel; an open popup in + // the dialog, such as a date picker's calendar, takes it to close itself) + if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::widgets::escape_taken(ctx) { + close = true; + } + if !raw_blocked && confirm { + match confirm_dialog(app, &dlg) { + // the import review stays open on an error (e.g. an unusable folder template), and so + // does Export (e.g. no folder chosen) so the choices aren't lost, and Edit Capture Time + // (a time that isn't a date, or a shift it refuses) + Err(e) + if matches!( + dlg, + Dialog::Import { .. } + | Dialog::Export { .. } + | Dialog::ContactSheet { .. } + | Dialog::SlideshowExport { .. } + | Dialog::Print + | Dialog::NewAlbum { .. } + | Dialog::NewSmartAlbum { .. } + | Dialog::SmartRules { .. } + | Dialog::KeywordTag { .. } + | Dialog::KeywordSet { .. } + | Dialog::SynchronizeFolder { .. } + | Dialog::SaveEffect { .. } + | Dialog::CaptureTime { .. } + ) => + { + app.toast(ctx, e) + } + // the SAM 3 dialog stays open to show the download (or why it can't start) + Err(e) if matches!(dlg, Dialog::SamModel { .. }) => { + if let Dialog::SamModel { error, .. } = &mut dlg { + *error = Some(e); + } + } + Ok(r) if matches!(dlg, Dialog::NewAlbum { .. }) && r.get("skipped").and_then(serde_json::Value::as_u64).is_some_and(|n| n > 0) => { + // albums hold library photos (issue #684): say which part of the selection stayed out + crate::panels::grid::toast_skipped(app, ctx, &r); + close = true; + } + // a move says how it went, or why nothing moved + Ok(r) if matches!(dlg, Dialog::MovePhotos { .. }) => { + if let Dialog::MovePhotos { name, .. } = &dlg { + let text = crate::panels::left::moved_text(r["moved"].as_u64().unwrap_or(0), name); + app.toast(ctx, text); + } + close = true; + } + Err(e) if matches!(dlg, Dialog::MovePhotos { .. }) => { + app.toast(ctx, e); + close = true; + } + // photos whose capture time doesn't read are left as they were: say so + Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["unreadable"].as_u64().is_some_and(|n| n > 0) => { + app.toast(ctx, crate::i18n::tr("Photos whose capture time can't be read were left as they were")); + close = true; + } + // where a Lightroom catalog goes: stays open to be corrected (a folder that isn't + // empty), unless the library it names has gone + Err(e) if matches!(dlg, Dialog::LightroomDestination { .. }) => { + close = !crate::lightroom_destination::keeps_open_on_error(app, &dlg); + app.toast(ctx, e); + } + Ok(_) if keeps_open(app, &dlg) => { + if let Dialog::SamModel { error, .. } = &mut dlg { + *error = None; + } + } + _ => close = true, + } + } + // a dialog opened from inside this one (a button in Settings that shows a licence) takes its place + if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) { + return; + } + if !close && !blocked { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame)); + } + app.ui.dialog = if close { None } else { Some(dlg) }; +} + +/// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`]. +const BACKDROP_SHOWN: &str = "dialog-backdrop-shown"; + +/// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and +/// released outside the window, so a slider dragged past its edge doesn't close it; a press while a +/// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is +/// read before the window is drawn, since drawing it already closes the popup. Only a press made +/// while the dialog is shown counts: in the frame a dialog appears, its input is the click that +/// opened it (a quick click on a slow frame presses and releases in that one frame), so it never +/// closes it. (Read from the raw events: egui forgets the press origin on release.) +fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool { + let press_id = egui::Id::unique("dialog-backdrop-press"); + let frame = ctx.cumulative_frame_nr(); + // the same frame too: a second pass of it gets no input + let shown = ctx.data(|d| d.get_temp::(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame); + if !shown { + ctx.data_mut(|d| d.remove_temp::(press_id)); + return false; + } + let (press, release, clicked) = ctx.input(|i| { + let at = |down: bool| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos), + _ => None, + }) + }; + (at(true), at(false), i.pointer.primary_clicked()) + }); + if let Some(p) = press { + let outside = !window.contains(p) && !popup_was_open; + ctx.data_mut(|d| d.insert_temp(press_id, outside)); + } + let Some(release) = release else { return false }; + let pressed_outside = ctx.data_mut(|d| d.remove_temp::(press_id)).unwrap_or(false); + clicked && pressed_outside && !window.contains(release) +} + +/// Room kept free above and below a dialog (#781). +const DIALOG_SCREEN_MARGIN: f32 = 12.0; +/// A dialog's title bar, frame and button row before the first frame measures them. +const DIALOG_CHROME_GUESS: f32 = 100.0; +/// A dialog's options never get less room than this, however short the window. +const DIALOG_MIN_BODY: f32 = 80.0; + +/// A list that scrolls on its own never gets shorter than this to make its dialog fit. +const DIALOG_MIN_LIST: f32 = 120.0; + +fn list_shrink_id() -> egui::Id { + egui::Id::unique("dialog-list-shrink") +} + +fn list_applied_id() -> egui::Id { + egui::Id::unique("dialog-list-applied") +} + +/// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the +/// shortcuts, smart-album rules): `preferred`, less what the dialog needs to fit the window, so +/// on a short window the list gets shorter rather than scrolling inside a scrolling dialog. +pub fn list_height(ui: &egui::Ui, preferred: f32) -> f32 { + let shrink = ui.data(|d| d.get_temp::(list_shrink_id())).unwrap_or(0.0); + let height = (preferred - shrink).max(preferred.min(DIALOG_MIN_LIST)); + ui.data_mut(|d| *d.get_temp_mut_or_default::(list_applied_id()) += preferred - height); + height +} + +/// A dialog's options: in a vertical scroll area at most `max_height` tall when `scroll` names +/// the dialog (it shrinks to its content, so a dialog that fits looks as it would without it; +/// each dialog keeps a scroll position of its own), drawn directly otherwise. Returns the height +/// they took when scrolled. +fn dialog_body(ui: &mut egui::Ui, scroll: Option<&str>, max_height: f32, body: impl FnOnce(&mut egui::Ui)) -> Option { + let Some(name) = scroll else { + ui.data_mut(|d| d.remove_temp::(list_shrink_id())); + body(ui); + return None; + }; + ui.data_mut(|d| d.insert_temp(list_applied_id(), 0.0_f32)); + let top = ui.cursor().top(); + // (an auto-sized window offers its content last frame's height; the minimum lets a dialog + // that grows take its full height at once, and the area still shrinks to fit its content) + let out = egui::ScrollArea::vertical() + .id_salt(("dialog-body", name)) + .max_height(max_height) + .min_scrolled_height(max_height) + .auto_shrink([true, true]) + .show(ui, body); + // what the lists that scroll on their own gave up this frame, and what they should next frame + let applied = ui.data(|d| d.get_temp::(list_applied_id())).unwrap_or(0.0); + let was = ui.data(|d| d.get_temp::(list_shrink_id())).unwrap_or(0.0); + let shrink = (out.content_size.y + applied - max_height).max(0.0); + if (shrink - was).abs() > 0.5 { + ui.data_mut(|d| d.insert_temp(list_shrink_id(), shrink)); + ui.ctx().request_repaint(); + } + // (the room the scroll area took: its `inner_rect` can be taller than what it allocated) + Some(ui.min_rect().bottom() - top) +} + +/// Apply a dialog's action (also used by `ui.dialog.confirm`). +/// What [`fmt_gap`] writes, read back: `90`, `90 s`, `1 min 30 s`, `2 h 5 min`, `1 day` +/// (units `s`, `min`, `h`, `day`, each optional after a plain number of seconds). +pub fn parse_gap(text: &str) -> Option { + // the one translated text `fmt_gap` writes ("1 Tag") + if text.trim() == crate::i18n::tr("1 day") { + return Some(86400.0); + } + let mut total = 0.0; + let mut seen = false; + let mut words = text.split_whitespace().peekable(); + while let Some(word) = words.next() { + // "90s" as well as "90 s" + let split = word.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(word.len()); + let (num, unit) = word.split_at(split); + let n: f64 = num.parse().ok().filter(|n: &f64| n.is_finite())?; + let unit = if unit.is_empty() { + match words.peek() { + Some(u) if u.parse::().is_err() => words.next().unwrap_or_default(), + _ => "s", + } + } else { + unit + }; + let scale = match unit.trim_end_matches('.').to_lowercase().as_str() { + "s" | "sec" | "secs" | "second" | "seconds" => 1.0, + "m" | "min" | "mins" | "minute" | "minutes" => 60.0, + "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0, + "d" | "day" | "days" => 86400.0, + _ => return None, + }; + total += n * scale; + seen = true; + } + seen.then_some(total) +} + +/// The longest burst gap `photo.analyze` accepts: a day. +pub const MAX_BURST_GAP: f32 = 86_400.0; + +/// Keep what was typed in the Assisted Culling value fields within what `photo.analyze` accepts +/// (a gap of 0 s to a day, a similarity of 0 to 1), not within the sliders' drag range. +pub fn clamp_cull_burst(gap: &mut f32, similarity: &mut f32) { + *gap = if gap.is_finite() { gap.clamp(0.0, MAX_BURST_GAP) } else { 10.0 }; + *similarity = if similarity.is_finite() { similarity.clamp(0.0, 1.0) } else { 0.93 }; +} + +/// The `photo.analyze` parameters of the Assisted Culling dialog, its values as they are. +pub fn cull_params(reject_below: f32, pick_best: bool, burst_gap: f32, similarity: f32) -> serde_json::Value { + let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity}); + if reject_below > 0.0 { + p["rejectBelow"] = json!(reject_below); + } + p +} + +/// `90` → `1 min 30 s`. +pub fn fmt_gap(v: f64) -> String { + let v = v.round() as u64; + match v { + 0..60 => format!("{v} s"), + 60..3600 if v.is_multiple_of(60) => format!("{} min", v / 60), + 60..3600 => format!("{} min {} s", v / 60, v % 60), + 3600..86400 if v.is_multiple_of(3600) => format!("{} h", v / 3600), + 3600..86400 if v.is_multiple_of(60) => format!("{} h {} min", v / 3600, v % 3600 / 60), + // the seconds too, so editing the text reads back the same gap + 3600..86400 => format!("{} h {} min {} s", v / 3600, v % 3600 / 60, v % 60), + _ => crate::i18n::tr("1 day").into(), + } +} + +/// Whether a dialog stays open after its action succeeded (the SAM 3 dialog while the model +/// downloads). +pub fn keeps_open(app: &LightcraftApp, dlg: &Dialog) -> bool { + matches!(dlg, Dialog::SamModel { .. }) && !app.session.segmenter.installed() +} + +/// No SAM 3 model, no download running and nowhere to download it from: installing it by hand is +/// all the dialog can offer. +fn sam_by_hand(sam: &lightcraft_engine::segment::Segmenter) -> bool { + !sam.installed() && !sam.download_status().running && sam.mirrors().is_empty() +} + +/// The model installation guide. +const SAM_HELP: &str = "https://github.com/storytold/lightcraft/blob/main/docs/ai-masks.md#getting-the-model"; + +/// Open the configured SAM 3 folder itself; revealing a file opens its parent instead. +pub(crate) fn show_model_folder(app: &mut LightcraftApp) -> Result { + let dir = app.session.segmenter.dir.as_ref().ok_or("no folder is set for the SAM 3 model")?; + let path = dir.to_str().ok_or("the model folder path is not valid UTF-8")?; + let open = app.services.open_with.as_mut().ok_or("opening model folders is not available here")?; + // Create only after the host action is available. Existing model files are left alone. + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + #[cfg(target_os = "linux")] + if let Some(open_folder) = app.services.open_model_folder.clone() { + let path = path.to_string(); + let folder = path.clone(); + crate::tasks::spawn( + app, + "Show in File Manager", + Some("openModelFolder"), + move || open_folder(&folder), + |app, ctx, result| { + if let Err(e) = result { + app.toast_error(ctx, e); + } + }, + )?; + return Ok(json!({"path": path, "background": true})); + } + open(path, "")?; + Ok(json!({"path": path})) +} + +/// The SAM 3 dialog: what the model is, its size and licence, and the download's progress. +fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str>) { + use lightcraft_engine::segment::{LICENSE_NAME, LICENSE_URL, MODEL_BYTES}; + let t = Tokens::get(ui.ctx()); + let seg = &app.session.segmenter; + let d = seg.download_status(); + if seg.installed() { + ui.label(crate::i18n::tr("The SAM 3 model is installed: Object and Describe masks are ready.")); + return; + } + let gb = |b: u64| b as f64 / 1e9; + ui.label(crate::i18n::tr( + "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.", + )); + let dir = seg.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default(); + ui.label(format!("{} {:.1} GB, {} {dir}", crate::i18n::tr("A one-time download of about"), gb(MODEL_BYTES), crate::i18n::tr("saved in"))); + ui.label( + egui::RichText::new(format!( + "{} {LICENSE_NAME} — {}", + crate::i18n::tr("Licence:"), + crate::i18n::tr("Meta's terms, not LightCraft's. Downloading it means accepting them.") + )) + .color(t.text_label), + ); + let r = ui.link(crate::i18n::tr("Read the SAM License")).on_hover_text(LICENSE_URL); + crate::widgets::register(ui, "link:samLicense", r.rect); + if r.clicked() { + let _ = crate::links::open(app, LICENSE_URL); + } + let seg = &app.session.segmenter; + if d.running { + ui.add_space(4.0); + let text = format!("{:.2} / {:.2} GB · {}", gb(d.done), gb(d.total), d.file); + crate::progress::Progress::new(crate::progress::fraction_of(d.done, d.total)).label(text).widget("progress:samDownload").show(ui); + let r = ui.button(crate::i18n::tr("Cancel Download")); + crate::widgets::register(ui, "button:samCancel", r.rect); + if r.clicked() { + app.session.segmenter.cancel_download(); + } + ui.label(egui::RichText::new(crate::i18n::tr("You can close this: the download continues, and resumes if interrupted.")).color(t.text_dim)); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); + return; + } + if seg.mirrors().is_empty() { + // nothing to download from: say how to install it by hand, with the folder and the guide a click away + let dir = seg.dir.clone(); + ui.label( + egui::RichText::new(crate::i18n::tr( + "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.", + )) + .color(t.text_dim), + ); + ui.horizontal_wrapped(|ui| { + if dir.is_some() && crate::menus::ui_enabled(app, "app.openSamModelFolder") { + let r = ui.button(crate::i18n::tr(crate::menus::reveal_label())); + crate::widgets::register(ui, "button:samFolder", r.rect); + if r.clicked() + && let Err(e) = app.run("app.openSamModelFolder", json!({})) + { + app.toast_error(ui.ctx(), e); + } + } + let r = ui.link(crate::i18n::tr("How to install the model")).on_hover_text(SAM_HELP); + crate::widgets::register(ui, "link:samHelp", r.rect); + if r.clicked() + && let Err(e) = crate::links::open(app, SAM_HELP) + { + app.toast(ui.ctx(), e); + } + }); + } + if let Some(e) = error.map(str::to_string).or(d.error) { + ui.label(egui::RichText::new(format!("{} {e}", crate::i18n::tr("The download didn't work:"))).color(egui::Color32::from_rgb(230, 90, 80))); + } +} + +/// Runs a command that creates an album and asks the Albums tree to open the folders down to it. +fn created_in(app: &mut LightcraftApp, command: &str, params: serde_json::Value) -> Result { + let r = app.run(command, params)?; + app.ui.reveal_album = r.get("id").and_then(serde_json::Value::as_u64); + Ok(r) +} + +/// The albums an Album rule in smart album `editing` picks from, in the sidebar's order: the album +/// itself and any smart album that tests it (testing it back would loop) are blocked, with why. +pub(crate) fn album_entries(cat: &lightcraft_catalog::Catalog, editing: Option) -> Vec { + let editing = editing.map(lightcraft_catalog::AlbumId); + crate::album_picker::entries_from(cat, |a| match editing { + Some(e) if a.id == e => Some(crate::i18n::tr("This is the album you're editing").to_string()), + Some(e) if cat.album_reaches(a.id, e) => Some(crate::i18n::tr("It tests this album, so testing it back would loop").to_string()), + _ => None, + }) +} + +pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result { + match dlg { + Dialog::LightroomResult { first, .. } => { + if let Some(first) = first { + app.run("library.source", json!({"kind": "all"}))?; + let mut filter = serde_json::to_value(lightcraft_catalog::Filter::default()).map_err(|e| e.to_string())?; + // The filter command merges a patch; these defaults are omitted by serde. + filter["only"] = json!([]); + filter["labels"] = json!([]); + filter["keywords"] = json!([]); + filter["dates"] = json!([]); + filter["ruleSet"] = serde_json::Value::Null; + app.run("library.filter", filter)?; + app.run("library.select", json!({"ids": [first]}))?; + app.ui.view = crate::state::ViewMode::PhotoGrid; + } + Ok(serde_json::Value::Null) + } + Dialog::SamModel { then, .. } => { + if app.session.segmenter.installed() { + // installed: start what the user was doing + if let Some((kind, op)) = then { + crate::panels::masking::begin_ai(app, kind, op)?; + } + return Ok(serde_json::Value::Null); + } + let r = app.run("segment.model.download", json!({"acknowledged": true})); + if r.is_ok() { + app.ui.sam_downloading = true; + } + r + } + Dialog::NewAlbum { name, folder, parent, include_selected } => { + created_in(app, "album.create", json!({"name": name, "folder": folder, "addSelected": !folder && *include_selected, "parent": parent})) + } + Dialog::RenameAlbum { id, name } => app.run("album.rename", json!({"id": id, "name": name})), + Dialog::TextPrompt { value, command, params, key, .. } => { + let mut p = params.clone(); + p[key.as_str()] = json!(value.trim()); + app.run(command, p) + } + Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => app.run( + "photo.setCaptureTime", + match mode.as_str() { + "set" => json!({"time": time}), + "shift" => json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}), + _ => json!({"hours": zone}), + }, + ), + Dialog::LabelNames { names, save_as } => { + let mut m = serde_json::Map::new(); + for (l, n) in lightcraft_catalog::ColorLabel::ALL.iter().zip(names) { + m.insert(format!("{l:?}").to_lowercase(), if n.trim().is_empty() { serde_json::Value::Null } else { json!(n.trim()) }); + } + let r = app.run("label.setNames", json!({"names": m})); + if r.is_ok() && !save_as.trim().is_empty() { + return app.run("label.saveSet", json!({"name": save_as.trim()})); + } + r + } + Dialog::Rename { template, start } => app.run("photo.rename", json!({"template": template, "start": start})), + Dialog::RenameKeyword { from, to } => app.run("keyword.rename", json!({"from": from, "to": to})), + Dialog::RenamePerson { from, to, merge } => app.run("faces.renamePerson", json!({"from": from, "to": to.trim(), "merge": merge})), + Dialog::KeywordTag { + editing, + name, + parent, + inside, + synonyms, + include_on_export, + export_containing, + export_synonyms, + person, + add_to_selected, + reveal, + } => { + let mut params = json!({ + "synonyms": synonyms.split(',').map(str::trim).filter(|s| !s.is_empty()).collect::>(), + "includeOnExport": include_on_export, + "exportContaining": export_containing, + "exportSynonyms": export_synonyms, + "person": person, + }); + match editing { + Some(keyword) => { + params["keyword"] = json!(keyword); + params["name"] = json!(name); + let r = app.run("keyword.edit", params); + if r.is_ok() { + let to = match keyword.rsplit_once('|') { + Some((parent, _)) => format!("{parent}|{}", name.trim()), + None => name.trim().to_string(), + }; + crate::panels::keyword_list::follow(app, keyword, &to); + } + r + } + None => { + params["name"] = json!(name); + params["parent"] = if *inside { json!(parent) } else { serde_json::Value::Null }; + params["addToSelected"] = json!(add_to_selected); + let r = app.run("keyword.create", params); + if *reveal && let Ok(made) = &r { + app.ui.reveal_keyword = made["keyword"].as_str().map(str::to_string); + } + r + } + } + } + Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})), + Dialog::KeywordSet { replaces, name, slots, as_new } => { + use lightcraft_catalog::keywords::same; + let name = name.trim(); + if name.is_empty() { + return Err(crate::i18n::tr("A keyword set needs a name").to_string()); + } + if same(name, lightcraft_engine::cmd::keywords::RECENT) { + return Err(crate::i18n::tr("Recent Keywords is built in: choose another name").to_string()); + } + // the set it renames: none when saving as new, or when it was deleted meanwhile (then it is + // saved anew rather than refused) + let sets = &app.session.keyword_sets; + let renames = replaces.as_deref().filter(|_| !as_new).filter(|old| sets.iter().any(|x| same(&x.name, old))); + if sets.iter().any(|x| same(&x.name, name) && !renames.is_some_and(|old| same(&x.name, old))) { + return Err(crate::i18n::tr_format!("There is a keyword set “{name}” already", name = name)); + } + let mut params = json!({"name": name, "keywords": slots}); + match renames { + Some(old) => params["replace"] = json!(old), + None => params["new"] = json!(true), + } + app.run("keyword.saveSet", params) + } + Dialog::MoveKeyword { keyword, parent } => { + let r = app.run("keyword.move", json!({"keyword": keyword, "parent": parent, "merge": true})); + if r.is_ok() { + let leaf = keyword.rsplit('|').next().unwrap_or(keyword); + let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}|{leaf}")); + crate::panels::keyword_list::follow(app, keyword, &to); + } + r + } + Dialog::MergeKeywords { from, into } => app.run("keyword.merge", json!({"from": from, "into": into})), + Dialog::AutoStack { gap } => app.run("stack.auto", json!({"gap": gap})), + Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted), + Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), + Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), + Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + app.ui.cull_burst = Some((*burst_gap, *similarity)); + app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity)) + } + Dialog::SmartRules { id, name, rules, parent } => { + // refused before anything changes (not even the name) + if let Some(problem) = rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).first() { + return Err(problem.to_string()); + } + let name = if name.trim().is_empty() { "Smart Album".to_string() } else { name.trim().to_string() }; + match id { + // the name and the rules together: one undo step, both or neither + Some(id) => app.run("album.setRules", json!({"id": id, "name": name, "replace": true, "rules": {"ruleSet": rules}})), + None => created_in(app, "album.createSmart", json!({"name": name, "rules": {"ruleSet": rules}, "parent": parent})), + } + } + Dialog::NewSmartAlbum { name, parent } => { + created_in(app, "album.createSmart", json!({"name": if name.trim().is_empty() { "Smart Album" } else { name }, "parent": parent})) + } + Dialog::CreatePreset { name, group, groups } => app.run( + "preset.create", + json!({ + "name": if name.trim().is_empty() { "My Preset" } else { name }, + "group": if group.trim().is_empty() { "User Presets" } else { group }, + "groups": groups, + }), + ), + Dialog::ContactSheet { options } => app.run("app.contactSheet", json!(options)), + Dialog::SlideshowExport { settings } => app.run("app.slideshowExport", json!(settings)), + Dialog::Print => app.run("app.print", json!({})), + Dialog::CopySettings { groups } => app.run("develop.copy", json!({"groups": groups})), + Dialog::PasteSettings { groups } => app.run("develop.paste", json!({"groups": groups})), + Dialog::Export { opts, full_size, resize, limit_kb, dir, .. } => { + let mut p = export_dialog_params(opts, *full_size, resize, *limit_kb); + p["dir"] = json!(dir); + p["background"] = json!(true); + app.run("app.export", p) + } + Dialog::Merge { opts } => crate::merge::start_final(app, opts), + Dialog::Import { opts } => crate::import::start(app, opts), + Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})), + Dialog::MovePhotos { ids, folder, dont_ask, library, .. } => { + // another library opened meanwhile (from the menu bar, an agent): these numbers are + // other photos there + if *library != app.session.library_generation() { + return Err(crate::i18n::tr("Another library was opened since the photos were dropped: nothing was moved").to_string()); + } + if *dont_ask { + app.ui.settings.ask_before_move = false; + } + crate::panels::left::move_photos(app, Some(ids), folder).map(|n| json!({"moved": n})) + } + // the catalog found: no file dialog; none: File ▸ Import Lightroom Catalog… asks for it + Dialog::LightroomCatalog { catalog, .. } => { + app.run("file.importLightroom", catalog.as_ref().map_or_else(|| json!({}), |c| json!({"path": c}))) + } + d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::confirm(app, d), + Dialog::SaveEffect { name, group, fields, amount, brush } => { + crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush) + } + Dialog::DeleteEffects { names } => app.run("mask.deleteEffect", json!({"names": names})), + Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})), + d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d), + Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => { + Ok(serde_json::Value::Null) + } + } +} + +/// Open a one-field dialog that runs `command` with `params` + `{key: typed value}`. +pub fn prompt(app: &mut LightcraftApp, title: &str, hint: &str, value: &str, command: &str, params: serde_json::Value, key: &str) { + app.ui.dialog = + Some(Dialog::TextPrompt { title: title.into(), hint: hint.into(), value: value.into(), command: command.into(), params, key: key.into() }); +} + +/// The Export dialog's choices as `app.export` params (without the folder). +fn export_dialog_params( + opts: &lightcraft_engine::export::ExportOptions, + full_size: bool, + resize: &lightcraft_engine::export::Resize, + limit_kb: u32, +) -> serde_json::Value { + let o = lightcraft_engine::export::ExportOptions { + resize: (!full_size).then_some(*resize), + limit_kb: (limit_kb > 0).then_some(limit_kb), + ..opts.clone() + }; + o.to_json() +} + +// ------------------------------------------------------------------------------------------ dialog widgets + +/// Two columns of settings-group checkboxes (Copy Settings, Create Preset) plus All / None. +fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec) { + let key_of = |g: &SettingsGroup| serde_json::to_value(g).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); + ui.columns(2, |cols| { + for (i, g) in SettingsGroup::ALL.iter().enumerate() { + let key = key_of(g); + let mut on = groups.contains(&key); + let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label())); + crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r); + if r.changed() { + if on { + groups.push(key); + } else { + groups.retain(|x| *x != key); + } + } + } + }); + ui.horizontal(|ui| { + let all = ui.small_button(crate::i18n::tr("All")); + crate::widgets::register(ui, format!("{tag}:all"), all.rect); + if all.clicked() { + *groups = SettingsGroup::ALL.iter().map(key_of).collect(); + } + let none = ui.small_button(crate::i18n::tr("None")); + crate::widgets::register(ui, format!("{tag}:none"), none.rect); + if none.clicked() { + groups.clear(); + } + }); +} + +/// Width of the label column in dialogs. +const LABEL_W: f32 = 78.0; + +const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, default: f64, step: f64) -> ControlSpec { + ControlSpec { id, label, section: Section::Light, min, max, default, step, decimals: 0, track: Track::Plain } +} +const QUALITY: ControlSpec = spec("export.quality", "Quality", 1.0, 100.0, 90.0, 1.0); +const LIMIT_KB: ControlSpec = spec("export.limitKb", "Limit file size (KB, 0 = off)", 0.0, 20_000.0, 0.0, 10.0); +const SIZE_PX: ControlSpec = spec("export.sizePx", "Pixels", 16.0, 20_000.0, 2048.0, 16.0); +const SIZE_W: ControlSpec = spec("export.sizeW", "Width (px)", 16.0, 20_000.0, 2048.0, 16.0); +const SIZE_H: ControlSpec = spec("export.sizeH", "Height (px)", 16.0, 20_000.0, 2048.0, 16.0); +const SIZE_MP: ControlSpec = ControlSpec { decimals: 1, ..spec("export.sizeMp", "Megapixels", 0.1, 100.0, 12.0, 0.1) }; +const SIZE_PCT: ControlSpec = spec("export.sizePercent", "Percent", 1.0, 400.0, 50.0, 1.0); +const START_NUMBER: ControlSpec = spec("export.startNumber", "Start number", 1.0, 9999.0, 1.0, 1.0); +const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240.0, 1.0); + +/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi. +fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) { + use lightcraft_engine::export::ResizeMode as R; + const MODES: [(R, &str); 8] = [ + (R::LongEdge, "Long Edge"), + (R::ShortEdge, "Short Edge"), + (R::Width, "Width"), + (R::Height, "Height"), + (R::WidthHeight, "Width & Height"), + (R::Dimensions, "Dimensions"), + (R::Megapixels, "Megapixels"), + (R::Percent, "Percentage"), + ]; + let r_full = ui.checkbox(full, crate::i18n::tr("Full size")); + crate::widgets::register(ui, "check:exportFullSize", r_full.rect); + if !*full { + field(ui, "Resize to", |ui| { + let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1); + let before = r.mode; + let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { + for (m, l) in MODES { + ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l)); + } + }); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize")); + crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect); + if r.mode != before { + // a sensible value for the new unit + r.value = match r.mode { + R::Megapixels => 12.0, + R::Percent => 50.0, + _ if matches!(before, R::Megapixels | R::Percent) => 2048.0, + _ => r.value, + }; + if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 { + r.height = r.value as u32; + } + } + }); + let mut v = r.value as f64; + let spec = match r.mode { + R::Megapixels => &SIZE_MP, + R::Percent => &SIZE_PCT, + R::Dimensions | R::WidthHeight => &SIZE_W, + _ => &SIZE_PX, + }; + if num(ui, spec, &mut v) { + r.value = v as f32; + } + if matches!(r.mode, R::Dimensions | R::WidthHeight) { + let mut h = r.height as f64; + if num(ui, &SIZE_H, &mut h) { + r.height = h as u32; + } + } + let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge")); + crate::widgets::register(ui, "check:exportDontEnlarge", c.rect); + } + let mut p = *ppi as f64; + if num(ui, &PPI, &mut p) { + *ppi = p as u16; + } +} +/// All nine positions supported by both the text and graphic watermark renderer. +/// Keep them in grid order so bottom-centre and edge-centre anchors are available in Export. +const WM_POSITIONS: [(lightcraft_engine::export::Anchor, &str); 9] = { + use lightcraft_engine::export::Anchor::*; + [(TopLeft, "↖"), (Top, "↑"), (TopRight, "↗"), (Left, "←"), (Center, "•"), (Right, "→"), (BottomLeft, "↙"), (Bottom, "↓"), (BottomRight, "↘")] +}; + +const WM_IMAGE_WIDTH: ControlSpec = spec("export.watermarkImageWidth", "Width (% of photo)", 2.0, 100.0, 20.0, 1.0); +const WM_SIZE: ControlSpec = spec("export.watermarkSize", "Size (% of short edge)", 1.0, 15.0, 3.5, 0.5); +const WM_OPACITY: ControlSpec = spec("export.watermarkOpacity", "Opacity (%)", 5.0, 100.0, 70.0, 1.0); +const WM_INSET_X: ControlSpec = + ControlSpec { decimals: 1, ..spec("export.watermarkInsetX", "Horizontal inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) }; +const WM_INSET_Y: ControlSpec = + ControlSpec { decimals: 1, ..spec("export.watermarkInsetY", "Vertical inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) }; + +/// A themed slider row editing `v`; true when it changed. +fn num(ui: &mut egui::Ui, spec: &ControlSpec, v: &mut f64) -> bool { + match crate::widgets::slider(ui, spec, *v, true, None).value { + Some(n) => { + *v = n; + true + } + None => false, + } +} + +/// A labelled row (fixed label column). +/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes +/// after (a save dialog). +fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) { + use lightcraft_engine::slideshow_export::{ExportSettings, Format}; + let t = Tokens::get(ui.ctx()); + let photos = app.session.visible_cloned().len(); + let slide = app.session.slideshow.slide_duration; + let (intro, ending) = app.session.slide_titles.durations(slide); + let titles = usize::from(intro.is_some()) + usize::from(ending.is_some()); + let seconds = photos as f64 * slide + intro.unwrap_or(0.0) + ending.unwrap_or(0.0); + let summary = crate::i18n::tr_format!( + "{n} photos in view · {slides} slides · {time}", + n = photos, + slides = photos + titles, + time = format!("{}:{:02}", (seconds / 60.0).floor() as u64, (seconds % 60.0).round() as u64) + ); + ui.label(egui::RichText::new(summary).color(t.text_dim)); + let before = settings.format; + choices(ui, "Format", "slideshowExportFormat", &[(Format::Pdf, "PDF"), (Format::Jpeg, "JPEG"), (Format::Video, "Video")], &mut settings.format); + if settings.format != before { + *settings = ExportSettings { full_screen: settings.full_screen, ..ExportSettings::for_format(settings.format) }; + } + match settings.format { + Format::Video => { + choices(ui, "Size", "slideshowExportSize", &[(720, "720p"), (1080, "1080p")], &mut settings.size); + choices(ui, "Frame rate", "slideshowExportFps", &[(24, "24 fps"), (30, "30 fps")], &mut settings.fps); + let mut webm = settings.container == "webm"; + choices(ui, "Container", "slideshowExportContainer", &[(false, "MP4"), (true, "WebM")], &mut webm); + settings.container = if webm { "webm".into() } else { "mp4".into() }; + } + _ => { + choices(ui, "Size", "slideshowExportSize", &[(1024, "1024 px"), (1920, "1920 px"), (3840, "3840 px")], &mut settings.size); + } + } + field(ui, "Quality", |ui| { + let r = ui.add(egui::Slider::new(&mut settings.quality, 1..=100)); + crate::widgets::register(ui, "slider:slideshowExportQuality", r.rect); + }); + let note = match settings.format { + Format::Pdf => { + let r = ui.checkbox(&mut settings.full_screen, crate::i18n::tr("Automatically show full screen")); + crate::widgets::register(ui, "check:slideshowExportFullScreen", r.rect); + "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode." + } + Format::Jpeg => "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.", + Format::Video => "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.", + }; + ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)); + ui.label( + egui::RichText::new(crate::i18n::tr("Slides use the slideshow's layout, overlays and intro and ending screens, in view order.")) + .color(t.text_dim), + ); +} + +fn field(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let t = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(LABEL_W); + ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text_label)); + }); + add(ui) + }) + .inner +} + +/// The rest of a [`field`] row, laid out right to left: `add` places its trailing button(s) first, +/// then a text field taking exactly the width that's left. (Subtracting a guessed button width +/// instead made the auto-sized dialog grow every frame when the real button was wider, #8.) +fn trailing_button_row(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { + let h = ui.spacing().interact_size.y.max(24.0); + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), h), egui::Layout::right_to_left(egui::Align::Center), add); +} + +/// A labelled row of mutually exclusive choice buttons (ids `button:{id}-{index}`). +fn choices(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], value: &mut V) { + field(ui, label, |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (i, (v, l)) in options.iter().enumerate() { + if crate::widgets::text_button(ui, &format!("{id}-{i}"), l, *value == *v).clicked() { + *value = *v; + } + } + }); +} + +/// Dialogs that Return confirms with nothing focused (those with text fields confirm from the +/// field: `dialog_field`). +fn return_confirms(dlg: &Dialog) -> bool { + matches!(dlg, Dialog::CopySettings { .. } | Dialog::PasteSettings { .. }) +} + +struct PersonRenamePlan { + faces: usize, + needs_merge: bool, + /// Why Rename stays disabled. `None` when the typed name can be applied. + block: Option<&'static str>, +} + +/// What renaming `from` to `to` would do, using the same rules as `faces.renamePerson`. +fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, to: &str) -> PersonRenamePlan { + let to_trim = to.trim(); + if to_trim.is_empty() { + return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("Type a name") }; + } + if to_trim.chars().count() > 200 || to_trim.chars().any(char::is_control) { + return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("A name is at most 200 characters, without control characters") }; + } + let from_key = from.trim().to_lowercase(); + let to_key = to_trim.to_lowercase(); + let mut matched = 0usize; + let mut faces = 0usize; + 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) { + 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 { + matched += 1; + if region.name.as_deref() != Some(to_trim) { + faces += 1; + } + } else if key == to_key { + needs_merge = true; + } + } + } + } + let block = if matched == 0 { + Some("No person by that name") + } else if faces == 0 { + Some("That is already their name") + } else { + None + }; + // a case-only change is the same person, not a merge + PersonRenamePlan { faces, needs_merge: needs_merge && from_key != to_key, block } +} + +/// A dialog's one text field: it takes the focus when the dialog opens, and opens with its text +/// selected, so typing replaces it. It takes the focus back only while nothing else has it: taking +/// it back every frame would keep Tab from ever reaching the dialog's buttons and check boxes. +/// True when Return confirms the dialog; Esc cancels the dialog (`show`). +fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) -> bool { + let r = crate::text_field::TextField::singleline(widget, text).hint(crate::i18n::tr(hint)).width(f32::INFINITY).select_on_focus(true).show(ui); + // (and takes it back when nothing has it: after a click on the dialog's background or a check box, + // or when Return gave it up on a refusal; a control Tab reached keeps it). A disabled dialog (a + // prompt or the blocking library window owns input) must not request the focus at all: egui's + // text edit would otherwise keep editing the draft from host text behind that window. + if ui.is_enabled() && (just_opened(ui, widget) || (!r.editing && r.ending.is_none() && ui.memory(|m| m.focused().is_none()))) { + r.response.request_focus(); + } + r.ending == Some(crate::text_field::Ending::Return) +} + +/// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just +/// opened (to give its first field the focus once). +fn just_opened(ui: &egui::Ui, key: &str) -> bool { + let id = egui::Id::unique(("dialog-shown", key)); + let pass = ui.ctx().cumulative_pass_nr(); + let last: Option = ui.data_mut(|d| d.get_temp(id)); + ui.data_mut(|d| d.insert_temp(id, pass)); + last.and_then(|l| l.checked_add(1)) != Some(pass) +} + +#[cfg(test)] +mod watermark_position_tests { + use super::WM_POSITIONS; + use lightcraft_engine::export::Anchor; + + #[test] + fn export_dialog_offers_every_rendered_anchor_exactly_once() { + let anchors = [ + Anchor::TopLeft, + Anchor::Top, + Anchor::TopRight, + Anchor::Left, + Anchor::Center, + Anchor::Right, + Anchor::BottomLeft, + Anchor::Bottom, + Anchor::BottomRight, + ]; + assert_eq!(WM_POSITIONS.len(), anchors.len()); + for anchor in anchors { + assert_eq!(WM_POSITIONS.iter().filter(|(position, _)| *position == anchor).count(), 1); + } + } +} + +/// How a dialog's confirm button looks: [`ConfirmStyle::Primary`] (the accent's fill) when it +/// makes or brings in something, plain when it deletes or removes (never the eye-catching +/// default) or when the dialog only shows something (its Close). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ConfirmStyle { + Primary, + Plain, +} + +pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle { + match dlg { + Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } => { + ConfirmStyle::Plain + } + _ if only_shows(dlg) => ConfirmStyle::Plain, + _ => ConfirmStyle::Primary, + } +} + +/// A dialog that only shows something: one Close, nothing to confirm or cancel. (Synchronize +/// Folder is one when its folder turned out up to date.) +fn only_shows(dlg: &Dialog) -> bool { + matches!( + dlg, + Dialog::About + | Dialog::Shortcuts + | Dialog::Settings { .. } + | Dialog::SystemInfo { .. } + | Dialog::AllMetadata { .. } + | Dialog::WhatsNew + | Dialog::ManageEffects { .. } + | Dialog::ViewOptions + ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date()) +} + +#[cfg(test)] +mod gap_tests { + use super::{fmt_gap, parse_gap}; + + #[test] + fn gap_text_reads_back_what_it_shows() { + for v in [0.0, 1.0, 12.0, 59.0, 60.0, 90.0, 600.0, 3599.0, 3600.0, 3601.0, 3661.0, 3900.0, 7325.0, 86340.0, 86399.0] { + assert_eq!(parse_gap(&fmt_gap(v)), Some(v), "{}", fmt_gap(v)); + } + assert_eq!(parse_gap("1 day"), Some(86400.0)); + assert_eq!(parse_gap("45"), Some(45.0)); + assert_eq!(parse_gap(" 45s "), Some(45.0)); + assert_eq!(parse_gap("2min 5s"), Some(125.0)); + for bad in ["", "abc", "5 parsecs", "NaN", "1 min x"] { + assert_eq!(parse_gap(bad), None, "{bad:?}"); + } + // a day reads back in the UI language too ("1 Tag") + crate::i18n::set_language(crate::i18n::Locale::De); + let shown = fmt_gap(86400.0); + let back = parse_gap(&shown); + crate::i18n::set_language(crate::i18n::Locale::En); + assert_eq!((shown.as_str(), back), ("1 Tag", Some(86400.0))); + } + + #[test] + fn gaps_past_the_slider_read_back_too() { + // the Assisted Culling slider drags to 10 min; its value field takes up to a day + for (v, text) in [(1800.0, "30 min"), (5400.0, "1 h 30 min"), (3601.0, "1 h 0 min 1 s"), (86400.0, "1 day")] { + assert_eq!(fmt_gap(v), text); + assert_eq!(parse_gap(text), Some(v), "{text}"); + } + assert_eq!(parse_gap("1800"), Some(1800.0)); + assert_eq!(parse_gap("0"), Some(0.0)); + } +} + +#[cfg(test)] +mod cull_dialog_tests { + use std::time::Duration; + + use serde_json::json; + + use super::{clamp_cull_burst, cull_params}; + use crate::headless::Headless; + use crate::state::Dialog; + use crate::{LightcraftApp, Services}; + + const T: Duration = Duration::from_secs(20); + + #[test] + fn typed_values_are_kept_within_what_photo_analyze_accepts() { + for (gap, sim) in [(0.0, 0.0), (1800.0, 1.0), (86400.0, 0.5), (0.5, 0.995)] { + let (mut g, mut s) = (gap, sim); + clamp_cull_burst(&mut g, &mut s); + assert_eq!((g, s), (gap, sim), "in range: kept as typed"); + } + for ((gap, sim), want) in [((-5.0, -0.1), (0.0, 0.0)), ((90000.0, 1.5), (86400.0, 1.0)), ((f32::NAN, f32::INFINITY), (10.0, 0.93))] { + let (mut g, mut s) = (gap, sim); + clamp_cull_burst(&mut g, &mut s); + assert_eq!((g, s), want); + } + assert_eq!(cull_params(0.0, true, 1800.0, 1.0), json!({"pickBest": true, "burstGap": 1800.0, "similarity": 1.0})); + assert_eq!(cull_params(20.0, false, 0.0, 0.7)["rejectBelow"], 20.0); + } + + /// Click the value field right of a slider registered as `id`, type `text`, Enter. + fn type_value(h: &mut Headless, id: &str, text: &str) { + let r = h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} not on screen")); + let spacing = h.view.ctx.global_style().spacing.clone(); + let x = r.left() + spacing.slider_width + spacing.item_spacing.x + 6.0; + assert_eq!(h.request("ui.click", json!({"x": x, "y": r.center().y}), T)["ok"], true); + h.step(); + for key in ["a", "Backspace"] { + assert_eq!(h.request("ui.key", json!({"key": key, "cmd": key == "a"}), T)["ok"], true); + } + assert_eq!(h.request("ui.text", json!({"text": text}), T)["ok"], true); + assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); + h.step(); + h.step(); + } + + fn burst(h: &Headless) -> (f32, f32) { + match &h.app.ui.dialog { + Some(Dialog::Cull { burst_gap, similarity, .. }) => (*burst_gap, *similarity), + d => panic!("{d:?}"), + } + } + + #[test] + fn the_culling_value_fields_take_values_past_the_sliders() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); + h.step(); + h.app.run("dialog.cull", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(burst(&h), (10.0, 0.93)); + // half an hour and "only identical shots": past the sliders' 10 min and 0.99 + type_value(&mut h, "field:cullGap", "30 min"); + type_value(&mut h, "field:cullSimilar", "1.0"); + assert_eq!(burst(&h), (1800.0, 1.0)); + // a day is as far as photo.analyze goes; more is held there + type_value(&mut h, "field:cullGap", "2 days"); + assert_eq!(burst(&h).0, 86400.0); + type_value(&mut h, "field:cullGap", "0"); + assert_eq!(burst(&h), (0.0, 1.0)); + type_value(&mut h, "field:cullGap", "1800"); + assert_eq!(burst(&h).0, 1800.0); + // a similarity between the slider's hundredths is kept to the thousandth + type_value(&mut h, "field:cullSimilar", "0.995"); + assert_eq!(burst(&h).1, 0.995); + type_value(&mut h, "field:cullSimilar", "0.9951"); + assert_eq!(burst(&h).1, 0.995); + type_value(&mut h, "field:cullSimilar", "1.0"); + assert_eq!(burst(&h).1, 1.0); + // OK hands them to photo.analyze as typed (it refuses values out of its range) + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); + assert_eq!(h.app.ui.cull_burst, Some((1800.0, 1.0))); + // and the next opening starts from them, not from the sliders' range + h.app.run("dialog.cull", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(burst(&h), (1800.0, 1.0)); + } +} diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 871a53d8263..933d7e9d0a1 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -249,11 +249,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ("lens", "lens", "Lens", f.lens.clone(), lenses), ("keyword", "keyword", "Keyword", f.keyword.clone(), keywords), ] { - let mut items = vec![(format!("Any {}", all_label.to_lowercase()), json!({key: Value::Null}), current.is_none())]; - items.extend(values.into_iter().map(|v| (v.clone(), json!({key: v.clone()}), current.as_deref() == Some(v.as_str())))); + // (the keyword picker puts the keywords chosen with Cmd+click in the sidebar aside, as a keyword set here) + let set = |v: Value| if key == "keyword" { json!({"keyword": v, "keywords": []}) } else { json!({key: v}) }; + let mut items = + vec![(format!("Any {}", all_label.to_lowercase()), set(Value::Null), current.is_none() && !(key == "keyword" && !f.keywords.is_empty()))]; + items.extend(values.into_iter().map(|v| (v.clone(), set(json!(v)), current.as_deref() == Some(v.as_str())))); let shown = current.clone().unwrap_or_else(|| all_label.to_string()); let shown = if shown.chars().count() > 22 { format!("{}…", shown.chars().take(21).collect::()) } else { shown }; - picker(app, ui, id, &shown, current.is_some(), items); + // (several keywords chosen in the sidebar filter the grid too: the picker is on, though it names none) + let on = current.is_some() || (key == "keyword" && !f.keywords.is_empty()); + picker(app, ui, id, &shown, on, items); } // save / clear diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index db4dfa1b83e..112aec4a859 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1404,7 +1404,9 @@ fn context_menu_albums(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) register(ui, "button:contextAddToAlbum", add.response.rect); } // in a (non-smart) album: take the selection out of it, or make this photo its cover + // (with several albums shown there is no telling which one is meant) if let lightcraft_engine::LibrarySource::Album(aid) = app.session.source + && app.session.also_albums.is_empty() && app.session.catalog.album(aid).is_some_and(|a| !a.folder && !a.is_smart()) { if ui.button(crate::i18n::tr("Remove from Album")).clicked() { diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 2da58c594ac..19c0a440db7 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -79,7 +79,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } let selection = app.session.selected(); let ticks = app.caches.keyword_ticks(&app.session.catalog, &selection); + app.ui.side.keyword_list.begin_frame(); for r in &rows { + app.ui.side.keyword_list.saw(r.path.clone()); row(app, ui, r, &selection, &ticks, filter.trim().is_empty()); } ui.add_space(12.0); @@ -95,6 +97,11 @@ pub(crate) fn follow(app: &mut LightcraftApp, from: &str, to: &str) { { app.ui.keyword_list_selected = Some(reparent(&k, from, &to)); } + for k in &mut app.ui.side.keyword_list_also { + if is_under(k, from) { + *k = reparent(k, from, &to); + } + } for o in &mut app.ui.keyword_list_open { if is_under(o, from) { *o = reparent(o, from, &to).to_lowercase(); @@ -175,10 +182,11 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId app.ui.dragging_keyword = Some(r.path.clone()); } drop_target(app, ui, rect, &r.path); - let picked = app.ui.keyword_list_selected.as_deref().is_some_and(|k| same(k, &r.path)); + let picked = super::side_select::list_is_picked(app, &r.path); let inner = Rect::from_min_max(rect.min + vec2(16.0, 0.0), rect.max - vec2(16.0, 0.0)); if picked { ui.painter().rect_filled(inner, 4.0, t.canvas); + register(ui, format!("keywordPicked:{}", r.path), inner); } else if resp.hovered() { ui.painter().rect_filled(inner, 4.0, t.hover.gamma_multiply(0.6)); } @@ -268,7 +276,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId } if ar.on_hover_text(crate::i18n::tr("Show Photos with Keyword")).clicked() { super::left::browse_all_photos(app, true); - let _ = app.run("library.filter", json!({"keyword": r.path})); + let _ = app.run("library.filter", json!({"keyword": r.path, "keywords": []})); } // the name, cut short before the arrow, leaving room for the dot and the + that follow it let is_default = app.session.catalog.default_keyword_parent().as_deref().is_some_and(|k| same(k, &r.path)); @@ -296,9 +304,10 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId } let resp = resp.on_hover_text(r.path.replace('|', " › ")); if resp.clicked() { - app.ui.keyword_list_selected = Some(r.path.clone()); + super::side_select::list_clicked(app, ui, &r.path); } - if resp.double_clicked() { + // (not with Cmd or Shift held: those clicks pick rows) + if resp.double_clicked() && ui.input(|i| !i.modifiers.command && !i.modifiers.shift) { app.ui.dialog = Some(edit_dialog(app, &r.path)); } crate::widgets::context_menu(&resp, |ui| menu(app, ui, &r.path, selection)); @@ -401,7 +410,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[Pho } if item(ui, "show", crate::i18n::tr("Show Photos with Keyword"), true) { super::left::browse_all_photos(app, true); - let _ = app.run("library.filter", json!({"keyword": path})); + let _ = app.run("library.filter", json!({"keyword": path, "keywords": []})); } ui.separator(); if item(ui, "purge", crate::i18n::tr("Purge Unused Keywords"), true) { @@ -590,7 +599,7 @@ impl Ticks { } /// The keyword is in the tree (any case). -fn in_tree(tree: &[KeywordNode], path: &str) -> bool { +pub(crate) fn in_tree(tree: &[KeywordNode], path: &str) -> bool { tree.iter().any(|n| same(&n.path, path) || (lightcraft_catalog::keywords::is_under(path, &n.path) && in_tree(&n.children, path))) } diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 4861d4c6fa7..3f41dcab640 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -159,7 +159,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, chip: &Chip) { } if item(ui, "show", crate::i18n::tr("Show Photos with Keyword")) { super::left::browse_all_photos(app, true); - let _ = app.run("library.filter", json!({"keyword": chip.path})); + let _ = app.run("library.filter", json!({"keyword": chip.path, "keywords": []})); } ui.separator(); if item(ui, "edit", crate::i18n::tr("Edit Keyword Tag…")) { diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs new file mode 100644 index 00000000000..30bb90942b5 --- /dev/null +++ b/crates/ui-egui/src/panels/side_select.rs @@ -0,0 +1,225 @@ +//! Several rows of a sidebar list chosen at once (Cmd/Ctrl+click, Shift+click): what the left +//! panel's Albums, Folders, Keywords and By Date and the right panel's Keyword List do with the +//! click. The rule for the click itself is [`crate::multi_select`]'s. +//! +//! What is chosen in a list of the left panel is what the grid shows, so it lives in the session +//! (`library.source`, `library.filter`); only the anchor for Shift+click is kept here. The +//! Keyword List's rows don't change the grid: its chosen rows are kept here. +//! +//! A plain click does what it always did. + +use lightcraft_catalog::AlbumId; +use lightcraft_catalog::keywords::same as same_keyword; +use lightcraft_engine::LibrarySource; +use serde_json::json; + +use crate::LightcraftApp; +use crate::multi_select::{Click, ListRows}; + +/// What the sidebars keep for choosing several rows. +#[derive(Clone, Debug, Default)] +pub struct SideState { + /// The library all of this is about (its generation): another library starts afresh. + library: Option, + /// The catalog revision the Keyword List's picks were last checked against. + picks_at: u64, + pub albums: ListRows, + pub folders: ListRows, + pub keywords: ListRows, + pub dates: ListRows, + pub keyword_list: ListRows, + /// The other keywords picked in the Keyword List beside `keyword_list_selected` (which is the + /// one picked last, the one Edit takes), in the order picked. + pub keyword_list_also: Vec, +} + +fn same_id(a: &u64, b: &u64) -> bool { + a == b +} +// (a list's keys are `String`s: these are passed where two keys are told alike) +#[allow(clippy::ptr_arg)] +fn same_date(a: &String, b: &String) -> bool { + a == b +} +#[allow(clippy::ptr_arg)] +fn same_kw(a: &String, b: &String) -> bool { + same_keyword(a, b) +} +#[allow(clippy::ptr_arg)] +fn same_dir(a: &String, b: &String) -> bool { + super::left::same_folder(a, b) +} + +fn how(ui: &egui::Ui) -> Click { + Click::of(ui.input(|i| i.modifiers)) +} + +/// Each frame, before the panels: a library that was switched forgets everything kept here (its +/// rows are another library's), and a keyword picked in the Keyword List that is gone is let go. +pub(crate) fn frame(app: &mut LightcraftApp) { + let library = app.session.library_generation(); + if app.ui.side.library != Some(library) { + app.ui.side = SideState { library: Some(library), ..Default::default() }; + } + // a keyword picked in the Keyword List that is gone since (deleted, merged away, undone) is + // not picked any more. Looked up in the cached keyword tree, once per change to the library + // and while keywords are picked: never a pass over the photos per frame. + let revision = app.session.catalog.revision; + if app.ui.side.picks_at != revision && (!app.ui.side.keyword_list_also.is_empty() || app.ui.keyword_list_selected.is_some()) { + let tree = app.caches.keyword_tree(&app.session.catalog); + let there = |k: &String| super::keyword_list::in_tree(&tree, k); + app.ui.side.keyword_list_also.retain(there); + if app.ui.keyword_list_selected.as_ref().is_some_and(|k| !there(k)) { + app.ui.keyword_list_selected = app.ui.side.keyword_list_also.pop(); + } + } + app.ui.side.picks_at = revision; +} + +/// A new frame of the left panel: the rows of the last one are what a click now is on. +pub(crate) fn begin_left(app: &mut LightcraftApp) { + let s = &mut app.ui.side; + s.albums.begin_frame(); + s.folders.begin_frame(); + s.keywords.begin_frame(); + s.dates.begin_frame(); +} + +// ---- Albums + +/// Whether album `id` is one the grid shows the photos of. +pub(crate) fn album_shown(app: &LightcraftApp, id: AlbumId) -> bool { + app.session.source == LibrarySource::Album(id) || (matches!(app.session.source, LibrarySource::Album(_)) && app.session.also_albums.contains(&id)) +} + +fn albums_shown(app: &LightcraftApp) -> Vec { + app.session.source_albums().iter().map(|a| a.0).collect() +} + +/// A click on the row of album `id`: it is shown alone, or with Cmd/Ctrl or Shift beside the +/// others chosen. +pub(crate) fn album_clicked(app: &mut LightcraftApp, ui: &egui::Ui, id: AlbumId) { + let chosen = albums_shown(app); + let how = how(ui); + let keys = app.ui.side.albums.click(&chosen, &id.0, how, &same_id); + show_albums(app, &keys); +} + +/// Show these albums (none: All Photos). +fn show_albums(app: &mut LightcraftApp, ids: &[u64]) { + match ids { + [] => app.act("library.source", json!({"kind": "all"})), + [one] => app.act("library.source", json!({"kind": "album", "id": one})), + many => app.act("library.source", json!({"kind": "album", "ids": many})), + }; +} + +// ---- Folders (of the library) + +/// Whether the library folder `path` is one the grid shows the photos of. +pub(crate) fn folder_shown(app: &LightcraftApp, path: &str) -> bool { + app.session.source == LibrarySource::LibraryFolder + && (app.session.library_folder.as_deref().is_some_and(|f| super::left::same_folder(f, path)) + || app.session.also_library_folders.iter().any(|f| super::left::same_folder(f, path))) +} + +/// A click on the row of library folder `path`. +pub(crate) fn folder_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str) { + let chosen = app.session.source_library_folders(); + let how = how(ui); + let keys = app.ui.side.folders.click(&chosen, &path.to_string(), how, &same_dir); + match keys.as_slice() { + [] => app.act("library.source", json!({"kind": "all"})), + // a source like an album or a Local folder: it replaces what the grid showed + [one] => app.act("library.source", json!({"kind": "libraryFolder", "path": one})), + many => app.act("library.source", json!({"kind": "libraryFolder", "paths": many})), + }; +} + +// ---- Keywords and By Date (filters) + +/// Whether keyword `path` is one the grid is filtered by. +pub(crate) fn keyword_shown(app: &LightcraftApp, path: &str) -> bool { + let f = &app.session.filter; + f.keyword.iter().chain(&f.keywords).any(|k| same_keyword(k, path)) +} + +/// A click on the Keywords row `path`: the grid shows the photos with it (again: every photo), +/// or with Cmd/Ctrl or Shift the photos with any of the keywords chosen. +pub(crate) fn keyword_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str) { + let chosen = app.session.filter.keywords_wanted(); + let how = how(ui); + // a plain click on the one keyword shown clears it, as it always did + let clears = how == Click::Plain && chosen.len() == 1 && chosen.iter().any(|k| same_keyword(k, path)); + let keys = if clears { + app.ui.side.keywords.anchor = None; + Vec::new() + } else { + app.ui.side.keywords.click(&chosen, &path.to_string(), how, &same_kw) + }; + // (All Photos first, then the filter: the order a plain click always had) + super::left::browse_all_photos(app, !keys.is_empty()); + match keys.as_slice() { + [] => app.act("library.filter", json!({"keyword": null, "keywords": []})), + [one] => app.act("library.filter", json!({"keyword": one, "keywords": []})), + many => app.act("library.filter", json!({"keyword": null, "keywords": many})), + }; +} + +/// Whether the By Date row `key` is one the grid is filtered by. +pub(crate) fn date_shown(app: &LightcraftApp, key: &str) -> bool { + let f = &app.session.filter; + f.date.iter().chain(&f.dates).any(|d| d == key) +} + +/// A click on the By Date row `key`, like [`keyword_clicked`]. +pub(crate) fn date_clicked(app: &mut LightcraftApp, ui: &egui::Ui, key: &str) { + let chosen = app.session.filter.dates_wanted(); + let how = how(ui); + let clears = how == Click::Plain && chosen.len() == 1 && chosen.iter().any(|d| d == key); + let keys = if clears { + app.ui.side.dates.anchor = None; + Vec::new() + } else { + app.ui.side.dates.click(&chosen, &key.to_string(), how, &same_date) + }; + super::left::browse_all_photos(app, !keys.is_empty()); + match keys.as_slice() { + [] => app.act("library.filter", json!({"date": null, "dates": []})), + [one] => app.act("library.filter", json!({"date": one, "dates": []})), + many => app.act("library.filter", json!({"date": null, "dates": many})), + }; +} + +// ---- The Keyword List (right panel) + +/// The keywords picked in the Keyword List, in the order picked (the last is the one Edit takes). +pub(crate) fn list_picked(app: &LightcraftApp) -> Vec { + let mut out: Vec = Vec::new(); + // (those that are gone, deleted or merged away, were let go of by `frame`) + for k in app.ui.side.keyword_list_also.iter().chain(&app.ui.keyword_list_selected) { + if !out.iter().any(|o| same_keyword(o, k)) { + out.push(k.clone()); + } + } + out +} + +/// Whether `path` is picked in the Keyword List. +pub(crate) fn list_is_picked(app: &LightcraftApp, path: &str) -> bool { + app.ui.keyword_list_selected.iter().chain(&app.ui.side.keyword_list_also).any(|k| same_keyword(k, path)) +} + +/// Pick these keywords in the Keyword List (the last is the one Edit takes). +pub(crate) fn list_pick(app: &mut LightcraftApp, mut keys: Vec) { + app.ui.keyword_list_selected = keys.pop(); + app.ui.side.keyword_list_also = keys; +} + +/// A click on the Keyword List's row `path`. +pub(crate) fn list_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str) { + let chosen = list_picked(app); + let how = how(ui); + let keys = app.ui.side.keyword_list.click(&chosen, &path.to_string(), how, &same_kw); + list_pick(app, keys); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 37a8c2d4bb8..c944e435132 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -318,6 +318,10 @@ pub struct UiState { /// A keyword being dragged in the Keyword List (onto another to nest it). #[serde(skip)] pub dragging_keyword: Option, + /// Choosing several rows of a sidebar list: the rows drawn and the anchor of each list, and + /// the other keywords picked in the Keyword List. + #[serde(skip)] + pub side: crate::panels::side_select::SideState, /// A running slideshow (full screen; see [`crate::panels::slideshow`]). #[serde(skip)] pub slideshow: Option>, @@ -507,6 +511,7 @@ impl Default for UiState { keyword_list_open: Vec::new(), keyword_list_selected: None, dragging_keyword: None, + side: Default::default(), info_overlay: InfoOverlay::Off, brief_info: BriefInfo::default(), layout_image: LayoutImage::default(), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index f801ee843f2..750d38d9ff9 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -66,6 +66,7 @@ mod menubar; mod merge_preview; mod missing_sweep; mod move_folder; +mod multi_select; mod offline; mod open_lightroom; pub(super) mod panels; diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs new file mode 100644 index 00000000000..d55e8c1e33c --- /dev/null +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -0,0 +1,387 @@ +//! Several rows of a sidebar list chosen at once, driven through the control channel: Cmd/Ctrl+click +//! and Shift+click in the left panel's Albums, Folders, Keywords and By Date and in the right +//! panel's Keyword List. +//! +//! Scenarios: +//! - Given albums in the sidebar, when two are Cmd+clicked, then both are highlighted and the +//! grid shows the photos of either; Cmd+click on one of them takes it away again. +//! - When one album is clicked and another Shift+clicked, then every album between them is +//! chosen, but none inside a closed folder; a plain click chooses one alone again. +//! - Keywords and dates in the left panel: Cmd+click filters by any of those chosen; a plain +//! click on the one keyword shown still clears it. +//! - Folders: Cmd+click shows the photos of both folders; Shift+click takes those between. +//! - The Keyword List: Cmd+click and Shift+click pick several, and picking never changes the grid. + +use std::time::Duration; + +use lightcraft_catalog::AlbumId; +use lightcraft_engine::LibrarySource; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// The demo library in the grid, the left panel open, in a window tall enough for every row. +fn app(right: &str) -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1500.0, 3000.0], 1.0); + ask(&mut h, "ui.set", json!({"view": "photoGrid", "leftPanel": true, "right": right})); + h +} + +fn ask(h: &mut Headless, method: &str, params: Value) { + let r = h.request(method, params.clone(), T); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + h.settle(SETTLE); +} + +fn run(h: &mut Headless, command: &str, params: Value) -> Value { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(SETTLE); + r["result"].clone() +} + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +fn click(h: &mut Headless, id: &str) { + ask(h, "ui.clickWidget", json!({"id": id})); +} +fn cmd_click(h: &mut Headless, id: &str) { + ask(h, "ui.clickWidget", json!({"id": id, "cmd": true})); +} +fn shift_click(h: &mut Headless, id: &str) { + ask(h, "ui.clickWidget", json!({"id": id, "shift": true})); +} + +/// An album called `name` holding `photos`. +fn album(h: &mut Headless, name: &str, parent: Option, photos: &[u64]) -> u64 { + let id = run(h, "album.create", json!({"name": name, "parent": parent}))["id"].as_u64().unwrap(); + if !photos.is_empty() { + run(h, "library.select", json!({"ids": photos})); + run(h, "album.addPhotos", json!({"id": id, "ids": photos})); + } + id +} + +fn row(id: u64) -> String { + format!("source:album:{id}") +} + +fn shown(h: &Headless) -> Vec { + h.app.session.source_albums().iter().map(|a| a.0).collect() +} + +fn visible(h: &mut Headless) -> Vec { + let mut v: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + v.sort_unstable(); + v +} + +/// Four albums `Sel A`…`Sel D`, each with one photo of its own (and A and C sharing one). +fn four_albums(h: &mut Headless) -> ([u64; 4], Vec) { + let ids: Vec = h.app.session.visible_cloned().iter().take(5).map(|p| p.0).collect(); + let a = album(h, "Sel A", None, &[ids[0], ids[4]]); + let b = album(h, "Sel B", None, &[ids[1]]); + let c = album(h, "Sel C", None, &[ids[2], ids[4]]); + let d = album(h, "Sel D", None, &[ids[3]]); + ([a, b, c, d], ids) +} + +#[test] +fn cmd_click_shows_several_albums_and_takes_one_away_again() { + let mut h = app("info"); + let ([a, _, c, _], ids) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + assert_eq!(shown(&h), vec![a, c]); + let mut want = vec![ids[0], ids[2], ids[4]]; + want.sort_unstable(); + assert_eq!(visible(&mut h), want, "the photos of either, each once"); + assert!(has(&h, &format!("highlight:album:{a}")) && has(&h, &format!("highlight:album:{c}")), "both rows are highlighted"); + assert_eq!(crate::i18n::source_title(&h.app.session), "2 albums", "the title says how many are shown"); + // Cmd+click on one of them takes it away… + cmd_click(&mut h, &row(a)); + assert_eq!(shown(&h), vec![c]); + assert!(!has(&h, &format!("highlight:album:{a}"))); + // …and on the last one too: back to every photo + cmd_click(&mut h, &row(c)); + assert_eq!(h.app.session.source, LibrarySource::All); +} + +#[test] +fn shift_click_takes_the_albums_between_and_a_plain_click_one_alone() { + let mut h = app("info"); + let ([a, b, c, d], _) = four_albums(&mut h); + click(&mut h, &row(a)); + shift_click(&mut h, &row(c)); + assert_eq!(shown(&h), vec![a, b, c], "the row clicked is the last chosen"); + assert_eq!(h.app.session.source, LibrarySource::Album(AlbumId(c))); + // a second Shift+click from the same row replaces the range + shift_click(&mut h, &row(b)); + assert_eq!(shown(&h), vec![a, b]); + // upwards, from another row + click(&mut h, &row(d)); + shift_click(&mut h, &row(b)); + assert_eq!(shown(&h), vec![d, c, b]); + // Cmd+Shift adds a range to what is chosen + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + ask(&mut h, "ui.clickWidget", json!({"id": row(d), "cmd": true, "shift": true})); + assert_eq!(shown(&h), vec![a, c, d]); + // a plain click on one of several chosen: that one alone + click(&mut h, &row(c)); + assert_eq!(shown(&h), vec![c]); +} + +#[test] +fn shift_click_does_not_take_albums_inside_a_closed_folder() { + let mut h = app("info"); + let ids: Vec = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + // folders are listed first: Sel E (open, with Sel A), Sel Folder (closed, with Sel Inside), then Sel Z + let outer = run(&mut h, "album.create", json!({"name": "Sel E", "folder": true}))["id"].as_u64().unwrap(); + let before = album(&mut h, "Sel A", Some(outer), &[ids[0]]); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + let inside = album(&mut h, "Sel Inside", Some(folder), &[ids[0]]); + let after = album(&mut h, "Sel Z", None, &[ids[1]]); + assert!(has(&h, &row(inside)), "a folder starts open"); + click(&mut h, &format!("albumToggle:{folder}")); + assert!(!has(&h, &row(inside)), "closed"); + click(&mut h, &row(before)); + shift_click(&mut h, &row(after)); + let chosen = shown(&h); + assert!(chosen.contains(&before) && chosen.contains(&after), "{chosen:?}"); + assert!(!chosen.contains(&inside), "a row that is not in sight is not taken: {chosen:?}"); +} + +#[test] +fn cmd_click_filters_by_any_of_several_keywords() { + let mut h = app("info"); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + run(&mut h, "library.select", json!({"ids": [ids[0]]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "addKeywords": ["Sel One"]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "addKeywords": ["Sel Two"]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[2]], "addKeywords": ["Sel Three"]})); + click(&mut h, "source:keyword:Sel One"); + assert_eq!(h.app.session.filter.keyword.as_deref(), Some("Sel One"), "a plain click is what it was"); + cmd_click(&mut h, "source:keyword:Sel Two"); + assert_eq!(h.app.session.filter.keywords, vec!["Sel One".to_string(), "Sel Two".to_string()]); + assert_eq!(h.app.session.filter.keyword, None); + assert_eq!(visible(&mut h), { + let mut v = vec![ids[0], ids[1]]; + v.sort_unstable(); + v + }); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + // a plain click: that keyword alone; again: every photo + click(&mut h, "source:keyword:Sel Two"); + assert_eq!((h.app.session.filter.keyword.as_deref(), h.app.session.filter.keywords.len()), (Some("Sel Two"), 0)); + click(&mut h, "source:keyword:Sel Two"); + assert_eq!(h.app.session.filter, lightcraft_catalog::Filter::default()); +} + +#[test] +fn cmd_click_filters_by_any_of_several_dates() { + let mut h = app("info"); + // the months of the demo library's first year + let year: String = h.app.widgets.iter().find_map(|(w, _)| w.strip_prefix("source:date:").map(str::to_string)).expect("a year"); + click(&mut h, &format!("dateToggle:{year}")); + let years: Vec = + h.app.widgets.iter().filter_map(|(w, _)| w.strip_prefix("source:date:").filter(|k| k.len() == 7).map(str::to_string)).collect(); + assert!(years.len() >= 2, "the demo library spans months: {years:?}"); + let all = h.app.session.visible().len(); + click(&mut h, &format!("source:date:{}", years[0])); + let first = h.app.session.visible().len(); + cmd_click(&mut h, &format!("source:date:{}", years[1])); + assert_eq!(h.app.session.filter.dates, vec![years[0].clone(), years[1].clone()]); + let both = h.app.session.visible().len(); + assert!(both > first && both <= all, "{first} then {both} of {all}"); + cmd_click(&mut h, &format!("source:date:{}", years[0])); + assert_eq!((h.app.session.filter.date.as_deref(), h.app.session.filter.dates.len()), (Some(years[1].as_str()), 0)); +} + +/// A library of file-backed photos that exist only in the catalog. +fn folders_app(paths: &[&str]) -> Headless { + use lightcraft_catalog::{Op, Photo, Source}; + let mut session = lightcraft_engine::Session::new(); + for path in paths { + let id = session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: (*path).into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1500.0, 2000.0], 1.0); + ask(&mut h, "ui.set", json!({"view": "photoGrid", "leftPanel": true})); + h +} + +#[test] +fn cmd_click_shows_several_folders_and_shift_click_takes_those_between() { + let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg", "/pics/work/d.jpg"]); + click(&mut h, "libraryFolderToggle:/pics"); + click(&mut h, "source:libfolder:/pics/trip"); + cmd_click(&mut h, "source:libfolder:/pics/work"); + assert_eq!(h.app.session.source_library_folders(), vec!["/pics/trip".to_string(), "/pics/work".to_string()]); + assert_eq!(h.app.session.visible().len(), 3); + assert_eq!(crate::i18n::source_title(&h.app.session), "2 folders", "the title says how many are shown"); + assert!(has(&h, "highlight:libfolder:/pics/trip") && has(&h, "highlight:libfolder:/pics/work")); + // Shift+click takes the folders between, as drawn + click(&mut h, "source:all"); + let rows: Vec = h.app.widgets.iter().filter_map(|(w, _)| w.strip_prefix("source:libfolder:/pics/").map(str::to_string)).collect(); + assert_eq!(rows.len(), 3, "{rows:?}"); + click(&mut h, &format!("source:libfolder:/pics/{}", rows[0])); + shift_click(&mut h, &format!("source:libfolder:/pics/{}", rows[2])); + assert_eq!(h.app.session.source_library_folders().len(), 3); +} + +/// The Keyword List with three keywords of its own on the first photos, at the top level: +/// `Sel K1`, `Sel K2`, `Sel K3`, and an empty `Sel Parent`. +fn keyword_list() -> (Headless, Vec) { + let mut h = app("keywords"); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + run(&mut h, "library.select", json!({"ids": [ids[0]]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "addKeywords": ["Sel K1", "Sel K2"]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "addKeywords": ["Sel K2", "Sel K3"]})); + run(&mut h, "keyword.create", json!({"name": "Sel Parent"})); + // only these in the list: every row is on screen + ask(&mut h, "ui.clickWidget", json!({"id": "field:keywordFilter"})); + ask(&mut h, "ui.text", json!({"text": "Sel "})); + assert!(has(&h, "keywordRow:Sel K1") && has(&h, "keywordRow:Sel Parent")); + (h, ids) +} + +fn picked(h: &Headless) -> Vec { + crate::panels::side_select::list_picked(&h.app) +} + +#[test] +fn the_keyword_list_picks_several_with_cmd_and_shift() { + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + assert_eq!(picked(&h), vec!["Sel K1"]); + cmd_click(&mut h, "keywordRow:Sel K3"); + assert_eq!(picked(&h), vec!["Sel K1", "Sel K3"]); + assert_eq!(h.app.ui.keyword_list_selected.as_deref(), Some("Sel K3"), "the last picked is the one Edit takes"); + assert!(has(&h, "keywordPicked:Sel K1") && has(&h, "keywordPicked:Sel K3") && !has(&h, "keywordPicked:Sel K2")); + cmd_click(&mut h, "keywordRow:Sel K1"); + assert_eq!(picked(&h), vec!["Sel K3"]); + click(&mut h, "keywordRow:Sel K1"); + shift_click(&mut h, "keywordRow:Sel K3"); + assert_eq!(picked(&h), vec!["Sel K1", "Sel K2", "Sel K3"]); + // picking never changes what the grid shows + assert_eq!(h.app.session.filter, lightcraft_catalog::Filter::default()); +} + +/// A range starts from a row that is chosen: not from an album clicked before All Photos was shown. +#[test] +fn shift_click_does_not_start_from_an_album_that_is_no_longer_shown() { + let mut h = app("info"); + let ([a, _, c, d], _) = four_albums(&mut h); + click(&mut h, &row(a)); + click(&mut h, "source:all"); + shift_click(&mut h, &row(d)); + assert_eq!(shown(&h), vec![d], "nothing was chosen: the row alone"); + // chosen by a command, not a click: the range starts from it + run(&mut h, "library.source", json!({"kind": "album", "id": c})); + shift_click(&mut h, &row(a)); + assert_eq!(shown(&h).first(), Some(&c)); + assert_eq!(shown(&h).last(), Some(&a)); + assert_eq!(shown(&h).len(), 3); +} + +/// Showing one keyword from the Keyword List puts the ones chosen in the sidebar aside: the grid +/// is that keyword's, not those and this one. +#[test] +fn showing_a_keyword_from_the_keyword_list_replaces_the_keywords_chosen_in_the_sidebar() { + let (mut h, _) = keyword_list(); + click(&mut h, "source:keyword:Sel K1"); + cmd_click(&mut h, "source:keyword:Sel K2"); + assert_eq!(h.app.session.filter.keywords_wanted(), vec!["Sel K1".to_string(), "Sel K2".to_string()]); + click(&mut h, "keywordShow:Sel K3"); + assert_eq!(h.app.session.filter.keywords_wanted(), vec!["Sel K3".to_string()]); +} + +/// A keyword that is gone is not picked any more. +#[test] +fn a_keyword_that_is_gone_is_not_picked_any_more() { + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K3"); + run(&mut h, "keyword.delete", json!({"keyword": "Sel K3"})); + assert_eq!(picked(&h), vec!["Sel K1"]); + // one that was picked earlier is let go of too + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K3"); + run(&mut h, "keyword.delete", json!({"keyword": "Sel K1"})); + assert_eq!(picked(&h), vec!["Sel K3"]); + // and a keyword deleted while it was the only one picked does not come back with the next click + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + run(&mut h, "keyword.delete", json!({"keyword": "Sel K1"})); + cmd_click(&mut h, "keywordRow:Sel K2"); + assert_eq!(picked(&h), vec!["Sel K2"]); +} + +/// With several albums shown there is no telling which one Delete means: it is the photos' Delete +/// (which asks), and Photo ▸ Remove from Album is not on offer; no photo leaves the album chosen last. +#[test] +fn delete_with_several_albums_shown_does_not_take_a_photo_out_of_the_one_chosen_last() { + let mut h = app("info"); + let ([a, _, c, _], ids) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + assert!(!crate::menubar::in_normal_album(&h.app), "Remove from Album is not on offer for several albums"); + // a photo that is in A and in C (the one chosen last) + run(&mut h, "library.select", json!({"ids": [ids[4]]})); + ask(&mut h, "ui.key", json!({"key": "Delete"})); + assert_eq!(h.app.ui.dialog, Some(Dialog::ConfirmDelete { count: 1 }), "the photos' Delete asks"); + assert_eq!(h.app.session.catalog.album_count(AlbumId(a)), 2); + assert_eq!(h.app.session.catalog.album_count(AlbumId(c)), 2); +} + +/// Another library's rows are not what was chosen in this one. +#[test] +fn what_was_chosen_is_forgotten_when_another_library_opens() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let mut h = app("keywords"); + let ([a, _, c, _], _) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + assert!(h.app.ui.side.albums.anchor.is_some()); + let dir = Scratch(std::env::temp_dir().join(format!("lc-multi-select-switch-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + h.app.session.open_library(&dir.0, false).unwrap(); + h.settle(SETTLE); + assert!(h.app.ui.side.albums.anchor.is_none()); +} + +/// "Show in Library" after a Lightroom import shows every photo: keywords chosen in the +/// sidebar with Cmd+click are not left in the filter (dates go the same way: both lists are omitted from the default filter's JSON). +#[test] +fn show_in_library_clears_keywords_chosen_with_cmd_click() { + let mut h = app("info"); + let ids: Vec = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect(); + run(&mut h, "photo.setMeta", json!({"ids": [ids[0]], "addKeywords": ["Sel One"]})); + run(&mut h, "photo.setMeta", json!({"ids": [ids[1]], "addKeywords": ["Sel Two"]})); + click(&mut h, "source:keyword:Sel One"); + cmd_click(&mut h, "source:keyword:Sel Two"); + assert_eq!(h.app.session.filter.keywords.len(), 2); + h.app.ui.dialog = Some(Dialog::LightroomResult { summary: "done".into(), library: None, details: vec![], first: Some(ids[0]) }); + h.settle(SETTLE); + click(&mut h, "button:dialogOk"); + assert_eq!(h.app.session.filter, lightcraft_catalog::Filter::default()); + assert_eq!(h.app.session.selection.active.map(|p| p.0), Some(ids[0])); +} diff --git a/docs/gaps.md b/docs/gaps.md index 71861fb0e50..e2af2926f06 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,7 +45,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | -| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): the albums, folders, keywords and dates sidebars show one entry at a time. Cmd/Ctrl+click and Shift+click to show several at once are not wired to `library.source` (`ids`, `paths`) and `library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), which agents already use | `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ for the engine part | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | +| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars (`library.source` `ids`/`paths`, `library.filter` `keywords`/`dates`). The menus, drags and Delete key of those sidebars still act on one row | `crates/ui-egui/src/panels/side_select.rs`, `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ for the clicks | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -196,3 +196,4 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-20 | minor | Opt-in Windows DirectComposition preference added; VRR hardware verification pending; parity counts unchanged | | 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged | | 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) | +| 2026-10-26 | minor | Gap 31 narrows: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars; menus, drags and Delete for several rows remain | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ca828f06212..cf601ab7367 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -459,7 +459,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs` | photos in the grid; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter, each photo shown once (the sidebars' Cmd/Ctrl+click and Shift+click that use it are a later change); with Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/ui-egui/src/multi_select.rs`, `crates/ui-egui/src/panels/side_select.rs`, `crates/ui-egui/src/tests/multi_select.rs`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs` | photos in the grid; in the sidebars Cmd/Ctrl+click adds a row of Albums, Folders, Keywords or By Date or takes it away and Shift+click takes the rows between (as drawn: none inside a closed level), and the grid shows the photos of any of them, each once; the Keyword List picks several keywords the same way; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter (menus, drags and Delete for several rows are a later change); `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; with Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -1052,3 +1052,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | | 2026-10-21 | minor | LR-BEHAV-MULTISELECT: `library.source` takes several albums (`ids`) or folders (`paths`) and `library.filter` several keywords, dates, folders or albums, each photo shown once; `album.setRules` with `replace` keeps a smart album's album and folders; statuses unchanged | | 2026-11-03 | patch | LR-BEHAV-MULTISELECT: a view whose filter names a smart album can't be saved as smart-album rules, and New Smart Album from Filter… is grayed out saying which album it is (a smart album's rules can't test another one); `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does; deleting an album or a folder drops the filter put aside by Enable Filters when only the rating operator is left of it, and deleting a shown album moves the active photo into what is left; Hold View of several albums with a smart album among them is documented as it behaves (a photo stays only while one of them has it); statuses unchanged | +| 2026-10-26 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and several keywords in the Keyword List; menus, drags and Delete for several rows still to come; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 9e86af7a06a..24ea1d56fa5 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -337,6 +337,19 @@ 1200–1500-point-wide window on a Retina display. +## 2026-10-26 + +### Choose several albums, folders, keywords or dates in the sidebars +- In the left panel, Cmd+click (Ctrl+click on Windows and Linux) adds an album, a folder, a keyword or a date to the + ones chosen, or takes it away; Shift+click takes every row between the last one clicked and this one, except rows + inside a folder that is closed. The grid shows the photos of any of them, each once, and the title says how many + albums or folders are shown. A plain click chooses one row alone, as before. +- In the Keyword List (right panel, Keywords) the same clicks pick several keywords. Picking does not change the grid. +- With several albums shown, Remove from Album is not offered and the Delete key is the photos' Delete (it asks first + while Settings ▸ Confirm before moving photos to Recently Deleted is on), because there is no telling which album is meant. +- Menus, dragging, the Keyword List's − button and Delete still act on one row; choosing several rows for those + comes in a later change. + ## 2026-10-24 ### AI Denoise follows the photo's real noise From 2a31e8d4719eff3746bb4bd4b6d52221ed428090 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 18:54:32 -0400 Subject: [PATCH 29/55] LR-BEHAV-MULTISELECT: What's New says Delete once, not among the actions that still act on one row --- docs/whats-new.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index 24ea1d56fa5..aa90a924f92 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -347,8 +347,8 @@ - In the Keyword List (right panel, Keywords) the same clicks pick several keywords. Picking does not change the grid. - With several albums shown, Remove from Album is not offered and the Delete key is the photos' Delete (it asks first while Settings ▸ Confirm before moving photos to Recently Deleted is on), because there is no telling which album is meant. -- Menus, dragging, the Keyword List's − button and Delete still act on one row; choosing several rows for those - comes in a later change. +- Menus, dragging and the Keyword List's − button still act on one row; choosing several rows for those comes in a + later change. When several albums are shown, Delete stays the photos' Delete, as above. ## 2026-10-24 From 102a4f2d38eb9b3d2da003cda3e9a3bdc7adf737 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 19:02:31 -0400 Subject: [PATCH 30/55] LR-BEHAV-MULTISELECT: Show in Library clears albums and folders in the filter too; the smart-album editor counts every folder the album was made from Both findings are CodeRabbit's on the chain. The reset patch of Show in Library left out the empty lists `albums` and `libraryFolders`, which the default filter omits from its JSON, so they stayed in the filter. The rule editor's live count passed only the first folder of an album made from a view of several folders. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 464 +++++++++++++++++++++++ crates/ui-egui/src/panels/dialogs.rs | 12 +- crates/ui-egui/src/tests/multi_select.rs | 33 ++ 3 files changed, 506 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 54312c2a2cf..a8d3f91d108 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -735,3 +735,467 @@ pub struct Caches { /// What the grid did on its frames (benchmarks and tests check unchanged frames stay cheap). pub grid_stats: panels::grid::GridStats, } + +/// The left panel's counts. +#[derive(Clone, Copy, Debug, Default)] +pub struct LibraryCounts { + pub total: usize, + pub picks: usize, + pub deleted: usize, +} + +/// The values the filter bar's pickers offer. +#[derive(Clone, Debug, Default)] +pub struct FilterValues { + pub cameras: Vec, + pub lenses: Vec, + pub keywords: Vec, +} + +/// What the smart-album rule dialog shows besides the rules themselves: their problems (each row +/// marks its own), how many photos they match and the albums an Album rule picks from. +pub struct RulesView { + pub problems: Vec, + pub count: usize, + pub albums: Vec, +} + +pub(crate) fn key_of(parts: impl std::hash::Hash) -> u64 { + use std::hash::{BuildHasher, BuildHasherDefault, DefaultHasher}; + BuildHasherDefault::::default().hash_one(parts) +} + +/// Whether a tally of the library made when the catalog was at `revision` is still right, given that it reads only +/// `reads` of a photo: nothing changed since, or only other things of some photos did (a rating changes no folder's +/// count, a slider changes none at all). Each of these tallies asks every photo, so one kept is a pass over the +/// library saved on every edit. +fn still_right(cat: &lightcraft_catalog::Catalog, revision: u64, reads: lightcraft_catalog::Aspects) -> bool { + revision == cat.revision || cat.aspects_since(revision).is_some_and(|changed| !changed.any_of(reads)) +} + +/// What the tallies below read of a photo, besides whether it is in the library. +const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FILE); +const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); +const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); +const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); +const READS_FLAG: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FLAG); + +impl Caches { + /// The folders the library's photos were imported from. + pub fn folder_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { + let kept = self.folder_tree.take().filter(|(r, _)| still_right(cat, *r, READS_FILE)).map(|(_, t)| t); + let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.folder_tree())); + self.folder_tree = Some((cat.revision, t.clone())); + t + } + /// The folder tree as last built, when it still holds (a read-only check cannot rebuild it). + pub(crate) fn folder_tree_if_fresh(&self, cat: &lightcraft_catalog::Catalog) -> Option>> { + self.folder_tree.as_ref().filter(|(r, _)| still_right(cat, *r, READS_FILE)).map(|(_, t)| t.clone()) + } + /// The library's keyword tree. + pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { + let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); + let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); + self.keyword_tree = Some((cat.revision, t.clone())); + t + } + /// The Keywording box's read-only names for the selection: what exported files carry + /// (`export`), or the keywords with those containing them. + pub(crate) fn keyword_names( + &mut self, + cat: &lightcraft_catalog::Catalog, + selection: &[lightcraft_catalog::PhotoId], + export: bool, + ) -> std::sync::Arc> { + let key = key_of((selection, export)); + match &self.keyword_names { + Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), + _ => { + let c = std::sync::Arc::new(if export { + panels::keywording::will_export(cat, selection) + } else { + panels::keywording::with_containing(cat, selection) + }); + self.keyword_names = Some((cat.revision, key, c.clone())); + c + } + } + } + /// The selection's keywords (the Keywording box's chips). + pub(crate) fn keyword_chips( + &mut self, + cat: &lightcraft_catalog::Catalog, + selection: &[lightcraft_catalog::PhotoId], + ) -> std::sync::Arc> { + let key = key_of(selection); + match &self.keyword_chips { + Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), + _ => { + let c = std::sync::Arc::new(panels::keywording::chips(cat, selection)); + self.keyword_chips = Some((cat.revision, key, c.clone())); + c + } + } + } + /// How many photos the selection is: each once, those the library has (what the Keywording + /// box's "N of M" counts). + pub(crate) fn selected_photos(&mut self, cat: &lightcraft_catalog::Catalog, selection: &[lightcraft_catalog::PhotoId]) -> usize { + let key = key_of(selection); + match self.selected_photos { + Some((r, k, n)) if r == cat.revision && k == key => n, + _ => { + let n = panels::keywording::distinct(cat, selection).len(); + self.selected_photos = Some((cat.revision, key, n)); + n + } + } + } + /// The selection's keywords grouped by the keyword they are inside (the grouped Keywording box). + pub(crate) fn keyword_groups( + &mut self, + cat: &lightcraft_catalog::Catalog, + selection: &[lightcraft_catalog::PhotoId], + ) -> std::sync::Arc> { + let key = key_of(selection); + match &self.keyword_groups { + Some((r, k, g)) if *r == cat.revision && *k == key => g.clone(), + _ => { + let chips = self.keyword_chips(cat, selection); + let g = std::sync::Arc::new(panels::keywording::grouped(&chips)); + self.keyword_groups = Some((cat.revision, key, g.clone())); + g + } + } + } + /// How many selected photos have each keyword (the Keyword List's tick boxes). + pub(crate) fn keyword_ticks( + &mut self, + cat: &lightcraft_catalog::Catalog, + selection: &[lightcraft_catalog::PhotoId], + ) -> std::sync::Arc { + let key = key_of(selection); + match &self.keyword_ticks { + Some((r, k, t)) if *r == cat.revision && *k == key => t.clone(), + _ => { + let t = std::sync::Arc::new(panels::keyword_list::Ticks::of(cat, selection)); + self.keyword_ticks = Some((cat.revision, key, t.clone())); + t + } + } + } + /// The people named on faces among the photos the filter lets through (its own `person` aside), + /// with photo counts. + pub fn people( + &mut self, + cat: &lightcraft_catalog::Catalog, + filter: &lightcraft_catalog::Filter, + ) -> std::sync::Arc> { + let key = lightcraft_catalog::Filter { person: None, ..filter.clone() }; + match &self.people { + Some((r, f, t)) if *r == cat.revision && *f == key => t.clone(), + _ => { + let t = std::sync::Arc::new(cat.people_in(&key)); + self.people = Some((cat.revision, key, t.clone())); + t + } + } + } + /// All Photos / Picks / Recently Deleted counts. + pub fn counts(&mut self, cat: &lightcraft_catalog::Catalog) -> LibraryCounts { + if let Some((r, c)) = self.counts + && still_right(cat, r, READS_FLAG) + { + self.counts = Some((cat.revision, c)); + return c; + } + let mut c = LibraryCounts::default(); + for p in cat.photos() { + if p.in_library() { + c.total += 1; + if p.flag == lightcraft_catalog::Flag::Pick { + c.picks += 1; + } + } else if p.deleted && !p.local { + c.deleted += 1; + } + } + self.counts = Some((cat.revision, c)); + c + } + /// Everyone named on a face in the library (for completing a name as it is typed). + pub fn person_names(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { + let kept = self.person_names.take().filter(|(r, _)| still_right(cat, *r, READS_PEOPLE)).map(|(_, v)| v); + let v = kept.unwrap_or_else(|| std::sync::Arc::new(cat.people().into_iter().map(|p| p.name).collect::>())); + self.person_names = Some((cat.revision, v.clone())); + v + } + /// The By Date tree. + pub fn date_groups(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { + let kept = self.date_groups.take().filter(|(r, _)| still_right(cat, *r, READS_CAPTURED)).map(|(_, g)| g); + let g = kept.unwrap_or_else(|| std::sync::Arc::new(cat.date_groups())); + self.date_groups = Some((cat.revision, g.clone())); + g + } + /// Cameras, lenses and keywords in the library (filter bar pickers). + pub fn filter_values(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc { + match &self.filter_values { + Some((r, v)) if *r == cat.revision => v.clone(), + _ => { + let distinct = |mut v: Vec| { + v.retain(|s| !s.trim().is_empty()); + v.sort_by_key(|s| s.to_lowercase()); + v.dedup(); + v + }; + let lib = || cat.photos().filter(|p| p.in_library()); + let v = std::sync::Arc::new(FilterValues { + cameras: distinct(lib().map(|p| p.meta.camera.clone()).collect()), + lenses: distinct(lib().map(|p| p.meta.lens.clone()).collect()), + keywords: cat.keywords().into_iter().map(|(k, _)| k).collect(), + }); + self.filter_values = Some((cat.revision, v.clone())); + v + } + } + } + /// What the Add keyword box offers for `typed` (see [`panels::keywording::offers`]). Kept apart + /// from [`Self::suggestions`]: both are asked for on every frame of typing, and each looks + /// through the library's keywords. + pub(crate) fn completions( + &mut self, + cat: &lightcraft_catalog::Catalog, + current: &[String], + typed: &str, + ) -> std::sync::Arc { + let k = key_of((cat.revision, current, typed)); + match &self.completions { + Some((h, v)) if *h == k => v.clone(), + _ => { + let v = std::sync::Arc::new(panels::keywording::offers(cat, current, typed)); + self.completions = Some((k, v.clone())); + v + } + } + } + /// Keyword suggestions for a photo with `current` keywords and the typed `prefix`. + pub fn suggestions(&mut self, cat: &lightcraft_catalog::Catalog, current: &[String], prefix: &str, n: usize) -> std::sync::Arc> { + let k = key_of((cat.revision, current, prefix, n)); + match &self.suggestions { + Some((h, v)) if *h == k => v.clone(), + _ => { + let v = std::sync::Arc::new(cat.keyword_suggestions(current, prefix, n)); + self.suggestions = Some((k, v.clone())); + v + } + } + } + /// Every album's photo count for the sidebar (a smart album evaluates its rules, which + /// scans the catalog). Recomputed when the catalog changes (photos, metadata, album rules + /// all bump its revision) and — only while some smart album has an "in the last…" rule — + /// when `now` (the session clock, ISO) enters a new minute, so such counts follow the clock + /// within a minute without rescanning every frame. + /// [`RulesView`] for `rules` edited in smart album `editing` (`None`: a new album), within + /// `folders` when it was made from a folder view (a photo of any of them counts): worked out again only when the catalog, the + /// rules, the language or (for "in the last…" rules) the minute changes, not every frame. + pub fn rules_view( + &mut self, + cat: &lightcraft_catalog::Catalog, + rules: &lightcraft_catalog::RuleSet, + editing: Option, + folders: Vec, + now: &str, + ) -> std::sync::Arc { + let relative = rules.depends_on_now(); + let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; + let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folders, minute, i18n::language().code())); + if let Some((key, v)) = &self.rules_view + && *key == k + { + return v.clone(); + } + if relative { + lightcraft_catalog::rules::set_now(Some(now.to_string())); + } + let problems = rules.check_for(cat, editing.map(lightcraft_catalog::AlbumId)); + let filter = lightcraft_catalog::Filter { rule_set: Some(rules.clone()), library_folders: folders, ..Default::default() }; + let count = if problems.is_empty() { cat.query(&filter, &Default::default()).len() } else { 0 }; + let v = std::sync::Arc::new(RulesView { problems, count, albums: panels::dialogs::album_entries(cat, editing) }); + self.rules_view_scans += 1; + self.rules_view = Some((k, v.clone())); + v + } + + /// A count an open dialog shows (photos a filter matches, photos with a keyword…): `count` runs + /// again only when the catalog or `what` (what is counted) changes, not every frame. + pub(crate) fn dialog_count(&mut self, cat: &lightcraft_catalog::Catalog, what: impl std::hash::Hash, count: impl FnOnce() -> usize) -> usize { + let k = key_of((cat.revision, what)); + if let Some((key, n)) = self.dialog_count + && key == k + { + return n; + } + let n = count(); + self.dialog_count_scans += 1; + self.dialog_count = Some((k, n)); + n + } + + /// The problems of every saved smart album that has some (`Catalog::smart_album_problems`), + /// for the sidebar's ⚠ marks: worked out again only when the catalog changes. + pub fn smart_album_problems( + &mut self, + cat: &lightcraft_catalog::Catalog, + ) -> std::sync::Arc>> { + if let Some((rev, v)) = &self.smart_problems + && *rev == cat.revision + { + return v.clone(); + } + let v: std::sync::Arc> = std::sync::Arc::new( + cat.albums().filter(|a| a.is_smart()).map(|a| (a.id, cat.smart_album_problems(a.id))).filter(|(_, p)| !p.is_empty()).collect(), + ); + self.smart_problem_scans += 1; + self.smart_problems = Some((cat.revision, v.clone())); + v + } + + pub fn album_counts( + &mut self, + cat: &lightcraft_catalog::Catalog, + now: &str, + ) -> std::sync::Arc> { + let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); + let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; + // the counts of this minute, if there are any: an edit to a photo or a few is followed from them, a smart + // album asking only those photos again; anything more, or a new minute, is counted from every photo + let kept = self.album_counts.take().filter(|(of, _, _)| of == minute); + if let Some((_, tally, shown)) = &kept + && tally.revision() == cat.revision + { + let shown = shown.clone(); + self.album_counts = kept; + return shown; + } + if relative { + // "in the last N days" counts back from the session clock, as in the grid. (Within a minute an edit asks + // only the photos it touched, at this second; the others were asked earlier in the minute. That is as + // far out as the counts already were between edits, and the next minute counts them all again.) + lightcraft_catalog::rules::set_now(Some(now.to_string())); + } + let tally = match kept { + Some((_, mut tally, _)) => { + if !tally.update(cat) { + self.album_count_scans += 1; + } + tally + } + None => { + self.album_count_scans += 1; + lightcraft_catalog::tally::AlbumTally::of(cat) + } + }; + let shown = std::sync::Arc::new(tally.counts().clone()); + self.album_counts = Some((minute.to_string(), tally, shown.clone())); + shown + } +} + +#[cfg(test)] +mod cache_tests { + use lightcraft_catalog::{Album, AlbumId, Catalog, Filter, Op, Photo, PhotoId, RuleSet, Source}; + + fn photo(id: u64, captured: &str, rating: u8) -> Op { + let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.captured = Some(captured.into()); + p.rating = rating; + Op::AddPhoto { photo: Box::new(p) } + } + + fn smart(id: u64, rules: serde_json::Value) -> Op { + let mut a = Album::new(AlbumId(id), format!("smart {id}")); + let rules: RuleSet = serde_json::from_value(rules).unwrap(); + a.smart = Some(Box::new(Filter { rule_set: Some(rules), ..Default::default() })); + Op::AddAlbum { album: a } + } + + /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for + /// "in the last…" rules) the clock crossing into a new minute recompute them. + #[test] + fn smart_album_counts_are_cached_until_something_changes() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for (i, d) in ["2026-09-30T11:59:30", "2026-09-29T08:00:00", "2026-01-01T08:00:00"].iter().enumerate() { + cat.apply(photo(i as u64 + 1, d, if i == 0 { 5 } else { 1 })).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + cat.apply(smart(11, serde_json::json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}))).unwrap(); + let now = "2026-09-30T12:00:00"; + let n = c.album_counts(&cat, now); + assert_eq!((n[&AlbumId(10)], n[&AlbumId(11)]), (1, 1)); + assert_eq!(c.album_count_scans, 1); + for _ in 0..10 { + c.album_counts(&cat, "2026-09-30T12:00:40"); + } + assert_eq!(c.album_count_scans, 1, "unchanged frames in the same minute don't rescan"); + // a photo rated: followed from that photo, not counted from every one + cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); + assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 2); + assert_eq!(c.album_count_scans, 1); + // rule change + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 5}]})).unwrap(); + cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 1); + // an hour later the 11:59:30 photo has left "in the last hour", with no catalog change + assert_eq!(c.album_counts(&cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); + assert_eq!(c.album_count_scans, 3, "new rules and a new minute are counted from every photo; the rating was not"); + lightcraft_catalog::rules::set_now(None); + } + + /// The rule dialog's problems, live count and album list are worked out once per change to the + /// catalog or the rules, not every frame; so are the sidebar's smart-album problems. + #[test] + fn rule_dialog_and_problems_are_cached_until_something_changes() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 0..3u64 { + cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); + } + let rules = + |v: u64| -> RuleSet { serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": v}]})).unwrap() }; + let now = "2026-09-30T12:00:00"; + let view = c.rules_view(&cat, &rules(3), None, Vec::new(), now); + assert_eq!((view.count, view.problems.len()), (1, 0)); + for _ in 0..10 { + c.rules_view(&cat, &rules(3), None, Vec::new(), now); + } + assert_eq!(c.rules_view_scans, 1, "unchanged frames reuse it"); + assert_eq!(c.rules_view(&cat, &rules(1), None, Vec::new(), now).count, 3, "a rule change"); + assert_eq!(c.rules_view(&cat, &rules(9), None, Vec::new(), now).problems.len(), 1); + cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); + assert_eq!(c.rules_view(&cat, &rules(3), None, Vec::new(), now).count, 2, "a catalog change"); + assert_eq!(c.rules_view_scans, 4); + // the sidebar's problems + cat.apply(Op::AddAlbum { album: lightcraft_catalog::Album::new(AlbumId(20), "Trip") }).unwrap(); + cat.apply(smart(21, serde_json::json!({"rules": [{"field": "album", "op": "is", "value": 20}]}))).unwrap(); + assert!(c.smart_album_problems(&cat).get(&AlbumId(21)).is_none_or(Vec::is_empty)); + for _ in 0..10 { + c.smart_album_problems(&cat); + } + assert_eq!(c.smart_problem_scans, 1); + cat.apply(Op::RemoveAlbum { id: AlbumId(20) }).unwrap(); + assert!(c.smart_album_problems(&cat).get(&AlbumId(21)).is_some_and(|p| !p.is_empty()), "its album is gone"); + assert_eq!(c.smart_problem_scans, 2); + } + + /// Without "in the last…" rules the clock never causes a rescan. + #[test] + fn absolute_rules_ignore_the_clock() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + cat.apply(photo(1, "2026-09-30T11:59:30", 5)).unwrap(); + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + c.album_counts(&cat, "2026-09-30T12:00:00"); + c.album_counts(&cat, "2027-01-01T00:00:00"); + assert_eq!(c.album_count_scans, 1); + } +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index bca593f3682..a362748f77c 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -498,11 +498,15 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name")); crate::widgets::register(ui, "field:smartName", r.rect); ui.add_space(6.0); - // the folder an album made from a folder view carries is not in the editor, but it counts - let folder = id.and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))).and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone())); + // the folders an album made from a folder view carries are not in the editor, but they count + let folders: Vec = id + .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))) + .and_then(|a| a.smart.as_deref()) + .map(|f| f.library_folder.iter().chain(&f.library_folders).cloned().collect()) + .unwrap_or_default(); // problems, count and albums: cached until the catalog or the rules change (not per frame) let now = (app.session.clock)(); - let view = app.caches.rules_view(&app.session.catalog, rules, *id, folder, &now); + let view = app.caches.rules_view(&app.session.catalog, rules, *id, folders, &now); let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); @@ -1931,6 +1935,8 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result Date: Mon, 26 Oct 2026 20:16:06 -0400 Subject: [PATCH 31/55] LR-BEHAV-MULTISELECT: a keyword picked in the Keyword List is not picked in the library opened next CodeRabbit on #3106 (outside the diff): the reset for a switched library cleared the sidebar's state but kept `keyword_list_selected`, so a keyword of the same name in the other library showed as picked, and the next click took it as the one chosen. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/side_select.rs | 2 ++ crates/ui-egui/src/tests/multi_select.rs | 28 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs index 30bb90942b5..b0a7962d11e 100644 --- a/crates/ui-egui/src/panels/side_select.rs +++ b/crates/ui-egui/src/panels/side_select.rs @@ -60,6 +60,8 @@ pub(crate) fn frame(app: &mut LightcraftApp) { let library = app.session.library_generation(); if app.ui.side.library != Some(library) { app.ui.side = SideState { library: Some(library), ..Default::default() }; + // (a keyword picked here is another library's: it may have one by the same name) + app.ui.keyword_list_selected = None; } // a keyword picked in the Keyword List that is gone since (deleted, merged away, undone) is // not picked any more. Looked up in the cached keyword tree, once per change to the library diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index f5005a860b1..bf40cf1ba55 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -368,6 +368,34 @@ fn what_was_chosen_is_forgotten_when_another_library_opens() { assert!(h.app.ui.side.albums.anchor.is_none()); } +/// A keyword picked in the Keyword List is not picked in another library that has the same keyword. +#[test] +fn a_keyword_picked_in_the_keyword_list_is_forgotten_when_another_library_opens() { + /// Gone with the test, however it ends. + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let mut h = app("keywords"); + let here = Scratch(std::env::temp_dir().join(format!("lc-multi-select-keyword-a-{}", std::process::id()))); + let there = Scratch(std::env::temp_dir().join(format!("lc-multi-select-keyword-b-{}", std::process::id()))); + for dir in [&here, &there] { + let _ = std::fs::remove_dir_all(&dir.0); + h.app.session.open_library(&dir.0, false).unwrap(); + h.settle(SETTLE); + run(&mut h, "keyword.create", json!({"name": "Sel Same"})); + } + // Given a keyword picked in the library that is open + h.app.ui.keyword_list_selected = Some("Sel Same".into()); + // When the other library, which has a keyword by that name, opens + h.app.session.open_library(&here.0, false).unwrap(); + h.settle(SETTLE); + // Then its row is not picked + assert_eq!(h.app.ui.keyword_list_selected, None); +} + /// "Show in Library" after a Lightroom import shows every photo: keywords chosen in the /// sidebar with Cmd+click are not left in the filter (dates go the same way: both lists are omitted from the default filter's JSON). #[test] From 1b51673b059107da71d44ac5c304630bb46dc492 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 2 Nov 2026 10:47:40 -0500 Subject: [PATCH 32/55] LR-BEHAV-MULTISELECT: port the click selection onto main's ui-egui layout The replay wrote the old flat layout beside main's split files: the whole caches block and the rule-dialog fixes landed in dead copies (lib.rs duplicate impl, an undeclared panels/dialogs.rs) and the left panel never called the model. This moves each change into the live file: multi_select declared in lib.rs, rules_view(folders) in caches.rs with its callers and tests, the Show-in-Library reset and the smart-album folder count in dialogs.rs/dialogs/confirm.rs, and the Albums, Folders, Keywords and By Date rows wired to side_select. The dead copies are gone and the parity row cites the moved engine test. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/caches.rs | 18 +- crates/ui-egui/src/dialogs.rs | 10 +- crates/ui-egui/src/dialogs/confirm.rs | 4 + crates/ui-egui/src/lib.rs | 465 +--- crates/ui-egui/src/panels/dialogs.rs | 2659 -------------------- crates/ui-egui/src/panels/left.rs | 1 + crates/ui-egui/src/panels/left/albums.rs | 7 +- crates/ui-egui/src/panels/left/dates.rs | 7 +- crates/ui-egui/src/panels/left/folders.rs | 9 +- crates/ui-egui/src/panels/left/keywords.rs | 8 +- 10 files changed, 36 insertions(+), 3152 deletions(-) delete mode 100644 crates/ui-egui/src/panels/dialogs.rs diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 93fe551847f..0b66fc490d9 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -263,19 +263,19 @@ impl Caches { /// when `now` (the session clock, ISO) enters a new minute, so such counts follow the clock /// within a minute without rescanning every frame. /// [`RulesView`] for `rules` edited in smart album `editing` (`None`: a new album), within - /// `folder` when it was made from a folder view: worked out again only when the catalog, the + /// `folders` when it was made from a folder view (a photo of any of them counts): worked out again only when the catalog, the /// rules, the language or (for "in the last…" rules) the minute changes, not every frame. pub fn rules_view( &mut self, cat: &lightcraft_catalog::Catalog, rules: &lightcraft_catalog::RuleSet, editing: Option, - folder: Option, + folders: Vec, now: &str, ) -> std::sync::Arc { let relative = rules.depends_on_now(); let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folder, minute, i18n::language().code())); + let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folders, minute, i18n::language().code())); if let Some((key, v)) = &self.rules_view && *key == k { @@ -285,7 +285,7 @@ impl Caches { lightcraft_catalog::rules::set_now(Some(now.to_string())); } let problems = rules.check_for(cat, editing.map(lightcraft_catalog::AlbumId)); - let filter = lightcraft_catalog::Filter { rule_set: Some(rules.clone()), library_folder: folder, ..Default::default() }; + let filter = lightcraft_catalog::Filter { rule_set: Some(rules.clone()), library_folders: folders, ..Default::default() }; let count = if problems.is_empty() { cat.query(&filter, &Default::default()).len() } else { 0 }; let v = std::sync::Arc::new(RulesView { problems, count, albums: panels::dialogs::album_entries(cat, editing) }); self.rules_view_scans += 1; @@ -431,16 +431,16 @@ mod cache_tests { let rules = |v: u64| -> RuleSet { serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": v}]})).unwrap() }; let now = "2026-09-30T12:00:00"; - let view = c.rules_view(&cat, &rules(3), None, None, now); + let view = c.rules_view(&cat, &rules(3), None, Vec::new(), now); assert_eq!((view.count, view.problems.len()), (1, 0)); for _ in 0..10 { - c.rules_view(&cat, &rules(3), None, None, now); + c.rules_view(&cat, &rules(3), None, Vec::new(), now); } assert_eq!(c.rules_view_scans, 1, "unchanged frames reuse it"); - assert_eq!(c.rules_view(&cat, &rules(1), None, None, now).count, 3, "a rule change"); - assert_eq!(c.rules_view(&cat, &rules(9), None, None, now).problems.len(), 1); + assert_eq!(c.rules_view(&cat, &rules(1), None, Vec::new(), now).count, 3, "a rule change"); + assert_eq!(c.rules_view(&cat, &rules(9), None, Vec::new(), now).problems.len(), 1); cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.rules_view(&cat, &rules(3), None, None, now).count, 2, "a catalog change"); + assert_eq!(c.rules_view(&cat, &rules(3), None, Vec::new(), now).count, 2, "a catalog change"); assert_eq!(c.rules_view_scans, 4); // the sidebar's problems cat.apply(Op::AddAlbum { album: lightcraft_catalog::Album::new(AlbumId(20), "Trip") }).unwrap(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 91d9dd2611e..18eaf351e31 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1014,13 +1014,15 @@ fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: ); crate::widgets::register(ui, "field:smartName", r.rect); ui.add_space(6.0); - // the folder an album made from a folder view carries is not in the editor, but it counts - let folder = id + // the folders an album made from a folder view carries are not in the editor, but they count + let folders: Vec = id .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))) - .and_then(|a| a.smart.as_deref().and_then(|f| f.library_folder.clone())); + .and_then(|a| a.smart.as_deref()) + .map(|f| f.library_folder.iter().chain(&f.library_folders).cloned().collect()) + .unwrap_or_default(); // problems, count and albums: cached until the catalog or the rules change (not per frame) let now = (app.session.clock)(); - let view = app.caches.rules_view(&app.session.catalog, rules, *id, folder, &now); + let view = app.caches.rules_view(&app.session.catalog, rules, *id, folders, &now); let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index b0d816d25cc..64051c27949 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -30,6 +30,10 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result, - pub lenses: Vec, - pub keywords: Vec, -} - -/// What the smart-album rule dialog shows besides the rules themselves: their problems (each row -/// marks its own), how many photos they match and the albums an Album rule picks from. -pub struct RulesView { - pub problems: Vec, - pub count: usize, - pub albums: Vec, -} - -pub(crate) fn key_of(parts: impl std::hash::Hash) -> u64 { - use std::hash::{BuildHasher, BuildHasherDefault, DefaultHasher}; - BuildHasherDefault::::default().hash_one(parts) -} - -/// Whether a tally of the library made when the catalog was at `revision` is still right, given that it reads only -/// `reads` of a photo: nothing changed since, or only other things of some photos did (a rating changes no folder's -/// count, a slider changes none at all). Each of these tallies asks every photo, so one kept is a pass over the -/// library saved on every edit. -fn still_right(cat: &lightcraft_catalog::Catalog, revision: u64, reads: lightcraft_catalog::Aspects) -> bool { - revision == cat.revision || cat.aspects_since(revision).is_some_and(|changed| !changed.any_of(reads)) -} - -/// What the tallies below read of a photo, besides whether it is in the library. -const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FILE); -const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); -const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); -const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); -const READS_FLAG: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::FLAG); - -impl Caches { - /// The folders the library's photos were imported from. - pub fn folder_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.folder_tree.take().filter(|(r, _)| still_right(cat, *r, READS_FILE)).map(|(_, t)| t); - let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.folder_tree())); - self.folder_tree = Some((cat.revision, t.clone())); - t - } - /// The folder tree as last built, when it still holds (a read-only check cannot rebuild it). - pub(crate) fn folder_tree_if_fresh(&self, cat: &lightcraft_catalog::Catalog) -> Option>> { - self.folder_tree.as_ref().filter(|(r, _)| still_right(cat, *r, READS_FILE)).map(|(_, t)| t.clone()) - } - /// The library's keyword tree. - pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); - let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); - self.keyword_tree = Some((cat.revision, t.clone())); - t - } - /// The Keywording box's read-only names for the selection: what exported files carry - /// (`export`), or the keywords with those containing them. - pub(crate) fn keyword_names( - &mut self, - cat: &lightcraft_catalog::Catalog, - selection: &[lightcraft_catalog::PhotoId], - export: bool, - ) -> std::sync::Arc> { - let key = key_of((selection, export)); - match &self.keyword_names { - Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), - _ => { - let c = std::sync::Arc::new(if export { - panels::keywording::will_export(cat, selection) - } else { - panels::keywording::with_containing(cat, selection) - }); - self.keyword_names = Some((cat.revision, key, c.clone())); - c - } - } - } - /// The selection's keywords (the Keywording box's chips). - pub(crate) fn keyword_chips( - &mut self, - cat: &lightcraft_catalog::Catalog, - selection: &[lightcraft_catalog::PhotoId], - ) -> std::sync::Arc> { - let key = key_of(selection); - match &self.keyword_chips { - Some((r, k, c)) if *r == cat.revision && *k == key => c.clone(), - _ => { - let c = std::sync::Arc::new(panels::keywording::chips(cat, selection)); - self.keyword_chips = Some((cat.revision, key, c.clone())); - c - } - } - } - /// How many photos the selection is: each once, those the library has (what the Keywording - /// box's "N of M" counts). - pub(crate) fn selected_photos(&mut self, cat: &lightcraft_catalog::Catalog, selection: &[lightcraft_catalog::PhotoId]) -> usize { - let key = key_of(selection); - match self.selected_photos { - Some((r, k, n)) if r == cat.revision && k == key => n, - _ => { - let n = panels::keywording::distinct(cat, selection).len(); - self.selected_photos = Some((cat.revision, key, n)); - n - } - } - } - /// The selection's keywords grouped by the keyword they are inside (the grouped Keywording box). - pub(crate) fn keyword_groups( - &mut self, - cat: &lightcraft_catalog::Catalog, - selection: &[lightcraft_catalog::PhotoId], - ) -> std::sync::Arc> { - let key = key_of(selection); - match &self.keyword_groups { - Some((r, k, g)) if *r == cat.revision && *k == key => g.clone(), - _ => { - let chips = self.keyword_chips(cat, selection); - let g = std::sync::Arc::new(panels::keywording::grouped(&chips)); - self.keyword_groups = Some((cat.revision, key, g.clone())); - g - } - } - } - /// How many selected photos have each keyword (the Keyword List's tick boxes). - pub(crate) fn keyword_ticks( - &mut self, - cat: &lightcraft_catalog::Catalog, - selection: &[lightcraft_catalog::PhotoId], - ) -> std::sync::Arc { - let key = key_of(selection); - match &self.keyword_ticks { - Some((r, k, t)) if *r == cat.revision && *k == key => t.clone(), - _ => { - let t = std::sync::Arc::new(panels::keyword_list::Ticks::of(cat, selection)); - self.keyword_ticks = Some((cat.revision, key, t.clone())); - t - } - } - } - /// The people named on faces among the photos the filter lets through (its own `person` aside), - /// with photo counts. - pub fn people( - &mut self, - cat: &lightcraft_catalog::Catalog, - filter: &lightcraft_catalog::Filter, - ) -> std::sync::Arc> { - let key = lightcraft_catalog::Filter { person: None, ..filter.clone() }; - match &self.people { - Some((r, f, t)) if *r == cat.revision && *f == key => t.clone(), - _ => { - let t = std::sync::Arc::new(cat.people_in(&key)); - self.people = Some((cat.revision, key, t.clone())); - t - } - } - } - /// All Photos / Picks / Recently Deleted counts. - pub fn counts(&mut self, cat: &lightcraft_catalog::Catalog) -> LibraryCounts { - if let Some((r, c)) = self.counts - && still_right(cat, r, READS_FLAG) - { - self.counts = Some((cat.revision, c)); - return c; - } - let mut c = LibraryCounts::default(); - for p in cat.photos() { - if p.in_library() { - c.total += 1; - if p.flag == lightcraft_catalog::Flag::Pick { - c.picks += 1; - } - } else if p.deleted && !p.local { - c.deleted += 1; - } - } - self.counts = Some((cat.revision, c)); - c - } - /// Everyone named on a face in the library (for completing a name as it is typed). - pub fn person_names(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.person_names.take().filter(|(r, _)| still_right(cat, *r, READS_PEOPLE)).map(|(_, v)| v); - let v = kept.unwrap_or_else(|| std::sync::Arc::new(cat.people().into_iter().map(|p| p.name).collect::>())); - self.person_names = Some((cat.revision, v.clone())); - v - } - /// The By Date tree. - pub fn date_groups(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.date_groups.take().filter(|(r, _)| still_right(cat, *r, READS_CAPTURED)).map(|(_, g)| g); - let g = kept.unwrap_or_else(|| std::sync::Arc::new(cat.date_groups())); - self.date_groups = Some((cat.revision, g.clone())); - g - } - /// Cameras, lenses and keywords in the library (filter bar pickers). - pub fn filter_values(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc { - match &self.filter_values { - Some((r, v)) if *r == cat.revision => v.clone(), - _ => { - let distinct = |mut v: Vec| { - v.retain(|s| !s.trim().is_empty()); - v.sort_by_key(|s| s.to_lowercase()); - v.dedup(); - v - }; - let lib = || cat.photos().filter(|p| p.in_library()); - let v = std::sync::Arc::new(FilterValues { - cameras: distinct(lib().map(|p| p.meta.camera.clone()).collect()), - lenses: distinct(lib().map(|p| p.meta.lens.clone()).collect()), - keywords: cat.keywords().into_iter().map(|(k, _)| k).collect(), - }); - self.filter_values = Some((cat.revision, v.clone())); - v - } - } - } - /// What the Add keyword box offers for `typed` (see [`panels::keywording::offers`]). Kept apart - /// from [`Self::suggestions`]: both are asked for on every frame of typing, and each looks - /// through the library's keywords. - pub(crate) fn completions( - &mut self, - cat: &lightcraft_catalog::Catalog, - current: &[String], - typed: &str, - ) -> std::sync::Arc { - let k = key_of((cat.revision, current, typed)); - match &self.completions { - Some((h, v)) if *h == k => v.clone(), - _ => { - let v = std::sync::Arc::new(panels::keywording::offers(cat, current, typed)); - self.completions = Some((k, v.clone())); - v - } - } - } - /// Keyword suggestions for a photo with `current` keywords and the typed `prefix`. - pub fn suggestions(&mut self, cat: &lightcraft_catalog::Catalog, current: &[String], prefix: &str, n: usize) -> std::sync::Arc> { - let k = key_of((cat.revision, current, prefix, n)); - match &self.suggestions { - Some((h, v)) if *h == k => v.clone(), - _ => { - let v = std::sync::Arc::new(cat.keyword_suggestions(current, prefix, n)); - self.suggestions = Some((k, v.clone())); - v - } - } - } - /// Every album's photo count for the sidebar (a smart album evaluates its rules, which - /// scans the catalog). Recomputed when the catalog changes (photos, metadata, album rules - /// all bump its revision) and — only while some smart album has an "in the last…" rule — - /// when `now` (the session clock, ISO) enters a new minute, so such counts follow the clock - /// within a minute without rescanning every frame. - /// [`RulesView`] for `rules` edited in smart album `editing` (`None`: a new album), within - /// `folders` when it was made from a folder view (a photo of any of them counts): worked out again only when the catalog, the - /// rules, the language or (for "in the last…" rules) the minute changes, not every frame. - pub fn rules_view( - &mut self, - cat: &lightcraft_catalog::Catalog, - rules: &lightcraft_catalog::RuleSet, - editing: Option, - folders: Vec, - now: &str, - ) -> std::sync::Arc { - let relative = rules.depends_on_now(); - let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folders, minute, i18n::language().code())); - if let Some((key, v)) = &self.rules_view - && *key == k - { - return v.clone(); - } - if relative { - lightcraft_catalog::rules::set_now(Some(now.to_string())); - } - let problems = rules.check_for(cat, editing.map(lightcraft_catalog::AlbumId)); - let filter = lightcraft_catalog::Filter { rule_set: Some(rules.clone()), library_folders: folders, ..Default::default() }; - let count = if problems.is_empty() { cat.query(&filter, &Default::default()).len() } else { 0 }; - let v = std::sync::Arc::new(RulesView { problems, count, albums: panels::dialogs::album_entries(cat, editing) }); - self.rules_view_scans += 1; - self.rules_view = Some((k, v.clone())); - v - } - - /// A count an open dialog shows (photos a filter matches, photos with a keyword…): `count` runs - /// again only when the catalog or `what` (what is counted) changes, not every frame. - pub(crate) fn dialog_count(&mut self, cat: &lightcraft_catalog::Catalog, what: impl std::hash::Hash, count: impl FnOnce() -> usize) -> usize { - let k = key_of((cat.revision, what)); - if let Some((key, n)) = self.dialog_count - && key == k - { - return n; - } - let n = count(); - self.dialog_count_scans += 1; - self.dialog_count = Some((k, n)); - n - } - - /// The problems of every saved smart album that has some (`Catalog::smart_album_problems`), - /// for the sidebar's ⚠ marks: worked out again only when the catalog changes. - pub fn smart_album_problems( - &mut self, - cat: &lightcraft_catalog::Catalog, - ) -> std::sync::Arc>> { - if let Some((rev, v)) = &self.smart_problems - && *rev == cat.revision - { - return v.clone(); - } - let v: std::sync::Arc> = std::sync::Arc::new( - cat.albums().filter(|a| a.is_smart()).map(|a| (a.id, cat.smart_album_problems(a.id))).filter(|(_, p)| !p.is_empty()).collect(), - ); - self.smart_problem_scans += 1; - self.smart_problems = Some((cat.revision, v.clone())); - v - } - - pub fn album_counts( - &mut self, - cat: &lightcraft_catalog::Catalog, - now: &str, - ) -> std::sync::Arc> { - let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); - let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - // the counts of this minute, if there are any: an edit to a photo or a few is followed from them, a smart - // album asking only those photos again; anything more, or a new minute, is counted from every photo - let kept = self.album_counts.take().filter(|(of, _, _)| of == minute); - if let Some((_, tally, shown)) = &kept - && tally.revision() == cat.revision - { - let shown = shown.clone(); - self.album_counts = kept; - return shown; - } - if relative { - // "in the last N days" counts back from the session clock, as in the grid. (Within a minute an edit asks - // only the photos it touched, at this second; the others were asked earlier in the minute. That is as - // far out as the counts already were between edits, and the next minute counts them all again.) - lightcraft_catalog::rules::set_now(Some(now.to_string())); - } - let tally = match kept { - Some((_, mut tally, _)) => { - if !tally.update(cat) { - self.album_count_scans += 1; - } - tally - } - None => { - self.album_count_scans += 1; - lightcraft_catalog::tally::AlbumTally::of(cat) - } - }; - let shown = std::sync::Arc::new(tally.counts().clone()); - self.album_counts = Some((minute.to_string(), tally, shown.clone())); - shown - } -} - -#[cfg(test)] -mod cache_tests { - use lightcraft_catalog::{Album, AlbumId, Catalog, Filter, Op, Photo, PhotoId, RuleSet, Source}; - - fn photo(id: u64, captured: &str, rating: u8) -> Op { - let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); - p.captured = Some(captured.into()); - p.rating = rating; - Op::AddPhoto { photo: Box::new(p) } - } - - fn smart(id: u64, rules: serde_json::Value) -> Op { - let mut a = Album::new(AlbumId(id), format!("smart {id}")); - let rules: RuleSet = serde_json::from_value(rules).unwrap(); - a.smart = Some(Box::new(Filter { rule_set: Some(rules), ..Default::default() })); - Op::AddAlbum { album: a } - } - - /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for - /// "in the last…" rules) the clock crossing into a new minute recompute them. - #[test] - fn smart_album_counts_are_cached_until_something_changes() { - let mut cat = Catalog::default(); - let mut c = super::Caches::default(); - for (i, d) in ["2026-09-30T11:59:30", "2026-09-29T08:00:00", "2026-01-01T08:00:00"].iter().enumerate() { - cat.apply(photo(i as u64 + 1, d, if i == 0 { 5 } else { 1 })).unwrap(); - } - cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); - cat.apply(smart(11, serde_json::json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}))).unwrap(); - let now = "2026-09-30T12:00:00"; - let n = c.album_counts(&cat, now); - assert_eq!((n[&AlbumId(10)], n[&AlbumId(11)]), (1, 1)); - assert_eq!(c.album_count_scans, 1); - for _ in 0..10 { - c.album_counts(&cat, "2026-09-30T12:00:40"); - } - assert_eq!(c.album_count_scans, 1, "unchanged frames in the same minute don't rescan"); - // a photo rated: followed from that photo, not counted from every one - cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 2); - assert_eq!(c.album_count_scans, 1); - // rule change - let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 5}]})).unwrap(); - cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 1); - // an hour later the 11:59:30 photo has left "in the last hour", with no catalog change - assert_eq!(c.album_counts(&cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); - assert_eq!(c.album_count_scans, 3, "new rules and a new minute are counted from every photo; the rating was not"); - lightcraft_catalog::rules::set_now(None); - } - - /// The rule dialog's problems, live count and album list are worked out once per change to the - /// catalog or the rules, not every frame; so are the sidebar's smart-album problems. - #[test] - fn rule_dialog_and_problems_are_cached_until_something_changes() { - let mut cat = Catalog::default(); - let mut c = super::Caches::default(); - for i in 0..3u64 { - cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); - } - let rules = - |v: u64| -> RuleSet { serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": v}]})).unwrap() }; - let now = "2026-09-30T12:00:00"; - let view = c.rules_view(&cat, &rules(3), None, Vec::new(), now); - assert_eq!((view.count, view.problems.len()), (1, 0)); - for _ in 0..10 { - c.rules_view(&cat, &rules(3), None, Vec::new(), now); - } - assert_eq!(c.rules_view_scans, 1, "unchanged frames reuse it"); - assert_eq!(c.rules_view(&cat, &rules(1), None, Vec::new(), now).count, 3, "a rule change"); - assert_eq!(c.rules_view(&cat, &rules(9), None, Vec::new(), now).problems.len(), 1); - cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.rules_view(&cat, &rules(3), None, Vec::new(), now).count, 2, "a catalog change"); - assert_eq!(c.rules_view_scans, 4); - // the sidebar's problems - cat.apply(Op::AddAlbum { album: lightcraft_catalog::Album::new(AlbumId(20), "Trip") }).unwrap(); - cat.apply(smart(21, serde_json::json!({"rules": [{"field": "album", "op": "is", "value": 20}]}))).unwrap(); - assert!(c.smart_album_problems(&cat).get(&AlbumId(21)).is_none_or(Vec::is_empty)); - for _ in 0..10 { - c.smart_album_problems(&cat); - } - assert_eq!(c.smart_problem_scans, 1); - cat.apply(Op::RemoveAlbum { id: AlbumId(20) }).unwrap(); - assert!(c.smart_album_problems(&cat).get(&AlbumId(21)).is_some_and(|p| !p.is_empty()), "its album is gone"); - assert_eq!(c.smart_problem_scans, 2); - } - - /// Without "in the last…" rules the clock never causes a rescan. - #[test] - fn absolute_rules_ignore_the_clock() { - let mut cat = Catalog::default(); - let mut c = super::Caches::default(); - cat.apply(photo(1, "2026-09-30T11:59:30", 5)).unwrap(); - cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); - c.album_counts(&cat, "2026-09-30T12:00:00"); - c.album_counts(&cat, "2027-01-01T00:00:00"); - assert_eq!(c.album_count_scans, 1); - } -} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs deleted file mode 100644 index a362748f77c..00000000000 --- a/crates/ui-egui/src/panels/dialogs.rs +++ /dev/null @@ -1,2659 +0,0 @@ -//! Modal dialogs (new album, rename, create preset, choose settings to copy, export, about, shortcuts). - -use lightcraft_develop::{ControlSpec, Section, SettingsGroup, Track}; -use serde_json::json; - -use crate::LightcraftApp; -use crate::state::Dialog; -use crate::theme::Tokens; - -/// Rows the Rename dialog previews. -const RENAME_PREVIEW_ROWS: usize = 6; - -/// The Rename dialog's preview: its first rows (`None` while being planned) and how many files -/// are renamed. Which names are taken is checked on disk, which can block on a slow drive, so the -/// rows are planned on a worker thread, and only when the template, start number, photos or -/// catalog change — never once per frame. -pub(crate) fn rename_preview( - app: &mut LightcraftApp, - ctx: &egui::Context, - template: &str, - start: usize, -) -> (Option>, usize) { - use std::hash::{Hash, Hasher}; - type Rows = std::sync::Arc>>>; - let ids = app.session.selected(); - let photos = lightcraft_engine::rename::rename_photos(&app.session.catalog, &ids); - let total = photos.len(); - let mut h = std::collections::hash_map::DefaultHasher::new(); - (template, start, app.session.catalog.revision, &ids).hash(&mut h); - let key = h.finish(); - let id = egui::Id::unique("rename-preview-rows"); - let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); - if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id)) - && k == key - { - return (read(&rows), total); - } - let rows: Rows = Default::default(); - let first: Vec<_> = photos.into_iter().take(RENAME_PREVIEW_ROWS).collect(); - let (out, template, repaint) = (rows.clone(), template.to_string(), ctx.clone()); - let exists = app.session.media.availability.probe(); - let work = move || { - let plans = lightcraft_engine::rename::plan_rename_photos(&first, &template, start, &|f| exists(f)); - *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(plans); - repaint.request_repaint(); - }; - #[cfg(not(target_arch = "wasm32"))] - if let Err(e) = std::thread::Builder::new().name("lc-rename-preview".into()).spawn(work) { - log::warn!("rename preview: {e}"); - } - #[cfg(target_arch = "wasm32")] - work(); - ctx.data_mut(|d| d.insert_temp(id, (key, rows.clone()))); - (read(&rows), total) -} - -/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever -/// its shape, with the watermark drawn on it as the file will have it at size `resize` (`None` = -/// full size). On a worker thread, once per photo, catalog change and size step, the cached -/// thumbnail comes first (at once, a little soft) and then a render at the preview's own pixel size -/// replaces it. The watermark is redrawn on a copy only when it, the output size or the picture -/// changes, which is quick at this size, so the preview follows the sliders. -fn watermark_preview( - app: &mut LightcraftApp, - ui: &mut egui::Ui, - wm: &lightcraft_engine::export::Watermark, - resize: Option, -) { - use std::hash::{Hash, Hasher}; - // (pictures received so far: 1 the thumbnail, 2 the sharp render; the latest, or why none came) - type Base = std::sync::Arc>)>>; - type Shown = (u64, u8, lightcraft_engine::export::Watermark, usize, egui::TextureHandle); - let t = Tokens::get(ui.ctx()); - let Some(&id) = app.session.selected().first() else { return }; - let Some(photo) = app.session.catalog.photo(id).cloned() else { return }; - let (out_w, out_h) = lightcraft_engine::export::output_size(&photo, &lightcraft_engine::export::ExportOptions { resize, ..Default::default() }); - let export_short = out_w.min(out_h); - // pixels across the dialog, in steps so a scroll bar or a point of layout doesn't re-render - let step = 128.0; - let px = ((ui.available_width() * ui.ctx().pixels_per_point() / step).ceil() * step).clamp(step, 2048.0) as usize; - let mut h = std::collections::hash_map::DefaultHasher::new(); - (id, app.session.catalog.revision, px).hash(&mut h); - let key = h.finish(); - let ctx = ui.ctx().clone(); - let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown")); - let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) { - Some((k, base)) if k == key => base, - _ => { - let base: Base = Default::default(); - // the thumbnail, then as wide as the dialog (a tall photo up to three times that high) - let jobs: Vec<_> = [app.session.thumb_job(id, 512), app.session.render_job(id, px, px * 3, false, true)].into_iter().flatten().collect(); - // the web build has no worker thread: a full render there would hold up the page - #[cfg(target_arch = "wasm32")] - let jobs: Vec<_> = jobs.into_iter().take(1).collect(); - if jobs.is_empty() { - *base.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (1, Some(Err("no such photo".into()))); - } else { - let (out, repaint) = (base.clone(), ctx.clone()); - let work = move || { - for job in jobs { - // (a panic in the render is its failure: `RenderJob::run`) - let r = job.run().rendered.map(|r| r.image); - let mut got = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - // a failed sharp render keeps the thumbnail - if r.is_ok() || !matches!(got.1, Some(Ok(_))) { - *got = (got.0.saturating_add(1), Some(r)); - repaint.request_repaint(); - } - } - }; - #[cfg(not(target_arch = "wasm32"))] - if let Err(e) = std::thread::Builder::new().name("lc-watermark-preview".into()).spawn(work) { - log::warn!("watermark preview: {e}"); - } - #[cfg(target_arch = "wasm32")] - work(); - } - ctx.data_mut(|d| d.insert_temp(base_id, (key, base.clone()))); - base - } - }; - let shown = ctx.data(|d| d.get_temp::(shown_id)); - let stage = base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0; - let tex = match shown { - Some((k, g, w, s, tex)) if k == key && g == stage && &w == wm && s == export_short => tex, - _ => { - let photo_px = match &base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 { - Some(Ok(img)) => Ok(img.clone()), - Some(Err(e)) => Err(Some(e.clone())), - None => Err(None), - }; - let mut img = match photo_px { - Ok(img) => img, - Err(e) => { - let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" }; - let r = ui - .horizontal(|ui| { - if e.is_none() { - crate::progress::spinner(ui, 12.0); - } - ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)) - }) - .inner; - if let Some(e) = e { - r.on_hover_text(e); - } - return; - } - }; - lightcraft_engine::export::draw_watermark_preview(&mut img, wm, export_short); - // shown through the monitor profile like every other preview - if let Some(d) = app.renderer.display() - && let Err(e) = d.profile.from_srgb(&mut img) - { - log::warn!("display profile: {e}"); - } - let color = std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &img.as_bytes())); - let tex = match shown { - Some((.., mut tex)) => { - tex.set(color, egui::TextureOptions::LINEAR); - tex - } - None => ctx.load_texture("export-wm-preview", color, egui::TextureOptions::LINEAR), - }; - ctx.data_mut(|d| d.insert_temp(shown_id, (key, stage, wm.clone(), export_short, tex.clone()))); - tex - } - }; - let size = tex.size_vec2(); - let scale = ui.available_width() / size.x.max(1.0); - let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner; - crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect); -} - -/// About dialog tabs: (widget id suffix, label). The credits come from `crate::credits`. -pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", "Contributors"), ("models", "Models")]; - -/// Help ▸ What's New (docs/whats-new.md). -pub const WHATS_NEW: &str = include_str!("../../../../docs/whats-new.md"); - -/// The import review and Settings keep window ids of their own, so the size each is given -/// doesn't carry over to the other dialogs. -fn window_id(dialog: &Dialog) -> egui::Id { - egui::Id::unique(match dialog { - Dialog::Import { .. } => "lightcraft-import-dialog", - Dialog::Print => "lightcraft-print-dialog", - Dialog::Settings { .. } => "lightcraft-settings-dialog", - _ => "lightcraft-dialog", - }) -} - -/// Block the underlying panels from the first frame, before the window establishes its modal -/// layer. Close background menus on entry; popups subsequently opened inside the dialog stay usable. -pub(crate) fn prepare(app: &LightcraftApp, ui: &mut egui::Ui) { - let Some(dialog) = &app.ui.dialog else { return }; - ui.disable(); - let layer = egui::LayerId::new(egui::Order::Middle, window_id(dialog)); - if ui.ctx().memory(|m| m.top_modal_layer()) != Some(layer) { - egui::Popup::close_all(ui.ctx()); - } -} - -/// Draw the open dialog. `blocked` is true when a quit prompt or settings notice was on screen at -/// the start of this frame: the dialog is still drawn (its state is preserved), but none of its raw -/// keyboard/backdrop handling may act. The caller freezes `blocked` for the whole frame so the -/// click or key that dismisses the prompt cannot also reach the dialog drawn after it. The -/// blocking library-problem/launch-list window gets the same raw-input treatment while it is -/// actually on screen over this dialog; ordinary dialogs without that window keep their normal -/// Escape and outside-click behaviour. -pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { - let Some(mut dlg) = app.ui.dialog.clone() else { return }; - let at_start = dlg.clone(); - let library_blocks = crate::panels::library_problem::blocks_dialog_input(app); - let raw_blocked = blocked || library_blocks; - // Esc with a popup open in the dialog (a dropdown, a date picker's calendar) closes the popup - // only: claimed before the dialog is drawn, since the popup is gone once it has handled the key - if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && egui::Popup::is_any_open(ctx) { - crate::widgets::take_escape(ctx); - } - let t = Tokens::get(ctx); - let screen = ctx.content_rect(); - // The backdrop is an area below the dialog window (a bare `Middle` layer painter would be - // painted after every area — i.e. over the dialog too). - egui::Area::new(egui::Id::unique("dialog-dim")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(false).show(ctx, |ui| { - ui.painter().rect_filled(screen, 0.0, egui::Color32::from_black_alpha(140)); - }); - let mut close = false; - let mut confirm = false; - // Return presses OK in a dialog without a text field of its own (Lightroom's default button); - // a widget that has the keyboard focus (a text field, a button or checkbox reached with Tab) - // takes Return itself. Consumed before the dialog is drawn, so nothing else sees it too. - if !raw_blocked - && return_confirms(&dlg) - && ctx.memory(|m| m.focused().is_none()) - && !egui::Popup::is_any_open(ctx) - && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) - { - confirm = true; - } - let title: String = match &dlg { - Dialog::TextPrompt { title, .. } => title.as_str(), - Dialog::NewAlbum { folder: true, .. } => "Create Folder", - Dialog::NewAlbum { .. } => "Create Album", - Dialog::RenameAlbum { .. } => "Rename Album", - Dialog::Rename { .. } => "Rename Photos", - Dialog::Import { .. } => "Import Photos", - Dialog::LightroomResult { .. } => "Lightroom Catalog Import", - Dialog::LabelNames { .. } => "Edit Color Label Names", - Dialog::CaptureTime { .. } => "Edit Capture Time", - Dialog::RenameKeyword { .. } => "Rename Keyword", - Dialog::RenamePerson { .. } => "Rename Person", - Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag", - Dialog::KeywordTag { .. } => "Edit Keyword Tag", - Dialog::DeleteKeyword { .. } => "Delete Keyword", - Dialog::MoveKeyword { .. } => "Merge Keywords", - Dialog::KeywordSet { .. } => "Edit Keyword Set", - Dialog::MergeKeywords { .. } => "Merge Keywords", - Dialog::NewSmartAlbum { .. } => "Create Smart Album", - Dialog::AllMetadata { .. } => "All Metadata", - Dialog::SystemInfo { .. } => "System Info", - Dialog::DenoiseModel { .. } => "AI Denoise Model", - Dialog::FaceModel { info, .. } if info["download"].is_string() => "Download Face Model", - Dialog::FaceModel { .. } => "Add Face Model", - Dialog::WhatsNew => "What's New", - Dialog::Cull { .. } => "Assisted Culling", - Dialog::SmartRules { id: None, .. } => "New Smart Album", - Dialog::SmartRules { .. } => "Edit Smart Album", - Dialog::AutoStack { .. } => "Auto-Stack by Capture Time", - Dialog::CreatePreset { .. } => "Create Preset", - Dialog::CopySettings { .. } => "Choose Edit Settings to Copy", - Dialog::PasteSettings { .. } => "Paste Selected Settings", - Dialog::Export { .. } => "Export", - Dialog::ContactSheet { .. } => "Contact Sheet PDF", - Dialog::SlideshowExport { .. } => "Export Slideshow", - Dialog::Print => "Print", - Dialog::Merge { opts } => opts.title(), - Dialog::Settings { .. } => "Settings", - Dialog::ConfirmDelete { .. } => "Delete Photos", - Dialog::MovePhotos { .. } => "Move Photos", - Dialog::LightroomCatalog { .. } => "Lightroom Classic Catalog", - Dialog::LightroomDestination { .. } => "Import Lightroom Catalog", - Dialog::SaveEffect { .. } => "New Effect Preset", - Dialog::ManageEffects { .. } => "Manage Effect Presets", - Dialog::DeleteEffects { names } if names.len() == 1 => "Delete Effect Preset", - Dialog::DeleteEffects { .. } => "Delete Effect Presets", - Dialog::RemoveFolder { disk: true, .. } => "Remove Disk from Library", - Dialog::RemoveFolder { .. } => "Remove Folder from Library", - Dialog::SynchronizeFolder { .. } => "Synchronize Folder", - // (nothing to download from in this build: the dialog explains the manual install) - Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model", - Dialog::SamModel { .. } => "Download the SAM 3 Model?", - Dialog::About => "About LightCraft", - Dialog::Shortcuts => "Keyboard Shortcuts", - Dialog::ViewOptions => "View Options", - } - .to_string(); - let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(16, 12)); - // The import review can be resized (its photo grid takes the room); it keeps a window id of its - // own so the size it is given doesn't carry over to the other dialogs. Its content scrolls - // rather than growing the window when the options below the grid get taller (e.g. Copy). - let import = matches!(dlg, Dialog::Import { .. }); - // The Print dialog sizes itself to the window and scrolls its settings column on its own. - let print = matches!(dlg, Dialog::Print); - let window_id = window_id(&dlg); - // Every other dialog fits the window (#781): its options scroll when they don't, and the title - // bar and the button row stay outside the scroll area. The room they take is measured on the - // previous frame (a guess on the first one). - let chrome_id = window_id.with("chrome"); - let chrome = ctx.data(|d| d.get_temp::(chrome_id)).unwrap_or(DIALOG_CHROME_GUESS); - // Settings keeps its top edge, and the widest it has been, while tabs of different sizes are shown, so its tab - // row stays where it is (centred like the others, the row jumped with each tab's height) - let settings = matches!(dlg, Dialog::Settings { .. }); - let top = (screen.height() * 0.08).clamp(DIALOG_SCREEN_MARGIN, 96.0); - let body_max = - if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome } - .max(DIALOG_MIN_BODY); - let widest_id = window_id.with("widest"); - let widest = if settings { ctx.data(|d| d.get_temp::(widest_id)).unwrap_or(0.0).min(screen.width() * 0.9) } else { 0.0 }; - let mut content_w = 0.0f32; - let mut body_h = None; - // before the window: drawing it closes a dropdown the click lands outside of - let popup_was_open = egui::Popup::is_any_open(ctx); - let shown = egui::Window::new(crate::i18n::tr(&title)).id(window_id) - .collapsible(false) - .resizable(import) - .vscroll(import) - .resize(|r| if import { r.default_height(crate::import::DIALOG_SIZE[1]) } else { r }) - .frame(frame) - .anchor(if settings { egui::Align2::CENTER_TOP } else { egui::Align2::CENTER_CENTER }, [0.0, if settings { top } else { 0.0 }]) - .min_width(widest) - .default_width(match dlg { - Dialog::Import { .. } => crate::import::DIALOG_SIZE[0], - Dialog::SmartRules { .. } => 680.0, - Dialog::AllMetadata { .. } => 620.0, - Dialog::Print => 1100.0, - Dialog::FaceModel { .. } => 460.0, - Dialog::LightroomCatalog { .. } => 440.0, - Dialog::LightroomDestination { .. } => 480.0, - Dialog::ManageEffects { .. } => 560.0, - _ => 380.0, - }) - .show(ctx, |ui| { - // Disabled, not skipped: the dialog keeps its layout and state, but a raw event in the - // first prompt frame cannot toggle a checkbox or press a button underneath it. The - // blocking library window gets the same treatment: it owns input while it is on screen, - // so the dialog behind it must not take focus or accept typed text either. - if raw_blocked { - ui.disable(); - } - ui.spacing_mut().item_spacing.y = 8.0; - body_h = dialog_body(ui, (!import && !print).then_some(title.as_str()), body_max, |ui| match &mut dlg { - Dialog::AutoStack { gap } => { - ui.label(egui::RichText::new(crate::i18n::tr("Stack photos taken within this time of each other:")).color(t.text_label)); - let r = ui.add( - egui::Slider::new(gap, 0.0..=86400.0) - .logarithmic(true) - .smallest_positive(1.0) - .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) - .custom_parser(crate::panels::dialogs::parse_gap), - ); - crate::widgets::named(r, crate::i18n::tr("Stack photos taken within this time of each other:")); - let preview = app.session.execute("stack.auto", &json!({"gap": *gap, "preview": true})).unwrap_or_default(); - let scope = if app.session.selection.ids.len() > 1 { "the selected photos" } else { "the photos in view" }; - ui.label( - egui::RichText::new(crate::i18n::tr_format!("Creates {} stacks from {} of {scope}", preview["stacks"], preview["photos"], scope = crate::i18n::tr(scope))).color(t.text_dim), - ); - } - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { - let n = app.session.selection.ids.len(); - let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) } else { crate::i18n::tr_format!("the {} photos in view", app.session.visible_cloned().len()) }; - ui.label(egui::RichText::new(crate::i18n::tr_format!("Scores {scope} for focus and exposure and finds similar shots taken within seconds of each other (bursts).", scope = scope)).color(t.text_label)); - ui.add_space(6.0); - let r = ui.add(egui::Slider::new(reject_below, 0.0..=80.0).text(crate::i18n::tr("Reject below focus")).step_by(1.0)); - crate::widgets::register(ui, "field:cullReject", r.rect); - ui.label(egui::RichText::new(crate::i18n::tr(if *reject_below > 0.0 { "Blurry photos below the score are flagged as rejects." } else { "0: nothing is rejected." })).color(t.text_dim)); - let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); - crate::widgets::register(ui, "check:cullPick", r.rect); - ui.add_space(6.0); - // the sliders drag over the usual range; their value fields take whatever - // `photo.analyze` accepts (a gap of 0 s to a day, a similarity of 0 to 1) - let r = ui.add( - egui::Slider::new(burst_gap, 1.0..=600.0) - .logarithmic(true) - .smallest_positive(1.0) - .clamping(egui::SliderClamping::Never) - .text(crate::i18n::tr("Burst: shots at most this far apart")) - .custom_formatter(|v, _| crate::panels::dialogs::fmt_gap(v)) - .custom_parser(crate::panels::dialogs::parse_gap), - ); - crate::widgets::register(ui, "field:cullGap", r.rect); - let r = ui.add( - egui::Slider::new(similarity, 0.70..=0.99) - .clamping(egui::SliderClamping::Never) - .text(crate::i18n::tr("Burst: how alike (loose … strict)")) - // a typed 0.995 is kept (whole hundredths would round it to 1.00) - .step_by(0.001) - .min_decimals(2) - .max_decimals(3), - ); - crate::widgets::register(ui, "field:cullSimilar", r.rect); - clamp_cull_burst(burst_gap, similarity); - ui.label(egui::RichText::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).color(t.text_dim)); - ui.label(egui::RichText::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")).color(t.text_dim)); - } - Dialog::WhatsNew => { - egui::ScrollArea::vertical().max_height(list_height(ui, 460.0)).auto_shrink([false, true]).show(ui, |ui| { - for line in WHATS_NEW.lines() { - let l = line.trim_end(); - if let Some(h) = l.strip_prefix("### ") { - ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); - } else if let Some(h) = l.strip_prefix("## ") { - ui.add_space(8.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); - } else if l.starts_with("# ") || l.is_empty() { - } else if let Some(b) = l.strip_prefix("- ") { - ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label)); - } else { - ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label)); - } - } - }); - } - Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::model_dialog(app, ui, &t, info, accepted), - Dialog::FaceModel { info, accepted, .. } => crate::panels::faces::model_dialog(app, ui, &t, info, accepted), - Dialog::LightroomResult { summary, library, details, .. } => { - ui.label(summary.as_str()); - ui.add_space(8.0); - if let Some(library) = library { - ui.label(crate::i18n::tr("Destination library")); - ui.add(egui::Label::new(library.as_str()).wrap().selectable(true)); - ui.label(crate::i18n::tr("Lightroom catalogs import into the open library; no separate catalog folder is created.")); - } else { - ui.label(crate::i18n::tr("These photos are only in memory. Open a library on disk and import the catalog again to save them.")); - } - for detail in details.iter() { - ui.add(egui::Label::new(detail).wrap().selectable(true)); - } - } - Dialog::SystemInfo { rows } => { - egui::Grid::new("sysinfo").num_columns(2).spacing([16.0, 4.0]).striped(true).show(ui, |ui| { - for (k, v) in rows.iter() { - ui.label(egui::RichText::new(crate::i18n::tr(k)).color(t.text_dim)); - ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); - ui.end_row(); - } - }); - if ui.button(crate::i18n::tr("Copy to Clipboard")).clicked() { - let text: String = rows.iter().map(|(k, v)| format!("{k}: {v}\n")).collect(); - ui.ctx().copy_text(text); - } - } - Dialog::AllMetadata { title, rows, search } => { - ui.label(egui::RichText::new(title.as_str()).color(t.text_label)); - let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(search).hint_text(crate::i18n::tr("Filter fields")).desired_width(f32::INFINITY)), crate::i18n::tr("Filter fields")); - crate::widgets::register(ui, "field:metadataSearch", r.rect); - let q = search.trim().to_lowercase(); - let keep = |n: &str, v: &str| q.is_empty() || n.to_lowercase().contains(&q) || v.to_lowercase().contains(&q); - let mut groups: Vec<(String, Vec<(String, String)>)> = Vec::new(); - for row in rows["exif"].as_array().into_iter().flatten() { - let (g, n, v) = (row["group"].as_str().unwrap_or(""), row["name"].as_str().unwrap_or(""), row["value"].as_str().unwrap_or("")); - if !keep(n, v) { - continue; - } - match groups.iter_mut().find(|(x, _)| x == g) { - Some((_, list)) => list.push((n.into(), v.into())), - None => groups.push((g.into(), vec![(n.into(), v.into())])), - } - } - let xmp: Vec<(String, String)> = rows["xmp"] - .as_array() - .into_iter() - .flatten() - .map(|r| (r["name"].as_str().unwrap_or("").to_string(), r["value"].as_str().unwrap_or("").to_string())) - .filter(|(n, v)| keep(n, v)) - .collect(); - if !xmp.is_empty() { - groups.push(("XMP".into(), xmp)); - } - egui::ScrollArea::vertical().max_height(list_height(ui, 440.0)).auto_shrink([false, true]).show(ui, |ui| { - if groups.is_empty() { - ui.label(egui::RichText::new(crate::i18n::tr(rows["note"].as_str().unwrap_or("No metadata found"))).color(t.text_dim)); - } - for (g, list) in &groups { - ui.add_space(6.0); - ui.label(egui::RichText::new(g).font(t.semibold(12.5)).color(t.text)); - egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { - for (n, v) in list { - ui.label(egui::RichText::new(n).color(t.text_dim)); - ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); - ui.end_row(); - } - }); - } - }); - } - Dialog::SmartRules { id, name, rules, .. } => { - let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name")); - crate::widgets::register(ui, "field:smartName", r.rect); - ui.add_space(6.0); - // the folders an album made from a folder view carries are not in the editor, but they count - let folders: Vec = id - .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))) - .and_then(|a| a.smart.as_deref()) - .map(|f| f.library_folder.iter().chain(&f.library_folders).cloned().collect()) - .unwrap_or_default(); - // problems, count and albums: cached until the catalog or the rules change (not per frame) - let now = (app.session.clock)(); - let view = app.caches.rules_view(&app.session.catalog, rules, *id, folders, &now); - let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; - egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { - crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); - }); - let n = view.count; - ui.add_space(4.0); - if view.problems.is_empty() { - ui.label( - egui::RichText::new(crate::i18n::tr_format!("{n} photo{} match · updates automatically as photos change", if n == 1 { "" } else { "s" }, n = n)) - .color(t.text_dim), - ); - } else { - ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.caution)); - } - } - Dialog::NewSmartAlbum { name, .. } => { - if dialog_field(ui, "field:smartAlbumName", name, "Name") { - confirm = true; - } - let rules = app.session.view_rules(); - // counted when the library or the rules change (or, for "in the last…" rules, the minute), not every frame - let now = (app.session.clock)(); - let minute = if rules.depends_on_now() { now.get(..16).unwrap_or(&now) } else { "" }; - let n = app.caches.dialog_count(&app.session.catalog, ("smartAlbum", format!("{rules:?}"), minute), || { - lightcraft_catalog::rules::set_now(Some(now.clone())); - app.session.catalog.query(&rules, &Default::default()).len() - }); - ui.label(egui::RichText::new(crate::i18n::tr_format!("Matches: {}", crate::i18n::filter_label(&rules, &app.session.catalog))).color(t.text_label)); - ui.label( - egui::RichText::new(crate::i18n::tr_format!("{n} photo{} now · updates automatically as photos change", if n == 1 { "" } else { "s" }, n = n)) - .color(t.text_dim), - ); - } - Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => { - let n = app.session.selected().len(); - field(ui, "Change", |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (i, (label, m)) in [("Set date & time", "set"), ("Shift by", "shift"), ("Time zone", "zone")].iter().enumerate() { - if crate::widgets::text_button(ui, &format!("captureMode-{i}"), label, mode == m).clicked() { - *mode = m.to_string(); - } - } - }); - let params = match mode.as_str() { - "set" => { - field(ui, "New time", |ui| { - let r = ui.add(egui::TextEdit::singleline(time).hint_text("2026-09-30 14:05:00").desired_width(f32::INFINITY)); - crate::widgets::register(ui, "field:captureTime", r.rect); - }); - json!({"time": time}) - } - "shift" => { - field(ui, "Shift", |ui| { - ui.add(egui::DragValue::new(days).suffix(" d")); - ui.add(egui::DragValue::new(hours).suffix(" h")); - ui.add(egui::DragValue::new(minutes).suffix(" min")); - }); - json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}) - } - _ => { - field(ui, "Hours", |ui| ui.add(egui::DragValue::new(zone).range(-26.0..=26.0).speed(0.25).fixed_decimals(2))); - json!({"hours": zone}) - } - }; - // preview on the active photo (the others move by the same amount) - let active = app.session.active().and_then(|id| app.session.catalog.photo(id)).map(|p| (p.file_name.clone(), p.date().to_string())); - if let Some((name, cur)) = active { - let delta = match mode.as_str() { - "set" => lightcraft_catalog::dates::normalize_iso(time) - .and_then(|t| Some(lightcraft_catalog::dates::iso_seconds(&t)? - lightcraft_catalog::dates::iso_seconds(&cur)?)), - "shift" => params["shift"].as_i64(), - _ => Some((*zone as f64 * 3600.0).round() as i64), - }; - // the photo's own time is the problem (a Lightroom catalog's capture time - // is copied verbatim), not what was typed - let unreadable = lightcraft_catalog::dates::shift_iso(&cur, 0).is_none(); - let after = match (mode.as_str(), unreadable && n == 1) { - // alone, it simply gets the time typed (photo.setCaptureTime repairs it) - ("set", true) => lightcraft_catalog::dates::normalize_iso(time), - _ => delta.and_then(|d| lightcraft_catalog::dates::shift_iso(&cur, d)), - }; - ui.label( - egui::RichText::new(match after { - Some(a) => format!("{name}: {} → {}", cur.replace('T', " "), a.replace('T', " ")), - None if unreadable && !(mode == "set" && n == 1) => crate::i18n::tr("The active photo's capture time can't be read").to_string(), - None => "Enter a date as YYYY-MM-DD HH:MM:SS".into(), - }) - .color(t.text_label), - ); - } - if n > 1 { - ui.label(egui::RichText::new(crate::i18n::tr_format!("All {n} selected photos move by the same amount.", n = n)).color(t.text_dim)); - } - } - Dialog::LabelNames { names, save_as } => { - names.resize(5, String::new()); - // start from a set - let sets = lightcraft_engine::cmd::manage::label_sets_json(&app.session); - field(ui, "Set", |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for set in sets["sets"].as_array().into_iter().flatten() { - let name = set["name"].as_str().unwrap_or_default(); - if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false).clicked() { - *names = set["names"].as_array().into_iter().flatten().map(|n| n.as_str().unwrap_or_default().to_string()).collect(); - } - } - }); - for (i, l) in lightcraft_catalog::ColorLabel::ALL.iter().enumerate() { - let colour = format!("{l:?}"); - field(ui, &colour, |ui| { - let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); - ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l)); - let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut names[i]).hint_text(colour.as_str()).desired_width(f32::INFINITY)), crate::i18n::tr(&colour)); - crate::widgets::register(ui, format!("field:labelName-{}", colour.to_lowercase()), te.rect); - }); - } - field(ui, "Save as set", |ui| { - let te = crate::widgets::named(ui.add(egui::TextEdit::singleline(save_as).hint_text(crate::i18n::tr("Optional name")).desired_width(f32::INFINITY)), crate::i18n::tr("Save as set")); - crate::widgets::register(ui, "field:labelSetName", te.rect); - }); - ui.label( - egui::RichText::new(crate::i18n::tr("Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.")) - .color(t.text_dim), - ); - } - Dialog::Rename { template, start } => { - let n = app.session.selected().len(); - ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); - let template_id = egui::Id::unique("rename-template"); - let tags_open = field(ui, "Template", |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let w = crate::import::tag_field_width(ui); - let r = crate::widgets::named(ui.add(egui::TextEdit::singleline(template).id(template_id).hint_text("{name}").desired_width(w)), crate::i18n::tr("Template")); - crate::widgets::register(ui, "field:renameTemplate", r.rect); - crate::import::tag_toggle(ui, "renameTemplate") - }); - if tags_open { - crate::import::tag_help(ui, "renameTemplate", template, template_id); - } - crate::import::unknown_tags_warning(ui, template); - field(ui, "Presets", |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (i, (label, tpl)) in - [("Name", "{name}"), ("Date–Name", "{date}_{name}"), ("Title–Seq", "{title}-{seq:3}"), ("Custom–Seq", "Photo-{seq:3}")].iter().enumerate() - { - if crate::widgets::text_button(ui, &format!("renamePreset-{i}"), label, template == tpl).clicked() { - *template = tpl.to_string(); - } - } - }); - field(ui, "Start at", |ui| ui.add(egui::DragValue::new(start).range(0..=999_999))); - ui.label( - egui::RichText::new(crate::i18n::tr("Tags: see Tags beside the template. Files are renamed on disk (with their XMP sidecars); existing names get -1, -2…")) - .color(t.text_dim), - ); - let (preview, total) = rename_preview(app, ui.ctx(), template, *start as usize); - match &preview { - Some(rows) => { - egui::Grid::new("rename-preview").num_columns(3).spacing([8.0, 2.0]).show(ui, |ui| { - for pl in rows { - ui.label(egui::RichText::new(&pl.from).color(t.text_dim)); - let (arrow, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); - crate::icons::paint(ui.painter(), arrow, crate::icons::Icon::ChevronRight, t.text_dim); - ui.label(egui::RichText::new(&pl.to).color(t.text)); - ui.end_row(); - } - }); - } - None => { - ui.horizontal(|ui| { - crate::progress::spinner(ui, 12.0); - ui.label(egui::RichText::new(crate::i18n::tr("Checking names…")).color(t.text_dim)); - }); - } - } - let more = total.saturating_sub(RENAME_PREVIEW_ROWS); - if more > 0 { - ui.label(egui::RichText::new(crate::i18n::tr_format!("… and {more} more", more = more)).color(t.text_dim)); - } - } - Dialog::RenamePerson { from, to, merge } => { - let submitted = dialog_field(ui, "field:personName", to, "Name"); - let plan = person_rename_plan(&app.session.catalog, from, to); - if !plan.needs_merge { - *merge = false; - } - if submitted && plan.block.is_none() && (!plan.needs_merge || *merge) { - confirm = true; - } - if let Some(why) = plan.block { - ui.label(egui::RichText::new(crate::i18n::tr(why)).color(t.caution)); - } else { - ui.label( - egui::RichText::new(crate::i18n::tr_format!( - "Renames {n} face{} across the library. The files are not changed.", - if plan.faces == 1 { "" } else { "s" }, - n = plan.faces - )) - .color(t.text_dim), - ); - } - if plan.needs_merge { - ui.label( - egui::RichText::new(crate::i18n::tr_format!("“{to}” is already a person. Combining them makes one person; Undo separates them again.", to = to.trim())) - .color(t.caution), - ); - let r = ui.checkbox(merge, crate::i18n::tr("Combine with the existing person")); - crate::widgets::register(ui, "check:personMerge", r.rect); - } - } - Dialog::RenameKeyword { from, to } => { - let n = app.caches.dialog_count(&app.session.catalog, ("renameKeyword", from.as_str()), || { - app.session.catalog.photos().filter(|p| p.meta.keywords.iter().any(|k| lightcraft_catalog::keywords::is_under(k, from))).count() - }); - if dialog_field(ui, "field:keywordName", to, "New name") { - confirm = true; - } - ui.label( - egui::RichText::new(crate::i18n::tr_format!("Renames “{from}” on {n} photo{} (keywords below it too). Use | for levels, e.g. Travel|Italy. An existing name merges the two.", - if n == 1 { "" } else { "s" }, from = from, n = n)) - .color(t.text_dim), - ); - } - Dialog::MergeKeywords { from, into } => { - ui.label(egui::RichText::new(crate::i18n::tr_format!("Replace {} with:", from.iter().map(|f| format!("“{f}”")).collect::>().join(", "))).color(t.text_label)); - if dialog_field(ui, "field:keywordInto", into, "Keyword") { - confirm = true; - } - let options: Vec = app - .caches - .suggestions(&app.session.catalog, from, into, 12) - .iter() - .filter(|k| !from.iter().any(|f| lightcraft_catalog::keywords::is_under(k, f))) - .cloned() - .collect(); - ui.horizontal_wrapped(|ui| { - for k in options { - if ui.add(egui::Button::new(egui::RichText::new(&k).color(t.text_label)).corner_radius(10.0)).clicked() { - *into = k; - } - } - }); - } - Dialog::TextPrompt { value, hint, .. } => { - if dialog_field(ui, "field:prompt", value, hint) { - confirm = true; - } - } - Dialog::NewAlbum { name, folder, include_selected, .. } => { - if dialog_field(ui, "field:albumName", name, "Name") { - confirm = true; - } - // as in Lightroom, the option is only there when something is selected - if !*folder && !app.session.selected().is_empty() { - ui.add_space(6.0); - let r = ui.checkbox(include_selected, crate::i18n::tr("Include selected photos")); - crate::widgets::register(ui, "check:albumIncludeSelected", r.rect); - } - } - Dialog::RenameAlbum { name, .. } => { - if dialog_field(ui, "field:albumName", name, "Name") { - confirm = true; - } - } - Dialog::CreatePreset { name, group, groups } => { - crate::widgets::named(ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Preset name")).desired_width(f32::INFINITY)), crate::i18n::tr("Preset name")); - crate::widgets::named(ui.add(egui::TextEdit::singleline(group).hint_text(crate::i18n::tr("Group")).desired_width(f32::INFINITY)), crate::i18n::tr("Group")); - ui.label(egui::RichText::new(crate::i18n::tr("Settings to include")).color(t.text_dim)); - group_checklist(ui, "presetInclude", groups); - } - Dialog::CopySettings { groups } => group_checklist(ui, "copyGroup", groups), - Dialog::PasteSettings { groups } => { - let n = app.session.selected().len(); - ui.label( - egui::RichText::new(crate::i18n::tr_format!("Paste into {n} photo{} — only settings that were copied are pasted", if n == 1 { "" } else { "s" }, n = n)) - .color(t.text_dim), - ); - group_checklist(ui, "pasteGroup", groups); - } - Dialog::SlideshowExport { settings } => slideshow_export_body(app, ui, settings), - Dialog::ContactSheet { options } => { - options.columns = options.columns.clamp(1, 8); - options.rows = options.rows.clamp(1, 10); - let n = app.session.selected().len(); - ui.label(crate::i18n::tr_format!("{n} selected photos · {pages} pages", n = n, pages = n.div_ceil(options.columns * options.rows))); - field(ui, "Paper", |ui| { - let c = crate::widgets::combo_box("contactSheetPaper").selected_text(&options.paper).show_ui(ui, |ui| { - ui.selectable_value(&mut options.paper, "a4".into(), "A4"); - ui.selectable_value(&mut options.paper, "letter".into(), crate::i18n::tr("Letter")); - }); - crate::widgets::name_combo(&c.response, crate::i18n::tr("Paper")); - }); - ui.checkbox(&mut options.landscape, crate::i18n::tr("Landscape")); - field(ui, "Columns", |ui| { ui.add(egui::DragValue::new(&mut options.columns).range(1..=8)); }); - field(ui, "Rows", |ui| { ui.add(egui::DragValue::new(&mut options.rows).range(1..=10)); }); - ui.checkbox(&mut options.captions, crate::i18n::tr("Filename captions")); - ui.label(crate::i18n::tr("150 dpi · sRGB · current edits · fit without cropping")); - ui.label(crate::i18n::tr("Choose a PDF destination after confirming. Print the PDF from your viewer.")); - } - Dialog::Export { opts, full_size, resize, preset_name, limit_kb, dir } => { - use lightcraft_engine::export::{ExportFormat as F, MetadataPolicy as M, SharpenAmount as A, SharpenFor as S}; - let n = app.session.selection.ids.len().max(1); - ui.label(egui::RichText::new(crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n)).color(t.text_dim)); - // Preset: load a built-in or saved set of options into the dialog - field(ui, "Preset", |ui| { - let mut chosen = None; - let c = crate::widgets::combo_box("exportPreset").width(220.0).selected_text(crate::i18n::tr("Choose…")).show_ui(ui, |ui| { - let mut builtin = true; - for (p, b) in app.session.all_export_presets() { - if builtin && !b { - ui.separator(); - } - builtin = b; - if ui.selectable_label(false, crate::i18n::builtin_label(&p.name, b)).clicked() { - chosen = Some(p.name); - } - } - }); - crate::widgets::name_combo(&c.response, crate::i18n::tr("Preset")); - crate::widgets::register(ui, "combo:exportPreset", c.response.rect); - if let Some(name) = chosen - && let Ok(params) = app.session.export_params(&json!({"preset": name})) - { - let o = lightcraft_engine::export::ExportOptions::from_json(¶ms); - *full_size = o.resize.is_none(); - *resize = o.resize.unwrap_or_default(); - *limit_kb = o.limit_kb.unwrap_or(0); - *opts = o; - } - }); - ui.add_space(4.0); - let before = opts.format; - // "Rendered DNG" is a DNG option (below), not a format of its own in this list - let mut shown = if opts.format == F::RenderedDng { F::Dng } else { opts.format }; - choices( - ui, - "Format", - "exportFormat", - &[(F::Jpeg, "JPEG"), (F::Png, "PNG"), (F::Tiff, "TIFF"), (F::Psd, "PSD"), (F::Webp, "WebP"), (F::Avif, "AVIF"), (F::Jxl, "JPEG XL"), (F::Dng, "DNG"), (F::Original, "Original files")], - &mut shown, - ); - if shown != opts.format && !(shown == F::Dng && opts.format == F::RenderedDng) { - opts.format = shown; - } - if matches!(opts.format, F::Dng | F::RenderedDng) { - choices(ui, "DNG of", "exportDngKind", &[(F::Dng, "Raw data"), (F::RenderedDng, "Rendered photo")], &mut opts.format); - } - if !opts.format.is_rendered() { - let note = if opts.format == F::Dng { - "Raw photos as DNG, with the edits embedded. Size, color and output options don't apply." - } else { - "The original files, unchanged, each with an XMP sidecar holding its edits." - }; - ui.label(egui::RichText::new(note).color(t.text_dim)); - } - if opts.format != before { - // each format starts at its own default depth (TIFF 16-bit, others 8-bit) - opts.bit_depth = None; - } - let rendered = opts.format.is_rendered(); - let depths = lightcraft_engine::export::ExportOptions::bit_depths(opts.format); - if rendered && depths.len() > 1 { - let mut bd = opts.bit_depth.filter(|b| depths.iter().any(|d| d.0 == *b)).unwrap_or(depths[0].0); - choices(ui, "Bit depth", "exportBitDepth", depths, &mut bd); - opts.bit_depth = Some(bd); - } - if matches!(opts.format, F::Jpeg | F::Tiff | F::Avif | F::Png | F::Jxl) { - let tip = crate::i18n::tr("Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float"); - ui.checkbox(&mut opts.hdr, crate::i18n::tr("HDR output")).on_hover_text(tip); - if opts.hdr && !opts.hdr_output() { - ui.label(egui::RichText::new(crate::i18n::tr("HDR TIFF needs 32-bit float.")).color(t.text_dim)); - } - if opts.hdr && opts.format == F::Avif { - use lightcraft_engine::export::HdrCurve as H; - choices(ui, "HDR curve", "exportHdrCurve", &[(H::Pq, "PQ"), (H::Hlg, "HLG")], &mut opts.hdr_transfer); - } - } - if !rendered { - } else if opts.format == F::Avif && opts.hdr { - let label = if opts.hdr_transfer == lightcraft_engine::export::HdrCurve::Hlg { - crate::i18n::tr("Color space: Rec. 2020 HLG (HDR AVIF)") - } else { - crate::i18n::tr("Color space: Rec. 2020 PQ (HDR AVIF)") - }; - ui.label(egui::RichText::new(label).color(t.text_dim)); - } else if opts.format == F::Png && opts.hdr { - ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ, 16-bit (HDR PNG)")).color(t.text_dim)) - .on_hover_text(crate::i18n::tr("Viewers that don't read the PNG cICP chunk show PQ values as sRGB: flat and washed out. For a picture that looks right everywhere, use JPEG (gain map).")); - } else if opts.format == F::Jxl && opts.hdr { - ui.label(egui::RichText::new(crate::i18n::tr("Color space: Rec. 2020 PQ (HDR JPEG XL)")).color(t.text_dim)); - } else if opts.format == F::Avif { - ui.label(egui::RichText::new(crate::i18n::tr("Color space: sRGB (AVIF)")).color(t.text_dim)); - } else { - use lightcraft_engine::export::OutputSpace as C; - choices( - ui, - "Color space", - "exportColorSpace", - &[ - (C::Srgb, "sRGB"), - (C::DisplayP3, "P3"), - (C::AdobeRgb, "Adobe RGB"), - (C::ProPhoto, "ProPhoto"), - (C::Rec2020, "Rec.2020"), - ], - &mut opts.color_space, - ); - if opts.effective_space() != opts.color_space { - let note = "Lossy JPEG XL writes Adobe RGB and ProPhoto as Rec. 2020; choose Lossless to keep them."; - ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)); - } - } - if opts.format == F::Jxl { - let tip = "Mathematically lossless: every pixel is kept exactly (larger files)"; - ui.checkbox(&mut opts.jxl_lossless, crate::i18n::tr("Lossless")).on_hover_text(crate::i18n::tr(tip)); - } - if matches!(opts.format, F::Jpeg | F::Avif) || (opts.format == F::Jxl && !opts.jxl_lossless) { - let mut q = opts.quality as f64; - if num(ui, &QUALITY, &mut q) { - opts.quality = q as u8; - } - } - if opts.format == F::Jxl { - use lightcraft_engine::export::JxlEffort as E; - choices(ui, "Effort", "exportJxlEffort", &[(E::Fast, "Fast"), (E::Normal, "Normal")], &mut opts.jxl_effort); - let tip = "Shows a coarse version first and refines it as the file loads"; - ui.checkbox(&mut opts.jxl_progressive, crate::i18n::tr("Progressive")).on_hover_text(crate::i18n::tr(tip)); - } - if opts.format == F::Jpeg { - let mut k = *limit_kb as f64; - if num(ui, &LIMIT_KB, &mut k) { - *limit_kb = k as u32; - } - } - if rendered { - export_size(ui, full_size, resize, &mut opts.ppi); - } - if rendered { - choices( - ui, - "Sharpen", - "exportSharpen", - &[(S::None, "None"), (S::Screen, "Screen"), (S::Matte, "Matte"), (S::Glossy, "Glossy")], - &mut opts.sharpen, - ); - if opts.sharpen != S::None { - choices( - ui, - "Amount", - "exportSharpenAmount", - &[(A::Low, "Low"), (A::Standard, "Standard"), (A::High, "High")], - &mut opts.sharpen_amount, - ); - } - } - if rendered { - choices( - ui, - "Metadata", - "exportMetadata", - &[(M::All, "All"), (M::AllExceptCamera, "No camera"), (M::Copyright, "Copyright"), (M::None, "None")], - &mut opts.metadata, - ); - if !matches!(opts.metadata, M::None | M::Copyright) { - ui.checkbox(&mut opts.remove_location, crate::i18n::tr("Remove location info")); - } - let mut wm_on = opts.watermark.is_some(); - if ui.checkbox(&mut wm_on, crate::i18n::tr("Watermark")).changed() { - opts.watermark = wm_on.then(|| lightcraft_engine::export::Watermark { text: "© ".into(), ..Default::default() }); - } - let wm_shown = opts.watermark.clone(); - if let Some(wm) = &wm_shown { - watermark_preview(app, ui, wm, (!*full_size).then_some(*resize)); - } - if let Some(wm) = &mut opts.watermark { - // text, or a graphic (a logo with transparency) - let mut graphic = !wm.image.is_empty() || ui.data(|d| d.get_temp::(egui::Id::unique("wm-graphic"))).unwrap_or(false); - let before = graphic; - choices(ui, "Style", "exportWmStyle", &[(false, "Text"), (true, "Graphic")], &mut graphic); - if graphic != before { - ui.data_mut(|d| d.insert_temp(egui::Id::unique("wm-graphic"), graphic)); - if !graphic { - wm.image.clear(); - } - } - if graphic { - field(ui, "Graphic", |ui| { - trailing_button_row(ui, |ui| { - if app.services.pick_files.is_some() - && crate::widgets::text_button(ui, "exportWmChoose", crate::i18n::tr("Choose…"), false).clicked() - && let Some(f) = app.services.pick_files.as_mut().and_then(|pick| pick().into_iter().next()) - { - wm.image = f; - } - crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut wm.image).hint_text("logo.png").desired_width(ui.available_width())), crate::i18n::tr("Image")); - }); - }); - let mut width = wm.image_width as f64 * 100.0; - if num(ui, &WM_IMAGE_WIDTH, &mut width) { - wm.image_width = (width / 100.0) as f32; - } - } else { - choices(ui, app.ui.language.tr("Text direction"), "exportWmOrientation", &[(false, app.ui.language.tr("Horizontal text")), (true, app.ui.language.tr("Vertical text"))], &mut wm.vertical); - field(ui, "Text", |ui| { - crate::widgets::named(ui.add(egui::TextEdit::multiline(&mut wm.text).desired_rows(2).hint_text(crate::i18n::tr("© Your Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Text")) - }); - } - choices( - ui, - "Position", - "exportWmAnchor", - &WM_POSITIONS, - &mut wm.anchor, - ); - choices(ui, "Rotate", "exportWmRotation", &[(0u16, "0°"), (90, "90°"), (180, "180°"), (270, "270°")], &mut wm.rotation); - let mut size = wm.size as f64 * 100.0; - if !graphic && num(ui, &WM_SIZE, &mut size) { - wm.size = (size / 100.0) as f32; - } - let mut op = wm.opacity as f64 * 100.0; - if num(ui, &WM_OPACITY, &mut op) { - wm.opacity = (op / 100.0) as f32; - } - // like Lightroom Classic: a margin from the side edges and one from the top and bottom - // edges, each unused (greyed) when the position is centred along that axis - use lightcraft_engine::export::Anchor as P; - let across = !matches!(wm.anchor, P::Top | P::Center | P::Bottom); - if let Some(v) = crate::widgets::slider(ui, &WM_INSET_X, wm.inset_x as f64 * 100.0, across, None).value { - wm.inset_x = (v / 100.0) as f32; - } - let down = !matches!(wm.anchor, P::Left | P::Center | P::Right); - if let Some(v) = crate::widgets::slider(ui, &WM_INSET_Y, wm.inset_y as f64 * 100.0, down, None).value { - wm.inset_y = (v / 100.0) as f32; - } - if !graphic { - ui.checkbox(&mut wm.shadow, crate::i18n::tr("Shadow")); - } - } - if opts.watermark != wm_shown { - // the preview above was drawn with the old settings - ui.ctx().request_repaint(); - } - } - ui.add_space(4.0); - if opts.format == F::Tiff { - use lightcraft_engine::export::TiffCompression as Z; - choices(ui, "Compression", "exportTiffCompression", &[(Z::None, "None"), (Z::Lzw, "LZW"), (Z::Deflate, "ZIP")], &mut opts.tiff_compression); - } - if opts.format == F::Dng { - use lightcraft_engine::export::DngCompression as Z; - choices(ui, "Compression", "exportDngCompression", &[(Z::Lossless, "Lossless"), (Z::Deflate, "ZIP"), (Z::Uncompressed, "None"), (Z::Lossy, "Lossy")], &mut opts.dng_compression); - } - let naming_id = egui::Id::unique("export-naming"); - let tags_open = field(ui, "File name", |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let w = crate::import::tag_field_width(ui); - crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.naming).id(naming_id).hint_text("{name}-{seq} · {date} · {title} · {folder}").desired_width(w)), crate::i18n::tr("File name")); - crate::import::tag_toggle(ui, "exportNaming") - }); - if tags_open { - crate::import::tag_help(ui, "exportNaming", &mut opts.naming, naming_id); - } - crate::import::unknown_tags_warning(ui, &opts.naming); - if opts.naming.contains("{seq") { - let mut v = opts.start_number as f64; - if num(ui, &START_NUMBER, &mut v) { - opts.start_number = v as u32; - } - } - // like Lightroom Classic's Export To: one folder, or each photo's own folder (not on - // the web, where originals live in the browser's storage, not in folders) - use lightcraft_engine::export::DestinationMode as D; - if !cfg!(target_arch = "wasm32") || opts.destination_mode != D::SpecificFolder { - choices( - ui, - "Export to", - "exportDestinationMode", - &[(D::SpecificFolder, "Specific folder"), (D::SameAsOriginal, "Same folder as original photo")], - &mut opts.destination_mode, - ); - } - if opts.destination_mode == D::SpecificFolder { - field(ui, "Folder", |ui| { - trailing_button_row(ui, |ui| { - if app.services.pick_folder.is_some() - && crate::widgets::text_button(ui, "exportChooseFolder", crate::i18n::tr("Choose…"), false).clicked() - && let Some(pick) = app.services.pick_folder.as_mut() - && let Some(d) = pick() - { - *dir = d; - } - crate::widgets::named(ui.add(egui::TextEdit::singleline(dir).desired_width(ui.available_width())), crate::i18n::tr("Folder")); - }); - }); - } - field(ui, "Subfolder", |ui| { - crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.subfolder).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), crate::i18n::tr("Subfolder")) - }); - use lightcraft_engine::export::Conflict as K; - choices( - ui, - "If file exists", - "exportConflict", - &[(K::Unique, "Add number"), (K::Overwrite, "Overwrite"), (K::Skip, "Skip")], - &mut opts.conflict, - ); - // After export: Apple Photos imports the files written (macOS only) - #[cfg(target_os = "macos")] - { - let r = ui.checkbox(&mut opts.add_to_photos, crate::i18n::tr("Add to Apple Photos")); - crate::widgets::register(ui, "exportAddToPhotos", r.rect); - if opts.add_to_photos { - field(ui, "Album", |ui| { - crate::widgets::named(ui.add(egui::TextEdit::singleline(&mut opts.photos_album).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)), crate::i18n::tr("Album")) - }); - ui.label( - egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")) - .size(11.0) - .color(t.text_dim), - ); - } - } - // nowhere to add them: a setting carried over from a Mac is dropped, not refused - #[cfg(not(target_os = "macos"))] - { - opts.add_to_photos = false; - } - ui.add_space(4.0); - field(ui, "Save preset", |ui| { - trailing_button_row(ui, |ui| { - let named = !preset_name.trim().is_empty(); - if crate::widgets::text_button(ui, "exportSavePreset", crate::i18n::tr("Save"), false).clicked() && named { - let params = export_dialog_params(opts, *full_size, resize, *limit_kb); - match app.run("export.savePreset", json!({"name": preset_name.trim(), "params": params})) { - Ok(_) => { - app.toast(ui.ctx(), crate::i18n::tr_format!("Saved export preset “{}”", preset_name.trim())); - preset_name.clear(); - } - Err(e) => app.toast(ui.ctx(), e), - } - } - crate::widgets::named(ui.add(egui::TextEdit::singleline(preset_name).hint_text(crate::i18n::tr("Preset name")).desired_width(ui.available_width())), crate::i18n::tr("Preset name")); - }); - }); - } - Dialog::Merge { opts } => crate::merge::body(app, ui, opts), - Dialog::Import { opts } => crate::import::body(app, ui, opts), - // (Settings is never taller than `body_max`, so the scroll area round it never - // scrolls: its tab bar stays put and its pages scroll by themselves) - Dialog::Settings { tab } => crate::panels::settings::window(app, ui, tab, body_max), - Dialog::SamModel { error, .. } => sam_model_body(app, ui, error.as_deref()), - Dialog::KeywordTag { - editing, - name, - parent, - inside, - synonyms, - include_on_export, - export_containing, - export_synonyms, - person, - add_to_selected, - .. - } => { - ui.label(egui::RichText::new(crate::i18n::tr("Keyword Name")).color(t.text_dim)); - // several fields: the name takes the focus when the dialog opens, not after - let r = crate::text_field::TextField::singleline("field:keywordTagName", name) - .hint(crate::i18n::tr("Keyword Name")) - .width(f32::INFINITY) - .select_on_focus(true) - .show(ui); - if ui.is_enabled() && just_opened(ui, "keyword-tag") { - r.response.request_focus(); - } - if r.ending == Some(crate::text_field::Ending::Return) { - confirm = true; - } - ui.add_space(4.0); - ui.label(egui::RichText::new(crate::i18n::tr("Synonyms")).color(t.text_dim)); - // Return in either field creates (or saves) the keyword - let r = crate::text_field::TextField::singleline("field:keywordSynonyms", synonyms) - .hint(crate::i18n::tr("Separated by commas")) - .width(f32::INFINITY) - .show(ui); - if r.ending == Some(crate::text_field::Ending::Return) { - confirm = true; - } - ui.add_space(6.0); - if editing.is_none() { - if let Some(p) = parent { - let r = ui.checkbox(inside, crate::i18n::tr_format!("Put inside “{parent}”", parent = p.replace('|', " › "))); - crate::widgets::register(ui, "check:keywordInside", r.rect); - } - let n = app.session.selection.ids.len(); - let r = ui.add_enabled(n > 0, egui::Checkbox::new(add_to_selected, crate::i18n::tr("Add to Selected Photos"))); - crate::widgets::register(ui, "check:keywordAddToSelected", r.rect); - ui.add_space(4.0); - } - ui.label(egui::RichText::new(crate::i18n::tr("Keyword Tag Options")).color(t.text_dim)); - for (on, label, id) in [ - (include_on_export, "Include on Export", "check:keywordIncludeOnExport"), - (export_containing, "Export Containing Keywords", "check:keywordExportContaining"), - (export_synonyms, "Export Synonyms", "check:keywordExportSynonyms"), - (person, "Person", "check:keywordPerson"), - ] { - let r = ui.checkbox(on, crate::i18n::tr(label)); - crate::widgets::register(ui, id, r.rect); - } - } - Dialog::KeywordSet { replaces, name, slots, as_new } => { - ui.label(egui::RichText::new(crate::i18n::tr("Set name")).color(t.text_dim)); - let r = crate::text_field::TextField::singleline("field:keywordSetName", name) - .hint(crate::i18n::tr("Set name")) - .width(f32::INFINITY) - .select_on_focus(true) - .show(ui); - if ui.is_enabled() && just_opened(ui, "keyword-set") { - r.response.request_focus(); - } - let mut returned = r.ending == Some(crate::text_field::Ending::Return); - ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr("Keywords (⌥1–⌥9)")).color(t.text_dim)); - slots.resize(9, String::new()); - // equal columns of a set width (the window is still finding its own) - let w = 130.0; - egui::Grid::new("keyword-set-slots").num_columns(3).min_col_width(w).spacing([6.0, 4.0]).show(ui, |ui| { - for (i, slot) in slots.iter_mut().enumerate() { - let r = crate::text_field::TextField::singleline(&format!("field:keywordSetSlot:{}", i + 1), slot) - .hint(format!("⌥{}", i + 1)) - .width(w) - .show(ui); - returned |= r.ending == Some(crate::text_field::Ending::Return); - if i % 3 == 2 { - ui.end_row(); - } - } - }); - if replaces.is_some() { - ui.add_space(6.0); - let r = ui.checkbox(as_new, crate::i18n::tr("Save as a new set")); - crate::widgets::register(ui, "check:keywordSetAsNew", r.rect); - } - // Return in any field saves the set - if returned { - confirm = true; - } - } - Dialog::MoveKeyword { keyword, parent } => { - let name = keyword.rsplit('|').next().unwrap_or(keyword); - match parent { - Some(p) => ui.label(crate::i18n::tr_format!( - "“{parent}” has a “{name}” already. Merge the two?", - parent = p.replace('|', " › "), - name = name - )), - None => ui.label(crate::i18n::tr_format!("There is a “{name}” at the top level already. Merge the two?", name = name)), - }; - ui.label(egui::RichText::new(crate::i18n::tr("Their photos and the keywords below them come together under one keyword.")).color(t.text_dim)); - } - Dialog::DeleteKeyword { keyword, count } => { - let name = keyword.replace('|', " › "); - ui.label(crate::i18n::tr_format!("Delete the keyword “{name}”?", name = name)); - ui.label( - egui::RichText::new(if *count == 0 { - crate::i18n::tr("No photo has it; the keywords below it go too.").to_string() - } else { - crate::i18n::tr_format!( - "It is taken off {count} photo{}, with the keywords below it. Undo brings it back.", - if *count == 1 { "" } else { "s" }, - count = count - ) - }) - .color(t.text_dim), - ); - } - Dialog::SaveEffect { name, group, fields, amount, brush } => { - if crate::panels::mask_effects::save_body(app, ui, name, group, fields, amount, brush) { - confirm = true; - } - } - Dialog::ManageEffects { search, selected, rename, confirm_delete, new_group } => { - crate::panels::mask_effects::manage_body(app, ui, search, selected, rename, confirm_delete, new_group) - } - Dialog::DeleteEffects { names } => { - let what = match names.as_slice() { - [one] => crate::i18n::tr_format!("Delete the effect preset “{name}”?", name = one), - _ => crate::i18n::tr_format!("Delete these {n} effect presets?", n = names.len()), - }; - ui.label(what); - ui.label(egui::RichText::new(crate::i18n::tr("Masks keep their sliders. Export presets first to keep a copy.")).color(t.text_dim)); - } - Dialog::ConfirmDelete { count } => { - let what = if *count == 1 { crate::i18n::tr("this photo").to_string() } else { crate::i18n::tr_format!("these {count} photos", count = count) }; - ui.label(crate::i18n::tr_format!("Move {what} to Recently Deleted?", what = what)); - ui.label(egui::RichText::new(crate::i18n::tr("They can be restored from Recently Deleted until it is emptied.")).color(t.text_dim)); - } - Dialog::MovePhotos { ids, name, dont_ask, .. } => { - let n = ids.len(); - ui.label(crate::i18n::tr_format!("Move {n} photo{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); - ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim)); - ui.add_space(4.0); - let c = ui.checkbox(dont_ask, crate::i18n::tr("Don't ask again")); - crate::widgets::register(ui, "check:moveDontAsk", c.rect); - c.on_hover_text(crate::i18n::tr("Settings → Confirm before moving photos to another folder on disk turns it back on")); - } - d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d), - Dialog::LightroomCatalog { folder, catalog } => { - ui.label(crate::i18n::tr("This is a Lightroom catalog, not a LightCraft library. Import it into a LightCraft library instead?")); - ui.label(egui::RichText::new(catalog.as_deref().unwrap_or(folder.as_str())).color(t.text_dim)); - // (the import then asks where the catalog goes, unless Settings says to merge, #2672) - let asks = app.ui.settings.lightroom_import == crate::state::LightroomImport::Ask - && app.session.library.as_ref().is_some_and(|l| l.on_disk); - let what = if asks { - "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library." - } else { - "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now." - }; - ui.label(egui::RichText::new(crate::i18n::tr(what)).color(t.text_dim)); - } - d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d), - Dialog::RemoveFolder { name, count, path, disk } => { - ui.label(crate::i18n::tr_format!( - "Remove “{name}” and its {count} photo{} from the library?", - if *count == 1 { "" } else { "s" }, - name = name, - count = count - )); - ui.label(egui::RichText::new(path.as_str()).color(t.text_dim)); - let scope = if *disk { "All the photos imported from this disk are included." } else { "That includes the photos in the folders inside it." }; - ui.label(egui::RichText::new(crate::i18n::tr(scope)).color(t.text_dim)); - ui.label( - egui::RichText::new(crate::i18n::tr("They move to Recently Deleted and can be restored; no file on disk is touched.")) - .color(t.text_dim), - ); - } - Dialog::About => { - ui.set_min_width(680.0); - let tab_id = egui::Id::unique("about_tab"); - let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (i, (id, label)) in ABOUT_TABS.iter().enumerate() { - if crate::widgets::text_button(ui, &format!("aboutTab-{id}"), label, usize::from(tab) == i).clicked() { - tab = u8::try_from(i).unwrap_or(0); - } - } - }); - ui.data_mut(|d| d.insert_temp(tab_id, tab)); - ui.separator(); - match tab { - 1 => crate::credits::contributors_ui(app, ui), - 2 => crate::credits::models_ui(ui), - _ => { - ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text)); - ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION"))); - ui.label(crate::i18n::tr_format!( - "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", - crate::theme::font_credits(app.chinese_font.is_some()) - )); - ui.add_space(10.0); - let r = crate::button::Button::new("Join the ArtCraft Discord") - .primary() - .large() - .min_width(260.0) - .widget("button:aboutDiscord") - .tooltip(crate::links::DISCORD) - .show(ui); - if r.clicked() { - let _ = crate::links::open(app, crate::links::DISCORD); - } - ui.add_space(6.0); - for (label, url) in [ - ("LightCraft website", crate::links::APP_PAGE), - ("Source code on GitHub", crate::links::GITHUB), - ("ArtCraft — more creative apps", crate::links::WEBSITE), - ] { - let r = ui.link(crate::i18n::tr(label)).on_hover_text(url); - if r.clicked() { - let _ = crate::links::open(app, url); - } - } - } - } - } - Dialog::Shortcuts => crate::panels::keymap::body(app, ui, &t), - Dialog::ViewOptions => crate::panels::settings::view_options(app, ui, &t), - Dialog::Print => crate::print_view::body(app, ui, &t), - }); - ui.add_space(4.0); - // the confirm on the right with Cancel to its left (macOS and GNOME's order), filled with - // the accent when it is the dialog's primary action. The row spans the width the window - // gives its content this frame (its default width, or its content's if wider), so it - // reaches the edge without widening the window. - let row_w = ui.available_width().max(ui.min_rect().width()).max(1.0); - let row_h = ui.spacing().interact_size.y; - ui.allocate_ui_with_layout(egui::vec2(row_w, row_h), egui::Layout::left_to_right(egui::Align::Center), |ui| { - // a model file LightCraft cannot use has nothing to confirm, nor has a dialog that - // only shows something (one Close, no Cancel / OK) - let unusable_model = matches!(&dlg, Dialog::DenoiseModel { info, .. } | Dialog::FaceModel { info, .. } if info["kind"] == "unsupported"); - let informational = unusable_model || matches!(dlg, Dialog::LightroomResult { first: None, .. }) || only_shows(&dlg); - let sam = &app.session.segmenter; - let (sam_installed, sam_running, sam_failed) = (sam.installed(), sam.download_status().running, sam.download_status().error.is_some()); - // no download location in this build: nothing to offer but the manual install - let sam_nowhere = sam_by_hand(sam); - let cancel = match &dlg { - Dialog::SamModel { .. } if sam_running || sam_installed || sam_nowhere => "Close", - Dialog::SamModel { .. } => "Not Now", - Dialog::LightroomResult { .. } => "Close", - _ => "Cancel", - }; - let add_label; - let ok = match &dlg { - Dialog::Import { opts } => { - let n = opts.selected_paths().len(); - let verb = if opts.copy && opts.move_files { "Move" } else { "Import" }; - add_label = crate::i18n::tr_format!("{verb} {n} Photo{}", if n == 1 { "" } else { "s" }, verb = crate::i18n::tr(verb), n = n); - add_label.as_str() - } - Dialog::LightroomResult { first: Some(_), .. } => "Show in Library", - Dialog::ContactSheet { .. } => "Choose PDF…", - Dialog::SlideshowExport { .. } => "Export…", - Dialog::Print => "Print to PDF…", - Dialog::Merge { .. } => "Merge", - Dialog::DenoiseModel { info, .. } if info["download"].is_string() => "Accept & Download", - Dialog::DenoiseModel { .. } => "Install", - Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download", - Dialog::FaceModel { .. } if !informational => "Install", - Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } => "Delete", - Dialog::SaveEffect { .. } => "Create", - Dialog::MovePhotos { .. } => "Move", - // (not "Merge": that is photo merging, HDR / panorama, in some languages) - Dialog::MoveKeyword { .. } => "Merge Keywords", - Dialog::KeywordSet { .. } => "Save", - Dialog::KeywordTag { editing: None, .. } => "Create", - Dialog::KeywordTag { .. } => "Save", - Dialog::RemoveFolder { .. } => "Remove", - Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", - d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), - Dialog::SynchronizeFolder { .. } if informational => "Close", - Dialog::SynchronizeFolder { .. } => "Synchronize", - Dialog::SamModel { then: Some(_), .. } if sam_installed => "Continue", - Dialog::SamModel { .. } if sam_installed || sam_running || sam_nowhere => "", - Dialog::SamModel { error, .. } if error.is_some() || sam_failed => "Try Again", - Dialog::SamModel { .. } => "Download", - Dialog::RenamePerson { from, to, .. } if person_rename_plan(&app.session.catalog, from, to).needs_merge => "Merge", - _ if informational => "Close", - _ => "OK", - }; - // installing waits for the licence to be accepted - // (and Synchronize waits for the scan) - let rename_blocked = match &dlg { - Dialog::RenamePerson { from, to, merge } => { - let plan = person_rename_plan(&app.session.catalog, from, to); - plan.block.is_some() || (plan.needs_merge && !*merge) - } - _ => false, - }; - let can_confirm = !rename_blocked - && (informational - || !matches!( - &dlg, - Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. } - ) - // smart-album rules that can't mean anything wait to be fixed - && !matches!(&dlg, Dialog::SmartRules { id, rules, .. } if !rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).is_empty())); - let primary = !informational && can_confirm && confirm_style(&dlg) == ConfirmStyle::Primary; - use crate::button::{Button, Kind}; - // (each kind of dialog its own buttons: the keyboard's place doesn't carry from a - // dialog to the one it opens) - let kind = std::mem::discriminant(&dlg); - let cancel_button = Button::new(cancel).widget("button:dialogCancel").id_salt(kind).min_width(72.0); - let ok_button = Button::new(ok) - .kind(if primary { Kind::Primary } else { Kind::Secondary }) - .enabled(can_confirm) - .widget("button:dialogOk") - .id_salt(kind) - .min_width(72.0); - // (Cancel first, then the confirm: the keyboard goes through them as the eye does) - let gap = ui.spacing().item_spacing.x; - let mut buttons_w = 0.0; - if !informational { - buttons_w += cancel_button.desired_size(ui).x + gap; - } - if !ok.is_empty() { - buttons_w += ok_button.desired_size(ui).x; - } - ui.add_space((ui.available_width() - buttons_w).max(0.0)); - if !informational && cancel_button.show(ui).clicked() { - close = true; - } - let r = (!ok.is_empty()).then(|| ok_button.show(ui)); - if r.is_some_and(|r| r.clicked()) { - if informational { - close = true; - } else { - confirm = true; - } - } - }); - if import { - crate::import::note_dialog_bottom(ui); - } - content_w = ui.min_rect().width(); - }); - if settings && content_w > widest + 0.5 { - ctx.data_mut(|d| d.insert_temp(widest_id, content_w)); - } - if let Some(w) = &shown { - // (the import review keeps its hand-picked photos however the click lands) - if !raw_blocked && app.ui.settings.close_dialogs_outside && !import && clicked_backdrop(ctx, w.response.rect, popup_was_open) { - close = true; - } else if raw_blocked { - // A press made under the prompt or library window must not be remembered as a - // backdrop press for a release that arrives after that covering window goes away. - ctx.data_mut(|d| d.remove_temp::(egui::Id::unique("dialog-backdrop-press"))); - } - } - if let Some(w) = shown { - ctx.memory_mut(|m| m.set_modal_layer(w.response.layer_id)); - if let Some(body_h) = body_h { - let measured = (w.response.rect.height() - body_h).max(0.0); - if (measured - chrome).abs() > 0.5 { - ctx.data_mut(|d| d.insert_temp(chrome_id, measured)); - ctx.request_repaint(); - } - } - ctx.move_to_top(w.response.layer_id); - crate::widgets::register_response("dialog:window", w.response.rect, &w.response); - } - // (while the shortcuts editor records a key, it takes Esc itself to cancel; an open popup in - // the dialog, such as a date picker's calendar, takes it to close itself) - if !raw_blocked && ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::widgets::escape_taken(ctx) { - close = true; - } - if !raw_blocked && confirm { - match confirm_dialog(app, &dlg) { - // the import review stays open on an error (e.g. an unusable folder template), and so - // does Export (e.g. no folder chosen) so the choices aren't lost, and Edit Capture Time - // (a time that isn't a date, or a shift it refuses) - Err(e) - if matches!( - dlg, - Dialog::Import { .. } - | Dialog::Export { .. } - | Dialog::ContactSheet { .. } - | Dialog::SlideshowExport { .. } - | Dialog::Print - | Dialog::NewAlbum { .. } - | Dialog::NewSmartAlbum { .. } - | Dialog::SmartRules { .. } - | Dialog::KeywordTag { .. } - | Dialog::KeywordSet { .. } - | Dialog::SynchronizeFolder { .. } - | Dialog::SaveEffect { .. } - | Dialog::CaptureTime { .. } - ) => - { - app.toast(ctx, e) - } - // the SAM 3 dialog stays open to show the download (or why it can't start) - Err(e) if matches!(dlg, Dialog::SamModel { .. }) => { - if let Dialog::SamModel { error, .. } = &mut dlg { - *error = Some(e); - } - } - Ok(r) if matches!(dlg, Dialog::NewAlbum { .. }) && r.get("skipped").and_then(serde_json::Value::as_u64).is_some_and(|n| n > 0) => { - // albums hold library photos (issue #684): say which part of the selection stayed out - crate::panels::grid::toast_skipped(app, ctx, &r); - close = true; - } - // a move says how it went, or why nothing moved - Ok(r) if matches!(dlg, Dialog::MovePhotos { .. }) => { - if let Dialog::MovePhotos { name, .. } = &dlg { - let text = crate::panels::left::moved_text(r["moved"].as_u64().unwrap_or(0), name); - app.toast(ctx, text); - } - close = true; - } - Err(e) if matches!(dlg, Dialog::MovePhotos { .. }) => { - app.toast(ctx, e); - close = true; - } - // photos whose capture time doesn't read are left as they were: say so - Ok(r) if matches!(dlg, Dialog::CaptureTime { .. }) && r["unreadable"].as_u64().is_some_and(|n| n > 0) => { - app.toast(ctx, crate::i18n::tr("Photos whose capture time can't be read were left as they were")); - close = true; - } - // where a Lightroom catalog goes: stays open to be corrected (a folder that isn't - // empty), unless the library it names has gone - Err(e) if matches!(dlg, Dialog::LightroomDestination { .. }) => { - close = !crate::lightroom_destination::keeps_open_on_error(app, &dlg); - app.toast(ctx, e); - } - Ok(_) if keeps_open(app, &dlg) => { - if let Dialog::SamModel { error, .. } = &mut dlg { - *error = None; - } - } - _ => close = true, - } - } - // a dialog opened from inside this one (a button in Settings that shows a licence) takes its place - if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) { - return; - } - if !close && !blocked { - let frame = ctx.cumulative_frame_nr(); - ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame)); - } - app.ui.dialog = if close { None } else { Some(dlg) }; -} - -/// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`]. -const BACKDROP_SHOWN: &str = "dialog-backdrop-shown"; - -/// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and -/// released outside the window, so a slider dragged past its edge doesn't close it; a press while a -/// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is -/// read before the window is drawn, since drawing it already closes the popup. Only a press made -/// while the dialog is shown counts: in the frame a dialog appears, its input is the click that -/// opened it (a quick click on a slow frame presses and releases in that one frame), so it never -/// closes it. (Read from the raw events: egui forgets the press origin on release.) -fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool { - let press_id = egui::Id::unique("dialog-backdrop-press"); - let frame = ctx.cumulative_frame_nr(); - // the same frame too: a second pass of it gets no input - let shown = ctx.data(|d| d.get_temp::(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame); - if !shown { - ctx.data_mut(|d| d.remove_temp::(press_id)); - return false; - } - let (press, release, clicked) = ctx.input(|i| { - let at = |down: bool| { - i.events.iter().rev().find_map(|e| match e { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos), - _ => None, - }) - }; - (at(true), at(false), i.pointer.primary_clicked()) - }); - if let Some(p) = press { - let outside = !window.contains(p) && !popup_was_open; - ctx.data_mut(|d| d.insert_temp(press_id, outside)); - } - let Some(release) = release else { return false }; - let pressed_outside = ctx.data_mut(|d| d.remove_temp::(press_id)).unwrap_or(false); - clicked && pressed_outside && !window.contains(release) -} - -/// Room kept free above and below a dialog (#781). -const DIALOG_SCREEN_MARGIN: f32 = 12.0; -/// A dialog's title bar, frame and button row before the first frame measures them. -const DIALOG_CHROME_GUESS: f32 = 100.0; -/// A dialog's options never get less room than this, however short the window. -const DIALOG_MIN_BODY: f32 = 80.0; - -/// A list that scrolls on its own never gets shorter than this to make its dialog fit. -const DIALOG_MIN_LIST: f32 = 120.0; - -fn list_shrink_id() -> egui::Id { - egui::Id::unique("dialog-list-shrink") -} - -fn list_applied_id() -> egui::Id { - egui::Id::unique("dialog-list-applied") -} - -/// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the -/// shortcuts, smart-album rules): `preferred`, less what the dialog needs to fit the window, so -/// on a short window the list gets shorter rather than scrolling inside a scrolling dialog. -pub fn list_height(ui: &egui::Ui, preferred: f32) -> f32 { - let shrink = ui.data(|d| d.get_temp::(list_shrink_id())).unwrap_or(0.0); - let height = (preferred - shrink).max(preferred.min(DIALOG_MIN_LIST)); - ui.data_mut(|d| *d.get_temp_mut_or_default::(list_applied_id()) += preferred - height); - height -} - -/// A dialog's options: in a vertical scroll area at most `max_height` tall when `scroll` names -/// the dialog (it shrinks to its content, so a dialog that fits looks as it would without it; -/// each dialog keeps a scroll position of its own), drawn directly otherwise. Returns the height -/// they took when scrolled. -fn dialog_body(ui: &mut egui::Ui, scroll: Option<&str>, max_height: f32, body: impl FnOnce(&mut egui::Ui)) -> Option { - let Some(name) = scroll else { - ui.data_mut(|d| d.remove_temp::(list_shrink_id())); - body(ui); - return None; - }; - ui.data_mut(|d| d.insert_temp(list_applied_id(), 0.0_f32)); - let top = ui.cursor().top(); - // (an auto-sized window offers its content last frame's height; the minimum lets a dialog - // that grows take its full height at once, and the area still shrinks to fit its content) - let out = egui::ScrollArea::vertical() - .id_salt(("dialog-body", name)) - .max_height(max_height) - .min_scrolled_height(max_height) - .auto_shrink([true, true]) - .show(ui, body); - // what the lists that scroll on their own gave up this frame, and what they should next frame - let applied = ui.data(|d| d.get_temp::(list_applied_id())).unwrap_or(0.0); - let was = ui.data(|d| d.get_temp::(list_shrink_id())).unwrap_or(0.0); - let shrink = (out.content_size.y + applied - max_height).max(0.0); - if (shrink - was).abs() > 0.5 { - ui.data_mut(|d| d.insert_temp(list_shrink_id(), shrink)); - ui.ctx().request_repaint(); - } - // (the room the scroll area took: its `inner_rect` can be taller than what it allocated) - Some(ui.min_rect().bottom() - top) -} - -/// Apply a dialog's action (also used by `ui.dialog.confirm`). -/// What [`fmt_gap`] writes, read back: `90`, `90 s`, `1 min 30 s`, `2 h 5 min`, `1 day` -/// (units `s`, `min`, `h`, `day`, each optional after a plain number of seconds). -pub fn parse_gap(text: &str) -> Option { - // the one translated text `fmt_gap` writes ("1 Tag") - if text.trim() == crate::i18n::tr("1 day") { - return Some(86400.0); - } - let mut total = 0.0; - let mut seen = false; - let mut words = text.split_whitespace().peekable(); - while let Some(word) = words.next() { - // "90s" as well as "90 s" - let split = word.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(word.len()); - let (num, unit) = word.split_at(split); - let n: f64 = num.parse().ok().filter(|n: &f64| n.is_finite())?; - let unit = if unit.is_empty() { - match words.peek() { - Some(u) if u.parse::().is_err() => words.next().unwrap_or_default(), - _ => "s", - } - } else { - unit - }; - let scale = match unit.trim_end_matches('.').to_lowercase().as_str() { - "s" | "sec" | "secs" | "second" | "seconds" => 1.0, - "m" | "min" | "mins" | "minute" | "minutes" => 60.0, - "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0, - "d" | "day" | "days" => 86400.0, - _ => return None, - }; - total += n * scale; - seen = true; - } - seen.then_some(total) -} - -/// The longest burst gap `photo.analyze` accepts: a day. -pub const MAX_BURST_GAP: f32 = 86_400.0; - -/// Keep what was typed in the Assisted Culling value fields within what `photo.analyze` accepts -/// (a gap of 0 s to a day, a similarity of 0 to 1), not within the sliders' drag range. -pub fn clamp_cull_burst(gap: &mut f32, similarity: &mut f32) { - *gap = if gap.is_finite() { gap.clamp(0.0, MAX_BURST_GAP) } else { 10.0 }; - *similarity = if similarity.is_finite() { similarity.clamp(0.0, 1.0) } else { 0.93 }; -} - -/// The `photo.analyze` parameters of the Assisted Culling dialog, its values as they are. -pub fn cull_params(reject_below: f32, pick_best: bool, burst_gap: f32, similarity: f32) -> serde_json::Value { - let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity}); - if reject_below > 0.0 { - p["rejectBelow"] = json!(reject_below); - } - p -} - -/// `90` → `1 min 30 s`. -pub fn fmt_gap(v: f64) -> String { - let v = v.round() as u64; - match v { - 0..60 => format!("{v} s"), - 60..3600 if v.is_multiple_of(60) => format!("{} min", v / 60), - 60..3600 => format!("{} min {} s", v / 60, v % 60), - 3600..86400 if v.is_multiple_of(3600) => format!("{} h", v / 3600), - 3600..86400 if v.is_multiple_of(60) => format!("{} h {} min", v / 3600, v % 3600 / 60), - // the seconds too, so editing the text reads back the same gap - 3600..86400 => format!("{} h {} min {} s", v / 3600, v % 3600 / 60, v % 60), - _ => crate::i18n::tr("1 day").into(), - } -} - -/// Whether a dialog stays open after its action succeeded (the SAM 3 dialog while the model -/// downloads). -pub fn keeps_open(app: &LightcraftApp, dlg: &Dialog) -> bool { - matches!(dlg, Dialog::SamModel { .. }) && !app.session.segmenter.installed() -} - -/// No SAM 3 model, no download running and nowhere to download it from: installing it by hand is -/// all the dialog can offer. -fn sam_by_hand(sam: &lightcraft_engine::segment::Segmenter) -> bool { - !sam.installed() && !sam.download_status().running && sam.mirrors().is_empty() -} - -/// The model installation guide. -const SAM_HELP: &str = "https://github.com/storytold/lightcraft/blob/main/docs/ai-masks.md#getting-the-model"; - -/// Open the configured SAM 3 folder itself; revealing a file opens its parent instead. -pub(crate) fn show_model_folder(app: &mut LightcraftApp) -> Result { - let dir = app.session.segmenter.dir.as_ref().ok_or("no folder is set for the SAM 3 model")?; - let path = dir.to_str().ok_or("the model folder path is not valid UTF-8")?; - let open = app.services.open_with.as_mut().ok_or("opening model folders is not available here")?; - // Create only after the host action is available. Existing model files are left alone. - std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - #[cfg(target_os = "linux")] - if let Some(open_folder) = app.services.open_model_folder.clone() { - let path = path.to_string(); - let folder = path.clone(); - crate::tasks::spawn( - app, - "Show in File Manager", - Some("openModelFolder"), - move || open_folder(&folder), - |app, ctx, result| { - if let Err(e) = result { - app.toast_error(ctx, e); - } - }, - )?; - return Ok(json!({"path": path, "background": true})); - } - open(path, "")?; - Ok(json!({"path": path})) -} - -/// The SAM 3 dialog: what the model is, its size and licence, and the download's progress. -fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str>) { - use lightcraft_engine::segment::{LICENSE_NAME, LICENSE_URL, MODEL_BYTES}; - let t = Tokens::get(ui.ctx()); - let seg = &app.session.segmenter; - let d = seg.download_status(); - if seg.installed() { - ui.label(crate::i18n::tr("The SAM 3 model is installed: Object and Describe masks are ready.")); - return; - } - let gb = |b: u64| b as f64 / 1e9; - ui.label(crate::i18n::tr( - "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.", - )); - let dir = seg.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default(); - ui.label(format!("{} {:.1} GB, {} {dir}", crate::i18n::tr("A one-time download of about"), gb(MODEL_BYTES), crate::i18n::tr("saved in"))); - ui.label( - egui::RichText::new(format!( - "{} {LICENSE_NAME} — {}", - crate::i18n::tr("Licence:"), - crate::i18n::tr("Meta's terms, not LightCraft's. Downloading it means accepting them.") - )) - .color(t.text_label), - ); - let r = ui.link(crate::i18n::tr("Read the SAM License")).on_hover_text(LICENSE_URL); - crate::widgets::register(ui, "link:samLicense", r.rect); - if r.clicked() { - let _ = crate::links::open(app, LICENSE_URL); - } - let seg = &app.session.segmenter; - if d.running { - ui.add_space(4.0); - let text = format!("{:.2} / {:.2} GB · {}", gb(d.done), gb(d.total), d.file); - crate::progress::Progress::new(crate::progress::fraction_of(d.done, d.total)).label(text).widget("progress:samDownload").show(ui); - let r = ui.button(crate::i18n::tr("Cancel Download")); - crate::widgets::register(ui, "button:samCancel", r.rect); - if r.clicked() { - app.session.segmenter.cancel_download(); - } - ui.label(egui::RichText::new(crate::i18n::tr("You can close this: the download continues, and resumes if interrupted.")).color(t.text_dim)); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); - return; - } - if seg.mirrors().is_empty() { - // nothing to download from: say how to install it by hand, with the folder and the guide a click away - let dir = seg.dir.clone(); - ui.label( - egui::RichText::new(crate::i18n::tr( - "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.", - )) - .color(t.text_dim), - ); - ui.horizontal_wrapped(|ui| { - if dir.is_some() && crate::menus::ui_enabled(app, "app.openSamModelFolder") { - let r = ui.button(crate::i18n::tr(crate::menus::reveal_label())); - crate::widgets::register(ui, "button:samFolder", r.rect); - if r.clicked() - && let Err(e) = app.run("app.openSamModelFolder", json!({})) - { - app.toast_error(ui.ctx(), e); - } - } - let r = ui.link(crate::i18n::tr("How to install the model")).on_hover_text(SAM_HELP); - crate::widgets::register(ui, "link:samHelp", r.rect); - if r.clicked() - && let Err(e) = crate::links::open(app, SAM_HELP) - { - app.toast(ui.ctx(), e); - } - }); - } - if let Some(e) = error.map(str::to_string).or(d.error) { - ui.label(egui::RichText::new(format!("{} {e}", crate::i18n::tr("The download didn't work:"))).color(egui::Color32::from_rgb(230, 90, 80))); - } -} - -/// Runs a command that creates an album and asks the Albums tree to open the folders down to it. -fn created_in(app: &mut LightcraftApp, command: &str, params: serde_json::Value) -> Result { - let r = app.run(command, params)?; - app.ui.reveal_album = r.get("id").and_then(serde_json::Value::as_u64); - Ok(r) -} - -/// The albums an Album rule in smart album `editing` picks from, in the sidebar's order: the album -/// itself and any smart album that tests it (testing it back would loop) are blocked, with why. -pub(crate) fn album_entries(cat: &lightcraft_catalog::Catalog, editing: Option) -> Vec { - let editing = editing.map(lightcraft_catalog::AlbumId); - crate::album_picker::entries_from(cat, |a| match editing { - Some(e) if a.id == e => Some(crate::i18n::tr("This is the album you're editing").to_string()), - Some(e) if cat.album_reaches(a.id, e) => Some(crate::i18n::tr("It tests this album, so testing it back would loop").to_string()), - _ => None, - }) -} - -pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result { - match dlg { - Dialog::LightroomResult { first, .. } => { - if let Some(first) = first { - app.run("library.source", json!({"kind": "all"}))?; - let mut filter = serde_json::to_value(lightcraft_catalog::Filter::default()).map_err(|e| e.to_string())?; - // The filter command merges a patch; these defaults are omitted by serde. - filter["only"] = json!([]); - filter["labels"] = json!([]); - filter["keywords"] = json!([]); - filter["dates"] = json!([]); - filter["albums"] = json!([]); - filter["libraryFolders"] = json!([]); - filter["ruleSet"] = serde_json::Value::Null; - app.run("library.filter", filter)?; - app.run("library.select", json!({"ids": [first]}))?; - app.ui.view = crate::state::ViewMode::PhotoGrid; - } - Ok(serde_json::Value::Null) - } - Dialog::SamModel { then, .. } => { - if app.session.segmenter.installed() { - // installed: start what the user was doing - if let Some((kind, op)) = then { - crate::panels::masking::begin_ai(app, kind, op)?; - } - return Ok(serde_json::Value::Null); - } - let r = app.run("segment.model.download", json!({"acknowledged": true})); - if r.is_ok() { - app.ui.sam_downloading = true; - } - r - } - Dialog::NewAlbum { name, folder, parent, include_selected } => { - created_in(app, "album.create", json!({"name": name, "folder": folder, "addSelected": !folder && *include_selected, "parent": parent})) - } - Dialog::RenameAlbum { id, name } => app.run("album.rename", json!({"id": id, "name": name})), - Dialog::TextPrompt { value, command, params, key, .. } => { - let mut p = params.clone(); - p[key.as_str()] = json!(value.trim()); - app.run(command, p) - } - Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => app.run( - "photo.setCaptureTime", - match mode.as_str() { - "set" => json!({"time": time}), - "shift" => json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}), - _ => json!({"hours": zone}), - }, - ), - Dialog::LabelNames { names, save_as } => { - let mut m = serde_json::Map::new(); - for (l, n) in lightcraft_catalog::ColorLabel::ALL.iter().zip(names) { - m.insert(format!("{l:?}").to_lowercase(), if n.trim().is_empty() { serde_json::Value::Null } else { json!(n.trim()) }); - } - let r = app.run("label.setNames", json!({"names": m})); - if r.is_ok() && !save_as.trim().is_empty() { - return app.run("label.saveSet", json!({"name": save_as.trim()})); - } - r - } - Dialog::Rename { template, start } => app.run("photo.rename", json!({"template": template, "start": start})), - Dialog::RenameKeyword { from, to } => app.run("keyword.rename", json!({"from": from, "to": to})), - Dialog::RenamePerson { from, to, merge } => app.run("faces.renamePerson", json!({"from": from, "to": to.trim(), "merge": merge})), - Dialog::KeywordTag { - editing, - name, - parent, - inside, - synonyms, - include_on_export, - export_containing, - export_synonyms, - person, - add_to_selected, - reveal, - } => { - let mut params = json!({ - "synonyms": synonyms.split(',').map(str::trim).filter(|s| !s.is_empty()).collect::>(), - "includeOnExport": include_on_export, - "exportContaining": export_containing, - "exportSynonyms": export_synonyms, - "person": person, - }); - match editing { - Some(keyword) => { - params["keyword"] = json!(keyword); - params["name"] = json!(name); - let r = app.run("keyword.edit", params); - if r.is_ok() { - let to = match keyword.rsplit_once('|') { - Some((parent, _)) => format!("{parent}|{}", name.trim()), - None => name.trim().to_string(), - }; - crate::panels::keyword_list::follow(app, keyword, &to); - } - r - } - None => { - params["name"] = json!(name); - params["parent"] = if *inside { json!(parent) } else { serde_json::Value::Null }; - params["addToSelected"] = json!(add_to_selected); - let r = app.run("keyword.create", params); - if *reveal && let Ok(made) = &r { - app.ui.reveal_keyword = made["keyword"].as_str().map(str::to_string); - } - r - } - } - } - Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})), - Dialog::KeywordSet { replaces, name, slots, as_new } => { - use lightcraft_catalog::keywords::same; - let name = name.trim(); - if name.is_empty() { - return Err(crate::i18n::tr("A keyword set needs a name").to_string()); - } - if same(name, lightcraft_engine::cmd::keywords::RECENT) { - return Err(crate::i18n::tr("Recent Keywords is built in: choose another name").to_string()); - } - // the set it renames: none when saving as new, or when it was deleted meanwhile (then it is - // saved anew rather than refused) - let sets = &app.session.keyword_sets; - let renames = replaces.as_deref().filter(|_| !as_new).filter(|old| sets.iter().any(|x| same(&x.name, old))); - if sets.iter().any(|x| same(&x.name, name) && !renames.is_some_and(|old| same(&x.name, old))) { - return Err(crate::i18n::tr_format!("There is a keyword set “{name}” already", name = name)); - } - let mut params = json!({"name": name, "keywords": slots}); - match renames { - Some(old) => params["replace"] = json!(old), - None => params["new"] = json!(true), - } - app.run("keyword.saveSet", params) - } - Dialog::MoveKeyword { keyword, parent } => { - let r = app.run("keyword.move", json!({"keyword": keyword, "parent": parent, "merge": true})); - if r.is_ok() { - let leaf = keyword.rsplit('|').next().unwrap_or(keyword); - let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}|{leaf}")); - crate::panels::keyword_list::follow(app, keyword, &to); - } - r - } - Dialog::MergeKeywords { from, into } => app.run("keyword.merge", json!({"from": from, "into": into})), - Dialog::AutoStack { gap } => app.run("stack.auto", json!({"gap": gap})), - Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted), - Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), - Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { - app.ui.cull_burst = Some((*burst_gap, *similarity)); - app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity)) - } - Dialog::SmartRules { id, name, rules, parent } => { - // refused before anything changes (not even the name) - if let Some(problem) = rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).first() { - return Err(problem.to_string()); - } - let name = if name.trim().is_empty() { "Smart Album".to_string() } else { name.trim().to_string() }; - match id { - // the name and the rules together: one undo step, both or neither - Some(id) => app.run("album.setRules", json!({"id": id, "name": name, "replace": true, "rules": {"ruleSet": rules}})), - None => created_in(app, "album.createSmart", json!({"name": name, "rules": {"ruleSet": rules}, "parent": parent})), - } - } - Dialog::NewSmartAlbum { name, parent } => { - created_in(app, "album.createSmart", json!({"name": if name.trim().is_empty() { "Smart Album" } else { name }, "parent": parent})) - } - Dialog::CreatePreset { name, group, groups } => app.run( - "preset.create", - json!({ - "name": if name.trim().is_empty() { "My Preset" } else { name }, - "group": if group.trim().is_empty() { "User Presets" } else { group }, - "groups": groups, - }), - ), - Dialog::ContactSheet { options } => app.run("app.contactSheet", json!(options)), - Dialog::SlideshowExport { settings } => app.run("app.slideshowExport", json!(settings)), - Dialog::Print => app.run("app.print", json!({})), - Dialog::CopySettings { groups } => app.run("develop.copy", json!({"groups": groups})), - Dialog::PasteSettings { groups } => app.run("develop.paste", json!({"groups": groups})), - Dialog::Export { opts, full_size, resize, limit_kb, dir, .. } => { - let mut p = export_dialog_params(opts, *full_size, resize, *limit_kb); - p["dir"] = json!(dir); - p["background"] = json!(true); - app.run("app.export", p) - } - Dialog::Merge { opts } => crate::merge::start_final(app, opts), - Dialog::Import { opts } => crate::import::start(app, opts), - Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})), - Dialog::MovePhotos { ids, folder, dont_ask, library, .. } => { - // another library opened meanwhile (from the menu bar, an agent): these numbers are - // other photos there - if *library != app.session.library_generation() { - return Err(crate::i18n::tr("Another library was opened since the photos were dropped: nothing was moved").to_string()); - } - if *dont_ask { - app.ui.settings.ask_before_move = false; - } - crate::panels::left::move_photos(app, Some(ids), folder).map(|n| json!({"moved": n})) - } - // the catalog found: no file dialog; none: File ▸ Import Lightroom Catalog… asks for it - Dialog::LightroomCatalog { catalog, .. } => { - app.run("file.importLightroom", catalog.as_ref().map_or_else(|| json!({}), |c| json!({"path": c}))) - } - d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::confirm(app, d), - Dialog::SaveEffect { name, group, fields, amount, brush } => { - crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush) - } - Dialog::DeleteEffects { names } => app.run("mask.deleteEffect", json!({"names": names})), - Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})), - d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d), - Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => { - Ok(serde_json::Value::Null) - } - } -} - -/// Open a one-field dialog that runs `command` with `params` + `{key: typed value}`. -pub fn prompt(app: &mut LightcraftApp, title: &str, hint: &str, value: &str, command: &str, params: serde_json::Value, key: &str) { - app.ui.dialog = - Some(Dialog::TextPrompt { title: title.into(), hint: hint.into(), value: value.into(), command: command.into(), params, key: key.into() }); -} - -/// The Export dialog's choices as `app.export` params (without the folder). -fn export_dialog_params( - opts: &lightcraft_engine::export::ExportOptions, - full_size: bool, - resize: &lightcraft_engine::export::Resize, - limit_kb: u32, -) -> serde_json::Value { - let o = lightcraft_engine::export::ExportOptions { - resize: (!full_size).then_some(*resize), - limit_kb: (limit_kb > 0).then_some(limit_kb), - ..opts.clone() - }; - o.to_json() -} - -// ------------------------------------------------------------------------------------------ dialog widgets - -/// Two columns of settings-group checkboxes (Copy Settings, Create Preset) plus All / None. -fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec) { - let key_of = |g: &SettingsGroup| serde_json::to_value(g).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); - ui.columns(2, |cols| { - for (i, g) in SettingsGroup::ALL.iter().enumerate() { - let key = key_of(g); - let mut on = groups.contains(&key); - let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label())); - crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r); - if r.changed() { - if on { - groups.push(key); - } else { - groups.retain(|x| *x != key); - } - } - } - }); - ui.horizontal(|ui| { - let all = ui.small_button(crate::i18n::tr("All")); - crate::widgets::register(ui, format!("{tag}:all"), all.rect); - if all.clicked() { - *groups = SettingsGroup::ALL.iter().map(key_of).collect(); - } - let none = ui.small_button(crate::i18n::tr("None")); - crate::widgets::register(ui, format!("{tag}:none"), none.rect); - if none.clicked() { - groups.clear(); - } - }); -} - -/// Width of the label column in dialogs. -const LABEL_W: f32 = 78.0; - -const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, default: f64, step: f64) -> ControlSpec { - ControlSpec { id, label, section: Section::Light, min, max, default, step, decimals: 0, track: Track::Plain } -} -const QUALITY: ControlSpec = spec("export.quality", "Quality", 1.0, 100.0, 90.0, 1.0); -const LIMIT_KB: ControlSpec = spec("export.limitKb", "Limit file size (KB, 0 = off)", 0.0, 20_000.0, 0.0, 10.0); -const SIZE_PX: ControlSpec = spec("export.sizePx", "Pixels", 16.0, 20_000.0, 2048.0, 16.0); -const SIZE_W: ControlSpec = spec("export.sizeW", "Width (px)", 16.0, 20_000.0, 2048.0, 16.0); -const SIZE_H: ControlSpec = spec("export.sizeH", "Height (px)", 16.0, 20_000.0, 2048.0, 16.0); -const SIZE_MP: ControlSpec = ControlSpec { decimals: 1, ..spec("export.sizeMp", "Megapixels", 0.1, 100.0, 12.0, 0.1) }; -const SIZE_PCT: ControlSpec = spec("export.sizePercent", "Percent", 1.0, 400.0, 50.0, 1.0); -const START_NUMBER: ControlSpec = spec("export.startNumber", "Start number", 1.0, 9999.0, 1.0, 1.0); -const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240.0, 1.0); - -/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi. -fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) { - use lightcraft_engine::export::ResizeMode as R; - const MODES: [(R, &str); 8] = [ - (R::LongEdge, "Long Edge"), - (R::ShortEdge, "Short Edge"), - (R::Width, "Width"), - (R::Height, "Height"), - (R::WidthHeight, "Width & Height"), - (R::Dimensions, "Dimensions"), - (R::Megapixels, "Megapixels"), - (R::Percent, "Percentage"), - ]; - let r_full = ui.checkbox(full, crate::i18n::tr("Full size")); - crate::widgets::register(ui, "check:exportFullSize", r_full.rect); - if !*full { - field(ui, "Resize to", |ui| { - let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1); - let before = r.mode; - let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| { - for (m, l) in MODES { - ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l)); - } - }); - crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize")); - crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect); - if r.mode != before { - // a sensible value for the new unit - r.value = match r.mode { - R::Megapixels => 12.0, - R::Percent => 50.0, - _ if matches!(before, R::Megapixels | R::Percent) => 2048.0, - _ => r.value, - }; - if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 { - r.height = r.value as u32; - } - } - }); - let mut v = r.value as f64; - let spec = match r.mode { - R::Megapixels => &SIZE_MP, - R::Percent => &SIZE_PCT, - R::Dimensions | R::WidthHeight => &SIZE_W, - _ => &SIZE_PX, - }; - if num(ui, spec, &mut v) { - r.value = v as f32; - } - if matches!(r.mode, R::Dimensions | R::WidthHeight) { - let mut h = r.height as f64; - if num(ui, &SIZE_H, &mut h) { - r.height = h as u32; - } - } - let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge")); - crate::widgets::register(ui, "check:exportDontEnlarge", c.rect); - } - let mut p = *ppi as f64; - if num(ui, &PPI, &mut p) { - *ppi = p as u16; - } -} -/// All nine positions supported by both the text and graphic watermark renderer. -/// Keep them in grid order so bottom-centre and edge-centre anchors are available in Export. -const WM_POSITIONS: [(lightcraft_engine::export::Anchor, &str); 9] = { - use lightcraft_engine::export::Anchor::*; - [(TopLeft, "↖"), (Top, "↑"), (TopRight, "↗"), (Left, "←"), (Center, "•"), (Right, "→"), (BottomLeft, "↙"), (Bottom, "↓"), (BottomRight, "↘")] -}; - -const WM_IMAGE_WIDTH: ControlSpec = spec("export.watermarkImageWidth", "Width (% of photo)", 2.0, 100.0, 20.0, 1.0); -const WM_SIZE: ControlSpec = spec("export.watermarkSize", "Size (% of short edge)", 1.0, 15.0, 3.5, 0.5); -const WM_OPACITY: ControlSpec = spec("export.watermarkOpacity", "Opacity (%)", 5.0, 100.0, 70.0, 1.0); -const WM_INSET_X: ControlSpec = - ControlSpec { decimals: 1, ..spec("export.watermarkInsetX", "Horizontal inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) }; -const WM_INSET_Y: ControlSpec = - ControlSpec { decimals: 1, ..spec("export.watermarkInsetY", "Vertical inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) }; - -/// A themed slider row editing `v`; true when it changed. -fn num(ui: &mut egui::Ui, spec: &ControlSpec, v: &mut f64) -> bool { - match crate::widgets::slider(ui, spec, *v, true, None).value { - Some(n) => { - *v = n; - true - } - None => false, - } -} - -/// A labelled row (fixed label column). -/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes -/// after (a save dialog). -fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) { - use lightcraft_engine::slideshow_export::{ExportSettings, Format}; - let t = Tokens::get(ui.ctx()); - let photos = app.session.visible_cloned().len(); - let slide = app.session.slideshow.slide_duration; - let (intro, ending) = app.session.slide_titles.durations(slide); - let titles = usize::from(intro.is_some()) + usize::from(ending.is_some()); - let seconds = photos as f64 * slide + intro.unwrap_or(0.0) + ending.unwrap_or(0.0); - let summary = crate::i18n::tr_format!( - "{n} photos in view · {slides} slides · {time}", - n = photos, - slides = photos + titles, - time = format!("{}:{:02}", (seconds / 60.0).floor() as u64, (seconds % 60.0).round() as u64) - ); - ui.label(egui::RichText::new(summary).color(t.text_dim)); - let before = settings.format; - choices(ui, "Format", "slideshowExportFormat", &[(Format::Pdf, "PDF"), (Format::Jpeg, "JPEG"), (Format::Video, "Video")], &mut settings.format); - if settings.format != before { - *settings = ExportSettings { full_screen: settings.full_screen, ..ExportSettings::for_format(settings.format) }; - } - match settings.format { - Format::Video => { - choices(ui, "Size", "slideshowExportSize", &[(720, "720p"), (1080, "1080p")], &mut settings.size); - choices(ui, "Frame rate", "slideshowExportFps", &[(24, "24 fps"), (30, "30 fps")], &mut settings.fps); - let mut webm = settings.container == "webm"; - choices(ui, "Container", "slideshowExportContainer", &[(false, "MP4"), (true, "WebM")], &mut webm); - settings.container = if webm { "webm".into() } else { "mp4".into() }; - } - _ => { - choices(ui, "Size", "slideshowExportSize", &[(1024, "1024 px"), (1920, "1920 px"), (3840, "3840 px")], &mut settings.size); - } - } - field(ui, "Quality", |ui| { - let r = ui.add(egui::Slider::new(&mut settings.quality, 1..=100)); - crate::widgets::register(ui, "slider:slideshowExportQuality", r.rect); - }); - let note = match settings.format { - Format::Pdf => { - let r = ui.checkbox(&mut settings.full_screen, crate::i18n::tr("Automatically show full screen")); - crate::widgets::register(ui, "check:slideshowExportFullScreen", r.rect); - "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode." - } - Format::Jpeg => "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.", - Format::Video => "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.", - }; - ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim)); - ui.label( - egui::RichText::new(crate::i18n::tr("Slides use the slideshow's layout, overlays and intro and ending screens, in view order.")) - .color(t.text_dim), - ); -} - -fn field(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let t = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.set_min_width(LABEL_W); - ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text_label)); - }); - add(ui) - }) - .inner -} - -/// The rest of a [`field`] row, laid out right to left: `add` places its trailing button(s) first, -/// then a text field taking exactly the width that's left. (Subtracting a guessed button width -/// instead made the auto-sized dialog grow every frame when the real button was wider, #8.) -fn trailing_button_row(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { - let h = ui.spacing().interact_size.y.max(24.0); - ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), h), egui::Layout::right_to_left(egui::Align::Center), add); -} - -/// A labelled row of mutually exclusive choice buttons (ids `button:{id}-{index}`). -fn choices(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], value: &mut V) { - field(ui, label, |ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for (i, (v, l)) in options.iter().enumerate() { - if crate::widgets::text_button(ui, &format!("{id}-{i}"), l, *value == *v).clicked() { - *value = *v; - } - } - }); -} - -/// Dialogs that Return confirms with nothing focused (those with text fields confirm from the -/// field: `dialog_field`). -fn return_confirms(dlg: &Dialog) -> bool { - matches!(dlg, Dialog::CopySettings { .. } | Dialog::PasteSettings { .. }) -} - -struct PersonRenamePlan { - faces: usize, - needs_merge: bool, - /// Why Rename stays disabled. `None` when the typed name can be applied. - block: Option<&'static str>, -} - -/// What renaming `from` to `to` would do, using the same rules as `faces.renamePerson`. -fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, to: &str) -> PersonRenamePlan { - let to_trim = to.trim(); - if to_trim.is_empty() { - return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("Type a name") }; - } - if to_trim.chars().count() > 200 || to_trim.chars().any(char::is_control) { - return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("A name is at most 200 characters, without control characters") }; - } - let from_key = from.trim().to_lowercase(); - let to_key = to_trim.to_lowercase(); - let mut matched = 0usize; - let mut faces = 0usize; - 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) { - 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 { - matched += 1; - if region.name.as_deref() != Some(to_trim) { - faces += 1; - } - } else if key == to_key { - needs_merge = true; - } - } - } - } - let block = if matched == 0 { - Some("No person by that name") - } else if faces == 0 { - Some("That is already their name") - } else { - None - }; - // a case-only change is the same person, not a merge - PersonRenamePlan { faces, needs_merge: needs_merge && from_key != to_key, block } -} - -/// A dialog's one text field: it takes the focus when the dialog opens, and opens with its text -/// selected, so typing replaces it. It takes the focus back only while nothing else has it: taking -/// it back every frame would keep Tab from ever reaching the dialog's buttons and check boxes. -/// True when Return confirms the dialog; Esc cancels the dialog (`show`). -fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) -> bool { - let r = crate::text_field::TextField::singleline(widget, text).hint(crate::i18n::tr(hint)).width(f32::INFINITY).select_on_focus(true).show(ui); - // (and takes it back when nothing has it: after a click on the dialog's background or a check box, - // or when Return gave it up on a refusal; a control Tab reached keeps it). A disabled dialog (a - // prompt or the blocking library window owns input) must not request the focus at all: egui's - // text edit would otherwise keep editing the draft from host text behind that window. - if ui.is_enabled() && (just_opened(ui, widget) || (!r.editing && r.ending.is_none() && ui.memory(|m| m.focused().is_none()))) { - r.response.request_focus(); - } - r.ending == Some(crate::text_field::Ending::Return) -} - -/// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just -/// opened (to give its first field the focus once). -fn just_opened(ui: &egui::Ui, key: &str) -> bool { - let id = egui::Id::unique(("dialog-shown", key)); - let pass = ui.ctx().cumulative_pass_nr(); - let last: Option = ui.data_mut(|d| d.get_temp(id)); - ui.data_mut(|d| d.insert_temp(id, pass)); - last.and_then(|l| l.checked_add(1)) != Some(pass) -} - -#[cfg(test)] -mod watermark_position_tests { - use super::WM_POSITIONS; - use lightcraft_engine::export::Anchor; - - #[test] - fn export_dialog_offers_every_rendered_anchor_exactly_once() { - let anchors = [ - Anchor::TopLeft, - Anchor::Top, - Anchor::TopRight, - Anchor::Left, - Anchor::Center, - Anchor::Right, - Anchor::BottomLeft, - Anchor::Bottom, - Anchor::BottomRight, - ]; - assert_eq!(WM_POSITIONS.len(), anchors.len()); - for anchor in anchors { - assert_eq!(WM_POSITIONS.iter().filter(|(position, _)| *position == anchor).count(), 1); - } - } -} - -/// How a dialog's confirm button looks: [`ConfirmStyle::Primary`] (the accent's fill) when it -/// makes or brings in something, plain when it deletes or removes (never the eye-catching -/// default) or when the dialog only shows something (its Close). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ConfirmStyle { - Primary, - Plain, -} - -pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle { - match dlg { - Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } => { - ConfirmStyle::Plain - } - _ if only_shows(dlg) => ConfirmStyle::Plain, - _ => ConfirmStyle::Primary, - } -} - -/// A dialog that only shows something: one Close, nothing to confirm or cancel. (Synchronize -/// Folder is one when its folder turned out up to date.) -fn only_shows(dlg: &Dialog) -> bool { - matches!( - dlg, - Dialog::About - | Dialog::Shortcuts - | Dialog::Settings { .. } - | Dialog::SystemInfo { .. } - | Dialog::AllMetadata { .. } - | Dialog::WhatsNew - | Dialog::ManageEffects { .. } - | Dialog::ViewOptions - ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date()) -} - -#[cfg(test)] -mod gap_tests { - use super::{fmt_gap, parse_gap}; - - #[test] - fn gap_text_reads_back_what_it_shows() { - for v in [0.0, 1.0, 12.0, 59.0, 60.0, 90.0, 600.0, 3599.0, 3600.0, 3601.0, 3661.0, 3900.0, 7325.0, 86340.0, 86399.0] { - assert_eq!(parse_gap(&fmt_gap(v)), Some(v), "{}", fmt_gap(v)); - } - assert_eq!(parse_gap("1 day"), Some(86400.0)); - assert_eq!(parse_gap("45"), Some(45.0)); - assert_eq!(parse_gap(" 45s "), Some(45.0)); - assert_eq!(parse_gap("2min 5s"), Some(125.0)); - for bad in ["", "abc", "5 parsecs", "NaN", "1 min x"] { - assert_eq!(parse_gap(bad), None, "{bad:?}"); - } - // a day reads back in the UI language too ("1 Tag") - crate::i18n::set_language(crate::i18n::Locale::De); - let shown = fmt_gap(86400.0); - let back = parse_gap(&shown); - crate::i18n::set_language(crate::i18n::Locale::En); - assert_eq!((shown.as_str(), back), ("1 Tag", Some(86400.0))); - } - - #[test] - fn gaps_past_the_slider_read_back_too() { - // the Assisted Culling slider drags to 10 min; its value field takes up to a day - for (v, text) in [(1800.0, "30 min"), (5400.0, "1 h 30 min"), (3601.0, "1 h 0 min 1 s"), (86400.0, "1 day")] { - assert_eq!(fmt_gap(v), text); - assert_eq!(parse_gap(text), Some(v), "{text}"); - } - assert_eq!(parse_gap("1800"), Some(1800.0)); - assert_eq!(parse_gap("0"), Some(0.0)); - } -} - -#[cfg(test)] -mod cull_dialog_tests { - use std::time::Duration; - - use serde_json::json; - - use super::{clamp_cull_burst, cull_params}; - use crate::headless::Headless; - use crate::state::Dialog; - use crate::{LightcraftApp, Services}; - - const T: Duration = Duration::from_secs(20); - - #[test] - fn typed_values_are_kept_within_what_photo_analyze_accepts() { - for (gap, sim) in [(0.0, 0.0), (1800.0, 1.0), (86400.0, 0.5), (0.5, 0.995)] { - let (mut g, mut s) = (gap, sim); - clamp_cull_burst(&mut g, &mut s); - assert_eq!((g, s), (gap, sim), "in range: kept as typed"); - } - for ((gap, sim), want) in [((-5.0, -0.1), (0.0, 0.0)), ((90000.0, 1.5), (86400.0, 1.0)), ((f32::NAN, f32::INFINITY), (10.0, 0.93))] { - let (mut g, mut s) = (gap, sim); - clamp_cull_burst(&mut g, &mut s); - assert_eq!((g, s), want); - } - assert_eq!(cull_params(0.0, true, 1800.0, 1.0), json!({"pickBest": true, "burstGap": 1800.0, "similarity": 1.0})); - assert_eq!(cull_params(20.0, false, 0.0, 0.7)["rejectBelow"], 20.0); - } - - /// Click the value field right of a slider registered as `id`, type `text`, Enter. - fn type_value(h: &mut Headless, id: &str, text: &str) { - let r = h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} not on screen")); - let spacing = h.view.ctx.global_style().spacing.clone(); - let x = r.left() + spacing.slider_width + spacing.item_spacing.x + 6.0; - assert_eq!(h.request("ui.click", json!({"x": x, "y": r.center().y}), T)["ok"], true); - h.step(); - for key in ["a", "Backspace"] { - assert_eq!(h.request("ui.key", json!({"key": key, "cmd": key == "a"}), T)["ok"], true); - } - assert_eq!(h.request("ui.text", json!({"text": text}), T)["ok"], true); - assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); - h.step(); - h.step(); - } - - fn burst(h: &Headless) -> (f32, f32) { - match &h.app.ui.dialog { - Some(Dialog::Cull { burst_gap, similarity, .. }) => (*burst_gap, *similarity), - d => panic!("{d:?}"), - } - } - - #[test] - fn the_culling_value_fields_take_values_past_the_sliders() { - let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); - let mut h = Headless::new(app, [1400.0, 1000.0], 1.0); - h.step(); - h.app.run("dialog.cull", json!({})).unwrap(); - for _ in 0..4 { - h.step(); - } - assert_eq!(burst(&h), (10.0, 0.93)); - // half an hour and "only identical shots": past the sliders' 10 min and 0.99 - type_value(&mut h, "field:cullGap", "30 min"); - type_value(&mut h, "field:cullSimilar", "1.0"); - assert_eq!(burst(&h), (1800.0, 1.0)); - // a day is as far as photo.analyze goes; more is held there - type_value(&mut h, "field:cullGap", "2 days"); - assert_eq!(burst(&h).0, 86400.0); - type_value(&mut h, "field:cullGap", "0"); - assert_eq!(burst(&h), (0.0, 1.0)); - type_value(&mut h, "field:cullGap", "1800"); - assert_eq!(burst(&h).0, 1800.0); - // a similarity between the slider's hundredths is kept to the thousandth - type_value(&mut h, "field:cullSimilar", "0.995"); - assert_eq!(burst(&h).1, 0.995); - type_value(&mut h, "field:cullSimilar", "0.9951"); - assert_eq!(burst(&h).1, 0.995); - type_value(&mut h, "field:cullSimilar", "1.0"); - assert_eq!(burst(&h).1, 1.0); - // OK hands them to photo.analyze as typed (it refuses values out of its range) - let r = h.request("ui.dialog.confirm", json!({}), T); - assert_eq!(r["ok"], true, "{r}"); - assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); - assert_eq!(h.app.ui.cull_burst, Some((1800.0, 1.0))); - // and the next opening starts from them, not from the sliders' range - h.app.run("dialog.cull", json!({})).unwrap(); - h.step(); - h.step(); - assert_eq!(burst(&h), (1800.0, 1.0)); - } -} diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 19a9265a580..2fe4be0796d 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -44,6 +44,7 @@ use sections::{SECTION_GAP, missing_count, pinned_header, section, section_drag, pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); + super::side_select::begin_left(app); frame.show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; // the title offers the sections' menu too: where hidden sections come back from diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index f9a2cf229f2..d1e14ed07ef 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -1,6 +1,6 @@ use super::folders::{folder_menu, is_within}; use super::rows::{INDENT_STEP, Row, indent_x, set_tree_open, tree_open, tree_toggle}; -use super::{Album, AlbumId, Align2, Icon, LibrarySource, LightcraftApp, Rect, Sense, Tokens, json, pos2, register, vec2}; +use super::{Album, AlbumId, Align2, Icon, LightcraftApp, Rect, Sense, Tokens, json, pos2, register, vec2}; /// Albums: the tree of albums and the folders they are sorted into. `reveal`: an album just made, /// whose folders open down to it. @@ -61,7 +61,8 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare albums_tree(app, ui, all, Some(a.id), indent + INDENT_STEP, open_to); } } else { - let sel = app.session.source == LibrarySource::Album(a.id); + let sel = crate::panels::side_select::album_shown(app, a.id); + app.ui.side.albums.saw(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)(); @@ -103,7 +104,7 @@ 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})); + crate::panels::side_select::album_clicked(app, ui, a.id); } folder_menu(app, &resp, a); } diff --git a/crates/ui-egui/src/panels/left/dates.rs b/crates/ui-egui/src/panels/left/dates.rs index 09f942914f0..6b27d056e16 100644 --- a/crates/ui-egui/src/panels/left/dates.rs +++ b/crates/ui-egui/src/panels/left/dates.rs @@ -23,16 +23,15 @@ pub(super) fn date_rows(app: &mut LightcraftApp, ui: &mut egui::Ui) { fn date_row(app: &mut LightcraftApp, ui: &mut egui::Ui, key: &str, label: &str, count: usize, indent: f32) -> bool { let open_id = egui::Id::unique(("date-open", key.to_string())); let mut open = tree_open(ui, open_id, false); - let sel = app.session.filter.date.as_deref() == Some(key); + let sel = crate::panels::side_select::date_shown(app, key); + app.ui.side.dates.saw(key.to_string()); let resp = Row::new(&format!("date:{key}"), Icon::Clock, label).count(Some(count)).selected(sel).indent(indent).show(app, ui); if key.len() < 10 { // (the name carries the year, so two Marches in different years differ in a screen reader's list of triangles) tree_toggle(ui, &resp, indent, open_id, &mut open, format!("dateToggle:{key}"), &crate::i18n::date_group_label(key, false)); } if resp.clicked() { - let v = if sel { serde_json::Value::Null } else { json!(key) }; - browse_all_photos(app, !sel); - let _ = app.run("library.filter", json!({"date": v})); + crate::panels::side_select::date_clicked(app, ui, key); } open } diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 9d420fc36b9..6279e416491 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -319,6 +319,9 @@ pub(super) fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[F let leads_on = n.own == 0 && n.children.len() == 1; let mut open = tree_open(ui, open_id, n.volume || leads_on); // a row whose path would cover other disks' photos too only opens and closes + if n.selectable { + app.ui.side.folders.saw(n.path.clone()); + } let name = if n.selectable { n.name.clone() } else { crate::i18n::tr("This Computer").to_string() }; let id = format!("libfolder:{}", n.path); if !out_of_sight(app, ui, &id, &name, Some(n.count), indent, n.label.is_some()) { @@ -333,9 +336,7 @@ pub(super) fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[F /// One drawn row of [`folder_rows`], shown as `name`; `open_id` and `open` are its triangle's. #[allow(clippy::too_many_arguments)] fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &str, name: &str, indent: f32, open_id: egui::Id, open: &mut bool) { - let sel = n.selectable - && app.session.source == LibrarySource::LibraryFolder - && app.session.library_folder.as_deref().is_some_and(|f| same_folder(f, &n.path)); + let sel = n.selectable && crate::panels::side_select::folder_shown(app, &n.path); // the label is said with the name, as it is shown beside it let spoken = match n.label { Some(l) => format!("{name}, {}", crate::i18n::color_label(&app.session.catalog, l)), @@ -356,7 +357,7 @@ fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &s if resp.clicked() && !toggled { if n.selectable { // a source like an album or a Local folder: it replaces what the grid showed - let _ = app.run("library.source", json!({"kind": "libraryFolder", "path": n.path})); + crate::panels::side_select::folder_clicked(app, ui, &n.path); } else { *open = !*open; set_tree_open(ui, open_id, *open); diff --git a/crates/ui-egui/src/panels/left/keywords.rs b/crates/ui-egui/src/panels/left/keywords.rs index 2ec3569fa52..2e732b18f4e 100644 --- a/crates/ui-egui/src/panels/left/keywords.rs +++ b/crates/ui-egui/src/panels/left/keywords.rs @@ -1,4 +1,3 @@ -use super::dates::browse_all_photos; use super::rows::{INDENT_STEP, Row, out_of_sight, tree_open, tree_toggle}; use super::{Icon, KeywordNode, LightcraftApp, json}; @@ -11,6 +10,7 @@ pub(super) fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[ let open_id = (!n.children.is_empty()).then(|| egui::Id::unique(("kw-open", n.path.to_lowercase()))); let mut open = open_id.is_some_and(|k| tree_open(ui, k, false)); let id = format!("keyword:{}", n.path); + app.ui.side.keywords.saw(n.path.clone()); if !out_of_sight(app, ui, &id, &n.name, Some(n.count), indent, false) { keyword_row(app, ui, n, &id, indent, open_id, &mut open); } @@ -22,16 +22,14 @@ pub(super) fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[ /// One drawn row of [`keyword_rows`]; `open_id` and `open` are its triangle's when it has rows inside it. fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: &str, indent: f32, open_id: Option, open: &mut bool) { - let sel = app.session.filter.keyword.as_deref().is_some_and(|k| k.eq_ignore_ascii_case(&n.path)); + let sel = crate::panels::side_select::keyword_shown(app, &n.path); let resp = Row::new(id, Icon::Tag, &n.name).count(Some(n.count)).selected(sel).indent(indent).show(app, ui); if let Some(k) = open_id { tree_toggle(ui, &resp, indent, k, open, format!("keywordToggle:{}", n.path), &n.name); } let resp = resp.on_hover_text(if n.children.is_empty() { n.path.clone() } else { format!("{} (includes the keywords below it)", n.path) }); if resp.clicked() { - let v = if sel { serde_json::Value::Null } else { json!(n.path) }; - browse_all_photos(app, !sel); - let _ = app.run("library.filter", json!({"keyword": v})); + crate::panels::side_select::keyword_clicked(app, ui, &n.path); } crate::widgets::context_menu(&resp, |ui| { let has_sel = app.session.active().is_some(); From 639924eca85a54eb071de7711aea3cfde56b7a6e Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 20:23:26 -0500 Subject: [PATCH 33/55] LR-BEHAV-MULTISELECT: the smart-album editor counts within the albums the smart album was made from again The 2 Nov restack dropped the fix kept in 417196047b (first written as 316f3f7b48, pushed in 137bbfad): rules_view took only the folders, so the editor of a smart album made from a view of several albums counted every photo of the library. rules_view takes the filter the album carries again (library_folders, album and albums, and the filter goes into the cache key); the editor passes the one the saved album holds. The unit test of that commit comes back too, and a dialog-level test opens the editor of an album made from two albums: it counted the whole library (24 photos match) at de07d6bf37 and counts the three photos of the two albums now. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/caches.rs | 55 ++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 13 ++++-- crates/ui-egui/src/tests/multi_select.rs | 27 ++++++++++++ 3 files changed, 82 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 0b66fc490d9..f454a5ae790 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -263,19 +263,26 @@ impl Caches { /// when `now` (the session clock, ISO) enters a new minute, so such counts follow the clock /// within a minute without rescanning every frame. /// [`RulesView`] for `rules` edited in smart album `editing` (`None`: a new album), within - /// `folders` when it was made from a folder view (a photo of any of them counts): worked out again only when the catalog, the + /// what it carries (`carried`: the albums and folders it was made from, a photo of any of them counts): worked out again only when the catalog, the /// rules, the language or (for "in the last…" rules) the minute changes, not every frame. pub fn rules_view( &mut self, cat: &lightcraft_catalog::Catalog, rules: &lightcraft_catalog::RuleSet, editing: Option, - folders: Vec, + carried: lightcraft_catalog::Filter, now: &str, ) -> std::sync::Arc { let relative = rules.depends_on_now(); let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - let k = key_of((cat.revision, serde_json::to_string(rules).unwrap_or_default(), editing, &folders, minute, i18n::language().code())); + let k = key_of(( + cat.revision, + serde_json::to_string(rules).unwrap_or_default(), + editing, + serde_json::to_string(&carried).unwrap_or_default(), + minute, + i18n::language().code(), + )); if let Some((key, v)) = &self.rules_view && *key == k { @@ -285,7 +292,13 @@ impl Caches { lightcraft_catalog::rules::set_now(Some(now.to_string())); } let problems = rules.check_for(cat, editing.map(lightcraft_catalog::AlbumId)); - let filter = lightcraft_catalog::Filter { rule_set: Some(rules.clone()), library_folders: folders, ..Default::default() }; + let filter = lightcraft_catalog::Filter { + rule_set: Some(rules.clone()), + library_folders: carried.library_folders, + album: carried.album, + albums: carried.albums, + ..Default::default() + }; let count = if problems.is_empty() { cat.query(&filter, &Default::default()).len() } else { 0 }; let v = std::sync::Arc::new(RulesView { problems, count, albums: panels::dialogs::album_entries(cat, editing) }); self.rules_view_scans += 1; @@ -419,6 +432,30 @@ mod cache_tests { lightcraft_catalog::rules::set_now(None); } + /// A smart album made from a view of several albums stays limited to them (`album.setRules` with + /// `replace` keeps its albums and folders): the editor's count is of the photos the saved album shows. + #[test] + fn the_rule_dialog_counts_within_the_albums_the_smart_album_was_made_from() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 1..=3u64 { + cat.apply(photo(i, "2026-09-30T11:00:00", 5)).unwrap(); + } + let mut a = Album::new(AlbumId(20), "Trip"); + a.photos = vec![PhotoId(1), PhotoId(2)]; + cat.apply(Op::AddAlbum { album: a }).unwrap(); + let rules: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + let now = "2026-09-30T12:00:00"; + let within = Filter { albums: vec![AlbumId(20)], ..Default::default() }; + assert_eq!(c.rules_view(&cat, &rules, None, within, now).count, 2, "only the photos of its albums"); + assert_eq!( + c.rules_view(&cat, &rules, None, Filter { album: Some(AlbumId(20)), ..Default::default() }, now).count, + 2, + "also its single album" + ); + assert_eq!(c.rules_view(&cat, &rules, None, Filter::default(), now).count, 3, "none carried: every photo"); + } + /// The rule dialog's problems, live count and album list are worked out once per change to the /// catalog or the rules, not every frame; so are the sidebar's smart-album problems. #[test] @@ -431,16 +468,16 @@ mod cache_tests { let rules = |v: u64| -> RuleSet { serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": v}]})).unwrap() }; let now = "2026-09-30T12:00:00"; - let view = c.rules_view(&cat, &rules(3), None, Vec::new(), now); + let view = c.rules_view(&cat, &rules(3), None, Filter::default(), now); assert_eq!((view.count, view.problems.len()), (1, 0)); for _ in 0..10 { - c.rules_view(&cat, &rules(3), None, Vec::new(), now); + c.rules_view(&cat, &rules(3), None, Filter::default(), now); } assert_eq!(c.rules_view_scans, 1, "unchanged frames reuse it"); - assert_eq!(c.rules_view(&cat, &rules(1), None, Vec::new(), now).count, 3, "a rule change"); - assert_eq!(c.rules_view(&cat, &rules(9), None, Vec::new(), now).problems.len(), 1); + assert_eq!(c.rules_view(&cat, &rules(1), None, Filter::default(), now).count, 3, "a rule change"); + assert_eq!(c.rules_view(&cat, &rules(9), None, Filter::default(), now).problems.len(), 1); cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.rules_view(&cat, &rules(3), None, Vec::new(), now).count, 2, "a catalog change"); + assert_eq!(c.rules_view(&cat, &rules(3), None, Filter::default(), now).count, 2, "a catalog change"); assert_eq!(c.rules_view_scans, 4); // the sidebar's problems cat.apply(Op::AddAlbum { album: lightcraft_catalog::Album::new(AlbumId(20), "Trip") }).unwrap(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 18eaf351e31..cb5ca33df99 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1014,15 +1014,20 @@ fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: ); crate::widgets::register(ui, "field:smartName", r.rect); ui.add_space(6.0); - // the folders an album made from a folder view carries are not in the editor, but they count - let folders: Vec = id + // the albums and folders an album made from a view of several carries are not in the editor, but they count + let carried: lightcraft_catalog::Filter = id .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id))) .and_then(|a| a.smart.as_deref()) - .map(|f| f.library_folder.iter().chain(&f.library_folders).cloned().collect()) + .map(|f| lightcraft_catalog::Filter { + library_folders: f.library_folder.iter().chain(&f.library_folders).cloned().collect(), + album: f.album, + albums: f.albums.clone(), + ..Default::default() + }) .unwrap_or_default(); // problems, count and albums: cached until the catalog or the rules change (not per frame) let now = (app.session.clock)(); - let view = app.caches.rules_view(&app.session.catalog, rules, *id, folders, &now); + let view = app.caches.rules_view(&app.session.catalog, rules, *id, carried, &now); let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index bf40cf1ba55..8bcf9a4f35d 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -446,3 +446,30 @@ fn the_smart_album_editor_counts_photos_of_every_folder_the_album_was_made_from( let text = h.painted_text().join(" "); assert!(text.contains("2 photos match"), "{text}"); } + +/// A smart album made from a view of albums stays limited to them (`album.setRules` with `replace` +/// keeps its albums): the editor counts the photos the saved album shows, not the whole library. +#[test] +fn the_smart_album_editor_counts_within_the_albums_the_album_was_made_from() { + let mut h = app("info"); + let ([a, b, c, _], _) = four_albums(&mut h); + let library = h.app.session.catalog.photos().count(); + assert!(library > 3, "the demo library has more photos than the albums hold: {library}"); + // Given a smart album made from the view of two albums (three photos between them, one in both) + run(&mut h, "library.source", json!({"kind": "album", "ids": [a, c]})); + let several = run(&mut h, "album.createSmart", json!({"name": "Both"}))["id"].as_u64().unwrap(); + // When its editor opens with no rule of its own + h.app.ui.dialog = Some(Dialog::SmartRules { id: Some(several), name: "Both".into(), rules: Default::default(), parent: None }); + h.settle(SETTLE); + // Then it counts those three photos + let text = h.painted_text().join(" "); + assert!(text.contains("3 photos match"), "{text}"); + // and one album alone, the photo that one holds + h.app.ui.dialog = None; + run(&mut h, "library.source", json!({"kind": "album", "id": b})); + let one = run(&mut h, "album.createSmart", json!({"name": "One"}))["id"].as_u64().unwrap(); + h.app.ui.dialog = Some(Dialog::SmartRules { id: Some(one), name: "One".into(), rules: Default::default(), parent: None }); + h.settle(SETTLE); + let text = h.painted_text().join(" "); + assert!(text.contains("1 photo match"), "{text}"); +} From 381c9f2becb2ea0991d242a2831ca6a19fcd31d6 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 14:16:44 -0400 Subject: [PATCH 34/55] LR-BEHAV-MULTISELECT: the menu, dragging and Delete key of several chosen sidebar rows act on all of them The menu of one of several rows chosen offers what can be done to them all (move, export or delete albums; label or remove folders; give keywords to the selected photos, take them away, merge or delete them), dragging one of them moves them all, and the Delete key asks about rows just chosen with Cmd or Shift. Deleting or removing several asks first and says what goes. Every action is one undo step through the batch commands of #2757. Parents: the PR before this one (sidebar-multiselect-click f54bb52eec) and #2757 b259121b9f. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs-formats.json | 17 +- crates/ui-egui/locales/cs.json | 18 +- crates/ui-egui/locales/de-formats.json | 17 +- crates/ui-egui/locales/de.json | 18 +- crates/ui-egui/locales/es-formats.json | 17 +- crates/ui-egui/locales/es.json | 19 +- crates/ui-egui/locales/fi-formats.json | 17 +- crates/ui-egui/locales/fi.json | 18 +- crates/ui-egui/locales/fr-formats.json | 17 +- crates/ui-egui/locales/id-formats.json | 17 +- crates/ui-egui/locales/id.json | 18 +- crates/ui-egui/locales/it-formats.json | 17 +- crates/ui-egui/locales/it.json | 18 +- crates/ui-egui/locales/ja-formats.json | 17 +- crates/ui-egui/locales/ja.json | 19 +- crates/ui-egui/locales/ka-formats.json | 17 +- crates/ui-egui/locales/ka.json | 18 +- crates/ui-egui/locales/pl-formats.json | 17 +- crates/ui-egui/locales/pl.json | 19 +- crates/ui-egui/locales/pt-br-formats.json | 17 +- crates/ui-egui/locales/pt-br.json | 19 +- crates/ui-egui/locales/ru-formats.json | 17 +- crates/ui-egui/locales/sv-formats.json | 17 +- crates/ui-egui/locales/sv.json | 18 +- crates/ui-egui/locales/uk-formats.json | 17 +- crates/ui-egui/locales/uk.json | 19 +- crates/ui-egui/locales/vi-formats.json | 17 +- crates/ui-egui/locales/vi.json | 18 +- crates/ui-egui/locales/zh-hans-formats.json | 17 +- crates/ui-egui/locales/zh-hans.json | 19 +- crates/ui-egui/locales/zh-hant-formats.json | 17 +- crates/ui-egui/locales/zh-hant.json | 19 +- crates/ui-egui/src/app.rs | 9 + crates/ui-egui/src/app/frame.rs | 2 +- crates/ui-egui/src/dialogs.rs | 6 + crates/ui-egui/src/dialogs/confirm.rs | 1 + crates/ui-egui/src/dialogs/frame.rs | 4 +- crates/ui-egui/src/panels/keyword_list.rs | 54 ++- crates/ui-egui/src/panels/left/albums.rs | 23 +- crates/ui-egui/src/panels/left/folders.rs | 28 +- crates/ui-egui/src/panels/left/keywords.rs | 22 +- crates/ui-egui/src/panels/side_select.rs | 389 +++++++++++++++++++- crates/ui-egui/src/shortcuts.rs | 4 + crates/ui-egui/src/state/dialog.rs | 2 + crates/ui-egui/src/tests/dialog_primary.rs | 4 + crates/ui-egui/src/tests/multi_select.rs | 292 ++++++++++++++- docs/gaps.md | 4 +- docs/parity-checklist.md | 1 + docs/whats-new.md | 18 +- 49 files changed, 1358 insertions(+), 71 deletions(-) diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 4f2b401ccc3..90f6abbbba2 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -327,5 +327,20 @@ "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", "{n} albums": "Alba: {n}", - "{n} folders": "Složky: {n}" + "{n} folders": "Složky: {n}", + "Export {n} Albums…": "Exportovat alba ({n})…", + "Move {n} Albums to": "Přesunout alba ({n}) do", + "Delete {n} Albums…": "Odstranit alba ({n})…", + "Remove {n} Folders from Library…": "Odebrat složky ({n}) z knihovny…", + "Add {n} Keywords to Selected Photos": "Přidat klíčová slova ({n}) k vybraným fotografiím", + "Remove {n} Keywords from Selected Photos": "Odebrat klíčová slova ({n}) z vybraných fotografií", + "Show Photos with Any of {n} Keywords": "Zobrazit fotografie s kterýmkoli z klíčových slov ({n})", + "Merge {n} Keywords into…": "Sloučit klíčová slova ({n}) do…", + "Delete {n} Keywords…": "Odstranit klíčová slova ({n})…", + "Delete {n} albums?": "Odstranit alba ({n})?", + "Delete {n} keywords?": "Odstranit klíčová slova ({n})?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotografie, které mají některé z nich: {count}. Smažou se i klíčová slova pod nimi. Zpět je vrátí.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Odebrat složky ({n}) z knihovny? Fotografie z nich importované: {count}.", + "…and {n} more": "…a dalších {n}", + "{n} keywords": "Klíčová slova: {n}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ea102192177..38eee7fbe47 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2472,5 +2472,21 @@ "Welcome": "Vítejte", "Next": "Další", "Get Started": "Začít", - "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Choose one album to rename it": "Pro přejmenování vyberte jedno album", + "Choose one folder to rename it": "Pro přejmenování vyberte jednu složku", + "Choose one folder to synchronize it": "Pro synchronizaci vyberte jednu složku", + "Choose one keyword to create a keyword inside it": "Vyberte jedno klíčové slovo, abyste v něm vytvořili další", + "Choose one keyword to edit it": "Pro úpravu vyberte jedno klíčové slovo", + "Choose one keyword to rename it": "Pro přejmenování vyberte jedno klíčové slovo", + "Create Keyword Tag Inside…": "Vytvořit značku klíčového slova uvnitř…", + "Delete Albums": "Odstranit alba", + "Delete Folder": "Odstranit složku", + "Delete Keywords": "Odstranit klíčová slova", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Přesune fotografie importované z těchto složek do „Nedávno odstraněných“; souborů se nedotkne", + "No photo has them; the keywords below them go too.": "Žádná fotografie je nemá; odstraní se i klíčová slova pod nimi.", + "One of them is a whole disk: remove a disk by itself": "Jedna z nich je celý disk: disk odeberte samostatně", + "Remove Folders from Library": "Odebrat složky z knihovny", + "That includes the photos in the folders inside them.": "Patří sem i fotografie ve složkách uvnitř nich.", + "The photos stay in All Photos. Undo brings the albums back.": "Fotografie zůstanou ve „Všech fotografiích“. Zpět alba vrátí." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 85a573538f6..b8f835be951 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", "{n} albums": "{n} Alben", - "{n} folders": "{n} Ordner" + "{n} folders": "{n} Ordner", + "Export {n} Albums…": "{n} Alben exportieren…", + "Move {n} Albums to": "{n} Alben verschieben nach", + "Delete {n} Albums…": "{n} Alben löschen…", + "Remove {n} Folders from Library…": "{n} Ordner aus Bibliothek entfernen…", + "Add {n} Keywords to Selected Photos": "{n} Stichwörter zu ausgewählten Fotos hinzufügen", + "Remove {n} Keywords from Selected Photos": "{n} Stichwörter von ausgewählten Fotos entfernen", + "Show Photos with Any of {n} Keywords": "Fotos mit einem der {n} Stichwörter anzeigen", + "Merge {n} Keywords into…": "{n} Stichwörter zusammenführen mit…", + "Delete {n} Keywords…": "{n} Stichwörter löschen…", + "Delete {n} albums?": "{n} Alben löschen?", + "Delete {n} keywords?": "{n} Stichwörter löschen?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotos mit einem davon: {count}. Die Stichwörter darunter werden ebenfalls gelöscht. Rückgängig stellt sie wieder her.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "{n} Ordner aus der Bibliothek entfernen? Daraus importierte Fotos: {count}.", + "…and {n} more": "…und {n} weitere", + "{n} keywords": "{n} Stichwörter" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index bc67606eb61..e32a3798220 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3507,5 +3507,21 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", "Welcome": "Willkommen", "Next": "Weiter", - "Get Started": "Loslegen" + "Get Started": "Loslegen", + "Choose one album to rename it": "Wähle ein einzelnes Album, um es umzubenennen", + "Choose one folder to rename it": "Wähle einen einzelnen Ordner, um ihn umzubenennen", + "Choose one folder to synchronize it": "Wähle einen einzelnen Ordner, um ihn zu synchronisieren", + "Choose one keyword to create a keyword inside it": "Wähle ein einzelnes Stichwort, um darin ein Stichwort zu erstellen", + "Choose one keyword to edit it": "Wähle ein einzelnes Stichwort, um es zu bearbeiten", + "Choose one keyword to rename it": "Wähle ein einzelnes Stichwort, um es umzubenennen", + "Create Keyword Tag Inside…": "Stichwort darin erstellen…", + "Delete Albums": "Alben löschen", + "Delete Folder": "Ordner löschen", + "Delete Keywords": "Stichwörter löschen", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Verschiebt die aus diesen Ordnern importierten Fotos nach „Zuletzt gelöscht“; keine Datei wird verändert", + "No photo has them; the keywords below them go too.": "Kein Foto hat sie; die Stichwörter darunter werden ebenfalls gelöscht.", + "One of them is a whole disk: remove a disk by itself": "Einer davon ist ein ganzer Datenträger: einen Datenträger einzeln entfernen", + "Remove Folders from Library": "Ordner aus Bibliothek entfernen", + "That includes the photos in the folders inside them.": "Das schließt die Fotos in den enthaltenen Unterordnern ein.", + "The photos stay in All Photos. Undo brings the albums back.": "Die Fotos bleiben in „Alle Fotos“. Rückgängig stellt die Alben wieder her." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index c8d029dacb7..d5b0d5dd550 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", "{n} albums": "{n} álbumes", - "{n} folders": "{n} carpetas" + "{n} folders": "{n} carpetas", + "Export {n} Albums…": "Exportar {n} álbumes…", + "Move {n} Albums to": "Mover {n} álbumes a", + "Delete {n} Albums…": "Eliminar {n} álbumes…", + "Remove {n} Folders from Library…": "Quitar {n} carpetas de la biblioteca…", + "Add {n} Keywords to Selected Photos": "Añadir {n} palabras clave a las fotos seleccionadas", + "Remove {n} Keywords from Selected Photos": "Quitar {n} palabras clave de las fotos seleccionadas", + "Show Photos with Any of {n} Keywords": "Mostrar fotos con alguna de las {n} palabras clave", + "Merge {n} Keywords into…": "Combinar {n} palabras clave con…", + "Delete {n} Keywords…": "Eliminar {n} palabras clave…", + "Delete {n} albums?": "¿Eliminar {n} álbumes?", + "Delete {n} keywords?": "¿Eliminar {n} palabras clave?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotos que tienen alguna: {count}. Las palabras clave que contienen también se eliminan. Deshacer las recupera.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "¿Quitar {n} carpetas de la biblioteca? Fotos importadas de ellas: {count}.", + "…and {n} more": "…y {n} más", + "{n} keywords": "{n} palabras clave" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index c34057bdfe5..d2c3eb320b0 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2426,5 +2426,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", "Welcome": "Bienvenido", "Next": "Siguiente", - "Get Started": "Empezar" + "Get Started": "Empezar", + "Choose one album to rename it": "Elige un solo álbum para cambiarle el nombre", + "Choose one folder to rename it": "Elige una sola carpeta para cambiarle el nombre", + "Choose one folder to synchronize it": "Elige una sola carpeta para sincronizarla", + "Choose one keyword to create a keyword inside it": "Elige una sola palabra clave para crear otra dentro de ella", + "Choose one keyword to edit it": "Elige una sola palabra clave para editarla", + "Choose one keyword to rename it": "Elige una sola palabra clave para cambiarle el nombre", + "Create Keyword Tag Inside…": "Crear palabra clave dentro…", + "Delete Albums": "Eliminar álbumes", + "Delete Folder": "Eliminar carpeta", + "Delete Keywords": "Eliminar palabras clave", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Mueve las fotos importadas desde estas carpetas a Eliminadas recientemente; no se toca ningún archivo", + "No photo has them; the keywords below them go too.": "Ninguna foto las tiene; las palabras clave que contienen también se eliminan.", + "One of them is a whole disk: remove a disk by itself": "Una de ellas es un disco entero: quita un disco por separado", + "Remove Folders from Library": "Quitar carpetas de la biblioteca", + "That includes the photos in the folders inside them.": "Esto incluye las fotos de las carpetas que contienen.", + "The photos stay in All Photos. Undo brings the albums back.": "Las fotos se quedan en Todas las fotos. Deshacer recupera los álbumes.", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Las fotos se quedan en Todas las fotos. Al eliminar una carpeta también se eliminan sus álbumes. Puedes deshacerlo." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index e5d43578f2b..d0212b01fd0 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -324,5 +324,20 @@ "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", "{n} albums": "{n} albumia", - "{n} folders": "{n} kansiota" + "{n} folders": "{n} kansiota", + "Export {n} Albums…": "Vie {n} albumia…", + "Move {n} Albums to": "Siirrä {n} albumia kohteeseen", + "Delete {n} Albums…": "Poista {n} albumia…", + "Remove {n} Folders from Library…": "Poista {n} kansiota kirjastosta…", + "Add {n} Keywords to Selected Photos": "Lisää {n} avainsanaa valittuihin kuviin", + "Remove {n} Keywords from Selected Photos": "Poista {n} avainsanaa valituista kuvista", + "Show Photos with Any of {n} Keywords": "Näytä kuvat, joilla on jokin {n} avainsanasta", + "Merge {n} Keywords into…": "Yhdistä {n} avainsanaa kohteeseen…", + "Delete {n} Keywords…": "Poista {n} avainsanaa…", + "Delete {n} albums?": "Poistetaanko {n} albumia?", + "Delete {n} keywords?": "Poistetaanko {n} avainsanaa?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Kuvia, joilla on jokin niistä: {count}. Niiden alla olevat avainsanat poistetaan myös. Kumoa palauttaa ne.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Poistetaanko {n} kansiota kirjastosta? Niistä tuotuja kuvia: {count}.", + "…and {n} more": "…ja {n} muuta", + "{n} keywords": "{n} avainsanaa" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 59cc611cd61..2613f08fcae 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2383,5 +2383,21 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", - "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Choose one album to rename it": "Valitse yksi albumi nimetäksesi sen uudelleen", + "Choose one folder to rename it": "Valitse yksi kansio nimetäksesi sen uudelleen", + "Choose one folder to synchronize it": "Valitse yksi kansio synkronoidaksesi sen", + "Choose one keyword to create a keyword inside it": "Valitse yksi avainsana luodaksesi sen sisään avainsanan", + "Choose one keyword to edit it": "Valitse yksi avainsana muokataksesi sitä", + "Choose one keyword to rename it": "Valitse yksi avainsana nimetäksesi sen uudelleen", + "Create Keyword Tag Inside…": "Luo avainsanatunniste sisään…", + "Delete Albums": "Poista albumit", + "Delete Folder": "Poista kansio", + "Delete Keywords": "Poista avainsanat", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Siirtää näistä kansioista tuodut kuvat kohtaan Äskettäin poistetut; mitään tiedostoa ei kosketa", + "No photo has them; the keywords below them go too.": "Yhdelläkään kuvalla ei ole niitä; niiden alla olevat avainsanat poistetaan myös.", + "One of them is a whole disk: remove a disk by itself": "Yksi niistä on kokonainen levy: poista levy erikseen", + "Remove Folders from Library": "Poista kansiot kirjastosta", + "That includes the photos in the folders inside them.": "Tämä sisältää niiden sisällä olevissa kansioissa olevat kuvat.", + "The photos stay in All Photos. Undo brings the albums back.": "Kuvat pysyvät kohdassa Kaikki kuvat. Kumoa palauttaa albumit." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index db5aceb98bf..2ba583cd078 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", "{n} albums": "{n} albums", - "{n} folders": "{n} dossiers" + "{n} folders": "{n} dossiers", + "Export {n} Albums…": "Exporter {n} albums…", + "Move {n} Albums to": "Déplacer {n} albums vers", + "Delete {n} Albums…": "Supprimer {n} albums…", + "Remove {n} Folders from Library…": "Retirer {n} dossiers de la bibliothèque…", + "Add {n} Keywords to Selected Photos": "Ajouter {n} mots-clés aux photos sélectionnées", + "Remove {n} Keywords from Selected Photos": "Retirer {n} mots-clés des photos sélectionnées", + "Show Photos with Any of {n} Keywords": "Afficher les photos avec l'un des {n} mots-clés", + "Merge {n} Keywords into…": "Fusionner {n} mots-clés dans…", + "Delete {n} Keywords…": "Supprimer {n} mots-clés…", + "Delete {n} albums?": "Supprimer {n} albums ?", + "Delete {n} keywords?": "Supprimer {n} mots-clés ?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Photos qui en portent un : {count}. Les mots-clés qu'ils contiennent sont aussi supprimés. Annuler les rétablit.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Retirer {n} dossiers de la bibliothèque ? Photos importées depuis ces dossiers : {count}.", + "…and {n} more": "…et {n} de plus", + "{n} keywords": "{n} mots-clés" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 18218280d63..e69865e14e1 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -327,5 +327,20 @@ "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", "{n} albums": "{n} album", - "{n} folders": "{n} folder" + "{n} folders": "{n} folder", + "Export {n} Albums…": "Ekspor {n} album…", + "Move {n} Albums to": "Pindahkan {n} album ke", + "Delete {n} Albums…": "Hapus {n} album…", + "Remove {n} Folders from Library…": "Keluarkan {n} folder dari pustaka…", + "Add {n} Keywords to Selected Photos": "Tambahkan {n} kata kunci ke foto yang dipilih", + "Remove {n} Keywords from Selected Photos": "Hapus {n} kata kunci dari foto yang dipilih", + "Show Photos with Any of {n} Keywords": "Tampilkan foto dengan salah satu dari {n} kata kunci", + "Merge {n} Keywords into…": "Gabungkan {n} kata kunci ke…", + "Delete {n} Keywords…": "Hapus {n} kata kunci…", + "Delete {n} albums?": "Hapus {n} album?", + "Delete {n} keywords?": "Hapus {n} kata kunci?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Foto yang memiliki salah satunya: {count}. Kata kunci di bawahnya ikut terhapus. Urungkan mengembalikannya.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Keluarkan {n} folder dari pustaka? Foto yang diimpor dari folder tersebut: {count}.", + "…and {n} more": "…dan {n} lainnya", + "{n} keywords": "{n} kata kunci" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 52705328cc7..3c775154080 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2397,5 +2397,21 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", - "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Choose one album to rename it": "Pilih satu album untuk mengganti namanya", + "Choose one folder to rename it": "Pilih satu folder untuk mengganti namanya", + "Choose one folder to synchronize it": "Pilih satu folder untuk menyinkronkannya", + "Choose one keyword to create a keyword inside it": "Pilih satu kata kunci untuk membuat kata kunci di dalamnya", + "Choose one keyword to edit it": "Pilih satu kata kunci untuk mengeditnya", + "Choose one keyword to rename it": "Pilih satu kata kunci untuk mengganti namanya", + "Create Keyword Tag Inside…": "Buat tag kata kunci di dalam…", + "Delete Albums": "Hapus album", + "Delete Folder": "Hapus folder", + "Delete Keywords": "Hapus kata kunci", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Memindahkan foto yang diimpor dari folder ini ke Baru dihapus; tidak ada file yang disentuh", + "No photo has them; the keywords below them go too.": "Tidak ada foto yang memilikinya; kata kunci di bawahnya ikut terhapus.", + "One of them is a whole disk: remove a disk by itself": "Salah satunya adalah satu disk penuh: keluarkan disk secara terpisah", + "Remove Folders from Library": "Keluarkan folder dari pustaka", + "That includes the photos in the folders inside them.": "Ini mencakup foto di dalam folder yang ada di dalamnya.", + "The photos stay in All Photos. Undo brings the albums back.": "Foto tetap ada di Semua foto. Urungkan mengembalikan album." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index c9967b0bae4..bdb5faeda63 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -327,5 +327,20 @@ "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", "{n} albums": "{n} album", - "{n} folders": "{n} cartelle" + "{n} folders": "{n} cartelle", + "Export {n} Albums…": "Esporta {n} album…", + "Move {n} Albums to": "Sposta {n} album in", + "Delete {n} Albums…": "Elimina {n} album…", + "Remove {n} Folders from Library…": "Rimuovi {n} cartelle dalla libreria…", + "Add {n} Keywords to Selected Photos": "Aggiungi {n} parole chiave alle foto selezionate", + "Remove {n} Keywords from Selected Photos": "Rimuovi {n} parole chiave dalle foto selezionate", + "Show Photos with Any of {n} Keywords": "Mostra le foto con una qualsiasi delle {n} parole chiave", + "Merge {n} Keywords into…": "Unisci {n} parole chiave in…", + "Delete {n} Keywords…": "Elimina {n} parole chiave…", + "Delete {n} albums?": "Eliminare {n} album?", + "Delete {n} keywords?": "Eliminare {n} parole chiave?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Foto che ne hanno uno: {count}. Vengono eliminate anche le parole chiave sotto di esse. Annulla le ripristina.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Rimuovere {n} cartelle dalla libreria? Foto importate da esse: {count}.", + "…and {n} more": "…e altri {n}", + "{n} keywords": "{n} parole chiave" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5b0ccc0cee0..7bf4860e864 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2590,5 +2590,21 @@ "Welcome": "Benvenuto", "Next": "Avanti", "Get Started": "Inizia", - "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Choose one album to rename it": "Scegli un solo album per rinominarlo", + "Choose one folder to rename it": "Scegli una sola cartella per rinominarla", + "Choose one folder to synchronize it": "Scegli una sola cartella per sincronizzarla", + "Choose one keyword to create a keyword inside it": "Scegli una sola parola chiave per crearne una al suo interno", + "Choose one keyword to edit it": "Scegli una sola parola chiave per modificarla", + "Choose one keyword to rename it": "Scegli una sola parola chiave per rinominarla", + "Create Keyword Tag Inside…": "Crea tag parola chiave all'interno…", + "Delete Albums": "Elimina album", + "Delete Folder": "Elimina cartella", + "Delete Keywords": "Elimina parole chiave", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Sposta le foto importate da queste cartelle in Eliminate di recente; nessun file viene toccato", + "No photo has them; the keywords below them go too.": "Nessuna foto le ha; vengono eliminate anche le parole chiave sotto di esse.", + "One of them is a whole disk: remove a disk by itself": "Uno di essi è un disco intero: rimuovi un disco da solo", + "Remove Folders from Library": "Rimuovi cartelle dalla libreria", + "That includes the photos in the folders inside them.": "Sono incluse le foto nelle cartelle al loro interno.", + "The photos stay in All Photos. Undo brings the albums back.": "Le foto restano in Tutte le foto. Annulla ripristina gli album." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index ebaf0566115..9ba4d242c4d 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", "{n} albums": "{n}個のアルバム", - "{n} folders": "{n}個のフォルダ" + "{n} folders": "{n}個のフォルダ", + "Export {n} Albums…": "{n}個のアルバムを書き出す…", + "Move {n} Albums to": "{n}個のアルバムの移動先", + "Delete {n} Albums…": "{n}個のアルバムを削除…", + "Remove {n} Folders from Library…": "{n}個のフォルダをライブラリから除去…", + "Add {n} Keywords to Selected Photos": "{n}個のキーワードを選択した写真に追加", + "Remove {n} Keywords from Selected Photos": "{n}個のキーワードを選択した写真から削除", + "Show Photos with Any of {n} Keywords": "{n}個のキーワードのいずれかを含む写真を表示", + "Merge {n} Keywords into…": "{n}個のキーワードの統合先…", + "Delete {n} Keywords…": "{n}個のキーワードを削除…", + "Delete {n} albums?": "{n}個のアルバムを削除しますか?", + "Delete {n} keywords?": "{n}個のキーワードを削除しますか?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "いずれかを含む写真: {count}枚。下位のキーワードも削除されます。取り消すと元に戻ります。", + "Remove {n} folders from the library? Photos imported from them: {count}.": "{n}個のフォルダをライブラリから除去しますか? 読み込まれた写真: {count}枚。", + "…and {n} more": "…ほか{n}個", + "{n} keywords": "{n}個のキーワード" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 97c15dd0191..b1733d01aa6 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2424,5 +2424,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", "Welcome": "ようこそ", "Next": "次へ", - "Get Started": "始める" + "Get Started": "始める", + "Choose one album to rename it": "名前を変更するには、アルバムを1つだけ選択してください", + "Choose one folder to rename it": "名前を変更するには、フォルダを1つだけ選択してください", + "Choose one folder to synchronize it": "同期するには、フォルダを1つだけ選択してください", + "Choose one keyword to create a keyword inside it": "中にキーワードを作成するには、キーワードを1つだけ選択してください", + "Choose one keyword to edit it": "編集するには、キーワードを1つだけ選択してください", + "Choose one keyword to rename it": "名前を変更するには、キーワードを1つだけ選択してください", + "Create Keyword Tag Inside…": "この中にキーワードタグを作成…", + "Delete Albums": "アルバムを削除", + "Delete Folder": "フォルダを削除", + "Delete Keywords": "キーワードを削除", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "これらのフォルダから読み込んだ写真を「最近削除した写真」に移動します。ファイルには手を加えません", + "No photo has them; the keywords below them go too.": "これらのキーワードを持つ写真はありません。下位のキーワードも削除されます。", + "One of them is a whole disk: remove a disk by itself": "その中にディスク全体が含まれています。ディスクは単独で除去してください", + "Remove Folders from Library": "フォルダをライブラリから除去", + "That includes the photos in the folders inside them.": "その中にあるフォルダの写真も含まれます。", + "The photos stay in All Photos. Undo brings the albums back.": "写真は「すべての写真」に残ります。「取り消す」でアルバムが戻ります。", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "写真は「すべての写真」に残ります。フォルダを削除すると、その中のアルバムも削除されます。「取り消す」で元に戻せます。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index cf05948c2f5..ed1e5113dba 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -330,5 +330,20 @@ "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", "{n} albums": "ალბომები: {n}", - "{n} folders": "საქაღალდეები: {n}" + "{n} folders": "საქაღალდეები: {n}", + "Export {n} Albums…": "{n} ალბომის ექსპორტი…", + "Move {n} Albums to": "{n} ალბომის გადატანა", + "Delete {n} Albums…": "{n} ალბომის წაშლა…", + "Remove {n} Folders from Library…": "{n} საქაღალდის ამოღება ბიბლიოთეკიდან…", + "Add {n} Keywords to Selected Photos": "{n} საკვანძო სიტყვის დამატება არჩეულ ფოტოებზე", + "Remove {n} Keywords from Selected Photos": "{n} საკვანძო სიტყვის მოხსნა არჩეული ფოტოებიდან", + "Show Photos with Any of {n} Keywords": "ფოტოების ჩვენება {n} საკვანძო სიტყვიდან რომელიმეთი", + "Merge {n} Keywords into…": "{n} საკვანძო სიტყვის გაერთიანება…", + "Delete {n} Keywords…": "{n} საკვანძო სიტყვის წაშლა…", + "Delete {n} albums?": "წავშალოთ {n} ალბომი?", + "Delete {n} keywords?": "წავშალოთ {n} საკვანძო სიტყვა?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "ფოტოები, რომლებსაც ერთ-ერთი აქვს: {count}. მათ ქვემოთ არსებული საკვანძო სიტყვებიც წაიშლება. გაუქმება მათ დააბრუნებს.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "ამოვიღოთ {n} საქაღალდე ბიბლიოთეკიდან? მათგან იმპორტირებული ფოტოები: {count}.", + "…and {n} more": "…და კიდევ {n}", + "{n} keywords": "საკვანძო სიტყვები: {n}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 30769b60fa1..e7cc47b970a 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3692,5 +3692,21 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", - "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Choose one album to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი ალბომი", + "Choose one folder to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი საქაღალდე", + "Choose one folder to synchronize it": "სინქრონიზაციისთვის აირჩიეთ ერთი საქაღალდე", + "Choose one keyword to create a keyword inside it": "აირჩიეთ ერთი საკვანძო სიტყვა, რომ მასში ახალი შექმნათ", + "Choose one keyword to edit it": "რედაქტირებისთვის აირჩიეთ ერთი საკვანძო სიტყვა", + "Choose one keyword to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი საკვანძო სიტყვა", + "Create Keyword Tag Inside…": "შიგნით საკვანძო სიტყვის შექმნა…", + "Delete Albums": "ალბომების წაშლა", + "Delete Folder": "საქაღალდის წაშლა", + "Delete Keywords": "საკვანძო სიტყვების წაშლა", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "ამ საქაღალდეებიდან იმპორტირებულ ფოტოებს „ახლახან წაშლილში“ გადაიტანს; ფაილებს არ ეხება", + "No photo has them; the keywords below them go too.": "არცერთ ფოტოს არ აქვს; მათ ქვემოთ არსებული საკვანძო სიტყვებიც წაიშლება.", + "One of them is a whole disk: remove a disk by itself": "ერთ-ერთი მათგანი მთელი დისკია: დისკი ცალკე მოაშორეთ", + "Remove Folders from Library": "საქაღალდეების ბიბლიოთეკიდან ამოღება", + "That includes the photos in the folders inside them.": "ეს მოიცავს მათში არსებული საქაღალდეების ფოტოებსაც.", + "The photos stay in All Photos. Undo brings the albums back.": "ფოტოები „ყველა ფოტოში“ რჩება. „დაბრუნება“ ალბომებს აღადგენს." } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index af654a30171..ccb71e0da01 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -327,5 +327,20 @@ "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", "{n} albums": "Albumy: {n}", - "{n} folders": "Foldery: {n}" + "{n} folders": "Foldery: {n}", + "Export {n} Albums…": "Eksportuj albumy ({n})…", + "Move {n} Albums to": "Przenieś albumy ({n}) do", + "Delete {n} Albums…": "Usuń albumy ({n})…", + "Remove {n} Folders from Library…": "Usuń foldery ({n}) z biblioteki…", + "Add {n} Keywords to Selected Photos": "Dodaj słowa kluczowe ({n}) do zaznaczonych zdjęć", + "Remove {n} Keywords from Selected Photos": "Usuń słowa kluczowe ({n}) z zaznaczonych zdjęć", + "Show Photos with Any of {n} Keywords": "Pokaż zdjęcia z dowolnym ze słów kluczowych ({n})", + "Merge {n} Keywords into…": "Scal słowa kluczowe ({n}) z…", + "Delete {n} Keywords…": "Usuń słowa kluczowe ({n})…", + "Delete {n} albums?": "Usunąć albumy ({n})?", + "Delete {n} keywords?": "Usunąć słowa kluczowe ({n})?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Zdjęcia, które mają jedno z nich: {count}. Słowa kluczowe pod nimi też zostaną usunięte. Cofnij je przywróci.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Usunąć foldery ({n}) z biblioteki? Zdjęcia z nich zaimportowane: {count}.", + "…and {n} more": "…i {n} więcej", + "{n} keywords": "Słowa kluczowe: {n}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index dbc29a19417..db202d19a8d 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2348,5 +2348,22 @@ "Welcome": "Witamy", "Next": "Dalej", "Get Started": "Zaczynamy", - "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Choose one album to rename it": "Wybierz jeden album, aby zmienić jego nazwę", + "Choose one folder to rename it": "Wybierz jeden folder, aby zmienić jego nazwę", + "Choose one folder to synchronize it": "Wybierz jeden folder, aby go zsynchronizować", + "Choose one keyword to create a keyword inside it": "Wybierz jedno słowo kluczowe, aby utworzyć w nim kolejne", + "Choose one keyword to edit it": "Wybierz jedno słowo kluczowe, aby je edytować", + "Choose one keyword to rename it": "Wybierz jedno słowo kluczowe, aby zmienić jego nazwę", + "Create Keyword Tag Inside…": "Utwórz słowo kluczowe wewnątrz…", + "Delete Albums": "Usuń albumy", + "Delete Folder": "Usuń folder", + "Delete Keywords": "Usuń słowa kluczowe", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Przenosi zdjęcia zaimportowane z tych folderów do „Ostatnio usunięte”; żaden plik nie jest zmieniany", + "No photo has them; the keywords below them go too.": "Żadne zdjęcie ich nie ma; słowa kluczowe pod nimi też zostaną usunięte.", + "One of them is a whole disk: remove a disk by itself": "Jeden z nich to cały dysk: usuń dysk osobno", + "Remove Folders from Library": "Usuń foldery z biblioteki", + "That includes the photos in the folders inside them.": "Obejmuje to też zdjęcia w folderach wewnątrz nich.", + "The photos stay in All Photos. Undo brings the albums back.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Cofnij przywróci albumy.", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Usunięcie folderu usuwa też jego albumy. Możesz to cofnąć." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f7b24ef1c32..9e1a630b376 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", "{n} albums": "{n} álbuns", - "{n} folders": "{n} pastas" + "{n} folders": "{n} pastas", + "Export {n} Albums…": "Exportar {n} álbuns…", + "Move {n} Albums to": "Mover {n} álbuns para", + "Delete {n} Albums…": "Excluir {n} álbuns…", + "Remove {n} Folders from Library…": "Remover {n} pastas da biblioteca…", + "Add {n} Keywords to Selected Photos": "Adicionar {n} palavras-chave às fotos selecionadas", + "Remove {n} Keywords from Selected Photos": "Remover {n} palavras-chave das fotos selecionadas", + "Show Photos with Any of {n} Keywords": "Mostrar fotos com qualquer uma das {n} palavras-chave", + "Merge {n} Keywords into…": "Mesclar {n} palavras-chave em…", + "Delete {n} Keywords…": "Excluir {n} palavras-chave…", + "Delete {n} albums?": "Excluir {n} álbuns?", + "Delete {n} keywords?": "Excluir {n} palavras-chave?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotos que têm alguma delas: {count}. As palavras-chave abaixo delas também são excluídas. Desfazer as traz de volta.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Remover {n} pastas da biblioteca? Fotos importadas delas: {count}.", + "…and {n} more": "…e mais {n}", + "{n} keywords": "{n} palavras-chave" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 3aedd829064..cfeef163de5 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2270,5 +2270,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", "Welcome": "Bem-vindo", "Next": "Próximo", - "Get Started": "Começar" + "Get Started": "Começar", + "Choose one album to rename it": "Escolha um só álbum para renomeá-lo", + "Choose one folder to rename it": "Escolha uma só pasta para renomeá-la", + "Choose one folder to synchronize it": "Escolha uma só pasta para sincronizá-la", + "Choose one keyword to create a keyword inside it": "Escolha uma só palavra-chave para criar outra dentro dela", + "Choose one keyword to edit it": "Escolha uma só palavra-chave para editá-la", + "Choose one keyword to rename it": "Escolha uma só palavra-chave para renomeá-la", + "Create Keyword Tag Inside…": "Criar palavra-chave dentro…", + "Delete Albums": "Excluir álbuns", + "Delete Folder": "Excluir pasta", + "Delete Keywords": "Excluir palavras-chave", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Move as fotos importadas destas pastas para Excluídos recentemente; nenhum arquivo é alterado", + "No photo has them; the keywords below them go too.": "Nenhuma foto as tem; as palavras-chave abaixo delas também são excluídas.", + "One of them is a whole disk: remove a disk by itself": "Uma delas é um disco inteiro: remova um disco separadamente", + "Remove Folders from Library": "Remover pastas da biblioteca", + "That includes the photos in the folders inside them.": "Isso inclui as fotos das pastas dentro delas.", + "The photos stay in All Photos. Undo brings the albums back.": "As fotos continuam em Todas as fotos. Desfazer traz os álbuns de volta.", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "As fotos continuam em Todas as fotos. Excluir uma pasta também exclui os álbuns dela. Você pode desfazer." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 7107471bfcb..fcbc90d054e 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", "{n} albums": "Альбомы: {n}", - "{n} folders": "Папки: {n}" + "{n} folders": "Папки: {n}", + "Export {n} Albums…": "Экспортировать альбомы ({n})…", + "Move {n} Albums to": "Переместить альбомы ({n}) в", + "Delete {n} Albums…": "Удалить альбомы ({n})…", + "Remove {n} Folders from Library…": "Убрать папки ({n}) из библиотеки…", + "Add {n} Keywords to Selected Photos": "Добавить ключевые слова ({n}) к выбранным фото", + "Remove {n} Keywords from Selected Photos": "Убрать ключевые слова ({n}) с выбранных фото", + "Show Photos with Any of {n} Keywords": "Показать фото с любым из ключевых слов ({n})", + "Merge {n} Keywords into…": "Объединить ключевые слова ({n}) с…", + "Delete {n} Keywords…": "Удалить ключевые слова ({n})…", + "Delete {n} albums?": "Удалить альбомы ({n})?", + "Delete {n} keywords?": "Удалить ключевые слова ({n})?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Фото с одним из них: {count}. Вложенные ключевые слова тоже удаляются. Отмена вернёт их.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Убрать папки ({n}) из библиотеки? Импортированных из них фото: {count}.", + "…and {n} more": "…и ещё {n}", + "{n} keywords": "Ключевые слова: {n}" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 0406151a900..e902669bd96 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -327,5 +327,20 @@ "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", "{n} albums": "{n} album", - "{n} folders": "{n} mappar" + "{n} folders": "{n} mappar", + "Export {n} Albums…": "Exportera {n} album…", + "Move {n} Albums to": "Flytta {n} album till", + "Delete {n} Albums…": "Radera {n} album…", + "Remove {n} Folders from Library…": "Ta bort {n} mappar från biblioteket…", + "Add {n} Keywords to Selected Photos": "Lägg till {n} nyckelord i markerade foton", + "Remove {n} Keywords from Selected Photos": "Ta bort {n} nyckelord från markerade foton", + "Show Photos with Any of {n} Keywords": "Visa foton med något av {n} nyckelord", + "Merge {n} Keywords into…": "Sammanfoga {n} nyckelord med…", + "Delete {n} Keywords…": "Radera {n} nyckelord…", + "Delete {n} albums?": "Radera {n} album?", + "Delete {n} keywords?": "Radera {n} nyckelord?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Foton som har något av dem: {count}. Nyckelorden under dem raderas också. Ångra tar tillbaka dem.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Ta bort {n} mappar från biblioteket? Foton som importerats från dem: {count}.", + "…and {n} more": "…och {n} till", + "{n} keywords": "{n} nyckelord" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 94b9e303338..86a0c048d1d 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2486,5 +2486,21 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", - "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Choose one album to rename it": "Välj ett enda album för att byta namn på det", + "Choose one folder to rename it": "Välj en enda mapp för att byta namn på den", + "Choose one folder to synchronize it": "Välj en enda mapp för att synkronisera den", + "Choose one keyword to create a keyword inside it": "Välj ett enda nyckelord för att skapa ett nyckelord i det", + "Choose one keyword to edit it": "Välj ett enda nyckelord för att redigera det", + "Choose one keyword to rename it": "Välj ett enda nyckelord för att byta namn på det", + "Create Keyword Tag Inside…": "Skapa nyckelordstagg i…", + "Delete Albums": "Radera album", + "Delete Folder": "Radera mapp", + "Delete Keywords": "Radera nyckelord", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Flyttar de foton som importerats från de här mapparna till Nyligen raderade; inga filer berörs", + "No photo has them; the keywords below them go too.": "Inget foto har dem; nyckelorden under dem raderas också.", + "One of them is a whole disk: remove a disk by itself": "En av dem är en hel disk: ta bort en disk för sig", + "Remove Folders from Library": "Ta bort mappar från biblioteket", + "That includes the photos in the folders inside them.": "Det omfattar fotona i mapparna inuti dem.", + "The photos stay in All Photos. Undo brings the albums back.": "Fotona finns kvar i Alla foton. Ångra tar tillbaka albumen." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index a0870bd4eb8..950f5889b10 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", "{n} albums": "Альбоми: {n}", - "{n} folders": "Теки: {n}" + "{n} folders": "Теки: {n}", + "Export {n} Albums…": "Експортувати альбоми ({n})…", + "Move {n} Albums to": "Перемістити альбоми ({n}) до", + "Delete {n} Albums…": "Видалити альбоми ({n})…", + "Remove {n} Folders from Library…": "Вилучити теки ({n}) з бібліотеки…", + "Add {n} Keywords to Selected Photos": "Додати ключові слова ({n}) до вибраних фото", + "Remove {n} Keywords from Selected Photos": "Вилучити ключові слова ({n}) з вибраних фото", + "Show Photos with Any of {n} Keywords": "Показати фото з будь-яким із ключових слів ({n})", + "Merge {n} Keywords into…": "Об’єднати ключові слова ({n}) з…", + "Delete {n} Keywords…": "Видалити ключові слова ({n})…", + "Delete {n} albums?": "Видалити альбоми ({n})?", + "Delete {n} keywords?": "Видалити ключові слова ({n})?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Фото з одним із них: {count}. Вкладені ключові слова теж видаляються. Скасування поверне їх.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Вилучити теки ({n}) з бібліотеки? Імпортованих із них фото: {count}.", + "…and {n} more": "…і ще {n}", + "{n} keywords": "Ключові слова: {n}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09b78fab1e3..f32b316aec8 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2422,5 +2422,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", "Welcome": "Ласкаво просимо", "Next": "Далі", - "Get Started": "Почати" + "Get Started": "Почати", + "Choose one album to rename it": "Виберіть лише один альбом, щоб перейменувати його", + "Choose one folder to rename it": "Виберіть лише одну теку, щоб перейменувати її", + "Choose one folder to synchronize it": "Виберіть лише одну теку, щоб синхронізувати її", + "Choose one keyword to create a keyword inside it": "Виберіть лише одне ключове слово, щоб створити ключове слово всередині нього", + "Choose one keyword to edit it": "Виберіть лише одне ключове слово, щоб редагувати його", + "Choose one keyword to rename it": "Виберіть лише одне ключове слово, щоб перейменувати його", + "Create Keyword Tag Inside…": "Створити ключове слово всередині…", + "Delete Albums": "Видалити альбоми", + "Delete Folder": "Видалити теку", + "Delete Keywords": "Видалити ключові слова", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Переміщує імпортовані з цих тек фото до нещодавно видалених; файли не змінюються", + "No photo has them; the keywords below them go too.": "Їх не має жодне фото; вкладені в них ключові слова теж зникнуть.", + "One of them is a whole disk: remove a disk by itself": "Одна з них — цілий диск: вилучайте диск окремо", + "Remove Folders from Library": "Вилучити теки з бібліотеки", + "That includes the photos in the folders inside them.": "Також включаються фото у вкладених у них теках.", + "The photos stay in All Photos. Undo brings the albums back.": "Фото залишаються в «Усіх фото». Скасування повертає альбоми.", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення папки видаляє й її альбоми. Це можна скасувати." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 81a956e5074..89629938403 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -324,5 +324,20 @@ "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", "{n} albums": "{n} album", - "{n} folders": "{n} thư mục" + "{n} folders": "{n} thư mục", + "Export {n} Albums…": "Xuất {n} album…", + "Move {n} Albums to": "Di chuyển {n} album đến", + "Delete {n} Albums…": "Xóa {n} album…", + "Remove {n} Folders from Library…": "Gỡ {n} thư mục khỏi thư viện…", + "Add {n} Keywords to Selected Photos": "Thêm {n} từ khóa vào ảnh đã chọn", + "Remove {n} Keywords from Selected Photos": "Gỡ {n} từ khóa khỏi ảnh đã chọn", + "Show Photos with Any of {n} Keywords": "Hiện ảnh có bất kỳ từ khóa nào trong {n} từ khóa", + "Merge {n} Keywords into…": "Ghép {n} từ khóa vào…", + "Delete {n} Keywords…": "Xóa {n} từ khóa…", + "Delete {n} albums?": "Xóa {n} album?", + "Delete {n} keywords?": "Xóa {n} từ khóa?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Số ảnh có một trong số đó: {count}. Các từ khóa bên dưới cũng bị xóa. Hoàn tác sẽ đưa chúng trở lại.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Gỡ {n} thư mục khỏi thư viện? Số ảnh đã nhập từ chúng: {count}.", + "…and {n} more": "…và {n} mục nữa", + "{n} keywords": "{n} từ khóa" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index af27e9aa0ab..d62e349ab98 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2711,5 +2711,21 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", - "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Choose one album to rename it": "Chọn một album để đổi tên", + "Choose one folder to rename it": "Chọn một thư mục để đổi tên", + "Choose one folder to synchronize it": "Chọn một thư mục để đồng bộ", + "Choose one keyword to create a keyword inside it": "Chọn một từ khóa để tạo từ khóa bên trong nó", + "Choose one keyword to edit it": "Chọn một từ khóa để sửa", + "Choose one keyword to rename it": "Chọn một từ khóa để đổi tên", + "Create Keyword Tag Inside…": "Tạo thẻ từ khóa bên trong…", + "Delete Albums": "Xóa album", + "Delete Folder": "Xóa thư mục", + "Delete Keywords": "Xóa từ khóa", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Chuyển các ảnh đã nhập từ những thư mục này vào Đã xóa gần đây; không tệp nào bị đụng đến", + "No photo has them; the keywords below them go too.": "Không ảnh nào có chúng; các từ khóa bên dưới cũng bị xóa.", + "One of them is a whole disk: remove a disk by itself": "Một trong số đó là cả một ổ đĩa: hãy gỡ ổ đĩa riêng", + "Remove Folders from Library": "Gỡ thư mục khỏi thư viện", + "That includes the photos in the folders inside them.": "Bao gồm cả ảnh trong các thư mục bên trong chúng.", + "The photos stay in All Photos. Undo brings the albums back.": "Ảnh vẫn ở trong Tất cả ảnh. Hoàn tác sẽ đưa album trở lại." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index a8d1ae73d34..9a6fffe7efb 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", "{n} albums": "{n} 个相册", - "{n} folders": "{n} 个文件夹" + "{n} folders": "{n} 个文件夹", + "Export {n} Albums…": "导出 {n} 个相册…", + "Move {n} Albums to": "将 {n} 个相册移动到", + "Delete {n} Albums…": "删除 {n} 个相册…", + "Remove {n} Folders from Library…": "从图库中移除 {n} 个文件夹…", + "Add {n} Keywords to Selected Photos": "将 {n} 个关键字添加到所选照片", + "Remove {n} Keywords from Selected Photos": "从所选照片中移除 {n} 个关键字", + "Show Photos with Any of {n} Keywords": "显示包含这 {n} 个关键字中任意一个的照片", + "Merge {n} Keywords into…": "将 {n} 个关键字合并到…", + "Delete {n} Keywords…": "删除 {n} 个关键字…", + "Delete {n} albums?": "要删除 {n} 个相册吗?", + "Delete {n} keywords?": "要删除 {n} 个关键字吗?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "包含其中任意一个的照片:{count} 张。其下的关键字也会被删除。撤销可恢复。", + "Remove {n} folders from the library? Photos imported from them: {count}.": "要从图库中移除 {n} 个文件夹吗?从中导入的照片:{count} 张。", + "…and {n} more": "…以及另外 {n} 个", + "{n} keywords": "{n} 个关键字" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ca13d782a5e..15f88dfcf15 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2425,5 +2425,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", "Welcome": "欢迎", "Next": "下一步", - "Get Started": "开始使用" + "Get Started": "开始使用", + "Choose one album to rename it": "请只选择一个相册以重命名", + "Choose one folder to rename it": "请只选择一个文件夹以重命名", + "Choose one folder to synchronize it": "请只选择一个文件夹以同步", + "Choose one keyword to create a keyword inside it": "请只选择一个关键字以在其中创建关键字", + "Choose one keyword to edit it": "请只选择一个关键字以编辑", + "Choose one keyword to rename it": "请只选择一个关键字以重命名", + "Create Keyword Tag Inside…": "在其中创建关键字标记…", + "Delete Albums": "删除相册", + "Delete Folder": "删除文件夹", + "Delete Keywords": "删除关键字", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "将从这些文件夹导入的照片移到“最近删除”;不会改动任何文件", + "No photo has them; the keywords below them go too.": "没有照片使用它们;其下的关键字也会一并删除。", + "One of them is a whole disk: remove a disk by itself": "其中一个是整个磁盘:请单独移除磁盘", + "Remove Folders from Library": "从图库中移除文件夹", + "That includes the photos in the folders inside them.": "其中也包括这些文件夹内各子文件夹中的照片。", + "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在“所有照片”中。撤销可恢复这些相册。", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在“所有照片”中。删除文件夹也会删除其中的相册。可以撤销。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 102e4a9ddaa..9e9d8b447a8 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -328,5 +328,20 @@ "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", "{n} albums": "{n} 個相簿", - "{n} folders": "{n} 個資料夾" + "{n} folders": "{n} 個資料夾", + "Export {n} Albums…": "匯出 {n} 個相簿…", + "Move {n} Albums to": "將 {n} 個相簿移至", + "Delete {n} Albums…": "刪除 {n} 個相簿…", + "Remove {n} Folders from Library…": "從照片庫移除 {n} 個資料夾…", + "Add {n} Keywords to Selected Photos": "將 {n} 個關鍵字加入選取的照片", + "Remove {n} Keywords from Selected Photos": "從選取的照片移除 {n} 個關鍵字", + "Show Photos with Any of {n} Keywords": "顯示含這 {n} 個關鍵字中任一個的照片", + "Merge {n} Keywords into…": "將 {n} 個關鍵字合併至…", + "Delete {n} Keywords…": "刪除 {n} 個關鍵字…", + "Delete {n} albums?": "要刪除 {n} 個相簿嗎?", + "Delete {n} keywords?": "要刪除 {n} 個關鍵字嗎?", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "含其中任一個的照片:{count} 張。其下的關鍵字也會被刪除。復原即可回復。", + "Remove {n} folders from the library? Photos imported from them: {count}.": "要從照片庫移除 {n} 個資料夾嗎?從中匯入的照片:{count} 張。", + "…and {n} more": "…以及另外 {n} 個", + "{n} keywords": "{n} 個關鍵字" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index f3dfc422ec3..eb9ab8d6f6c 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2426,5 +2426,22 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", "Welcome": "歡迎", "Next": "下一步", - "Get Started": "開始使用" + "Get Started": "開始使用", + "Choose one album to rename it": "請只選擇一個相簿以重新命名", + "Choose one folder to rename it": "請只選擇一個資料夾以重新命名", + "Choose one folder to synchronize it": "請只選擇一個資料夾以同步", + "Choose one keyword to create a keyword inside it": "請只選擇一個關鍵字以在其中建立關鍵字", + "Choose one keyword to edit it": "請只選擇一個關鍵字以編輯", + "Choose one keyword to rename it": "請只選擇一個關鍵字以重新命名", + "Create Keyword Tag Inside…": "在其中建立關鍵字標記…", + "Delete Albums": "刪除相簿", + "Delete Folder": "刪除資料夾", + "Delete Keywords": "刪除關鍵字", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "將從這些資料夾匯入的照片移至「最近刪除」;不會更動任何檔案", + "No photo has them; the keywords below them go too.": "沒有照片使用它們;其下的關鍵字也會一併刪除。", + "One of them is a whole disk: remove a disk by itself": "其中一個是整個磁碟:請單獨移除磁碟", + "Remove Folders from Library": "從照片庫移除資料夾", + "That includes the photos in the folders inside them.": "其中也包括這些資料夾內各子資料夾中的照片。", + "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在「所有照片」中。復原即可還原這些相簿。", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在「所有照片」中。刪除資料夾也會刪除其中的相簿。可以復原。" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2b08fc7893c..01295317a28 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -221,6 +221,15 @@ impl LightcraftApp { } } + /// [`Self::act`] for a caller that hands the refusal on (a dialog's confirm, which the control + /// channel answers with it): the toast says the reason, the `Err` is the whole error. + pub(crate) fn act_told(&mut self, id: &str, params: Value) -> Result { + self.run_told(id, params).map_err(|refusal| { + self.ui.toast = Some((refusal.why, self.tick_now() + REFUSAL_SECONDS, None)); + refusal.error + }) + } + /// [`Self::run`], keeping what a refusal says to a person apart from the whole error. fn run_told(&mut self, id: &str, params: Value) -> Result { if let Some(r) = menus::run_ui_command(self, id, ¶ms) { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index baef834beda..7711f9b0a6c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -290,7 +290,7 @@ impl LightcraftApp { // Recent-library checks and launch-list keys read focus/time/keys: they belong to the UI // phase, not the hidden-capable `logic` tick (plan §4.5 / migration input contract). panels::library_problem::logic(self, ctx); - panels::side_select::frame(self); + panels::side_select::keys_frame(self, ctx); if self.fonts_ready && !updates_ui::blocks_input(self) { shortcuts::handle(self, ctx); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cb5ca33df99..abce1f21272 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -448,6 +448,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String { Dialog::RenamePerson { .. } => "Rename Person", Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag", Dialog::KeywordTag { .. } => "Edit Keyword Tag", + Dialog::Several(s) => crate::panels::side_select::several_title(s), Dialog::DeleteKeyword { .. } => "Delete Keyword", Dialog::MoveKeyword { .. } => "Merge Keywords", Dialog::KeywordSet { .. } => "Edit Keyword Set", @@ -579,6 +580,7 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download", Dialog::FaceModel { .. } if !informational => "Install", Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } => "Delete", + Dialog::Several(s) => crate::panels::side_select::several_button(s), Dialog::SaveEffect { .. } | Dialog::NewAlbum { .. } | Dialog::NewSmartAlbum { .. } @@ -737,6 +739,9 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> { app.toast(ctx, e) } + // several rows: one that can't be deleted or removed refuses them all; `several_run` + // already toasted the reason, which says which + Err(_) if matches!(dlg, Dialog::Several(_)) => {} // the SAM 3 dialog stays open to show the download (or why it can't start) Err(e) if matches!(dlg, Dialog::SamModel { .. }) => { if let Dialog::SamModel { error, .. } = dlg { @@ -2138,6 +2143,7 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m Dialog::KeywordTag { .. } => keyword_tag_body(app, ui, t, confirm, dlg), Dialog::KeywordSet { .. } => keyword_set_body(ui, t, confirm, dlg), Dialog::MoveKeyword { .. } => move_keyword_body(ui, t, dlg), + Dialog::Several(s) => crate::panels::side_select::several_body(ui, s, &app.session.catalog), Dialog::DeleteKeyword { .. } => delete_keyword_body(ui, t, dlg), Dialog::SaveEffect { name, group, fields, amount, brush } => { if crate::panels::mask_effects::save_body(app, ui, name, group, fields, amount, brush) { diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 64051c27949..b705d34b61e 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -144,6 +144,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::side_select::several_run(app, s), Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})), Dialog::KeywordSet { replaces, name, slots, as_new } => { use lightcraft_catalog::keywords::same; diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rs index d6e8ea8120e..dce36a03c25 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -189,7 +189,9 @@ pub enum ConfirmStyle { pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle { match dlg { - Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } => { + Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } + // (every several-rows action deletes or removes) + | Dialog::Several(_) => { ConfirmStyle::Plain } _ if only_shows(dlg) => ConfirmStyle::Plain, diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 19c0a440db7..142561ada37 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -56,13 +56,17 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if plus.clicked() { app.ui.dialog = Some(create_dialog(app)); } - let picked = app.ui.keyword_list_selected.clone().filter(|k| in_tree(&app.caches.keyword_tree(&app.session.catalog), k)); - let minus = ui.add_enabled(picked.is_some(), egui::Button::new("−")).on_hover_text(crate::i18n::tr("Delete Keyword")); + let tree = app.caches.keyword_tree(&app.session.catalog); + let picked: Vec = super::side_select::list_picked(app).into_iter().filter(|k| in_tree(&tree, k)).collect(); + let minus = ui.add_enabled(!picked.is_empty(), egui::Button::new("−")).on_hover_text(crate::i18n::tr("Delete Keyword")); register(ui, "keywordList:delete", minus.rect); - if minus.clicked() - && let Some(k) = picked - { - app.ui.dialog = Some(delete_dialog(app, &k)); + if minus.clicked() { + // several picked: they all go, after one question + app.ui.dialog = match picked.as_slice() { + [] => None, + [one] => Some(delete_dialog(app, one)), + many => Some(super::side_select::delete_keywords_dialog(app, many)), + }; } }); ui.data_mut(|d| d.insert_temp(fid, filter.clone())); @@ -136,7 +140,10 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(at) = at else { return }; let t = Tokens::get(ctx); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); - let name = keyword.rsplit('|').next().unwrap_or(&keyword).to_string(); + // picked up as one of several keywords picked: they all go + let several = super::side_select::list_targets(app, &keyword).len(); + let name = + if several > 1 { crate::i18n::tr_format!("{n} keywords", n = several) } else { keyword.rsplit('|').next().unwrap_or(&keyword).to_string() }; egui::Area::new(egui::Id::unique("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( ctx, |ui| { @@ -151,6 +158,11 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { /// already, ask before merging the two; where it is already, nothing happens. fn drop_keyword(app: &mut LightcraftApp, ctx: &egui::Context, keyword: &str, parent: Option<&str>) { app.ui.dragging_keyword = None; + // picked up as one of several keywords picked: they all go, as one step + let several = super::side_select::list_targets(app, keyword); + if several.len() > 1 { + return drop_keywords(app, &several, parent); + } let cat = &app.session.catalog; let leaf = keyword.rsplit('|').next().unwrap_or(keyword); let parent = parent.map(|p| cat.keyword_path(p).unwrap_or_else(|| p.to_string())); @@ -171,6 +183,28 @@ fn drop_keyword(app: &mut LightcraftApp, ctx: &egui::Context, keyword: &str, par } } +/// Drop several keywords inside `parent` (`None`: the top level), as one undo step. Nothing +/// merges here: where one of their names is taken the move is refused, and says so. +fn drop_keywords(app: &mut LightcraftApp, keywords: &[String], parent: Option<&str>) { + let cat = &app.session.catalog; + let parent = parent.map(|p| cat.keyword_path(p).unwrap_or_else(|| p.to_string())); + // dropped on one of themselves, or on something inside one: nothing to do + if parent.as_deref().is_some_and(|p| keywords.iter().any(|k| lightcraft_catalog::keywords::is_under(p, k))) { + return; + } + if app.act("keyword.move", json!({"keywords": keywords, "parent": parent})).is_none() { + return; + } + // the upper ones moved, and what is below them with them + let upper: Vec<&String> = + keywords.iter().filter(|k| !keywords.iter().any(|o| !same(o, k) && lightcraft_catalog::keywords::is_under(k, o))).collect(); + for k in upper { + let leaf = k.rsplit('|').next().unwrap_or(k); + let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}|{leaf}")); + follow(app, k, &to); + } +} + /// One keyword's row: the triangle, the tick box, the name, the count, and on hover the arrow. /// `can_fold`: the triangle opens and closes the level (not while a filter opens it). fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId], ticks: &Ticks, can_fold: bool) { @@ -187,6 +221,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId if picked { ui.painter().rect_filled(inner, 4.0, t.canvas); register(ui, format!("keywordPicked:{}", r.path), inner); + super::side_select::outline(app, ui, super::side_select::SideList::KeywordList, true, rect, 16.0); } else if resp.hovered() { ui.painter().rect_filled(inner, 4.0, t.hover.gamma_multiply(0.6)); } @@ -374,6 +409,11 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, path: &st /// A keyword's context menu. fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[PhotoId]) { + // one of several keywords picked: what can be done to them all + let several = super::side_select::list_targets(app, path); + if several.len() > 1 { + return super::side_select::keywords_menu(app, ui, &several, true); + } let name = path.replace('|', " › "); let item = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool| { let r = ui.add_enabled(enabled, egui::Button::new(label)); diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index d1e14ed07ef..243df560151 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -80,6 +80,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare .indent(indent) .sense(Sense::click_and_drag()) .show(app, ui); + crate::panels::side_select::outline(app, ui, crate::panels::side_select::SideList::Albums, sel, resp.rect, 8.0); if !problems.is_empty() { crate::widgets::register(ui, format!("albumProblem:{}", a.id.0), resp.rect); } @@ -214,14 +215,29 @@ fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { /// Moves the dragged album into a folder (`album.move`, one undo step; `None`: the top level). fn drop_album(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, target: Option) { - let r = app.run("album.move", json!({"id": dragged.0, "parent": target.map(|t| t.0)})); + // picked up as one of several albums chosen: they all go, as one step + let several = crate::panels::side_select::albums_dragged(app, dragged); + let r = if several.len() > 1 { + app.run("album.move", json!({"ids": several, "parent": target.map(|t| t.0)})) + } else { + app.run("album.move", json!({"id": dragged.0, "parent": target.map(|t| t.0)})) + }; finish_drop(app, ui, dragged, r); } /// Places the dragged album in `parent` before the sibling `before` (`None`: last of its kind), by /// hand (`album.reorder`, one undo step). fn place_album(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, parent: Option, before: Option) { - let r = app.run("album.reorder", json!({"id": dragged.0, "parent": parent.map(|p| p.0), "before": before.map(|b| b.0)})); + // picked up as one of several albums chosen: they all go into that folder (one step); a + // place by hand is one album's + let several = crate::panels::side_select::albums_dragged(app, dragged); + // (all of them there already: nothing to move, and the one dragged is placed) + let there = several.iter().all(|id| app.session.catalog.album(AlbumId(*id)).is_some_and(|a| a.parent == parent)); + let r = if several.len() > 1 && !there { + app.run("album.move", json!({"ids": several, "parent": parent.map(|p| p.0)})) + } else { + app.run("album.reorder", json!({"id": dragged.0, "parent": parent.map(|p| p.0), "before": before.map(|b| b.0)})) + }; finish_drop(app, ui, dragged, r); } @@ -362,6 +378,9 @@ pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { return; } let (Some(pos), Some(name)) = (pos, app.session.catalog.album(AlbumId(id)).map(|a| a.name.clone())) else { return }; + // picked up as one of several albums chosen: they all go + let several = crate::panels::side_select::albums_dragged(app, AlbumId(id)).len(); + let name = if several > 1 { crate::i18n::tr_format!("{n} albums", n = several) } else { name }; let t = Tokens::get(ctx); ctx.set_cursor_icon(egui::CursorIcon::Grabbing); egui::Area::new(egui::Id::unique("drag-album")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show( diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 6279e416491..34bebadf979 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -104,6 +104,11 @@ pub(super) fn folder_tree( pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { crate::widgets::context_menu(resp, |ui| { + // one of several albums chosen: what can be done to them all + let several = crate::panels::side_select::album_targets(app, a.id); + if several.len() > 1 { + return crate::panels::side_select::albums_menu(app, ui, &several); + } if a.folder { // the same commands as File ▸ New…, aimed at this folder crate::widgets::menu_button(ui, crate::i18n::tr("New"), |ui| { @@ -319,13 +324,14 @@ pub(super) fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[F let leads_on = n.own == 0 && n.children.len() == 1; let mut open = tree_open(ui, open_id, n.volume || leads_on); // a row whose path would cover other disks' photos too only opens and closes + let sel = n.selectable && crate::panels::side_select::folder_shown(app, &n.path); if n.selectable { app.ui.side.folders.saw(n.path.clone()); } let name = if n.selectable { n.name.clone() } else { crate::i18n::tr("This Computer").to_string() }; let id = format!("libfolder:{}", n.path); if !out_of_sight(app, ui, &id, &name, Some(n.count), indent, n.label.is_some()) { - folder_row(app, ui, n, &id, &name, indent, open_id, &mut open); + folder_row(app, ui, n, &id, &name, indent, open_id, &mut open, sel); } if open && !n.children.is_empty() { folder_rows(app, ui, &n.children, indent + INDENT_STEP); @@ -335,8 +341,17 @@ pub(super) fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[F /// One drawn row of [`folder_rows`], shown as `name`; `open_id` and `open` are its triangle's. #[allow(clippy::too_many_arguments)] -fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &str, name: &str, indent: f32, open_id: egui::Id, open: &mut bool) { - let sel = n.selectable && crate::panels::side_select::folder_shown(app, &n.path); +fn folder_row( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + n: &FolderNode, + id: &str, + name: &str, + indent: f32, + open_id: egui::Id, + open: &mut bool, + sel: bool, +) { // the label is said with the name, as it is shown beside it let spoken = match n.label { Some(l) => format!("{name}, {}", crate::i18n::color_label(&app.session.catalog, l)), @@ -345,6 +360,7 @@ fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &s let mark = n.label.map(crate::theme::label_color); let resp = Row::new(id, Icon::Folder, name).spoken(&spoken).count(Some(n.count)).selected(sel).indent(indent).mark(mark).show(app, ui); folder_drop_target(app, ui, &resp, n, open_id, open); + crate::panels::side_select::outline(app, ui, crate::panels::side_select::SideList::Folders, sel, resp.rect, 8.0); let mut toggled = false; if !n.children.is_empty() { let tr = tree_toggle(ui, &resp, indent, open_id, open, format!("libraryFolderToggle:{}", n.path), name); @@ -505,6 +521,12 @@ fn move_photos_here(app: &mut LightcraftApp, ctx: &egui::Context, ids: Option<&[ /// The context menu of a Folders row: a folder's own, a disk's (remove it), none for the /// startup disk. fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) { + // one of several folders chosen: what can be done to them all + let several = crate::panels::side_select::folder_targets(app, &n.path); + if several.len() > 1 { + crate::widgets::context_menu(resp, |ui| crate::panels::side_select::folders_menu(app, ui, &several)); + return; + } if !n.volume { folder_menu_for_library(app, resp, n); } else if n.path != "/" { diff --git a/crates/ui-egui/src/panels/left/keywords.rs b/crates/ui-egui/src/panels/left/keywords.rs index 2e732b18f4e..4c9e7c7bf78 100644 --- a/crates/ui-egui/src/panels/left/keywords.rs +++ b/crates/ui-egui/src/panels/left/keywords.rs @@ -10,9 +10,10 @@ pub(super) fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[ let open_id = (!n.children.is_empty()).then(|| egui::Id::unique(("kw-open", n.path.to_lowercase()))); let mut open = open_id.is_some_and(|k| tree_open(ui, k, false)); let id = format!("keyword:{}", n.path); + let sel = crate::panels::side_select::keyword_shown(app, &n.path); app.ui.side.keywords.saw(n.path.clone()); if !out_of_sight(app, ui, &id, &n.name, Some(n.count), indent, false) { - keyword_row(app, ui, n, &id, indent, open_id, &mut open); + keyword_row(app, ui, n, &id, indent, open_id, &mut open, sel); } if open { keyword_rows(app, ui, &n.children, indent + INDENT_STEP); @@ -21,9 +22,19 @@ pub(super) fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[ } /// One drawn row of [`keyword_rows`]; `open_id` and `open` are its triangle's when it has rows inside it. -fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: &str, indent: f32, open_id: Option, open: &mut bool) { - let sel = crate::panels::side_select::keyword_shown(app, &n.path); +#[allow(clippy::too_many_arguments)] +fn keyword_row( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + n: &KeywordNode, + id: &str, + indent: f32, + open_id: Option, + open: &mut bool, + sel: bool, +) { let resp = Row::new(id, Icon::Tag, &n.name).count(Some(n.count)).selected(sel).indent(indent).show(app, ui); + crate::panels::side_select::outline(app, ui, crate::panels::side_select::SideList::Keywords, sel, resp.rect, 8.0); if let Some(k) = open_id { tree_toggle(ui, &resp, indent, k, open, format!("keywordToggle:{}", n.path), &n.name); } @@ -32,6 +43,11 @@ fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: crate::panels::side_select::keyword_clicked(app, ui, &n.path); } crate::widgets::context_menu(&resp, |ui| { + // one of several keywords chosen: what can be done to them all + let several = crate::panels::side_select::keyword_targets(app, &n.path); + if several.len() > 1 { + return crate::panels::side_select::keywords_menu(app, ui, &several, false); + } let has_sel = app.session.active().is_some(); if ui.add_enabled(has_sel, egui::Button::new(crate::i18n::tr("Add to Selected Photos"))).clicked() { let _ = app.run("photo.setMeta", json!({"addKeywords": [n.path]})); diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs index b0a7962d11e..1d54044cb70 100644 --- a/crates/ui-egui/src/panels/side_select.rs +++ b/crates/ui-egui/src/panels/side_select.rs @@ -1,6 +1,7 @@ //! Several rows of a sidebar list chosen at once (Cmd/Ctrl+click, Shift+click): what the left //! panel's Albums, Folders, Keywords and By Date and the right panel's Keyword List do with the -//! click. The rule for the click itself is [`crate::multi_select`]'s. +//! click, and the context menu and the confirmations for several rows. The rule for the click +//! itself is [`crate::multi_select`]'s. //! //! What is chosen in a list of the left panel is what the grid shows, so it lives in the session //! (`library.source`, `library.filter`); only the anchor for Shift+click is kept here. The @@ -14,11 +15,28 @@ use lightcraft_engine::LibrarySource; use serde_json::json; use crate::LightcraftApp; -use crate::multi_select::{Click, ListRows}; +use crate::multi_select::{Click, ListRows, targets}; +use crate::state::Dialog; +use crate::widgets::register; + +/// A sidebar list in which several rows can be chosen and then deleted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SideList { + Albums, + Folders, + Keywords, + KeywordList, +} /// What the sidebars keep for choosing several rows. #[derive(Clone, Debug, Default)] pub struct SideState { + /// The list the Delete key acts on: the one in which several rows were just chosen with + /// Cmd/Ctrl or Shift, until the next click anywhere. A plain click never sets it, so after + /// choosing an album the usual way the keys stay with the photos. + pub keys: Option, + /// What the key was taken over ([`keys_mark`]): any change to it gives the key back. + keys_at: u64, /// The library all of this is about (its generation): another library starts afresh. library: Option, /// The catalog revision the Keyword List's picks were last checked against. @@ -33,6 +51,17 @@ pub struct SideState { pub keyword_list_also: Vec, } +/// A confirmation before something happens to several rows at once. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum Several { + /// Delete several albums. + DeleteAlbums { ids: Vec }, + /// Delete keywords from every photo and the keyword list; `count` photos have one of them. + DeleteKeywords { keywords: Vec, count: usize }, + /// Remove folders from the library; `count` photos were imported from them. + RemoveFolders { paths: Vec, count: usize }, +} + fn same_id(a: &u64, b: &u64) -> bool { a == b } @@ -54,15 +83,41 @@ fn how(ui: &egui::Ui) -> Click { Click::of(ui.input(|i| i.modifiers)) } -/// Each frame, before the panels: a library that was switched forgets everything kept here (its -/// rows are another library's), and a keyword picked in the Keyword List that is gone is let go. -pub(crate) fn frame(app: &mut LightcraftApp) { +/// After a click in `list` that left `chosen` rows chosen: it takes the Delete key when several +/// were chosen with Cmd/Ctrl or Shift. +fn take_keys(app: &mut LightcraftApp, list: SideList, how: Click, chosen: usize) { + app.ui.side.keys = (how != Click::Plain && chosen > 1).then_some(list); + app.ui.side.keys_at = keys_mark(app); +} + +/// What the Delete key was taken over: what is shown, chosen and selected, and where. When any of +/// it changes (a key, a menu, an agent), the key is the photos' again. +fn keys_mark(app: &LightcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let (s, ui) = (&app.session, &app.ui); + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}|{:?}|{:?}|{:?}", s.source, s.library_folder, ui.view, ui.right).hash(&mut h); + (&s.also_albums, &s.also_library_folders, &s.filter.keyword, &s.filter.keywords).hash(&mut h); + // (the selection by its size and ends: it can be every photo of a large library, each frame) + (s.selection.ids.len(), s.selection.ids.first(), s.selection.ids.last(), s.selection.active).hash(&mut h); + (&ui.keyword_list_selected, &ui.side.keyword_list_also, ui.left_panel, s.library_generation()).hash(&mut h); + h.finish() +} + +/// Each frame, before the panels and the shortcuts: a press anywhere, or any change to what the +/// key was taken over, gives the keys back to the photos (a Cmd/Shift+click in a list takes them +/// again when it is released). A library that was switched forgets everything kept here: its +/// rows are another library's. +pub(crate) fn keys_frame(app: &mut LightcraftApp, ctx: &egui::Context) { let library = app.session.library_generation(); if app.ui.side.library != Some(library) { app.ui.side = SideState { library: Some(library), ..Default::default() }; // (a keyword picked here is another library's: it may have one by the same name) app.ui.keyword_list_selected = None; } + if app.ui.side.keys.is_some() && (ctx.input(|i| i.pointer.any_pressed()) || app.ui.side.keys_at != keys_mark(app)) { + app.ui.side.keys = None; + } // a keyword picked in the Keyword List that is gone since (deleted, merged away, undone) is // not picked any more. Looked up in the cached keyword tree, once per change to the library // and while keywords are picked: never a pass over the photos per frame. @@ -78,6 +133,57 @@ pub(crate) fn frame(app: &mut LightcraftApp) { app.ui.side.picks_at = revision; } +/// Delete (the photos' delete shortcut, whatever key it is on), when a sidebar list has the key +/// ([`SideState::keys`]): asks before deleting (or removing from the library) the rows chosen +/// there. Returns whether it was about those rows; `false` leaves it to the photos. +pub(crate) fn delete_asked(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { + let Some(list) = app.ui.side.keys else { return false }; + let dialog = match list { + SideList::Albums => Some(albums_shown(app)).filter(|ids| ids.len() > 1).map(|ids| delete_albums_dialog(&ids)), + SideList::Keywords => Some(app.session.filter.keywords_wanted()).filter(|k| k.len() > 1).map(|k| delete_keywords_dialog(app, &k)), + SideList::KeywordList => Some(list_picked(app)).filter(|k| k.len() > 1).map(|k| delete_keywords_dialog(app, &k)), + SideList::Folders => { + let paths = app.session.source_library_folders(); + if paths.len() > 1 && paths.iter().any(|p| lightcraft_catalog::folders::is_disk_root(p)) { + app.toast(ctx, crate::i18n::tr("One of them is a whole disk: remove a disk by itself").to_string()); + return true; + } + Some(paths).filter(|p| p.len() > 1).map(|p| remove_folders_dialog(app, &p)) + } + }; + match dialog { + Some(d) => { + app.ui.dialog = Some(d); + true + } + // what was chosen is not there any more: the key is the photos' again, this press too + None => { + app.ui.side.keys = None; + false + } + } +} + +/// Whether the rows chosen in `list` are what the Delete key acts on now (they are outlined). +pub(crate) fn has_keys(app: &LightcraftApp, list: SideList) -> bool { + app.ui.side.keys == Some(list) +} + +/// Outline a chosen row of the list that has the Delete key. +pub(crate) fn outline(app: &LightcraftApp, ui: &egui::Ui, list: SideList, chosen: bool, row: egui::Rect, inset: f32) { + if chosen && has_keys(app, list) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_stroke(row.shrink2(egui::vec2(inset, 1.0)), 4.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } +} + +/// The confirmation for removing several folders from the library. +fn remove_folders_dialog(app: &LightcraftApp, paths: &[String]) -> Dialog { + let f = lightcraft_catalog::Filter { library_folders: paths.to_vec(), ..Default::default() }; + let count = app.session.catalog.query(&f, &lightcraft_catalog::Sort::default()).len(); + Dialog::Several(Several::RemoveFolders { paths: paths.to_vec(), count }) +} + /// A new frame of the left panel: the rows of the last one are what a click now is on. pub(crate) fn begin_left(app: &mut LightcraftApp) { let s = &mut app.ui.side; @@ -105,6 +211,7 @@ pub(crate) fn album_clicked(app: &mut LightcraftApp, ui: &egui::Ui, id: AlbumId) let how = how(ui); let keys = app.ui.side.albums.click(&chosen, &id.0, how, &same_id); show_albums(app, &keys); + take_keys(app, SideList::Albums, how, albums_shown(app).len()); } /// Show these albums (none: All Photos). @@ -116,6 +223,89 @@ fn show_albums(app: &mut LightcraftApp, ids: &[u64]) { }; } +/// The albums a context menu opened on album `id` acts on: those shown when it is one of +/// several, else itself. +pub(crate) fn album_targets(app: &LightcraftApp, id: AlbumId) -> Vec { + targets(&albums_shown(app), &id.0, &same_id) +} + +/// The albums a drag that picked up album `id` moves: those shown when it is one of several. +pub(crate) fn albums_dragged(app: &LightcraftApp, id: AlbumId) -> Vec { + album_targets(app, id) +} + +/// A menu item that is there but can't be used with several rows chosen, saying why. +fn single_only(ui: &mut egui::Ui, label: &str, why: &str) { + ui.add_enabled(false, egui::Button::new(crate::i18n::tr(label))).on_disabled_hover_text(crate::i18n::tr(why)); +} + +/// A menu item of a several-rows menu, registered as `sideMenu:` for the control channel. +fn item(ui: &mut egui::Ui, id: &str, label: String, enabled: bool) -> egui::Response { + let r = ui.add_enabled(enabled, egui::Button::new(label)); + register(ui, format!("sideMenu:{id}"), r.rect); + r +} + +/// The context menu for several albums chosen at once. +pub(crate) fn albums_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, ids: &[u64]) { + let n = ids.len(); + let cat = &app.session.catalog; + let chosen: Vec = ids.iter().map(|i| AlbumId(*i)).collect(); + // show them all, select their photos, then the dialog + let has_photos = chosen.iter().any(|a| cat.album_count(*a) > 0); + if item(ui, "albums:export", crate::i18n::tr_format!("Export {n} Albums…", n = n), has_photos).clicked() { + show_albums(app, ids); + app.act("library.selectAll", json!({})); + app.act("dialog.export", json!({})); + ui.close(); + } + ui.separator(); + // into a folder that is none of them, nor inside one of them + let cat = &app.session.catalog; + let inside_chosen = |mut id: AlbumId| { + for _ in 0..=cat.albums().count() { + if chosen.contains(&id) { + return true; + } + match cat.album(id).and_then(|a| a.parent) { + Some(p) => id = p, + None => break, + } + } + false + }; + // …nor where they all are + let all_in = |folder: AlbumId| chosen.iter().all(|a| cat.album(*a).is_some_and(|a| a.parent == Some(folder))); + let mut folders: Vec<(u64, String)> = + cat.albums().filter(|f| f.folder && !inside_chosen(f.id) && !all_in(f.id)).map(|f| (f.id.0, f.name.clone())).collect(); + folders.sort_by_key(|(_, name)| name.to_lowercase()); + let any_nested = chosen.iter().any(|a| cat.album(*a).is_some_and(|a| a.parent.is_some())); + ui.menu_button(crate::i18n::tr_format!("Move {n} Albums to", n = n), |ui| { + if item(ui, "albums:moveTop", crate::i18n::tr("Top Level").to_string(), any_nested).clicked() { + app.act("album.move", json!({"ids": ids, "parent": null})); + ui.close(); + } + for (folder, name) in &folders { + if ui.button(name).clicked() { + app.act("album.move", json!({"ids": ids, "parent": folder})); + ui.close(); + } + } + }); + single_only(ui, "Rename…", "Choose one album to rename it"); + let delete = item(ui, "albums:delete", crate::i18n::tr_format!("Delete {n} Albums…", n = n), true) + .on_hover_text(crate::i18n::tr("The photos stay in All Photos. Undo brings the albums back.")); + if delete.clicked() { + app.ui.dialog = Some(delete_albums_dialog(ids)); + ui.close(); + } +} + +/// The confirmation for deleting several albums. +pub(crate) fn delete_albums_dialog(ids: &[u64]) -> Dialog { + Dialog::Several(Several::DeleteAlbums { ids: ids.to_vec() }) +} + // ---- Folders (of the library) /// Whether the library folder `path` is one the grid shows the photos of. @@ -136,6 +326,44 @@ pub(crate) fn folder_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str) [one] => app.act("library.source", json!({"kind": "libraryFolder", "path": one})), many => app.act("library.source", json!({"kind": "libraryFolder", "paths": many})), }; + take_keys(app, SideList::Folders, how, app.session.source_library_folders().len()); +} + +/// The folders a context menu opened on folder `path` acts on. +pub(crate) fn folder_targets(app: &LightcraftApp, path: &str) -> Vec { + targets(&app.session.source_library_folders(), &path.to_string(), &same_dir) +} + +/// The context menu for several library folders chosen at once. +pub(crate) fn folders_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, paths: &[String]) { + use lightcraft_catalog::ColorLabel; + let n = paths.len(); + ui.menu_button(crate::i18n::tr("Color Label"), |ui| { + for l in ColorLabel::ALL { + let name = crate::i18n::color_label(&app.session.catalog, l); + if ui.button(name).clicked() { + app.act("folder.label", json!({"paths": paths, "label": format!("{l:?}").to_lowercase()})); + ui.close(); + } + } + ui.separator(); + if ui.button(crate::i18n::tr("None")).clicked() { + app.act("folder.label", json!({"paths": paths, "label": "none"})); + ui.close(); + } + }); + single_only(ui, "Synchronize Folder…", "Choose one folder to synchronize it"); + single_only(ui, "Rename Folder…", "Choose one folder to rename it"); + ui.separator(); + // a whole disk goes by itself, after its own question + let disk = paths.iter().any(|p| lightcraft_catalog::folders::is_disk_root(p)); + let remove = item(ui, "folders:remove", crate::i18n::tr_format!("Remove {n} Folders from Library…", n = n), !disk) + .on_hover_text(crate::i18n::tr("Moves the photos imported from these folders to Recently Deleted; no file is touched")) + .on_disabled_hover_text(crate::i18n::tr("One of them is a whole disk: remove a disk by itself")); + if remove.clicked() { + app.ui.dialog = Some(remove_folders_dialog(app, paths)); + ui.close(); + } } // ---- Keywords and By Date (filters) @@ -166,6 +394,12 @@ pub(crate) fn keyword_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str [one] => app.act("library.filter", json!({"keyword": one, "keywords": []})), many => app.act("library.filter", json!({"keyword": null, "keywords": many})), }; + take_keys(app, SideList::Keywords, how, app.session.filter.keywords_wanted().len()); +} + +/// The keywords a context menu opened on the Keywords row `path` acts on. +pub(crate) fn keyword_targets(app: &LightcraftApp, path: &str) -> Vec { + targets(&app.session.filter.keywords_wanted(), &path.to_string(), &same_kw) } /// Whether the By Date row `key` is one the grid is filtered by. @@ -193,12 +427,58 @@ pub(crate) fn date_clicked(app: &mut LightcraftApp, ui: &egui::Ui, key: &str) { }; } +/// The context menu for several keywords chosen at once, in the left panel's Keywords or in the +/// Keyword List (`list`: its items that need one keyword are shown, greyed out). +pub(crate) fn keywords_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, keywords: &[String], list: bool) { + let n = keywords.len(); + if list { + single_only(ui, "Create Keyword Tag Inside…", "Choose one keyword to create a keyword inside it"); + single_only(ui, "Edit Keyword Tag…", "Choose one keyword to edit it"); + ui.separator(); + } + let has_sel = app.session.active().is_some(); + if item(ui, "keywords:add", crate::i18n::tr_format!("Add {n} Keywords to Selected Photos", n = n), has_sel).clicked() { + app.act("photo.setMeta", json!({"addKeywords": keywords})); + ui.close(); + } + if item(ui, "keywords:remove", crate::i18n::tr_format!("Remove {n} Keywords from Selected Photos", n = n), has_sel).clicked() { + app.act("photo.setMeta", json!({"removeKeywords": keywords})); + ui.close(); + } + if list && item(ui, "keywords:show", crate::i18n::tr_format!("Show Photos with Any of {n} Keywords", n = n), true).clicked() { + super::left::browse_all_photos(app, true); + app.act("library.filter", json!({"keyword": null, "keywords": keywords})); + ui.close(); + } + ui.separator(); + if !list { + single_only(ui, "Rename Keyword…", "Choose one keyword to rename it"); + } + if item(ui, "keywords:merge", crate::i18n::tr_format!("Merge {n} Keywords into…", n = n), true).clicked() { + app.ui.dialog = Some(Dialog::MergeKeywords { from: keywords.to_vec(), into: String::new() }); + ui.close(); + } + if item(ui, "keywords:delete", crate::i18n::tr_format!("Delete {n} Keywords…", n = n), true).clicked() { + app.ui.dialog = Some(delete_keywords_dialog(app, keywords)); + ui.close(); + } +} + +/// The confirmation for deleting several keywords, saying how many photos have one of them. +pub(crate) fn delete_keywords_dialog(app: &LightcraftApp, keywords: &[String]) -> Dialog { + let cat = &app.session.catalog; + let paths: Vec = keywords.iter().map(|k| cat.keyword_path(k).unwrap_or_else(|| k.clone())).collect(); + let has = |p: &lightcraft_catalog::Photo| p.meta.keywords.iter().any(|k| paths.iter().any(|g| lightcraft_catalog::keywords::is_under(k, g))); + let count = cat.photos().filter(|p| p.in_library() && has(p)).count(); + Dialog::Several(Several::DeleteKeywords { keywords: paths, count }) +} + // ---- The Keyword List (right panel) /// The keywords picked in the Keyword List, in the order picked (the last is the one Edit takes). pub(crate) fn list_picked(app: &LightcraftApp) -> Vec { let mut out: Vec = Vec::new(); - // (those that are gone, deleted or merged away, were let go of by `frame`) + // (those that are gone, deleted or merged away, were let go of by `keys_frame`) for k in app.ui.side.keyword_list_also.iter().chain(&app.ui.keyword_list_selected) { if !out.iter().any(|o| same_keyword(o, k)) { out.push(k.clone()); @@ -223,5 +503,102 @@ pub(crate) fn list_clicked(app: &mut LightcraftApp, ui: &egui::Ui, path: &str) { let chosen = list_picked(app); let how = how(ui); let keys = app.ui.side.keyword_list.click(&chosen, &path.to_string(), how, &same_kw); + let chosen = keys.len(); list_pick(app, keys); + take_keys(app, SideList::KeywordList, how, chosen); +} + +/// The keywords a context menu opened on the Keyword List's row `path` acts on, or a drag that +/// picked that row up moves. +pub(crate) fn list_targets(app: &LightcraftApp, path: &str) -> Vec { + targets(&list_picked(app), &path.to_string(), &same_kw) +} + +// ---- The confirmations + +pub(crate) fn several_title(s: &Several) -> &'static str { + match s { + Several::DeleteAlbums { .. } => "Delete Albums", + Several::DeleteKeywords { .. } => "Delete Keywords", + Several::RemoveFolders { .. } => "Remove Folders from Library", + } +} + +pub(crate) fn several_button(s: &Several) -> &'static str { + match s { + Several::DeleteAlbums { .. } | Several::DeleteKeywords { .. } => "Delete", + Several::RemoveFolders { .. } => "Remove", + } +} + +/// What the confirmation says: what goes, and what stays. +pub(crate) fn several_body(ui: &mut egui::Ui, s: &Several, cat: &lightcraft_catalog::Catalog) { + let t = crate::theme::Tokens::get(ui.ctx()); + let dim = |ui: &mut egui::Ui, text: String| { + ui.label(egui::RichText::new(text).color(t.text_dim)); + }; + match s { + Several::DeleteAlbums { ids } => { + ui.label(crate::i18n::tr_format!("Delete {n} albums?", n = ids.len())); + names(ui, ids.iter().filter_map(|id| cat.album(lightcraft_catalog::AlbumId(*id))).map(|a| a.name.clone()).collect()); + // (a folder among them takes the albums inside it along, as for one album) + dim(ui, crate::i18n::tr("Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.").to_string()); + } + Several::DeleteKeywords { keywords, count } => { + ui.label(crate::i18n::tr_format!("Delete {n} keywords?", n = keywords.len())); + names(ui, keywords.iter().map(|k| k.replace('|', " › ")).collect()); + dim( + ui, + if *count == 0 { + crate::i18n::tr("No photo has them; the keywords below them go too.").to_string() + } else { + crate::i18n::tr_format!( + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.", + count = count + ) + }, + ); + } + Several::RemoveFolders { paths, count } => { + ui.label(crate::i18n::tr_format!( + "Remove {n} folders from the library? Photos imported from them: {count}.", + n = paths.len(), + count = count + )); + names(ui, paths.clone()); + dim(ui, crate::i18n::tr("That includes the photos in the folders inside them.").to_string()); + dim(ui, crate::i18n::tr("They move to Recently Deleted and can be restored; no file on disk is touched.").to_string()); + } + } +} + +/// The first few of the rows a confirmation is about, then how many more. +fn names(ui: &mut egui::Ui, all: Vec) { + const SHOWN: usize = 6; + let t = crate::theme::Tokens::get(ui.ctx()); + for name in all.iter().take(SHOWN) { + ui.label(egui::RichText::new(name).color(t.text_dim)); + } + if all.len() > SHOWN { + ui.label(egui::RichText::new(crate::i18n::tr_format!("…and {n} more", n = all.len() - SHOWN)).color(t.text_dim)); + } +} + +/// Do what the confirmation asked. A refusal is toasted by `act` (the reason, for as long as any +/// refusal stays), and the `Err` keeps the whole error for the control channel. +pub(crate) fn several_run(app: &mut LightcraftApp, s: &Several) -> Result { + match s { + Several::DeleteAlbums { ids } => app.act_told("album.delete", json!({"ids": ids})), + Several::DeleteKeywords { keywords, .. } => { + let r = app.act_told("keyword.delete", json!({"keywords": keywords})); + if r.is_ok() { + // none of them is picked in the Keyword List any more + let gone = |k: &String| keywords.iter().any(|g| lightcraft_catalog::keywords::is_under(k, g)); + let left: Vec = list_picked(app).into_iter().filter(|k| !gone(k)).collect(); + list_pick(app, left); + } + r + } + Several::RemoveFolders { paths, .. } => app.act_told("library.removeFolder", json!({"paths": paths})), + } } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index a01c0007aef..4f81b0df035 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -720,6 +720,10 @@ fn delete_key(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { R::RedEye => return true, _ => {} } + // several sidebar rows just chosen with Cmd/Shift+click: it asks about them + if crate::panels::side_select::delete_asked(app, ctx) { + return true; + } // in an album, Delete takes the photos out of the album only, as in Lightroom: they // stay in the library and their folder (issue #1805) crate::menus::delete_in_album(app, ctx) || crate::menus::confirm_delete(app) diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 77f80a280c6..65e13b808a8 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -142,6 +142,8 @@ pub enum Dialog { keyword: String, parent: Option, }, + /// Delete or remove several sidebar rows at once (albums, keywords, folders), after asking. + Several(crate::panels::side_select::Several), /// Delete a keyword from every photo and the keyword list, after asking. DeleteKeyword { keyword: String, diff --git a/crates/ui-egui/src/tests/dialog_primary.rs b/crates/ui-egui/src/tests/dialog_primary.rs index 29078d00956..e4df6cd674e 100644 --- a/crates/ui-egui/src/tests/dialog_primary.rs +++ b/crates/ui-egui/src/tests/dialog_primary.rs @@ -49,6 +49,10 @@ fn constructive_confirms_are_primary_and_destructive_ones_plain() { use crate::state::Dialog; assert_eq!(confirm_style(&Dialog::AutoStack { gap: 60.0 }), ConfirmStyle::Primary); assert_eq!(confirm_style(&Dialog::ConfirmDelete { count: 3 }), ConfirmStyle::Plain); + assert_eq!( + confirm_style(&Dialog::Several(crate::panels::side_select::Several::DeleteKeywords { keywords: vec!["a".into()], count: 1 })), + ConfirmStyle::Plain + ); // a dialog that only shows something has nothing to confirm: its Close is plain assert_eq!(confirm_style(&Dialog::About), ConfirmStyle::Plain); } diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index 8bcf9a4f35d..25ea0347f72 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -1,24 +1,34 @@ //! Several rows of a sidebar list chosen at once, driven through the control channel: Cmd/Ctrl+click //! and Shift+click in the left panel's Albums, Folders, Keywords and By Date and in the right -//! panel's Keyword List. +//! panel's Keyword List, and what a context menu, a drag and the − button do with several rows. //! //! Scenarios: //! - Given albums in the sidebar, when two are Cmd+clicked, then both are highlighted and the //! grid shows the photos of either; Cmd+click on one of them takes it away again. //! - When one album is clicked and another Shift+clicked, then every album between them is //! chosen, but none inside a closed folder; a plain click chooses one alone again. +//! - Given several albums chosen, when the menu of one of them is opened, then it offers what can +//! be done to all (Delete N Albums… asks first, and is one step to undo); the menu of an album +//! that is not chosen is that album's own, and the chosen ones stay chosen. +//! - Given two albums chosen, when one is dragged onto a folder, then both move into it. //! - Keywords and dates in the left panel: Cmd+click filters by any of those chosen; a plain //! click on the one keyword shown still clears it. -//! - Folders: Cmd+click shows the photos of both folders; Shift+click takes those between. -//! - The Keyword List: Cmd+click and Shift+click pick several, and picking never changes the grid. +//! - Folders: Cmd+click shows the photos of both folders; the menu removes both after asking. +//! - The Keyword List: Cmd+click and Shift+click pick several; − and the menu delete them all +//! after one question; the menu gives them all to the selected photos; dragging one of them +//! nests them all. +//! - Given several rows just chosen with Cmd/Shift+click, when Delete is pressed, then the +//! question about those rows comes up; after a click elsewhere, or with one row chosen the +//! usual way, Delete is the photos' as it always was. use std::time::Duration; -use lightcraft_catalog::AlbumId; +use lightcraft_catalog::{AlbumId, PhotoId}; use lightcraft_engine::LibrarySource; use serde_json::{Value, json}; use crate::headless::Headless; +use crate::panels::side_select::Several; use crate::state::Dialog; use crate::{LightcraftApp, Services}; @@ -59,6 +69,19 @@ fn cmd_click(h: &mut Headless, id: &str) { fn shift_click(h: &mut Headless, id: &str) { ask(h, "ui.clickWidget", json!({"id": id, "shift": true})); } +fn right_click(h: &mut Headless, id: &str) { + ask(h, "ui.clickWidget", json!({"id": id, "button": "right"})); +} + +fn center(h: &Headless, id: &str) -> egui::Pos2 { + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no {id} on screen")) +} + +/// Drag the widget `from` and drop it on the widget `onto`. +fn drag(h: &mut Headless, from: &str, onto: &str) { + let to = center(h, onto); + ask(h, "ui.dragWidget", json!({"id": from, "toX": to.x, "toY": to.y, "steps": 12})); +} /// An album called `name` holding `photos`. fn album(h: &mut Headless, name: &str, parent: Option, photos: &[u64]) -> u64 { @@ -160,6 +183,59 @@ fn shift_click_does_not_take_albums_inside_a_closed_folder() { assert!(!chosen.contains(&inside), "a row that is not in sight is not taken: {chosen:?}"); } +#[test] +fn the_menu_of_several_albums_deletes_them_after_asking_as_one_step() { + let mut h = app("info"); + let ([a, b, c, d], _) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + // the menu of an album that is not chosen is its own, and the chosen ones stay + right_click(&mut h, &row(d)); + assert!(has(&h, &format!("albumDelete:{d}")), "one album's menu"); + assert!(!has(&h, "sideMenu:albums:delete")); + assert_eq!(shown(&h), vec![a, c]); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + // the menu of one of them: what can be done to both + right_click(&mut h, &row(c)); + assert!(has(&h, "sideMenu:albums:delete") && has(&h, "sideMenu:albums:export")); + assert!(!has(&h, &format!("albumDelete:{c}")), "not the single album's Delete"); + let undo = h.app.session.undo.len(); + click(&mut h, "sideMenu:albums:delete"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Several(Several::DeleteAlbums { ids: vec![a, c] }))); + ask(&mut h, "ui.dialog.cancel", json!({})); + let exists = |h: &Headless, id: u64| h.app.session.catalog.album(AlbumId(id)).is_some(); + assert!(exists(&h, a) && exists(&h, c), "Cancel keeps them"); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:albums:delete"); + click(&mut h, "button:dialogOk"); + assert!(!exists(&h, a) && !exists(&h, c) && exists(&h, b) && exists(&h, d)); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + assert_eq!(h.app.session.source, LibrarySource::All, "nothing of what was shown is left"); + run(&mut h, "edit.undo", json!({})); + assert!(exists(&h, a) && exists(&h, c)); +} + +#[test] +fn dragging_one_of_several_albums_onto_a_folder_moves_them_all() { + let mut h = app("info"); + let ([a, b, c, _], _) = four_albums(&mut h); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + let parent = |h: &Headless, id: u64| h.app.session.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + let undo = h.app.session.undo.len(); + drag(&mut h, &row(c), &format!("source:folder:{folder}")); + assert_eq!((parent(&h, a), parent(&h, c), parent(&h, b)), (Some(folder), Some(folder), None)); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + assert_eq!(shown(&h), vec![a, c], "still the ones shown"); + // an album that is not one of them goes alone + drag(&mut h, &row(b), &format!("source:folder:{folder}")); + assert_eq!(parent(&h, b), Some(folder)); + run(&mut h, "edit.undo", json!({})); + run(&mut h, "edit.undo", json!({})); + assert_eq!((parent(&h, a), parent(&h, c)), (None, None)); +} + #[test] fn cmd_click_filters_by_any_of_several_keywords() { let mut h = app("info"); @@ -178,6 +254,10 @@ fn cmd_click_filters_by_any_of_several_keywords() { v.sort_unstable(); v }); + assert!(has(&h, "highlight:keyword:Sel One") && has(&h, "highlight:keyword:Sel Two")); + // the menu of one of them offers what can be done to both + right_click(&mut h, "source:keyword:Sel Two"); + assert!(has(&h, "sideMenu:keywords:delete") && has(&h, "sideMenu:keywords:merge")); ask(&mut h, "ui.key", json!({"key": "Escape"})); // a plain click: that keyword alone; again: every photo click(&mut h, "source:keyword:Sel Two"); @@ -222,7 +302,7 @@ fn folders_app(paths: &[&str]) -> Headless { } #[test] -fn cmd_click_shows_several_folders_and_shift_click_takes_those_between() { +fn cmd_click_shows_several_folders_and_the_menu_removes_them_after_asking() { let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/trip/b.jpg", "/pics/home/c.jpg", "/pics/work/d.jpg"]); click(&mut h, "libraryFolderToggle:/pics"); click(&mut h, "source:libfolder:/pics/trip"); @@ -231,8 +311,20 @@ fn cmd_click_shows_several_folders_and_shift_click_takes_those_between() { assert_eq!(h.app.session.visible().len(), 3); assert_eq!(crate::i18n::source_title(&h.app.session), "2 folders", "the title says how many are shown"); assert!(has(&h, "highlight:libfolder:/pics/trip") && has(&h, "highlight:libfolder:/pics/work")); + right_click(&mut h, "source:libfolder:/pics/work"); + assert!(has(&h, "sideMenu:folders:remove")); + click(&mut h, "sideMenu:folders:remove"); + assert_eq!( + h.app.ui.dialog, + Some(Dialog::Several(Several::RemoveFolders { paths: vec!["/pics/trip".to_string(), "/pics/work".to_string()], count: 3 })) + ); + let undo = h.app.session.undo.len(); + click(&mut h, "button:dialogOk"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.source, LibrarySource::All); + assert_eq!(h.app.session.visible().len(), 1, "the photo of the folder that stayed"); // Shift+click takes the folders between, as drawn - click(&mut h, "source:all"); + run(&mut h, "edit.undo", json!({})); let rows: Vec = h.app.widgets.iter().filter_map(|(w, _)| w.strip_prefix("source:libfolder:/pics/").map(str::to_string)).collect(); assert_eq!(rows.len(), 3, "{rows:?}"); click(&mut h, &format!("source:libfolder:/pics/{}", rows[0])); @@ -260,6 +352,12 @@ fn picked(h: &Headless) -> Vec { crate::panels::side_select::list_picked(&h.app) } +fn keywords_of(h: &Headless, id: u64) -> Vec { + let mut k: Vec = h.app.session.catalog.photo(PhotoId(id)).unwrap().meta.keywords.iter().filter(|k| k.contains("Sel")).cloned().collect(); + k.sort(); + k +} + #[test] fn the_keyword_list_picks_several_with_cmd_and_shift() { let (mut h, _) = keyword_list(); @@ -278,6 +376,124 @@ fn the_keyword_list_picks_several_with_cmd_and_shift() { assert_eq!(h.app.session.filter, lightcraft_catalog::Filter::default()); } +#[test] +fn the_keyword_list_deletes_several_after_one_question() { + let (mut h, ids) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K2"); + let undo = h.app.session.undo.len(); + click(&mut h, "keywordList:delete"); + assert_eq!( + h.app.ui.dialog, + Some(Dialog::Several(Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string()], count: 2 })) + ); + ask(&mut h, "ui.dialog.cancel", json!({})); + assert!(h.app.session.catalog.has_keyword("Sel K1"), "Cancel kept them"); + // from the menu of one of them, the same question + right_click(&mut h, "keywordRow:Sel K2"); + assert!(has(&h, "sideMenu:keywords:delete") && !has(&h, "keywordMenu:delete"), "the menu for several"); + click(&mut h, "sideMenu:keywords:delete"); + click(&mut h, "button:dialogOk"); + assert!(!h.app.session.catalog.has_keyword("Sel K1") && !h.app.session.catalog.has_keyword("Sel K2")); + assert!(h.app.session.catalog.has_keyword("Sel K3")); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + assert!(picked(&h).is_empty(), "nothing that is gone stays picked"); + run(&mut h, "edit.undo", json!({})); + assert_eq!(keywords_of(&h, ids[0]), vec!["Sel K1", "Sel K2"]); +} + +#[test] +fn the_menu_of_several_keywords_gives_them_all_to_the_selected_photos() { + let (mut h, ids) = keyword_list(); + run(&mut h, "library.select", json!({"ids": [ids[2]]})); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K3"); + // the menu of a keyword that is not picked is its own + right_click(&mut h, "keywordRow:Sel K2"); + assert!(has(&h, "keywordMenu:delete") && !has(&h, "sideMenu:keywords:add")); + assert_eq!(picked(&h), vec!["Sel K1", "Sel K3"], "the picked ones stay picked"); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + let undo = h.app.session.undo.len(); + right_click(&mut h, "keywordRow:Sel K3"); + click(&mut h, "sideMenu:keywords:add"); + assert_eq!(keywords_of(&h, ids[2]), vec!["Sel K1", "Sel K3"]); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + // …and shows the photos with any of them + right_click(&mut h, "keywordRow:Sel K3"); + click(&mut h, "sideMenu:keywords:show"); + assert_eq!(h.app.session.filter.keywords, vec!["Sel K1".to_string(), "Sel K3".to_string()]); +} + +#[test] +fn dragging_one_of_several_keywords_nests_them_all() { + let (mut h, ids) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K3"); + let undo = h.app.session.undo.len(); + drag(&mut h, "keywordRow:Sel K3", "keywordRow:Sel Parent"); + assert_eq!(keywords_of(&h, ids[0]), vec!["Sel K2", "Sel Parent|Sel K1"]); + assert_eq!(keywords_of(&h, ids[1]), vec!["Sel K2", "Sel Parent|Sel K3"]); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + assert_eq!(picked(&h), vec!["Sel Parent|Sel K1", "Sel Parent|Sel K3"], "still picked, where they are now"); + assert!(h.app.ui.dragging_keyword.is_none(), "the drag ended"); + run(&mut h, "edit.undo", json!({})); + assert_eq!(keywords_of(&h, ids[0]), vec!["Sel K1", "Sel K2"]); +} + +fn several_dialog(h: &Headless) -> bool { + matches!(h.app.ui.dialog, Some(Dialog::Several(_))) +} + +#[test] +fn delete_asks_about_several_rows_just_chosen_and_is_the_photos_otherwise() { + let mut h = app("info"); + let ([a, _, c, _], _) = four_albums(&mut h); + // one album chosen the usual way: Delete is not about albums + click(&mut h, &row(a)); + assert!(h.app.ui.side.keys.is_none()); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); + ask(&mut h, "ui.dialog.cancel", json!({})); + // several chosen with Cmd+click: Delete asks about them + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + assert!(has(&h, &format!("highlight:album:{a}"))); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert_eq!(h.app.ui.dialog, Some(Dialog::Several(Several::DeleteAlbums { ids: vec![a, c] }))); + ask(&mut h, "ui.dialog.cancel", json!({})); + assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "asking deleted nothing"); + // forward Delete too + ask(&mut h, "ui.key", json!({"key": "Delete"})); + assert!(several_dialog(&h)); + ask(&mut h, "ui.dialog.cancel", json!({})); + // a click anywhere else gives the key back to the photos, with both albums still shown + let cell = + h.app.widgets.iter().find(|(w, _)| w.starts_with("cell:") || w.starts_with("thumb:")).map(|(w, _)| w.clone()).expect("a photo in the grid"); + click(&mut h, &cell); + assert_eq!(shown(&h), vec![a, c]); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); +} + +#[test] +fn delete_asks_about_several_keywords_picked_in_the_keyword_list() { + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + shift_click(&mut h, "keywordRow:Sel K3"); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert_eq!( + h.app.ui.dialog, + Some(Dialog::Several(Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string(), "Sel K3".to_string()], count: 2 })) + ); + click(&mut h, "button:dialogOk"); + assert!(!h.app.session.catalog.has_keyword("Sel K2")); + // nothing is chosen there any more: Delete is the photos' again + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); +} + +// ---- What two independent reviews found + /// A range starts from a row that is chosen: not from an album clicked before All Photos was shown. #[test] fn shift_click_does_not_start_from_an_album_that_is_no_longer_shown() { @@ -307,7 +523,60 @@ fn showing_a_keyword_from_the_keyword_list_replaces_the_keywords_chosen_in_the_s assert_eq!(h.app.session.filter.keywords_wanted(), vec!["Sel K3".to_string()]); } -/// A keyword that is gone is not picked any more. +/// The Delete key goes back to the photos when anything else changes what is shown or selected. +#[test] +fn delete_is_the_photos_again_after_a_change_made_without_the_pointer() { + let mut h = app("info"); + let ([a, _, c, _], ids) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + assert!(h.app.ui.side.keys.is_some()); + // a key, a menu or an agent selects photos + run(&mut h, "library.select", json!({"ids": [ids[0]]})); + ask(&mut h, "ui.key", json!({"key": "Backspace"})); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); + assert!(h.app.ui.side.keys.is_none()); +} + +/// A confirmation for several rows that is refused says why. +#[test] +fn a_refused_question_about_several_albums_says_why() { + let mut h = app("info"); + let ([a, _, c, _], _) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:albums:delete"); + // one of them goes while the question is up + h.app.session.execute("album.delete", &json!({"id": c})).unwrap(); + click(&mut h, "button:dialogOk"); + assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "refused as a whole"); + let said = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(said.contains(&c.to_string()), "the toast names the album that is gone: {said:?}"); + // only the reason, not the command it came from, and for as long as any refusal stays + assert!(!said.contains("album.delete"), "{said:?}"); + let (left, now) = (h.app.ui.toast.as_ref().map_or(0.0, |t| t.1), h.time()); + assert!(left - now > 5.0, "a refusal stays {} s", left - now); +} + +/// The control channel's confirm of a refused question about several rows answers with the reason. +#[test] +fn a_refused_confirm_of_several_albums_answers_with_the_reason() { + let mut h = app("info"); + let ([a, _, c, _], _) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:albums:delete"); + h.app.session.execute("album.delete", &json!({"id": c})).unwrap(); + let r = h.request("ui.dialog.confirm", json!({}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], false, "{r}"); + let said = r["error"].as_str().unwrap_or_default(); + assert!(said.contains(&c.to_string()), "the error names the album that is gone: {said:?}"); + assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "refused as a whole"); +} + +/// A keyword that is gone is not picked any more: the row left alone has its own menu. #[test] fn a_keyword_that_is_gone_is_not_picked_any_more() { let (mut h, _) = keyword_list(); @@ -315,6 +584,8 @@ fn a_keyword_that_is_gone_is_not_picked_any_more() { cmd_click(&mut h, "keywordRow:Sel K3"); run(&mut h, "keyword.delete", json!({"keyword": "Sel K3"})); assert_eq!(picked(&h), vec!["Sel K1"]); + right_click(&mut h, "keywordRow:Sel K1"); + assert!(has(&h, "keywordMenu:delete") && !has(&h, "sideMenu:keywords:delete"), "one keyword's menu"); // one that was picked earlier is let go of too let (mut h, _) = keyword_list(); click(&mut h, "keywordRow:Sel K1"); @@ -335,10 +606,11 @@ fn a_keyword_that_is_gone_is_not_picked_any_more() { fn delete_with_several_albums_shown_does_not_take_a_photo_out_of_the_one_chosen_last() { let mut h = app("info"); let ([a, _, c, _], ids) = four_albums(&mut h); + run(&mut h, "library.select", json!({"ids": [ids[0]]})); click(&mut h, &row(a)); cmd_click(&mut h, &row(c)); assert!(!crate::menubar::in_normal_album(&h.app), "Remove from Album is not on offer for several albums"); - // a photo that is in A and in C (the one chosen last) + // a photo that is in A and in C (the one chosen last): choosing it is a change, so the key is the photos' again run(&mut h, "library.select", json!({"ids": [ids[4]]})); ask(&mut h, "ui.key", json!({"key": "Delete"})); assert_eq!(h.app.ui.dialog, Some(Dialog::ConfirmDelete { count: 1 }), "the photos' Delete asks"); @@ -360,12 +632,12 @@ fn what_was_chosen_is_forgotten_when_another_library_opens() { let ([a, _, c, _], _) = four_albums(&mut h); click(&mut h, &row(a)); cmd_click(&mut h, &row(c)); - assert!(h.app.ui.side.albums.anchor.is_some()); + assert!(h.app.ui.side.keys.is_some()); let dir = Scratch(std::env::temp_dir().join(format!("lc-multi-select-switch-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&dir.0); h.app.session.open_library(&dir.0, false).unwrap(); h.settle(SETTLE); - assert!(h.app.ui.side.albums.anchor.is_none()); + assert!(h.app.ui.side.keys.is_none()); } /// A keyword picked in the Keyword List is not picked in another library that has the same keyword. diff --git a/docs/gaps.md b/docs/gaps.md index e2af2926f06..e5ffd6869ce 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,7 +45,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | -| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars (`library.source` `ids`/`paths`, `library.filter` `keywords`/`dates`). The menus, drags and Delete key of those sidebars still act on one row | `crates/ui-egui/src/panels/side_select.rs`, `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ for the clicks | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | +| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars (`library.source` `ids`/`paths`, `library.filter` `keywords`/`dates`). The menus, dragging and Delete key of those sidebars act on all the rows chosen (`album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder`, `folder.label` take several). Synchronize Folder is still for one folder at a time | `crates/ui-egui/src/panels/side_select.rs`, `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -196,4 +196,4 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-20 | minor | Opt-in Windows DirectComposition preference added; VRR hardware verification pending; parity counts unchanged | | 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged | | 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) | -| 2026-10-26 | minor | Gap 31 narrows: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars; menus, drags and Delete for several rows remain | +| 2026-10-26 | minor | Gap 31 narrows: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and their menus, dragging and Delete act on them all; Synchronize Folder for several folders remains | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 24a3dca72f4..37592895203 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1054,3 +1054,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-21 | minor | LR-BEHAV-MULTISELECT: `library.source` takes several albums (`ids`) or folders (`paths`) and `library.filter` several keywords, dates, folders or albums, each photo shown once; `album.setRules` with `replace` keeps a smart album's album and folders; statuses unchanged | | 2026-11-03 | patch | LR-BEHAV-MULTISELECT: a view whose filter names a smart album can't be saved as smart-album rules, and New Smart Album from Filter… is grayed out saying which album it is (a smart album's rules can't test another one); `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does; deleting an album or a folder drops the filter put aside by Enable Filters when only the rating operator is left of it, and deleting a shown album moves the active photo into what is left; Hold View of several albums with a smart album among them is documented as it behaves (a photo stays only while one of them has it); statuses unchanged | | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and several keywords in the Keyword List; menus, drags and Delete for several rows still to come; statuses unchanged | +| 2026-10-26 | minor | LR-BEHAV-MULTISELECT: the menu of several chosen sidebar rows, dragging one of them, and the Delete key act on them all as one undo step (they call `album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder` and `folder.label` with several); ✅ again after the 2026-10-23 downgrade | diff --git a/docs/whats-new.md b/docs/whats-new.md index aa90a924f92..5e7ce66b36d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -345,10 +345,20 @@ inside a folder that is closed. The grid shows the photos of any of them, each once, and the title says how many albums or folders are shown. A plain click chooses one row alone, as before. - In the Keyword List (right panel, Keywords) the same clicks pick several keywords. Picking does not change the grid. -- With several albums shown, Remove from Album is not offered and the Delete key is the photos' Delete (it asks first - while Settings ▸ Confirm before moving photos to Recently Deleted is on), because there is no telling which album is meant. -- Menus, dragging and the Keyword List's − button still act on one row; choosing several rows for those comes in a - later change. When several albums are shown, Delete stays the photos' Delete, as above. +- With several albums shown, Remove from Album is not offered and the Delete key is the photos' Delete once you click + elsewhere (it asks first while Settings ▸ Confirm before moving photos to Recently Deleted is on), because there is no + telling which album is meant. +- Right-click one of several rows chosen to act on them all, as one step to undo: move albums into a folder, export + them, or delete them; give folders a color label or remove them from the library; give keywords to the selected + photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes. + Right-click a row that is not among them and you get that row's own menu; the others stay chosen. +- Dragging one of several albums or keywords moves them all (albums go into the folder they are dropped in or + beside; placing by hand among its neighbors stays one album's). +- Right after choosing several rows with Cmd or Shift, the Delete key asks about those rows. Click anywhere else, + or select photos or change what is shown in any other way, and Delete is about the photos again; after a plain + click on an album it always was. +- For agents: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, + `library.removeFolder` and `folder.label` take `paths`, as one undo step each. ## 2026-10-24 From f810140ee8fd15ede69cb826e05f55d9ed783506 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 18:38:55 -0400 Subject: [PATCH 35/55] =?UTF-8?q?LR-BEHAV-MULTISELECT:=20the=20Ukrainian?= =?UTF-8?q?=20Delete=20Albums=20sentence=20says=20=D1=82=D0=B5=D0=BA=D0=B0?= =?UTF-8?q?,=20as=20the=20rest=20of=20the=20catalog=20does?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/locales/uk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index f32b316aec8..f370daeb08d 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2439,5 +2439,5 @@ "Remove Folders from Library": "Вилучити теки з бібліотеки", "That includes the photos in the folders inside them.": "Також включаються фото у вкладених у них теках.", "The photos stay in All Photos. Undo brings the albums back.": "Фото залишаються в «Усіх фото». Скасування повертає альбоми.", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення папки видаляє й її альбоми. Це можна скасувати." + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення теки видаляє й її альбоми. Це можна скасувати." } From 2570503a68e19993820c29a8b1ffe5a0d37a215d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 19:27:54 -0400 Subject: [PATCH 36/55] LR-BEHAV-MULTISELECT: Spanish says the nested keywords and folders are below or inside the chosen ones; What's New finishes the dragging sentence --- crates/ui-egui/locales/es.json | 6 +++--- docs/whats-new.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index d2c3eb320b0..b536a3e5e3d 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2073,7 +2073,7 @@ "Purge Unused Keywords": "Eliminar palabras clave no usadas", "Delete Keyword…": "Eliminar palabra clave…", "Drop here for the top level": "Soltar aquí para el nivel superior", - "Their photos and the keywords below them come together under one keyword.": "Sus fotos y las palabras clave que contienen quedan bajo una sola palabra clave.", + "Their photos and the keywords below them come together under one keyword.": "Sus fotos y las palabras clave que están debajo de ellas quedan bajo una sola palabra clave.", "Select photos to give them keywords.": "Seleccionar fotos para darles palabras clave.", "Add to All Selected Photos": "Añadir a todas las fotos seleccionadas", "Will Export": "Se exportará", @@ -2438,10 +2438,10 @@ "Delete Folder": "Eliminar carpeta", "Delete Keywords": "Eliminar palabras clave", "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Mueve las fotos importadas desde estas carpetas a Eliminadas recientemente; no se toca ningún archivo", - "No photo has them; the keywords below them go too.": "Ninguna foto las tiene; las palabras clave que contienen también se eliminan.", + "No photo has them; the keywords below them go too.": "Ninguna foto las tiene; también se eliminan las palabras clave que están debajo de ellas.", "One of them is a whole disk: remove a disk by itself": "Una de ellas es un disco entero: quita un disco por separado", "Remove Folders from Library": "Quitar carpetas de la biblioteca", - "That includes the photos in the folders inside them.": "Esto incluye las fotos de las carpetas que contienen.", + "That includes the photos in the folders inside them.": "Esto incluye las fotos de las carpetas que están dentro de ellas.", "The photos stay in All Photos. Undo brings the albums back.": "Las fotos se quedan en Todas las fotos. Deshacer recupera los álbumes.", "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Las fotos se quedan en Todas las fotos. Al eliminar una carpeta también se eliminan sus álbumes. Puedes deshacerlo." } diff --git a/docs/whats-new.md b/docs/whats-new.md index 5e7ce66b36d..9867426669d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -353,7 +353,7 @@ photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes. Right-click a row that is not among them and you get that row's own menu; the others stay chosen. - Dragging one of several albums or keywords moves them all (albums go into the folder they are dropped in or - beside; placing by hand among its neighbors stays one album's). + beside; placing an album by hand among its neighbors moves only that album). - Right after choosing several rows with Cmd or Shift, the Delete key asks about those rows. Click anywhere else, or select photos or change what is shown in any other way, and Delete is about the photos again; after a plain click on an album it always was. From f078518719fabde3ba6a1d7016214acf9a7b4e89 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 21:02:18 -0400 Subject: [PATCH 37/55] LR-BEHAV-MULTISELECT: the Spanish keyword-delete count line also says the nested keywords are below the chosen ones --- crates/ui-egui/locales/es-formats.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index d5b0d5dd550..424134b4e7a 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -340,7 +340,7 @@ "Delete {n} Keywords…": "Eliminar {n} palabras clave…", "Delete {n} albums?": "¿Eliminar {n} álbumes?", "Delete {n} keywords?": "¿Eliminar {n} palabras clave?", - "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotos que tienen alguna: {count}. Las palabras clave que contienen también se eliminan. Deshacer las recupera.", + "Photos that have one of them: {count}. The keywords below them go too. Undo brings them back.": "Fotos que tienen alguna: {count}. También se eliminan las palabras clave que están debajo de ellas. Deshacer las recupera.", "Remove {n} folders from the library? Photos imported from them: {count}.": "¿Quitar {n} carpetas de la biblioteca? Fotos importadas de ellas: {count}.", "…and {n} more": "…y {n} más", "{n} keywords": "{n} palabras clave" From 292045dbab54b2440c912c4d647cd2134fa0fb9d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Wed, 28 Oct 2026 12:40:34 -0400 Subject: [PATCH 38/55] LR-BEHAV-MULTISELECT: a group of albums is dropped where an album chosen with the dragged one still has to move, also when the dragged one is there already --- crates/ui-egui/src/panels/left/albums.rs | 32 +++++++++++----- crates/ui-egui/src/tests/multi_select.rs | 47 ++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 243df560151..7b6d865b805 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -180,13 +180,22 @@ pub(super) const MARK_W: f32 = 12.0; /// How long a dragged album must rest on a closed folder before it opens. const HOVER_OPEN_SECS: f64 = 0.6; -/// Whether the album `dragged` may be dropped into the folder `target` (`None`: the top level): -/// a folder other than where it already is, and not itself or something inside it. +/// Whether the album `dragged`, with the albums chosen beside it when it is one of several, may be +/// dropped into the folder `target` (`None`: the top level): at least one of them has to move +/// there (it is not in that folder already), and none may go into itself or something inside it. fn can_drop_album(app: &LightcraftApp, dragged: AlbumId, target: Option) -> bool { - let Some(d) = app.session.catalog.album(dragged) else { return false }; + let cat = &app.session.catalog; + if cat.album(dragged).is_none() { + return false; + } + let group: Vec = crate::panels::side_select::albums_dragged(app, dragged).into_iter().map(AlbumId).collect(); match target { - None => d.parent.is_some(), - Some(t) => app.session.catalog.album(t).is_some_and(|f| f.folder) && d.parent != Some(t) && !is_within(app, t, dragged), + None => group.iter().any(|id| cat.album(*id).is_some_and(|a| a.parent.is_some())), + Some(t) => { + cat.album(t).is_some_and(|f| f.folder) + && group.iter().any(|id| cat.album(*id).is_some_and(|a| a.parent != Some(t))) + && !group.iter().any(|id| is_within(app, t, *id)) + } } } @@ -278,11 +287,14 @@ fn album_drop_at(app: &LightcraftApp, dragged: AlbumId, target: &Album, frac: f3 let sibs = cat.album_children(parent); let at = sibs.iter().position(|a| a.id == target.id)?; let was = sibs.iter().position(|a| a.id == dragged); + // (placed where it already is is nothing, unless an album chosen with it is elsewhere: `place_album` moves those here) + let group = crate::panels::side_select::albums_dragged(app, dragged); + let others_move = group.iter().any(|id| cat.album(AlbumId(*id)).is_some_and(|a| a.parent != parent)); if !after { - (was.map(|w| w + 1) != Some(at)).then_some(AlbumDrop::Place { parent, before: Some(target.id), above: true }) + (others_move || was.map(|w| w + 1) != Some(at)).then_some(AlbumDrop::Place { parent, before: Some(target.id), above: true }) } else { let next = sibs.iter().skip(at + 1).find(|a| a.id != dragged).filter(|a| a.folder == target.folder).map(|a| a.id); - (was != Some(at + 1)).then_some(AlbumDrop::Place { parent, before: next, above: false }) + (others_move || was != Some(at + 1)).then_some(AlbumDrop::Place { parent, before: next, above: false }) } } @@ -345,9 +357,9 @@ fn album_drag_over(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Resp opened } -/// While an album that sits in a folder is dragged: the "Albums" header takes it back to the top -/// level (outlined, with a hint). The header stays in view however long the tree is, and nothing -/// moves when it appears. +/// While an album that sits in a folder, or chosen with one that does, is dragged: the "Albums" +/// header takes it back to the top level (outlined, with a hint). The header stays in view however +/// long the tree is, and nothing moves when it appears. pub(super) fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, header: Rect) { let Some(dragged) = app.ui.dragging_album.map(AlbumId) else { return }; if !can_drop_album(app, dragged, None) { diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index 25ea0347f72..32211f3288e 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -236,6 +236,53 @@ fn dragging_one_of_several_albums_onto_a_folder_moves_them_all() { assert_eq!((parent(&h, a), parent(&h, c)), (None, None)); } +/// The group goes wherever one of its albums still has to move: the dragged row may already be there. +#[test] +fn a_group_can_be_dropped_where_only_the_dragged_album_already_is() { + let mut h = app("info"); + let ([a, _, c, _], _) = four_albums(&mut h); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + run(&mut h, "album.move", json!({"id": a, "parent": folder})); + let parent = |h: &Headless, id: u64| h.app.session.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0); + h.app.ui.reveal_album = Some(a); + run(&mut h, "library.source", json!({"kind": "album", "ids": [a, c]})); + h.step(); + h.step(); + let undo = h.app.session.undo.len(); + // dragged: the one already at the top level; the other one is in the folder + drag(&mut h, &row(c), "sidebarSection:albums"); + assert_eq!((parent(&h, a), parent(&h, c)), (None, None), "both at the top level"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + run(&mut h, "edit.undo", json!({})); + h.app.ui.reveal_album = Some(a); + h.step(); + h.step(); + // dragged: the one already in the folder; the other one is at the top level + drag(&mut h, &row(a), &format!("source:folder:{folder}")); + assert_eq!((parent(&h, a), parent(&h, c)), (Some(folder), Some(folder)), "both in the folder"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); +} + +/// A drop beside a row that would put the dragged album where it already is still moves the albums +/// chosen with it that are elsewhere. +#[test] +fn a_group_dropped_beside_the_row_above_its_dragged_album_still_moves_the_others() { + let mut h = app("info"); + let ([a, b, c, _], _) = four_albums(&mut h); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + run(&mut h, "album.move", json!({"id": a, "parent": folder})); + let parent = |h: &Headless, id: u64| h.app.session.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0); + h.app.ui.reveal_album = Some(a); + run(&mut h, "library.source", json!({"kind": "album", "ids": [a, c]})); + h.step(); + h.step(); + let undo = h.app.session.undo.len(); + // (C goes below B, where it already is: for C alone that is nothing) + drag(&mut h, &row(c), &row(b)); + assert_eq!((parent(&h, a), parent(&h, c)), (None, None), "A comes out of its folder to the top level"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); +} + #[test] fn cmd_click_filters_by_any_of_several_keywords() { let mut h = app("info"); From 1dacef8ffd5bc3c9e5dcd205db796656a86ee998 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:09:20 -0400 Subject: [PATCH 39/55] LR-BEHAV-MULTISELECT: a group of albums dropped beside a row places the dragged album there in the same undo step --- crates/engine/src/cmd/library/specs.rs | 135 ++++++++++++++--------- crates/engine/src/tests/album_order.rs | 54 +++++++++ crates/ui-egui/src/panels/left/albums.rs | 16 ++- crates/ui-egui/src/tests/multi_select.rs | 28 +++++ docs/parity-checklist.md | 1 + docs/whats-new.md | 5 +- 6 files changed, 176 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 536f99608d3..de14d582ea3 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -29,22 +29,19 @@ fn next_seed(prev: u64, now: &str) -> u64 { (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1) } -/// `album.move` for several albums and folders (`ids`) at once: everything is checked first, then -/// they move as one undo step. -fn move_albums(s: &mut Session, p: &Value) -> Result { - const C: &str = "album.move"; - let ids = album_ids(p.get("ids").unwrap_or(&Value::Null), C)?; +/// The albums and folders of `ids` that move into `parent`, checked as `album.move` checks them: all exist, `parent` +/// is a folder (or the top level) and none goes inside itself. Of a folder and what is inside it, the folder moves. +fn plan_moves(s: &Session, ids: &[AlbumId], parent: Option, cmd: &str) -> Result> { if ids.is_empty() { - return Err(bad(C, "`ids` names no album")); + return Err(bad(cmd, "`ids` names no album")); } if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { - return Err(bad(C, format!("no such album {}", gone.0))); + return Err(bad(cmd, format!("no such album {}", gone.0))); } - let parent = opt_album_param(p, "parent", C)?; if let Some(folder) = parent && !s.catalog.album(folder).is_some_and(|a| a.folder) { - return Err(bad(C, format!("album {} is not a folder of albums", folder.0))); + return Err(bad(cmd, format!("album {} is not a folder of albums", folder.0))); } // where `parent` sits: itself and the folders above it (a ring, in a damaged library, ends the walk) let mut above: Vec = Vec::new(); @@ -70,9 +67,19 @@ fn move_albums(s: &mut Session, p: &Value) -> Result { for id in &moving { let name = s.catalog.album(*id).map(|a| a.name.clone()).unwrap_or_default(); if above.contains(id) { - return Err(bad(C, format!("“{name}” can't go inside itself"))); + return Err(bad(cmd, format!("“{name}” can't go inside itself"))); } } + Ok(moving) +} + +/// `album.move` for several albums and folders (`ids`) at once: everything is checked first, then +/// they move as one undo step. +fn move_albums(s: &mut Session, p: &Value) -> Result { + const C: &str = "album.move"; + let ids = album_ids(p.get("ids").unwrap_or(&Value::Null), "ids", C)?; + let parent = opt_album_param(p, "parent", C)?; + let moving = plan_moves(s, &ids, parent, C)?; let ops: Vec = moving.iter().map(|id| Op::MoveAlbum { id: *id, parent }).collect(); let label = if moving.len() == 1 { "Move Album".to_string() } else { format!("Move {} Albums", moving.len()) }; s.commit(&label, Op::Batch { ops })?; @@ -83,15 +90,20 @@ fn move_albums(s: &mut Session, p: &Value) -> Result { /// chooses in a sidebar, and a bound on what one call can make the engine check. pub(crate) const MAX_SOURCES: usize = 1000; -/// A command's `ids`: album ids, each once (named twice, the last naming counts). -fn album_ids(v: &Value, c: &str) -> Result> { - let list = v.as_array().ok_or_else(|| bad(c, "`ids` must be a list of album ids"))?; +/// `library.source`'s `ids`: album ids, each once (named twice, the last naming counts). +fn source_album_ids(v: &Value) -> Result> { + album_ids(v, "ids", "library.source") +} + +/// A command's list of album ids (`name`, `ids` or `with`): each once (named twice, the last naming counts). +fn album_ids(v: &Value, name: &str, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, format!("`{name}` must be a list of album ids")))?; if list.len() > MAX_SOURCES { - return Err(bad(c, format!("`ids` names more than {MAX_SOURCES} albums"))); + return Err(bad(c, format!("`{name}` names more than {MAX_SOURCES} albums"))); } let mut out: Vec = Vec::new(); for x in list { - let id = AlbumId(x.as_u64().ok_or_else(|| bad(c, format!("`ids` must be a list of album ids, not {x}")))?); + let id = AlbumId(x.as_u64().ok_or_else(|| bad(c, format!("`{name}` must be a list of album ids, not {x}")))?); out.retain(|o| *o != id); out.push(id); } @@ -114,11 +126,6 @@ fn folder_paths(v: &Value, c: &str) -> Result> { Ok(out) } -/// `library.source`'s `ids`: album ids, each once (named twice, the last naming counts). -fn source_album_ids(v: &Value) -> Result> { - album_ids(v, "library.source") -} - /// `library.source`'s `paths`: folder paths, each folder once (named twice, the last counts). fn source_folder_paths(v: &Value) -> Result> { folder_paths(v, "library.source") @@ -1141,7 +1148,7 @@ pub fn specs() -> Vec { const C: &str = "album.delete"; let several = p.get("ids").is_some_and(|v| !v.is_null()); let ids = match p.get("ids") { - Some(v) if several => album_ids(v, C)?, + Some(v) if several => album_ids(v, "ids", C)?, _ => vec![album_param(p, "id", C)?], }; if ids.is_empty() { @@ -1237,48 +1244,72 @@ pub fn specs() -> Vec { "Reorder Album", [], None, - "{id, parent?: folderId|null, before?: albumId|null} — places the album (or folder) in `parent` (default: where it is; null: the top level) before the sibling `before` of the same kind, or last of its kind; the folder is then ordered by hand. One undo step. → {changed}: how many edits it took (0: already there)", + "{id, parent?: folderId|null, before?: albumId|null, with?: [albumId]} — places the album (or folder) in `parent` (default: where it is; null: the top level) before the sibling `before` of the same kind, or last of its kind; the folder is then ordered by hand. `with`: albums and folders chosen beside it that are elsewhere, which come to `parent` too, checked as `album.move` checks them (one that can't go there refuses the whole call; one inside a folder that moves too stays in it, and then `id` is not placed). One undo step. → {changed}: how many edits it took (0: already there)", always, |s, p| { - let id = album_param(p, "id", "album.reorder")?; - let me = s.catalog.album(id).ok_or_else(|| bad("album.reorder", "no such album"))?; - let parent = if p.get("parent").is_some() { opt_album_param(p, "parent", "album.reorder")? } else { me.parent }; - let before = opt_album_param(p, "before", "album.reorder")?; - if before == Some(id) { - // before itself: where it is - return Ok(json!({"changed": 0})); + const C: &str = "album.reorder"; + let id = album_param(p, "id", C)?; + let me = s.catalog.album(id).ok_or_else(|| bad(C, "no such album"))?; + let parent = if p.get("parent").is_some() { opt_album_param(p, "parent", C)? } else { me.parent }; + let before = opt_album_param(p, "before", C)?; + // the ones chosen with it come to `parent` in the same step (those there already stay) + let mut with = match p.get("with") { + None | Some(Value::Null) => Vec::new(), + Some(v) => album_ids(v, "with", C)?, + }; + let mut placed = true; + let mut others: Vec = Vec::new(); + if !with.is_empty() { + if !with.contains(&id) { + with.push(id); + } + let moving = plan_moves(s, &with, parent, C)?; + // (inside a folder that moves too, it is carried with it and not placed) + placed = moving.contains(&id); + others = moving.into_iter().filter(|a| *a != id && s.catalog.album(*a).is_some_and(|x| x.parent != parent)).collect(); } - let mut order: Vec = s.catalog.album_children(parent).into_iter().filter(|a| a.id != id).map(|a| a.id).collect(); - let at = match before { - Some(b) => { - let at = order.iter().position(|x| *x == b).ok_or_else(|| bad("album.reorder", "`before` is not inside that folder"))?; - if s.catalog.album(b).is_none_or(|x| x.folder != me.folder) { - return Err(bad("album.reorder", "folders are placed among folders and albums among albums")); + let mut ops: Vec = others.iter().map(|a| Op::MoveAlbum { id: *a, parent }).collect(); + // before itself: where it is + if placed && before != Some(id) { + let mut order: Vec = s.catalog.album_children(parent).into_iter().filter(|a| a.id != id).map(|a| a.id).collect(); + let at = match before { + Some(b) => { + let at = order.iter().position(|x| *x == b).ok_or_else(|| bad(C, "`before` is not inside that folder"))?; + if s.catalog.album(b).is_none_or(|x| x.folder != me.folder) { + return Err(bad(C, "folders are placed among folders and albums among albums")); + } + at } - at + None if me.folder => order.iter().take_while(|x| s.catalog.album(**x).is_some_and(|a| a.folder)).count(), + None => order.len(), + }; + order.insert(at.min(order.len()), id); + let moved = me.parent != parent; + if moved { + ops.push(Op::MoveAlbum { id, parent }); } - None if me.folder => order.iter().take_while(|x| s.catalog.album(**x).is_some_and(|a| a.folder)).count(), - None => order.len(), - }; - order.insert(at.min(order.len()), id); - let moved = me.parent != parent; - let mut ops = Vec::new(); - if moved { - ops.push(Op::MoveAlbum { id, parent }); - } - for (i, aid) in order.iter().enumerate() { - let want = u32::try_from(i).ok(); - // a moved album starts without a place in its new folder - let have = if moved && *aid == id { None } else { s.catalog.album(*aid).and_then(|a| a.order) }; - if have != want { - ops.push(Op::SetAlbumOrder { id: *aid, order: want }); + for (i, aid) in order.iter().enumerate() { + let want = u32::try_from(i).ok(); + // a moved album starts without a place in its new folder + let have = if moved && *aid == id { None } else { s.catalog.album(*aid).and_then(|a| a.order) }; + if have != want { + ops.push(Op::SetAlbumOrder { id: *aid, order: want }); + } } } if ops.is_empty() { return Ok(json!({"changed": 0})); } let changed = ops.len(); - s.commit("Reorder Album", Op::Batch { ops })?; + let n = others.len() + usize::from(placed); + let label = if others.is_empty() { + "Reorder Album".to_string() + } else if n == 1 { + "Move Album".to_string() + } else { + format!("Move {n} Albums") + }; + s.commit(&label, Op::Batch { ops })?; Ok(json!({"changed": changed})) } ), diff --git a/crates/engine/src/tests/album_order.rs b/crates/engine/src/tests/album_order.rs index cff524cbe12..b87c794c4b8 100644 --- a/crates/engine/src/tests/album_order.rs +++ b/crates/engine/src/tests/album_order.rs @@ -157,3 +157,57 @@ fn moving_out_of_an_ordered_folder_keeps_the_others_in_place() { assert_eq!(names(&s, None), ["F", "X"]); let _ = y; } + +/// Given albums chosen together in other folders, when one of them is placed before a sibling with the others named +/// in `with`, then it lands there and the others come to the same folder, as one undo step. +#[test] +fn placing_one_of_a_group_moves_the_others_along_in_one_step() { + let mut s = Session::new(); + let f = make(&mut s, "F", None, true); + let (x, y) = (make(&mut s, "X", Some(f), false), make(&mut s, "Y", Some(f), false)); + let (a, b) = (make(&mut s, "A", None, false), make(&mut s, "B", None, false)); + let undo = s.undo.len(); + reorder(&mut s, y, json!({"parent": null, "before": b, "with": [x, y]})).unwrap(); + let top = names(&s, None); + let at = |n: &str| top.iter().position(|x| x == n).unwrap(); + assert_eq!(at("Y") + 1, at("B"), "Y is placed before B: {top:?}"); + assert!(top.contains(&"X".to_string()), "X came along: {top:?}"); + assert!(names(&s, Some(f)).is_empty()); + assert_eq!(s.undo.len(), undo + 1, "one step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s, Some(f)), ["X", "Y"], "one undo puts both back"); + assert_eq!(names(&s, None), ["F", "A", "B"]); + let _ = a; +} + +/// A group that is already in the folder is not moved again, and the placement is all that is left. +#[test] +fn placing_one_of_a_group_that_is_there_already_only_places_it() { + let mut s = Session::new(); + let (a, b, c) = (make(&mut s, "A", None, false), make(&mut s, "B", None, false), make(&mut s, "C", None, false)); + reorder(&mut s, c, json!({"before": a, "with": [a, c]})).unwrap(); + assert_eq!(names(&s, None), ["C", "A", "B"]); + let _ = b; +} + +#[test] +fn placing_a_group_refuses_what_a_move_refuses_and_changes_nothing() { + let mut s = Session::new(); + let f = make(&mut s, "F", None, true); + let g = make(&mut s, "G", Some(f), true); + let a = make(&mut s, "A", None, false); + let undo = s.undo.len(); + reorder(&mut s, a, json!({"parent": g, "with": [a, f]})).expect_err("a folder can't go inside what is inside it"); + reorder(&mut s, a, json!({"with": [a, 987_654]})).expect_err("an album that is gone"); + assert_eq!((s.undo.len(), names(&s, None)), (undo, vec!["F".to_string(), "A".to_string()])); +} + +#[test] +fn a_bad_with_is_reported_under_its_own_name() { + let mut s = Session::new(); + let a = make(&mut s, "A", None, false); + let e = reorder(&mut s, a, json!({"with": 3})).expect_err("`with` is a list"); + assert!(e.contains("`with` must be a list of album ids"), "{e}"); + let e = reorder(&mut s, a, json!({"with": ["x"]})).expect_err("a list of ids"); + assert!(e.contains("`with`") && !e.contains("`ids`"), "{e}"); +} diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 7b6d865b805..a52d0055399 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -237,16 +237,14 @@ fn drop_album(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, target: /// Places the dragged album in `parent` before the sibling `before` (`None`: last of its kind), by /// hand (`album.reorder`, one undo step). fn place_album(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, parent: Option, before: Option) { - // picked up as one of several albums chosen: they all go into that folder (one step); a - // place by hand is one album's + // picked up as one of several albums chosen: the others that are elsewhere come into that folder + // in the same step (`with`); the one dragged is placed let several = crate::panels::side_select::albums_dragged(app, dragged); - // (all of them there already: nothing to move, and the one dragged is placed) - let there = several.iter().all(|id| app.session.catalog.album(AlbumId(*id)).is_some_and(|a| a.parent == parent)); - let r = if several.len() > 1 && !there { - app.run("album.move", json!({"ids": several, "parent": parent.map(|p| p.0)})) - } else { - app.run("album.reorder", json!({"id": dragged.0, "parent": parent.map(|p| p.0), "before": before.map(|b| b.0)})) - }; + let mut params = json!({"id": dragged.0, "parent": parent.map(|p| p.0), "before": before.map(|b| b.0)}); + if several.len() > 1 { + params["with"] = json!(several); + } + let r = app.run("album.reorder", params); finish_drop(app, ui, dragged, r); } diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index 32211f3288e..0f8f0177cd2 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -283,6 +283,34 @@ fn a_group_dropped_beside_the_row_above_its_dragged_album_still_moves_the_others assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); } +/// A drop beside a row places the dragged album there, and brings the others chosen with it along, as one step. +#[test] +fn a_group_dropped_beside_a_row_places_the_dragged_album_there() { + let mut h = app("info"); + let ([a, b, c, d], _) = four_albums(&mut h); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + run(&mut h, "album.move", json!({"id": a, "parent": folder})); + let mine = [a, b, c, d, folder]; + let top = + |h: &Headless| -> Vec { h.app.session.catalog.album_children(None).iter().map(|x| x.id.0).filter(|id| mine.contains(id)).collect() }; + h.app.ui.reveal_album = Some(a); + run(&mut h, "library.source", json!({"kind": "album", "ids": [a, c]})); + h.step(); + h.step(); + assert_eq!(top(&h), vec![folder, b, c, d]); + let undo = h.app.session.undo.len(); + // C is dropped below D (the bottom half of a row): after it, where listing by name would not have put it + drag(&mut h, &row(c), &row(d)); + let after = top(&h); + let at = |id: u64| after.iter().position(|x| *x == id); + assert!(at(c) > at(d) && at(d).is_some(), "C was placed after D: {after:?}"); + assert!(after.contains(&a), "A came out of its folder: {after:?}"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + run(&mut h, "edit.undo", json!({})); + assert_eq!(top(&h), vec![folder, b, c, d], "one undo puts both back"); + assert_eq!(h.app.session.catalog.album(AlbumId(a)).unwrap().parent, Some(AlbumId(folder))); +} + #[test] fn cmd_click_filters_by_any_of_several_keywords() { let mut h = app("info"); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 37592895203..2544e93d389 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1055,3 +1055,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-11-03 | patch | LR-BEHAV-MULTISELECT: a view whose filter names a smart album can't be saved as smart-album rules, and New Smart Album from Filter… is grayed out saying which album it is (a smart album's rules can't test another one); `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does; deleting an album or a folder drops the filter put aside by Enable Filters when only the rating operator is left of it, and deleting a shown album moves the active photo into what is left; Hold View of several albums with a smart album among them is documented as it behaves (a photo stays only while one of them has it); statuses unchanged | | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and several keywords in the Keyword List; menus, drags and Delete for several rows still to come; statuses unchanged | | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: the menu of several chosen sidebar rows, dragging one of them, and the Delete key act on them all as one undo step (they call `album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder` and `folder.label` with several); ✅ again after the 2026-10-23 downgrade | +| 2026-10-29 | minor | LR-BEHAV-MULTISELECT: `album.reorder` takes `with` (the albums chosen with the dragged one), so a group of albums is dropped where an album chosen with the dragged one still has to move, and dropped beside a row it places the dragged album there in the same undo step; status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 9867426669d..5dfb8e5b137 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -353,12 +353,13 @@ photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes. Right-click a row that is not among them and you get that row's own menu; the others stay chosen. - Dragging one of several albums or keywords moves them all (albums go into the folder they are dropped in or - beside; placing an album by hand among its neighbors moves only that album). + beside; dropped beside a row, the one you dragged is placed there and the others come into that folder). - Right after choosing several rows with Cmd or Shift, the Delete key asks about those rows. Click anywhere else, or select photos or change what is shown in any other way, and Delete is about the photos again; after a plain click on an album it always was. - For agents: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, - `library.removeFolder` and `folder.label` take `paths`, as one undo step each. + `library.removeFolder` and `folder.label` take `paths`, as one undo step each; `album.reorder` takes `with`, the + albums chosen beside the one it places, which come to the same folder in the same step. ## 2026-10-24 From dd484c3d1d38238dc3e78f88cd45be3cbe957716 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 20:28:21 -0500 Subject: [PATCH 40/55] LR-BEHAV-MULTISELECT: a refused question about several rows closes its dialog again When one of the chosen albums, keywords or folders is gone by the time OK is pressed, the command refuses them all: `several_run` toasts the reason and `confirmed` answers whether the dialog closes. The 2 Nov restack wrote that arm as `=> {}`, so the question stayed up with its OK button after the refusal; 0392e8a165 and the pushed heads (5b8dc7600c, c6ee880fdf) had `closed = true`. The control channel's ui.dialog.confirm already closed it (it takes the dialog first), so only the button was wrong. The new test deletes one of two chosen albums while the question is up, presses OK and expects the albums left alone and no dialog. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/tests/multi_select.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index abce1f21272..6cfbc4e1bde 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -741,7 +741,7 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> } // several rows: one that can't be deleted or removed refuses them all; `several_run` // already toasted the reason, which says which - Err(_) if matches!(dlg, Dialog::Several(_)) => {} + Err(_) if matches!(dlg, Dialog::Several(_)) => closed = true, // the SAM 3 dialog stays open to show the download (or why it can't start) Err(e) if matches!(dlg, Dialog::SamModel { .. }) => { if let Dialog::SamModel { error, .. } = dlg { diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index 0f8f0177cd2..09465ab42b9 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -651,6 +651,24 @@ fn a_refused_confirm_of_several_albums_answers_with_the_reason() { assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "refused as a whole"); } +/// A refused question about several rows closes: the reason is in the toast, and the window does +/// not stay up with its button asking the same thing again. +#[test] +fn a_refused_question_about_several_rows_closes_its_dialog() { + let mut h = app("info"); + let ([a, _, c, _], _) = four_albums(&mut h); + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:albums:delete"); + assert!(several_dialog(&h), "{:?}", h.app.ui.dialog); + // one of them goes while the question is up + h.app.session.execute("album.delete", &json!({"id": c})).unwrap(); + click(&mut h, "button:dialogOk"); + assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "refused as a whole"); + assert!(!several_dialog(&h), "the question closes with its refusal: {:?}", h.app.ui.dialog); +} + /// A keyword that is gone is not picked any more: the row left alone has its own menu. #[test] fn a_keyword_that_is_gone_is_not_picked_any_more() { From 6bd40740cf4880ce8e86a7d0ae0aa5a920d05098 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 3 Nov 2026 20:28:21 -0500 Subject: [PATCH 41/55] LR-BEHAV-MULTISELECT: the French and Russian texts of the menus and the question for several rows are back The pushed head c6ee880fdf had 16 texts in fr.json and in ru.json that 0392e8a165 added for the menus and the question about several chosen sidebar rows (Delete Albums, Remove Folders from Library, the "Choose one ... to ..." lines and the rest); the 2 Nov restack kept the other 15 languages and dropped these two, so both showed English. They are back, the same text as the pushed head, after the Prevent G-SYNC line main ends those files with. A test checks that every language translates each of the 16 texts. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/fr.json | 18 +++++++++++++++++- crates/ui-egui/locales/ru.json | 18 +++++++++++++++++- crates/ui-egui/src/i18n/tests.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 31e6814b6d5..f67eec540f3 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3609,5 +3609,21 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", "Welcome": "Bienvenue", "Next": "Suivant", - "Get Started": "Commencer" + "Get Started": "Commencer", + "Choose one album to rename it": "Choisissez un seul album pour le renommer", + "Choose one folder to rename it": "Choisissez un seul dossier pour le renommer", + "Choose one folder to synchronize it": "Choisissez un seul dossier pour le synchroniser", + "Choose one keyword to create a keyword inside it": "Choisissez un seul mot-clé pour en créer un à l'intérieur", + "Choose one keyword to edit it": "Choisissez un seul mot-clé pour le modifier", + "Choose one keyword to rename it": "Choisissez un seul mot-clé pour le renommer", + "Create Keyword Tag Inside…": "Créer un mot-clé à l'intérieur…", + "Delete Albums": "Supprimer les albums", + "Delete Folder": "Supprimer le dossier", + "Delete Keywords": "Supprimer les mots-clés", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Déplace les photos importées depuis ces dossiers vers Supprimées récemment ; aucun fichier n'est touché", + "No photo has them; the keywords below them go too.": "Aucune photo ne les a ; les mots-clés qu'ils contiennent sont aussi supprimés.", + "One of them is a whole disk: remove a disk by itself": "L'un d'eux est un disque entier : retirez un disque séparément", + "Remove Folders from Library": "Retirer les dossiers de la bibliothèque", + "That includes the photos in the folders inside them.": "Cela inclut les photos des dossiers qu'ils contiennent.", + "The photos stay in All Photos. Undo brings the albums back.": "Les photos restent dans Toutes les photos. Vous pourrez annuler la suppression des albums." } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b3df02470e3..38a5a86169e 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2632,5 +2632,21 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", "Welcome": "Добро пожаловать", "Next": "Далее", - "Get Started": "Начать" + "Get Started": "Начать", + "Choose one album to rename it": "Выберите только один альбом, чтобы переименовать его", + "Choose one folder to rename it": "Выберите только одну папку, чтобы переименовать её", + "Choose one folder to synchronize it": "Выберите только одну папку, чтобы синхронизировать её", + "Choose one keyword to create a keyword inside it": "Выберите только одно ключевое слово, чтобы создать ключевое слово внутри него", + "Choose one keyword to edit it": "Выберите только одно ключевое слово, чтобы изменить его", + "Choose one keyword to rename it": "Выберите только одно ключевое слово, чтобы переименовать его", + "Create Keyword Tag Inside…": "Создать ключевое слово внутри…", + "Delete Albums": "Удалить альбомы", + "Delete Folder": "Удалить папку", + "Delete Keywords": "Удалить ключевые слова", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Перемещает фото, импортированные из этих папок, в «Недавно удалённые»; файлы не затрагиваются", + "No photo has them; the keywords below them go too.": "Их нет ни на одном фото; вложенные в них ключевые слова тоже исчезнут.", + "One of them is a whole disk: remove a disk by itself": "Одна из них — целый диск: убирайте диск отдельно", + "Remove Folders from Library": "Убрать папки из библиотеки", + "That includes the photos in the folders inside them.": "Сюда входят и фото во вложенных в них папках.", + "The photos stay in All Photos. Undo brings the albums back.": "Фото остаются во «Всех фото». Команда «Отменить» вернёт альбомы." } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0b7f31cf9e8..10e2492b08e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -163,6 +163,35 @@ fn the_welcome_tour_is_translated_in_every_catalog() { } } +/// The menus and the question for several chosen sidebar rows have a translation in every language: +/// one without a translation shows the English. +#[test] +fn the_texts_for_several_chosen_sidebar_rows_are_translated_in_every_language() { + const TEXTS: [&str; 16] = [ + "Choose one album to rename it", + "Choose one folder to rename it", + "Choose one folder to synchronize it", + "Choose one keyword to create a keyword inside it", + "Choose one keyword to edit it", + "Choose one keyword to rename it", + "Create Keyword Tag Inside…", + "Delete Albums", + "Delete Folder", + "Delete Keywords", + "Moves the photos imported from these folders to Recently Deleted; no file is touched", + "No photo has them; the keywords below them go too.", + "One of them is a whole disk: remove a disk by itself", + "Remove Folders from Library", + "That includes the photos in the folders inside them.", + "The photos stay in All Photos. Undo brings the albums back.", + ]; + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + let catalog = language.catalog(); + let lacking: Vec<&str> = TEXTS.into_iter().filter(|text| catalog.get(*text).is_none_or(|translation| translation.is_empty())).collect(); + assert!(lacking.is_empty(), "{language:?} shows English for {lacking:?}"); + } +} + /// Locale tags are matched leniently, so a system locale reaches a shipped language. /// The message box for a desktop start that failed (issue #260) names the error and the log /// file, in the UI language. From ce9fb707aaccbacb6b6dce8e2341a63e6283d6b0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 5 Nov 2026 17:58:16 -0500 Subject: [PATCH 42/55] LR-BEHAV-MULTISELECT: the question for several rows is bound to the library it was asked in and refused once another library has opened A library switch left an open question about several albums, keywords or folders up (`switch_library` closes only the Lightroom result, and `ui.dialog` is not reset as `ui.side` is), and OK then ran the saved rows against whatever library was open by then: album ids are numbered per library, so `album.delete {ids}` deleted that library's albums with the same numbers, and a keyword of the same name or a folder of the same path went the same way. `Dialog::Several` is now `Several { rows, library }`, stamped with `Session::library_generation()` where the question is built (one `question()` for the three kinds), and `several_run`, which `confirm_dialog` calls for the button, Enter and the control channel's `ui.dialog.confirm`, refuses it when the generation differs, as `MovePhotos` does: nothing is changed, the window closes, and the toast (and the control channel's error) says "Another library was opened since this window appeared: nothing was changed". The text is translated in the 17 catalogs and added to the test that every language translates the several-rows texts. What's New says it. Four new tests open a scratch library whose albums, keywords or folders match the question's and press OK (albums, albums through `ui.dialog.confirm`, keywords, folders). On the previous head all four fail: album 8 of the second library is deleted, `ui.dialog.confirm` answers `{"ok":true,"result":{"deleted":2}}`, its keywords are deleted and its two photos moved to Recently Deleted. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka.json | 1 + crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/dialogs.rs | 8 +- crates/ui-egui/src/dialogs/confirm.rs | 2 +- crates/ui-egui/src/dialogs/frame.rs | 2 +- crates/ui-egui/src/i18n/tests.rs | 3 +- crates/ui-egui/src/panels/side_select.rs | 30 +++-- crates/ui-egui/src/state/dialog.rs | 7 +- crates/ui-egui/src/tests/dialog_primary.rs | 6 +- crates/ui-egui/src/tests/multi_select.rs | 127 ++++++++++++++++++++- docs/whats-new.md | 5 +- 26 files changed, 194 insertions(+), 45 deletions(-) diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 38eee7fbe47..e0320a405f7 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2488,5 +2488,6 @@ "One of them is a whole disk: remove a disk by itself": "Jedna z nich je celý disk: disk odeberte samostatně", "Remove Folders from Library": "Odebrat složky z knihovny", "That includes the photos in the folders inside them.": "Patří sem i fotografie ve složkách uvnitř nich.", - "The photos stay in All Photos. Undo brings the albums back.": "Fotografie zůstanou ve „Všech fotografiích“. Zpět alba vrátí." + "The photos stay in All Photos. Undo brings the albums back.": "Fotografie zůstanou ve „Všech fotografiích“. Zpět alba vrátí.", + "Another library was opened since this window appeared: nothing was changed": "Od zobrazení tohoto okna byla otevřena jiná knihovna: nic nebylo změněno" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e32a3798220..d66b06eabf9 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3523,5 +3523,6 @@ "One of them is a whole disk: remove a disk by itself": "Einer davon ist ein ganzer Datenträger: einen Datenträger einzeln entfernen", "Remove Folders from Library": "Ordner aus Bibliothek entfernen", "That includes the photos in the folders inside them.": "Das schließt die Fotos in den enthaltenen Unterordnern ein.", - "The photos stay in All Photos. Undo brings the albums back.": "Die Fotos bleiben in „Alle Fotos“. Rückgängig stellt die Alben wieder her." + "The photos stay in All Photos. Undo brings the albums back.": "Die Fotos bleiben in „Alle Fotos“. Rückgängig stellt die Alben wieder her.", + "Another library was opened since this window appeared: nothing was changed": "Seit dem Erscheinen dieses Fensters wurde eine andere Bibliothek geöffnet: Es wurde nichts geändert" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b536a3e5e3d..4ee1860c9bf 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2443,5 +2443,6 @@ "Remove Folders from Library": "Quitar carpetas de la biblioteca", "That includes the photos in the folders inside them.": "Esto incluye las fotos de las carpetas que están dentro de ellas.", "The photos stay in All Photos. Undo brings the albums back.": "Las fotos se quedan en Todas las fotos. Deshacer recupera los álbumes.", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Las fotos se quedan en Todas las fotos. Al eliminar una carpeta también se eliminan sus álbumes. Puedes deshacerlo." + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Las fotos se quedan en Todas las fotos. Al eliminar una carpeta también se eliminan sus álbumes. Puedes deshacerlo.", + "Another library was opened since this window appeared: nothing was changed": "Se abrió otra biblioteca desde que apareció esta ventana: no se cambió nada" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 2613f08fcae..f96281e4a1d 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2399,5 +2399,6 @@ "One of them is a whole disk: remove a disk by itself": "Yksi niistä on kokonainen levy: poista levy erikseen", "Remove Folders from Library": "Poista kansiot kirjastosta", "That includes the photos in the folders inside them.": "Tämä sisältää niiden sisällä olevissa kansioissa olevat kuvat.", - "The photos stay in All Photos. Undo brings the albums back.": "Kuvat pysyvät kohdassa Kaikki kuvat. Kumoa palauttaa albumit." + "The photos stay in All Photos. Undo brings the albums back.": "Kuvat pysyvät kohdassa Kaikki kuvat. Kumoa palauttaa albumit.", + "Another library was opened since this window appeared: nothing was changed": "Toinen kirjasto avattiin tämän ikkunan ilmestymisen jälkeen: mitään ei muutettu" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index f67eec540f3..4387081fe48 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3625,5 +3625,6 @@ "One of them is a whole disk: remove a disk by itself": "L'un d'eux est un disque entier : retirez un disque séparément", "Remove Folders from Library": "Retirer les dossiers de la bibliothèque", "That includes the photos in the folders inside them.": "Cela inclut les photos des dossiers qu'ils contiennent.", - "The photos stay in All Photos. Undo brings the albums back.": "Les photos restent dans Toutes les photos. Vous pourrez annuler la suppression des albums." + "The photos stay in All Photos. Undo brings the albums back.": "Les photos restent dans Toutes les photos. Vous pourrez annuler la suppression des albums.", + "Another library was opened since this window appeared: nothing was changed": "Une autre bibliothèque a été ouverte depuis l’apparition de cette fenêtre : rien n’a été modifié" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 3c775154080..7981ca3d143 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2413,5 +2413,6 @@ "One of them is a whole disk: remove a disk by itself": "Salah satunya adalah satu disk penuh: keluarkan disk secara terpisah", "Remove Folders from Library": "Keluarkan folder dari pustaka", "That includes the photos in the folders inside them.": "Ini mencakup foto di dalam folder yang ada di dalamnya.", - "The photos stay in All Photos. Undo brings the albums back.": "Foto tetap ada di Semua foto. Urungkan mengembalikan album." + "The photos stay in All Photos. Undo brings the albums back.": "Foto tetap ada di Semua foto. Urungkan mengembalikan album.", + "Another library was opened since this window appeared: nothing was changed": "Pustaka lain telah dibuka setelah jendela ini muncul: tidak ada yang diubah" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 7bf4860e864..0ff0d22ffea 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2606,5 +2606,6 @@ "One of them is a whole disk: remove a disk by itself": "Uno di essi è un disco intero: rimuovi un disco da solo", "Remove Folders from Library": "Rimuovi cartelle dalla libreria", "That includes the photos in the folders inside them.": "Sono incluse le foto nelle cartelle al loro interno.", - "The photos stay in All Photos. Undo brings the albums back.": "Le foto restano in Tutte le foto. Annulla ripristina gli album." + "The photos stay in All Photos. Undo brings the albums back.": "Le foto restano in Tutte le foto. Annulla ripristina gli album.", + "Another library was opened since this window appeared: nothing was changed": "Nel frattempo è stata aperta un'altra libreria: non è stato modificato nulla" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index b1733d01aa6..f5806de0176 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2441,5 +2441,6 @@ "Remove Folders from Library": "フォルダをライブラリから除去", "That includes the photos in the folders inside them.": "その中にあるフォルダの写真も含まれます。", "The photos stay in All Photos. Undo brings the albums back.": "写真は「すべての写真」に残ります。「取り消す」でアルバムが戻ります。", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "写真は「すべての写真」に残ります。フォルダを削除すると、その中のアルバムも削除されます。「取り消す」で元に戻せます。" + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "写真は「すべての写真」に残ります。フォルダを削除すると、その中のアルバムも削除されます。「取り消す」で元に戻せます。", + "Another library was opened since this window appeared: nothing was changed": "このウィンドウが表示された後に別のライブラリが開かれました。何も変更していません" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e7cc47b970a..20e697194ab 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3693,6 +3693,7 @@ "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Another library was opened since this window appeared: nothing was changed": "ამ ფანჯრის გამოჩენის შემდეგ სხვა ბიბლიოთეკა გაიხსნა: არაფერი შეცვლილა", "Choose one album to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი ალბომი", "Choose one folder to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი საქაღალდე", "Choose one folder to synchronize it": "სინქრონიზაციისთვის აირჩიეთ ერთი საქაღალდე", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index db202d19a8d..b8f3ed56d6a 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2365,5 +2365,6 @@ "Remove Folders from Library": "Usuń foldery z biblioteki", "That includes the photos in the folders inside them.": "Obejmuje to też zdjęcia w folderach wewnątrz nich.", "The photos stay in All Photos. Undo brings the albums back.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Cofnij przywróci albumy.", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Usunięcie folderu usuwa też jego albumy. Możesz to cofnąć." + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Usunięcie folderu usuwa też jego albumy. Możesz to cofnąć.", + "Another library was opened since this window appeared: nothing was changed": "Od pojawienia się tego okna otwarto inną bibliotekę: nic nie zostało zmienione" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index cfeef163de5..87be063522c 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2287,5 +2287,6 @@ "Remove Folders from Library": "Remover pastas da biblioteca", "That includes the photos in the folders inside them.": "Isso inclui as fotos das pastas dentro delas.", "The photos stay in All Photos. Undo brings the albums back.": "As fotos continuam em Todas as fotos. Desfazer traz os álbuns de volta.", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "As fotos continuam em Todas as fotos. Excluir uma pasta também exclui os álbuns dela. Você pode desfazer." + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "As fotos continuam em Todas as fotos. Excluir uma pasta também exclui os álbuns dela. Você pode desfazer.", + "Another library was opened since this window appeared: nothing was changed": "Outra biblioteca foi aberta depois que esta janela apareceu: nada foi alterado" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 38a5a86169e..d7677cafb5f 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2648,5 +2648,6 @@ "One of them is a whole disk: remove a disk by itself": "Одна из них — целый диск: убирайте диск отдельно", "Remove Folders from Library": "Убрать папки из библиотеки", "That includes the photos in the folders inside them.": "Сюда входят и фото во вложенных в них папках.", - "The photos stay in All Photos. Undo brings the albums back.": "Фото остаются во «Всех фото». Команда «Отменить» вернёт альбомы." + "The photos stay in All Photos. Undo brings the albums back.": "Фото остаются во «Всех фото». Команда «Отменить» вернёт альбомы.", + "Another library was opened since this window appeared: nothing was changed": "После появления этого окна была открыта другая библиотека: ничего не изменено" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 86a0c048d1d..a270ef5d953 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2502,5 +2502,6 @@ "One of them is a whole disk: remove a disk by itself": "En av dem är en hel disk: ta bort en disk för sig", "Remove Folders from Library": "Ta bort mappar från biblioteket", "That includes the photos in the folders inside them.": "Det omfattar fotona i mapparna inuti dem.", - "The photos stay in All Photos. Undo brings the albums back.": "Fotona finns kvar i Alla foton. Ångra tar tillbaka albumen." + "The photos stay in All Photos. Undo brings the albums back.": "Fotona finns kvar i Alla foton. Ångra tar tillbaka albumen.", + "Another library was opened since this window appeared: nothing was changed": "Ett annat bibliotek har öppnats sedan det här fönstret visades: ingenting ändrades" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index f370daeb08d..cd62286c1a8 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2439,5 +2439,6 @@ "Remove Folders from Library": "Вилучити теки з бібліотеки", "That includes the photos in the folders inside them.": "Також включаються фото у вкладених у них теках.", "The photos stay in All Photos. Undo brings the albums back.": "Фото залишаються в «Усіх фото». Скасування повертає альбоми.", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення теки видаляє й її альбоми. Це можна скасувати." + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення теки видаляє й її альбоми. Це можна скасувати.", + "Another library was opened since this window appeared: nothing was changed": "Після появи цього вікна було відкрито іншу бібліотеку: нічого не змінено" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index d62e349ab98..470f83f89b9 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2727,5 +2727,6 @@ "One of them is a whole disk: remove a disk by itself": "Một trong số đó là cả một ổ đĩa: hãy gỡ ổ đĩa riêng", "Remove Folders from Library": "Gỡ thư mục khỏi thư viện", "That includes the photos in the folders inside them.": "Bao gồm cả ảnh trong các thư mục bên trong chúng.", - "The photos stay in All Photos. Undo brings the albums back.": "Ảnh vẫn ở trong Tất cả ảnh. Hoàn tác sẽ đưa album trở lại." + "The photos stay in All Photos. Undo brings the albums back.": "Ảnh vẫn ở trong Tất cả ảnh. Hoàn tác sẽ đưa album trở lại.", + "Another library was opened since this window appeared: nothing was changed": "Một thư viện khác đã được mở kể từ khi cửa sổ này xuất hiện: chưa thay đổi mục nào" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 15f88dfcf15..dc577404479 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2442,5 +2442,6 @@ "Remove Folders from Library": "从图库中移除文件夹", "That includes the photos in the folders inside them.": "其中也包括这些文件夹内各子文件夹中的照片。", "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在“所有照片”中。撤销可恢复这些相册。", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在“所有照片”中。删除文件夹也会删除其中的相册。可以撤销。" + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在“所有照片”中。删除文件夹也会删除其中的相册。可以撤销。", + "Another library was opened since this window appeared: nothing was changed": "此窗口出现后打开了另一个图库:未更改任何内容" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index eb9ab8d6f6c..25292685d35 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2443,5 +2443,6 @@ "Remove Folders from Library": "從照片庫移除資料夾", "That includes the photos in the folders inside them.": "其中也包括這些資料夾內各子資料夾中的照片。", "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在「所有照片」中。復原即可還原這些相簿。", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在「所有照片」中。刪除資料夾也會刪除其中的相簿。可以復原。" + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在「所有照片」中。刪除資料夾也會刪除其中的相簿。可以復原。", + "Another library was opened since this window appeared: nothing was changed": "此視窗出現後開啟了另一個照片庫:未變更任何內容" } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6cfbc4e1bde..c9bbde34aeb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -448,7 +448,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String { Dialog::RenamePerson { .. } => "Rename Person", Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag", Dialog::KeywordTag { .. } => "Edit Keyword Tag", - Dialog::Several(s) => crate::panels::side_select::several_title(s), + Dialog::Several { rows, .. } => crate::panels::side_select::several_title(rows), Dialog::DeleteKeyword { .. } => "Delete Keyword", Dialog::MoveKeyword { .. } => "Merge Keywords", Dialog::KeywordSet { .. } => "Edit Keyword Set", @@ -580,7 +580,7 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s Dialog::FaceModel { info, .. } if !informational && info["download"].is_string() => "Download", Dialog::FaceModel { .. } if !informational => "Install", Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } => "Delete", - Dialog::Several(s) => crate::panels::side_select::several_button(s), + Dialog::Several { rows, .. } => crate::panels::side_select::several_button(rows), Dialog::SaveEffect { .. } | Dialog::NewAlbum { .. } | Dialog::NewSmartAlbum { .. } @@ -741,7 +741,7 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> } // several rows: one that can't be deleted or removed refuses them all; `several_run` // already toasted the reason, which says which - Err(_) if matches!(dlg, Dialog::Several(_)) => closed = true, + Err(_) if matches!(dlg, Dialog::Several { .. }) => closed = true, // the SAM 3 dialog stays open to show the download (or why it can't start) Err(e) if matches!(dlg, Dialog::SamModel { .. }) => { if let Dialog::SamModel { error, .. } = dlg { @@ -2143,7 +2143,7 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m Dialog::KeywordTag { .. } => keyword_tag_body(app, ui, t, confirm, dlg), Dialog::KeywordSet { .. } => keyword_set_body(ui, t, confirm, dlg), Dialog::MoveKeyword { .. } => move_keyword_body(ui, t, dlg), - Dialog::Several(s) => crate::panels::side_select::several_body(ui, s, &app.session.catalog), + Dialog::Several { rows, .. } => crate::panels::side_select::several_body(ui, rows, &app.session.catalog), Dialog::DeleteKeyword { .. } => delete_keyword_body(ui, t, dlg), Dialog::SaveEffect { name, group, fields, amount, brush } => { if crate::panels::mask_effects::save_body(app, ui, name, group, fields, amount, brush) { diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index b705d34b61e..99394ba4e44 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -144,7 +144,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::side_select::several_run(app, s), + Dialog::Several { rows, library } => crate::panels::side_select::several_run(app, rows, *library), Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})), Dialog::KeywordSet { replaces, name, slots, as_new } => { use lightcraft_catalog::keywords::same; diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rs index dce36a03c25..11067230577 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -191,7 +191,7 @@ pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle { match dlg { Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } // (every several-rows action deletes or removes) - | Dialog::Several(_) => { + | Dialog::Several { .. } => { ConfirmStyle::Plain } _ if only_shows(dlg) => ConfirmStyle::Plain, diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 10e2492b08e..dce7928d9e0 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -167,7 +167,8 @@ fn the_welcome_tour_is_translated_in_every_catalog() { /// one without a translation shows the English. #[test] fn the_texts_for_several_chosen_sidebar_rows_are_translated_in_every_language() { - const TEXTS: [&str; 16] = [ + const TEXTS: [&str; 17] = [ + "Another library was opened since this window appeared: nothing was changed", "Choose one album to rename it", "Choose one folder to rename it", "Choose one folder to synchronize it", diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs index 1d54044cb70..6bb0c93ce17 100644 --- a/crates/ui-egui/src/panels/side_select.rs +++ b/crates/ui-egui/src/panels/side_select.rs @@ -62,6 +62,12 @@ pub enum Several { RemoveFolders { paths: Vec, count: usize }, } +/// The question about `rows` as it is asked now: bound to the library that is open. Album ids are numbered per library, and a keyword of +/// that name or a folder of that path can be another one in a library that opens later, so [`several_run`] refuses it there. +fn question(app: &LightcraftApp, rows: Several) -> Dialog { + Dialog::Several { rows, library: app.session.library_generation() } +} + fn same_id(a: &u64, b: &u64) -> bool { a == b } @@ -139,7 +145,7 @@ pub(crate) fn keys_frame(app: &mut LightcraftApp, ctx: &egui::Context) { pub(crate) fn delete_asked(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { let Some(list) = app.ui.side.keys else { return false }; let dialog = match list { - SideList::Albums => Some(albums_shown(app)).filter(|ids| ids.len() > 1).map(|ids| delete_albums_dialog(&ids)), + SideList::Albums => Some(albums_shown(app)).filter(|ids| ids.len() > 1).map(|ids| delete_albums_dialog(app, &ids)), SideList::Keywords => Some(app.session.filter.keywords_wanted()).filter(|k| k.len() > 1).map(|k| delete_keywords_dialog(app, &k)), SideList::KeywordList => Some(list_picked(app)).filter(|k| k.len() > 1).map(|k| delete_keywords_dialog(app, &k)), SideList::Folders => { @@ -181,7 +187,7 @@ pub(crate) fn outline(app: &LightcraftApp, ui: &egui::Ui, list: SideList, chosen fn remove_folders_dialog(app: &LightcraftApp, paths: &[String]) -> Dialog { let f = lightcraft_catalog::Filter { library_folders: paths.to_vec(), ..Default::default() }; let count = app.session.catalog.query(&f, &lightcraft_catalog::Sort::default()).len(); - Dialog::Several(Several::RemoveFolders { paths: paths.to_vec(), count }) + question(app, Several::RemoveFolders { paths: paths.to_vec(), count }) } /// A new frame of the left panel: the rows of the last one are what a click now is on. @@ -296,14 +302,14 @@ pub(crate) fn albums_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, ids: &[u64 let delete = item(ui, "albums:delete", crate::i18n::tr_format!("Delete {n} Albums…", n = n), true) .on_hover_text(crate::i18n::tr("The photos stay in All Photos. Undo brings the albums back.")); if delete.clicked() { - app.ui.dialog = Some(delete_albums_dialog(ids)); + app.ui.dialog = Some(delete_albums_dialog(app, ids)); ui.close(); } } /// The confirmation for deleting several albums. -pub(crate) fn delete_albums_dialog(ids: &[u64]) -> Dialog { - Dialog::Several(Several::DeleteAlbums { ids: ids.to_vec() }) +pub(crate) fn delete_albums_dialog(app: &LightcraftApp, ids: &[u64]) -> Dialog { + question(app, Several::DeleteAlbums { ids: ids.to_vec() }) } // ---- Folders (of the library) @@ -470,7 +476,7 @@ pub(crate) fn delete_keywords_dialog(app: &LightcraftApp, keywords: &[String]) - let paths: Vec = keywords.iter().map(|k| cat.keyword_path(k).unwrap_or_else(|| k.clone())).collect(); let has = |p: &lightcraft_catalog::Photo| p.meta.keywords.iter().any(|k| paths.iter().any(|g| lightcraft_catalog::keywords::is_under(k, g))); let count = cat.photos().filter(|p| p.in_library() && has(p)).count(); - Dialog::Several(Several::DeleteKeywords { keywords: paths, count }) + question(app, Several::DeleteKeywords { keywords: paths, count }) } // ---- The Keyword List (right panel) @@ -584,9 +590,15 @@ fn names(ui: &mut egui::Ui, all: Vec) { } } -/// Do what the confirmation asked. A refusal is toasted by `act` (the reason, for as long as any -/// refusal stays), and the `Err` keeps the whole error for the control channel. -pub(crate) fn several_run(app: &mut LightcraftApp, s: &Several) -> Result { +/// Do what the confirmation asked, in the library it was asked in: once another one has opened, its ids, names and paths mean something else +/// there (or nothing), so nothing is changed. A refusal is toasted (the reason, for as long as any refusal stays) by this or by `act_told`, +/// and the `Err` keeps the whole error for the control channel. +pub(crate) fn several_run(app: &mut LightcraftApp, s: &Several, library: u64) -> Result { + if library != app.session.library_generation() { + let why = crate::i18n::tr("Another library was opened since this window appeared: nothing was changed").to_string(); + app.ui.toast = Some((why.clone(), app.tick_now() + crate::REFUSAL_SECONDS, None)); + return Err(why); + } match s { Several::DeleteAlbums { ids } => app.act_told("album.delete", json!({"ids": ids})), Several::DeleteKeywords { keywords, .. } => { diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 65e13b808a8..3c9676f0e0e 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -143,7 +143,12 @@ pub enum Dialog { parent: Option, }, /// Delete or remove several sidebar rows at once (albums, keywords, folders), after asking. - Several(crate::panels::side_select::Several), + Several { + rows: crate::panels::side_select::Several, + /// The library the question was asked in (`Session::library_generation`): album ids are numbered per library, and a keyword + /// of that name or a folder of that path can be another one in a library that opened since, so OK changes nothing there. + library: u64, + }, /// Delete a keyword from every photo and the keyword list, after asking. DeleteKeyword { keyword: String, diff --git a/crates/ui-egui/src/tests/dialog_primary.rs b/crates/ui-egui/src/tests/dialog_primary.rs index e4df6cd674e..8987f05486a 100644 --- a/crates/ui-egui/src/tests/dialog_primary.rs +++ b/crates/ui-egui/src/tests/dialog_primary.rs @@ -49,10 +49,8 @@ fn constructive_confirms_are_primary_and_destructive_ones_plain() { use crate::state::Dialog; assert_eq!(confirm_style(&Dialog::AutoStack { gap: 60.0 }), ConfirmStyle::Primary); assert_eq!(confirm_style(&Dialog::ConfirmDelete { count: 3 }), ConfirmStyle::Plain); - assert_eq!( - confirm_style(&Dialog::Several(crate::panels::side_select::Several::DeleteKeywords { keywords: vec!["a".into()], count: 1 })), - ConfirmStyle::Plain - ); + let rows = crate::panels::side_select::Several::DeleteKeywords { keywords: vec!["a".into()], count: 1 }; + assert_eq!(confirm_style(&Dialog::Several { rows, library: 0 }), ConfirmStyle::Plain); // a dialog that only shows something has nothing to confirm: its Close is plain assert_eq!(confirm_style(&Dialog::About), ConfirmStyle::Plain); } diff --git a/crates/ui-egui/src/tests/multi_select.rs b/crates/ui-egui/src/tests/multi_select.rs index 09465ab42b9..716712197b0 100644 --- a/crates/ui-egui/src/tests/multi_select.rs +++ b/crates/ui-egui/src/tests/multi_select.rs @@ -201,7 +201,7 @@ fn the_menu_of_several_albums_deletes_them_after_asking_as_one_step() { assert!(!has(&h, &format!("albumDelete:{c}")), "not the single album's Delete"); let undo = h.app.session.undo.len(); click(&mut h, "sideMenu:albums:delete"); - assert_eq!(h.app.ui.dialog, Some(Dialog::Several(Several::DeleteAlbums { ids: vec![a, c] }))); + assert_eq!(h.app.ui.dialog, several_question(&h, Several::DeleteAlbums { ids: vec![a, c] })); ask(&mut h, "ui.dialog.cancel", json!({})); let exists = |h: &Headless, id: u64| h.app.session.catalog.album(AlbumId(id)).is_some(); assert!(exists(&h, a) && exists(&h, c), "Cancel keeps them"); @@ -391,7 +391,7 @@ fn cmd_click_shows_several_folders_and_the_menu_removes_them_after_asking() { click(&mut h, "sideMenu:folders:remove"); assert_eq!( h.app.ui.dialog, - Some(Dialog::Several(Several::RemoveFolders { paths: vec!["/pics/trip".to_string(), "/pics/work".to_string()], count: 3 })) + several_question(&h, Several::RemoveFolders { paths: vec!["/pics/trip".to_string(), "/pics/work".to_string()], count: 3 }) ); let undo = h.app.session.undo.len(); click(&mut h, "button:dialogOk"); @@ -460,7 +460,7 @@ fn the_keyword_list_deletes_several_after_one_question() { click(&mut h, "keywordList:delete"); assert_eq!( h.app.ui.dialog, - Some(Dialog::Several(Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string()], count: 2 })) + several_question(&h, Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string()], count: 2 }) ); ask(&mut h, "ui.dialog.cancel", json!({})); assert!(h.app.session.catalog.has_keyword("Sel K1"), "Cancel kept them"); @@ -516,7 +516,12 @@ fn dragging_one_of_several_keywords_nests_them_all() { } fn several_dialog(h: &Headless) -> bool { - matches!(h.app.ui.dialog, Some(Dialog::Several(_))) + matches!(h.app.ui.dialog, Some(Dialog::Several { .. })) +} + +/// The question about `rows` as asked in the library that is open. +fn several_question(h: &Headless, rows: Several) -> Option { + Some(Dialog::Several { rows, library: h.app.session.library_generation() }) } #[test] @@ -534,7 +539,7 @@ fn delete_asks_about_several_rows_just_chosen_and_is_the_photos_otherwise() { cmd_click(&mut h, &row(c)); assert!(has(&h, &format!("highlight:album:{a}"))); ask(&mut h, "ui.key", json!({"key": "Backspace"})); - assert_eq!(h.app.ui.dialog, Some(Dialog::Several(Several::DeleteAlbums { ids: vec![a, c] }))); + assert_eq!(h.app.ui.dialog, several_question(&h, Several::DeleteAlbums { ids: vec![a, c] })); ask(&mut h, "ui.dialog.cancel", json!({})); assert!(h.app.session.catalog.album(AlbumId(a)).is_some(), "asking deleted nothing"); // forward Delete too @@ -558,7 +563,7 @@ fn delete_asks_about_several_keywords_picked_in_the_keyword_list() { ask(&mut h, "ui.key", json!({"key": "Backspace"})); assert_eq!( h.app.ui.dialog, - Some(Dialog::Several(Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string(), "Sel K3".to_string()], count: 2 })) + several_question(&h, Several::DeleteKeywords { keywords: vec!["Sel K1".to_string(), "Sel K2".to_string(), "Sel K3".to_string()], count: 2 }) ); click(&mut h, "button:dialogOk"); assert!(!h.app.session.catalog.has_keyword("Sel K2")); @@ -669,6 +674,116 @@ fn a_refused_question_about_several_rows_closes_its_dialog() { assert!(!several_dialog(&h), "the question closes with its refusal: {:?}", h.app.ui.dialog); } +/// A library folder that goes with the test, however it ends. +struct Scratch(std::path::PathBuf); +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Another library, empty, opened as the menu bar or an agent does while a question is up. +fn open_another_library(h: &mut Headless, tag: &str) -> Scratch { + let dir = Scratch(std::env::temp_dir().join(format!("lc-multi-select-{tag}-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + h.app.session.open_library(&dir.0, false).unwrap(); + h.settle(SETTLE); + dir +} + +/// The question about two albums, up in the demo library. +fn question_about_two_albums(h: &mut Headless) -> [u64; 2] { + let ([a, _, c, _], _) = four_albums(h); + click(h, &row(a)); + cmd_click(h, &row(c)); + right_click(h, &row(c)); + click(h, "sideMenu:albums:delete"); + assert!(several_dialog(h), "{:?}", h.app.ui.dialog); + [a, c] +} + +/// Another library with an album under each number the question holds (album numbers are per library). +fn albums_numbered_like(h: &mut Headless, asked: [u64; 2]) { + let top = asked[0].max(asked[1]); + let made: Vec = (1..=top).map(|n| run(h, "album.create", json!({"name": format!("Other {n}")}))["id"].as_u64().unwrap()).collect(); + assert!(asked.iter().all(|id| made.contains(id)), "{asked:?} name albums there too: {made:?}"); +} + +/// A question asked in one library is not answered in another: album numbers are per library, so +/// once another library has opened the same numbers name other albums there, and OK would delete those. +#[test] +fn a_question_about_several_albums_is_refused_once_another_library_opened() { + let mut h = app("info"); + let asked = question_about_two_albums(&mut h); + let _other = open_another_library(&mut h, "albums-button"); + albums_numbered_like(&mut h, asked); + click(&mut h, "button:dialogOk"); + for id in asked { + assert!(h.app.session.catalog.album(AlbumId(id)).is_some(), "album {id} of the library that opened is still there"); + } + assert!(!several_dialog(&h), "the refused question closes: {:?}", h.app.ui.dialog); + let said = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(said.contains("Another library was opened"), "the toast says why: {said:?}"); +} + +/// The control channel's confirm of a question that another library made stale answers with the +/// reason, and changes nothing. +#[test] +fn a_confirm_of_several_albums_is_refused_with_the_reason_once_another_library_opened() { + let mut h = app("info"); + let asked = question_about_two_albums(&mut h); + let _other = open_another_library(&mut h, "albums-control"); + albums_numbered_like(&mut h, asked); + let r = h.request("ui.dialog.confirm", json!({}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or_default().contains("Another library was opened"), "{r}"); + for id in asked { + assert!(h.app.session.catalog.album(AlbumId(id)).is_some(), "album {id} of the library that opened is still there"); + } +} + +/// A keyword with the name the question holds is another keyword in the library that opened since. +#[test] +fn a_question_about_several_keywords_is_refused_once_another_library_opened() { + let (mut h, _) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K2"); + click(&mut h, "keywordList:delete"); + assert!(several_dialog(&h), "{:?}", h.app.ui.dialog); + let _other = open_another_library(&mut h, "keywords"); + for name in ["Sel K1", "Sel K2"] { + run(&mut h, "keyword.create", json!({"name": name})); + } + click(&mut h, "button:dialogOk"); + assert!( + h.app.session.catalog.has_keyword("Sel K1") && h.app.session.catalog.has_keyword("Sel K2"), + "the keywords of the library that opened stay" + ); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); +} + +/// A folder with the path the question holds is another folder in the library that opened since. +#[test] +fn a_question_about_several_folders_is_refused_once_another_library_opened() { + use lightcraft_catalog::{Op, Photo, Source}; + let mut h = folders_app(&["/pics/trip/a.jpg", "/pics/home/b.jpg", "/pics/work/c.jpg"]); + click(&mut h, "libraryFolderToggle:/pics"); + click(&mut h, "source:libfolder:/pics/trip"); + cmd_click(&mut h, "source:libfolder:/pics/work"); + right_click(&mut h, "source:libfolder:/pics/work"); + click(&mut h, "sideMenu:folders:remove"); + assert!(several_dialog(&h), "{:?}", h.app.ui.dialog); + let _other = open_another_library(&mut h, "folders"); + for path in ["/pics/trip/x.jpg", "/pics/work/y.jpg"] { + let id = h.app.session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + click(&mut h, "button:dialogOk"); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.in_library()).count(), 2, "the photos of the library that opened stay in it"); + assert!(!several_dialog(&h), "{:?}", h.app.ui.dialog); +} + /// A keyword that is gone is not picked any more: the row left alone has its own menu. #[test] fn a_keyword_that_is_gone_is_not_picked_any_more() { diff --git a/docs/whats-new.md b/docs/whats-new.md index 5dfb8e5b137..0dfff02b41d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -350,8 +350,9 @@ telling which album is meant. - Right-click one of several rows chosen to act on them all, as one step to undo: move albums into a folder, export them, or delete them; give folders a color label or remove them from the library; give keywords to the selected - photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes. - Right-click a row that is not among them and you get that row's own menu; the others stay chosen. + photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes; if + another library is opened while it asks, OK changes nothing and says so. Right-click a row that is not among them + and you get that row's own menu; the others stay chosen. - Dragging one of several albums or keywords moves them all (albums go into the folder they are dropped in or beside; dropped beside a row, the one you dragged is placed there and the others come into that folder). - Right after choosing several rows with Cmd or Shift, the Delete key asks about those rows. Click anywhere else, From f485fcf7f80640e0c5ac8f8e25aaf550b8cad32d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 5 Nov 2026 21:11:05 -0500 Subject: [PATCH 43/55] LR-BEHAV-MULTISELECT: deleting several shown albums in one call also moves the active photo into what is left The test of the engine change in #1153 (album.delete keeps the active photo in the grid when a shown album went) through the batch form this PR takes from #2757: album.delete {ids: [b, c]} with the album chosen last of three shown going with Beach. --- crates/engine/src/tests/multi_source.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/engine/src/tests/multi_source.rs b/crates/engine/src/tests/multi_source.rs index 9f6b0285b6c..62f8c85018e 100644 --- a/crates/engine/src/tests/multi_source.rs +++ b/crates/engine/src/tests/multi_source.rs @@ -671,3 +671,19 @@ fn deleting_one_of_several_shown_albums_moves_the_active_photo_into_what_is_left s.execute("album.delete", &json!({"id": b})).unwrap(); assert_eq!(s.active(), Some(PhotoId(ids[2]))); } + +#[test] +fn deleting_several_shown_albums_at_once_moves_the_active_photo_into_what_is_left() { + let mut s = Session::new(); + let (ids, a, b) = two_albums(&mut s); + let c = album(&mut s, "Cairo", &[ids[3]]); + s.execute("library.source", &json!({"kind": "album", "ids": [a, b, c]})).unwrap(); + // Given the active photo is in an album that goes only (Cairo, the one chosen last) + s.execute("library.select", &json!({"ids": [ids[3]]})).unwrap(); + // When Beach and Cairo are deleted in one call + s.execute("album.delete", &json!({"ids": [b, c]})).unwrap(); + // Then Alps is what the grid shows and the active photo is one of its photos + let left = shown(&mut s); + assert_eq!(left, vec![ids[0], ids[1]]); + assert!(s.active().is_some_and(|p| left.contains(&p.0)), "{:?}", s.active()); +} From 43bd6870fe8f5a2903f5ade283fb0c4d59ca0ba0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 6 Nov 2026 07:23:59 -0500 Subject: [PATCH 44/55] docs: drop the stale 'later change' note for the sidebar clicks from What's New --- docs/whats-new.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index aa90a924f92..fc46d13a102 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -771,9 +771,9 @@ - `library.source` takes `ids` (albums) or `paths` (folders of the library, as `library.folders` lists them, not a browsed Local folder) and shows the photos of any of them, each once; `library.filter` takes `keywords`, `dates`, `libraryFolders` and `albums`. The single fields stay and count as one - more of them. `library.state` lists `albums` and `libraryFolders`. The sidebars' Cmd+click and Shift+click that use - this come in a later change. When the albums shown include a smart album, New Smart Album from Filter… is grayed out - and says why, as `album.createSmart` does. So does a filter that names a smart album. + more of them. `library.state` lists `albums` and `libraryFolders`. When the albums shown include a smart album, + New Smart Album from Filter… is grayed out and says why, as `album.createSmart` does. So does a filter that names a + smart album. - With View ▸ Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it: a photo that stops matching the rules of a smart album among them goes at once, unless another album shown has it. - `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does. Deleting a shown From ddb7391c039bf5eb87aedf69e442dc268840fb29 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 6 Nov 2026 07:24:06 -0500 Subject: [PATCH 45/55] docs: say exporting several chosen rows is not an undo step in What's New --- docs/whats-new.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index cbe57103c3f..19bb9effba3 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -348,11 +348,12 @@ - With several albums shown, Remove from Album is not offered and the Delete key is the photos' Delete once you click elsewhere (it asks first while Settings ▸ Confirm before moving photos to Recently Deleted is on), because there is no telling which album is meant. -- Right-click one of several rows chosen to act on them all, as one step to undo: move albums into a folder, export - them, or delete them; give folders a color label or remove them from the library; give keywords to the selected - photos, take them away, merge them or delete them. Deleting or removing several asks first and says what goes; if - another library is opened while it asks, OK changes nothing and says so. Right-click a row that is not among them - and you get that row's own menu; the others stay chosen. +- Right-click one of several rows chosen to act on them all: move albums into a folder, export them, or delete them; + give folders a color label or remove them from the library; give keywords to the selected photos, take them away, + merge them or delete them. Each change is one step to undo; exporting writes files and is not an undo step. + Deleting or removing several asks first and says what goes; if another library is opened while it asks, OK changes + nothing and says so. Right-click a row that is not among them and you get that row's own menu; the others stay + chosen. - Dragging one of several albums or keywords moves them all (albums go into the folder they are dropped in or beside; dropped beside a row, the one you dragged is placed there and the others come into that folder). - Right after choosing several rows with Cmd or Shift, the Delete key asks about those rows. Click anywhere else, From 524b5697cdfff973518179af8468a1937f85d566 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 6 Nov 2026 08:20:00 -0500 Subject: [PATCH 46/55] docs: say when a view cannot be saved as a smart album in What's New MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The entry said New Smart Album from Filter… is grayed out whenever the albums shown include a smart album. Session::view_save_refusal refuses only several albums shown with a smart one among them, or a filter that names a smart album; one smart album shown alone can be saved. album.createSmart reads the view, and so refuses it, only when `rules` is omitted. The entry now says both. Co-Authored-By: Claude --- docs/whats-new.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/whats-new.md b/docs/whats-new.md index 19bb9effba3..64d20ad6ea0 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -784,9 +784,10 @@ - `library.source` takes `ids` (albums) or `paths` (folders of the library, as `library.folders` lists them, not a browsed Local folder) and shows the photos of any of them, each once; `library.filter` takes `keywords`, `dates`, `libraryFolders` and `albums`. The single fields stay and count as one - more of them. `library.state` lists `albums` and `libraryFolders`. When the albums shown include a smart album, - New Smart Album from Filter… is grayed out and says why, as `album.createSmart` does. So does a filter that names a - smart album. + more of them. `library.state` lists `albums` and `libraryFolders`. New Smart Album from Filter… is grayed out and + says why when several albums are shown and one of them is a smart album, or when the filter names a smart album + (one smart album shown alone can still be saved). `album.createSmart` refuses the same views, but only when it is + called without `rules`: given `rules`, it does not look at the view. - With View ▸ Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it: a photo that stops matching the rules of a smart album among them goes at once, unless another album shown has it. - `library.filter` refuses an album that is not there (`no such album N`), as `library.source` does. Deleting a shown From 1a8c74ae079d5caaa88e024ba9d0b167f341a3c8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 22:43:14 -0400 Subject: [PATCH 47/55] LRC-LIB-LIBFOLDERS: Synchronize several folders at once, one after another MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several Folders rows chosen at once offer Synchronize N Folders…: one dialog scans them one after another under one row and says what changed in each, with one set of choices. Each folder with something to do then waits in the library lane as a Synchronize of its own, in the sidebar's order, removing, relinking or reading sidecars of only the photos its scan found. A folder inside another chosen one is taken in by it (and comes back if that one can't be synchronized); whole disks, folders not there and folders up to date are passed over. A waiting row names what it is about (Request::subject). --- crates/engine/src/activity.rs | 29 +- crates/engine/src/cmd/previews.rs | 2 +- crates/engine/src/tests/task_queue.rs | 2 +- crates/ui-egui/locales/cs-formats.json | 9 +- crates/ui-egui/locales/cs.json | 14 +- crates/ui-egui/locales/de-formats.json | 9 +- crates/ui-egui/locales/de.json | 14 +- crates/ui-egui/locales/es-formats.json | 9 +- crates/ui-egui/locales/es.json | 14 +- crates/ui-egui/locales/fi-formats.json | 9 +- crates/ui-egui/locales/fi.json | 14 +- crates/ui-egui/locales/fr-formats.json | 9 +- crates/ui-egui/locales/fr.json | 14 +- crates/ui-egui/locales/id-formats.json | 9 +- crates/ui-egui/locales/id.json | 14 +- crates/ui-egui/locales/it-formats.json | 9 +- crates/ui-egui/locales/it.json | 14 +- crates/ui-egui/locales/ja-formats.json | 9 +- crates/ui-egui/locales/ja.json | 14 +- crates/ui-egui/locales/ka-formats.json | 9 +- crates/ui-egui/locales/ka.json | 14 +- crates/ui-egui/locales/pl-formats.json | 9 +- crates/ui-egui/locales/pl.json | 14 +- crates/ui-egui/locales/pt-br-formats.json | 9 +- crates/ui-egui/locales/pt-br.json | 14 +- crates/ui-egui/locales/ru-formats.json | 9 +- crates/ui-egui/locales/ru.json | 14 +- crates/ui-egui/locales/sv-formats.json | 9 +- crates/ui-egui/locales/sv.json | 14 +- crates/ui-egui/locales/uk-formats.json | 9 +- crates/ui-egui/locales/uk.json | 14 +- crates/ui-egui/locales/vi-formats.json | 9 +- crates/ui-egui/locales/vi.json | 14 +- crates/ui-egui/locales/zh-hans-formats.json | 9 +- crates/ui-egui/locales/zh-hans.json | 14 +- crates/ui-egui/locales/zh-hant-formats.json | 9 +- crates/ui-egui/locales/zh-hant.json | 14 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/dialogs.rs | 15 +- crates/ui-egui/src/dialogs/confirm.rs | 1 + crates/ui-egui/src/dialogs/frame.rs | 1 + crates/ui-egui/src/dialogs/import/scan.rs | 2 +- crates/ui-egui/src/headless.rs | 1 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/activity.rs | 17 +- crates/ui-egui/src/panels/side_select.rs | 10 +- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/state/dialog.rs | 44 +++ crates/ui-egui/src/sync.rs | 376 +++++++++++++++++++- crates/ui-egui/src/tests/drop_import.rs | 6 +- crates/ui-egui/src/tests/sync.rs | 250 ++++++++++++- docs/background-tasks.md | 5 +- docs/control-protocol.md | 2 +- docs/gaps.md | 3 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 11 +- 58 files changed, 1105 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 45d0e59e04e..85bd2a49155 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -49,10 +49,13 @@ impl Lane { /// What a job was asked: the command and its parameters, with everything that depends on the moment (the /// selection, the photos in view) written out, so that running it later does the same work. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct Request { pub command: String, pub params: Value, + /// What it is about, for its row while it waits (a folder's name…; empty: nothing more than its label). It goes + /// with the request, so it is the same whenever the request is read again. + pub subject: String, } /// A task waiting in line ([`Activity::enqueue`]), as [`Activity::take_ready`] hands it over to be started. @@ -75,7 +78,7 @@ impl Waiting { done: 0, total: 0, unit: Unit::Count, - detail: String::new(), + detail: capped(&self.request.subject), cancellable: true, cancelling: false, age_ms: millis(self.queued.elapsed()), @@ -622,7 +625,7 @@ mod tests { } fn request(command: &str) -> Request { - Request { command: command.into(), params: serde_json::json!({}) } + Request { command: command.into(), params: serde_json::json!({}), ..Default::default() } } #[test] @@ -698,6 +701,22 @@ mod tests { assert!(a.waiting().is_empty() && !a.lane_waiting(Lane::Previews)); } + /// Given a request that says what it is about, then its waiting row's detail is that (capped), and a request + /// without one leaves the detail empty. + #[test] + fn a_waiting_task_names_what_it_is_about() { + let a = Activity::default(); + let running = a.start("import", "Importing", Cancel::Yes); + let about = |subject: &str| Request { subject: subject.into(), ..request("x") }; + a.enqueue("sync", "Synchronizing folder", about("photos/Garden")).unwrap(); + a.enqueue("sync", "Synchronizing folder", request("x")).unwrap(); + a.enqueue("sync", "Synchronizing folder", about(&"é".repeat(300))).unwrap(); + let details: Vec = a.waiting().iter().map(|t| t.detail.chars().count()).collect(); + assert_eq!(a.waiting()[0].detail, "photos/Garden"); + assert_eq!(details, vec![13, 0, 200]); + drop(running); + } + #[test] fn a_library_change_empties_the_line() { let a = Activity::default(); @@ -715,8 +734,8 @@ mod tests { #[test] fn each_frontend_starts_only_what_it_can_run_and_no_task_jumps_its_line() { let a = Activity::default(); - let app = |p: u64| Request { command: "app:import".into(), params: serde_json::json!({ "n": p }) }; - let engine = |p: u64| Request { command: "library.import".into(), params: serde_json::json!({ "n": p }) }; + let app = |p: u64| Request { command: "app:import".into(), params: serde_json::json!({ "n": p }), ..Default::default() }; + let engine = |p: u64| Request { command: "library.import".into(), params: serde_json::json!({ "n": p }), ..Default::default() }; let (first, _) = a.enqueue("import", "Importing", app(1)).unwrap(); let (second, _) = a.enqueue("import", "Importing", engine(2)).unwrap(); let (previews, _) = a.enqueue("previews", "Building previews", request("library.buildPreviews")).unwrap(); diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index fc59de61f8c..4673c568985 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -259,7 +259,7 @@ fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> params.remove(key); } params.insert("ids".into(), ids.iter().map(|id| id.0).collect()); - Request { command: command.into(), params: Value::Object(params) } + Request { command: command.into(), params: Value::Object(params), ..Default::default() } } /// The refusal of a build while another runs, unless the call asks to `queue`. diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs index 939c2d30428..dec866a23f1 100644 --- a/crates/engine/src/tests/task_queue.rs +++ b/crates/engine/src/tests/task_queue.rs @@ -208,7 +208,7 @@ fn a_build_that_can_not_start_does_not_hold_up_the_line() { let mut s = Session::with_demo(); let ids = build_ids(&s, 1); let h = hold(&mut s); - let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}) }; + let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}), ..Default::default() }; s.activity.enqueue("previews", "Building previews", bad).unwrap(); s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); release(h); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index a159cd73557..3b31633cb1e 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -346,5 +346,12 @@ "Queued: it starts after {n} more": "Ve frontě: začne po dalších úlohách: {n}", "Left alone: {n} (synchronize again to review them)": "Ponecháno: {n} (pro kontrolu synchronizujte znovu)", "Starts after {n} more": "Začne po dalších úlohách: {n}", - "Remove from Queue: {label}": "Odebrat z fronty: {label}" + "Remove from Queue: {label}": "Odebrat z fronty: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Synchronizace složek ({n}) jedné po druhé: najdete je pod zvonkem", + "Too many tasks are waiting: only {n} more can wait in line": "Čeká příliš mnoho úloh: do fronty se vejde už jen {n}", + "Synchronize {n} Folders…": "Synchronizovat složky ({n})…", + "{n} new": "nové: {n}", + "{n} moved": "přesunuté: {n}", + "{n} missing": "chybějící: {n}", + "{n} with changed sidecars": "se změněným přidruženým souborem: {n}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 78dc1503330..1d57d285be1 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2472,7 +2472,6 @@ "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", "Choose one album to rename it": "Pro přejmenování vyberte jedno album", "Choose one folder to rename it": "Pro přejmenování vyberte jednu složku", - "Choose one folder to synchronize it": "Pro synchronizaci vyberte jednu složku", "Choose one keyword to create a keyword inside it": "Vyberte jedno klíčové slovo, abyste v něm vytvořili další", "Choose one keyword to edit it": "Pro úpravu vyberte jedno klíčové slovo", "Choose one keyword to rename it": "Pro přejmenování vyberte jedno klíčové slovo", @@ -2490,5 +2489,16 @@ "Queued: it starts when the task ahead of it ends": "Ve frontě: začne, až skončí úloha před ní", "Another library was opened: nothing was done": "Byla otevřena jiná knihovna: nic se neprovedlo", "Photos of the folder changed while it was read: nothing was done": "Fotografie ve složce se během čtení změnily: nic se neprovedlo", - "Starts next": "Začne jako další" + "Starts next": "Začne jako další", + "A whole disk: synchronize it by itself": "Celý disk: synchronizujte ho samostatně", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Uvést knihovnu do souladu s těmito složkami a složkami v nich, jednu po druhé:", + "Waiting to be scanned": "Čeká na prohledání", + "Up to date": "Aktuální", + "Nothing to do: the library is up to date with these folders": "Není co dělat: knihovna odpovídá těmto složkám", + "Synchronizing the folder: see it under the bell": "Synchronizace složky: najdete ji pod zvonkem", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Najde, co se v každé z těchto složek na disku změnilo, a pak s nimi knihovnu postupně sladí", + "Synchronize Folders": "Synchronizovat složky", + "Can't be synchronized with the others: synchronize it by itself": "Nelze synchronizovat s ostatními: synchronizujte ji samostatně", + "Nothing to do with the choices ticked": "Se zaškrtnutými volbami není co dělat", + "Nothing was synchronized": "Nic nebylo synchronizováno" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 8c5289dfa01..814d2ce9ece 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "In der Warteschlange: startet nach {n} weiteren", "Left alone: {n} (synchronize again to review them)": "Unangetastet: {n} (zum Prüfen erneut synchronisieren)", "Starts after {n} more": "Startet nach {n} weiteren", - "Remove from Queue: {label}": "Aus der Warteschlange entfernen: {label}" + "Remove from Queue: {label}": "Aus der Warteschlange entfernen: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "{n} Ordner werden nacheinander synchronisiert: siehe unter der Glocke", + "Too many tasks are waiting: only {n} more can wait in line": "Zu viele Aufgaben warten: nur noch {n} passen in die Warteschlange", + "Synchronize {n} Folders…": "{n} Ordner synchronisieren…", + "{n} new": "{n} neu", + "{n} moved": "{n} verschoben", + "{n} missing": "{n} fehlend", + "{n} with changed sidecars": "{n} mit geänderter Begleitdatei" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e1b69e8022a..ae65360ac88 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3507,7 +3507,6 @@ "Get Started": "Loslegen", "Choose one album to rename it": "Wähle ein einzelnes Album, um es umzubenennen", "Choose one folder to rename it": "Wähle einen einzelnen Ordner, um ihn umzubenennen", - "Choose one folder to synchronize it": "Wähle einen einzelnen Ordner, um ihn zu synchronisieren", "Choose one keyword to create a keyword inside it": "Wähle ein einzelnes Stichwort, um darin ein Stichwort zu erstellen", "Choose one keyword to edit it": "Wähle ein einzelnes Stichwort, um es zu bearbeiten", "Choose one keyword to rename it": "Wähle ein einzelnes Stichwort, um es umzubenennen", @@ -3525,5 +3524,16 @@ "Queued: it starts when the task ahead of it ends": "In der Warteschlange: startet, wenn die Aufgabe davor endet", "Another library was opened: nothing was done": "Eine andere Bibliothek wurde geöffnet: es wurde nichts getan", "Photos of the folder changed while it was read: nothing was done": "Fotos des Ordners haben sich beim Lesen geändert: es wurde nichts getan", - "Starts next": "Startet als Nächstes" + "Starts next": "Startet als Nächstes", + "A whole disk: synchronize it by itself": "Eine ganze Festplatte: einzeln synchronisieren", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Die Bibliothek nacheinander mit diesen Ordnern und den Ordnern darin abgleichen:", + "Waiting to be scanned": "Wartet auf die Suche", + "Up to date": "Aktuell", + "Nothing to do: the library is up to date with these folders": "Nichts zu tun: Die Bibliothek ist mit diesen Ordnern auf dem neuesten Stand", + "Synchronizing the folder: see it under the bell": "Ordner wird synchronisiert: siehe unter der Glocke", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Findet, was sich in jedem dieser Ordner auf der Festplatte geändert hat, und gleicht die Bibliothek nacheinander mit ihnen ab", + "Synchronize Folders": "Ordner synchronisieren", + "Can't be synchronized with the others: synchronize it by itself": "Nicht zusammen mit den anderen synchronisierbar: einzeln synchronisieren", + "Nothing to do with the choices ticked": "Mit den gewählten Optionen ist nichts zu tun", + "Nothing was synchronized": "Nichts wurde synchronisiert" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 71eaf8e8322..e8906273f9d 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "En cola: empieza tras {n} más", "Left alone: {n} (synchronize again to review them)": "Sin tocar: {n} (sincroniza de nuevo para revisarlos)", "Starts after {n} more": "Empieza tras {n} más", - "Remove from Queue: {label}": "Quitar de la cola: {label}" + "Remove from Queue: {label}": "Quitar de la cola: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Sincronizando {n} carpetas una tras otra: puedes verlo bajo la campana", + "Too many tasks are waiting: only {n} more can wait in line": "Hay demasiadas tareas esperando: plazas libres en la cola: {n}", + "Synchronize {n} Folders…": "Sincronizar {n} carpetas…", + "{n} new": "nuevas: {n}", + "{n} moved": "movidas: {n}", + "{n} missing": "faltan: {n}", + "{n} with changed sidecars": "con archivo complementario cambiado: {n}" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 34f7b73ae46..ccc3acd47e4 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2426,7 +2426,6 @@ "Get Started": "Empezar", "Choose one album to rename it": "Elige un solo álbum para cambiarle el nombre", "Choose one folder to rename it": "Elige una sola carpeta para cambiarle el nombre", - "Choose one folder to synchronize it": "Elige una sola carpeta para sincronizarla", "Choose one keyword to create a keyword inside it": "Elige una sola palabra clave para crear otra dentro de ella", "Choose one keyword to edit it": "Elige una sola palabra clave para editarla", "Choose one keyword to rename it": "Elige una sola palabra clave para cambiarle el nombre", @@ -2445,5 +2444,16 @@ "Queued: it starts when the task ahead of it ends": "En cola: empieza cuando termine la tarea anterior", "Another library was opened: nothing was done": "Se abrió otra biblioteca: no se hizo nada", "Photos of the folder changed while it was read: nothing was done": "Las fotos de la carpeta cambiaron mientras se leía: no se hizo nada", - "Starts next": "Empieza la siguiente" + "Starts next": "Empieza la siguiente", + "A whole disk: synchronize it by itself": "Un disco entero: sincronízalo por separado", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Poner la biblioteca al día con estas carpetas y las carpetas que contienen, una tras otra:", + "Waiting to be scanned": "En espera de exploración", + "Up to date": "Al día", + "Nothing to do: the library is up to date with these folders": "Nada que hacer: la biblioteca está al día con estas carpetas", + "Synchronizing the folder: see it under the bell": "Sincronizando la carpeta: puedes verlo bajo la campana", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Busca qué cambió en el disco en cada una de estas carpetas y después pone la biblioteca al día con ellas, una tras otra", + "Synchronize Folders": "Sincronizar carpetas", + "Can't be synchronized with the others: synchronize it by itself": "No se puede sincronizar con las demás: sincronízala por separado", + "Nothing to do with the choices ticked": "Nada que hacer con las opciones marcadas", + "Nothing was synchronized": "No se sincronizó nada" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index d86a947bb19..39645b6eb69 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -343,5 +343,12 @@ "Queued: it starts after {n} more": "Jonossa: alkaa {n} muun jälkeen", "Left alone: {n} (synchronize again to review them)": "Jätetty ennalleen: {n} (synkronoi uudelleen tarkistaaksesi)", "Starts after {n} more": "Alkaa {n} muun jälkeen", - "Remove from Queue: {label}": "Poista jonosta: {label}" + "Remove from Queue: {label}": "Poista jonosta: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Synkronoidaan {n} kansiota yksi kerrallaan: katso ne kellon alta", + "Too many tasks are waiting: only {n} more can wait in line": "Liian monta tehtävää odottaa: jonoon mahtuu vielä vain {n}", + "Synchronize {n} Folders…": "Synkronoi {n} kansiota…", + "{n} new": "uusia: {n}", + "{n} moved": "siirretty: {n}", + "{n} missing": "puuttuu: {n}", + "{n} with changed sidecars": "muuttuneita sivutiedostoja: {n}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 2cccefd5357..71e245a5510 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2383,7 +2383,6 @@ "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", "Choose one album to rename it": "Valitse yksi albumi nimetäksesi sen uudelleen", "Choose one folder to rename it": "Valitse yksi kansio nimetäksesi sen uudelleen", - "Choose one folder to synchronize it": "Valitse yksi kansio synkronoidaksesi sen", "Choose one keyword to create a keyword inside it": "Valitse yksi avainsana luodaksesi sen sisään avainsanan", "Choose one keyword to edit it": "Valitse yksi avainsana muokataksesi sitä", "Choose one keyword to rename it": "Valitse yksi avainsana nimetäksesi sen uudelleen", @@ -2401,5 +2400,16 @@ "Queued: it starts when the task ahead of it ends": "Jonossa: alkaa, kun sen edellä oleva tehtävä päättyy", "Another library was opened: nothing was done": "Toinen kirjasto avattiin: mitään ei tehty", "Photos of the folder changed while it was read: nothing was done": "Kansion valokuvat muuttuivat lukemisen aikana: mitään ei tehty", - "Starts next": "Alkaa seuraavaksi" + "Starts next": "Alkaa seuraavaksi", + "A whole disk: synchronize it by itself": "Kokonainen levy: synkronoi se erikseen", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Saata kirjasto ajan tasalle näiden kansioiden ja niiden sisällä olevien kansioiden kanssa, yksi kerrallaan:", + "Waiting to be scanned": "Odottaa skannausta", + "Up to date": "Ajan tasalla", + "Nothing to do: the library is up to date with these folders": "Ei tehtävää: kirjasto on ajan tasalla näiden kansioiden kanssa", + "Synchronizing the folder: see it under the bell": "Synkronoidaan kansiota: katso se kellon alta", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Etsi, mikä on muuttunut kussakin näistä kansioista levyllä, ja saata kirjasto sitten ajan tasalle niiden kanssa yksi kerrallaan", + "Synchronize Folders": "Synkronoi kansiot", + "Can't be synchronized with the others: synchronize it by itself": "Ei voi synkronoida muiden kanssa: synkronoi se erikseen", + "Nothing to do with the choices ticked": "Ei tehtävää valituilla asetuksilla", + "Nothing was synchronized": "Mitään ei synkronoitu" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 73eefe40c06..95e9b3740ef 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "En file : démarre après {n} autre(s) tâche(s)", "Left alone: {n} (synchronize again to review them)": "Laissés tels quels : {n} (synchronisez à nouveau pour les examiner)", "Starts after {n} more": "Démarre après {n} autre(s) tâche(s)", - "Remove from Queue: {label}": "Retirer de la file : {label}" + "Remove from Queue: {label}": "Retirer de la file : {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Synchronisation de {n} dossiers l'un après l'autre : voir sous la cloche", + "Too many tasks are waiting: only {n} more can wait in line": "Trop de tâches en attente : places restantes dans la file : {n}", + "Synchronize {n} Folders…": "Synchroniser {n} dossiers…", + "{n} new": "nouvelles : {n}", + "{n} moved": "déplacées : {n}", + "{n} missing": "manquantes : {n}", + "{n} with changed sidecars": "fichier annexe modifié : {n}" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 190e9dacd09..ac8e6690223 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3609,7 +3609,6 @@ "Get Started": "Commencer", "Choose one album to rename it": "Choisissez un seul album pour le renommer", "Choose one folder to rename it": "Choisissez un seul dossier pour le renommer", - "Choose one folder to synchronize it": "Choisissez un seul dossier pour le synchroniser", "Choose one keyword to create a keyword inside it": "Choisissez un seul mot-clé pour en créer un à l'intérieur", "Choose one keyword to edit it": "Choisissez un seul mot-clé pour le modifier", "Choose one keyword to rename it": "Choisissez un seul mot-clé pour le renommer", @@ -3627,5 +3626,16 @@ "Queued: it starts when the task ahead of it ends": "En file : démarre à la fin de la tâche précédente", "Another library was opened: nothing was done": "Une autre bibliothèque a été ouverte : rien n’a été fait", "Photos of the folder changed while it was read: nothing was done": "Les photos du dossier ont changé pendant la lecture : rien n’a été fait", - "Starts next": "Démarre ensuite" + "Starts next": "Démarre ensuite", + "A whole disk: synchronize it by itself": "Un disque entier : synchronisez-le à part", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Mettre la bibliothèque à jour avec ces dossiers et les dossiers qu'ils contiennent, l'un après l'autre :", + "Waiting to be scanned": "En attente d'analyse", + "Up to date": "À jour", + "Nothing to do: the library is up to date with these folders": "Rien à faire : la bibliothèque est à jour avec ces dossiers", + "Synchronizing the folder: see it under the bell": "Synchronisation du dossier : voir sous la cloche", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Cherche ce qui a changé sur le disque dans chacun de ces dossiers, puis met la bibliothèque à jour avec eux l'un après l'autre", + "Synchronize Folders": "Synchroniser les dossiers", + "Can't be synchronized with the others: synchronize it by itself": "Impossible de le synchroniser avec les autres : synchronisez-le à part", + "Nothing to do with the choices ticked": "Rien à faire avec les choix cochés", + "Nothing was synchronized": "Rien n'a été synchronisé" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index db9cc4f0c8b..2cefb0fb148 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -346,5 +346,12 @@ "Queued: it starts after {n} more": "Dalam antrean: dimulai setelah {n} lagi", "Left alone: {n} (synchronize again to review them)": "Dibiarkan: {n} (sinkronkan lagi untuk meninjau)", "Starts after {n} more": "Dimulai setelah {n} lagi", - "Remove from Queue: {label}": "Hapus dari antrean: {label}" + "Remove from Queue: {label}": "Hapus dari antrean: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Menyinkronkan {n} folder satu per satu: lihat di bawah lonceng", + "Too many tasks are waiting: only {n} more can wait in line": "Terlalu banyak tugas menunggu: hanya {n} lagi yang bisa menunggu dalam antrean", + "Synchronize {n} Folders…": "Sinkronkan {n} folder…", + "{n} new": "{n} baru", + "{n} moved": "{n} dipindahkan", + "{n} missing": "{n} hilang", + "{n} with changed sidecars": "{n} dengan sidecar berubah" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 79a448043be..d1df001356c 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2397,7 +2397,6 @@ "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", "Choose one album to rename it": "Pilih satu album untuk mengganti namanya", "Choose one folder to rename it": "Pilih satu folder untuk mengganti namanya", - "Choose one folder to synchronize it": "Pilih satu folder untuk menyinkronkannya", "Choose one keyword to create a keyword inside it": "Pilih satu kata kunci untuk membuat kata kunci di dalamnya", "Choose one keyword to edit it": "Pilih satu kata kunci untuk mengeditnya", "Choose one keyword to rename it": "Pilih satu kata kunci untuk mengganti namanya", @@ -2415,5 +2414,16 @@ "Queued: it starts when the task ahead of it ends": "Dalam antrean: dimulai saat tugas di depannya selesai", "Another library was opened: nothing was done": "Pustaka lain dibuka: tidak ada yang dilakukan", "Photos of the folder changed while it was read: nothing was done": "Foto di folder berubah saat dibaca: tidak ada yang dilakukan", - "Starts next": "Dimulai berikutnya" + "Starts next": "Dimulai berikutnya", + "A whole disk: synchronize it by itself": "Seluruh disk: sinkronkan sendiri", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Perbarui pustaka sesuai folder-folder ini dan folder di dalamnya, satu per satu:", + "Waiting to be scanned": "Menunggu dipindai", + "Up to date": "Sudah terbaru", + "Nothing to do: the library is up to date with these folders": "Tidak ada yang perlu dilakukan: pustaka sudah sesuai dengan folder-folder ini", + "Synchronizing the folder: see it under the bell": "Menyinkronkan folder: lihat di bawah lonceng", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Cari apa yang berubah di setiap folder ini pada disk, lalu perbarui pustaka sesuai folder tersebut satu per satu", + "Synchronize Folders": "Sinkronkan folder", + "Can't be synchronized with the others: synchronize it by itself": "Tidak bisa disinkronkan bersama yang lain: sinkronkan sendiri", + "Nothing to do with the choices ticked": "Tidak ada yang perlu dilakukan dengan pilihan yang dicentang", + "Nothing was synchronized": "Tidak ada yang disinkronkan" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index be35bf1f36b..cdd57d5bffa 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -346,5 +346,12 @@ "Queued: it starts after {n} more": "In coda: parte dopo altre attività ({n})", "Left alone: {n} (synchronize again to review them)": "Lasciati invariati: {n} (sincronizza di nuovo per rivederli)", "Starts after {n} more": "Parte dopo altre attività ({n})", - "Remove from Queue: {label}": "Rimuovi dalla coda: {label}" + "Remove from Queue: {label}": "Rimuovi dalla coda: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Sincronizzazione di {n} cartelle una dopo l'altra: vedi sotto la campanella", + "Too many tasks are waiting: only {n} more can wait in line": "Troppe attività in attesa: posti rimasti in coda: {n}", + "Synchronize {n} Folders…": "Sincronizza {n} cartelle…", + "{n} new": "nuove: {n}", + "{n} moved": "spostate: {n}", + "{n} missing": "mancanti: {n}", + "{n} with changed sidecars": "con file collaterale cambiato: {n}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index f5412525162..9ca22aef483 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2590,7 +2590,6 @@ "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", "Choose one album to rename it": "Scegli un solo album per rinominarlo", "Choose one folder to rename it": "Scegli una sola cartella per rinominarla", - "Choose one folder to synchronize it": "Scegli una sola cartella per sincronizzarla", "Choose one keyword to create a keyword inside it": "Scegli una sola parola chiave per crearne una al suo interno", "Choose one keyword to edit it": "Scegli una sola parola chiave per modificarla", "Choose one keyword to rename it": "Scegli una sola parola chiave per rinominarla", @@ -2608,5 +2607,16 @@ "Queued: it starts when the task ahead of it ends": "In coda: parte quando finisce l'attività precedente", "Another library was opened: nothing was done": "È stata aperta un'altra libreria: non è stato fatto nulla", "Photos of the folder changed while it was read: nothing was done": "Le foto della cartella sono cambiate durante la lettura: non è stato fatto nulla", - "Starts next": "Parte subito dopo" + "Starts next": "Parte subito dopo", + "A whole disk: synchronize it by itself": "Un intero disco: sincronizzalo da solo", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Aggiorna la libreria con queste cartelle e le cartelle che contengono, una dopo l'altra:", + "Waiting to be scanned": "In attesa di scansione", + "Up to date": "Aggiornata", + "Nothing to do: the library is up to date with these folders": "Niente da fare: la libreria è aggiornata con queste cartelle", + "Synchronizing the folder: see it under the bell": "Sincronizzazione della cartella: vedi sotto la campanella", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Trova cosa è cambiato sul disco in ciascuna di queste cartelle, poi aggiorna la libreria con loro una dopo l'altra", + "Synchronize Folders": "Sincronizza cartelle", + "Can't be synchronized with the others: synchronize it by itself": "Non si può sincronizzare con le altre: sincronizzala da sola", + "Nothing to do with the choices ticked": "Niente da fare con le scelte spuntate", + "Nothing was synchronized": "Non è stato sincronizzato nulla" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index fb1f6fd39e3..f0be934c09c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "キューに追加: あと {n} 件の後に開始します", "Left alone: {n} (synchronize again to review them)": "そのまま: {n} 件(再度同期して確認してください)", "Starts after {n} more": "あと {n} 件の後に開始します", - "Remove from Queue: {label}": "キューから削除: {label}" + "Remove from Queue: {label}": "キューから削除: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "{n}個のフォルダを順番に同期中:ベルの下で確認できます", + "Too many tasks are waiting: only {n} more can wait in line": "待機中のタスクが多すぎます:あと{n}個まで待機できます", + "Synchronize {n} Folders…": "{n}個のフォルダを同期…", + "{n} new": "新規 {n}", + "{n} moved": "移動 {n}", + "{n} missing": "見つからない {n}", + "{n} with changed sidecars": "サイドカー変更 {n}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index cf9b731dab7..def3985df24 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2424,7 +2424,6 @@ "Get Started": "始める", "Choose one album to rename it": "名前を変更するには、アルバムを1つだけ選択してください", "Choose one folder to rename it": "名前を変更するには、フォルダを1つだけ選択してください", - "Choose one folder to synchronize it": "同期するには、フォルダを1つだけ選択してください", "Choose one keyword to create a keyword inside it": "中にキーワードを作成するには、キーワードを1つだけ選択してください", "Choose one keyword to edit it": "編集するには、キーワードを1つだけ選択してください", "Choose one keyword to rename it": "名前を変更するには、キーワードを1つだけ選択してください", @@ -2443,5 +2442,16 @@ "Queued: it starts when the task ahead of it ends": "キューに追加: 前のタスクが終わると開始します", "Another library was opened: nothing was done": "別のライブラリが開かれました: 何も行われていません", "Photos of the folder changed while it was read: nothing was done": "読み取り中にフォルダ内の写真が変更されました: 何も行われていません", - "Starts next": "次に開始します" + "Starts next": "次に開始します", + "A whole disk: synchronize it by itself": "ディスク全体:個別に同期してください", + "Bring the library up to date with these folders and the folders inside them, one after another:": "これらのフォルダとその中のフォルダに合わせて、ライブラリを順番に最新の状態にします:", + "Waiting to be scanned": "スキャン待ち", + "Up to date": "最新", + "Nothing to do: the library is up to date with these folders": "何もすることはありません:ライブラリはこれらのフォルダと一致しています", + "Synchronizing the folder: see it under the bell": "フォルダを同期中:ベルの下で確認できます", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "これらの各フォルダでディスク上の変更を確認し、順番にライブラリを最新の状態にします", + "Synchronize Folders": "フォルダを同期", + "Can't be synchronized with the others: synchronize it by itself": "他のフォルダと一緒には同期できません:個別に同期してください", + "Nothing to do with the choices ticked": "選択した項目では何もすることはありません", + "Nothing was synchronized": "何も同期されませんでした" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 5d256ef84f8..38997a59cef 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -349,5 +349,12 @@ "Queued: it starts after {n} more": "რიგშია: დაიწყება კიდევ {n}-ის შემდეგ", "Left alone: {n} (synchronize again to review them)": "უცვლელი დარჩა: {n} (გადასახედად თავიდან დაასინქრონეთ)", "Starts after {n} more": "დაიწყება კიდევ {n}-ის შემდეგ", - "Remove from Queue: {label}": "რიგიდან ამოღება: {label}" + "Remove from Queue: {label}": "რიგიდან ამოღება: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "{n} საქაღალდის სინქრონიზაცია სათითაოდ: იხილეთ ზარის ქვეშ", + "Too many tasks are waiting: only {n} more can wait in line": "ძალიან ბევრი დავალება ელოდება: რიგში მხოლოდ კიდევ {n} ჩაეტევა", + "Synchronize {n} Folders…": "{n} საქაღალდის სინქრონიზაცია…", + "{n} new": "ახალი: {n}", + "{n} moved": "გადატანილი: {n}", + "{n} missing": "დაკარგული: {n}", + "{n} with changed sidecars": "შეცვლილი თანმხლები ფაილით: {n}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 4ad5cf87b25..3ce400edabc 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3693,7 +3693,6 @@ "Another library was opened since this window appeared: nothing was changed": "ამ ფანჯრის გამოჩენის შემდეგ სხვა ბიბლიოთეკა გაიხსნა: არაფერი შეცვლილა", "Choose one album to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი ალბომი", "Choose one folder to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი საქაღალდე", - "Choose one folder to synchronize it": "სინქრონიზაციისთვის აირჩიეთ ერთი საქაღალდე", "Choose one keyword to create a keyword inside it": "აირჩიეთ ერთი საკვანძო სიტყვა, რომ მასში ახალი შექმნათ", "Choose one keyword to edit it": "რედაქტირებისთვის აირჩიეთ ერთი საკვანძო სიტყვა", "Choose one keyword to rename it": "სახელის შესაცვლელად აირჩიეთ ერთი საკვანძო სიტყვა", @@ -3710,5 +3709,16 @@ "Queued: it starts when the task ahead of it ends": "რიგშია: დაიწყება, როცა წინა ამოცანა დასრულდება", "Another library was opened: nothing was done": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა", "Photos of the folder changed while it was read: nothing was done": "საქაღალდის ფოტოები წაკითხვისას შეიცვალა: არაფერი გაკეთებულა", - "Starts next": "დაიწყება შემდეგი" + "Starts next": "დაიწყება შემდეგი", + "A whole disk: synchronize it by itself": "მთელი დისკი: მისი სინქრონიზაცია ცალკე მოახდინეთ", + "Bring the library up to date with these folders and the folders inside them, one after another:": "ბიბლიოთეკის განახლება ამ საქაღალდეებისა და მათში არსებული საქაღალდეების მიხედვით, სათითაოდ:", + "Waiting to be scanned": "ელოდება სკანირებას", + "Up to date": "განახლებულია", + "Nothing to do: the library is up to date with these folders": "გასაკეთებელი არაფერია: ბიბლიოთეკა ამ საქაღალდეებთან შესაბამისობაშია", + "Synchronizing the folder: see it under the bell": "საქაღალდის სინქრონიზაცია: იხილეთ ზარის ქვეშ", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "პოულობს, რა შეიცვალა დისკზე თითოეულ ამ საქაღალდეში, შემდეგ კი სათითაოდ ანახლებს ბიბლიოთეკას", + "Synchronize Folders": "საქაღალდეების სინქრონიზაცია", + "Can't be synchronized with the others: synchronize it by itself": "სხვებთან ერთად სინქრონიზაცია შეუძლებელია: მოახდინეთ მისი სინქრონიზაცია ცალკე", + "Nothing to do with the choices ticked": "მონიშნული არჩევანით გასაკეთებელი არაფერია", + "Nothing was synchronized": "არაფრის სინქრონიზაცია არ მომხდარა" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 9852c093be8..d5bc4b4f992 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -346,5 +346,12 @@ "Queued: it starts after {n} more": "W kolejce: rozpocznie się po kolejnych zadaniach ({n})", "Left alone: {n} (synchronize again to review them)": "Pominięto: {n} (zsynchronizuj ponownie, aby je sprawdzić)", "Starts after {n} more": "Rozpocznie się po kolejnych zadaniach ({n})", - "Remove from Queue: {label}": "Usuń z kolejki: {label}" + "Remove from Queue: {label}": "Usuń z kolejki: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Synchronizacja folderów ({n}) jeden po drugim: zobacz pod dzwonkiem", + "Too many tasks are waiting: only {n} more can wait in line": "Czeka zbyt wiele zadań: w kolejce zmieści się jeszcze tylko {n}", + "Synchronize {n} Folders…": "Synchronizuj foldery ({n})…", + "{n} new": "nowe: {n}", + "{n} moved": "przeniesione: {n}", + "{n} missing": "brakujące: {n}", + "{n} with changed sidecars": "ze zmienionym plikiem XMP: {n}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index fd0d6a1deb6..fa046dcce4b 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2348,7 +2348,6 @@ "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", "Choose one album to rename it": "Wybierz jeden album, aby zmienić jego nazwę", "Choose one folder to rename it": "Wybierz jeden folder, aby zmienić jego nazwę", - "Choose one folder to synchronize it": "Wybierz jeden folder, aby go zsynchronizować", "Choose one keyword to create a keyword inside it": "Wybierz jedno słowo kluczowe, aby utworzyć w nim kolejne", "Choose one keyword to edit it": "Wybierz jedno słowo kluczowe, aby je edytować", "Choose one keyword to rename it": "Wybierz jedno słowo kluczowe, aby zmienić jego nazwę", @@ -2367,5 +2366,16 @@ "Queued: it starts when the task ahead of it ends": "W kolejce: rozpocznie się po zakończeniu poprzedniego zadania", "Another library was opened: nothing was done": "Otwarto inną bibliotekę: nic nie zrobiono", "Photos of the folder changed while it was read: nothing was done": "Zdjęcia w folderze zmieniły się podczas odczytu: nic nie zrobiono", - "Starts next": "Rozpocznie się jako następne" + "Starts next": "Rozpocznie się jako następne", + "A whole disk: synchronize it by itself": "Cały dysk: zsynchronizuj go osobno", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Uzgodnij bibliotekę z tymi folderami i folderami w nich, jeden po drugim:", + "Waiting to be scanned": "Czeka na skanowanie", + "Up to date": "Aktualny", + "Nothing to do: the library is up to date with these folders": "Nic do zrobienia: biblioteka jest zgodna z tymi folderami", + "Synchronizing the folder: see it under the bell": "Synchronizacja folderu: zobacz pod dzwonkiem", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Wyszukuje zmiany na dysku w każdym z tych folderów, a potem uzgadnia z nimi bibliotekę, jeden po drugim", + "Synchronize Folders": "Synchronizuj foldery", + "Can't be synchronized with the others: synchronize it by itself": "Nie można go zsynchronizować z pozostałymi: zsynchronizuj go osobno", + "Nothing to do with the choices ticked": "Przy zaznaczonych opcjach nie ma nic do zrobienia", + "Nothing was synchronized": "Nic nie zostało zsynchronizowane" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 623252aa5c5..77c7dc43bc1 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "Na fila: começa depois de mais {n}", "Left alone: {n} (synchronize again to review them)": "Deixados como estavam: {n} (sincronize de novo para revisá-los)", "Starts after {n} more": "Começa depois de mais {n}", - "Remove from Queue: {label}": "Remover da fila: {label}" + "Remove from Queue: {label}": "Remover da fila: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Sincronizando {n} pastas uma após a outra: veja sob o sino", + "Too many tasks are waiting: only {n} more can wait in line": "Tarefas demais aguardando: vagas restantes na fila: {n}", + "Synchronize {n} Folders…": "Sincronizar {n} pastas…", + "{n} new": "novas: {n}", + "{n} moved": "movidas: {n}", + "{n} missing": "ausentes: {n}", + "{n} with changed sidecars": "com arquivo auxiliar alterado: {n}" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 0ce723537e0..6eafb6ac8cd 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2270,7 +2270,6 @@ "Get Started": "Começar", "Choose one album to rename it": "Escolha um só álbum para renomeá-lo", "Choose one folder to rename it": "Escolha uma só pasta para renomeá-la", - "Choose one folder to synchronize it": "Escolha uma só pasta para sincronizá-la", "Choose one keyword to create a keyword inside it": "Escolha uma só palavra-chave para criar outra dentro dela", "Choose one keyword to edit it": "Escolha uma só palavra-chave para editá-la", "Choose one keyword to rename it": "Escolha uma só palavra-chave para renomeá-la", @@ -2289,5 +2288,16 @@ "Queued: it starts when the task ahead of it ends": "Na fila: começa quando a tarefa anterior terminar", "Another library was opened: nothing was done": "Outra biblioteca foi aberta: nada foi feito", "Photos of the folder changed while it was read: nothing was done": "As fotos da pasta mudaram durante a leitura: nada foi feito", - "Starts next": "Começa em seguida" + "Starts next": "Começa em seguida", + "A whole disk: synchronize it by itself": "Um disco inteiro: sincronize-o separadamente", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Atualizar a biblioteca com estas pastas e as pastas dentro delas, uma após a outra:", + "Waiting to be scanned": "Aguardando verificação", + "Up to date": "Atualizada", + "Nothing to do: the library is up to date with these folders": "Nada a fazer: a biblioteca está atualizada com estas pastas", + "Synchronizing the folder: see it under the bell": "Sincronizando a pasta: veja sob o sino", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Procura o que mudou no disco em cada uma destas pastas e depois atualiza a biblioteca com elas, uma após a outra", + "Synchronize Folders": "Sincronizar pastas", + "Can't be synchronized with the others: synchronize it by itself": "Não pode ser sincronizada com as outras: sincronize-a separadamente", + "Nothing to do with the choices ticked": "Nada a fazer com as opções marcadas", + "Nothing was synchronized": "Nada foi sincronizado" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index c643e9dd81f..d8cb387fed4 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "В очереди: начнётся после ещё {n}", "Left alone: {n} (synchronize again to review them)": "Оставлено без изменений: {n} (синхронизируйте снова, чтобы проверить)", "Starts after {n} more": "Начнётся после ещё {n}", - "Remove from Queue: {label}": "Убрать из очереди: {label}" + "Remove from Queue: {label}": "Убрать из очереди: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Папки ({n}) синхронизируются по очереди: смотрите под колокольчиком", + "Too many tasks are waiting: only {n} more can wait in line": "Слишком много задач в очереди: поместится ещё только {n}", + "Synchronize {n} Folders…": "Синхронизировать папки ({n})…", + "{n} new": "новых: {n}", + "{n} moved": "перемещённых: {n}", + "{n} missing": "отсутствующих: {n}", + "{n} with changed sidecars": "с изменённым XMP-файлом: {n}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 224b9b34980..5baec52a863 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2632,7 +2632,6 @@ "Get Started": "Начать", "Choose one album to rename it": "Выберите только один альбом, чтобы переименовать его", "Choose one folder to rename it": "Выберите только одну папку, чтобы переименовать её", - "Choose one folder to synchronize it": "Выберите только одну папку, чтобы синхронизировать её", "Choose one keyword to create a keyword inside it": "Выберите только одно ключевое слово, чтобы создать ключевое слово внутри него", "Choose one keyword to edit it": "Выберите только одно ключевое слово, чтобы изменить его", "Choose one keyword to rename it": "Выберите только одно ключевое слово, чтобы переименовать его", @@ -2650,5 +2649,16 @@ "Queued: it starts when the task ahead of it ends": "В очереди: начнётся, когда закончится задача перед ней", "Another library was opened: nothing was done": "Открыта другая библиотека: ничего не сделано", "Photos of the folder changed while it was read: nothing was done": "Фотографии в папке изменились во время чтения: ничего не сделано", - "Starts next": "Начнётся следующей" + "Starts next": "Начнётся следующей", + "A whole disk: synchronize it by itself": "Целый диск: синхронизируйте его отдельно", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Привести библиотеку в соответствие с этими папками и вложенными в них, по очереди:", + "Waiting to be scanned": "Ожидает сканирования", + "Up to date": "Актуальна", + "Nothing to do: the library is up to date with these folders": "Делать нечего: библиотека соответствует этим папкам", + "Synchronizing the folder: see it under the bell": "Папка синхронизируется: смотрите под колокольчиком", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Находит, что изменилось на диске в каждой из этих папок, и по очереди приводит библиотеку в соответствие с ними", + "Synchronize Folders": "Синхронизировать папки", + "Can't be synchronized with the others: synchronize it by itself": "Нельзя синхронизировать вместе с остальными: синхронизируйте её отдельно", + "Nothing to do with the choices ticked": "С отмеченными вариантами делать нечего", + "Nothing was synchronized": "Ничего не синхронизировано" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index df3be0224e9..02983c15d67 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -346,5 +346,12 @@ "Queued: it starts after {n} more": "I kö: startar efter {n} till", "Left alone: {n} (synchronize again to review them)": "Lämnade orörda: {n} (synkronisera igen för att granska dem)", "Starts after {n} more": "Startar efter {n} till", - "Remove from Queue: {label}": "Ta bort från kön: {label}" + "Remove from Queue: {label}": "Ta bort från kön: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Synkroniserar {n} mappar en i taget: se dem under klockan", + "Too many tasks are waiting: only {n} more can wait in line": "För många uppgifter väntar: bara {n} till får plats i kön", + "Synchronize {n} Folders…": "Synkronisera {n} mappar…", + "{n} new": "nya: {n}", + "{n} moved": "flyttade: {n}", + "{n} missing": "{n} saknas", + "{n} with changed sidecars": "med ändrade sidofiler: {n}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 84bfd51feeb..fae30f168f0 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2486,7 +2486,6 @@ "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", "Choose one album to rename it": "Välj ett enda album för att byta namn på det", "Choose one folder to rename it": "Välj en enda mapp för att byta namn på den", - "Choose one folder to synchronize it": "Välj en enda mapp för att synkronisera den", "Choose one keyword to create a keyword inside it": "Välj ett enda nyckelord för att skapa ett nyckelord i det", "Choose one keyword to edit it": "Välj ett enda nyckelord för att redigera det", "Choose one keyword to rename it": "Välj ett enda nyckelord för att byta namn på det", @@ -2504,5 +2503,16 @@ "Queued: it starts when the task ahead of it ends": "I kö: startar när uppgiften före är klar", "Another library was opened: nothing was done": "Ett annat bibliotek öppnades: ingenting gjordes", "Photos of the folder changed while it was read: nothing was done": "Fotona i mappen ändrades medan den lästes: ingenting gjordes", - "Starts next": "Startar härnäst" + "Starts next": "Startar härnäst", + "A whole disk: synchronize it by itself": "En hel disk: synkronisera den för sig", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Uppdatera biblioteket med de här mapparna och mapparna i dem, en i taget:", + "Waiting to be scanned": "Väntar på att skannas", + "Up to date": "Uppdaterad", + "Nothing to do: the library is up to date with these folders": "Inget att göra: biblioteket är uppdaterat med de här mapparna", + "Synchronizing the folder: see it under the bell": "Synkroniserar mappen: se den under klockan", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Sök efter vad som har ändrats i var och en av de här mapparna på disken och uppdatera sedan biblioteket med dem, en i taget", + "Synchronize Folders": "Synkronisera mappar", + "Can't be synchronized with the others: synchronize it by itself": "Kan inte synkroniseras med de andra: synkronisera den för sig", + "Nothing to do with the choices ticked": "Inget att göra med de ikryssade valen", + "Nothing was synchronized": "Inget synkroniserades" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index b3bd5e2395d..ee4602d4078 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "У черзі: почнеться після ще {n}", "Left alone: {n} (synchronize again to review them)": "Залишено без змін: {n} (синхронізуйте знову, щоб переглянути)", "Starts after {n} more": "Почнеться після ще {n}", - "Remove from Queue: {label}": "Прибрати з черги: {label}" + "Remove from Queue: {label}": "Прибрати з черги: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Теки ({n}) синхронізуються по черзі: дивіться під дзвоником", + "Too many tasks are waiting: only {n} more can wait in line": "Забагато завдань у черзі: поміститься ще лише {n}", + "Synchronize {n} Folders…": "Синхронізувати теки ({n})…", + "{n} new": "нових: {n}", + "{n} moved": "переміщених: {n}", + "{n} missing": "відсутніх: {n}", + "{n} with changed sidecars": "зі зміненим файлом XMP: {n}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index bdf6aa123aa..69da01f5624 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2422,7 +2422,6 @@ "Get Started": "Почати", "Choose one album to rename it": "Виберіть лише один альбом, щоб перейменувати його", "Choose one folder to rename it": "Виберіть лише одну теку, щоб перейменувати її", - "Choose one folder to synchronize it": "Виберіть лише одну теку, щоб синхронізувати її", "Choose one keyword to create a keyword inside it": "Виберіть лише одне ключове слово, щоб створити ключове слово всередині нього", "Choose one keyword to edit it": "Виберіть лише одне ключове слово, щоб редагувати його", "Choose one keyword to rename it": "Виберіть лише одне ключове слово, щоб перейменувати його", @@ -2441,5 +2440,16 @@ "Queued: it starts when the task ahead of it ends": "У черзі: почнеться, коли завершиться попереднє завдання", "Another library was opened: nothing was done": "Відкрито іншу бібліотеку: нічого не зроблено", "Photos of the folder changed while it was read: nothing was done": "Фотографії в теці змінилися під час читання: нічого не зроблено", - "Starts next": "Почнеться наступним" + "Starts next": "Почнеться наступним", + "A whole disk: synchronize it by itself": "Цілий диск: синхронізуйте його окремо", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Узгодити бібліотеку з цими теками та теками в них, по черзі:", + "Waiting to be scanned": "Очікує сканування", + "Up to date": "Актуальна", + "Nothing to do: the library is up to date with these folders": "Нічого робити: бібліотека відповідає цим текам", + "Synchronizing the folder: see it under the bell": "Тека синхронізується: дивіться під дзвоником", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Знаходить, що змінилося на диску в кожній із цих тек, і по черзі узгоджує з ними бібліотеку", + "Synchronize Folders": "Синхронізувати теки", + "Can't be synchronized with the others: synchronize it by itself": "Не можна синхронізувати разом з іншими: синхронізуйте її окремо", + "Nothing to do with the choices ticked": "З позначеними варіантами робити нічого", + "Nothing was synchronized": "Нічого не синхронізовано" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index e362ae6a865..08a7334c7e5 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -343,5 +343,12 @@ "Queued: it starts after {n} more": "Trong hàng đợi: bắt đầu sau {n} tác vụ nữa", "Left alone: {n} (synchronize again to review them)": "Để nguyên: {n} (đồng bộ lại để xem xét)", "Starts after {n} more": "Bắt đầu sau {n} tác vụ nữa", - "Remove from Queue: {label}": "Xóa khỏi hàng đợi: {label}" + "Remove from Queue: {label}": "Xóa khỏi hàng đợi: {label}", + "Synchronizing {n} folders one after another: see them under the bell": "Đang đồng bộ {n} thư mục lần lượt: xem dưới biểu tượng chuông", + "Too many tasks are waiting: only {n} more can wait in line": "Quá nhiều tác vụ đang chờ: chỉ còn chỗ chờ cho {n} tác vụ nữa", + "Synchronize {n} Folders…": "Đồng bộ {n} thư mục…", + "{n} new": "{n} mới", + "{n} moved": "{n} đã chuyển", + "{n} missing": "{n} bị mất", + "{n} with changed sidecars": "{n} có sidecar thay đổi" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 3ffa690db97..3492b26b529 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2711,7 +2711,6 @@ "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", "Choose one album to rename it": "Chọn một album để đổi tên", "Choose one folder to rename it": "Chọn một thư mục để đổi tên", - "Choose one folder to synchronize it": "Chọn một thư mục để đồng bộ", "Choose one keyword to create a keyword inside it": "Chọn một từ khóa để tạo từ khóa bên trong nó", "Choose one keyword to edit it": "Chọn một từ khóa để sửa", "Choose one keyword to rename it": "Chọn một từ khóa để đổi tên", @@ -2729,5 +2728,16 @@ "Queued: it starts when the task ahead of it ends": "Trong hàng đợi: bắt đầu khi tác vụ trước nó kết thúc", "Another library was opened: nothing was done": "Đã mở thư viện khác: không có gì được thực hiện", "Photos of the folder changed while it was read: nothing was done": "Ảnh trong thư mục đã thay đổi trong lúc đọc: không có gì được thực hiện", - "Starts next": "Bắt đầu tiếp theo" + "Starts next": "Bắt đầu tiếp theo", + "A whole disk: synchronize it by itself": "Cả một ổ đĩa: hãy đồng bộ riêng", + "Bring the library up to date with these folders and the folders inside them, one after another:": "Cập nhật thư viện theo các thư mục này và các thư mục bên trong chúng, lần lượt từng thư mục:", + "Waiting to be scanned": "Đang chờ được quét", + "Up to date": "Đã cập nhật", + "Nothing to do: the library is up to date with these folders": "Không có gì để làm: thư viện đã đồng bộ với các thư mục này", + "Synchronizing the folder: see it under the bell": "Đang đồng bộ thư mục: xem dưới biểu tượng chuông", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "Tìm xem mỗi thư mục này trên đĩa đã thay đổi gì, rồi cập nhật thư viện theo chúng lần lượt từng thư mục", + "Synchronize Folders": "Đồng bộ thư mục", + "Can't be synchronized with the others: synchronize it by itself": "Không thể đồng bộ cùng các thư mục khác: hãy đồng bộ riêng", + "Nothing to do with the choices ticked": "Không có gì để làm với các lựa chọn đã đánh dấu", + "Nothing was synchronized": "Không có gì được đồng bộ" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7f535bc3ec0..dcac8af0cb8 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "已加入队列:再过 {n} 个后开始", "Left alone: {n} (synchronize again to review them)": "未处理:{n}(再次同步以查看)", "Starts after {n} more": "再过 {n} 个后开始", - "Remove from Queue: {label}": "从队列中移除:{label}" + "Remove from Queue: {label}": "从队列中移除:{label}", + "Synchronizing {n} folders one after another: see them under the bell": "正在依次同步 {n} 个文件夹:可在铃铛下查看", + "Too many tasks are waiting: only {n} more can wait in line": "等待的任务过多:队列中只能再加入 {n} 个", + "Synchronize {n} Folders…": "同步 {n} 个文件夹…", + "{n} new": "新增 {n}", + "{n} moved": "已移动 {n}", + "{n} missing": "缺失 {n}", + "{n} with changed sidecars": "附属文件已更改 {n}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 1aa147acd94..231d8dce04a 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2425,7 +2425,6 @@ "Get Started": "开始使用", "Choose one album to rename it": "请只选择一个相册以重命名", "Choose one folder to rename it": "请只选择一个文件夹以重命名", - "Choose one folder to synchronize it": "请只选择一个文件夹以同步", "Choose one keyword to create a keyword inside it": "请只选择一个关键字以在其中创建关键字", "Choose one keyword to edit it": "请只选择一个关键字以编辑", "Choose one keyword to rename it": "请只选择一个关键字以重命名", @@ -2444,5 +2443,16 @@ "Queued: it starts when the task ahead of it ends": "已加入队列:前一个任务结束后开始", "Another library was opened: nothing was done": "已打开另一个图库:未执行任何操作", "Photos of the folder changed while it was read: nothing was done": "读取期间文件夹中的照片发生了变化:未执行任何操作", - "Starts next": "接下来开始" + "Starts next": "接下来开始", + "A whole disk: synchronize it by itself": "整个磁盘:请单独同步", + "Bring the library up to date with these folders and the folders inside them, one after another:": "依次使图库与这些文件夹及其中的文件夹保持一致:", + "Waiting to be scanned": "等待扫描", + "Up to date": "已是最新", + "Nothing to do: the library is up to date with these folders": "无需操作:图库与这些文件夹一致", + "Synchronizing the folder: see it under the bell": "正在同步文件夹:可在铃铛下查看", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "查找磁盘上这些文件夹各自的更改,然后依次使图库与它们保持一致", + "Synchronize Folders": "同步文件夹", + "Can't be synchronized with the others: synchronize it by itself": "无法与其他文件夹一起同步:请单独同步", + "Nothing to do with the choices ticked": "按所勾选的选项无需操作", + "Nothing was synchronized": "没有同步任何内容" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 997204d7b9d..32101d06079 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -347,5 +347,12 @@ "Queued: it starts after {n} more": "已加入佇列:再過 {n} 個後開始", "Left alone: {n} (synchronize again to review them)": "未處理:{n}(再次同步以檢視)", "Starts after {n} more": "再過 {n} 個後開始", - "Remove from Queue: {label}": "從佇列中移除:{label}" + "Remove from Queue: {label}": "從佇列中移除:{label}", + "Synchronizing {n} folders one after another: see them under the bell": "正在依序同步 {n} 個資料夾:可在鈴鐺下查看", + "Too many tasks are waiting: only {n} more can wait in line": "等待中的工作過多:佇列中只能再加入 {n} 個", + "Synchronize {n} Folders…": "同步 {n} 個資料夾…", + "{n} new": "新增 {n}", + "{n} moved": "已移動 {n}", + "{n} missing": "遺失 {n}", + "{n} with changed sidecars": "附屬檔案已變更 {n}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index c9bf20299f8..33323616e3c 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2426,7 +2426,6 @@ "Get Started": "開始使用", "Choose one album to rename it": "請只選擇一個相簿以重新命名", "Choose one folder to rename it": "請只選擇一個資料夾以重新命名", - "Choose one folder to synchronize it": "請只選擇一個資料夾以同步", "Choose one keyword to create a keyword inside it": "請只選擇一個關鍵字以在其中建立關鍵字", "Choose one keyword to edit it": "請只選擇一個關鍵字以編輯", "Choose one keyword to rename it": "請只選擇一個關鍵字以重新命名", @@ -2445,5 +2444,16 @@ "Queued: it starts when the task ahead of it ends": "已加入佇列:前一個工作結束後開始", "Another library was opened: nothing was done": "已開啟另一個圖庫:未執行任何操作", "Photos of the folder changed while it was read: nothing was done": "讀取期間資料夾中的照片發生了變化:未執行任何操作", - "Starts next": "接下來開始" + "Starts next": "接下來開始", + "A whole disk: synchronize it by itself": "整個磁碟:請單獨同步", + "Bring the library up to date with these folders and the folders inside them, one after another:": "依序使照片庫與這些資料夾及其中的資料夾保持一致:", + "Waiting to be scanned": "等待掃描", + "Up to date": "已是最新", + "Nothing to do: the library is up to date with these folders": "無需操作:照片庫與這些資料夾一致", + "Synchronizing the folder: see it under the bell": "正在同步資料夾:可在鈴鐺下查看", + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another": "尋找磁碟上這些資料夾各自的變更,然後依序使照片庫與它們保持一致", + "Synchronize Folders": "同步資料夾", + "Can't be synchronized with the others: synchronize it by itself": "無法與其他資料夾一起同步:請單獨同步", + "Nothing to do with the choices ticked": "依所勾選的選項無需操作", + "Nothing was synchronized": "沒有同步任何內容" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 93380218cf2..1702060af62 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -117,6 +117,7 @@ impl LightcraftApp { sync_owns_changes: false, sync_run: None, sync_queued: None, + sync_scans: None, lightroom: None, lightroom_last: None, lightroom_result: None, diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index c5571490e62..7d18e199883 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -79,6 +79,7 @@ impl LightcraftApp { merge::poll(self, ctx); import::poll_scan(self, ctx); sync::poll(self, ctx); + sync::poll_many(self, ctx); sync::poll_rescan(self, ctx); sync::poll_run(self, ctx); // Import commits batches and must not run twice in one host frame. The first layout pass diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2032fd6f94b..4144cbdeddb 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -442,7 +442,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest (Ok(made), crate::state::Dialog::TextPrompt { .. }) => crate::dialogs::toast_created_folder(app, ctx, &d, made), _ => {} } - // the import review, the rule editor and the one-line prompts stay open on an error, as with their buttons + // the import review, the rule editor, the one-line prompts and the folders' Synchronize stay open on an error, as with their buttons if (r.is_err() && matches!( d, @@ -453,6 +453,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest | crate::state::Dialog::CaptureTime { .. } | crate::state::Dialog::LensDatabase { .. } | crate::state::Dialog::TextPrompt { .. } + | crate::state::Dialog::SynchronizeFolders { .. } )) || (r.is_ok() && crate::panels::dialogs::keeps_open(app, &d)) || (r.is_err() && crate::lightroom_destination::keeps_open_on_error(app, &d)) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c9bbde34aeb..d68168d9b94 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -486,6 +486,7 @@ fn dialog_title(app: &LightcraftApp, dlg: &Dialog) -> String { Dialog::RemoveFolder { disk: true, .. } => "Remove Disk from Library", Dialog::RemoveFolder { .. } => "Remove Folder from Library", Dialog::SynchronizeFolder { .. } => "Synchronize Folder", + Dialog::SynchronizeFolders { .. } => "Synchronize Folders", // (nothing to download from in this build: the dialog explains the manual install) Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model", Dialog::SamModel { .. } => "Download the SAM 3 Model?", @@ -524,6 +525,12 @@ impl SamState { } } +/// The label the dialog's confirm button has now, for tests. +#[cfg(test)] +pub(crate) fn confirm_label(app: &LightcraftApp, dlg: &Dialog) -> String { + ok_label(app, dlg, is_informational(dlg), &SamState::of(app)) +} + /// The label of a dialog's cancel button. fn cancel_label(dlg: &Dialog, sam: &SamState) -> &'static str { match dlg { @@ -608,8 +615,8 @@ fn fixed_ok_label(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> &'s d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), Dialog::Welcome { .. } => "", Dialog::LensDatabase { .. } => "Download", - Dialog::SynchronizeFolder { .. } if informational => "Close", - Dialog::SynchronizeFolder { .. } => "Synchronize", + Dialog::SynchronizeFolder { .. } | Dialog::SynchronizeFolders { .. } if informational => "Close", + Dialog::SynchronizeFolder { .. } | Dialog::SynchronizeFolders { .. } => "Synchronize", Dialog::RenamePerson { from, to, .. } if person_rename_plan(&app.session.catalog, from, to).needs_merge => "Merge", Dialog::RenamePerson { .. } => "Rename", // the dialogs that only show something, or a model file that can't be used @@ -650,7 +657,7 @@ fn can_confirm(app: &LightcraftApp, dlg: &Dialog, informational: bool) -> bool { let waiting = matches!( dlg, Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. } - ); + ) || (matches!(dlg, Dialog::SynchronizeFolders { .. }) && !crate::sync::many_scanned(dlg)); let bad_rules = matches!(dlg, Dialog::SmartRules { id, rules, .. } if !rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).is_empty()); !rename_blocked && (informational || (!waiting && !bad_rules)) @@ -732,6 +739,7 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> | Dialog::KeywordTag { .. } | Dialog::KeywordSet { .. } | Dialog::SynchronizeFolder { .. } + | Dialog::SynchronizeFolders { .. } | Dialog::SaveEffect { .. } | Dialog::CaptureTime { .. } | Dialog::LensDatabase { .. } @@ -2162,6 +2170,7 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m } Dialog::MovePhotos { .. } => move_photos_body(ui, t, dlg), d @ Dialog::SynchronizeFolder { .. } => crate::sync::body(app, ui, d), + d @ Dialog::SynchronizeFolders { .. } => crate::sync::many_body(app, ui, d), Dialog::LightroomCatalog { .. } => lightroom_catalog_body(app, ui, t, dlg), d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::body(app, ui, d), Dialog::LensDatabase { .. } => crate::lens_db::offer(ui), diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 99394ba4e44..442017b7cd2 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -252,6 +252,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result app.run("mask.deleteEffect", json!({"names": names})), Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})), d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d), + d @ Dialog::SynchronizeFolders { .. } => crate::sync::confirm_many(app, d), Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => { Ok(serde_json::Value::Null) } diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rs index 11067230577..8ae2316ef1e 100644 --- a/crates/ui-egui/src/dialogs/frame.rs +++ b/crates/ui-egui/src/dialogs/frame.rs @@ -214,4 +214,5 @@ pub(super) fn only_shows(dlg: &Dialog) -> bool { | Dialog::ManageEffects { .. } | Dialog::ViewOptions ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date()) + || matches!(dlg, Dialog::SynchronizeFolders { folders, .. } if crate::sync::all_up_to_date(folders)) } diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index f5c9f74ce33..8d469a530ee 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -114,7 +114,7 @@ fn scan_guard(app: &LightcraftApp, progress: &ScanProgress, browse: bool) -> lig pub const IMPORT_REQUEST: &str = "app:import"; fn import_request(paths: &[String], params: &Value, auto: bool) -> Request { - Request { command: IMPORT_REQUEST.into(), params: json!({"paths": paths, "params": params, "auto": auto}) } + Request { command: IMPORT_REQUEST.into(), params: json!({"paths": paths, "params": params, "auto": auto}), ..Default::default() } } /// The library lane is taken: an import (or the reading of a Local folder) or a Synchronize Folder runs, or waits diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index 374cb1fe8ef..a8840b1d087 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -398,6 +398,7 @@ impl Headless { || self.app.sync.is_some() || self.app.sync_run.is_some() || self.app.sync_queued.is_some() + || self.app.sync_scans.is_some() || self.app.import.is_some() || self.app.export.is_some() || self.app.session.denoise_busy() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 72ddaf58c52..f9932d243ff 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -403,6 +403,8 @@ pub struct LightcraftApp { pub sync_run: Option, /// A Synchronize Folder that waited in line, scanning its folder again before it runs. pub sync_queued: Option, + /// The scans of the Synchronize N Folders dialog, one folder after another. + pub sync_scans: Option, /// A Lightroom catalog inspect/import in progress. pub lightroom: Option, /// Last terminal Lightroom result, exposed by the command's status/wait response. diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index 9492c7a6e84..97d437526cc 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -120,7 +120,7 @@ pub(crate) fn cancel(app: &mut LightcraftApp, id: u64) { /// What ✕ on `task`'s row is called, for screen readers and its tooltip. pub(crate) fn cross_name(task: &TaskInfo) -> String { - if task.waiting { tr_format!("Remove from Queue: {label}", label = tr(&task.label)) } else { tr("Cancel").to_string() } + if task.waiting { tr_format!("Remove from Queue: {label}", label = waiting_name(task)) } else { tr("Cancel").to_string() } } /// One task: name and ✕, the bar, the detail line (a waiting one: name and ✕, when it starts). True when ✕ was clicked. @@ -146,8 +146,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { } }); let line = if task.waiting { - // (counted as the Queued toast counts: the waiting tasks ahead of it, after the running one) - if task.place <= 1 { tr("Starts next").to_string() } else { tr_format!("Starts after {n} more", n = task.place - 1) } + waiting_line(task) } else { bar(ui, task, width); detail_line(task) @@ -168,3 +167,15 @@ pub(crate) fn bar(ui: &mut egui::Ui, task: &TaskInfo, width: f32) -> egui::Respo crate::widgets::screen_reader_name(ui.ctx(), response.id, tr(&task.label)); response } + +/// A waiting task as the ✕ announces it: its label, and what it is about if it says ("Synchronizing folder: Trip"). +fn waiting_name(task: &TaskInfo) -> String { + if task.detail.is_empty() { tr(&task.label).to_string() } else { format!("{}: {}", tr(&task.label), task.detail) } +} + +/// The line under a waiting task's name: what it is about if it says, then when it starts ("photos/Garden · Starts next"). +/// (Counted as the Queued toast counts: the waiting tasks ahead of it, after the running one.) +pub(crate) fn waiting_line(task: &TaskInfo) -> String { + let when = if task.place <= 1 { tr("Starts next").to_string() } else { tr_format!("Starts after {n} more", n = task.place - 1) }; + if task.detail.is_empty() { when } else { format!("{} · {when}", task.detail) } +} diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs index 6bb0c93ce17..405aded743d 100644 --- a/crates/ui-egui/src/panels/side_select.rs +++ b/crates/ui-egui/src/panels/side_select.rs @@ -358,7 +358,15 @@ pub(crate) fn folders_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, paths: &[ ui.close(); } }); - single_only(ui, "Synchronize Folder…", "Choose one folder to synchronize it"); + let sync = item(ui, "folders:synchronize", crate::i18n::tr_format!("Synchronize {n} Folders…", n = n), true).on_hover_text(crate::i18n::tr( + "Find what changed in each of these folders on disk, then bring the library up to date with them one after another", + )); + if sync.clicked() { + if let Err(e) = crate::sync::open_many(app, paths) { + app.toast(ui.ctx(), e); + } + ui.close(); + } single_only(ui, "Rename Folder…", "Choose one folder to rename it"); ui.separator(); // a whole disk goes by itself, after its own question diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f233d3fba40..a6a1da3b7c6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,7 +6,7 @@ mod dialog; mod settings; mod view; -pub use dialog::{Dialog, NameEdit, SyncCounts, default_preset_groups}; +pub use dialog::{Dialog, NameEdit, SyncCounts, SyncFolder, default_preset_groups}; pub use settings::{ AppSettings, AppearanceMode, DarkTheme, EditFile, EditFormat, EditSpace, GridBadges, HOT_PIXEL_LIMIT_DEFAULT, HOT_PIXEL_LIMITS, KeywordChips, LOUPE_EDGE_CEILING, LOUPE_EDGE_STEP, LaunchLibrary, LightTheme, LightroomImport, MIN_TEXTURE_SIDE, PHOTOCRAFT, PREVIEW_LIMITS, RECENT_LIBRARIES, diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 3c9676f0e0e..e0a989231b5 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -358,6 +358,21 @@ pub enum Dialog { remove_missing: bool, read_metadata: bool, }, + /// Synchronize N Folders: the folders chosen in the sidebar, scanned one after another, then synchronized with one + /// set of choices, one after another in the library lane (the scans run in [`crate::sync`]). + SynchronizeFolders { + /// In the sidebar's order; a folder inside another chosen one is left out (the other covers it). + folders: Vec, + import_new: bool, + #[serde(default = "yes")] + relink_moved: bool, + remove_missing: bool, + read_metadata: bool, + /// The library the folders were scanned in (`Session::library_generation`): photo ids are numbered per + /// library, so in another one they name other photos. + #[serde(default)] + library: u64, + }, About, Shortcuts, /// View ▸ View Options (⌘J): the info overlay and the lines of Info 1 and Info 2. Changes apply @@ -392,3 +407,32 @@ impl SyncCounts { !self.offline && self.new + self.moved + self.missing + self.metadata == 0 } } + +/// One folder of the Synchronize N Folders dialog. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SyncFolder { + pub path: String, + /// What the dialog calls it (a folder's last two names). + pub name: String, + /// What its scan found (`None` until it was scanned). + pub counts: Option, + /// Why it is left out (a whole disk, a folder that can't be scanned); it isn't scanned then. + #[serde(default)] + pub skipped: Option, + /// The missing and moved photos its scan found: the only ones its synchronize may remove or relink. + #[serde(default)] + pub missing: Vec, + #[serde(default)] + pub moved: Vec, + /// The photos whose sidecar changed: the only ones its synchronize may read. + #[serde(default)] + pub metadata: Vec, +} + +impl SyncFolder { + /// Whether it was scanned, or left out. + pub fn settled(&self) -> bool { + self.counts.is_some() || self.skipped.is_some() + } +} diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index db48585c6f3..42ae390d290 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -9,6 +9,10 @@ //! then runs as it was asked, but it removes, relinks or reads sidecars of only the photos its dialog showed: one that //! went missing, moved or got a sidecar update meanwhile was never shown to the person, so it is left alone, and the //! end says so. +//! +//! Synchronize N Folders (several Folders rows chosen at once) opens one dialog: the folders are scanned one after +//! another under one row ([`ManyScan`]), each says what changed, and one set of choices goes for all of them. Each +//! folder with something to do then waits in the library lane as a Synchronize of its own, in the sidebar's order. use std::sync::Arc; use std::sync::atomic::Ordering; @@ -18,7 +22,7 @@ use lightcraft_engine::sync::{FolderChanges, SyncChoice, SyncCommit, SyncInput, use serde_json::{Value, json}; use crate::LightcraftApp; -use crate::state::{Dialog, SyncCounts}; +use crate::state::{Dialog, SyncCounts, SyncFolder}; use crate::theme::Tokens; /// A running scan of the dialog's folder. @@ -288,6 +292,375 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { Ok(json!({"started": true})) } +// ---- Synchronize N Folders + +/// The scans of a Synchronize N Folders dialog: one folder after another, under one row of the activity stack. +pub struct ManyScan { + guard: TaskGuard, + /// The folder being scanned (its place in the dialog), how far it is, and where its result comes. + at: Option<(usize, Arc, std::sync::mpsc::Receiver)>, + /// Chosen folders left out because another chosen one takes them in: back in the dialog if that one can't be + /// synchronized after all. + covered: Vec, +} + +impl ManyScan { + /// Stop the folder being scanned. + fn stop(&self) { + if let Some((_, progress, _)) = &self.at { + progress.files.cancel.store(true, Ordering::Relaxed); + } + } +} + +/// `path` as a list of names (as the catalog spells a folder's identity), to tell whether one folder is inside another. +fn names(path: &str) -> Vec { + lightcraft_catalog::query::folder_key(path).split('/').filter(|n| !n.is_empty()).map(str::to_string).collect() +} + +/// Whether folder `inner` (its [`names`]) is inside folder `outer`. +fn inside(inner: &[String], outer: &[String]) -> bool { + inner.len() > outer.len() && inner.starts_with(outer) +} + +/// The folders Synchronize N Folders goes through, for library folders `paths` as the sidebar chose them, and the +/// ones it leaves out because another chosen one takes them in (synchronizing a folder takes in the folders inside +/// it). `order` is the sidebar's folders, as drawn (depth first): the folders go in that order, each once. A whole +/// disk is listed but left out, saying why: it is synchronized by itself, after its own question. +pub fn many_folders(paths: &[String], order: &[String]) -> (Vec, Vec) { + use lightcraft_catalog::query::folder_key; + let place = |p: &str| { + let k = folder_key(p); + order.iter().position(|o| folder_key(o) == k).unwrap_or(order.len()) + }; + let mut chosen: Vec<(usize, Vec, &String)> = paths.iter().map(|p| (place(p), names(p), p)).collect(); + // (a folder the sidebar doesn't show goes last, by name) + chosen.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + chosen.dedup_by(|a, b| a.1 == b.1); + let disk = |p: &str| lightcraft_catalog::folders::is_disk_root(p); + let folder = |p: &str| SyncFolder { + path: p.to_string(), + name: lightcraft_catalog::folders::folder_label(p), + skipped: disk(p).then(|| crate::i18n::tr("A whole disk: synchronize it by itself").to_string()), + ..Default::default() + }; + // (a disk left out takes in nothing) + let outers: Vec<&Vec> = chosen.iter().filter(|(_, _, p)| !disk(p)).map(|(_, n, _)| n).collect(); + let (covered, listed): (Vec<_>, Vec<_>) = chosen.iter().partition(|(_, n, _)| outers.iter().any(|o| inside(n, o))); + (listed.iter().map(|(_, _, p)| folder(p)).collect(), covered.iter().map(|(_, _, p)| folder(p)).collect()) +} + +/// The sidebar's library folders as drawn, depth first. +fn sidebar_order(app: &LightcraftApp) -> Vec { + fn walk(nodes: &[lightcraft_catalog::FolderNode], out: &mut Vec) { + for n in nodes { + out.push(n.path.clone()); + walk(&n.children, out); + } + } + let mut out = Vec::new(); + walk(&app.session.catalog.folder_tree(), &mut out); + out +} + +/// Open the Synchronize N Folders dialog for library folders `paths` and start scanning the first of them. +pub fn open_many(app: &mut LightcraftApp, paths: &[String]) -> Result<(), String> { + let (folders, covered) = many_folders(paths, &sidebar_order(app)); + if folders.is_empty() { + return Err("no folder to synchronize".into()); + } + cancel_many(app); + let guard = app.session.activity.start("scan", "Looking for changes", Cancel::Yes); + app.sync_scans = Some(ManyScan { guard, at: None, covered }); + let d = SyncChoice::default(); + app.ui.dialog = Some(Dialog::SynchronizeFolders { + folders, + import_new: d.import_new, + relink_moved: d.relink_moved, + remove_missing: d.remove_missing, + read_metadata: d.read_metadata, + library: app.session.library_generation(), + }); + Ok(()) +} + +/// Stop the scans of a Synchronize N Folders dialog that closed (Cancel, or another dialog): nothing to report, so +/// its row goes without a trace, as the single folder's does. +fn cancel_many(app: &mut LightcraftApp) { + if let Some(scan) = app.sync_scans.take() { + scan.stop(); + } +} + +/// Folder `at` of the dialog can't be synchronized (`why`): the chosen folders it took in come back after it, to be +/// scanned themselves (those inside one of them stay taken in by it). +pub(crate) fn skip(folders: &mut Vec, covered: &mut Vec, at: usize, why: String) { + let Some(f) = folders.get_mut(at) else { return }; + f.skipped = Some(why); + let outer = names(&f.path); + let (back, stay): (Vec, Vec) = std::mem::take(covered).into_iter().partition(|c| inside(&names(&c.path), &outer)); + *covered = stay; + let keys: Vec> = back.iter().map(|c| names(&c.path)).collect(); + let (top, under): (Vec<_>, Vec<_>) = back.into_iter().zip(&keys).partition(|(_, k)| !keys.iter().any(|o| inside(k, o))); + covered.extend(under.into_iter().map(|(c, _)| c)); + let at = at.saturating_add(1).min(folders.len()); + folders.splice(at..at, top.into_iter().map(|(c, _)| c)); +} + +/// Collect a finished folder scan into the Synchronize N Folders dialog and start the next (called every frame). Its +/// ✕ stops them and closes the dialog; so does opening another library (the folders and photos found were the +/// other library's). +pub fn poll_many(app: &mut LightcraftApp, ctx: &egui::Context) { + let library = match &app.ui.dialog { + Some(Dialog::SynchronizeFolders { library, .. }) => *library, + _ => { + cancel_many(app); + return; + } + }; + // (also after the last scan: another library opened meanwhile closes the dialog, whose photo ids are the old one's) + if library != app.session.library_generation() { + cancel_many(app); + app.ui.dialog = None; + return; + } + let Some(mut scan) = app.sync_scans.take() else { return }; + if scan.guard.is_cancelled() { + scan.stop(); + app.ui.dialog = None; + return; + } + let Some(Dialog::SynchronizeFolders { folders, .. }) = &mut app.ui.dialog else { return }; + if let Some((i, progress, rx)) = &scan.at { + let i = *i; + let found = match rx.try_recv() { + Err(std::sync::mpsc::TryRecvError::Empty) => { + let shown = folders + .get(i) + .map(|f| scan_row(progress, &f.name)) + .map(|(done, total, name)| if total > 0 { format!("{name} · {done} / {total}") } else { name }); + scan.guard.detail(&shown.unwrap_or_default()); + app.sync_scans = Some(scan); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + Ok(changes) => Some(changes), + // the worker died (a panic, logged) + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + }; + scan.at = None; + match found { + Some(c) => { + if let Some(f) = folders.get_mut(i) { + f.counts = Some(SyncCounts { + offline: c.offline, + new: c.new.len(), + duplicates: c.duplicates, + unreadable: c.unreadable.len(), + missing: c.missing.len(), + metadata: c.metadata.len(), + moved: c.moved.len(), + }); + f.missing = c.missing.iter().map(|m| m.id).collect(); + f.moved = c.moved.iter().map(|m| m.id).collect(); + f.metadata = c.metadata.iter().map(|m| m.id).collect(); + } + } + None => skip(folders, &mut scan.covered, i, crate::i18n::tr("Scan failed").to_string()), + } + } + // the next folder not looked at yet; one that can't be scanned says why and is passed over + while let Some(i) = folders.iter().position(|f| !f.settled()) { + let Some(f) = folders.get(i) else { break }; + match SyncInput::new(&mut app.session, &f.path, false) { + Ok(input) => { + let progress = Arc::new(SyncProgress::default()); + let (tx, rx) = std::sync::mpsc::channel(); + let p = progress.clone(); + let job = move || { + let _ = tx.send(scan_with(input, &p)); + }; + #[cfg(not(target_arch = "wasm32"))] + std::thread::spawn(job); + #[cfg(target_arch = "wasm32")] + job(); + scan.guard.progress(i as u64, folders.len() as u64); + scan.guard.detail(&f.name); + scan.at = Some((i, progress, rx)); + app.sync_scans = Some(scan); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + // (a folder holding disks, mostly: the engine's reason is for agents) + Err(_) => { + skip(folders, &mut scan.covered, i, crate::i18n::tr("Can't be synchronized with the others: synchronize it by itself").to_string()) + } + } + } + // all looked at + scan.guard.progress(folders.len() as u64, folders.len() as u64); +} + +/// Whether the Synchronize N Folders dialog has scanned every folder (its Synchronize waits for that). +pub fn many_scanned(dlg: &Dialog) -> bool { + matches!(dlg, Dialog::SynchronizeFolders { folders, .. } if folders.iter().all(SyncFolder::settled)) +} + +/// Whether a folder's scan found something the choices would do. +fn has_work(c: &SyncCounts, choice: &SyncChoice) -> bool { + !c.offline + && ((choice.import_new && c.new > 0) + || (choice.relink_moved && c.moved > 0) + || (choice.remove_missing && c.missing > 0) + || (choice.read_metadata && c.metadata > 0)) +} + +/// What the folders' scans found, added up (folders not there count nothing). +fn found(folders: &[SyncFolder]) -> SyncCounts { + let mut sum = SyncCounts::default(); + for c in folders.iter().filter(|f| f.skipped.is_none()).filter_map(|f| f.counts.as_ref()).filter(|c| !c.offline) { + sum.new = sum.new.saturating_add(c.new); + sum.moved = sum.moved.saturating_add(c.moved); + sum.missing = sum.missing.saturating_add(c.missing); + sum.metadata = sum.metadata.saturating_add(c.metadata); + sum.duplicates = sum.duplicates.saturating_add(c.duplicates); + sum.unreadable = sum.unreadable.saturating_add(c.unreadable); + } + sum +} + +/// Whether every folder was scanned and found up to date (none left out, none missing): the dialog only says so. +pub fn all_up_to_date(folders: &[SyncFolder]) -> bool { + !folders.is_empty() && folders.iter().all(|f| f.skipped.is_none() && f.counts.as_ref().is_some_and(SyncCounts::up_to_date)) +} + +/// What a folder's scan found, naming only what there is: "1500 new, 1 missing". +fn changes_found(c: &SyncCounts) -> String { + let mut parts = Vec::new(); + if c.new > 0 { + parts.push(crate::i18n::tr_format!("{n} new", n = c.new)); + } + if c.moved > 0 { + parts.push(crate::i18n::tr_format!("{n} moved", n = c.moved)); + } + if c.missing > 0 { + parts.push(crate::i18n::tr_format!("{n} missing", n = c.missing)); + } + if c.metadata > 0 { + parts.push(crate::i18n::tr_format!("{n} with changed sidecars", n = c.metadata)); + } + parts.join(", ") +} + +/// The body of the Synchronize N Folders dialog: a line per folder, then the choices with the folders' totals. +pub fn many_body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { + let Dialog::SynchronizeFolders { folders, import_new, relink_moved, remove_missing, read_metadata, .. } = dlg else { return }; + let t = Tokens::get(ui.ctx()); + let scanning = app.sync_scans.as_ref().and_then(|s| s.at.as_ref().map(|(i, p, _)| (*i, p.listing(), p.counts()))); + ui.set_min_width(460.0); + ui.label(crate::i18n::tr("Bring the library up to date with these folders and the folders inside them, one after another:")); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, f) in folders.iter().enumerate() { + let state = match (&f.skipped, &f.counts) { + (Some(why), _) => why.clone(), + (None, None) => match scanning { + Some((at, Some((listed, files)), _)) if at == i => listing_text(listed, files), + Some((at, None, (done, total))) if at == i && total > 0 => format!("{} {done} / {total}", crate::i18n::tr("Scanning…")), + Some((at, _, _)) if at == i => crate::i18n::tr("Scanning…").to_string(), + _ => crate::i18n::tr("Waiting to be scanned").to_string(), + }, + (None, Some(c)) if c.offline => { + crate::i18n::tr("This folder isn't there: it was moved or renamed, or its disk isn't connected.").to_string() + } + (None, Some(c)) if c.up_to_date() => crate::i18n::tr("Up to date").to_string(), + (None, Some(c)) => changes_found(c), + }; + let r = ui + .horizontal(|ui| { + ui.label(egui::RichText::new(f.name.as_str()).strong()).on_hover_text(f.path.as_str()); + ui.label(egui::RichText::new(state).color(t.text_dim)); + }) + .response; + crate::widgets::register(ui, format!("syncFolder:{i}"), r.rect); + } + }); + ui.add_space(6.0); + if all_up_to_date(folders) { + // nothing to choose: the answer takes the choices' place, and the one button closes (`only_shows`) + ui.label(crate::i18n::tr("Nothing to do: the library is up to date with these folders")); + return; + } + let sum = found(folders); + let choice = |ui: &mut egui::Ui, on: &mut bool, n: usize, text: String, widget: &str| { + let r = ui.add_enabled(n > 0, egui::Checkbox::new(on, text)); + crate::widgets::register(ui, widget, r.rect); + }; + let count = |text: &str, n: usize| format!("{} ({n})", crate::i18n::tr(text)); + choice(ui, import_new, sum.new, count("Import new photos", sum.new), "syncImportNew"); + choice(ui, relink_moved, sum.moved, count("Relink photos whose file was renamed or moved", sum.moved), "syncRelinkMoved"); + choice(ui, remove_missing, sum.missing, count("Remove missing photos from the library", sum.missing), "syncRemoveMissing"); + choice(ui, read_metadata, sum.metadata, count("Read metadata updates from XMP sidecars", sum.metadata), "syncReadMetadata"); + ui.add_space(6.0); + let dim = |ui: &mut egui::Ui, s: &str| ui.label(egui::RichText::new(s).color(t.text_dim)); + if sum.missing > 0 { + dim(ui, crate::i18n::tr("Missing photos move to Recently Deleted and can be restored; no file on disk is touched.")); + } + if sum.metadata > 0 { + dim(ui, crate::i18n::tr("Reading a sidecar replaces the photo's rating, labels, metadata and edits with what it says.")); + } + if sum.duplicates > 0 { + dim(ui, &count("Skipped: files already in the library elsewhere", sum.duplicates)); + } + if sum.unreadable > 0 { + dim(ui, &count("Skipped: files that can't be read", sum.unreadable)); + } +} + +/// Synchronize N Folders' Synchronize: each folder with something to do waits in the library lane as a Synchronize of +/// its own, in the dialog's order, removing or relinking only the photos its scan found (the first starts at once if +/// nothing else runs there). Folders up to date, not there or left out are passed over. +pub fn confirm_many(app: &mut LightcraftApp, dlg: &Dialog) -> Result { + let Dialog::SynchronizeFolders { folders, import_new, relink_moved, remove_missing, read_metadata, library } = dlg else { + return Err("not a Synchronize Folders dialog".into()); + }; + // (before the line and the library check: nothing is written, the dialog only closes, as for one folder) + if all_up_to_date(folders) { + return Ok(json!({"upToDate": true})); + } + // another library opened meanwhile (from the menu bar, an agent): the photos found are another library's + if *library != app.session.library_generation() { + return Err(crate::i18n::tr("Another library was opened: nothing was done").to_string()); + } + if !many_scanned(dlg) { + return Err("the folders are still being scanned".into()); + } + let choice = SyncChoice { import_new: *import_new, relink_moved: *relink_moved, remove_missing: *remove_missing, read_metadata: *read_metadata }; + let to_do: Vec<&SyncFolder> = folders.iter().filter(|f| f.skipped.is_none() && f.counts.as_ref().is_some_and(|c| has_work(c, &choice))).collect(); + // all or none: a line too full for them all takes none of them (the dialog stays, nothing half done) + let room = lightcraft_engine::activity::MAX_WAITING.saturating_sub(app.session.activity.waiting().len()); + if to_do.len() > room { + return Err(crate::i18n::tr_format!("Too many tasks are waiting: only {n} more can wait in line", n = room)); + } + let mut queued = Vec::new(); + for f in &to_do { + let shown = Shown { missing: f.missing.clone(), moved: f.moved.clone(), metadata: f.metadata.clone() }; + let request = sync_request(&f.path, &f.name, false, choice, &shown); + let (id, _) = app.session.activity.enqueue("sync", "Synchronizing folder", request)?; + queued.push(id); + } + let text = match queued.len() { + 0 if all_up_to_date(folders) => crate::i18n::tr("Nothing to do: the library is up to date with these folders").to_string(), + 0 if !found(folders).up_to_date() => crate::i18n::tr("Nothing to do with the choices ticked").to_string(), + 0 => crate::i18n::tr("Nothing was synchronized").to_string(), + 1 => crate::i18n::tr("Synchronizing the folder: see it under the bell").to_string(), + n => crate::i18n::tr_format!("Synchronizing {n} folders one after another: see them under the bell", n = n), + }; + let now = app.tick_now(); + app.ui.toast = Some((text, now + crate::TOAST_SECONDS, None)); + Ok(json!({"queued": queued})) +} + /// Hand the work of a synchronize to a worker thread, its steps committed between frames ([`poll_run`]). `left_alone`: /// photos found missing, moved or with a sidecar update that its dialog never showed, said at the end. fn run( @@ -347,6 +720,7 @@ fn sync_request(path: &str, name: &str, disk: bool, choice: SyncChoice, shown: & "importNew": choice.import_new, "relinkMoved": choice.relink_moved, "removeMissing": choice.remove_missing, "readMetadata": choice.read_metadata, "missing": shown.missing, "moved": shown.moved, "metadata": shown.metadata, }), + subject: name.to_string(), } } diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 354bdb73d22..8963c30178f 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -932,7 +932,11 @@ fn an_auto_import_with_no_room_in_line_is_left_for_the_next_listing() { let listing = || lightcraft_engine::cmd::library::list_auto_import_folder(&watched).unwrap(); let hold = h.app.session.activity.start("import", "Importing", Cancel::Yes); for _ in 0..MAX_WAITING { - h.app.session.activity.enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}) }).unwrap(); + h.app + .session + .activity + .enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}), ..Default::default() }) + .unwrap(); } crate::import::auto_import_listed(&mut h.app, listing()); crate::import::auto_import_listed(&mut h.app, listing()); diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index f50d5f2895e..79f0c5b82c2 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -421,7 +421,11 @@ fn a_synchronize_refused_for_a_full_line_keeps_what_its_dialog_showed() { tick_remove_missing(&mut h); let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); for _ in 0..MAX_WAITING { - h.app.session.activity.enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}) }).unwrap(); + h.app + .session + .activity + .enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}), ..Default::default() }) + .unwrap(); } let dlg = h.app.ui.dialog.take().expect("the dialog is open"); assert!(crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).is_err(), "no room in the line"); @@ -633,3 +637,247 @@ fn while_the_folder_is_listed_its_row_says_what_was_listed_and_its_bar_moves_on_ p.checked.store(10, Relaxed); assert_eq!(crate::sync::scan_row(&p, "photos/Various"), (10, 64085, "photos/Various".to_string())); } + +// ---- Synchronize N Folders + +/// Which folders Synchronize N Folders goes through: in the sidebar's order as drawn (a folder's insides before the +/// next folder, whatever the names' characters), each once; a folder inside another chosen one is taken in by it, and +/// a whole disk is listed but left out, saying why. +#[test] +fn several_folders_go_in_the_sidebars_order_without_those_inside_another() { + let sidebar = ["/pics", "/pics/2024", "/pics/2024/Jan", "/pics/2024-02", "/pics/Archive", "/pics/home", "/pics/home/garden", "/Volumes/Card"]; + let chosen = ["/pics/2024-02", "/pics/home/garden", "/pics/2024/Jan", "/pics/home", "/pics/Archive", "/pics/home", "/Volumes/Card"]; + let (folders, covered) = crate::sync::many_folders(&chosen.map(String::from), &sidebar.map(String::from)); + let listed: Vec<(&str, bool)> = folders.iter().map(|f| (f.path.as_str(), f.skipped.is_some())).collect(); + assert_eq!( + listed, + vec![("/pics/2024/Jan", false), ("/pics/2024-02", false), ("/pics/Archive", false), ("/pics/home", false), ("/Volumes/Card", true)] + ); + assert_eq!(folders[3].name, "pics/home"); + assert_eq!(covered.iter().map(|f| f.path.as_str()).collect::>(), vec!["/pics/home/garden"]); +} + +/// Given a folder taken in by another chosen one, when that one can't be synchronized after all (it holds disks, its +/// scan died), then the folder comes back into the dialog right after it, to be scanned itself. +#[test] +fn a_folder_taken_in_by_one_that_cant_be_synchronized_comes_back() { + let chosen = ["/mnt", "/mnt/card/2024", "/mnt/card/2024/day 1", "/pics"].map(String::from); + let (mut folders, mut covered) = crate::sync::many_folders(&chosen, &chosen); + assert_eq!(folders.iter().map(|f| f.path.as_str()).collect::>(), vec!["/mnt", "/pics"]); + crate::sync::skip(&mut folders, &mut covered, 0, "holds disks".into()); + assert_eq!(folders.iter().map(|f| f.path.as_str()).collect::>(), vec!["/mnt", "/mnt/card/2024", "/pics"]); + assert_eq!(covered.iter().map(|f| f.path.as_str()).collect::>(), vec!["/mnt/card/2024/day 1"], "still taken in by 2024"); +} + +/// `trip` (c new, b missing), `home` (g new), `still` (unchanged) and `gone` (its folder deleted), all imported. +fn changed_folders(dir: &Scratch) -> Headless { + write_png(&dir.path("trip/a.png"), 1); + write_png(&dir.path("trip/b.png"), 2); + write_png(&dir.path("home/f.png"), 6); + write_png(&dir.path("still/s.png"), 9); + write_png(&dir.path("gone/x.png"), 12); + let mut session = lightcraft_engine::Session::new().with_fs(); + let dirs: Vec = ["trip", "home", "still", "gone"].iter().map(|d| dir.path(d)).collect(); + session.execute("library.import", &json!({"paths": dirs})).unwrap(); + write_png(&dir.path("trip/c.png"), 3); + std::fs::remove_file(dir.path("trip/b.png")).unwrap(); + write_png(&dir.path("home/g.png"), 7); + std::fs::remove_dir_all(dir.path("gone")).unwrap(); + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 1200.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +/// Choose `folders` in the sidebar, right-click the first one's row and pick Synchronize N Folders…; wait for the +/// dialog's scans. +fn open_many_and_scan(h: &mut Headless, folders: &[String]) { + let r = h.request("engine.execute", json!({"command": "library.source", "params": {"kind": "libraryFolder", "paths": folders}}), T); + assert_eq!(r["ok"], true, "{r}"); + let row = format!("source:libfolder:{}", folders[0]); + assert!(h.step_until(T, |h| h.app.widgets.iter().any(|(w, _)| *w == row)), "no row {row}"); + let c = h.app.widgets.iter().find(|(w, _)| *w == row).map(|(_, r)| r.center()).unwrap(); + let r = h.request("ui.click", json!({"x": c.x, "y": c.y, "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "sideMenu:folders:synchronize"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. })), "the dialog opens at once: {:?}", h.app.ui.dialog); + assert!(h.step_until(T, |h| h.app.ui.dialog.as_ref().is_some_and(crate::sync::many_scanned)), "every folder was scanned"); +} + +fn many_folders_of(h: &Headless) -> Vec { + match &h.app.ui.dialog { + Some(Dialog::SynchronizeFolders { folders, .. }) => folders.clone(), + other => panic!("not the folders' dialog: {other:?}"), + } +} + +/// Given four folders chosen in the sidebar (two changed, one unchanged, one gone), when Synchronize 4 Folders… is +/// picked, then one dialog scans them one after another and says what changed in each; and Synchronize (with Remove +/// missing ticked) puts the two changed ones in line, in the sidebar's order, each named in its row, and they run one +/// after another: the new photos come in, the missing one goes, and the unchanged and gone folders are left alone. +#[test] +fn several_folders_are_scanned_in_one_dialog_and_synchronized_one_after_another() { + let dir = Scratch::new("many"); + let mut h = changed_folders(&dir); + let chosen: Vec = ["trip", "still", "gone", "home"].iter().map(|d| dir.path(d)).collect(); + open_many_and_scan(&mut h, &chosen); + let folders = many_folders_of(&h); + let found: Vec<(String, Option<(bool, usize, usize)>)> = folders + .iter() + .map(|f| (f.path.rsplit('/').next().unwrap_or("").to_string(), f.counts.as_ref().map(|c| (c.offline, c.new, c.missing)))) + .collect(); + assert_eq!( + found, + vec![ + ("gone".to_string(), Some((true, 0, 0))), + ("home".to_string(), Some((false, 1, 0))), + ("still".to_string(), Some((false, 0, 0))), + ("trip".to_string(), Some((false, 1, 1))), + ] + ); + if let Some(Dialog::SynchronizeFolders { remove_missing, .. }) = &mut h.app.ui.dialog { + *remove_missing = true; + } + assert_eq!(crate::panels::dialogs::confirm_label(&h.app, h.app.ui.dialog.as_ref().expect("the dialog is open")), "Synchronize"); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).expect("it synchronizes"); + assert_eq!(r["queued"].as_array().map(Vec::len), Some(2), "home and trip only: {r}"); + let waiting: Vec<(&str, String)> = h.app.session.activity.waiting().iter().map(|t| (t.kind, t.detail.clone())).collect(); + assert_eq!(waiting, vec![("sync", folders[1].name.clone()), ("sync", folders[3].name.clone())], "in the sidebar's order, named"); + let lines: Vec = h.app.session.activity.waiting().iter().map(crate::panels::activity::waiting_line).collect(); + assert_eq!( + lines, + vec![format!("{} · Starts next", folders[1].name), format!("{} · Starts after 1 more", folders[3].name)], + "each waiting row says which folder it is" + ); + let crosses: Vec = h.app.session.activity.waiting().iter().map(crate::panels::activity::cross_name).collect(); + assert_eq!( + crosses, + vec![ + format!("Remove from Queue: Synchronizing folder: {}", folders[1].name), + format!("Remove from Queue: Synchronizing folder: {}", folders[3].name) + ], + "each ✕ says which folder it removes" + ); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("2 folders")), "{:?}", h.app.ui.toast); + assert!(h.step_until(SETTLE, idle), "both ran"); + assert_eq!(in_library(&h), vec!["a.png", "c.png", "f.png", "g.png", "s.png", "x.png"], "b went; the gone folder's x stays"); +} + +/// Given several folders that were all scanned and are up to date, then the dialog only says so (no choices) and its +/// one button, Close, starts nothing; confirming it from the control channel answers `upToDate`. +#[test] +fn folders_that_are_all_up_to_date_are_only_reported() { + let dir = Scratch::new("many-uptodate"); + write_png(&dir.path("one/a.png"), 1); + write_png(&dir.path("two/b.png"), 2); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [dir.path("one"), dir.path("two")]})).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 1200.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + open_many_and_scan(&mut h, &[dir.path("one"), dir.path("two")]); + h.step(); + assert!(shown(&h, "button:dialogOk"), "one button, to close it"); + for gone in ["button:dialogCancel", "syncImportNew", "syncRelinkMoved", "syncRemoveMissing", "syncReadMetadata"] { + assert!(!shown(&h, gone), "nothing to choose: {gone}"); + } + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["upToDate"], true, "{r}"); + assert!(h.app.ui.dialog.is_none() && h.app.session.activity.waiting().is_empty(), "closed, and nothing waits"); +} + +/// Given the folders' dialog scanned in one library, when another library is opened before Synchronize, then it does +/// nothing: the photos it found are the other library's. +#[test] +fn the_folders_dialog_acts_only_in_the_library_it_was_opened_in() { + let dir = Scratch::new("many-switch"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("trip"), dir.path("home")]); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + h.app.session.open_library(dir.path("other"), false).unwrap(); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg); + assert!(r.is_err(), "{r:?}"); + assert!(h.app.session.activity.waiting().is_empty(), "nothing waits"); +} + +/// Given the folders' dialog scanned in one library, when another library is opened while it is still on screen, then +/// it closes by itself (its photo ids are the old library's), even though every scan has finished. +#[test] +fn a_library_opened_after_the_scans_closes_the_folders_dialog() { + let dir = Scratch::new("many-switch-open"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("trip"), dir.path("home")]); + h.app.session.open_library(dir.path("other"), false).unwrap(); + h.step(); + assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog); +} + +/// Given folders whose scans found changes, when Synchronize is confirmed with every choice that would act on them +/// unticked, then nothing is put in line and the toast says the choices ticked leave nothing to do. +#[test] +fn folders_with_nothing_to_do_for_the_choices_ticked_say_so() { + let dir = Scratch::new("many-nothing"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("trip"), dir.path("home")]); + if let Some(Dialog::SynchronizeFolders { import_new, .. }) = &mut h.app.ui.dialog { + *import_new = false; + } + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).expect("nothing to do is not an error"); + assert_eq!(r["queued"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(h.app.session.activity.waiting().is_empty(), "nothing waits"); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "Nothing to do with the choices ticked"), "{:?}", h.app.ui.toast); +} + +/// The folders' scans have one row; its ✕ stops them and closes the dialog, which then opens nothing later. +#[test] +fn the_folders_scans_row_cross_closes_their_dialog() { + let dir = Scratch::new("many-cross"); + let mut h = changed_folders(&dir); + crate::sync::open_many(&mut h.app, &[dir.path("trip"), dir.path("home")]).unwrap(); + assert!( + h.step_until(T, |h| h.app.session.activity.list().first().is_some_and(|r| !r.detail.is_empty())), + "the first folder's scan has started and its row names it" + ); + let rows = h.app.session.activity.list(); + assert_eq!((rows.len(), rows[0].kind, rows[0].label.as_str()), (1, "scan", "Looking for changes"), "{rows:?}"); + h.app.session.activity.cancel(rows[0].id).unwrap(); + h.step(); + assert!(h.app.sync_scans.is_none() && h.app.ui.dialog.is_none()); + assert!(h.app.session.activity.list().is_empty(), "the stopped scan's row is gone"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none(), "a stopped scan opens nothing later"); +} + +/// Given a line with room for only one of the two folders with something to do, when the dialog is confirmed from the +/// control channel, then it is refused (all or none), neither folder takes a place, and the dialog stays open (as its +/// button leaves it). +#[test] +fn the_folders_dialog_stays_open_when_confirmed_for_a_full_line_from_the_control_channel() { + use lightcraft_engine::activity::{MAX_WAITING, Request}; + let dir = Scratch::new("many-full-line"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("trip"), dir.path("home")]); + let hold = h.app.session.activity.start("import", "Importing", lightcraft_engine::activity::Cancel::Yes); + for _ in 0..MAX_WAITING - 1 { + h.app + .session + .activity + .enqueue("import", "Importing", Request { command: "app:import".into(), params: json!({}), ..Default::default() }) + .unwrap(); + } + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], false, "no room in the line: {r}"); + assert!(matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. })), "the dialog stays: {:?}", h.app.ui.dialog); + assert_eq!(h.app.session.activity.waiting().len(), MAX_WAITING - 1, "neither of the folders took a place"); + drop(hold); +} diff --git a/docs/background-tasks.md b/docs/background-tasks.md index a7ea722f6a5..64cc6e2ab5b 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -69,7 +69,10 @@ Jobs that must not run side by side share a lane (`activity::Lane`). There are t (`LightcraftApp::start_waiting`, every frame), and the engine leaves them alone (`Activity::take_ready_if`). Auto Import lists its folder only when nothing runs, rescans or waits in this lane; files it finds after something started meanwhile wait in line, quietly. A drop while a scan runs or an import's review waits behind a dialog is - still refused. + still refused. Synchronize N Folders (several Folders rows) scans its folders one after another under one + "Looking for changes" row, then puts one Synchronize per folder with something to do in this line, in the + sidebar's order, each removing, relinking or reading sidecars of only the photos its scan found; a waiting row names its folder + (`Request::subject`, the row's detail). A call that sets `queue: true` while its lane is busy does not fail: `Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b995019df3e..f0b76149977 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -106,7 +106,7 @@ filmstrip is visible. | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"` or `"library"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it; the app puts its own imports and Synchronize Folder there, `lane: "library"`); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"` or `"library"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it; the app puts its own imports and Synchronize Folder there, `lane: "library"`; a waiting Synchronize's `detail` is its folder's name); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | diff --git a/docs/gaps.md b/docs/gaps.md index e5ffd6869ce..7cef362ead6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,7 +45,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | -| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars (`library.source` `ids`/`paths`, `library.filter` `keywords`/`dates`). The menus, dragging and Delete key of those sidebars act on all the rows chosen (`album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder`, `folder.label` take several). Synchronize Folder is still for one folder at a time | `crates/ui-egui/src/panels/side_select.rs`, `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | +| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars (`library.source` `ids`/`paths`, `library.filter` `keywords`/`dates`). The menus, dragging and Delete key of those sidebars act on all the rows chosen (`album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder`, `folder.label` take several). Several chosen folders offer Synchronize N Folders…, which scans them one after another in one dialog and synchronizes each in the library lane (`crates/ui-egui/src/sync.rs`) | `crates/ui-egui/src/panels/side_select.rs`, `crates/engine/src/tests/multi_source.rs`; the checklist row is ✅ | Lightroom users who combine folders or collections by clicking | 4–8 | [ui-parity](ui-parity.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -197,3 +197,4 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-25 | minor | Gap 1: first chart-calibrated model, the Canon EOS D60 (ColorChecker Classic under tungsten and sun, `crates/raw/src/chart_table.rs`); the gap stays open, hours unchanged | | 2026-11-05 | minor | Gap 9: a Windows leg runs clippy and the tests of the crates with Windows-only code when a pull request or push changes that code, or a pull request is labelled `full-ci`; gap not closed (macOS, GPU tests) | | 2026-10-26 | minor | Gap 31 narrows: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and their menus, dragging and Delete act on them all; Synchronize Folder for several folders remains | +| 2026-10-29 | minor | Gap 31 narrows: several chosen folders offer Synchronize N Folders… (one dialog, scans one after another, each folder then synchronized in the library lane) | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7c5db507e90..f0138b2d258 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -459,7 +459,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-BEHAV-AUTOSAVE | Instant autosave | P0 | ✅ | `crates/catalog/src/journal.rs`, `crates/engine/src/library.rs` | every change fsynced before the command returns; a failed write fails the command ("saved in memory but not written to disk"), keeps the change queued and retries; top-bar warning until saved; a write that fails part-way is cut back to the last whole record so the retry never reads back as damage (logs from older builds with such a fragment load in full); quitting saves queued changes in the closing snapshot even when the log can't be appended to; versioned catalog format (`journal::VERSION`): older libraries are upgraded on open, a library from a newer LightCraft is refused untouched ("written by a newer version"); a damaged or hand-edited snapshot that still reads is made consistent on open (`Catalog::repair`: records filed under another id, stacks of missing, repeated or too few photos, folders inside themselves, id counters behind the ids in use) instead of panicking or hanging later | | LR-BEHAV-UNDO | Global undo | P0 | ✅ | `cmd:edit.undo`, `crates/engine/src/tests.rs` (`rating_flag_undo_redo`), `crates/engine/src/tests/filesystem_history.rs` | covers ratings, albums, deletes, edits; partial file/XMP moves keep unfinished repairs across retries and discarded history; merged renames move directly to their final catalog path | -| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `cmd:album.delete` / `cmd:album.move` (`ids`), `cmd:album.reorder` (`with`), `cmd:keyword.delete` / `cmd:keyword.move` (`keywords`), `cmd:library.removeFolder` / `cmd:folder.label` (`paths`), `crates/ui-egui/src/multi_select.rs`, `crates/ui-egui/src/panels/side_select.rs`, `crates/ui-egui/src/tests/multi_select.rs`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs`, `crates/engine/src/tests/batch_sidebar.rs` | photos in the grid; in the sidebars Cmd/Ctrl+click adds a row of Albums, Folders, Keywords or By Date or takes it away and Shift+click takes the rows between (as drawn: none inside a closed level), and the grid shows the photos of any of them, each once; the Keyword List picks several keywords the same way; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter; the menu of one of several rows acts on them all as one undo step (move, export or delete albums; label or remove folders; give keywords to the selected photos, take them away, merge or delete them), dragging one of several albums or keywords moves them all (dropped beside a row, the dragged album is placed there and the others come into that folder in the same step), and Delete asks about rows just chosen; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; with Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it | +| LR-BEHAV-MULTISELECT | Multi-selection | P0 | ✅ | `cmd:library.select` (`replace`/`add`/`toggle`/`range`), `cmd:library.selectAll`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `cmd:album.delete` / `cmd:album.move` (`ids`), `cmd:album.reorder` (`with`), `cmd:keyword.delete` / `cmd:keyword.move` (`keywords`), `cmd:library.removeFolder` / `cmd:folder.label` (`paths`), `crates/ui-egui/src/multi_select.rs`, `crates/ui-egui/src/panels/side_select.rs`, `crates/ui-egui/src/tests/multi_select.rs`, `crates/engine/src/tests/ids_params.rs` (`library_select_replace_drops_repeated_ids`), `crates/engine/src/tests/multi_source.rs`, `crates/engine/src/tests/batch_sidebar.rs` | photos in the grid; in the sidebars Cmd/Ctrl+click adds a row of Albums, Folders, Keywords or By Date or takes it away and Shift+click takes the rows between (as drawn: none inside a closed level), and the grid shows the photos of any of them, each once; the Keyword List picks several keywords the same way; for agents, several albums or folders can be the source and several keywords, dates, folders or albums the filter; the menu of one of several rows acts on them all as one undo step (move, export or delete albums; label or remove folders; give keywords to the selected photos, take them away, merge or delete them), dragging one of several albums or keywords moves them all (dropped beside a row, the dragged album is placed there and the others come into that folder in the same step), and Delete asks about rows just chosen; `replace` keeps each photo once, in the order first given, so a drag of the selection carries it once; with Hold View Until Refreshed on, a view of several albums holds a photo only while one of them has it; several folders' menu also offers Synchronize N Folders… (see LRC-LIB-LIBFOLDERS) | | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | @@ -705,7 +705,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290); the library last opened that is missing at launch (moved, or on a drive or network share that isn't connected) opens the can't-open window (Try Again, Choose Another, Continue Without Saving, Quit) instead of a new library with demo photos in its place (`apps/lightcraft/src/tests.rs`: `a_remembered_library_missing_at_launch_is_reported_not_made_anew`, issue #3239); a library's `catalog.snap` or folder given at launch (a double-click in the file manager) opens that library, through the usual launch path (lock check), makes it the library in use and is never imported; a second library argument gets a notice | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`), `crates/ui-egui/src/tests/move_folder.rs` | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken); Move Folder To… (here and in Folders) asks for the destination in a folder dialog that doesn't hold up the window (issue #3140); the rows of the standard places themselves (Pictures, Desktop, Downloads, Home) offer neither Rename Folder… nor Move Folder To…, while the folders inside them and the ones kept with Browse Folder… do, starting from their real name; `folder.rename` and `folder.move` refuse the home folder and its Pictures, Desktop and Downloads for every caller | -| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge, except on a row indented so far that its count (or colour dot) would cover its name: that count follows the name, wholly past the edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, which is kept only once the move has started, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | +| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge, except on a row indented so far that its count (or colour dot) would cover its name: that count follows the name, wholly past the edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, which is kept only once the move has started, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Several folders chosen at once offer Synchronize N Folders… (one dialog scans them one after another under one “Looking for changes” row and says what changed in each; one set of choices; each folder with something to do then waits in the library lane as a Synchronize of its own, in the sidebar's order, removing, relinking or reading sidecars of only the photos its scan found; a folder inside another chosen one is covered by it and comes back if that one can't be synchronized; whole disks, folders not there and folders up to date are passed over, saying why; a waiting row names its folder). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) | | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/dialogs/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 47 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/widgets/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/widgets/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents | | LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | | @@ -1057,3 +1057,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and several keywords in the Keyword List; menus, drags and Delete for several rows still to come; statuses unchanged | | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: the menu of several chosen sidebar rows, dragging one of them, and the Delete key act on them all as one undo step (they call `album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder` and `folder.label` with several); ✅ again after the 2026-10-23 downgrade | | 2026-10-29 | minor | LR-BEHAV-MULTISELECT: `album.reorder` takes `with` (the albums chosen with the dragged one), so a group of albums is dropped where an album chosen with the dragged one still has to move, and dropped beside a row it places the dragged album there in the same undo step; status unchanged (✅) | +| 2026-10-29 | minor | LRC-LIB-LIBFOLDERS: several folders' menu offers Synchronize N Folders… (one dialog, scans one after another, one set of choices; each folder then waits in the library lane in the sidebar's order, removing or relinking only the photos its scan found; waiting rows name their folder); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 9f4aefc9824..2fa6cafe7f0 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -146,6 +146,16 @@ ## 2026-10-29 +### Synchronize several folders at once +- Choose several folders in the Folders list (Cmd/Ctrl+click, Shift+click) and right-click: Synchronize N Folders… + opens one dialog. It looks at the folders one after another and says, for each, what changed (new, moved, missing, + with changed sidecars) or that it is up to date; the choices below count them all. +- Synchronize then brings the library up to date with each folder in turn, in the order the sidebar lists them, under + the bell. Each one removes or relinks only the photos its scan found, and a folder that is up to date, isn't there (moved, + renamed, or on a disk that isn't connected) or is a whole disk is passed over, and the dialog says why. +- A folder inside another chosen one is taken in with it, not done twice. Cancel leaves nothing behind under the bell; + the rows waiting in line name their folder. + ### A person's page opens in seconds in a large library - Finding the unnamed faces that look like a person (a person's page, and again after each face confirmed there) now runs on every processor core, and each comparison of two faces uses the processor's vector instructions. In a @@ -336,7 +346,6 @@ a second. On a Mac the window also holds one drawable less: its width × height × 4 bytes, 15–22 MB for a 1200–1500-point-wide window on a Retina display. - ## 2026-10-26 ### Choose several albums, folders, keywords or dates in the sidebars From eb04b54d4ea452e8458492a296140cade3f236b5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 23:51:14 -0400 Subject: [PATCH 48/55] Synchronize several folders: the docs and a comment also say it reads sidecars of only the photos its scan found --- crates/ui-egui/src/sync.rs | 4 ++-- docs/parity-checklist.md | 2 +- docs/whats-new.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 42ae390d290..17c03b53740 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -618,8 +618,8 @@ pub fn many_body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { } /// Synchronize N Folders' Synchronize: each folder with something to do waits in the library lane as a Synchronize of -/// its own, in the dialog's order, removing or relinking only the photos its scan found (the first starts at once if -/// nothing else runs there). Folders up to date, not there or left out are passed over. +/// its own, in the dialog's order, removing, relinking or reading sidecars of only the photos its scan found (the +/// first starts at once if nothing else runs there). Folders up to date, not there or left out are passed over. pub fn confirm_many(app: &mut LightcraftApp, dlg: &Dialog) -> Result { let Dialog::SynchronizeFolders { folders, import_new, relink_moved, remove_missing, read_metadata, library } = dlg else { return Err("not a Synchronize Folders dialog".into()); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index f0138b2d258..d5325b1c49d 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1057,4 +1057,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars, and several keywords in the Keyword List; menus, drags and Delete for several rows still to come; statuses unchanged | | 2026-10-26 | minor | LR-BEHAV-MULTISELECT: the menu of several chosen sidebar rows, dragging one of them, and the Delete key act on them all as one undo step (they call `album.delete`, `album.move`, `keyword.delete`, `keyword.move`, `library.removeFolder` and `folder.label` with several); ✅ again after the 2026-10-23 downgrade | | 2026-10-29 | minor | LR-BEHAV-MULTISELECT: `album.reorder` takes `with` (the albums chosen with the dragged one), so a group of albums is dropped where an album chosen with the dragged one still has to move, and dropped beside a row it places the dragged album there in the same undo step; status unchanged (✅) | -| 2026-10-29 | minor | LRC-LIB-LIBFOLDERS: several folders' menu offers Synchronize N Folders… (one dialog, scans one after another, one set of choices; each folder then waits in the library lane in the sidebar's order, removing or relinking only the photos its scan found; waiting rows name their folder); status unchanged (✅) | +| 2026-10-29 | minor | LRC-LIB-LIBFOLDERS: several folders' menu offers Synchronize N Folders… (one dialog, scans one after another, one set of choices; each folder then waits in the library lane in the sidebar's order, removing, relinking or reading sidecars of only the photos its scan found; waiting rows name their folder); status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 2fa6cafe7f0..e999aef1d6f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -151,7 +151,7 @@ opens one dialog. It looks at the folders one after another and says, for each, what changed (new, moved, missing, with changed sidecars) or that it is up to date; the choices below count them all. - Synchronize then brings the library up to date with each folder in turn, in the order the sidebar lists them, under - the bell. Each one removes or relinks only the photos its scan found, and a folder that is up to date, isn't there (moved, + the bell. Each one removes, relinks or reads sidecars of only the photos its scan found, and a folder that is up to date, isn't there (moved, renamed, or on a disk that isn't connected) or is a whole disk is passed over, and the dialog says why. - A folder inside another chosen one is taken in with it, not done twice. Cancel leaves nothing behind under the bell; the rows waiting in line name their folder. From 3bc747a9f447c621c32be27cad184c9a6170ead5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 30 Oct 2026 06:13:27 -0400 Subject: [PATCH 49/55] Synchronize several folders: ui.dialog.confirm's reply for the folders' dialog is documented, and the parity summary is regenerated --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f0b76149977..c82c1fef13d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -100,7 +100,7 @@ filmstrip is visible. | `ui.scroll` | `{dx, dy, source?, unit?, phase?, cmd?, ctrl?, shift?, alt?}` | Wheel / two-finger scroll at the current pointer; pans over the image, modifier-scroll zooms. `source` is `unknown` (default), `wheel`, `trackpad` or `momentum`; `unit` is `point` (default), `line` or `page`; `phase` is `move` (default), `start`, `end` or `cancel`. Wheel/line events drive the grid/filmstrip one-third wheel step and the loupe's notch zoom; trackpad/momentum phases drive kinetic scrolling and rubber-band boundaries. Invalid values are refused and queue nothing | | `ui.zoom` | `{factor}` | Pinch zoom at the current pointer (positive scale multiplier; 1 = unchanged). Position it first with `ui.move` or `ui.hoverWidget` | | `ui.set` | partial UI state, e.g. `{"view": "detail"}` | Resulting UI state | -| `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing; the Import review and Synchronize Folder answer `{queued, place}` instead of `{importing}` / `{started}` while an import or a synchronize runs: the task waits in line and starts by itself) | +| `ui.dialog.confirm` / `ui.dialog.cancel` | — | Close the open dialog (confirm runs its action; Synchronize Folder on a folder that is up to date answers `{"upToDate": true}` and starts nothing; the Import review and Synchronize Folder answer `{queued, place}` instead of `{importing}` / `{started}` while an import or a synchronize runs: the task waits in line and starts by itself; Synchronize N Folders answers `{queued: [ids]}` (one waiting Synchronize per folder with something to do, in the sidebar's order; empty when the ticked choices leave nothing to do) or `{upToDate: true}`, and is refused, with the dialog left open, when the line has no room for all of them or another library was opened) | | `ui.resize` | `{width, height}` | Resize the window | | `ui.dropFiles` | `{paths: [..], hover?}` | Files dragged from the file manager. `hover: true` makes every following frame report `paths` as hovered over the window (the drop card appears, `ui.widgets` lists `dropOverlay`) until another `ui.dropFiles` replaces them; `{paths: [], hover: true}` ends the hover. Without `hover` the files are dropped: the hover ends and the next frame receives them as dropped files, exactly as an OS drop arrives (photos and folders open the import review, or import at once with Settings ▸ Import ▸ Import dropped files without review). An empty path stands for a file whose path the platform doesn't tell | | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | From 0516e7d4cadb85ca0d87b8112548e39242f07036 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 08:39:13 -0500 Subject: [PATCH 50/55] Synchronize several folders: rustfmt of the restack's resolutions (import re-exports, one build spawn line) Co-Authored-By: Claude --- crates/engine/src/cmd/previews.rs | 3 ++- crates/ui-egui/src/dialogs/import.rs | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 4673c568985..d89a13e201e 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -637,7 +637,8 @@ fn build(s: &mut Session, p: &Value) -> Result { std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)) }; #[cfg(not(test))] - let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)); + let started = + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)); // never started: nothing was made the session's build (which would hold every later build back), and the // background build it was to replace carries on if let Err(e) = started { diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index c165f72ce28..ce7fb9656d3 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -41,12 +41,12 @@ pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summar pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; #[cfg(test)] use body::{RECIPE_CONTROLS, note_recipe_value}; -pub(crate) use scan::{StoppingScans, library_busy}; -#[cfg(not(target_arch = "wasm32"))] -pub(crate) use scan::{auto_import_listed, cards_seen}; #[cfg(test)] pub(crate) use scan::{HELD_RESOLVES, ScanEnd, scan_by_hand, stall_scan, stall_scan_of}; pub use scan::{IMPORT_REQUEST, ScanTask, browse, drop_blocked, open, poll_scan, running}; +pub(crate) use scan::{StoppingScans, library_busy}; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use scan::{auto_import_listed, cards_seen}; pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; pub use task::{ImportTask, start, start_paths, start_request, tick}; From f3d4275e8eebac4184bc67de857d4fa7d17fdc7b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 08:48:49 -0500 Subject: [PATCH 51/55] Preview builds: a build asked to queue behind one with no row of its own is refused, not lost A build with row: false holds no lane, so a build put in line behind it was started at once, refused as already running, and dropped. Co-Authored-By: Claude --- crates/engine/src/cmd/previews.rs | 5 +++++ crates/engine/src/tests/task_queue.rs | 29 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index d89a13e201e..f8758cd1f6a 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -286,6 +286,11 @@ fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, prep: bool, request if !build_running(s, prep) && !s.activity.lane_waiting(Lane::Previews) { return None; } + // a build with no row of its own (`row: false`) never frees the lane for the line: what waited behind it would be + // started at once, refused as already running, and lost + if build_running(s, prep) && !s.activity.lane_busy(Lane::Previews) { + return Some(Err(bad(c, REFUSED))); + } if p.get("wait").and_then(Value::as_bool) == Some(true) { return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); } diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs index dec866a23f1..d130d3a4ec0 100644 --- a/crates/engine/src/tests/task_queue.rs +++ b/crates/engine/src/tests/task_queue.rs @@ -228,6 +228,35 @@ fn a_build_that_would_wait_for_its_turn_and_its_end_is_refused() { release(h); } +/// Given a build with no row of its own (`row: false`) running, when a build is asked for with `queue`, then it is +/// refused as before, and nothing waits: a build in line behind it would be started at once, refused as running, and +/// lost, because no row ever holds the lane. +#[test] +fn a_build_asked_to_queue_behind_one_with_no_row_is_refused_not_lost() { + let mut s = Session::with_demo(); + let build = Arc::new(PreviewBuild::default()); + s.preview_build = Some(build.clone()); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + assert!(tasks(&mut s).is_empty(), "nothing waits"); + build.finished.store(true, Ordering::Release); +} + +/// Given the background preparation running, when a build is asked for with `queue`, then it starts at once, as one +/// without `queue` does, and the preparation stops: it gives way, it is not waited for. +#[test] +fn a_build_asked_to_queue_while_the_background_preparation_runs_starts_at_once() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let prep = Arc::new(PreviewBuild { background: true, ..Default::default() }); + s.preview_build = Some(prep.clone()); + let _row = s.activity.start("previews", "Preparing photos in the background", Cancel::Yes); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!(r["total"].as_u64(), Some(2), "{r}"); + assert!(prep.cancel.load(Ordering::Relaxed), "the preparation was stopped"); +} + /// Given a build waiting and one still running, when another library is opened, then nothing waits any more: the /// build asked for was about the old library's photos. #[test] From c9e65834d78a9e898796a98d31c9e9d87c069dbc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 09:21:50 -0500 Subject: [PATCH 52/55] Synchronize several folders: tests for the scan-failure, one-folder and nothing-synchronized cases, the sidebar-order fallback keyed once, wrapped folder states Co-Authored-By: Claude --- crates/ui-egui/src/sync.rs | 29 +++++--- crates/ui-egui/src/tests/sync.rs | 114 ++++++++++++++++++++++++++++++- 2 files changed, 133 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 17c03b53740..fa54f270654 100644 --- a/crates/ui-egui/src/sync.rs +++ b/crates/ui-egui/src/sync.rs @@ -298,7 +298,7 @@ pub fn confirm(app: &mut LightcraftApp, dlg: &Dialog) -> Result { pub struct ManyScan { guard: TaskGuard, /// The folder being scanned (its place in the dialog), how far it is, and where its result comes. - at: Option<(usize, Arc, std::sync::mpsc::Receiver)>, + pub(crate) at: Option<(usize, Arc, std::sync::mpsc::Receiver)>, /// Chosen folders left out because another chosen one takes them in: back in the dialog if that one can't be /// synchronized after all. covered: Vec, @@ -315,7 +315,12 @@ impl ManyScan { /// `path` as a list of names (as the catalog spells a folder's identity), to tell whether one folder is inside another. fn names(path: &str) -> Vec { - lightcraft_catalog::query::folder_key(path).split('/').filter(|n| !n.is_empty()).map(str::to_string).collect() + key_names(&lightcraft_catalog::query::folder_key(path)) +} + +/// The names of a folder's identity key ([`folder_key`](lightcraft_catalog::query::folder_key)). +fn key_names(key: &str) -> Vec { + key.split('/').filter(|n| !n.is_empty()).map(str::to_string).collect() } /// Whether folder `inner` (its [`names`]) is inside folder `outer`. @@ -329,11 +334,18 @@ fn inside(inner: &[String], outer: &[String]) -> bool { /// disk is listed but left out, saying why: it is synchronized by itself, after its own question. pub fn many_folders(paths: &[String], order: &[String]) -> (Vec, Vec) { use lightcraft_catalog::query::folder_key; - let place = |p: &str| { - let k = folder_key(p); - order.iter().position(|o| folder_key(o) == k).unwrap_or(order.len()) - }; - let mut chosen: Vec<(usize, Vec, &String)> = paths.iter().map(|p| (place(p), names(p), p)).collect(); + // (each sidebar folder's key made once: the first of two spellings of one folder wins) + let mut index: std::collections::HashMap = std::collections::HashMap::with_capacity(order.len()); + for (i, o) in order.iter().enumerate() { + index.entry(folder_key(o)).or_insert(i); + } + let mut chosen: Vec<(usize, Vec, &String)> = paths + .iter() + .map(|p| { + let key = folder_key(p); + (index.get(&key).copied().unwrap_or(order.len()), key_names(&key), p) + }) + .collect(); // (a folder the sidebar doesn't show goes last, by name) chosen.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); chosen.dedup_by(|a, b| a.1 == b.1); @@ -576,8 +588,9 @@ pub fn many_body(app: &LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dialog) { (None, Some(c)) if c.up_to_date() => crate::i18n::tr("Up to date").to_string(), (None, Some(c)) => changes_found(c), }; + // (the state wraps under the name when it doesn't fit, as the other dialogs' long lines do) let r = ui - .horizontal(|ui| { + .horizontal_wrapped(|ui| { ui.label(egui::RichText::new(f.name.as_str()).strong()).on_hover_text(f.path.as_str()); ui.label(egui::RichText::new(state).color(t.text_dim)); }) diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index 79f0c5b82c2..89bc23a52dc 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -669,6 +669,18 @@ fn a_folder_taken_in_by_one_that_cant_be_synchronized_comes_back() { assert_eq!(covered.iter().map(|f| f.path.as_str()).collect::>(), vec!["/mnt/card/2024/day 1"], "still taken in by 2024"); } +/// Given chosen folders the sidebar doesn't show (its order lacks them), then they go after the ones it shows, by +/// name. +#[test] +fn a_chosen_folder_missing_from_the_sidebar_goes_after_the_others_by_name() { + let sidebar = ["/pics/Zed", "/pics/Beta"].map(String::from); + let chosen = ["/pics/Cat", "/pics/Beta", "/pics/Ant", "/pics/Zed"].map(String::from); + let (folders, covered) = crate::sync::many_folders(&chosen, &sidebar); + let listed: Vec<&str> = folders.iter().map(|f| f.path.as_str()).collect(); + assert_eq!(listed, vec!["/pics/Zed", "/pics/Beta", "/pics/Ant", "/pics/Cat"], "the sidebar's, then the rest by name"); + assert!(covered.is_empty()); +} + /// `trip` (c new, b missing), `home` (g new), `still` (unchanged) and `gone` (its folder deleted), all imported. fn changed_folders(dir: &Scratch) -> Headless { write_png(&dir.path("trip/a.png"), 1); @@ -705,8 +717,11 @@ fn open_many_and_scan(h: &mut Headless, folders: &[String]) { h.step(); let r = h.request("ui.clickWidget", json!({"id": "sideMenu:folders:synchronize"}), T); assert_eq!(r["ok"], true, "{r}"); - h.step(); - assert!(matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. })), "the dialog opens at once: {:?}", h.app.ui.dialog); + assert!( + h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. }))), + "the dialog opens: {:?}", + h.app.ui.dialog + ); assert!(h.step_until(T, |h| h.app.ui.dialog.as_ref().is_some_and(crate::sync::many_scanned)), "every folder was scanned"); } @@ -881,3 +896,98 @@ fn the_folders_dialog_stays_open_when_confirmed_for_a_full_line_from_the_control assert_eq!(h.app.session.activity.waiting().len(), MAX_WAITING - 1, "neither of the folders took a place"); drop(hold); } + +/// Given two chosen folders, one up to date and one changed, when Synchronize is confirmed, then the one folder with +/// something to do is put in line, and the toast speaks of one folder, not "1 folders". +#[test] +fn one_folder_with_something_to_do_is_put_in_line_and_the_toast_says_so() { + let dir = Scratch::new("many-one"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("still"), dir.path("trip")]); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).expect("it synchronizes"); + assert_eq!(r["queued"].as_array().map(Vec::len), Some(1), "trip only: {r}"); + assert!( + h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "Synchronizing the folder: see it under the bell"), + "{:?}", + h.app.ui.toast + ); +} + +/// Given folders that are up to date or not there (nothing is wrong with the choices: the scans found nothing to +/// do), when Synchronize is confirmed, then nothing is put in line and the toast says nothing was synchronized. +#[test] +fn folders_that_are_up_to_date_or_not_there_synchronize_nothing() { + let dir = Scratch::new("many-offline"); + let mut h = changed_folders(&dir); + open_many_and_scan(&mut h, &[dir.path("still"), dir.path("gone")]); + let found: Vec<(bool, bool)> = many_folders_of(&h).iter().map(|f| (f.counts.as_ref().is_some_and(|c| c.offline), f.skipped.is_some())).collect(); + assert_eq!(found, vec![(true, false), (false, false)], "gone is not there, still is up to date"); + let dlg = h.app.ui.dialog.take().expect("the dialog is open"); + let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).expect("nothing to do is not an error"); + assert_eq!(r["queued"].as_array().map(Vec::len), Some(0), "{r}"); + assert!(h.app.session.activity.waiting().is_empty(), "nothing waits"); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "Nothing was synchronized"), "{:?}", h.app.ui.toast); +} + +/// `outer` holding `inner`, both imported, with the folders' dialog open for both: `outer` is listed and `inner`, +/// taken in by it, waits to come back if `outer` can't be synchronized. +fn nested_folders(dir: &Scratch) -> (Headless, String, String) { + write_png(&dir.path("outer/a.png"), 1); + write_png(&dir.path("outer/inner/b.png"), 2); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [dir.path("outer")]})).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 1200.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let (outer, inner) = (dir.path("outer"), dir.path("outer/inner")); + crate::sync::open_many(&mut h.app, &[outer.clone(), inner.clone()]).unwrap(); + (h, outer, inner) +} + +/// Assert the folders' dialog lists `outer` as left out for `why` and `inner` as scanned. +fn outer_left_out_inner_scanned(h: &Headless, outer: &str, inner: &str, why: &str) { + let folders = many_folders_of(h); + let state = |p: &str| folders.iter().find(|f| f.path == p).map(|f| (f.skipped.clone(), f.counts.is_some())); + assert_eq!(state(outer), Some((Some(why.to_string()), false)), "{folders:?}"); + assert_eq!(state(inner), Some((None, true)), "the folder it took in is listed and scanned: {folders:?}"); +} + +/// Given a folder that takes in another chosen one but whose scan can't start (it holds disks), when the dialog +/// scans, then the outer folder says why it was left out and the folder it took in is scanned and listed after all. +#[test] +fn a_folder_whose_scan_cant_start_gives_back_the_folder_it_took_in() { + use lightcraft_catalog::{Op, Photo, Source}; + let mut session = lightcraft_engine::Session::new().with_fs(); + for path in ["/Volumes/lc-sync-card/2024/a.jpg", "/Volumes/lc-sync-card/2024/day/b.jpg"] { + let id = session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 1200.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + // (`/Volumes` lies above a disk: the engine refuses to scan it with the others) + let (outer, inner) = ("/Volumes".to_string(), "/Volumes/lc-sync-card/2024".to_string()); + crate::sync::open_many(&mut h.app, &[outer.clone(), inner.clone()]).unwrap(); + assert_eq!(many_folders_of(&h).iter().map(|f| f.path.as_str()).collect::>(), vec![outer.as_str()], "the inner one is taken in"); + assert!(h.step_until(T, |h| h.app.ui.dialog.as_ref().is_some_and(crate::sync::many_scanned)), "every folder was scanned"); + outer_left_out_inner_scanned(&h, &outer, &inner, "Can't be synchronized with the others: synchronize it by itself"); +} + +/// Given a folder that takes in another chosen one whose scan's worker dies (its result never comes), when the +/// dialog polls, then the outer folder says its scan failed and the folder it took in is scanned and listed after all. +#[test] +fn a_folder_whose_scan_dies_gives_back_the_folder_it_took_in() { + let dir = Scratch::new("many-died"); + let (mut h, outer, inner) = nested_folders(&dir); + assert_eq!(many_folders_of(&h).iter().map(|f| f.path.as_str()).collect::>(), vec![outer.as_str()], "the inner one is taken in"); + let (tx, rx) = std::sync::mpsc::channel(); + drop(tx); + let Some(scan) = h.app.sync_scans.as_mut() else { panic!("the dialog's scans are set up") }; + scan.at = Some((0, std::sync::Arc::new(lightcraft_engine::sync::SyncProgress::default()), rx)); + assert!(h.step_until(T, |h| h.app.ui.dialog.as_ref().is_some_and(crate::sync::many_scanned)), "every folder was scanned"); + outer_left_out_inner_scanned(&h, &outer, &inner, "Scan failed"); +} From 1d5913678eecdfa7c4f90200bb759a22fce2f755 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 09:24:32 -0500 Subject: [PATCH 53/55] Synchronize several folders: rustfmt of the new tests Co-Authored-By: Claude --- crates/ui-egui/src/tests/sync.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/tests/sync.rs b/crates/ui-egui/src/tests/sync.rs index 89bc23a52dc..62ffaefbbac 100644 --- a/crates/ui-egui/src/tests/sync.rs +++ b/crates/ui-egui/src/tests/sync.rs @@ -717,11 +717,7 @@ fn open_many_and_scan(h: &mut Headless, folders: &[String]) { h.step(); let r = h.request("ui.clickWidget", json!({"id": "sideMenu:folders:synchronize"}), T); assert_eq!(r["ok"], true, "{r}"); - assert!( - h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. }))), - "the dialog opens: {:?}", - h.app.ui.dialog - ); + assert!(h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::SynchronizeFolders { .. }))), "the dialog opens: {:?}", h.app.ui.dialog); assert!(h.step_until(T, |h| h.app.ui.dialog.as_ref().is_some_and(crate::sync::many_scanned)), "every folder was scanned"); } @@ -907,11 +903,7 @@ fn one_folder_with_something_to_do_is_put_in_line_and_the_toast_says_so() { let dlg = h.app.ui.dialog.take().expect("the dialog is open"); let r = crate::panels::dialogs::confirm_dialog(&mut h.app, &dlg).expect("it synchronizes"); assert_eq!(r["queued"].as_array().map(Vec::len), Some(1), "trip only: {r}"); - assert!( - h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "Synchronizing the folder: see it under the bell"), - "{:?}", - h.app.ui.toast - ); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0 == "Synchronizing the folder: see it under the bell"), "{:?}", h.app.ui.toast); } /// Given folders that are up to date or not there (nothing is wrong with the choices: the scans found nothing to From 3aefe5b76476c98daac97502f09a146c468050fc Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 10:16:08 -0500 Subject: [PATCH 54/55] Preview builds: a build with no row of its own is refused a place in line, not started from it without holding the lane A queued `row: false` build started from the line without a TaskGuard, so Session::start_waiting took the next build out of the line while it ran, and that one was refused as running and lost (CodeRabbit on #3363). Co-Authored-By: Claude --- crates/engine/src/cmd/previews.rs | 16 +++++++++----- crates/engine/src/tests/task_queue.rs | 31 +++++++++++++++++++++++++++ docs/background-tasks.md | 1 + 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index f8758cd1f6a..dd14fccb8d0 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -281,8 +281,9 @@ fn build_running(s: &Session, prep: bool) -> bool { } /// A build asked for with `queue`: while one runs (or others already wait) this one waits in line behind them → -/// `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. (`prep`: as [`build_running`].) -fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, prep: bool, request: &Request) -> Option> { +/// `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. (`prep`: as [`build_running`]; `row`: the +/// build will have a row of its own, which holds the lane while it runs.) +fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, prep: bool, row: bool, request: &Request) -> Option> { if !build_running(s, prep) && !s.activity.lane_waiting(Lane::Previews) { return None; } @@ -291,6 +292,11 @@ fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, prep: bool, request if build_running(s, prep) && !s.activity.lane_busy(Lane::Previews) { return Some(Err(bad(c, REFUSED))); } + // nor can one that would start from the line without a row of its own: it would not hold the lane, and the build + // behind it would be started at once, refused as already running, and lost + if !row { + return Some(Err(bad(c, "a build with no row of its own can't wait in line: leave out row or queue"))); + } if p.get("wait").and_then(Value::as_bool) == Some(true) { return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); } @@ -604,7 +610,7 @@ fn build(s: &mut Session, p: &Value) -> Result { } else { s.visible_cloned() }; - if queue && let Some(queued) = wait_in_line(s, C, p, "", background, &request_for(C, p, &ids)) { + if queue && let Some(queued) = wait_in_line(s, C, p, "", background, row, &request_for(C, p, &ids)) { return queued; } let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); @@ -832,7 +838,7 @@ fn smart(s: &mut Session, p: &Value) -> Result { return Err(bad(C, REFUSED)); } let what = if discard { "discarding smart previews" } else { "smart previews" }; - if queue && let Some(queued) = wait_in_line(s, C, p, what, false, &request_for(C, p, &ids)) { + if queue && let Some(queued) = wait_in_line(s, C, p, what, false, true, &request_for(C, p, &ids)) { return queued; } let mut jobs: Vec = Vec::new(); @@ -1042,7 +1048,7 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background; the background preparation gives way to a build asked for): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background; the background preparation gives way to a build asked for): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs, and not with `row: false` (no row would hold the lane for it: refused)", always, build ), diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs index d130d3a4ec0..8552b5b9f68 100644 --- a/crates/engine/src/tests/task_queue.rs +++ b/crates/engine/src/tests/task_queue.rs @@ -242,6 +242,37 @@ fn a_build_asked_to_queue_behind_one_with_no_row_is_refused_not_lost() { build.finished.store(true, Ordering::Release); } +/// Given a build running with its row, when a build with no row of its own (`row: false`) is asked for with `queue`, +/// then it is refused and nothing waits: it would start from the line without holding the lane, and the build asked +/// for after it would be started at once, refused as running, and lost. A build asked for with `queue` after that +/// still waits and starts when the running one ends. +#[test] +fn a_build_with_no_row_of_its_own_is_refused_a_place_in_line_and_the_next_one_is_not_lost() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "row": false})).unwrap_err().to_string(); + assert!(e.contains("no row of its own"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is listed"); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(r["place"], 1, "{r}"); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(2), Some(2)), "{progress}"); +} + +/// Given no build running, when a build with no row of its own is asked for with `queue`, then it starts at once, as +/// one without `queue` does: there is nothing to wait for. +#[test] +fn a_build_with_no_row_that_asks_to_queue_starts_at_once_when_nothing_is_ahead_of_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "row": false, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!((r["total"].as_u64(), r["done"].as_u64()), (Some(2), Some(2)), "{r}"); +} + /// Given the background preparation running, when a build is asked for with `queue`, then it starts at once, as one /// without `queue` does, and the preparation stops: it gives way, it is not waited for. #[test] diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 64cc6e2ab5b..93fff02a775 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -82,6 +82,7 @@ every command and the app every frame. `activity.list` shows a waiting task afte of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged (the app's own, an import or a Synchronize Folder, also says why in a toast) and the next in line goes on. +A build asked for with `row: false` (no row of its own: the job that asked shows its progress) starts at once when the lane is free. While the lane is busy it is refused, `queue` or not: from the line it would start without holding the lane, and the build behind it would be started at once, refused as running, and lost. ## Examples in the code From bc0e314dd276215294f1384597090535b29388da Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 15 Nov 2026 10:16:08 -0500 Subject: [PATCH 55/55] Synchronize several folders: the translation test no longer asks for the unused "Choose one folder to synchronize it" Co-Authored-By: Claude --- crates/ui-egui/src/i18n/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index dce7928d9e0..4ad4178f97b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -167,11 +167,10 @@ fn the_welcome_tour_is_translated_in_every_catalog() { /// one without a translation shows the English. #[test] fn the_texts_for_several_chosen_sidebar_rows_are_translated_in_every_language() { - const TEXTS: [&str; 17] = [ + const TEXTS: [&str; 16] = [ "Another library was opened since this window appeared: nothing was changed", "Choose one album to rename it", "Choose one folder to rename it", - "Choose one folder to synchronize it", "Choose one keyword to create a keyword inside it", "Choose one keyword to edit it", "Choose one keyword to rename it",