From 5e2a54ba007deddd6707c13ee847ec6fa813db4c Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 08:05:16 -0400 Subject: [PATCH 01/30] 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 | 36 +++- crates/engine/src/library.rs | 5 + crates/engine/src/tests_task_queue.rs | 249 ++++++++++++++++++++++ crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/lib.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 +- 13 files changed, 752 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 af86677287e..80b52ecc731 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. 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 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 bef292f8f7d..91046008f08 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}; @@ -65,18 +65,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). pub(crate) fn run_photo(jobs: Vec) -> bool { @@ -148,28 +210,31 @@ 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(); 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()) @@ -334,10 +399,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 }; @@ -350,19 +420,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()); @@ -503,7 +571,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 ), @@ -530,7 +598,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 ), @@ -579,4 +647,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 ff2b972c0a1..bea01e28fb0 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. @@ -1444,6 +1476,8 @@ mod tests_spots; #[cfg(test)] mod tests_sync; #[cfg(test)] +mod tests_task_queue; +#[cfg(test)] mod tests_view_follow; #[cfg(test)] mod tests_xmp; 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_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/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/lib.rs b/crates/ui-egui/src/lib.rs index be1a9e879f8..763c77d863c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1971,6 +1971,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/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 4ed2b317832..b06ca52b683 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); @@ -529,3 +532,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 86deac24d7f..014a149da25 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 3b4c7ed954d..2086f5ac8c3 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 31f374da297705df0b8176e7fd0e54e42d035092 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 13:07:52 -0400 Subject: [PATCH 02/30] 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/engine/src/tests_task_queue.rs | 37 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 53 ++++++++++++++++----------- crates/ui-egui/src/state.rs | 4 -- crates/ui-egui/src/tests_activity.rs | 26 +++++++++++++ 6 files changed, 131 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 91046008f08..64abdda53de 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). @@ -104,6 +107,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 { @@ -221,7 +236,7 @@ fn build(s: &mut Session, p: &Value) -> Result { } let jobs: Vec> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect(); 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"); @@ -421,7 +436,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 bea01e28fb0..57459d00cf8 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/engine/src/tests_task_queue.rs b/crates/engine/src/tests_task_queue.rs index 1eade863445..35c2ff01689 100644 --- a/crates/engine/src/tests_task_queue.rs +++ b/crates/engine/src/tests_task_queue.rs @@ -247,3 +247,40 @@ 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); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 763c77d863c..48aee3c5887 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1024,32 +1024,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 422d907f3a3..e365c4c7755 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -784,9 +784,6 @@ pub struct UiState { pub docking: Option, #[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)] @@ -1485,7 +1482,6 @@ impl Default for UiState { window: None, docking: None, 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 b06ca52b683..0a091a06627 100644 --- a/crates/ui-egui/src/tests_activity.rs +++ b/crates/ui-egui/src/tests_activity.rs @@ -564,3 +564,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 7a5d4f0265419f4b1ad4544227a112c114b8afc2 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 17:34:34 -0400 Subject: [PATCH 03/30] 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 | 166 ++++++++-- crates/engine/src/cmd/browse.rs | 17 ++ crates/engine/src/cmd/keywords.rs | 20 +- crates/engine/src/cmd/library.rs | 222 +++++++++++--- crates/engine/src/cmd/query.rs | 7 +- crates/engine/src/lib.rs | 164 ++++++++-- crates/engine/src/library.rs | 41 ++- 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 | 5 +- docs/whats-new.md | 8 + 13 files changed, 978 insertions(+), 120 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 453b68a6972..cf3937db79a 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -489,8 +489,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, @@ -528,9 +529,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 ff94268a8ba..843558d8de6 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -39,16 +39,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, @@ -141,7 +154,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>, } @@ -286,13 +300,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 { @@ -316,7 +333,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 } @@ -332,20 +349,79 @@ impl Filter { /// [`Filter::prepare`] for testing one photo (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self) -> Prepared { - Prepared { root: self.library_root(), only: None } + Prepared { roots: self.library_roots(), only: None } } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than /// once per photo: the library folder's identity and the `only` ids as a set. pub(crate) fn prepare(&self) -> Prepared { - Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) } + Prepared { roots: self.library_roots(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()) } + } + + /// 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 } - /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. - fn library_root(&self) -> Option { + /// 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 @@ -401,9 +477,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 @@ -427,14 +501,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 @@ -447,8 +519,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; } @@ -702,6 +774,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 6f3f8896317..0e601ececde 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -481,10 +481,27 @@ 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); if let Some(f) = s.shelved_filter.as_mut() { follow_library_folder(&mut f.library_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 ebed426faec..b8613a00bc4 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -32,11 +32,23 @@ 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 - if let Some(f) = s.shelved_filter.as_mut() - && let Some(k) = f.keyword.clone() - { - f.keyword = follow(&k); + if let Some(f) = s.shelved_filter.as_mut() { + if let Some(k) = f.keyword.clone() { + f.keyword = follow(&k); + } + f.keywords = follow_all(&f.keywords); } Ok(json!({"changed": photos, "listed": listed})) } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 25a03eab802..d552ad707e8 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -376,6 +376,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 @@ -384,47 +445,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()})) } @@ -434,7 +500,7 @@ pub fn specs() -> Vec { "Filter", [], None, - "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, 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, 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(); @@ -443,7 +509,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 @@ -501,19 +581,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; } } @@ -569,6 +653,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; } @@ -1161,7 +1246,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(); @@ -1206,6 +1294,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 @@ -1223,7 +1312,8 @@ pub fn specs() -> Vec { view } else { let replace = bool_or(p, "replace", false); - let folder = cur.library_folder.clone(); + 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 @@ -1231,6 +1321,18 @@ pub fn specs() -> Vec { if replace && p.get("rules").and_then(|r| r.get("libraryFolder")).is_none() { r.library_folder = folder; } + // nor one for the album a saved view is limited to (`album: null` drops it) + 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) }; @@ -1282,8 +1384,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() } @@ -1751,7 +1855,8 @@ 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() { @@ -1770,12 +1875,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. +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. 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 { @@ -1798,8 +1924,14 @@ 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/query.rs b/crates/engine/src/cmd/query.rs index a3926bc5144..9c2383ff096 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 ff2b972c0a1..b12f01f1292 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -88,7 +88,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; @@ -301,6 +301,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). @@ -486,6 +493,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()), @@ -1065,8 +1074,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. @@ -1092,6 +1107,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 @@ -1101,7 +1120,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) @@ -1114,6 +1133,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 @@ -1148,9 +1168,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) @@ -1197,22 +1220,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; @@ -1245,16 +1252,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) @@ -1265,7 +1370,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)()); @@ -1275,15 +1383,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); @@ -1418,6 +1518,8 @@ mod tests_merge; #[cfg(test)] mod tests_move_to_share; #[cfg(test)] +mod tests_multi_source; +#[cfg(test)] mod tests_organize; #[cfg(test)] mod tests_persist; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b358..a98f8b2898e 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -181,6 +181,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, @@ -488,6 +493,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)?; @@ -544,13 +551,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; @@ -739,6 +776,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_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 ea04142561a..1392e6258a5 100644 --- a/crates/engine/src/tests_organize.rs +++ b/crates/engine/src/tests_organize.rs @@ -95,6 +95,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 dbfb0fade6f..8a4254f9ed2 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -193,20 +193,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 080680b9ffe..991a1ff2e31 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-24 · **Change:** minor (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-24 · **Change:** minor (LR-BEHAV-MULTISELECT: several albums, folders, keywords or dates shown at once, for agents; 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 @@ -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` | | +| 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_multi_source.rs` | photos in the grid; 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` | | @@ -958,3 +958,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-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 c6c25920034..4309a27b4f8 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -157,6 +157,14 @@ the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of the albums themselves. The counts are the same as before, including for albums that loop through each other. +### 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 photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around From eba8273bc03542baaff41a533c3702a921fcab79 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 10:48:58 -0400 Subject: [PATCH 04/30] Sidebars: gaps.md entry for the sidebar multi-selection still to wire (gap 30) --- docs/gaps.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index 42d9d437b6d..64c021717d7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (gap 31: sidebar multi-selection, engine part landed for agents; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -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)). @@ -94,6 +95,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-22 | patch | XMP namespace-prefix collisions no longer overwrite foreign metadata; ranked gaps and estimates unchanged | | 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-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 | #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 | | 2026-10-19 | minor | Gap 9 shrinks: `.github/workflows/ci.yml` runs `cargo xtask ci` on Linux x64 for every PR and push to main; macOS and Windows remain | From 5739ecd425f5a7fd0e5bbcdba207a266d4cb0ed2 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 13:20:37 -0400 Subject: [PATCH 05/30] Sidebars: album.setRules says [] (not null) clears the list fields --- crates/engine/src/cmd/library.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index d552ad707e8..11d5fa5295f 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1286,7 +1286,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 1eb39f780ea390e788aed2ae6327295ecc58aac6 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 15:16:22 -0400 Subject: [PATCH 06/30] Sidebars: library.filter refuses a single album beside an album source --- crates/engine/src/cmd/library.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.rs b/crates/engine/src/cmd/library.rs index 11d5fa5295f..90070cd903e 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -518,8 +518,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 fe5ed2b152c82e368ee2a06d339e188540728569 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 18:39:53 -0400 Subject: [PATCH 07/30] 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 b12f01f1292..967d94c696a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1314,7 +1314,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(); @@ -1325,15 +1326,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 2d41475ed16ebb84d5cf71aa5e7b8c90434c3482 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 20:25:13 -0400 Subject: [PATCH 08/30] 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.rs | 7 ++++++- crates/engine/src/tests_multi_source.rs | 16 ++++++++++++++++ crates/ui-egui/src/panels/chips.rs | 8 +++++++- crates/ui-egui/src/tests_panels.rs | 16 ++++++++++++++++ docs/whats-new.md | 5 +++-- 5 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 90070cd903e..7329277350e 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -468,7 +468,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()) @@ -657,6 +658,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 c18b3ad7215..21e851b9e03 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -67,7 +67,13 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt let value = if matches!(prefix, "Flag" | "Type") { tr(value).to_string() } else if prefix == "Date" { - filter.date.as_ref().map_or_else(|| value.to_string(), |date| date_group_label(date, false)) + // every date of the chip, as the engine's label lists them + let dates = filter.dates_wanted(); + if dates.is_empty() { + value.to_string() + } else { + dates.iter().map(|date| date_group_label(date, false)).collect::>().join(&format!(" {} ", tr("or"))) + } } else if prefix == "Imported" { filter.imported.as_ref().map_or_else(|| value.to_string(), |date| date_group_label(date, false)) } else { diff --git a/crates/ui-egui/src/tests_panels.rs b/crates/ui-egui/src/tests_panels.rs index 96b0a1a9d63..974d44b5bcf 100644 --- a/crates/ui-egui/src/tests_panels.rs +++ b/crates/ui-egui/src/tests_panels.rs @@ -2585,3 +2585,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 4309a27b4f8..6224706087f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -158,8 +158,9 @@ the albums themselves. The counts are the same as before, including for albums that loop through each other. ### 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 e6eff73c6e674be5e6f398546bc24adb17d41bbb Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 07:53:28 -0400 Subject: [PATCH 09/30] 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 | 12 ++++++ crates/engine/src/tests_multi_source.rs | 49 +++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index b8613a00bc4..d11063194b3 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -1,6 +1,7 @@ //! Library-wide keyword commands: list (tree with counts), suggestions, rename, delete, merge; //! keyword sets (nine keywords a keystroke away: ⌥1–⌥9) and Recent Keywords. +use lightcraft_catalog::Filter; use lightcraft_catalog::keywords::{KeywordInfo, clean, closest, is_under, reparent}; use serde_json::{Value, json}; @@ -44,11 +45,22 @@ fn commit_keywords(s: &mut Session, label: &str, op: lightcraft_catalog::Op, fol }; 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 held_keywords = f.keyword.is_some() || !f.keywords.is_empty(); if let Some(k) = f.keyword.clone() { f.keyword = follow(&k); } 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; } Ok(json!({"changed": photos, "listed": listed})) } 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 bfb014bcbe75c903cc42dc3196f521adcbb973ba Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 22:09:58 -0400 Subject: [PATCH 10/30] Sidebars: keyword, album and folder chips join their values with the language's own "or" --- crates/ui-egui/src/panels/chips.rs | 14 ++++++++++++++ crates/ui-egui/src/tests_panels.rs | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index 21e851b9e03..0a28f814adb 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -76,6 +76,8 @@ pub(crate) fn display_label(chip: &FilterChip, filter: &lightcraft_catalog::Filt } } else if prefix == "Imported" { filter.imported.as_ref().map_or_else(|| value.to_string(), |date| date_group_label(date, false)) + } else if let Some(names) = several_names(prefix, filter, catalog) { + names.join(&format!(" {} ", tr("or"))) } else { value.to_string() }; @@ -87,6 +89,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 974d44b5bcf..3f691b32eb0 100644 --- a/crates/ui-egui/src/tests_panels.rs +++ b/crates/ui-egui/src/tests_panels.rs @@ -2601,3 +2601,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 cf9a2df30f3b597e26cf792f3518f22c2307eefe Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 08:37:48 -0400 Subject: [PATCH 11/30] 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.rs | 34 ++++++++++++-------- crates/engine/src/tests_multi_source.rs | 24 +++++++++++++++ crates/ui-egui/src/menus.rs | 5 +++ crates/ui-egui/src/panels/filterbar.rs | 10 +++++- crates/ui-egui/src/panels/left.rs | 13 ++++++-- crates/ui-egui/src/shortcuts.rs | 5 +-- crates/ui-egui/src/tests_panels.rs | 41 +++++++++++++++++++++++++ docs/whats-new.md | 5 +-- 8 files changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 7329277350e..3082c9248ca 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1886,19 +1886,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. 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 84ec8ae0c1e..bc3520b1f44 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1451,6 +1451,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option { + // (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) } @@ -2285,6 +2289,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/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 8b34fbaf950..8a4e1899409 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -252,8 +252,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.rs b/crates/ui-egui/src/panels/left.rs index 5a81edfab89..566fe80becb 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -624,7 +624,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() { @@ -1654,7 +1658,12 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { ("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/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 8ea82f68dc7..a6c4c76fdf1 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -694,9 +694,10 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } continue; } - // 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.as_str(), "app.export" | "app.exportPrevious") + && matches!(f.as_str(), "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 3f691b32eb0..8d8a63f25bc 100644 --- a/crates/ui-egui/src/tests_panels.rs +++ b/crates/ui-egui/src/tests_panels.rs @@ -2624,3 +2624,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 6224706087f..a1abe36704e 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -161,8 +161,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 08d66c0037c7243eb0d88a9575599c014eb6873d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 09:30:33 -0400 Subject: [PATCH 12/30] Sidebars: a folder filter put aside by Enable Filters follows its folder when it is moved --- crates/engine/src/cmd/browse.rs | 1 + crates/engine/src/tests_folders.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 0e601ececde..feed92fd0e7 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -489,6 +489,7 @@ pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { follow_library_folder(&mut s.filter.library_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)); diff --git a/crates/engine/src/tests_folders.rs b/crates/engine/src/tests_folders.rs index 34017fc9776..55cbedb021d 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 14608fa9190d205f8108586e33f47e61e4ad88a3 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Wed, 21 Oct 2026 07:31:16 -0400 Subject: [PATCH 13/30] LR-LIB-FOLDER: a refused command says why act runs a command for the person and toasts the reason when it is refused; the interface's dropped command results became act, quiet or run, menu clicks go through menubar::act_item, and cargo xtask refusals (a step of ci) keeps them from coming back. --- CLAUDE.md | 9 +- crates/engine/src/cmd/library.rs | 2 +- crates/engine/src/tests.rs | 3 + crates/ui-egui/src/import.rs | 9 +- crates/ui-egui/src/lib.rs | 120 +++++- crates/ui-egui/src/menubar.rs | 38 +- crates/ui-egui/src/menus.rs | 12 +- crates/ui-egui/src/model_setup.rs | 3 +- crates/ui-egui/src/panels/activity.rs | 1 + crates/ui-egui/src/panels/bottombar.rs | 36 +- crates/ui-egui/src/panels/chips.rs | 6 +- crates/ui-egui/src/panels/compare.rs | 6 +- crates/ui-egui/src/panels/denoise.rs | 31 +- crates/ui-egui/src/panels/detail.rs | 88 ++-- crates/ui-egui/src/panels/edit.rs | 95 +++-- crates/ui-egui/src/panels/faces.rs | 11 +- crates/ui-egui/src/panels/filterbar.rs | 10 +- crates/ui-egui/src/panels/grid.rs | 96 +++-- crates/ui-egui/src/panels/keymap.rs | 2 +- crates/ui-egui/src/panels/keyword_list.rs | 14 +- crates/ui-egui/src/panels/keywording.rs | 4 +- crates/ui-egui/src/panels/left.rs | 58 +-- crates/ui-egui/src/panels/mask_effects.rs | 26 +- crates/ui-egui/src/panels/masking.rs | 66 +-- crates/ui-egui/src/panels/people.rs | 4 +- crates/ui-egui/src/panels/person.rs | 14 +- crates/ui-egui/src/panels/presets.rs | 21 +- crates/ui-egui/src/panels/profiles.rs | 4 +- crates/ui-egui/src/panels/right.rs | 108 ++--- crates/ui-egui/src/panels/settings.rs | 50 +-- crates/ui-egui/src/panels/slide_layout.rs | 2 +- crates/ui-egui/src/panels/slide_overlays.rs | 2 +- crates/ui-egui/src/panels/slide_titles.rs | 4 +- crates/ui-egui/src/panels/slideshow.rs | 8 +- crates/ui-egui/src/panels/strip.rs | 12 +- crates/ui-egui/src/panels/topbar.rs | 22 +- crates/ui-egui/src/panels/unnamed.rs | 8 +- crates/ui-egui/src/shortcuts.rs | 110 ++--- crates/ui-egui/src/tests_masking.rs | 4 +- crates/ui-egui/src/tests_refusals.rs | 422 ++++++++++++++++++++ docs/whats-new.md | 8 + xtask/src/ci_quick.rs | 2 +- xtask/src/main.rs | 6 +- xtask/src/refusals.rs | 410 +++++++++++++++++++ 44 files changed, 1473 insertions(+), 494 deletions(-) create mode 100644 crates/ui-egui/src/tests_refusals.rs create mode 100644 xtask/src/refusals.rs diff --git a/CLAUDE.md b/CLAUDE.md index 416ffc0a8d5..a5eee09fedc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,6 +62,13 @@ of it. Full standard: `../craftrules/standards/never-crash.md` - **Pure Rust** in the product. No C/C++ dependencies. - **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd. - **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. +- **A refused command says why.** In the interface, run a command for the person (a click, a drop, a slider, a key) + with `app.act(id, params)`: a refusal shows its reason in a toast. It returns `None` then: say a success of your own + only on `Some`, or it writes over the reason. `app.quiet(…)` is for the few calls where a refusal is expected (say + why at the call); `app.run(…)` hands the `Result` back for code that deals with it (and for agents). Never + `let _ = app.run(…)`, nor `let _ = app.session.execute(…)` round it: `cargo xtask refusals` (in `ci`) fails on + both. A dropped `session.execute` that is meant (not a person's action, or already inside `run`) says so on its line + or the one above: `// refusal expected: `. Better still, don't offer what would be refused. - **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind, label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses @@ -69,7 +76,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md` - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' - tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR + tests, layers, refusals, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 25a03eab802..9c53b06bd26 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -745,7 +745,7 @@ pub fn specs() -> Vec { has_selection, |s, p| { let c = "photo.pasteMetadata"; - let clip = s.meta_clipboard.clone().ok_or_else(|| bad(c, "nothing copied (photo.copyMetadata)"))?; + let clip = s.meta_clipboard.clone().ok_or_else(|| bad(c, "nothing copied: use Copy Metadata first"))?; let fields: Option> = p.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()); let mut params = serde_json::Map::new(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 93f4e6adcfd..54a9e6a5d5d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -856,6 +856,9 @@ fn paste_from_previous_and_copy_paste_metadata() { let ids: Vec<_> = s.visible().iter().copied().take(3).collect(); s.execute("library.select", &json!({"ids": [ids[0].0]})).unwrap(); assert!(s.execute("develop.pastePrevious", &json!({})).is_err(), "nothing before"); + // nothing copied yet: the reason is shown to a person as it is, so it names the menu item, not a command id + let e = s.execute("photo.pasteMetadata", &json!({})).unwrap_err(); + assert!(matches!(&e, crate::EngineError::BadParams { msg, .. } if msg == "nothing copied: use Copy Metadata first"), "{e}"); s.execute("develop.set", &json!({"values": {"light.exposure": 0.8}})).unwrap(); s.execute("photo.setMeta", &json!({"title": "Dawn", "keywords": ["sky", "red"], "creator": "Me"})).unwrap(); s.execute("photo.copyMetadata", &json!({})).unwrap(); diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rs index 74dcc6c4067..0ff6ebd4935 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -956,9 +956,9 @@ fn finish(app: &mut LightcraftApp, ctx: &egui::Context, task: ImportTask) { // a view the new photos aren't in (an album, Picks, a Local folder) would leave the active // photo off screen: show All Photos, as Lightroom shows the import's own collection (#1446) if !app.session.visible().contains(&lightcraft_catalog::PhotoId(f)) { - let _ = app.run("library.source", json!({"kind": "all"})); + app.act("library.source", json!({"kind": "all"})); } - let _ = app.run("library.select", json!({"ids": [f]})); + app.act("library.select", json!({"ids": [f]})); } let plural = |n: usize| if n == 1 { "" } else { "s" }; // nothing new, only files the library already has: show where they are (Recently Deleted is @@ -1027,7 +1027,10 @@ fn show_existing(app: &mut LightcraftApp, ctx: &egui::Context, existing: &[u64]) if ids.is_empty() || app.run("library.source", json!({"kind": kind})).is_err() { return false; } - let _ = app.run("library.select", json!({"ids": ids})); + // refused: `act` said why, and a toast of ours would write over it + if app.act("library.select", json!({"ids": ids})).is_none() { + return true; + } app.ui.left_panel = true; let n = ids.len(); let plural = if n == 1 { "" } else { "s" }; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index be1a9e879f8..809ed9cc346 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -183,6 +183,8 @@ mod tests_rating; #[cfg(test)] mod tests_recheck; #[cfg(test)] +mod tests_refusals; +#[cfg(test)] mod tests_rename_person; #[cfg(test)] mod tests_rules_editor; @@ -229,6 +231,69 @@ pub use control::{ControlRequest, ControlResponse}; pub use state::UiState; 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). +struct Refusal { + error: String, + why: String, + /// What kind of error it is, for code that decides on it ([`LightcraftApp::run_typed`]). + kind: lightcraft_engine::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: lightcraft_engine::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"; @@ -844,22 +909,53 @@ 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. `cargo xtask refusals` keeps the dropped form, `let _ = app.run(…)` (and + /// `let _ = app.session.execute(…)`, which goes round this), out of the interface: a widget + /// says which of `act`, [`Self::quiet`] and [`Self::run`] it means. + pub fn act(&mut self, id: &str, params: Value) -> Option { + match self.run_told(id, params) { + Ok(v) => Some(v), + Err(refusal) => { + let now = self.tick_now(); + self.ui.toast = Some((refusal.why, now + REFUSAL_SECONDS, None)); + None + } + } + } + + /// Run a command whose refusal is expected here and means nothing to the person (it is + /// tried on the off chance, or again on every frame of a gesture): nothing is shown. Say why + /// at the call. `None` when it was refused. + pub fn quiet(&mut self, id: &str, params: Value) -> Option { + self.run_told(id, params).ok() + } + + /// [`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(result) = model_setup::intercept(self, id, ¶ms) { - return result.map_err(CommandError::from); + return result.map_err(Refusal::plain); } 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") @@ -870,7 +966,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")) @@ -928,11 +1024,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); } } @@ -2176,7 +2272,7 @@ impl LightcraftApp { if panels::library_problem::holds_drops(self) { self.toast(ctx, crate::i18n::tr("Open a library first, then drop the presets again")); } else { - let _ = self.run("file.importPresets", serde_json::json!({"paths": drop.presets})); + self.act("file.importPresets", serde_json::json!({"paths": drop.presets})); } } if drop.photos.is_empty() { @@ -2229,6 +2325,7 @@ impl LightcraftApp { fn apply_settings(&mut self, ctx: &egui::Context) { if self.gpu_applied != Some(self.ui.settings.gpu) { self.gpu_applied = Some(self.ui.settings.gpu); + // refusal expected: a saved setting applied at start-up and when it changes, nobody's command; app.gpu takes either value let _ = self.session.execute("app.gpu", &serde_json::json!({"enabled": self.ui.settings.gpu})); // GPU device + kernels off the UI thread, once the window is up and only when GPU // rendering is on: a broken driver must not keep the window from appearing (issue #136) @@ -2240,6 +2337,7 @@ impl LightcraftApp { // automatic at startup: leave the engine's default alone if self.memory_applied != Some(mb) && (mb > 0 || self.memory_applied.is_some()) { let mb = if mb == 0 { (lightcraft_engine::memory::default_budget() >> 20) as u32 } else { mb }; + // refusal expected: a saved setting applied at start-up; out of range (a hand-edited file) the engine keeps its budget let _ = self.session.execute("app.memoryBudget", &serde_json::json!({"mb": mb})); } self.memory_applied = Some(mb); diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rs index ba4a8a7c290..352f77eb29b 100644 --- a/crates/ui-egui/src/menubar.rs +++ b/crates/ui-egui/src/menubar.rs @@ -915,6 +915,24 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec)> { /// Run a menu item. Rating, flag and label items behave like their keys (the active photo only in /// Compare/Survey; Auto Advance moves on). pub fn run_item(app: &mut LightcraftApp, id: &str, params: Value) -> Result { + clicked_item(app, id, params, LightcraftApp::run, Result::is_ok).unwrap_or(Ok(Value::Null)) +} + +/// [`run_item`] for a click on the item: a refusal is said in a toast ([`LightcraftApp::act`]). +/// `None` when it was refused. +pub fn act_item(app: &mut LightcraftApp, id: &str, params: Value) -> Option { + clicked_item(app, id, params, LightcraftApp::act, Option::is_some).unwrap_or(Some(Value::Null)) +} + +/// A menu item run by `run`, which `went` says went through; `None` when the item only opened +/// its confirmation. +fn clicked_item( + app: &mut LightcraftApp, + id: &str, + params: Value, + run: impl FnOnce(&mut LightcraftApp, &str, Value) -> R, + went: impl FnOnce(&R) -> bool, +) -> Option { let mut params = if params.is_null() { json!({}) } else { params }; let culling_cmd = matches!( id, @@ -932,14 +950,14 @@ pub fn run_item(app: &mut LightcraftApp, id: &str, params: Value) -> Result N let policy = native_command_policy(app, id); match policy { NativeCommand::Run => { - let _ = run_item(app, id, params); + act_item(app, id, params); } NativeCommand::Blocked => log::debug!("native menu: {id} is blocked while another window owns input"), NativeCommand::Quit => {} @@ -1086,14 +1104,8 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32 }); } if let Some((id, params)) = clicked { - let r = run_item(app, &id, params); - // an export that can't start (e.g. no folder), or a backup / restore the host refuses - // (changes still unsaved, nothing stored in this browser), says why instead of doing nothing - if let Err(e) = r - && matches!(id.as_str(), "app.export" | "app.exportPrevious" | "file.backupLibrary" | "file.restoreLibrary") - { - app.toast(ui.ctx(), e); - } + // an item that can't run (an export with no folder…) says why instead of doing nothing + act_item(app, &id, params); } ui.cursor().left() - start } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 84ec8ae0c1e..3bdc31156b2 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -309,7 +309,7 @@ fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str /// `[` / `]` (size ×`k`) and ⇧`[` / ⇧`]` (feather +`df`) for the brush in use: the Remove tool's /// (and its selected spot's) or the Masking brush's. -fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { +fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Result { if app.ui.right == RightPanel::Remove { app.ui.remove_size = (app.ui.remove_size * k).clamp(0.001, 0.25); app.ui.remove_feather = (app.ui.remove_feather + df).clamp(0.0, 100.0); @@ -321,13 +321,14 @@ fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { if df != 0.0 { p["feather"] = json!(app.ui.remove_feather); } - let _ = app.run("spot.update", p); + // refused (the spot is gone): the caller says why, once + app.run("spot.update", p)?; } - json!({"size": app.ui.remove_size, "feather": app.ui.remove_feather}) + Ok(json!({"size": app.ui.remove_size, "feather": app.ui.remove_feather})) } else { app.ui.brush_size = (app.ui.brush_size * k).clamp(0.002, 0.5); app.ui.brush_feather = (app.ui.brush_feather + df).clamp(0.0, 100.0); - json!({"size": app.ui.brush_size, "feather": app.ui.brush_feather}) + Ok(json!({"size": app.ui.brush_size, "feather": app.ui.brush_feather})) } } @@ -626,6 +627,7 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option Option (1.0, -10.0), _ => (1.0, 10.0), }; - Ok(adjust_brush(app, k, df)) + adjust_brush(app, k, df) } "view.maskPins" => { app.ui.mask_pins = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.mask_pins); diff --git a/crates/ui-egui/src/model_setup.rs b/crates/ui-egui/src/model_setup.rs index 78587697eb3..94dbcfe6809 100644 --- a/crates/ui-egui/src/model_setup.rs +++ b/crates/ui-egui/src/model_setup.rs @@ -75,6 +75,7 @@ pub(crate) fn intercept(app: &mut LightcraftApp, command: &str, params: &Value) app.model_setup.denoise = None; return Some(app.session.execute("denoise.toggle", &json!({"id": id.0, "enabled": false})).map_err(|e| e.to_string())); } + // refusal expected: only refreshes the model state read on the next line; this is inside `run`, which answers for denoise.toggle let _ = app.session.execute("denoise.status", &json!({"id": id.0})); if !matches!(app.session.denoise_photo_state(id), PhotoState::NoModel) { return None; @@ -101,7 +102,7 @@ pub(crate) fn notice(app: &mut LightcraftApp, ui: &mut egui::Ui, kind: &str) { let r = ui.small_button(tr("Cancel pending action")); crate::widgets::register(ui, "modelSetup:cancel:denoise", r.rect); if r.clicked() { - let _ = app.run("modelSetup.cancel", json!({"kind": "denoise"})); + app.act("modelSetup.cancel", json!({"kind": "denoise"})); } ui.add_space(6.0); } diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index dffdd1c4d33..b168abd4d86 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -112,6 +112,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { /// ✕ on task `id`'s row. The task may have just finished or stopped being cancellable: nothing to tell the user then, /// so the command goes to the engine directly (`LightcraftApp::run` would put its error in the status bar). pub(crate) fn cancel(app: &mut LightcraftApp, id: u64) { + // refusal expected: the task finished or stopped being cancellable between the frame that drew ✕ and the click let _ = app.session.execute("activity.cancel", &json!({"id": id})); } diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 0b48d1e34a0..5780b1cd19b 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -36,7 +36,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if left_rect.width() >= 270.0 { for &(id, icon, mode, tip) in VIEW_MODES { if icon_button(ui, id, icon, vec2(32.0, 32.0), app.ui.view == mode, true, tip).clicked() { - let _ = app.run(&format!("view.{id}"), json!({})); + app.act(&format!("view.{id}"), json!({})); } } ui.add_space(10.0); @@ -57,7 +57,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { egui::Popup::menu(&more).show(|ui| { for &(id, _, mode, label) in VIEW_MODES { if ui.selectable_label(app.ui.view == mode, crate::i18n::tr(label)).clicked() { - let _ = app.run(&format!("view.{id}"), json!({})); + app.act(&format!("view.{id}"), json!({})); ui.close(); } } @@ -108,7 +108,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: if let Some(r) = crate::rating::Rating::new("bottom", rating).show(&mut pill_ui) { let mut params = json!({"rating": r}); crate::panels::compare::target_active(app, &mut params); - let _ = app.run("photo.rate", params); + app.act("photo.rate", params); } pill_ui.add_space(6.0); let flag = active.as_ref().map(|p| p.flag).unwrap_or_default(); @@ -138,7 +138,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: if resp.clicked() { let mut params = json!({"flag": match f { Flag::Pick => "pick", Flag::Reject => "reject", Flag::None => "none" }}); crate::panels::compare::target_active(app, &mut params); - let _ = app.run("photo.flag", params); + app.act("photo.flag", params); } } // copy / paste settings @@ -151,8 +151,8 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: register(ui, "button:copySettings", copy_r); ui.painter().rect_filled(copy_r, 15.0, if cresp.hovered() { t.hover } else { t.canvas }); ui.painter().text(copy_r.center(), Align2::CENTER_CENTER, label, t.font(13.0), if active.is_some() { t.text_label } else { t.text_disabled }); - if cresp.clicked() && active.is_some() { - let _ = if has_clip { app.run("develop.paste", json!({})) } else { app.run("develop.copy", json!({})) }; + // the success only when it went through: refused, `act` said why + if cresp.clicked() && active.is_some() && app.act(if has_clip { "develop.paste" } else { "develop.copy" }, json!({})).is_some() { let msg = if has_clip { "Settings pasted" } else { "Edit settings copied" }; app.toast(ui.ctx(), crate::i18n::tr(msg)); } @@ -163,7 +163,7 @@ fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: ui.painter().rect_filled(gear_r, 15.0, if gresp.hovered() { t.hover } else { t.canvas }); paint(ui.painter(), gear_r.shrink(7.0), Icon::Gear, t.icon); if gresp.clicked() { - let _ = app.run("dialog.copySettings", json!({})); + app.act("dialog.copySettings", json!({})); } } @@ -188,7 +188,7 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo ) .clicked() { - let _ = app.run("view.autoAdvance", json!({})); + app.act("view.autoAdvance", json!({})); } if app.ui.view == ViewMode::Survey { // no zoom or thumbnail size in Survey @@ -196,15 +196,15 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo if icon_button(&mut child, "beforeAfter", Icon::BeforeAfter, vec2(30.0, 30.0), app.ui.before_after.is_layout(), true, "Before/After (Y)") .clicked() { - let _ = app.run("view.beforeAfter", json!({})); + app.act("view.beforeAfter", json!({})); } if app.ui.view == ViewMode::Detail && icon_button(&mut child, "faceBoxes", Icon::FaceBox, vec2(30.0, 30.0), app.ui.face_boxes, true, "Face boxes").clicked() { - let _ = app.run("view.faceBoxes", json!({})); + app.act("view.faceBoxes", json!({})); } if icon_button(&mut child, "filmstrip", Icon::Filmstrip, vec2(30.0, 30.0), app.ui.filmstrip, true, "Filmstrip (/)").clicked() { - let _ = app.run("view.filmstrip", json!({})); + app.act("view.filmstrip", json!({})); } child.add_space(10.0); let zoom_label = match app.ui.zoom { @@ -263,7 +263,7 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo fn click_zoom_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { for pct in crate::state::CLICK_ZOOMS { if ui.selectable_label(app.ui.click_zoom == pct, format!("{}:1", pct / 100)).clicked() { - let _ = app.run("view.clickZoom", json!({"ratio": pct / 100})); + app.act("view.clickZoom", json!({"ratio": pct / 100})); } } } @@ -283,28 +283,28 @@ fn sort_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { ("Random", Random, "random"), ] { if ui.selectable_label(cur.key == key, crate::i18n::tr(label)).clicked() { - let _ = app.run("library.sort", json!({"key": k})); + app.act("library.sort", json!({"key": k})); } } if cur.key == Random && ui.button(crate::i18n::tr("Reshuffle")).clicked() { - let _ = app.run("library.shuffle", json!({})); + app.act("library.shuffle", json!({})); } // a view that holds its photos shows what matches now when asked to if app.session.hold_view { let r = ui.button(crate::i18n::tr("Refresh View")); crate::widgets::register(ui, "button:refreshView", r.rect); if r.clicked() { - let _ = app.run("library.refresh", json!({})); + app.act("library.refresh", json!({})); } } ui.separator(); // a shuffle has no direction worth choosing ui.add_enabled_ui(cur.key != Random, |ui| { if ui.selectable_label(cur.key != Random && cur.ascending, crate::i18n::tr("Ascending")).clicked() { - let _ = app.run("library.sort", json!({"ascending": true})); + app.act("library.sort", json!({"ascending": true})); } if ui.selectable_label(cur.key != Random && !cur.ascending, crate::i18n::tr("Descending")).clicked() { - let _ = app.run("library.sort", json!({"ascending": false})); + app.act("library.sort", json!({"ascending": false})); } }); ui.separator(); @@ -317,7 +317,7 @@ fn sort_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { ("None", GroupBy::None, "none"), ] { if ui.selectable_label(cur.group == g, crate::i18n::tr(label)).clicked() { - let _ = app.run("library.sort", json!({"group": k})); + app.act("library.sort", json!({"group": k})); } } } diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index c18b3ad7215..f483562822c 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -116,7 +116,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { ui.painter().line_segment([a, b], Stroke::new(1.3, col)); ui.painter().line_segment([pos2(a.x, b.y), pos2(b.x, a.y)], Stroke::new(1.3, col)); if resp.clicked() { - let _ = app.run("library.filter", c.clear.clone()); + app.act("library.filter", c.clear.clone()); if c.clear.get("text").is_some() { app.ui.search.clear(); } @@ -140,7 +140,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { .on_hover_text(crate::i18n::tr("Remove this filter")) .clicked() { - let _ = app.run("library.filter", c.clear.clone()); + app.act("library.filter", c.clear.clone()); if c.clear.get("text").is_some() { app.ui.search.clear(); } @@ -150,7 +150,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { } if crate::widgets::text_button(&mut child, "chipsClearAll", crate::i18n::tr("Clear all"), false).clicked() { app.ui.search.clear(); - let _ = app.run("library.clearFilter", json!({})); + app.act("library.clearFilter", json!({})); } } diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 829500da47b..37507c3e9c4 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -57,6 +57,7 @@ pub fn enter_compare(app: &mut LightcraftApp) -> Result { fn select_pair(app: &mut LightcraftApp, a: PhotoId, b: PhotoId, active: PhotoId) { app.ui.compare = Some((a.0, b.0)); + // refusal expected: a step of view.compare and its arrow keys, which answer for themselves; the pair is from the view let _ = app.session.execute("library.select", &json!({"ids": [a.0, b.0], "active": active.0})); } @@ -167,6 +168,7 @@ pub fn survey_step(app: &mut LightcraftApp, d: isize) -> Result { /// else the next photo in the view. `was` is the active photo before the rating: a rating that took /// it out of the view made the photo after it active already, and that is the next one (#2312). pub fn advance(app: &mut LightcraftApp, was: Option) { + // refusal expected: moving on by itself after a rating that went through and was said; a step that can't be taken is no news let _ = match app.ui.view { ViewMode::Compare => compare_step(app, 1), ViewMode::Survey => survey_step(app, 1), @@ -568,7 +570,7 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.session.selection.active = Some(*id); } if resp.double_clicked() { - let _ = app.run("library.select", json!({"ids": [id.0]})); + app.act("library.select", json!({"ids": [id.0]})); app.ui.view = ViewMode::Detail; } // remove from the survey (deselect) on hover @@ -579,7 +581,7 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.painter().circle_filled(xr.center(), 10.0, Color32::from_black_alpha(if xresp.hovered() { 230 } else { 160 })); paint(ui.painter(), xr.shrink(4.0), Icon::Close, t.text); if xresp.clicked() { - let _ = app.run("library.select", json!({"ids": [id.0], "mode": "toggle"})); + app.act("library.select", json!({"ids": [id.0], "mode": "toggle"})); } } crate::widgets::context_menu(&resp, |ui| super::grid::context_menu(app, ui, *id)); diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index fdb208b511f..c85f57fe883 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -132,6 +132,7 @@ fn watch_downloads(app: &mut LightcraftApp, ctx: &egui::Context) { } app.caches.denoise.dl_watch = keep; for id in installed { + // refusal expected: the watcher clearing a finished download's row, nobody's click; a row already gone is as good let _ = app.session.execute("denoise.models.downloadCancel", &json!({"id": id})); app.caches.denoise.epoch += 1; let text = tr("The denoise model is installed and in use: the AI Denoise Amount slider under Detail now works"); @@ -148,7 +149,7 @@ pub fn detail_toggle(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, on let r = ui.add_enabled(applicable, egui::Checkbox::new(&mut enabled, crate::i18n::tr("AI Denoise"))); register(ui, "denoise:enabled", r.rect); if r.changed() { - let _ = app.run("denoise.toggle", json!({"id": id.0, "enabled": enabled})); + app.act("denoise.toggle", json!({"id": id.0, "enabled": enabled})); } }); } @@ -187,7 +188,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am let r = ui.small_button(crate::i18n::tr("Set up AI Denoise…")); register(ui, "denoise:setup", r.rect); if r.clicked() { - let _ = app.run("denoise.toggle", json!({"id": id.0, "enabled": true})); + app.act("denoise.toggle", json!({"id": id.0, "enabled": true})); } }); } @@ -210,7 +211,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am let r = ui.small_button(crate::i18n::tr("Make it now")); register(ui, "denoise:make", r.rect); if r.clicked() { - let _ = app.run("denoise.queue", json!({"ids": [id.0]})); + app.act("denoise.queue", json!({"ids": [id.0]})); } }); } @@ -238,7 +239,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am let r = ui.small_button(crate::i18n::tr("Try again")); register(ui, "denoise:retry", r.rect); if r.clicked() { - let _ = app.run("denoise.queue", json!({"ids": [id.0], "retry": true})); + app.act("denoise.queue", json!({"ids": [id.0], "retry": true})); } } }); @@ -324,7 +325,7 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V let mut run_on = current.as_str(); let options = [("auto", "Automatic"), ("gpu", "Graphics card"), ("cpu", "Processor")]; if ui.horizontal(|ui| choices(ui, "denoiseRunOn", &options, &mut run_on)).inner { - let _ = app.run("denoise.settings", json!({"runOn": run_on})); + app.act("denoise.settings", json!({"runOn": run_on})); app.caches.denoise.epoch += 1; } hint( @@ -338,14 +339,14 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V register(ui, "denoise:retryGpu", r.rect); if r.clicked() { // choosing where it runs, even the same again, forgets the failed set-up - let _ = app.run("denoise.settings", json!({"runOn": run_on})); + app.act("denoise.settings", json!({"runOn": run_on})); app.caches.denoise.epoch += 1; } } heading(ui, t, "Photos"); let mut auto = list["auto"].as_bool().unwrap_or(true); if check(ui, "settings.denoiseAuto", &mut auto, "Make the denoised picture of the photos I am looking at") { - let _ = app.run("denoise.settings", json!({"auto": auto})); + app.act("denoise.settings", json!({"auto": auto})); app.caches.denoise.epoch += 1; } hint(ui, t, "Only photos whose AI Denoise amount is above 0 are made. Exports always make theirs if it is missing."); @@ -375,13 +376,13 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V let r = ui.button(tr("Denoise all photos with an Amount")); register(ui, "denoise:queueAll", r.rect); if r.clicked() { - let _ = app.run("denoise.queue", json!({"scope": "withAmount"})); + app.act("denoise.queue", json!({"scope": "withAmount"})); } if running.is_some() || queued > 0 { let r = ui.button(tr("Stop")); register(ui, "denoise:stop", r.rect); if r.clicked() { - let _ = app.run("denoise.cancel", json!({})); + app.act("denoise.cancel", json!({})); } } }); @@ -407,13 +408,13 @@ fn work_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, list: &V }); crate::widgets::name_combo(&combo.response, tr("Cache limit")); if choice != current { - let _ = app.run("denoise.settings", json!({"cacheGb": choice})); + app.act("denoise.settings", json!({"cacheGb": choice})); app.caches.denoise.epoch += 1; } let r = ui.button(tr("Clear cache")); register(ui, "denoise:clear", r.rect); if r.clicked() { - let _ = app.run("denoise.clear", json!({})); + app.act("denoise.clear", json!({})); } }); } @@ -497,21 +498,21 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui.button(tr("Remove")); register(ui, format!("denoise:remove:{id}"), r.rect); if r.clicked() { - let _ = app.run("denoise.models.remove", json!({"id": id})); + app.act("denoise.models.remove", json!({"id": id})); app.caches.denoise.epoch += 1; } if selected { let r = ui.button(tr("Turn off")); register(ui, format!("denoise:off:{id}"), r.rect); if r.clicked() { - let _ = app.run("denoise.models.select", json!({"id": null})); + app.act("denoise.models.select", json!({"id": null})); app.caches.denoise.epoch += 1; } } else { let r = ui.button(tr("Use")); register(ui, format!("denoise:use:{id}"), r.rect); if r.clicked() { - let _ = app.run("denoise.models.select", json!({"id": id})); + app.act("denoise.models.select", json!({"id": id})); app.caches.denoise.epoch += 1; } } @@ -521,7 +522,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui.button(tr("Cancel")); register(ui, format!("denoise:cancelDownload:{id}"), r.rect); if r.clicked() { - let _ = app.run("denoise.models.downloadCancel", json!({"id": id})); + app.act("denoise.models.downloadCancel", json!({"id": id})); app.caches.denoise.dl_watch.retain(|w| w != &id); } } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 5e610b098d2..67a8aa42532 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -191,7 +191,7 @@ fn bounded_pan(area: Rect, size: egui::Vec2, pan: (f32, f32)) -> (f32, f32) { pub(crate) fn pan_image(app: &mut LightcraftApp, area: Rect, img: Rect, delta: egui::Vec2) { let centre = area.center() - img.min - delta; let pan = bounded_pan(area, img.size(), (centre.x / img.width().max(1.0), centre.y / img.height().max(1.0))); - let _ = app.run("view.navigate", json!({"pan": pan})); + app.act("view.navigate", json!({"pan": pan})); } /// A drag with the middle button (the mouse wheel pressed) pans the zoomed photo whatever tool is @@ -267,7 +267,7 @@ pub(crate) fn navigate_gesture(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: let point = (anchor - img.min) / img.size(); let offset = area.center() - anchor - delta; let pan = bounded_pan(area, size, (point.x + offset.x / size.x.max(1.0), point.y + offset.y / size.y.max(1.0))); - let _ = app.run("view.navigate", json!({"zoom": zoom, "pan": pan})); + app.act("view.navigate", json!({"zoom": zoom, "pan": pan})); ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); ui.ctx().request_repaint(); true @@ -920,14 +920,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { super::faces::take_step(app, ui.ctx(), setup); } Some(RegionEdit::Remove(index)) => { - let _ = app.run("photo.removeRegion", json!({"id": id.0, "index": index})); + app.act("photo.removeRegion", json!({"id": id.0, "index": index})); } Some(RegionEdit::Name(index, name)) => { app.ui.name_edit = None; - let _ = app.run("faces.setName", json!({"id": id.0, "index": index, "name": name})); + app.act("faces.setName", json!({"id": id.0, "index": index, "name": name})); } Some(RegionEdit::Resize(index, r)) => { - let _ = app.run("photo.setRegion", json!({"id": id.0, "index": index, "rect": {"x0": r.x0, "y0": r.y0, "x1": r.x1, "y1": r.y1}})); + app.act("photo.setRegion", json!({"id": id.0, "index": index, "rect": {"x0": r.x0, "y0": r.y0, "x1": r.x1, "y1": r.y1}})); } None => {} } @@ -1017,7 +1017,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { crate::widgets::menu_button(ui, crate::i18n::tr("Zoom"), |ui| { for (label, cmd) in [("Fit", "view.zoomFit"), ("100%", "view.zoom100"), ("Zoom In", "view.zoomIn"), ("Zoom Out", "view.zoomOut")] { if ui.button(crate::i18n::tr(label)).clicked() { - let _ = app.run(cmd, json!({})); + app.act(cmd, json!({})); } } }); @@ -1353,7 +1353,7 @@ fn filter_pill(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect) { p.line_segment([c - vec2(m, m), c + vec2(m, m)], cross); p.line_segment([c - vec2(m, -m), c + vec2(m, -m)], cross); if resp.on_hover_text(crate::i18n::tr("Click to clear these filters")).clicked() { - let _ = app.run("library.clearFilter", json!({})); + app.act("library.clearFilter", json!({})); } } @@ -1543,7 +1543,7 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap if resp.drag_started() && let Some(q) = resp.interact_pointer_pos() { - let _ = app.run("develop.beginInteraction", json!({"label": "Targeted Adjustment"})); + app.act("develop.beginInteraction", json!({"label": "Targeted Adjustment"})); app.gesture = Some(Gesture::Targeted { at: map.norm(q), acc: 0.0 }); } if resp.dragged() @@ -1558,12 +1558,12 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap if target == "curve" && app.ui.curve_channel != "parametric" { p["channel"] = json!(app.ui.curve_channel); } - let _ = app.run("develop.targeted", p); + app.act("develop.targeted", p); } } if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::Targeted { .. })) { app.gesture = None; - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } } @@ -1656,7 +1656,7 @@ fn general_interaction( && let Some(q) = resp.interact_pointer_pos() { let n = map.norm(q); - let _ = app.run("develop.wbPick", json!({"x": n.x, "y": n.y})); + app.act("develop.wbPick", json!({"x": n.x, "y": n.y})); app.ui.tool.clear(); } return; @@ -1807,7 +1807,7 @@ fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons && inside(q) && !handles.iter().any(|h| h.distance(q) < 12.0) { - let _ = app.run("tool.done", json!({})); + app.act("tool.done", json!({})); return; } // egui reports a drag only once the pointer has moved a few px: the zone is where the button @@ -1842,7 +1842,7 @@ fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons let orig = ui.input(|i| i.pointer.press_origin()).map(|q0| to_straight(map.norm(q0), angle, frame)).unwrap_or(n); // Shift keeps the current proportions for this drag only; the Lock toggle is untouched. let keep_ratio = ui.input(|i| i.modifiers.shift); - let _ = app.run( + app.act( "crop.drag", json!({"handle": handle, "from": [orig.x, orig.y], "to": [n.x, n.y], "start": [start.x0, start.y0, start.x1, start.y1], "keepRatio": keep_ratio}), ); @@ -1852,14 +1852,14 @@ fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons let a = (q - c).angle(); let ang = (start_angle + (a - a0).to_degrees() as f64).clamp(-45.0, 45.0); shown_angle = (ang * 100.0).round() / 100.0; - let _ = app.run("crop.straighten", json!({"angle": shown_angle})); + app.act("crop.straighten", json!({"angle": shown_angle})); } _ => {} } } if resp.drag_stopped() { app.gesture = None; - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } if let Some(at) = readout_at { // the canvas (the loupe's own rect), not the photo: rotating happens in the margin around it @@ -1901,7 +1901,7 @@ fn crop_keys( let Some(at) = handles.get(i).copied().or_else(|| (i == 8).then_some(centre)) else { continue }; let keys = crate::canvas_keys::handle(ui, &format!("crop:{i}"), crate::i18n::tr(name), value.clone(), at); if keys.activated { - let _ = app.run("tool.done", json!({})); + app.act("tool.done", json!({})); return true; } let Some((dx, dy)) = keys.delta else { continue }; @@ -1916,11 +1916,11 @@ fn crop_keys( let _ = app.session.cancel_interaction(); return false; } - let _ = app.run( + app.act( "crop.drag", json!({"handle": i, "from": [from.x, from.y], "to": [to.x, to.y], "start": [r.x0, r.y0, r.x1, r.y1], "keepRatio": false}), ); - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } false } @@ -2125,7 +2125,7 @@ fn guided_overlay( [x.x, x.y, y.x, y.y] }) .collect(); - let _ = app.run("geometry.guides", json!({"guides": all})); + app.act("geometry.guides", json!({"guides": all})); } } } @@ -2135,7 +2135,7 @@ fn guided_overlay( { let b = map.norm(q); let (ca, cb) = (frame.transformed_to_corrected(a), frame.transformed_to_corrected(b)); - let _ = app.run("geometry.guides", json!({"guides": [[ca.x, ca.y, cb.x, cb.y]], "add": true})); + app.act("geometry.guides", json!({"guides": [[ca.x, ca.y, cb.x, cb.y]], "add": true})); } } other => app.gesture = other, @@ -2530,7 +2530,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons let erase = app.ui.brush_erase != alt; // a ⇧-click draws a straight line from where the last stroke ended, as in Lightroom let connect = shift && resp.clicked() && pts.len() == 1; - let _ = app.run( + app.act( "mask.brushStroke", json!({"points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather, "flow": app.ui.brush_flow, "erase": erase, "autoMask": app.ui.brush_auto_mask, "pressure": pressure, "connect": connect}), @@ -2553,7 +2553,7 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons && let Some((mid, ..)) = hit(q) && Some(mid) != active { - let _ = app.run("mask.select", json!({"id": mid})); + app.act("mask.select", json!({"id": mid})); } if resp.drag_started() && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) @@ -2573,9 +2573,9 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons && let Some(original_shape) = d.masks.iter().find(|m| m.id == mask).and_then(|m| m.components.get(comp)).map(|c| c.shape.clone()) { if Some(mask) != active { - let _ = app.run("mask.select", json!({"id": mask})); + app.act("mask.select", json!({"id": mask})); } - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); + app.act("develop.beginInteraction", json!({"label": "Edit Mask"})); app.gesture = Some(Gesture::MaskHandle { mask, comp, handle, original_shape }); } } @@ -2588,11 +2588,11 @@ fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respons let dn = Point::new(n.x - n0.x, n.y - n0.y); let alt = ui.input(|i| i.modifiers.alt); let new_shape = moved_shape(&original_shape, handle, dn, n, map, alt); - let _ = app.run("mask.update", json!({"id": mask, "component": comp, "shape": new_shape})); + app.act("mask.update", json!({"id": mask, "component": comp, "shape": new_shape})); } if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::MaskHandle { .. })) { app.gesture = None; - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } } @@ -2624,17 +2624,17 @@ fn mask_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De let name = mask_handle_name(&mask_name, shape, handle); let keys = crate::canvas_keys::handle(ui, &format!("mask:{mid}:{ci}:{handle}"), &name, crate::canvas_keys::position_text(at.x, at.y), q); if keys.activated && app.session.active_mask != Some(mid) { - let _ = app.run("mask.select", json!({"id": mid})); + app.act("mask.select", json!({"id": mid})); } let Some((dx, dy)) = keys.delta else { continue }; if app.session.active_mask != Some(mid) { - let _ = app.run("mask.select", json!({"id": mid})); + app.act("mask.select", json!({"id": mid})); } let to = Point::new(at.x + dx, at.y + dy); let new_shape = moved_shape(shape, handle, Point::new(dx, dy), to, map, false); - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Mask"})); - let _ = app.run("mask.update", json!({"id": mid, "component": ci, "shape": new_shape})); - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.beginInteraction", json!({"label": "Edit Mask"})); + app.act("mask.update", json!({"id": mid, "component": ci, "shape": new_shape})); + app.act("develop.endInteraction", json!({})); } } @@ -2737,9 +2737,9 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo && let Some((spot, source, ..)) = press.and_then(hit) { if Some(spot) != active { - let _ = app.run("spot.select", json!({"index": spot})); + app.act("spot.select", json!({"index": spot})); } - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); + app.act("develop.beginInteraction", json!({"label": "Edit Spot"})); app.gesture = Some(Gesture::SpotMove { spot, source }); } if let Some(Gesture::SpotMove { spot, source }) = app.gesture.clone() { @@ -2749,19 +2749,19 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo let (n, n0) = (map.norm(q), map.norm(q - resp.drag_delta())); let dn = [n.x - n0.x, n.y - n0.y]; if dn != [0.0, 0.0] { - let _ = app.run("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: dn})); + app.act("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: dn})); } } if resp.drag_stopped() { app.gesture = None; - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } return; } if resp.clicked() && let Some((spot, ..)) = press.and_then(hit) { - let _ = app.run("spot.select", json!({"index": spot})); + app.act("spot.select", json!({"index": spot})); return; } if let Some(q) = resp.interact_pointer_pos() @@ -2788,7 +2788,7 @@ fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Respo _ => "remove", }; let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect(); - let _ = app.run( + app.act( "spot.add", json!({"mode": mode, "points": pts, "size": app.ui.remove_size, "feather": app.ui.remove_feather, "opacity": app.ui.remove_opacity}), ); @@ -2807,12 +2807,12 @@ fn spot_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De let value = format!("{}, {} {:.0}%", crate::canvas_keys::position_text(at.x, at.y), crate::i18n::tr("size"), size * 100.0); let keys = crate::canvas_keys::handle(ui, &format!("spot:{spot}:{}", if source { "source" } else { "target" }), &name, value, q); if (keys.activated || keys.delta.is_some()) && app.session.active_spot != Some(spot) { - let _ = app.run("spot.select", json!({"index": spot})); + app.act("spot.select", json!({"index": spot})); } if let Some((dx, dy)) = keys.delta { - let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); - let _ = app.run("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: [dx, dy]})); - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.beginInteraction", json!({"label": "Edit Spot"})); + app.act("spot.update", json!({"index": spot, if source { "moveSource" } else { "move" }: [dx, dy]})); + app.act("develop.endInteraction", json!({})); } } // where a new spot goes: the photo's centre at first, then wherever the arrows took it @@ -2841,7 +2841,7 @@ fn spot_keys(app: &mut LightcraftApp, ui: &mut egui::Ui, map: &CanvasMap, d: &De "fill" => "fill", _ => "remove", }; - let _ = app.run( + app.act( "spot.add", json!({"mode": mode, "points": [[place.0, place.1]], "size": app.ui.remove_size, "feather": app.ui.remove_feather, "opacity": app.ui.remove_opacity}), ); @@ -3025,7 +3025,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { crate::icons::paint(p, Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)), crate::icons::Icon::Stack, Color32::WHITE); p.galley(pos2(br.min.x + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE); if badge.clicked() { - super::grid::toggle_stack(app, ui.ctx(), *id); + super::grid::toggle_stack(app, *id); } } } @@ -3213,7 +3213,7 @@ fn straighten_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::R while deg < -45.0 { deg += 90.0; } - let _ = app.run("crop.straighten", json!({"angle": (-deg * 100.0).round() / 100.0})); + app.act("crop.straighten", json!({"angle": (-deg * 100.0).round() / 100.0})); } if !held { app.ui.tool.clear(); diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 10542e4432a..65e211c1ac4 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -18,21 +18,16 @@ use crate::theme::Tokens; use crate::widgets::{BAND_COLORS, SliderOut, divider, flyout_row, hex, register, section_header, slider, text_button}; /// Commit a slider interaction: begin → live updates → end, so a drag is one undo step. -pub fn apply_slider_out( - app: &mut LightcraftApp, - spec: &ControlSpec, - out: SliderOut, - mut set: impl FnMut(&mut LightcraftApp, f64) -> Result, -) { +pub fn apply_slider_out(app: &mut LightcraftApp, spec: &ControlSpec, out: SliderOut, mut set: impl FnMut(&mut LightcraftApp, f64) -> Option) { if out.drag_started && !out.reset { - let _ = app.run("develop.beginInteraction", json!({"label": spec.label})); + app.act("develop.beginInteraction", json!({"label": spec.label})); app.ui.dragging_control = Some(spec.id.to_string()); } if let Some(v) = out.value { - let _ = set(app, v); + set(app, v); } if out.drag_stopped || out.reset { - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); app.ui.dragging_control = None; } } @@ -41,7 +36,7 @@ pub(crate) fn control(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSet let Some(spec) = controls::find(id) else { return }; let v = controls::get(d, id).unwrap_or(spec.default); let out = slider(ui, spec, v, enabled, None); - apply_slider_out(app, spec, out, |app, v| app.run("develop.set", json!({"control": id, "value": v}))); + apply_slider_out(app, spec, out, |app, v| app.act("develop.set", json!({"control": id, "value": v}))); } /// Relative temperature scale for rendered (non-raw) files: −100..100 ↔ Kelvin via mired shift. @@ -110,20 +105,20 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 8, bottom: 14 }).show(ui, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 8.0; - if text_button(ui, "auto", crate::i18n::tr("Auto"), false).clicked() { - let _ = app.run("develop.auto", json!({})); + if text_button(ui, "auto", crate::i18n::tr("Auto"), false).clicked() && app.act("develop.auto", json!({})).is_some() { + // only when it went through: refused (the original is missing…), `act` said why app.toast(ui.ctx(), crate::i18n::tr("Auto settings applied")); } let bw = crate::is_bw(&d); if text_button(ui, "bw", crate::i18n::tr("B&W"), bw).clicked() { - let _ = app.run("develop.treatment", json!({})); + app.act("develop.treatment", json!({})); } // HDR editing, next to B&W as Lightroom has it if text_button(ui, "hdr", crate::i18n::tr("HDR"), d.hdr.enabled) .on_hover_text(crate::i18n::tr("Edit in HDR: highlights above SDR white, for HDR exports and displays")) .clicked() { - let _ = app.run("develop.hdr", json!({"enabled": !d.hdr.enabled})); + app.act("develop.hdr", json!({"enabled": !d.hdr.enabled})); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, "reset", crate::i18n::tr("Reset"), false) @@ -154,7 +149,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.label(egui::RichText::new(crate::i18n::tr_format!("Auto Sync: edits apply to {n} photos", n = n)).color(t.accent).size(12.0)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, "autoSyncOff", crate::i18n::tr("Turn Off"), false).clicked() { - let _ = app.run("develop.autoSync", json!({"on": false})); + app.act("develop.autoSync", json!({"on": false})); } }); }); @@ -184,7 +179,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ) .clicked() { - let _ = app.run("panel.profiles", json!({})); + app.act("panel.profiles", json!({})); } }); }); @@ -201,7 +196,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let r = ui.checkbox(&mut on, crate::i18n::tr("Camera local tone mapping")); crate::widgets::register(ui, "check:profile.cameraLocalTone", r.rect); if r.on_hover_text(crate::i18n::tr("Apply the local tone mapping stored in the raw (Apple ProRAW), as the camera renders it")).changed() { - let _ = app.run("develop.merge", json!({"settings": {"profile": {"camera_local_tone": on}}, "label": "Camera Local Tone Mapping"})); + app.act("develop.merge", json!({"settings": {"profile": {"camera_local_tone": on}}, "label": "Camera Local Tone Mapping"})); } }); } @@ -247,7 +242,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } if ui.selectable_label(d.wb.mode == m, m.label()).clicked() { let mode = serde_json::to_value(m).unwrap_or_default(); - let _ = app.run("develop.wb", json!({"mode": mode})); + app.act("develop.wb", json!({"mode": mode})); } } }); @@ -279,9 +274,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { control(app, ui, d, "wb.tint", true); } else { let out = slider(ui, &REL_TEMP, k_to_rel(d.wb.temp), true, None); - apply_slider_out(app, &REL_TEMP, out, |app, v| app.run("develop.set", json!({"control": "wb.temp", "value": rel_to_k(v)}))); + apply_slider_out(app, &REL_TEMP, out, |app, v| app.act("develop.set", json!({"control": "wb.temp", "value": rel_to_k(v)}))); let out = slider(ui, &REL_TINT, d.wb.tint.clamp(-100.0, 100.0), true, None); - apply_slider_out(app, &REL_TINT, out, |app, v| app.run("develop.set", json!({"control": "wb.tint", "value": v}))); + apply_slider_out(app, &REL_TINT, out, |app, v| app.act("develop.set", json!({"control": "wb.tint", "value": v}))); } control(app, ui, d, "color.vibrance", true); control(app, ui, d, "color.saturation", true); @@ -330,7 +325,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { chosen = crate::widgets::segmented(ui, "vignetteStyle", &items, active, 3); }); if let Some(i) = chosen { - let _ = app.run( + app.act( "develop.merge", serde_json::json!({"settings": {"vignette": {"style": serde_json::to_value(styles[i].0).unwrap_or_default()}}}), ); @@ -370,11 +365,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 4 }).show(ui, |ui| { let mut ca = d.optics.remove_ca; if ui.checkbox(&mut ca, crate::i18n::tr("Remove Chromatic Aberration")).changed() { - let _ = app.run("develop.merge", json!({"settings": {"optics": {"remove_ca": ca}}, "label": "Remove CA"})); + app.act("develop.merge", json!({"settings": {"optics": {"remove_ca": ca}}, "label": "Remove CA"})); } let mut lp = d.optics.lens_profile; if ui.checkbox(&mut lp, crate::i18n::tr("Enable Lens Corrections")).changed() { - let _ = app.run("develop.merge", json!({"settings": {"optics": {"lens_profile": lp}}, "label": "Lens Corrections"})); + app.act("develop.merge", json!({"settings": {"optics": {"lens_profile": lp}}, "label": "Lens Corrections"})); } if lp && !has_lens { ui.label( @@ -426,7 +421,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.add_space(40.0); // A pending numeric edit commits on blur before the explicit Reset takes precedence. if reset_clicked { - let _ = app.run("develop.reset", json!({})); + app.act("develop.reset", json!({})); } } @@ -513,13 +508,13 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett let r = ui.button(label); register(ui, "profileMenu:toggleFavorite", r.rect); if r.clicked() { - let _ = app.run("profile.favorite", json!({"id": cur})); + app.act("profile.favorite", json!({"id": cur})); } } let r = ui.button(crate::i18n::tr("Browse…")); register(ui, "profileMenu:browse", r.rect); if r.clicked() { - let _ = app.run("panel.profiles", json!({})); + app.act("panel.profiles", json!({})); } // resting on a profile previews it in the loupe if let Some(hovered_id) = &pick.1 @@ -533,7 +528,7 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett Some(crate::HoverPreview { label: crate::i18n::tr_format!("Profile: {}", crate::i18n::profile_label(hovered_id, name)), settings: s }); } if let Some(id) = pick.0 { - let _ = app.run("develop.profile", json!({"id": id})); + app.act("develop.profile", json!({"id": id})); } } @@ -554,7 +549,7 @@ fn section( let open = app.ui.section_open(id); let (resp, toggled) = section_header(ui, id, title, open, Some(d.section_enabled(id))); if let Some(on) = toggled { - let _ = app.run("develop.sectionEnabled", json!({"section": id, "enabled": on})); + app.act("develop.sectionEnabled", json!({"section": id, "enabled": on})); } else if resp.clicked() { // ⌥-click opens just this section, as in Lightroom Classic let solo = ui.input(|i| i.modifiers.alt); @@ -780,7 +775,7 @@ fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { )); } if clicked { - let _ = app.run("view.clipping", json!({})); + app.act("view.clipping", json!({})); } // the tonal zone the pointer is on replaces the EXIF strip while it is there if let Some(text) = zone.as_ref().and_then(|a| a.readout()) { @@ -828,7 +823,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { .on_hover_text(crate::i18n::tr("Show display gamut warning")); register(ui, "button:proofDisplayWarning", r2.rect); if dest != app.ui.proof.dest_warning || disp != app.ui.proof.display_warning { - let _ = app.run("view.softProof", json!({"destWarning": dest, "displayWarning": disp})); + app.act("view.softProof", json!({"destWarning": dest, "displayWarning": disp})); } }); }); @@ -841,7 +836,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let combo = crate::widgets::combo_box("proof-space").width(170.0).selected_text(shown).show_ui(ui, |ui| { for s in OutputSpace::ALL { if ui.selectable_label(device.is_none() && cur == s, s.label()).clicked() { - let _ = app.run("view.softProof", json!({"space": s})); + app.act("view.softProof", json!({"space": s})); } } if let Some(n) = &device { @@ -867,7 +862,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let r = ui.selectable_label(app.ui.proof_intent == i, crate::i18n::tr(label)); register(ui, format!("button:proofIntent-{}", i.name()), r.rect); if r.clicked() && app.ui.proof_intent != i { - let _ = app.run("view.softProof", json!({"intent": i.name()})); + app.act("view.softProof", json!({"intent": i.name()})); } } }); @@ -875,7 +870,7 @@ fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let r = ui.checkbox(&mut paper, crate::i18n::tr("Simulate Paper & Ink")); register(ui, "button:proofPaperInk", r.rect); if r.changed() { - let _ = app.run("view.softProof", json!({"paperInk": paper})); + app.act("view.softProof", json!({"paperInk": paper})); } } let r = ui.button(crate::i18n::tr("Create Proof Copy")); @@ -1085,7 +1080,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev let resp = resp.on_hover_text(crate::i18n::tr_format!("{name} — double-click to reset it", name = name)); if resp.double_clicked() { app.ui.curve_channel = ch.into(); - let _ = app.run("curve.reset", json!({"channel": ch})); + app.act("curve.reset", json!({"channel": ch})); } else if resp.clicked() { app.ui.curve_channel = ch.into(); } @@ -1209,7 +1204,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev && let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) { // pick the point under the press, not where the pointer is once the drag threshold passed - let _ = app.run("develop.beginInteraction", json!({"label": "Tone Curve"})); + app.act("develop.beginInteraction", json!({"label": "Tone Curve"})); match nearest(q) { Some((i, dist)) if dist < 10.0 => dragging = Some(i), _ => { @@ -1264,7 +1259,7 @@ fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Dev } if let Some(v) = new_pts { let arr: Vec<[f64; 2]> = v.iter().map(|p| [p.x, p.y]).collect(); - let _ = app.run("develop.curve", json!({"channel": ch, "points": arr})); + app.act("develop.curve", json!({"channel": ch, "points": arr})); } // the drag is over when egui says so, or when the pointer comes up without it saying so (a // release outside the window would otherwise leave the interaction open, and every later edit a @@ -1301,13 +1296,13 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) let r = ui.selectable_label(current.as_deref() == Some(p.name.as_str()), crate::i18n::builtin_label(&p.name, p.builtin)); register(ui, format!("curvePreset:{}", p.name), r.rect); if r.clicked() { - let _ = app.run("curve.applyPreset", json!({"name": p.name})); + app.act("curve.applyPreset", json!({"name": p.name})); ui.close(); } if !p.builtin { crate::widgets::context_menu(&r, |ui| { if ui.button(crate::i18n::tr("Delete Preset")).clicked() { - let _ = app.run("curve.deletePreset", json!({"name": p.name})); + app.act("curve.deletePreset", json!({"name": p.name})); ui.close(); } }); @@ -1322,12 +1317,12 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) ui.close(); } if ui.add_enabled(app.services.pick_curve_preset_files.is_some(), egui::Button::new(crate::i18n::tr("Import Presets…"))).clicked() { - let _ = app.run("file.importCurvePresets", json!({})); + app.act("file.importCurvePresets", json!({})); ui.close(); } let can_export = app.services.save_curve_preset_file.is_some() && !app.session.curve_presets.is_empty(); if ui.add_enabled(can_export, egui::Button::new(crate::i18n::tr("Export Presets…"))).clicked() { - let _ = app.run("file.exportCurvePresets", json!({})); + app.act("file.exportCurvePresets", json!({})); ui.close(); } if presets.iter().any(|p| !p.builtin) { @@ -1339,7 +1334,7 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)", )); if r.clicked() { - let _ = app.run("curve.reset", json!({"channel": "all"})); + app.act("curve.reset", json!({"channel": "all"})); } }); }); @@ -1356,13 +1351,13 @@ fn curve_reset_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, ch: &str) { let r = ui.button(label); register(ui, "curveMenu:resetChannel", r.rect); if r.clicked() { - let _ = app.run("curve.reset", json!({"channel": ch})); + app.act("curve.reset", json!({"channel": ch})); ui.close(); } let r = ui.button(crate::i18n::tr("Reset All Curves")); register(ui, "curveMenu:resetAll", r.rect); if r.clicked() { - let _ = app.run("curve.reset", json!({"channel": "all"})); + app.act("curve.reset", json!({"channel": "all"})); ui.close(); } } @@ -1449,7 +1444,7 @@ fn mixer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { .on_hover_text(crate::i18n::tr("Set the mix from the photo's colours")) .clicked() { - let _ = app.run("develop.autoBwMix", json!({})); + app.act("develop.autoBwMix", json!({})); } }); control(app, ui, d, &format!("bw.{b}"), true); @@ -1533,7 +1528,7 @@ fn point_color(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, "pointColorDelete", crate::i18n::tr("Delete"), false).clicked() { - let _ = app.run("pointColor.delete", json!({"index": sel})); + app.act("pointColor.delete", json!({"index": sel})); } }); }); @@ -1698,16 +1693,16 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings ui.painter().circle_stroke(dot, 5.0, Stroke::new(1.0, Color32::BLACK)); ui.painter().text(pos2(c.x, c.y + rad + 12.0), Align2::CENTER_CENTER, crate::i18n::tr(label), t.font(12.0), t.text_label); if resp.drag_started() { - let _ = app.run("develop.beginInteraction", json!({"label": crate::i18n::tr_format!("{label} Grading", label = label)})); + app.act("develop.beginInteraction", json!({"label": crate::i18n::tr_format!("{label} Grading", label = label)})); } if (resp.dragged() || resp.clicked()) && let Some(q) = pointer { let (hue, sat) = grab.map_or_else(|| wheel_pick(q - c, rad, None), |g| g.pick(q - c, rad)); - let _ = app.run("develop.set", json!({"values": {format!("grading.{key}.hue"): hue.round(), format!("grading.{key}.sat"): sat.round()}})); + app.act("develop.set", json!({"values": {format!("grading.{key}.hue"): hue.round(), format!("grading.{key}.sat"): sat.round()}})); } if resp.drag_stopped() || resp.clicked() { - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } // released, or Esc (egui ends a drag on it) if resp.drag_stopped() @@ -1717,7 +1712,7 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings give_pointer_back(ui.ctx(), held.origin); } if resp.double_clicked() { - let _ = app.run("develop.set", json!({"values": {format!("grading.{key}.hue"): 0, format!("grading.{key}.sat"): 0}})); + app.act("develop.set", json!({"values": {format!("grading.{key}.hue"): 0, format!("grading.{key}.sat"): 0}})); } // hue and saturation readout: centred above the wheel, shown like the eye (no fade) if readout && (hovering || resp.dragged()) { @@ -2016,7 +2011,7 @@ fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) { if r.on_hover_text(crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label))) .clicked() { - let _ = app.run("develop.quickAdjust", json!({"control": ctl, "delta": d})); + app.act("develop.quickAdjust", json!({"control": ctl, "delta": d})); } } ui.end_row(); diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index 76cd1295cb5..d6add5f05a7 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -141,7 +141,7 @@ pub fn take_step(app: &mut LightcraftApp, ctx: &egui::Context, step: Setup) { } } Setup::GetModel => { - let _ = app.run("app.settings", json!({"tab": "faces"})); + app.act("app.settings", json!({"tab": "faces"})); } Setup::Running | Setup::Unavailable => {} } @@ -293,7 +293,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Add a model file…"))); register(ui, "faces:addModel", r.rect); if r.clicked() { - let _ = app.run("dialog.faceModel", json!({})); + app.act("dialog.faceModel", json!({})); } ui.label(RichText::new(crate::i18n::tr("or drop a .onnx file on the window")).color(t.text_dim)); }); @@ -390,14 +390,14 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui.button(crate::i18n::tr("Remove")); register(ui, format!("faces:remove:{id}"), r.rect); if r.clicked() { - let _ = app.run("faces.models.remove", json!({"id": id})); + app.act("faces.models.remove", json!({"id": id})); app.caches.faces_epoch += 1; } if !selected && !detector { let r = ui.button("Use"); register(ui, format!("faces:use:{id}"), r.rect); if r.clicked() { - let _ = app.run("faces.models.select", json!({"id": id})); + app.act("faces.models.select", json!({"id": id})); app.caches.faces_epoch += 1; } } @@ -407,7 +407,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, let r = ui.button(crate::i18n::tr("Cancel")); register(ui, format!("faces:cancelDownload:{id}"), r.rect); if r.clicked() { - let _ = app.run("faces.models.downloadCancel", json!({"id": id})); + app.act("faces.models.downloadCancel", json!({"id": id})); app.caches.faces_dl_watch.retain(|w| w != &id); } } @@ -801,6 +801,7 @@ fn watch_downloads(app: &mut LightcraftApp, ctx: &egui::Context) { l["models"].as_array().and_then(|a| a.iter().find(|m| m["id"] == id.as_str()).and_then(|m| m["name"].as_str().map(str::to_string))) }) .unwrap_or_else(|| id.clone()); + // refusal expected: the watcher clearing a finished download's row, nobody's click; a row already gone is as good let _ = app.session.execute("faces.models.downloadCancel", &json!({"id": id})); app.caches.faces_epoch += 1; let detector = app diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 8b34fbaf950..fcc9f9b258c 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -19,7 +19,7 @@ const WIDE: f32 = 1240.0; pub use crate::theme::label_color; fn filter(app: &mut LightcraftApp, patch: Value) { - let _ = app.run("library.filter", patch); + app.act("library.filter", patch); } /// A small label before a group of controls. @@ -255,13 +255,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5)))); register(ui, "button:filterSave", save.rect); if save.clicked() { - let _ = app.run("dialog.newSmartAlbum", json!({})); + app.act("dialog.newSmartAlbum", json!({})); } let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.font(12.5)))); register(ui, "button:filterClear", clear.rect); if clear.clicked() { app.ui.search.clear(); - let _ = app.run("library.clearFilter", json!({})); + app.act("library.clearFilter", json!({})); } // filter presets: apply one, save the current filter, delete let presets = crate::widgets::dropdown(ui, "filterPresets", crate::i18n::tr("Presets"), t.font(12.5), t.text); @@ -271,11 +271,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { for n in &names { let r = ui.button(n); if r.clicked() { - let _ = app.run("filter.applyPreset", json!({"name": n})); + app.act("filter.applyPreset", json!({"name": n})); } crate::widgets::context_menu(&r, |ui| { if ui.button(crate::i18n::tr("Delete Preset")).clicked() { - let _ = app.run("filter.deletePreset", json!({"name": n})); + app.act("filter.deletePreset", json!({"name": n})); } }); } diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index ba2e4886980..45a731fe8c9 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -682,7 +682,7 @@ fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids: let group: Vec = ids[run.start..(run.start + run.count).min(ids.len())].iter().map(|p| p.0).collect(); let m = ui.input(|i| i.modifiers); let mode = if m.command || m.shift { "add" } else { "replace" }; - let _ = app.run("library.select", json!({"ids": group, "mode": mode})); + app.act("library.select", json!({"ids": group, "mode": mode})); } } @@ -916,7 +916,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square if resp.clicked() { let has = photo.meta.keywords.iter().any(|x| x.eq_ignore_ascii_case(&k)); let key = if has { "removeKeywords" } else { "addKeywords" }; - let _ = app.run("photo.setMeta", json!({"ids": [id.0], key: [k]})); + app.act("photo.setMeta", json!({"ids": [id.0], key: [k]})); } return; } @@ -929,16 +929,16 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square } else { "replace" }; - let _ = app.run("library.select", json!({"ids": [id.0], "mode": mode})); + app.act("library.select", json!({"ids": [id.0], "mode": mode})); } if resp.double_clicked() { - let _ = app.run("library.select", json!({"ids": [id.0]})); - let _ = app.run("view.detail", json!({})); + app.act("library.select", json!({"ids": [id.0]})); + app.act("view.detail", json!({})); } // drag the selection (this photo joins it, or replaces it when it wasn't selected) if resp.drag_started() { if !app.session.selection.contains(id) { - let _ = app.run("library.select", json!({"ids": [id.0]})); + app.act("library.select", json!({"ids": [id.0]})); } app.ui.dragging_photos = Some(app.session.selection.ids.iter().map(|p| p.0).collect()); } @@ -972,7 +972,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi let c = ui.checkbox(&mut sub, crate::i18n::tr("Include subfolders")); register(ui, "check:includeSubfolders", c.rect); if c.changed() { - let _ = app.run("library.browse", json!({"path": b.path, "subfolders": sub})); + app.act("library.browse", json!({"path": b.path, "subfolders": sub})); } // Counted once per view (cached); the ids are only gathered on a click. if local_n > 0 { @@ -1050,7 +1050,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { if r.clicked() && let Some((_, to)) = crumbs.get(i) { - let _ = app.run("library.browse", json!({"path": to})); + app.act("library.browse", json!({"path": to})); } separator(ui); } @@ -1127,7 +1127,7 @@ pub fn label_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { if let Some(l) = label_items(app, ui, current, "photoLabel") { let mut params = json!({"label": label_param(l)}); crate::panels::compare::target_active(app, &mut params); - let _ = app.run("photo.label", params); + app.act("photo.label", params); ui.close(); } } @@ -1156,7 +1156,7 @@ pub fn label_items(app: &mut LightcraftApp, ui: &mut egui::Ui, current: Option= 2, egui::Button::new(crate::i18n::tr(label))).clicked() { - let _ = app.run(id, json!({})); + app.act(id, json!({})); } } }); ui.separator(); if ui.button(crate::i18n::tr("Rotate Left")).clicked() { - let _ = app.run("photo.rotateLeft", json!({})); + app.act("photo.rotateLeft", json!({})); } if ui.button(crate::i18n::tr("Rotate Right")).clicked() { - let _ = app.run("photo.rotateRight", json!({})); + app.act("photo.rotateRight", json!({})); } ui.separator(); // the original moved or its drive is gone: point the photo at the file again // (a cached answer, checked off the UI thread) let missing = matches!(&app.session.catalog.photo(id).map(|p| p.source.clone()), Some(lightcraft_catalog::Source::File { path }) if app.session.media.availability.is_offline(path)); if missing && ui.button(crate::i18n::tr("Locate Missing File…")).clicked() { - let _ = app.run("photo.locate", json!({})); + app.act("photo.locate", json!({})); } if ui.add_enabled(crate::menus::ui_enabled(app, "app.showInFinder"), egui::Button::new(crate::i18n::tr(crate::menus::reveal_label()))).clicked() { - let _ = app.run("app.showInFinder", json!({})); + app.act("app.showInFinder", json!({})); } // the photo's folder in the sidebar's Folders section, as Lightroom's Go to Folder in Library // (the photo right-clicked, which a multi-selection may leave other than the active one) if ui.add_enabled(crate::menus::show_in_folders_enabled(app, Some(id)), egui::Button::new(crate::i18n::tr("Show in Folders"))).clicked() { - let _ = app.run("app.showInFolders", json!({"id": id.0})); + app.act("app.showInFolders", json!({"id": id.0})); } if ui.button(crate::i18n::tr("Export…")).clicked() { - let _ = app.run("dialog.export", json!({})); + app.act("dialog.export", json!({})); } crate::widgets::menu_button(ui, crate::i18n::tr("Export with Preset"), |ui| { for (p, _) in app.session.all_export_presets() { @@ -1431,16 +1425,16 @@ pub fn context_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.separator(); if crate::menubar::selection_deleted(app) { if ui.button(crate::i18n::tr("Restore")).clicked() { - let _ = app.run("photo.restore", json!({})); + app.act("photo.restore", json!({})); } if ui.button(crate::i18n::tr("Delete Permanently")).clicked() { - let _ = app.run("photo.deletePermanently", json!({})); + app.act("photo.deletePermanently", json!({})); } } else { let delete = ui.button(crate::i18n::tr("Delete Photo")); register(ui, "button:contextDeletePhoto", delete.rect); if delete.clicked() { - let _ = crate::menubar::run_item(app, "photo.delete", json!({})); + crate::menubar::act_item(app, "photo.delete", json!({})); } } } diff --git a/crates/ui-egui/src/panels/keymap.rs b/crates/ui-egui/src/panels/keymap.rs index 3ebe2505705..7c999564426 100644 --- a/crates/ui-egui/src/panels/keymap.rs +++ b/crates/ui-egui/src/panels/keymap.rs @@ -34,7 +34,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.add_enabled(!app.ui.settings.keymap.is_empty(), egui::Button::new(crate::i18n::tr("Reset All"))); register(ui, "button:shortcutsResetAll", r.rect); if r.clicked() { - let _ = app.run("app.resetShortcuts", serde_json::json!({})); + app.act("app.resetShortcuts", serde_json::json!({})); app.recording_shortcut = None; } }); diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index ba31c6676d3..1874f2f8afc 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -252,7 +252,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId }; if tb.clicked() { let key = if state == Tick::All { "removeKeywords" } else { "addKeywords" }; - let _ = app.run("photo.setMeta", json!({key: [r.path]})); + app.act("photo.setMeta", json!({key: [r.path]})); } // the count, then the arrow left of it (shown on hover) let count = ui.painter().layout_no_wrap(r.count.to_string(), t.font(12.0), t.text_dim); @@ -268,7 +268,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})); + app.act("library.filter", json!({"keyword": r.path})); } // the name, cut short before the arrow let room = (arrow.left() - 4.0 - (x + 34.0)).max(0.0); @@ -371,23 +371,23 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[Pho let is_default = app.session.catalog.default_keyword_parent().as_deref().is_some_and(|k| same(k, path)); let label = format!("{}{}", if is_default { "✓ " } else { "" }, crate::i18n::tr("Put New Keywords Inside This Keyword")); if item(ui, "defaultParent", &label, true) { - let _ = app.run("keyword.setDefaultParent", json!({"keyword": if is_default { serde_json::Value::Null } else { json!(path) }})); + app.act("keyword.setDefaultParent", json!({"keyword": if is_default { serde_json::Value::Null } else { json!(path) }})); } ui.separator(); let some = !selection.is_empty(); if item(ui, "add", crate::i18n::tr("Add to Selected Photos"), some) { - let _ = app.run("photo.setMeta", json!({"addKeywords": [path]})); + app.act("photo.setMeta", json!({"addKeywords": [path]})); } if item(ui, "remove", crate::i18n::tr("Remove from Selected Photos"), some) { - let _ = app.run("photo.setMeta", json!({"removeKeywords": [path]})); + app.act("photo.setMeta", json!({"removeKeywords": [path]})); } 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})); + app.act("library.filter", json!({"keyword": path})); } ui.separator(); if item(ui, "purge", crate::i18n::tr("Purge Unused Keywords"), true) { - let _ = app.run("keyword.purgeUnused", json!({})); + app.act("keyword.purgeUnused", json!({})); } if item(ui, "delete", crate::i18n::tr("Delete Keyword…"), true) { app.ui.dialog = Some(delete_dialog(app, path)); diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 4861d4c6fa7..6b5b6f86d29 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -152,14 +152,14 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, chip: &Chip) { r.clicked() }; if !chip.on_all() && item(ui, "add", crate::i18n::tr("Add to All Selected Photos")) { - let _ = app.run("photo.setMeta", json!({"addKeywords": [chip.path]})); + app.act("photo.setMeta", json!({"addKeywords": [chip.path]})); } if item(ui, "remove", crate::i18n::tr("Remove from Selected Photos")) { remove(app, ui.ctx(), 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})); + app.act("library.filter", json!({"keyword": chip.path})); } ui.separator(); if item(ui, "edit", crate::i18n::tr("Edit Keyword Tag…")) { diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 5a81edfab89..d176ca6863c 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -634,7 +634,7 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { if app.session.catalog.album_children_are_ordered(None) { ui.separator(); if ui.button(crate::i18n::tr("Sort Albums A–Z")).on_hover_text(crate::i18n::tr("Go back to listing them by name")).clicked() { - let _ = app.run("album.sort", json!({})); + app.act("album.sort", json!({})); } } } @@ -692,7 +692,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ("picks", Icon::FlagPick, "Picks", Some(picks), LibrarySource::Picks), ] { if row(app, ui, id, icon, label, count, src == s, 0.0).clicked() { - let _ = app.run("library.source", json!({"kind": id})); + app.act("library.source", json!({"kind": id})); } } // photos whose files can't be found (checked every few seconds, not every frame) @@ -700,10 +700,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if (missing > 0 || src == LibrarySource::Missing) && row(app, ui, "missing", Icon::Folder, "Missing Photos", Some(missing), src == LibrarySource::Missing, 0.0).clicked() { - let _ = app.run("library.source", json!({"kind": "missing"})); + app.act("library.source", json!({"kind": "missing"})); } if row(app, ui, "recentlyDeleted", Icon::Trash, "Recently Deleted", Some(deleted), src == LibrarySource::RecentlyDeleted, 0.0).clicked() { - let _ = app.run("library.source", json!({"kind": "recentlyDeleted"})); + app.act("library.source", json!({"kind": "recentlyDeleted"})); } // the album just made: the folders down to it open, once (also when the section is shut) let reveal = app.ui.reveal_album.take(); @@ -916,7 +916,7 @@ fn local_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, now: &LocalNow) { // the picked folder stays in Local (and comes back if it was hidden) Ok(r) => { let dir = r["path"].as_str().unwrap_or(&path).to_string(); - let _ = app.run("local.addRoot", json!({"path": dir})); + app.act("local.addRoot", json!({"path": dir})); } Err(e) => app.toast(ui.ctx(), e), } @@ -931,7 +931,7 @@ fn local_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, now: &LocalNow) { .on_hover_text(crate::i18n::tr("Put the locations you removed from Local back (no files change)")); if let [(_, only)] = now.hidden.as_slice() { if resp.clicked() { - let _ = app.run("local.restoreHidden", json!({"path": only})); + app.act("local.restoreHidden", json!({"path": only})); } } else { egui::Popup::menu(&resp).show(|ui| hidden_menu(app, ui, &now.hidden)); @@ -946,7 +946,7 @@ fn hidden_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, hidden: &[(String, St let r = ui.button(name).on_hover_text(path); register(ui, format!("local:restoreHidden:{path}"), r.rect); if r.clicked() { - let _ = app.run("local.restoreHidden", json!({"path": path})); + app.act("local.restoreHidden", json!({"path": path})); ui.close(); } } @@ -954,7 +954,7 @@ fn hidden_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, hidden: &[(String, St let r = ui.button(crate::i18n::tr("Restore All")); register(ui, "local:restoreHidden:all", r.rect); if r.clicked() { - let _ = app.run("local.restoreHidden", json!({})); + app.act("local.restoreHidden", json!({})); ui.close(); } } @@ -1172,7 +1172,7 @@ fn folder_tree( .on_hover_text(crate::i18n::tr("List this folder in Local from now on")) .clicked() { - let _ = app.run("local.addRoot", json!({"path": path})); + app.act("local.addRoot", json!({"path": path})); ui.close(); } if indent == 0.0 @@ -1181,7 +1181,7 @@ fn folder_tree( .on_hover_text(crate::i18n::tr("Hides this shortcut only; the folder and its photos stay as they are")) .clicked() { - let _ = app.run("local.hide", json!({"path": path})); + app.act("local.hide", json!({"path": path})); ui.close(); } if ui.button(crate::i18n::tr("Rename Folder…")).clicked() { @@ -1232,7 +1232,7 @@ fn date_row(app: &mut LightcraftApp, ui: &mut egui::Ui, key: &str, label: &str, 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})); + app.act("library.filter", json!({"date": v})); } open } @@ -1242,7 +1242,7 @@ fn date_row(app: &mut LightcraftApp, ui: &mut egui::Ui, key: &str, label: &str, /// missing (issue #341). Only when choosing (`on`), not when clearing the row again. pub(crate) fn browse_all_photos(app: &mut LightcraftApp, on: bool) { if on && app.session.source != LibrarySource::All { - let _ = app.run("library.source", json!({"kind": "all"})); + app.act("library.source", json!({"kind": "all"})); } } @@ -1329,7 +1329,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})); + app.act("library.source", json!({"kind": "album", "id": a.id.0})); } folder_menu(app, &resp, a); } @@ -1655,7 +1655,7 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { ("Create Folder…", "dialog.newFolder"), ] { if ui.button(crate::i18n::tr(label)).clicked() { - let _ = app.run(command, json!({"parent": a.id.0})); + app.act(command, json!({"parent": a.id.0})); ui.close(); } } @@ -1663,7 +1663,7 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { if app.session.catalog.album_children_are_ordered(Some(a.id)) && ui.button(crate::i18n::tr("Sort Contents A–Z")).on_hover_text(crate::i18n::tr("Go back to listing them by name")).clicked() { - let _ = app.run("album.sort", json!({"parent": a.id.0})); + app.act("album.sort", json!({"parent": a.id.0})); ui.close(); } ui.separator(); @@ -1715,19 +1715,19 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { if !a.folder && !a.is_smart() { let is_target = app.session.target_album == Some(a.id) || (app.session.target_album.is_none() && a.quick); if !is_target && ui.button(crate::i18n::tr("Set as Target Album (B adds to it)")).clicked() { - let _ = app.run("album.setTarget", json!({"id": if a.quick { serde_json::Value::Null } else { json!(a.id.0) }})); + app.act("album.setTarget", json!({"id": if a.quick { serde_json::Value::Null } else { json!(a.id.0) }})); } if is_target && !a.quick && ui.button(crate::i18n::tr("Stop Using as Target Album")).clicked() { - let _ = app.run("album.setTarget", json!({"id": null})); + app.act("album.setTarget", json!({"id": null})); } } if a.quick && ui.button(crate::i18n::tr("Clear Quick Collection")).clicked() { - let _ = app.run("album.clearQuick", json!({})); + app.act("album.clearQuick", json!({})); } if a.is_smart() && ui.button(crate::i18n::tr("Edit Smart Album…")).clicked() { // the same editor as `dialog.smartAlbum` (older smart albums keep their filter fields; // it works on the rule set, upgraded) - let _ = app.run("dialog.smartAlbum", json!({"id": a.id.0})); + app.act("dialog.smartAlbum", json!({"id": a.id.0})); } if a.is_smart() && ui.button(crate::i18n::tr("Update Rules from Current Filter")).clicked() { // refused when the view would make the album test itself: say why @@ -1738,13 +1738,13 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { if !a.folder { // export: show the album, select its photos, then the dialog / a preset let show_all = |app: &mut LightcraftApp| { - let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0})); - let _ = app.run("library.selectAll", json!({})); + app.act("library.source", json!({"kind": "album", "id": a.id.0})); + app.act("library.selectAll", json!({})); }; let has_photos = app.session.catalog.album_count(a.id) > 0; if ui.add_enabled(has_photos, egui::Button::new(crate::i18n::tr("Export Album…"))).clicked() { show_all(app); - let _ = app.run("dialog.export", json!({})); + app.act("dialog.export", json!({})); } ui.add_enabled_ui(has_photos, |ui| { crate::widgets::menu_button(ui, crate::i18n::tr("Export Album with Preset"), |ui| { @@ -1766,11 +1766,11 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { folders.sort_by_key(|(_, n)| n.to_lowercase()); crate::widgets::menu_button(ui, crate::i18n::tr("Move to"), |ui| { if ui.add_enabled(a.parent.is_some(), egui::Button::new(crate::i18n::tr("Top Level"))).clicked() { - let _ = app.run("album.move", json!({"id": a.id.0, "parent": null})); + app.act("album.move", json!({"id": a.id.0, "parent": null})); } for (fid, name) in &folders { if ui.add_enabled(a.parent.map(|p| p.0) != Some(*fid), egui::Button::new(name)).clicked() { - let _ = app.run("album.move", json!({"id": a.id.0, "parent": fid})); + app.act("album.move", json!({"id": a.id.0, "parent": fid})); } } }); @@ -1892,7 +1892,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})); + app.act("library.source", json!({"kind": "libraryFolder", "path": n.path})); } else { *open = !*open; set_tree_open(ui, open_id, *open); @@ -2228,15 +2228,15 @@ fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: 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})); + app.act("library.filter", json!({"keyword": v})); } crate::widgets::context_menu(&resp, |ui| { 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]})); + app.act("photo.setMeta", json!({"addKeywords": [n.path]})); } if ui.add_enabled(has_sel, egui::Button::new(crate::i18n::tr("Remove from Selected Photos"))).clicked() { - let _ = app.run("photo.setMeta", json!({"removeKeywords": [n.path]})); + app.act("photo.setMeta", json!({"removeKeywords": [n.path]})); } ui.separator(); if ui.button(crate::i18n::tr("Rename Keyword…")).clicked() { @@ -2246,7 +2246,7 @@ fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: app.ui.dialog = Some(crate::state::Dialog::MergeKeywords { from: vec![n.path.clone()], into: String::new() }); } if ui.button(crate::i18n::tr("Delete Keyword")).clicked() { - let _ = app.run("keyword.delete", json!({"keyword": n.path})); + app.act("keyword.delete", json!({"keyword": n.path})); } }); } diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index 86f3796b9fa..3bad53d505b 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -275,9 +275,9 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option }; if item(ui, "maskEffectMenu:reset", crate::i18n::tr("Reset Sliders").to_string(), true) { let zero: serde_json::Map = FIELDS.iter().map(|k| (k.to_string(), json!(0.0))).collect(); - let _ = app.run("mask.adjust", json!({"id": mask.id, "values": zero})); + app.act("mask.adjust", json!({"id": mask.id, "values": zero})); if let Some(tool) = fx::mask_tool(mask) { - let _ = app.run("mask.toolEffect", json!({"tool": tool})); + app.act("mask.toolEffect", json!({"tool": tool})); } ui.close(); } @@ -288,7 +288,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option if let Some(last) = last_applied(app, mask) { let text = crate::i18n::tr_format!("Update “{name}” with Current Settings", name = last); if item(ui, "maskEffectMenu:update", text, current != Some(last.as_str())) { - let _ = app.run("mask.updateEffect", json!({"name": last, "id": mask.id})); + app.act("mask.updateEffect", json!({"name": last, "id": mask.id})); ui.close(); } } @@ -297,12 +297,12 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option ui.close(); } if item(ui, "maskEffectMenu:import", crate::i18n::tr("Import Presets…").to_string(), app.services.pick_preset_files.is_some()) { - let _ = app.run("file.importPresets", json!({})); + app.act("file.importPresets", json!({})); ui.close(); } let any = !app.session.mask_effects.is_empty(); if item(ui, "maskEffectMenu:export", crate::i18n::tr("Export Presets…").to_string(), any && app.services.save_preset_file.is_some()) { - let _ = app.run("file.exportMaskEffects", json!({})); + app.act("file.exportMaskEffects", json!({})); ui.close(); } } @@ -364,7 +364,7 @@ fn group_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, names: &[String]) { for g in groups.iter().map(String::as_str).chain(std::iter::once("")) { let label = if g.is_empty() { crate::i18n::tr("None").to_string() } else { g.to_string() }; if ui.button(label).clicked() { - let _ = app.run("mask.setEffectGroup", json!({"names": names, "group": g})); + app.act("mask.setEffectGroup", json!({"names": names, "group": g})); ui.close(); } } @@ -581,7 +581,7 @@ pub fn manage_body( } }); if let Some((name, on)) = toggle_star { - let _ = app.run("mask.favoriteEffect", json!({"name": name, "favorite": on})); + app.act("mask.favoriteEffect", json!({"name": name, "favorite": on})); } if let Some((old, to)) = commit_rename { *rename = None; @@ -605,7 +605,7 @@ pub fn manage_body( let d = ui.button(crate::i18n::tr("Delete")); register(ui, "button:effectDeleteConfirm", d.rect); if d.clicked() { - let _ = app.run("mask.deleteEffect", json!({"names": selected.clone()})); + app.act("mask.deleteEffect", json!({"names": selected.clone()})); selected.clear(); *confirm_delete = false; } @@ -631,7 +631,7 @@ pub fn manage_body( if button(ui, "Update", "Update with Mask", one.is_some() && mask.is_some()) && let (Some(name), Some(mid)) = (&one, mask) { - let _ = app.run("mask.updateEffect", json!({"name": name, "id": mid})); + app.act("mask.updateEffect", json!({"name": name, "id": mid})); } if button(ui, "Rename", "Rename", one.is_some()) && let Some(name) = &one @@ -647,7 +647,7 @@ pub fn manage_body( } if button(ui, "Favorite", "★ Favorite", n > 0) { let all_fav = selected.iter().all(|s| effects.iter().any(|e| &e.name == s && e.favorite)); - let _ = app.run("mask.favoriteEffect", json!({"names": selected.clone(), "favorite": !all_fav})); + app.act("mask.favoriteEffect", json!({"names": selected.clone(), "favorite": !all_fav})); } let g = ui.add_enabled(n > 0, egui::Button::new(crate::i18n::tr("Move to Group…"))); register(ui, "button:effectGroup", g.rect); @@ -656,7 +656,7 @@ pub fn manage_body( for (grp, _) in fx::menu_order(&app.session.mask_effects) { let label = if grp.is_empty() { crate::i18n::tr("None").to_string() } else { grp.clone() }; if ui.button(label).clicked() { - let _ = app.run("mask.setEffectGroup", json!({"names": names, "group": grp})); + app.act("mask.setEffectGroup", json!({"names": names, "group": grp})); ui.close(); } } @@ -666,13 +666,13 @@ pub fn manage_body( .width(180.0) .show(ui); if r.ending == Some(crate::text_field::Ending::Return) && !new_group.trim().is_empty() { - let _ = app.run("mask.setEffectGroup", json!({"names": names, "group": new_group.trim()})); + app.act("mask.setEffectGroup", json!({"names": names, "group": new_group.trim()})); new_group.clear(); ui.close(); } }); if button(ui, "Export", "Export…", n > 0 && app.services.save_preset_file.is_some()) { - let _ = app.run("file.exportMaskEffects", json!({"names": selected.clone()})); + app.act("file.exportMaskEffects", json!({"names": selected.clone()})); } if button(ui, "Delete", "Delete…", n > 0) { *confirm_delete = true; diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index ce28482c464..488ec87da1d 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -133,21 +133,25 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { match *kind { "colorRange" => { // an empty colour range; clicking the photo samples it - let _ = app.run("mask.add", json!({"kind": "colorRange"})); - app.ui.tool = "colorRange".into(); - app.toast(ui.ctx(), crate::i18n::tr("Click the photo to pick a colour · ⇧-click adds more")); + // refused, there is no mask to sample into: `act` said why + if app.act("mask.add", json!({"kind": "colorRange"})).is_some() { + app.ui.tool = "colorRange".into(); + app.toast(ui.ctx(), crate::i18n::tr("Click the photo to pick a colour · ⇧-click adds more")); + } } "object" => start_object(app, ui.ctx(), "new"), "prompt" => start_describe(app, "new"), "brush" => { - let _ = app.run("tool.brush", json!({"new": true})); + app.act("tool.brush", json!({"new": true})); } "linear" | "radial" => { - app.ui.tool = kind.to_string(); - let _ = app.run("mask.add", json!({"kind": kind})); + // refused: no mask to draw into, `act` said why + if app.act("mask.add", json!({"kind": kind})).is_some() { + app.ui.tool = kind.to_string(); + } } k => { - let _ = app.run("mask.add", json!({"kind": k})); + app.act("mask.add", json!({"kind": k})); } } } @@ -231,7 +235,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let name = name.trim().to_string(); app.ui.renaming_mask = None; if !name.is_empty() && name != m.name { - let _ = app.run("mask.rename", json!({"id": rid, "name": name})); + app.act("mask.rename", json!({"id": rid, "name": name})); } } continue; @@ -274,11 +278,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if eye.hovered() { t.text } else { t.text_dim }, ); if eye.clicked() { - let _ = app.run("mask.visible", json!({"id": m.id})); + app.act("mask.visible", json!({"id": m.id})); } } if resp.clicked() { - let _ = app.run("mask.select", json!({"id": m.id})); + app.act("mask.select", json!({"id": m.id})); } if resp.double_clicked() { app.ui.renaming_mask = Some((m.id, m.name.clone())); @@ -333,7 +337,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let name = name.trim().to_string(); app.ui.renaming_component = None; if Some(&name) != c.name.as_ref() { - let _ = app.run("mask.component", json!({"id": m.id, "component": i, "action": "rename", "name": name})); + app.act("mask.component", json!({"id": m.id, "component": i, "action": "rename", "name": name})); } } return; @@ -370,10 +374,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let int = text_button(ui, "maskIntComp", crate::i18n::tr("Intersect"), false); egui::Popup::menu(&int).show(|ui| component_menu(app, ui, "intersect")); if text_button(ui, "maskInvert", crate::i18n::tr("Invert"), m.invert).clicked() { - let _ = app.run("mask.invert", json!({})); + app.act("mask.invert", json!({})); } if icon_button(ui, "maskDelete", Icon::Trash, vec2(26.0, 24.0), false, true, "Delete mask").clicked() { - let _ = app.run("mask.delete", json!({})); + app.act("mask.delete", json!({})); } }); }); @@ -386,7 +390,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { for s in LOCAL { let v = local_get(&m.adjust, s.id); let out = slider(ui, s, v, true, None); - apply_slider_out(app, s, out, |app, v| app.run("mask.adjust", json!({"values": {s.id: v}}))); + apply_slider_out(app, s, out, |app, v| app.act("mask.adjust", json!({"values": {s.id: v}}))); } let amt = ControlSpec { id: "amount", @@ -400,7 +404,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { track: Track::Plain, }; let out = slider(ui, &amt, m.adjust.amount, true, None); - apply_slider_out(app, &amt, out, |app, v| app.run("mask.adjust", json!({"values": {"amount": v}}))); + apply_slider_out(app, &amt, out, |app, v| app.act("mask.adjust", json!({"values": {"amount": v}}))); let refine = ControlSpec { id: "refine", label: "Refine Edges", @@ -413,7 +417,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { track: Track::Plain, }; let out = slider(ui, &refine, m.refine, true, None); - apply_slider_out(app, &refine, out, |app, v| app.run("mask.refine", json!({"value": v}))); + apply_slider_out(app, &refine, out, |app, v| app.act("mask.refine", json!({"value": v}))); ui.add_space(30.0); let _ = Stroke::NONE; } @@ -427,7 +431,7 @@ fn menu_label(source: &str) -> &str { fn mask_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: u32, name: &str, visible: bool, index: usize, count: usize) { let mut run = |ui: &mut egui::Ui, label: &str, enabled: bool, cmd: &str, p: serde_json::Value| { if ui.add_enabled(enabled, egui::Button::new(menu_label(label))).clicked() { - let _ = app.run(cmd, p); + app.act(cmd, p); ui.close(); } }; @@ -444,7 +448,7 @@ fn mask_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: u32, name: &str, vi ui.close(); } if ui.button(crate::i18n::tr("Delete Mask")).clicked() { - let _ = app.run("mask.delete", json!({"id": id})); + app.act("mask.delete", json!({"id": id})); ui.close(); } } @@ -463,7 +467,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { egui::Popup::menu(&r).show(|ui| { for v in MaskView::ALL { if ui.selectable_label(v == view, menu_label(v.label())).clicked() { - let _ = app.run("view.maskOverlayMode", json!({"mode": v.name()})); + app.act("view.maskOverlayMode", json!({"mode": v.name()})); } } }); @@ -480,7 +484,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, t.text), egui::StrokeKind::Inside); } if resp.clicked() { - let _ = app.run("view.maskOverlayColor", json!({"color": c})); + app.act("view.maskOverlayColor", json!({"color": c})); } } }); @@ -502,7 +506,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { } let mut pins = app.ui.mask_pins; if ui.checkbox(&mut pins, crate::i18n::tr("Show Pins")).changed() { - let _ = app.run("view.maskPins", json!({"show": pins})); + app.act("view.maskPins", json!({"show": pins})); } if app.ui.mask_pins { super::right::tool_overlay_options(app, ui); @@ -514,7 +518,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape: &MaskShape) { let t = Tokens::get(ui.ctx()); let update = |app: &mut LightcraftApp, shape: MaskShape| { - let _ = app.run("mask.update", json!({"component": comp, "shape": shape})); + app.act("mask.update", json!({"component": comp, "shape": shape})); }; match shape { MaskShape::LuminanceRange { lo, hi, lo_feather, hi_feather } => { @@ -555,7 +559,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape if let Some(origin) = ui.input(|i| i.pointer.press_origin()) { ui.data_mut(|d| d.insert_temp(handle_id, nearer_low(origin.x))); } - let _ = app.run("develop.beginInteraction", json!({"label": "Luminance Range"})); + app.act("develop.beginInteraction", json!({"label": "Luminance Range"})); } if (resp.dragged() || resp.clicked()) && let Some(pos) = resp.interact_pointer_pos() @@ -568,7 +572,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape } if resp.drag_stopped() { ui.data_mut(|d| d.remove::(handle_id)); - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } // Smoothness: both falloffs at once let smooth = ControlSpec { @@ -586,7 +590,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape let out = slider(ui, &smooth, cur, true, None); apply_slider_out(app, &smooth, out, |app, v| { let f = v / 100.0 * 0.5; - app.run("mask.update", json!({"component": comp, "shape": MaskShape::LuminanceRange { lo, hi, lo_feather: f, hi_feather: f }})) + app.act("mask.update", json!({"component": comp, "shape": MaskShape::LuminanceRange { lo, hi, lo_feather: f, hi_feather: f }})) }); let mut map = app.ui.mask_overlay && app.ui.mask_overlay_mode == "colorOnBw"; let r = ui.checkbox(&mut map, crate::i18n::tr("Show Luminance Map")); @@ -624,7 +628,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape if let MaskShape::Object { edge, .. } | MaskShape::Prompt { edge, .. } = &mut s { *edge = v.clamp(-100.0, 100.0); } - app.run("mask.update", json!({"component": comp, "shape": s})) + app.act("mask.update", json!({"component": comp, "shape": s})) }); ui.label(egui::RichText::new(crate::i18n::tr("− harder border · + softer border")).color(t.text_dim).size(11.0)); } @@ -657,7 +661,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape let out = slider(ui, &spec, *refine, true, None); let samples = samples.clone(); apply_slider_out(app, &spec, out, |app, v| { - app.run("mask.update", json!({"component": comp, "shape": MaskShape::ColorRange { samples: samples.clone(), refine: v }})) + app.act("mask.update", json!({"component": comp, "shape": MaskShape::ColorRange { samples: samples.clone(), refine: v }})) }); } _ => {} @@ -671,7 +675,7 @@ fn component_row_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: u32, k: let mut p = p; p["id"] = json!(mask); p["component"] = json!(k); - let _ = app.run("mask.component", p); + app.act("mask.component", p); ui.close(); } }; @@ -697,7 +701,7 @@ fn component_row_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: u32, k: crate::i18n::tr_format!("Delete \"{label}\"", label = label) }; if ui.button(del).clicked() { - let _ = app.run("mask.component", json!({"id": mask, "component": k, "action": "delete"})); + app.act("mask.component", json!({"id": mask, "component": k, "action": "delete"})); ui.close(); } } @@ -865,9 +869,9 @@ fn component_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, op: &str) { register(ui, format!("maskComp:{op}:{kind}"), b.rect); if b.clicked() { if kind == "brush" { - let _ = app.run("tool.brush", json!({"op": op})); + app.act("tool.brush", json!({"op": op})); } else { - let _ = app.run("mask.addComponent", json!({"op": op, "kind": kind})); + app.act("mask.addComponent", json!({"op": op, "kind": kind})); } } } diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 73d19cbaa95..6af20e6491a 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -76,7 +76,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let b = crate::widgets::arrow_button(&mut child, RichText::new(label).font(t.font(13.0)), crate::icons::Icon::ChevronRight, false); register(ui, "people:last", b.rect); if b.on_hover_text(crate::i18n::tr("Back to this person")).clicked() { - let _ = app.run("view.person", json!({"name": last})); + app.act("view.person", json!({"name": last})); } } ui.painter().text(pos2(head.right() - PAD, head.center().y), Align2::RIGHT_CENTER, people.len().to_string(), t.font(13.0), t.text_dim); @@ -193,7 +193,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed } }); if resp.clicked() { - let _ = app.run("view.person", json!({"name": person.name})); + app.act("view.person", json!({"name": person.name})); } } diff --git a/crates/ui-egui/src/panels/person.rs b/crates/ui-egui/src/panels/person.rs index 98b738cf231..7904d36f0fe 100644 --- a/crates/ui-egui/src/panels/person.rs +++ b/crates/ui-egui/src/panels/person.rs @@ -151,7 +151,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let back = crate::widgets::arrow_button(ui, crate::i18n::tr("People"), crate::icons::Icon::ChevronLeft, true); register(ui, "person:back", back.rect); if back.clicked() { - let _ = app.run("view.people", json!({})); + app.act("view.people", json!({})); } ui.label(RichText::new(&shown_name).font(t.semibold(15.0)).color(t.text)); let rename = ui.button(crate::i18n::tr("Rename Person…")); @@ -166,8 +166,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { let photos = ui.button(crate::i18n::tr("Show photos")).on_hover_text(crate::i18n::tr("Their photos in the grid")); register(ui, "person:photos", photos.rect); if photos.clicked() { - let _ = app.run("library.filter", json!({"person": shown_name})); - let _ = app.run("view.photoGrid", json!({})); + app.act("library.filter", json!({"person": shown_name})); + app.act("view.photoGrid", json!({})); } }); }); @@ -243,7 +243,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { if step == super::faces::Setup::TurnOn { super::faces::take_step(app, ui.ctx(), step); } else { - let _ = app.run("app.settings", json!({"tab": "faces"})); + app.act("app.settings", json!({"tab": "faces"})); } } } @@ -268,15 +268,15 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) { if let Some((what, f)) = hit { match what { Hit::Open => { - let _ = app.run("library.select", json!({"ids": [f.photo], "active": f.photo})); - let _ = app.run("view.detail", json!({})); + app.act("library.select", json!({"ids": [f.photo], "active": f.photo})); + app.act("view.detail", json!({})); // Escape comes back to this page; the People button to everyone, with this person next to its title app.ui.person_from = Some((Some(shown_name.clone()), f.photo)); app.ui.last_person = Some(shown_name.clone()); app.ui.person_page = None; } Hit::Confirm => { - let _ = app.run("faces.setName", json!({"id": f.photo, "index": f.index, "name": shown_name})); + app.act("faces.setName", json!({"id": f.photo, "index": f.index, "name": shown_name})); } Hit::ConfirmAbove => confirm_above(app, ui.ctx(), &shown_name, &more, f.score), Hit::Dismiss => { diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 6d35a50274c..4f27c796550 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -114,11 +114,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { register(ui, "presetMenu:thumbnails", r.rect); ui.separator(); if ui.button(crate::i18n::tr("Import Presets…")).clicked() { - let _ = app.run("file.importPresets", json!({})); + app.act("file.importPresets", json!({})); } let any_user = app.session.presets.iter().any(|p| !p.builtin); if ui.add_enabled(any_user, egui::Button::new(crate::i18n::tr("Export User Presets…"))).clicked() { - let _ = app.run("file.exportPresets", json!({})); + app.act("file.exportPresets", json!({})); } }); divider(ui); @@ -138,15 +138,17 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { track: Track::Plain, }; let out = slider(ui, &spec, last.amount, true, None); + // (`run`: when the undo is refused there is nothing to re-apply, and nothing to say) if let Some(v) = out.value && app.run("edit.undo", json!({})).is_ok() { // Only replace the most recent preset; never undo intervening edits. - if app.run("preset.apply", json!({"id": &last.id, "amount": v})).is_ok() { + if app.act("preset.apply", json!({"id": &last.id, "amount": v})).is_some() { AppliedByPhoto::remember(ui.ctx(), &app.session, &last.id); ui.data_mut(|d| d.insert_temp(amt_id, AppliedPreset::new(&app.session, last.id, v))); } else { - let _ = app.run("edit.redo", json!({})); + // (quiet: it puts back the step just undone; `act` already said why the preset was refused) + app.quiet("edit.redo", json!({})); ui.data_mut(|d| d.remove::(amt_id)); } } @@ -195,7 +197,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if !favorites { crate::widgets::context_menu(&resp, |ui| { if ui.button(crate::i18n::tr("Export Group…")).clicked() { - let _ = app.run("file.exportPresets", json!({"group": g})); + app.act("file.exportPresets", json!({"group": g})); } }); } @@ -251,7 +253,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.data_mut(|d| d.insert_temp(egui::Id::unique("last-preset-hover"), (id, pr.clone(), label))); } } - if resp.clicked() && app.run("preset.apply", json!({"id": pid, "amount": 100})).is_ok() { + // only when it went through: refused (nothing selected…), `act` said why + if resp.clicked() && app.act("preset.apply", json!({"id": pid, "amount": 100})).is_some() { AppliedByPhoto::remember(ui.ctx(), &app.session, &pid); ui.data_mut(|d| d.insert_temp(amt_id, AppliedPreset::new(&app.session, pid.clone(), 100.0))); ui.data_mut(|d| d.remove::<(lightcraft_catalog::PhotoId, Preset, String)>(egui::Id::unique("last-preset-hover"))); @@ -260,7 +263,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (builtin, group) = (pr.builtin, pr.group.clone()); crate::widgets::context_menu(&resp, |ui| { if ui.button(crate::i18n::tr(if fav { "Remove from Favorites" } else { "Add to Favorites" })).clicked() { - let _ = app.run("preset.favorite", json!({"id": pid})); + app.act("preset.favorite", json!({"id": pid})); } if builtin { return; @@ -281,7 +284,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { crate::widgets::menu_button(ui, crate::i18n::tr("Move to Group"), |ui| { for g in groups.iter().filter(|x| x.user && x.name != group).map(|x| &x.name) { if ui.button(g).clicked() { - let _ = app.run("preset.move", json!({"id": pid, "group": g})); + app.act("preset.move", json!({"id": pid, "group": g})); } } if ui.button(crate::i18n::tr("New Group…")).clicked() { @@ -298,7 +301,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { }); ui.separator(); if ui.button(crate::i18n::tr("Delete Preset")).clicked() { - let _ = app.run("preset.delete", json!({"id": pid})); + app.act("preset.delete", json!({"id": pid})); } }); } diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index cf9a6c50cdb..140211712ee 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -199,9 +199,9 @@ fn cell_ui( )); if resp.clicked() { if resp.interact_pointer_pos().is_some_and(|q| star.contains(q)) { - let _ = app.run("profile.favorite", json!({"id": p_id})); + app.act("profile.favorite", json!({"id": p_id})); } else if !applied { - let _ = app.run("develop.profile", json!({"id": p_id, "amount": 100})); + app.act("develop.profile", json!({"id": p_id, "amount": 100})); ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))); } } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 45a7bf2579a..ebe32d5bb4b 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -201,7 +201,7 @@ fn custom_aspect(app: &mut LightcraftApp, ui: &mut egui::Ui) { if let (Some(x), Some(y)) = (num(&w), num(&h)) && (1.0 / lightcraft_geom::MAX_RATIO..=lightcraft_geom::MAX_RATIO).contains(&(x / y)) { - let _ = app.run("crop.aspect", json!({"aspect": [x, y]})); + app.act("crop.aspect", json!({"aspect": [x, y]})); ui.close(); } } @@ -225,7 +225,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { egui::Popup::menu(&r).show(|ui| { for (label, a) in ASPECT_PRESETS { if ui.button(crate::i18n::tr(label)).clicked() { - let _ = app.run("crop.aspect", json!({"aspect": a})); + app.act("crop.aspect", json!({"aspect": a})); } } ui.separator(); @@ -233,38 +233,38 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }); let locked = app.crop_tool_aspect().is_some(); if text_button(ui, "cropLock", if locked { "Locked" } else { "Lock" }, locked).clicked() { - let _ = app.run("crop.aspect", json!({"aspect": "toggle"})); + app.act("crop.aspect", json!({"aspect": "toggle"})); } }); ui.add_space(6.0); ui.horizontal_wrapped(|ui| { if text_button(ui, "cropRotateLeft", crate::i18n::tr("Rotate Left"), false).clicked() { - let _ = app.run("photo.rotateLeft", json!({})); + app.act("photo.rotateLeft", json!({})); } if text_button(ui, "cropRotateRight", crate::i18n::tr("Rotate Right"), false).clicked() { - let _ = app.run("photo.rotateRight", json!({})); + app.act("photo.rotateRight", json!({})); } }); ui.add_space(6.0); ui.horizontal_wrapped(|ui| { if text_button(ui, "cropFlipH", crate::i18n::tr("Flip H"), d.crop.flip_h).clicked() { - let _ = app.run("photo.flipHorizontal", json!({})); + app.act("photo.flipHorizontal", json!({})); } if text_button(ui, "cropFlipV", crate::i18n::tr("Flip V"), d.crop.flip_v).clicked() { - let _ = app.run("photo.flipVertical", json!({})); + app.act("photo.flipVertical", json!({})); } if text_button(ui, "cropSwapAspect", crate::i18n::tr("Swap Aspect (X)"), false).clicked() { - let _ = app.run("crop.rotateAspect", json!({})); + app.act("crop.rotateAspect", json!({})); } if text_button(ui, "cropReset", crate::i18n::tr("Reset"), false).clicked() { - let _ = app.run("crop.reset", json!({})); + app.act("crop.reset", json!({})); } }); }); let ang = lightcraft_develop::controls::find("crop.angle").copied(); if let Some(spec) = ang { let out = slider(ui, &spec, d.crop.geometry.angle, true, Some("Straighten")); - super::edit::apply_slider_out(app, &spec, out, |app, v| app.run("crop.straighten", json!({"angle": v}))); + super::edit::apply_slider_out(app, &spec, out, |app, v| app.act("crop.straighten", json!({"angle": v}))); // an exact angle, typed (issue #534): a field of its own, besides the slider's value padded(ui, |ui| { ui.horizontal(|ui| { @@ -289,7 +289,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { crate::widgets::register(ui, "cropAngleField", r.rect); // a drag on the field is one undo step, like the slider's if r.drag_started() { - let _ = app.run("develop.beginInteraction", json!({"label": "Straighten"})); + app.act("develop.beginInteraction", json!({"label": "Straighten"})); } // egui reports a change while text is typed even when the value isn't updated yet: // apply only a new angle @@ -301,10 +301,10 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.data_mut(|m| m.insert_temp(cancel, true)); } if r.changed() && !escaped && angle.is_finite() && angle != d.crop.geometry.angle { - let _ = app.run("crop.straighten", json!({"angle": (angle.clamp(spec.min, spec.max) * 100.0).round() / 100.0})); + app.act("crop.straighten", json!({"angle": (angle.clamp(spec.min, spec.max) * 100.0).round() / 100.0})); } if r.drag_stopped() { - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } }); }); @@ -344,7 +344,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if matches!(app.ui.crop_overlay, O::Triangle | O::Spiral) && text_button(ui, "cropOverlayOrient", crate::i18n::tr("Flip Overlay (⇧O)"), false).clicked() { - let _ = app.run("view.cropOverlayOrientation", json!({})); + app.act("view.cropOverlayOrientation", json!({})); } } }); @@ -366,7 +366,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let active = modes.iter().position(|(_, m, _)| *m == d.geometry.upright); if let Some(i) = crate::widgets::segmented(ui, "upright", &items, active, 3) { let (_, mode, key) = modes[i]; - let _ = app.run("geometry.upright", json!({"mode": key})); + app.act("geometry.upright", json!({"mode": key})); app.ui.tool = if mode == Upright::Guided { "guidedUpright".into() } else { String::new() }; } } @@ -377,7 +377,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { && text_button(ui, "uprightUpdate", crate::i18n::tr("Update"), false).clicked() { let mode = serde_json::to_value(d.geometry.upright).unwrap_or_default(); - let _ = app.run("geometry.upright", json!({"mode": mode})); + app.act("geometry.upright", json!({"mode": mode})); } if guided { let drawing = app.ui.tool == "guidedUpright"; @@ -385,7 +385,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { app.ui.tool = if drawing { String::new() } else { "guidedUpright".into() }; } if !d.geometry.guides.is_empty() && text_button(ui, "uprightClear", crate::i18n::tr("Clear Guides"), false).clicked() { - let _ = app.run("geometry.guides", json!({"guides": []})); + app.act("geometry.guides", json!({"guides": []})); } } }); @@ -402,13 +402,13 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.add_space(4.0); let mut c = d.geometry.constrain_crop; if ui.checkbox(&mut c, crate::i18n::tr("Constrain Crop")).changed() { - let _ = app.run("develop.merge", json!({"settings": {"geometry": {"constrain_crop": c}}, "label": "Constrain Crop"})); + app.act("develop.merge", json!({"settings": {"geometry": {"constrain_crop": c}}, "label": "Constrain Crop"})); } }); for spec in lightcraft_develop::controls::in_section(lightcraft_develop::Section::Geometry).filter(|c| c.id != "crop.angle") { let v = lightcraft_develop::controls::get(&d, spec.id).unwrap_or(spec.default); let out = slider(ui, spec, v, true, None); - super::edit::apply_slider_out(app, spec, out, |app, v| app.run("develop.set", json!({"control": spec.id, "value": v}))); + super::edit::apply_slider_out(app, spec, out, |app, v| app.act("develop.set", json!({"control": spec.id, "value": v}))); } } @@ -488,17 +488,17 @@ fn remove(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } } if sel.is_some() { - super::edit::apply_slider_out(app, &spec, out, |app, v| app.run("spot.update", json!({key: v / scale}))); + super::edit::apply_slider_out(app, &spec, out, |app, v| app.act("spot.update", json!({key: v / scale}))); } } if sel.is_some() { padded(ui, |ui| { ui.horizontal(|ui| { if text_button(ui, "spotRefresh", crate::i18n::tr("Refresh Source (/)"), false).clicked() { - let _ = app.run("spot.refreshSource", json!({})); + app.act("spot.refreshSource", json!({})); } if text_button(ui, "spotDelete", crate::i18n::tr("Delete (⌫)"), false).clicked() { - let _ = app.run("spot.delete", json!({})); + app.act("spot.delete", json!({})); } }); }); @@ -530,7 +530,7 @@ fn remove(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.add_space(4.0); if !d.spots.is_empty() && text_button(ui, "removeClear", crate::i18n::tr("Delete all spots"), false).clicked() { for i in (0..d.spots.len()).rev() { - let _ = app.run("spot.delete", json!({"index": i})); + app.act("spot.delete", json!({"index": i})); } } }); @@ -551,7 +551,7 @@ pub(crate) fn tool_overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { let item = ui.selectable_label(m == current, crate::i18n::tr(m.label())); register(ui, format!("toolOverlay:{}", m.name()), item.rect); if item.clicked() { - let _ = app.run("view.toolOverlay", json!({"mode": m.name()})); + app.act("view.toolOverlay", json!({"mode": m.name()})); } } }); @@ -599,23 +599,23 @@ fn red_eye(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let Some(spec) = lightcraft_develop::controls::find(&cid) else { continue }; let v = lightcraft_develop::controls::get(&d, &cid).unwrap_or(spec.default); let out = slider(ui, spec, v, true, None); - super::edit::apply_slider_out(app, spec, out, |app, v| app.run("develop.set", json!({"control": cid, "value": v}))); + super::edit::apply_slider_out(app, spec, out, |app, v| app.act("develop.set", json!({"control": cid, "value": v}))); } padded(ui, |ui| { if eye.pet { let mut on = eye.catchlight.is_some(); if ui.checkbox(&mut on, crate::i18n::tr("Add Catchlight")).changed() { - let _ = app.run("redeye.catchlight", json!({"index": i, "on": on})); + app.act("redeye.catchlight", json!({"index": i, "on": on})); } ui.add_space(4.0); } ui.horizontal(|ui| { if text_button(ui, "eyeDelete", crate::i18n::tr("Delete"), false).clicked() { - let _ = app.run("redeye.delete", json!({"index": i})); + app.act("redeye.delete", json!({"index": i})); } if n > 1 && text_button(ui, "eyeDeleteAll", crate::i18n::tr("Delete all"), false).clicked() { for k in (0..n).rev() { - let _ = app.run("redeye.delete", json!({"index": k})); + app.act("redeye.delete", json!({"index": k})); } } }); @@ -647,7 +647,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if let Some(r) = ui.horizontal(|ui| crate::rating::Rating::new("info", p.rating).show(ui)).inner { let mut params = json!({"rating": r}); crate::panels::compare::target_active(app, &mut params); - let _ = app.run("photo.rate", params); + app.act("photo.rate", params); } ui.add_space(6.0); // colour label: one swatch per label (hover shows its name); clicking the current one clears it @@ -667,7 +667,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // in Compare / Survey only the active photo, as the rating keys and the bottom pill do let mut params = json!({"label": if on { "none".to_string() } else { key }}); crate::panels::compare::target_active(app, &mut params); - let _ = app.run("photo.label", params); + app.act("photo.label", params); } } if let Some(l) = p.label { @@ -711,7 +711,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { small(ui, "File Name"); ui.allocate_ui_with_layout(vec2(ui.available_width(), 22.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoRename", Icon::Pencil, vec2(20.0, 20.0), false, true, "Rename…").clicked() { - let _ = app.run("dialog.rename", json!({})); + app.act("dialog.rename", json!({})); } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.add(egui::Label::new(egui::RichText::new(&p.file_name).color(t.text)).truncate()); @@ -730,7 +730,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if crate::widgets::icon_button(ui, "infoReveal", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) .clicked() { - let _ = app.run("app.showInFinder", json!({})); + app.act("app.showInFinder", json!({})); } }); } @@ -739,7 +739,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { small(ui, "Captured"); ui.allocate_ui_with_layout(vec2(ui.available_width(), 22.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "editCaptureTime", Icon::Pencil, vec2(20.0, 20.0), false, true, "Edit Capture Time…").clicked() { - let _ = app.run("dialog.captureTime", json!({})); + app.act("dialog.captureTime", json!({})); } let cap = p.captured.as_deref().map(crate::i18n::display_time).unwrap_or_else(|| "—".into()); ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { @@ -840,7 +840,7 @@ fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { .on_hover_text(crate::i18n::tr("Every EXIF, GPS and XMP field in the file")) .clicked() { - let _ = app.run("dialog.allMetadata", json!({})); + app.act("dialog.allMetadata", json!({})); } }); } @@ -1027,7 +1027,7 @@ fn metadata_for(app: &mut LightcraftApp, ui: &mut egui::Ui) { let on = app.ui.settings.info_selected_photos; for (id, label, selected) in [("infoFor-target", "Target Photo", false), ("infoFor-selected", "Selected Photos", true)] { if text_button(ui, id, label, on == selected).clicked() && on != selected { - let _ = app.run("view.infoSelectedPhotos", json!({"on": selected})); + app.act("view.infoSelectedPhotos", json!({"on": selected})); } } }); @@ -1046,7 +1046,7 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr let on = !mixed && st == current; if ui.selectable_label(on, crate::i18n::tr(st.label())).clicked() && !on { let ids: Vec = targets.iter().map(|id| id.0).collect(); - let _ = app.run("photo.setMeta", json!({"ids": ids, "copyrightStatus": st.id()})); + app.act("photo.setMeta", json!({"ids": ids, "copyrightStatus": st.id()})); } } }); @@ -1083,7 +1083,7 @@ fn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str } // Return (one line) or leaving saves; Esc gives the edit up if r.committed() && (edit.text != edit.start || edit.clears()) { - let _ = app.run("photo.setMeta", json!({"ids": edit.ids, key: edit.text})); + app.act("photo.setMeta", json!({"ids": edit.ids, key: edit.text})); } ui.add_space(6.0); } @@ -1256,7 +1256,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { .clicked() || returned { - let _ = app.run("tool.keywordPainter", json!({"keyword": if painting.is_some() { serde_json::Value::Null } else { json!(k) }})); + app.act("tool.keywordPainter", json!({"keyword": if painting.is_some() { serde_json::Value::Null } else { json!(k) }})); } }); ui.add_space(10.0); @@ -1279,7 +1279,7 @@ fn keywording(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = if grouped { r.on_hover_text(&whole) } else { r }; register(ui, format!("kwSuggest:{k}"), r.rect); if r.clicked() { - let _ = app.run("photo.setMeta", json!({"addKeywords": [k]})); + app.act("photo.setMeta", json!({"addKeywords": [k]})); } } }); @@ -1336,7 +1336,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { .selectable_label(name == current, crate::i18n::builtin_label(name, name == lightcraft_engine::cmd::keywords::RECENT)) .clicked() { - let _ = app.run("keyword.useSet", json!({"name": name})); + app.act("keyword.useSet", json!({"name": name})); } } ui.separator(); @@ -1368,7 +1368,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { if current != lightcraft_engine::cmd::keywords::RECENT && ui.button(crate::i18n::tr_format!("Delete “{current}”", current = current)).clicked() { - let _ = app.run("keyword.deleteSet", json!({"name": current})); + app.act("keyword.deleteSet", json!({"name": current})); } }); crate::widgets::name_combo(&combo.response, crate::i18n::tr("Keyword Set")); @@ -1408,7 +1408,7 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { register(ui, format!("kwSetSome:{}", i + 1), r.rect); } if r.clicked() { - let _ = app.run("keyword.toggleFromSet", json!({"index": i + 1})); + app.act("keyword.toggleFromSet", json!({"index": i + 1})); } if i % 3 == 2 { ui.end_row(); @@ -1423,7 +1423,7 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let t = Tokens::get(ui.ctx()); padded(ui, |ui| { if text_button(ui, "versionCreate", crate::i18n::tr("Create Version"), false).clicked() { - let _ = app.run("version.create", json!({})); + app.act("version.create", json!({})); } ui.add_space(8.0); // Named (made by you) and Auto (made by LightCraft) versions @@ -1482,7 +1482,7 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if resp.double_clicked() { crate::panels::dialogs::prompt(app, "Rename Version", "Version name", &v.name, "version.rename", json!({"index": i}), "name"); } else if resp.clicked() && !current { - let _ = app.run("version.restore", json!({"index": i})); + app.act("version.restore", json!({"index": i})); } let resp = resp.on_hover_text(crate::i18n::tr(if current { "The photo has these settings" @@ -1491,20 +1491,20 @@ fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { })); crate::widgets::context_menu(&resp, |ui| { if ui.button(crate::i18n::tr("Restore")).clicked() { - let _ = app.run("version.restore", json!({"index": i})); + app.act("version.restore", json!({"index": i})); } if ui.button(crate::i18n::tr("Update with Current Settings")).clicked() { - let _ = app.run("version.update", json!({"index": i})); + app.act("version.update", json!({"index": i})); } if ui.button(crate::i18n::tr("Rename…")).clicked() { crate::panels::dialogs::prompt(app, "Rename Version", "Version name", &v.name, "version.rename", json!({"index": i}), "name"); } if ui.button(crate::i18n::tr("Set as Before")).clicked() { - let _ = app.run("beforeAfter.setBefore", json!({"source": "version", "name": v.name})); + app.act("beforeAfter.setBefore", json!({"source": "version", "name": v.name})); } ui.separator(); if ui.button(crate::i18n::tr("Delete")).clicked() { - let _ = app.run("version.delete", json!({"index": i})); + app.act("version.delete", json!({"index": i})); } }); } @@ -1576,19 +1576,21 @@ fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { text, ); if resp.clicked() { - let _ = app.run("history.restore", json!({"index": i})); + app.act("history.restore", json!({"index": i})); } crate::widgets::context_menu(&resp, |ui| { if ui.button(crate::i18n::tr("Copy History Step Settings to Before")).clicked() { - let _ = app.run("beforeAfter.setBefore", json!({"source": "history", "index": i})); + app.act("beforeAfter.setBefore", json!({"source": "history", "index": i})); } if ui.button(crate::i18n::tr("Create Version from Step")).clicked() { - let _ = app.run("history.restore", json!({"index": i})); - let _ = app.run("version.create", json!({"name": h.label})); + // refused: `act` said why, and a version of the current step would be wrong + if app.act("history.restore", json!({"index": i})).is_some() { + app.act("version.create", json!({"name": h.label})); + } } ui.separator(); if ui.button(crate::i18n::tr("Clear History")).clicked() { - let _ = app.run("history.clear", json!({})); + app.act("history.clear", json!({})); } }); } diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 338d55c0091..48672065ba3 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -257,12 +257,12 @@ fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Open Library…"))); register(ui, "button:settingsOpenLibrary", r.rect); if r.clicked() { - let _ = app.run("app.openLibrary", json!({})); + app.act("app.openLibrary", json!({})); } let r = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("New Library…"))); register(ui, "button:settingsNewLibrary", r.rect); if r.clicked() { - let _ = app.run("app.newLibrary", json!({})); + app.act("app.newLibrary", json!({})); } if !can { hint(ui, t, crate::i18n::tr("not available here")); @@ -405,13 +405,13 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { hint(ui, t, crate::i18n::tr("Settings new raw photos start from. Changing them doesn't touch photos already in the library.")); row(ui, t, crate::i18n::tr("Raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsRawPreset", crate::i18n::tr("Raw default"), d.raw_preset.as_deref(), "LightCraft Default") { - let _ = app.run("library.preferences", json!({"import": {"rawPreset": v}})); + app.act("library.preferences", json!({"import": {"rawPreset": v}})); } }); let mut per = d.per_camera; row(ui, t, "", |ui| { if check(ui, "settings.perCamera", &mut per, "Use camera-specific defaults") { - let _ = app.run("library.preferences", json!({"import": {"perCamera": per}})); + app.act("library.preferences", json!({"import": {"perCamera": per}})); } }); if per { @@ -456,7 +456,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { crate::widgets::name_combo(&r.response, crate::i18n::tr("Camera")); register(ui, format!("combo:{id}"), r.response.rect); if let Some(c) = pick { - let _ = app.run("library.preferences", json!({"camera": c})); + app.act("library.preferences", json!({"camera": c})); } }); } @@ -465,7 +465,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Other images (JPEG, PNG, TIFF, HEIC…)")); row(ui, t, crate::i18n::tr("Non-raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", crate::i18n::tr("Other preset"), d.other_preset.as_deref(), "None") { - let _ = app.run("library.preferences", json!({"import": {"otherPreset": v}})); + app.act("library.preferences", json!({"import": {"otherPreset": v}})); } }); heading(ui, t, crate::i18n::tr("Metadata")); @@ -479,7 +479,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(hint_text).desired_width(240.0)); register(ui, format!("field:settings.{key}"), r.rect); if r.lost_focus() && text.trim() != value { - let _ = app.run("library.preferences", json!({"import": {key: text.trim()}})); + app.act("library.preferences", json!({"import": {key: text.trim()}})); } if r.has_focus() { ui.data_mut(|m| m.insert_temp(id, text)); @@ -508,21 +508,21 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { crate::widgets::name_combo(&r.response, crate::i18n::tr("Metadata preset")); register(ui, "combo:settingsMetaPreset", r.response.rect); if let Some(n) = pick { - let _ = app.run("library.preferences", json!({"import": {"metadataPreset": n}})); + app.act("library.preferences", json!({"import": {"metadataPreset": n}})); } }); } heading(ui, t, crate::i18n::tr("XMP sidecars")); let mut xmp = app.session.xmp; if check(ui, "settings.autoWriteXmp", &mut xmp.auto_write, "Automatically write changes into XMP sidecars") { - let _ = app.run("library.xmpPreferences", json!({"autoWrite": xmp.auto_write})); + app.act("library.xmpPreferences", json!({"autoWrite": xmp.auto_write})); } row(ui, t, crate::i18n::tr("Sidecar names"), |ui| { use lightcraft_engine::sidecar::SidecarNaming as N; let mut n = xmp.naming; if choices(ui, "settingsXmpNaming", &[(N::Stem, "IMG_1.xmp"), (N::Full, "IMG_1.CR3.xmp")], &mut n) { let naming = if n == N::Full { "full" } else { "stem" }; - let _ = app.run("library.xmpPreferences", json!({"naming": naming})); + app.act("library.xmpPreferences", json!({"naming": naming})); } }); if !cfg!(target_arch = "wasm32") { @@ -531,7 +531,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, crate::i18n::tr("Cameras and Cards")); let mut on_card = d.show_on_card; if check(ui, "settings.importOnCard", &mut on_card, "Show the import review when a camera or card is connected") { - let _ = app.run("library.preferences", json!({"import": {"showOnCard": on_card}})); + app.act("library.preferences", json!({"import": {"showOnCard": on_card}})); } heading(ui, t, crate::i18n::tr("Auto Import")); hint(ui, t, crate::i18n::tr("Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.")); @@ -557,14 +557,14 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { app.toast(ui.ctx(), e); } if d.auto_folder.is_some() && ui.button(crate::i18n::tr("Turn Off")).clicked() { - let _ = app.run("library.autoImport", json!({"folder": null})); + app.act("library.autoImport", json!({"folder": null})); } }); if d.auto_folder.is_some() { row(ui, t, "", |ui| { let mut copy = d.auto_copy; if ui.checkbox(&mut copy, crate::i18n::tr("Copy into the library (else use the files where they are)")).changed() { - let _ = app.run("library.autoImport", json!({"copy": copy})); + app.act("library.autoImport", json!({"copy": copy})); } }); row(ui, t, crate::i18n::tr("Album"), |ui| { @@ -572,7 +572,7 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let mut name = ui.data(|m| m.get_temp::(id)).unwrap_or_else(|| d.auto_album.clone().unwrap_or_default()); let r = ui.add(egui::TextEdit::singleline(&mut name).hint_text(crate::i18n::tr("None")).desired_width(180.0)); if r.lost_focus() { - let _ = app.run("library.autoImport", json!({"album": name.trim()})); + app.act("library.autoImport", json!({"album": name.trim()})); } ui.data_mut(|m| m.insert_temp(id, name)); }); @@ -625,7 +625,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let opts = [(512u32, "512 MB"), (1024, "1 GB"), (2048, "2 GB"), (4096, "4 GB"), (8192, "8 GB")]; let mut v = if CACHE_SIZES.contains(&cur) { cur } else { 2048 }; if choices(ui, "settingsCache", &opts, &mut v) { - let _ = app.run("library.preferences", json!({"cacheMb": v})); + app.act("library.preferences", json!({"cacheMb": v})); } }); let used = app.session.media.rendered.disk().map(|d| d.size()); @@ -637,7 +637,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.button(crate::i18n::tr("Clear Cache")); register(ui, "button:settingsClearCache", r.rect); if r.clicked() { - let _ = app.run("library.clearPreviews", json!({})); + app.act("library.clearPreviews", json!({})); } }); heading(ui, t, crate::i18n::tr("Local folders")); @@ -645,7 +645,7 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")]; let mut v = app.session.forget_local_days; if choices(ui, "settingsForgetLocal", &opts, &mut v) { - let _ = app.run("library.preferences", json!({"forgetLocalDays": v})); + app.act("library.preferences", json!({"forgetLocalDays": v})); } }); hint( @@ -939,7 +939,7 @@ fn duration_slider(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, key: &s app.session.slideshow = next; } if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("slideshow.playback", json!({ key: v })); + app.act("slideshow.playback", json!({ key: v })); } } @@ -977,7 +977,7 @@ fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = ui.add_enabled(!running, egui::Button::new(crate::i18n::tr(label))); register(ui, format!("button:{id}"), r.rect); if r.clicked() { - let _ = app.run("dialog.slideshowExport", json!({"format": format})); + app.act("dialog.slideshowExport", json!({"format": format})); } } }); @@ -990,7 +990,7 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let s = app.session.slideshow.clone(); let mut v = s.manual; if check(ui, "settings.slideshowManual", &mut v, "Manual slideshow") { - let _ = app.run("slideshow.playback", json!({"manual": v})); + app.act("slideshow.playback", json!({"manual": v})); } hint(ui, t, crate::i18n::tr("A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.")); row(ui, t, crate::i18n::tr("Slide duration"), |ui| { @@ -1022,7 +1022,7 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { Fade::White => json!("#ffffff"), Fade::Color => json!([64, 64, 64]), }; - let _ = app.run("slideshow.playback", json!({"fadeColor": c})); + app.act("slideshow.playback", json!({"fadeColor": c})); } if f == Fade::Color && let Some(mut c) = s.fade_color @@ -1030,21 +1030,21 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let r = egui::color_picker::color_edit_button_srgb(ui, &mut c); register(ui, "button:slideshowFadeColor", r.rect); if r.changed() { - let _ = app.run("slideshow.playback", json!({"fadeColor": c})); + app.act("slideshow.playback", json!({"fadeColor": c})); } } }); let mut v = s.random_order; if check(ui, "settings.slideshowRandom", &mut v, "Random order") { - let _ = app.run("slideshow.playback", json!({"randomOrder": v})); + app.act("slideshow.playback", json!({"randomOrder": v})); } let mut v = s.repeat; if check(ui, "settings.slideshowRepeat", &mut v, "Repeat (off: the slideshow ends after the last photo)") { - let _ = app.run("slideshow.playback", json!({"repeat": v})); + app.act("slideshow.playback", json!({"repeat": v})); } let mut v = s.prepare_previews; if check(ui, "settings.slideshowPrepare", &mut v, "Prepare previews in advance") { - let _ = app.run("slideshow.playback", json!({"preparePreviews": v})); + app.act("slideshow.playback", json!({"preparePreviews": v})); } hint( ui, diff --git a/crates/ui-egui/src/panels/slide_layout.rs b/crates/ui-egui/src/panels/slide_layout.rs index 82387f1e61d..414e1e45ff0 100644 --- a/crates/ui-egui/src/panels/slide_layout.rs +++ b/crates/ui-egui/src/panels/slide_layout.rs @@ -35,7 +35,7 @@ enum Unit { } fn set(app: &mut LightcraftApp, p: Value) { - let _ = app.run("slideshow.layout", p); + app.act("slideshow.layout", p); } /// A layout slider (`slider:{id}`): `key`'s value, 0–`max` (percent) or −180–180° (degrees). diff --git a/crates/ui-egui/src/panels/slide_overlays.rs b/crates/ui-egui/src/panels/slide_overlays.rs index e9c88f0b326..72e1b32f0da 100644 --- a/crates/ui-egui/src/panels/slide_overlays.rs +++ b/crates/ui-egui/src/panels/slide_overlays.rs @@ -27,7 +27,7 @@ enum Unit { } fn set(app: &mut LightcraftApp, p: Value) { - let _ = app.run("slideshow.overlays", p); + app.act("slideshow.overlays", p); } /// A slider (`slider:{id}`) over `lo..=hi`; `wrap(value)` makes the `slideshow.overlays` request. diff --git a/crates/ui-egui/src/panels/slide_titles.rs b/crates/ui-egui/src/panels/slide_titles.rs index b3c10340216..b0ecc858c0a 100644 --- a/crates/ui-egui/src/panels/slide_titles.rs +++ b/crates/ui-egui/src/panels/slide_titles.rs @@ -45,7 +45,7 @@ pub fn preview_choice(ui: &mut egui::Ui) { /// Change `key` of screen `t` (and show that screen in the preview). fn set(app: &mut LightcraftApp, ctx: &egui::Context, t: Title, key: &str, v: Value) { - let _ = app.run("slideshow.titles", json!({ t.id(): { key: v } })); + app.act("slideshow.titles", json!({ t.id(): { key: v } })); set_preview_shows(ctx, Some(t)); } @@ -73,7 +73,7 @@ fn slider( set_preview_shows(ui.ctx(), Some(t)); } if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("slideshow.titles", p); + app.act("slideshow.titles", p); } } diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index cfe0ce6e68d..ee873cbe6f9 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -76,7 +76,8 @@ pub fn start(app: &mut LightcraftApp, p: &Value, now: f64) -> Result Value { fn after(app: &mut LightcraftApp, t: Tick) { match t { Tick::Advanced(Item::Photo(id)) if app.session.active() != Some(id) => { - let _ = app.run("library.select", json!({"ids": [id.0]})); + // refusal expected: the slideshow moving on by itself: nobody asked, so nobody is told + app.quiet("library.select", json!({"ids": [id.0]})); } Tick::Ended => end(app), _ => {} @@ -424,7 +426,7 @@ fn controls(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, now: f64) fire = Some("slideshow.end"); } if let Some(id) = fire { - let _ = app.run(id, json!({})); + app.act(id, json!({})); } } diff --git a/crates/ui-egui/src/panels/strip.rs b/crates/ui-egui/src/panels/strip.rs index 164204b869e..220667fa2a4 100644 --- a/crates/ui-egui/src/panels/strip.rs +++ b/crates/ui-egui/src/panels/strip.rs @@ -31,7 +31,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = GAP; let sz = vec2(t.strip_w, BUTTON_H); if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() { - let _ = app.run("panel.presets", json!({})); + app.act("panel.presets", json!({})); } for (id, icon, panel, tip) in [ ("edit", Icon::Sliders, RightPanel::Edit, "Edit (E)"), @@ -42,7 +42,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ] { let on = app.ui.right == panel || (panel == RightPanel::Edit && app.ui.right == RightPanel::Profiles); if icon_button(ui, id, icon, sz, on, has_photo, tip).clicked() { - let _ = app.run(&format!("panel.{id}"), json!({})); + app.act(&format!("panel.{id}"), json!({})); } if id == "edit" { separator(ui, &t); @@ -50,10 +50,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } separator(ui, &t); if icon_button(ui, "versions", Icon::Versions, sz, app.ui.right == RightPanel::Versions, has_photo, "Versions (Shift+V)").clicked() { - let _ = app.run("panel.versions", json!({})); + app.act("panel.versions", json!({})); } if icon_button(ui, "activity", Icon::Activity, sz, app.ui.right == RightPanel::Activity, true, "History & Activity (Y)").clicked() { - let _ = app.run("panel.activity", json!({})); + app.act("panel.activity", json!({})); } if icon_button(ui, "more", Icon::More, sz, false, true, "More").clicked() { app.ui.dialog = Some(crate::state::Dialog::About); @@ -71,10 +71,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = GAP; let sz = vec2(t.strip_w, BUTTON_H); if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() { - let _ = app.run("panel.keywords", json!({})); + app.act("panel.keywords", json!({})); } if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() { - let _ = app.run("panel.info", json!({})); + app.act("panel.info", json!({})); } }); }); diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index c1c645a1d6e..dc88c9b4cef 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -85,11 +85,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if icon_button(ui, "sidebar", Icon::Sidebar, vec2(30.0, 30.0), app.ui.left_panel, true, crate::i18n::tr("Show/hide My Photos panel")) .clicked() { - let _ = app.run("view.leftPanel", json!({})); + app.act("view.leftPanel", json!({})); } ui.add_space(8.0); if icon_button(ui, "back", Icon::Back, vec2(30.0, 30.0), false, true, crate::i18n::tr("Back")).clicked() { - let _ = app.run("view.back", json!({})); + app.act("view.back", json!({})); } icon_button(ui, "forward", Icon::Forward, vec2(30.0, 30.0), false, false, crate::i18n::tr("Forward")); if !app.native_menu { @@ -132,7 +132,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .response; if resp.changed() { let q = app.ui.search.clone(); - let _ = app.run("library.filter", json!({"text": q})); + app.act("library.filter", json!({"text": q})); } // filter icon right of the search field let fr = Rect::from_center_size(pos2(sr.right() + 22.0, sr.center().y), vec2(28.0, 28.0)); @@ -165,7 +165,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { crate::i18n::tr("Filter bar").into() }); if fresp.clicked() { - let _ = app.run("view.filterBar", json!({})); + app.act("view.filterBar", json!({})); } // right icons let mut x = full.right() - 18.0; @@ -213,12 +213,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.painter().text(c, Align2::CENTER_CENTER, "!", t.semibold(9.5), t.canvas); register(ui, "indicator:unsaved", r); } - // a refusal says why (Import while a Lightroom catalog is coming in) - if resp.clicked() - && !cmd.is_empty() - && let Err(e) = app.run(cmd, json!({})) - { - app.toast_error(ui.ctx(), e); + if resp.clicked() && !cmd.is_empty() { + app.act(cmd, json!({})); } x -= 40.0; } @@ -231,13 +227,13 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { register(ui, "icon:appearance", r); paint(ui.painter(), r.shrink(5.0), icon, if resp.hovered() { t.text } else { t.icon }); if resp.clicked() { - let _ = app.run("view.appearance", json!({})); + app.act("view.appearance", json!({})); } crate::widgets::context_menu(&resp, |ui| { let settings = ui.button(crate::i18n::tr("Appearance Settings…")); register(ui, "menu:appearanceSettings", settings.rect); if settings.clicked() { - let _ = app.run("app.settings", json!({"tab": "interface"})); + app.act("app.settings", json!({"tab": "interface"})); ui.close(); } let favorites = app.ui.settings.favorite_themes.clone(); @@ -251,7 +247,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = ui.selectable_label(app.ui.settings.theme(app.system_theme(ui.ctx())) == *kind, crate::i18n::tr(kind.label())); register(ui, format!("menu:themeFavorite-{}", kind.id()), r.rect); if r.clicked() { - let _ = app.run("view.theme", json!({"theme": kind.id()})); + app.act("view.theme", json!({"theme": kind.id()})); ui.close(); } } diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 7f42437b2ef..9dd16f4b5c9 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -101,7 +101,7 @@ fn click(app: &mut LightcraftApp, list: &Unnamed, i: usize, shift: bool) { /// Name `faces` (photo, region) `name`, as one undo step. fn name(app: &mut LightcraftApp, faces: &[(u64, usize)], name: &str) { let list: Vec = faces.iter().map(|(photo, index)| json!({"photo": photo, "index": index})).collect(); - let _ = app.run("faces.nameFaces", json!({"faces": list, "name": name})); + app.act("faces.nameFaces", json!({"faces": list, "name": name})); } /// The bar above the faces while some are selected: how many, a box to name them all, and the people already named. @@ -206,7 +206,7 @@ pub fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed let b = ui.put(r, egui::Button::new(crate::i18n::tr("Open Settings"))); register(ui, "unnamed:openSettings", b.rect); if b.clicked() { - let _ = app.run("app.settings", json!({"tab": "faces"})); + app.act("app.settings", json!({"tab": "faces"})); } } else if !list.faces.is_empty() { let r = Rect::from_min_size(pos2(right - 130.0, at.y + 12.0), vec2(130.0, 22.0)); @@ -269,8 +269,8 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize } // a double click opens the photo, as in the grid; its second click must not undo the first one's selection if resp.double_clicked() { - let _ = app.run("library.select", json!({"ids": [f.photo], "active": f.photo})); - let _ = app.run("view.detail", json!({})); + app.act("library.select", json!({"ids": [f.photo], "active": f.photo})); + app.act("view.detail", json!({})); // Escape comes back to the faces app.ui.person_from = Some((None, f.photo)); } else if resp.clicked() { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 8ea82f68dc7..637bbc532d1 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -464,14 +464,17 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { }); use crate::panels::compare; // rating/flag/label keys: in Compare/Survey they act on the active photo only; Shift+key or - // Auto Advance then moves on (next candidate in Compare, next photo elsewhere) - let cull = |app: &mut LightcraftApp, id: &str, mut params: serde_json::Value, advance: bool| { + // Auto Advance then moves on (next candidate in Compare, next photo elsewhere). A key is a + // click by another name: refused, `act` says why, and the caller says its success only when + // this answers true. + let cull = |app: &mut LightcraftApp, id: &str, mut params: serde_json::Value, advance: bool| -> bool { compare::target_active(app, &mut params); let was = app.session.active(); - let ok = app.run(id, params).is_ok(); + let ok = key_act(app, id, params).is_some(); if ok && (advance || app.ui.auto_advance) { compare::advance(app, was); } + ok }; for (id, params) in aliased { // a slideshow: Space pauses / resumes @@ -490,29 +493,28 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { o.remove("advance"); } cull(app, id, params, advance); - } else if let Err(e) = app.run(id, params) - && matches!(id, "app.export" | "app.exportPrevious") - { - // an export that can't start (e.g. no folder) says why instead of doing nothing - app.toast(ctx, e); + } else { + // a command that can't run (an export with no folder…) says why instead of doing nothing + key_act(app, id, params); } } let rotate_fires = fire.iter().any(|f| f == "crop.rotateAspect"); for f in fire { // a slideshow: ←/→ step (a cut) if app.ui.slideshow.is_some() && matches!(f.as_str(), "library.next" | "library.previous") { - let _ = app.run(if f == "library.next" { "slideshow.next" } else { "slideshow.previous" }, json!({})); + key_act(app, if f == "library.next" { "slideshow.next" } else { "slideshow.previous" }, json!({})); continue; } if let Some(rest) = f.strip_prefix("rate:") { let (n, adv) = rest.split_once(':').unwrap_or(("0", "0")); - cull(app, "photo.rate", json!({"rating": n.parse::().unwrap_or(0)}), adv == "1"); - let label = if n == "0" { - crate::i18n::tr("Rating cleared").to_string() - } else { - crate::i18n::tr_format!("Rated {}", "★".repeat(n.parse().unwrap_or(0))) - }; - app.toast(ctx, label); + if cull(app, "photo.rate", json!({"rating": n.parse::().unwrap_or(0)}), adv == "1") { + let label = if n == "0" { + crate::i18n::tr("Rating cleared").to_string() + } else { + crate::i18n::tr_format!("Rated {}", "★".repeat(n.parse().unwrap_or(0))) + }; + app.toast(ctx, label); + } } else if matches!(f.as_str(), "photo.decreaseRating" | "photo.increaseRating") { cull(app, &f, json!({}), false); } else if let Some(l) = f.strip_prefix("label:") { @@ -522,13 +524,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { cull(app, "photo.flag", json!({"flag": "pick"}), true); } else if f == "view.softProof" && matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) { // S in a grid: expand / collapse the stack (Lightroom's Library binding) - let _ = app.run("stack.toggle", json!({})); + key_act(app, "stack.toggle", json!({})); } else if f == "grid:first" || f == "grid:last" { // Home / End in a grid: make the first / last photo of the view the active, selected one let vis = app.session.visible_cloned(); let edge = if f == "grid:first" { vis.first() } else { vis.last() }; if let Some(id) = edge { - let _ = app.run("library.select", json!({"ids": [id.0], "active": id.0})); + key_act(app, "library.select", json!({"ids": [id.0], "active": id.0})); } } else if let Some(step) = f.strip_prefix("grid:extend:") { // Shift+← / Shift+→ in a grid: the neighbour of the active photo joins the selection and @@ -544,16 +546,16 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { .and_then(|pos| usize::try_from(pos).ok()) .and_then(|pos| vis.get(pos)); if let Some(id) = neighbour { - let _ = app.run("library.select", json!({"ids": [id.0], "mode": "add"})); + key_act(app, "library.select", json!({"ids": [id.0], "mode": "add"})); } } else if compare::culling(app) && (f == "library.next" || f == "library.previous") { let d = if f == "library.next" { 1 } else { -1 }; let _ = if app.ui.view == crate::state::ViewMode::Compare { compare::compare_step(app, d) } else { compare::survey_step(app, d) }; } else if matches!(f.as_str(), "photo.cycleFlag" | "photo.increaseFlag" | "photo.decreaseFlag") { - // `, ⌘↑, ⌘↓: step the flag; the toast names the active photo's new state (read before Auto Advance moves on) + // `, ⌘↑, ⌘↓: step the flag; the toast names the active photo's new state (read before Auto Advance moves on). + // A refused step keeps the reason `act` gave on screen. let active = app.session.active(); - cull(app, &f, json!({}), false); - let flag = active.and_then(|id| app.session.catalog.photo(id)).map(|p| p.flag); + let flag = if cull(app, &f, json!({}), false) { active.and_then(|id| app.session.catalog.photo(id)).map(|p| p.flag) } else { None }; match flag { Some(lightcraft_catalog::Flag::Pick) => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), Some(lightcraft_catalog::Flag::Reject) => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), @@ -561,16 +563,17 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { None => {} } } else if matches!(f.as_str(), "photo.pick" | "photo.reject" | "photo.unflag") && app.ui.right != crate::state::RightPanel::Crop { - cull(app, &f, json!({}), false); - match f.as_str() { - "photo.pick" => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), - "photo.reject" => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), - _ => app.toast(ctx, crate::i18n::tr("Unflagged")), + if cull(app, &f, json!({}), false) { + match f.as_str() { + "photo.pick" => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), + "photo.reject" => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), + _ => app.toast(ctx, crate::i18n::tr("Unflagged")), + } } } else { // in the full-screen preview (no panels) I cycles the info overlay instead if f == "panel.info" && app.ui.fullscreen { - let _ = app.run("view.infoOverlay", json!({})); + key_act(app, "view.infoOverlay", json!({})); continue; } // Delete acts on what's being edited: the active mask in the Masking panel; never the @@ -580,13 +583,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { match app.ui.right { R::Masking => { if app.session.active_mask.is_some() { - let _ = app.run("mask.delete", json!({})); + key_act(app, "mask.delete", json!({})); } continue; } R::Remove => { if app.session.active_spot.is_some() { - let _ = app.run("spot.delete", json!({})); + key_act(app, "spot.delete", json!({})); } continue; } @@ -600,7 +603,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { { let guides: Vec<[f64; 4]> = d.geometry.guides.iter().enumerate().filter(|(k, _)| *k != i).map(|(_, (a, b))| [a.x, a.y, b.x, b.y]).collect(); - let _ = app.run("geometry.guides", json!({"guides": guides})); + app.act("geometry.guides", json!({"guides": guides})); } app.ui.selected_guide = None; } @@ -620,7 +623,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } // B: the brush while editing; in the grids, add to the target album (Quick Collection) if f == "tool.brush" && matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) { - if let Ok(r) = app.run("album.toggleTarget", json!({})) { + if let Some(r) = key_act(app, "album.toggleTarget", json!({})) { let n = app.session.selected().len(); let what = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); let name = r["name"].as_str().unwrap_or("Quick Collection").to_string(); @@ -639,7 +642,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { // swap once: twice would put the crop straight back (issue #1866). if f == "photo.reject" && app.ui.right == crate::state::RightPanel::Crop { if !rotate_fires { - let _ = app.run("crop.rotateAspect", json!({})); + key_act(app, "crop.rotateAspect", json!({})); } continue; } @@ -655,12 +658,12 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } // / refreshes the selected spot's source in the Remove tool (the filmstrip elsewhere) if f == "view.filmstrip" && app.ui.right == crate::state::RightPanel::Remove && app.session.active_spot.is_some() { - let _ = app.run("spot.refreshSource", json!({})); + key_act(app, "spot.refreshSource", json!({})); continue; } // Shift+O cycles the mask overlay colour while masking (the crop overlay elsewhere) if f == "view.cropOverlay" && app.ui.right == crate::state::RightPanel::Masking { - let _ = app.run("view.maskOverlayColor", json!({})); + key_act(app, "view.maskOverlayColor", json!({})); continue; } // while cropping: O cycles the guides, Shift+O their orientation @@ -671,7 +674,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { _ => None, }; if let Some((cmd, p)) = crop_key { - let _ = app.run(cmd, p); + key_act(app, cmd, p); continue; } } @@ -686,27 +689,25 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { match crate::panels::grid::row_distance(app, f == "library.down") { Some(0) => {} Some(rows) => { - let _ = app.run(&f, json!({"rows": rows})); + app.act(&f, json!({"rows": rows})); } None => { - let _ = app.run(&f, json!({})); + app.act(&f, json!({})); } } continue; } - // an export that can't start (e.g. no folder) says why instead of doing nothing - if let Err(e) = app.run(&f, json!({})) - && matches!(f.as_str(), "app.export" | "app.exportPrevious") - { - app.toast(ctx, e); - } - match f.as_str() { - "photo.pick" => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), - "photo.reject" => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), - "photo.unflag" => app.toast(ctx, crate::i18n::tr("Unflagged")), - "edit.undo" => app.toast(ctx, crate::i18n::tr("Undo")), - "edit.redo" => app.toast(ctx, crate::i18n::tr("Redo")), - _ => {} + // a command that can't run (an export with no folder, nothing to undo…) says why + // instead of doing nothing; its success is said only when it went through + if key_act(app, &f, json!({})).is_some() { + match f.as_str() { + "photo.pick" => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), + "photo.reject" => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), + "photo.unflag" => app.toast(ctx, crate::i18n::tr("Unflagged")), + "edit.undo" => app.toast(ctx, crate::i18n::tr("Undo")), + "edit.redo" => app.toast(ctx, crate::i18n::tr("Redo")), + _ => {} + } } } } @@ -716,6 +717,13 @@ pub(crate) fn library_grid(app: &LightcraftApp) -> bool { matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) } +/// Runs a key's command for the person ([`LightcraftApp::act`]: a refusal says why). With a +/// dialog open the keys still reach here, but the person is typing at the dialog, not asking for +/// the command behind it: a refusal there says nothing. +fn key_act(app: &mut LightcraftApp, id: &str, params: serde_json::Value) -> Option { + if app.ui.dialog.is_some() { app.quiet(id, params) } else { app.act(id, params) } +} + #[cfg(test)] mod tests { diff --git a/crates/ui-egui/src/tests_masking.rs b/crates/ui-egui/src/tests_masking.rs index c8d6d6c2eae..e7d10a7031a 100644 --- a/crates/ui-egui/src/tests_masking.rs +++ b/crates/ui-egui/src/tests_masking.rs @@ -1155,11 +1155,11 @@ fn geometry_slider_drag_marks_the_grid() { let mut h = detail("panel.crop"); let spec = lightcraft_develop::controls::find("geometry.vertical").unwrap(); let start = crate::widgets::SliderOut { value: None, drag_started: true, drag_stopped: false, reset: false }; - crate::panels::edit::apply_slider_out(&mut h.app, spec, start, |_, _| Ok(serde_json::Value::Null)); + crate::panels::edit::apply_slider_out(&mut h.app, spec, start, |_, _| Some(serde_json::Value::Null)); assert_eq!(h.app.ui.dragging_control.as_deref(), Some("geometry.vertical")); h.step(); let stop = crate::widgets::SliderOut { value: None, drag_started: false, drag_stopped: true, reset: false }; - crate::panels::edit::apply_slider_out(&mut h.app, spec, stop, |_, _| Ok(serde_json::Value::Null)); + crate::panels::edit::apply_slider_out(&mut h.app, spec, stop, |_, _| Some(serde_json::Value::Null)); assert!(h.app.ui.dragging_control.is_none()); h.settle(SETTLE); } diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs new file mode 100644 index 00000000000..ce2ef72930c --- /dev/null +++ b/crates/ui-egui/src/tests_refusals.rs @@ -0,0 +1,422 @@ +//! A command the interface runs and the library refuses says why, where the person looks: a +//! toast. `LightcraftApp::act` is how the interface runs a command for someone's click, drop or +//! key; the reason is shown without each widget having to. `run` stays the raw entry (agents and +//! code that handles the answer itself get the error back and nothing is shown), and `quiet` is +//! for the few places where a refusal is expected and means nothing to the person. +//! +//! Scenarios: +//! - Given a command the library refuses (a smart album into the folder it shows), when the +//! interface runs it for the person, then a toast gives the reason in words, without the +//! command's id, and stays long enough to read. +//! - Given a command that isn't available right now (rating with nothing selected), then the +//! toast says why. +//! - Given a command that goes through, then nothing is said that the command didn't say itself. +//! - Given the same refusals through `run` or `quiet`, then nothing is shown; `run` gives the +//! error back in full and agents can still read it as the status. +//! - Given a menu item that is refused, when it is clicked (`menubar::act_item`), then the toast +//! says why; `run_item` stays the raw form. +//! - Given a command nobody knows, then that is said too. +//! - Given an interface command that wraps an engine command (Edit In…, All Metadata), when the +//! engine refuses, then the toast gives the engine's reason only, and `run` keeps the whole +//! error. +//! - Given a reason that starts with a file's name or a path, then its spelling is kept; only a +//! reason that starts with a word gets a capital. +//! - Given a dialog open, when a key behind it is refused, then nothing is said. +//! +//! Real widgets, driven headlessly: +//! - Given a photo whose original is missing, when Edit ▸ Auto is clicked, then the toast is the +//! reason and not "Auto settings applied"; on a photo that is there, it still says so. +//! - Given nothing selected, when a preset row is clicked, then the toast is the reason and not +//! "Preset: "; with a photo selected, it still says so. +//! - Given a slider, when it is dragged, then nothing is said; when the change is refused, on +//! every frame of the drag, then the toast says why. +//! - Given nothing selected, when 3 is pressed, or Cmd+Z with nothing to undo, then the toast is +//! the reason and not "Rated ★★★" / "Undo"; when they go through, they still say so. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +fn app() -> LightcraftApp { + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }) +} + +/// An album placed in a folder before one that is not in it: refused. (Any engine refusal will do: +/// this is the reason the tests read back, not a feature of the folder views.) +fn refused_move(app: &mut LightcraftApp) -> serde_json::Value { + let mut make = |params: serde_json::Value| app.session.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap(); + let trips = make(json!({"name": "Trips", "folder": true})); + let (rome, paris) = (make(json!({"name": "Rome"})), make(json!({"name": "Paris"}))); + json!({"id": rome, "parent": trips, "before": paris}) +} + +fn toast(app: &LightcraftApp) -> Option<&str> { + app.ui.toast.as_ref().map(|t| t.0.as_str()) +} + +#[test] +fn a_refused_command_says_why_in_a_toast() { + let mut app = app(); + let params = refused_move(&mut app); + assert_eq!(app.act("album.reorder", params), None); + let said = toast(&app).expect("a toast"); + assert!(said.contains("not inside that folder"), "{said}"); + assert!(!said.contains("album.reorder") && !said.contains("invalid parameters"), "words for a person, not the command's id: {said}"); + let (_, until, _) = app.ui.toast.clone().unwrap(); + assert!(until - app.tick_now() >= 5.0, "long enough to read a sentence"); + // agents still find the full error as the status + assert!(app.ui.status.contains("album.reorder"), "{}", app.ui.status); +} + +#[test] +fn a_command_that_isnt_available_says_why() { + let mut app = app(); + app.session.selection = Default::default(); + assert_eq!(app.act("photo.rate", json!({"rating": 3})), None); + let said = toast(&app).expect("a toast"); + assert!(said.to_lowercase().contains("no photo"), "{said}"); + assert!(!said.contains("photo.rate"), "{said}"); +} + +#[test] +fn a_command_that_goes_through_adds_nothing() { + let mut app = app(); + let made = app.act("album.create", json!({"name": "Made"})); + assert!(made.is_some_and(|v| v["id"].is_u64()), "its result comes back"); + assert_eq!(toast(&app), None); +} + +#[test] +fn run_and_quiet_show_nothing() { + let mut app = app(); + let params = refused_move(&mut app); + let e = app.run("album.reorder", params.clone()).unwrap_err(); + assert!(e.contains("album.reorder") && e.contains("not inside that folder"), "the caller gets the whole error: {e}"); + assert_eq!(toast(&app), None, "run: the caller decides what to show"); + assert_eq!(app.quiet("album.reorder", params), None); + assert_eq!(toast(&app), None, "quiet: a refusal expected here"); + assert!(app.ui.status.contains("not inside that folder"), "both leave the status for agents"); +} + +/// A click on a menu item goes the same way, whatever the item (before, only an export that +/// couldn't start said so). +#[test] +fn a_refused_menu_item_says_why() { + let mut app = app(); + let params = refused_move(&mut app); + assert_eq!(crate::menubar::act_item(&mut app, "album.reorder", params.clone()), None); + assert!(toast(&app).is_some_and(|t| t.contains("not inside that folder")), "{:?}", toast(&app)); + // `run_item` stays the raw form: the error back, nothing shown + app.ui.toast = None; + assert!(crate::menubar::run_item(&mut app, "album.reorder", params).is_err()); + assert_eq!(toast(&app), None); + // an item that goes through answers as before + assert!(crate::menubar::act_item(&mut app, "album.create", json!({"name": "From the menu"})).is_some()); + assert_eq!(toast(&app), None); +} + +/// An interface command that wraps an engine command (Edit In, All Metadata…) hands on the +/// engine's error as text ("command `photo.editExternal` is not available right now: no photo +/// selected"): the person reads the reason only, agents the whole of it as before. +#[test] +fn an_interface_command_that_wraps_an_engine_command_says_the_reason_only() { + let mut app = app(); + app.session.selection = Default::default(); + for (id, wrapped) in [("photo.editInExternal", "photo.editExternal"), ("dialog.allMetadata", "photo.allMetadata")] { + app.ui.toast = None; + let whole = app.run(id, json!({})).unwrap_err(); + assert!(whole.contains(&format!("`{wrapped}`")), "agents get the engine's error as it was: {whole}"); + assert_eq!(toast(&app), None); + assert_eq!(app.act(id, json!({})), None); + let said = toast(&app).expect("a toast").to_string(); + assert!(!said.contains(wrapped) && !said.contains("not available right now") && !said.contains("invalid parameters"), "{said}"); + assert!(whole.to_lowercase().ends_with(&said.to_lowercase()), "the reason, capitalised: {said} / {whole}"); + assert!(said.chars().next().is_some_and(char::is_uppercase), "{said}"); + } +} + +/// A reason that starts with a file's name or a path keeps its spelling; one that starts with a +/// word gets its capital. +#[test] +fn a_reason_is_capitalised_only_when_it_starts_with_a_word() { + use crate::sentence; + assert_eq!(sentence("no photos selected"), "No photos selected"); + assert_eq!(sentence("nothing copied: use Copy Metadata first"), "Nothing copied: use Copy Metadata first"); + for kept in + ["img_0012.jpg is a virtual copy", "photos/a.jpg: No such file", "ßtraße", "`x` must be a number", "“Trips” is a folder", "3 photos", ""] + { + assert_eq!(sentence(kept), kept); + } +} + +/// With a dialog open the keys behind it still run their commands, but nobody asked: a refused +/// one says nothing there, and says why once the dialog is gone. +#[test] +fn a_refused_key_behind_a_dialog_says_nothing() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "photoGrid"})); + h.app.session.selection = Default::default(); + h.app.run("dialog.export", json!({})).unwrap(); + h.step(); + assert!(h.app.ui.dialog.is_some()); + h.app.ui.toast = None; + key(&mut h, "3", false); + assert_eq!(toast(&h.app), None); + h.app.ui.dialog = None; + h.step(); + key(&mut h, "3", false); + assert!(toast(&h.app).is_some_and(|t| t.to_lowercase().contains("no photo")), "{:?}", toast(&h.app)); +} + +#[test] +fn the_reason_is_read_out_of_an_engine_error_that_is_already_text() { + use crate::{Refusal, engine_reason}; + assert_eq!(engine_reason("command `photo.editExternal` is not available right now: no photo selected"), Some("no photo selected")); + assert_eq!(engine_reason("invalid parameters for `photo.allMetadata`: no photo"), Some("no photo")); + // the engine's own formats, so a change there shows up here + let disabled = lightcraft_engine::EngineError::Disabled("a.b".into(), "nothing to undo".into()).to_string(); + assert_eq!(engine_reason(&disabled), Some("nothing to undo")); + let bad = lightcraft_engine::EngineError::BadParams { cmd: "a.b-c_d".into(), msg: "`x` must be a number: got `y`".into() }.to_string(); + assert_eq!(engine_reason(&bad), Some("`x` must be a number: got `y`"), "a reason with colons and backticks is kept whole"); + assert_eq!( + engine_reason("invalid parameters for `album.move`: command `x.y` is not available right now: busy"), + Some("command `x.y` is not available right now: busy"), + "only the outer wrapping is taken off" + ); + // text that only resembles one + for other in [ + "command line tools are missing", + "command `photo.rate` failed: disk full", + "command `photo rate` is not available right now: x", + "command `` is not available right now: x", + "invalid parameters for the export: no folder", + "invalid parameters for `x.y`", + "invalid parameters for `x.y`: ", + "invalid parameters for `a`b`: c", + "the command `x.y` is not available right now: busy", + "select a photo to use as the reference", + "", + ] { + assert_eq!(engine_reason(other), None, "{other}"); + } + // `plain`: the reason for the person, capitalised as an engine refusal's is; the error whole + let whole = "command `photo.editExternal` is not available right now: no photo selected"; + let r = Refusal::plain(whole.into()); + assert_eq!((r.why.as_str(), r.error.as_str()), ("No photo selected", whole)); + // words that are the interface's own stay as written + let r = Refusal::plain("select a photo to use as the reference".into()); + assert_eq!((r.why.as_str(), r.error.as_str()), ("select a photo to use as the reference", "select a photo to use as the reference")); +} + +// ---- real widgets, driven headlessly ---- + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn headless(session: lightcraft_engine::Session, ui: serde_json::Value) -> Headless { + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", ui, T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +/// Photos whose originals are gone (the files never existed), the first one selected. +fn missing_originals() -> lightcraft_engine::Session { + use lightcraft_catalog::{Op, Photo, PhotoId, Source}; + let mut session = lightcraft_engine::Session::new(); + for id in 1..=3 { + let source = Source::File { path: format!("/lightcraft-refusals/{id}.jpg") }; + let photo = Photo::new(PhotoId(id), source, &format!("{id}.jpg"), "JPEG", 100, 100, "2026-10-08"); + session.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + } + session.execute("library.select", &json!({"ids": [1]})).unwrap(); + session +} + +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{r}; widgets: {:?}", h.app.widgets.iter().map(|(w, _)| w.as_str()).collect::>()); + h.step(); +} + +fn key(h: &mut Headless, key: &str, cmd: bool) { + let r = h.request("ui.key", json!({"key": key, "cmd": cmd}), T); + assert_eq!(r["ok"], true, "{r}"); +} + +/// Edit ▸ Auto on a photo whose original is missing: nothing changed, and the toast used to read +/// "Auto settings applied" (the success was said whatever the command answered). +#[test] +fn the_auto_button_doesnt_claim_success_when_refused() { + let mut h = headless(missing_originals(), json!({"view": "detail", "right": "edit"})); + let before = h.app.session.develop_of(lightcraft_catalog::PhotoId(1)); + click(&mut h, "button:auto"); + let said = toast(&h.app).expect("a toast").to_string(); + assert!(!said.contains("Auto settings applied"), "{said}"); + assert!(h.app.ui.status.contains("develop.auto"), "the refusal it is about: {}", h.app.ui.status); + assert_eq!(h.app.session.develop_of(lightcraft_catalog::PhotoId(1)), before, "nothing changed"); +} + +/// And where Auto goes through, it still says so. +#[test] +fn the_auto_button_says_so_when_it_went_through() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "detail", "right": "edit"})); + click(&mut h, "button:auto"); + assert_eq!(toast(&h.app), Some("Auto settings applied")); +} + +/// A preset row clicked with nothing selected: the toast used to read "Preset: ". +#[test] +fn a_preset_row_doesnt_claim_success_when_refused() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "detail", "right": "edit", "presets": true})); + let row = |h: &Headless| h.app.widgets.iter().map(|(w, _)| w.clone()).find(|w| w.starts_with("preset:")); + let id = row(&h).expect("a preset row"); + // with a photo selected the row says what it applied + click(&mut h, &id); + assert!(toast(&h.app).is_some_and(|t| t.starts_with("Preset: ")), "{:?}", toast(&h.app)); + // with none, why not + h.app.ui.toast = None; + h.app.session.selection = Default::default(); + h.step(); + let id = row(&h).expect("a preset row with nothing selected"); + click(&mut h, &id); + let said = toast(&h.app).expect("a toast").to_string(); + assert!(!said.starts_with("Preset: "), "{said}"); + assert!(said.to_lowercase().contains("no photo"), "{said}"); +} + +/// A slider drag is begin, a change per frame, end: all three say why when refused, in the one +/// toast slot, and an ordinary drag says nothing. +#[test] +fn a_refused_slider_change_says_why_and_an_ordinary_drag_says_nothing() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "detail", "right": "edit"})); + let id = h.app.session.active().expect("an active photo"); + let before = h.app.session.develop_of(id); + let r = h.request("ui.dragWidget", json!({"id": "slider:light.exposure", "dx": 40.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert_ne!(h.app.session.develop_of(id), before, "the drag moved Exposure"); + assert_eq!(toast(&h.app), None, "an ordinary drag says nothing"); + // a change the library refuses, as a panel's slider passes it on, on every frame of a drag + let spec = lightcraft_develop::controls::find("light.exposure").unwrap(); + for _ in 0..3 { + let out = crate::widgets::SliderOut { value: Some(1.0), ..Default::default() }; + crate::panels::edit::apply_slider_out(&mut h.app, spec, out, |app, v| { + app.act("develop.set", json!({"control": "no.suchControl", "value": v})) + }); + } + let said = toast(&h.app).expect("a toast"); + assert!(said.contains("no.suchControl") && !said.contains("develop.set"), "{said}"); +} + +/// A key is a click by another name: refused, it says why instead of the success it used to +/// claim ("Rated ★★★" with nothing selected, "Undo" with nothing to undo). +#[test] +fn a_refused_key_says_why_instead_of_claiming_success() { + let mut h = headless(missing_originals(), json!({"view": "photoGrid"})); + // goes through: its own success toast, as before + key(&mut h, "3", false); + assert_eq!(h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).unwrap().rating, 3); + assert_eq!(toast(&h.app), Some("Rated ★★★")); + key(&mut h, "Z", true); + assert_eq!(h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).unwrap().rating, 0); + assert_eq!(toast(&h.app), Some("Undo")); + // nothing left to undo + h.app.ui.toast = None; + key(&mut h, "Z", true); + let said = toast(&h.app).expect("a toast").to_string(); + assert!(said != "Undo" && said.to_lowercase().contains("nothing to undo"), "{said}"); + // nothing selected + h.app.ui.toast = None; + h.app.session.selection = Default::default(); + key(&mut h, "3", false); + let said = toast(&h.app).expect("a toast").to_string(); + assert!(!said.contains("Rated") && said.to_lowercase().contains("no photo"), "{said}"); + assert!(h.app.session.catalog.photos().all(|p| p.rating == 0), "and nothing was rated"); +} + +/// A library whose disk takes nothing while `full` is set: every command that changes something fails to save. +#[derive(Clone, Default)] +struct FullDisk { + files: lightcraft_catalog::MemStore, + full: std::sync::Arc, +} + +impl lightcraft_catalog::Store for FullDisk { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if self.full.load(std::sync::atomic::Ordering::SeqCst) { + return Err(std::io::Error::other("disk full")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if self.full.load(std::sync::atomic::Ordering::SeqCst) { + return Err(std::io::Error::other("disk full")); + } + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn describe(&self) -> String { + "full disk".into() + } +} + +/// The flag-stepping keys (`, ⌘↑, ⌘↓) name the new flag only when the step went through: one that failed (here: the +/// library could not be saved) keeps its reason on screen, not "Unflagged" or "Flagged as …". +#[test] +fn a_refused_flag_step_key_says_why_instead_of_naming_the_flag() { + let disk = FullDisk::default(); + let mut session = lightcraft_engine::Session::new(); + let stores = lightcraft_engine::library::LibraryStores { + dir: "full-disk".into(), + catalog: Box::new(disk.clone()), + files: Box::new(lightcraft_catalog::MemStore::new()), + on_disk: false, + }; + session.open_library_in(stores, true).unwrap(); + let mut h = headless(session, json!({"view": "photoGrid"})); + assert!(h.app.session.active().is_some(), "a photo to flag"); + // goes through: the new flag is named + key(&mut h, "`", false); + assert_eq!(toast(&h.app), Some("Flagged as Pick")); + // (the first failed save also brings the library's own "not written to disk" notice; the keys after it are on + // their own) + disk.full.store(true, std::sync::atomic::Ordering::SeqCst); + let flag = |h: &Headless| h.app.session.active().and_then(|id| h.app.session.catalog.photo(id)).map(|p| p.flag); + for (k, cmd) in [("`", false), ("ArrowUp", true), ("ArrowDown", true)] { + h.app.ui.toast = None; + let before = flag(&h); + key(&mut h, k, cmd); + assert_ne!(flag(&h), before, "{k} reached the command (the change stays in memory)"); + let said = toast(&h.app).expect("a toast").to_string(); + assert!(said.contains("not written to disk"), "{k}: {said}"); + } +} + +#[test] +fn an_unknown_command_is_said_too() { + let mut app = app(); + assert_eq!(app.act("no.suchCommand", json!({})), None); + assert!(toast(&app).is_some_and(|t| t.contains("no.suchCommand")), "{:?}", toast(&app)); +} + +/// `[` / `]` on a spot that is gone: the command gives the refusal back (and, run for a key, the +/// toast says why once) and doesn't answer with the new size as if it had changed the spot. +#[test] +fn a_brush_size_key_on_a_vanished_spot_is_refused() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "detail", "right": "remove"})); + h.app.session.active_spot = Some(7); + let r = h.app.run("brush.larger", json!({})); + assert!(r.is_err(), "{r:?}"); + h.app.session.active_spot = None; + assert!(h.app.run("brush.larger", json!({})).is_ok(), "with no spot it only sizes the brush"); +} diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..fbc024ac4dc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -157,6 +157,14 @@ the full count took about 14 s instead of about 23 s on a heavily loaded machine; the rest is the text rules of the albums themselves. The counts are the same as before, including for albums that loop through each other. +### Refused commands say why +- When something you click, drop, drag a slider for, choose from a menu or press a key for can't be done, a message + at the bottom of the photo says why ("No photos selected", "Nothing copied: use Copy Metadata first") and stays long enough to read. Before, most such clicks did nothing and said nothing; only a few places, + such as an export that couldn't start, explained themselves. +- Nothing claims a success that didn't happen: pressing 3 with no photo selected no longer says "Rated ★★★", ⌘Z with + nothing to undo no longer says "Undo", and Auto, a preset or Paste Settings that couldn't be applied say why + instead of "applied". + ### 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 photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index 3242c95afad..452969ce1dc 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -4,7 +4,7 @@ //! parity check, ~23 minutes cold. `--quick` looks at what changed since the merge base with //! `origin/main` (or `--base REF`), committed or not, and runs: //! -//! - fmt, layers, assets: always (seconds); +//! - fmt, layers, refusals, assets: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); //! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 088103f7800..38a9e065d03 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -11,6 +11,7 @@ mod ci_report; mod ico; mod layers; mod parity; +mod refusals; mod stats; mod version; mod web; @@ -37,7 +38,7 @@ commands: build the browser app (apps/lightcraft-web) into /web-site/; --serve serves it on http://127.0.0.1: (default 8080) ci [--hardware] [--summary-md] [--quick [--base REF]] - fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, wasm + fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, refusals, assets, wasm (stops at first failure). Tests run under cargo test (cargo nextest with LIGHTCRAFT_NEXTEST=1), without examples, then doctests with cargo test --doc; after them it prints the translation gaps report (never a failure). Writes @@ -48,6 +49,7 @@ commands: break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, LIGHTCRAFT_CI_LOCK=off to skip the lock) + refusals check that the interface drops no command's refusal (`let _ = app.run(…)`): act, quiet or deal with it corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -65,6 +67,7 @@ fn main() -> ExitCode { Some("ico") => ico::run(&rest), Some("version") => version::run(&root(), &rest), Some("layers") => cmd_layers(), + Some("refusals") => refusals::run(&root()), Some("assets") => assets::run(&root()), Some("bench") => bench::run(&root(), &rest), Some("parity") => parity::run(&root(), rest.contains(&"--write")), @@ -559,6 +562,7 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { steps.push(("parity", Box::new(|| parity::run(&root, false)))); } steps.push(("layers", Box::new(cmd_layers))); + steps.push(("refusals", Box::new(|| refusals::run(&root)))); steps.push(("assets", Box::new(|| assets::run(&root)))); if wants("wasm") { match plan.as_ref().filter(|p| !p.workspace_wide) { diff --git a/xtask/src/refusals.rs b/xtask/src/refusals.rs new file mode 100644 index 00000000000..0f280304cbf --- /dev/null +++ b/xtask/src/refusals.rs @@ -0,0 +1,410 @@ +//! Refused commands are said, not dropped (`cargo xtask refusals`). +//! +//! The interface runs commands for the person at it. `LightcraftApp::run` hands the error back; +//! written as `let _ = app.run(…)` a refusal went nowhere: the click did nothing and nobody said +//! why. A widget now says which it means: `app.act(…)` (a toast gives the reason), +//! `app.quiet(…)` (a refusal is expected here; the call says why), or `run` with the `Result` +//! dealt with. This check keeps the dropped form out of the interface's code. +//! +//! Going round `run` drops it just the same: `let _ = app.session.execute(…)` is flagged too. +//! Where that is meant (not a person's action, or a refusal that means nothing to them), a +//! comment on the same line or the line directly above says so, with the reason: +//! `// refusal expected: the task may have finished by itself`. +//! +//! Test code may drop what it likes: `tests_*.rs` files aren't read, and whatever a +//! `#[cfg(test)]` applies to (a module, a `mod x;`, a fn, a field, a statement) is skipped, and +//! only that. `apps/lightcraft-web` is left out on purpose: what drops results there is its +//! benchmark (`bench.rs`), which times commands and has nobody to tell. +//! +//! This reads Rust as text, not as syntax. What is approximated: +//! - comments, strings (raw ones too) and char literals are blanked before anything is looked +//! for; a `'` is taken for a char literal when it closes within one character or starts with a +//! backslash, and for a lifetime otherwise; +//! - the item after `#[cfg(test)]` ends at the first `;` or `,` outside brackets (a `,` also +//! outside `<…>`, where `<` and `>` are counted as brackets unless the `>` belongs to `->` or +//! `=>`), or, when a `{` comes first, at the brace that closes it; so `a < b` in a test-only +//! constant can stretch the skip as far as the next `;` or `{…}`; +//! - only the exact attribute `#[cfg(test)]` (or `#![cfg(test)]` for a whole file) counts as +//! test code, not `cfg(all(test, …))` or a `cfg_attr`; +//! - a dropped result is a `let _ =` whose expression, up to its first `;`, contains one of the +//! calls below with white space taken out. `_ = …`, `.ok();` and `drop(…)` are not looked for. + +use std::path::{Path, PathBuf}; + +/// Where the interface's code is. +const DIRS: &[&str] = &["crates/ui-egui/src", "apps/lightcraft/src"]; + +/// A result dropped on the floor: what follows `let _ =` runs a command. +const RUNS: &[&str] = &["app.run(", "self.run(", "app.run_typed(", "self.run_typed(", "run_item("]; + +/// The same, going round `run` (and so round the interface's own commands and the toast). +const EXECUTES: &[&str] = &[".session.execute("]; + +/// What excuses a dropped `session.execute`, followed by the reason. +const EXPECTED: &str = "// refusal expected:"; + +const TEST_ONLY: &str = "#[cfg(test)]"; +const LET_UNDERSCORE: &str = "let _ ="; + +fn at(code: &[char], i: usize, what: &str) -> bool { + what.chars().enumerate().all(|(k, c)| code.get(i + k) == Some(&c)) +} + +fn is_ident(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn after_ident(code: &[char], i: usize) -> bool { + i.checked_sub(1).and_then(|p| code.get(p)).is_some_and(|p| is_ident(*p)) +} + +/// Where the comment, string or char literal that starts at `i` ends (`None`: none starts here). +fn end_of_blank(src: &[char], i: usize) -> Option { + let n = src.len(); + let c = *src.get(i)?; + let mut j = i; + if at(src, i, "//") { + while j < n && src.get(j) != Some(&'\n') { + j += 1; + } + } else if at(src, i, "/*") { + let mut depth = 0usize; + while j < n { + if at(src, j, "/*") { + depth += 1; + j += 2; + } else if at(src, j, "*/") { + depth = depth.saturating_sub(1); + j += 2; + if depth == 0 { + break; + } + } else { + j += 1; + } + } + } else if c == '"' { + j += 1; + while j < n { + match src.get(j) { + Some('\\') => j += 2, + Some('"') => { + j += 1; + break; + } + _ => j += 1, + } + } + } else if c == 'r' && (!after_ident(src, i) || (src.get(i.wrapping_sub(1)) == Some(&'b') && !after_ident(src, i.saturating_sub(1)))) { + // r"…", r#"…"#, br#"…"#: ends at a quote followed by as many hashes + j += 1; + while src.get(j) == Some(&'#') { + j += 1; + } + if src.get(j) != Some(&'"') { + return None; + } + let hashes = j - i - 1; + j += 1; + while j < n && !(src.get(j) == Some(&'"') && (1..=hashes).all(|k| src.get(j + k) == Some(&'#'))) { + j += 1; + } + j += 1 + hashes; + } else if c == '\'' && src.get(i + 1) == Some(&'\\') { + // '\n', '\'', '\u{1F600}' + j += 3; + while j < n && src.get(j) != Some(&'\'') && src.get(j) != Some(&'\n') { + j += 1; + } + j += 1; + } else if c == '\'' && src.get(i + 2) == Some(&'\'') { + j += 3; + } else { + // code (a lone `'` is a lifetime's) + return None; + } + Some(j.min(n)) +} + +/// The text with comments and string and char literals blanked (newlines kept, so offsets and +/// line numbers are the text's). +fn code_only(text: &str) -> Vec { + let mut code: Vec = text.chars().collect(); + let mut i = 0; + while i < code.len() { + let Some(end) = end_of_blank(&code, i) else { + i += 1; + continue; + }; + for c in code.iter_mut().take(end).skip(i) { + if *c != '\n' { + *c = ' '; + } + } + i = end.max(i + 1); + } + code +} + +/// Where what `#[cfg(test)]` applies to ends: `from` is just past the attribute. +fn end_of_item(code: &[char], from: usize) -> usize { + let (mut round, mut square, mut angle) = (0usize, 0usize, 0usize); + let mut i = from; + while let Some(&c) = code.get(i) { + let outside = round == 0 && square == 0; + match c { + '(' => round += 1, + '[' => square += 1, + // a bracket that isn't the item's closes what the item is in (a test-only argument) + ')' if round == 0 => return i, + ']' if square == 0 => return i, + ')' => round -= 1, + ']' => square -= 1, + '<' => angle += 1, + '>' if !matches!(i.checked_sub(1).and_then(|p| code.get(p)), Some('-' | '=')) => angle = angle.saturating_sub(1), + ';' if outside => return i + 1, + ',' if outside && angle == 0 => return i + 1, + // the last field of a struct: the brace is the struct's + '}' if outside => return i, + '{' if outside => { + let mut depth = 0usize; + while let Some(&c) = code.get(i) { + i += 1; + match c { + '{' => depth += 1, + '}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return i; + } + } + _ => {} + } + } + return i; + } + _ => {} + } + i += 1; + } + i +} + +/// Whether the comment that excuses a dropped `session.execute` is on this line: the marker and +/// a reason after it. +fn says_expected(line: &str, whole_line: bool) -> bool { + let reason = if whole_line { line.trim_start().strip_prefix(EXPECTED) } else { line.split_once(EXPECTED).map(|(_, reason)| reason) }; + reason.is_some_and(|reason| !reason.trim().is_empty()) +} + +/// The offending lines of one file's text: `(line number, the line)`. Test code (a `tests_*.rs` +/// file is not passed in; whatever a `#[cfg(test)]` applies to is skipped) may drop what it likes. +pub fn dropped(text: &str) -> Vec<(usize, String)> { + let code = code_only(text); + let lines: Vec<&str> = text.lines().collect(); + let mut found = Vec::new(); + let (mut i, mut line) = (0usize, 1usize); + while let Some(&c) = code.get(i) { + // a file that is all test code says so at its head, before any item's body; the same + // attribute further in (a module's own) is that module's and stops nothing here + if at(&code, i, "#![cfg(test)]") && !code.iter().take(i).any(|c| *c == '{') { + return Vec::new(); + } + if at(&code, i, TEST_ONLY) { + let end = end_of_item(&code, i + TEST_ONLY.len()).max(i + 1); + line += code.iter().take(end).skip(i).filter(|c| **c == '\n').count(); + i = end; + continue; + } + let after = i + LET_UNDERSCORE.len(); + if at(&code, i, LET_UNDERSCORE) && !after_ident(&code, i) && code.get(after) != Some(&'=') { + // what is dropped, up to the statement's first `;` (a closure's later statements are + // their own), white space taken out so a call broken over lines reads as one + let expression: String = code.iter().skip(after).take_while(|c| **c != ';').filter(|c| !c.is_whitespace()).collect(); + let here = line.checked_sub(1).and_then(|l| lines.get(l)).copied().unwrap_or_default(); + let above = line.checked_sub(2).and_then(|l| lines.get(l)).copied().unwrap_or_default(); + let runs = RUNS.iter().any(|run| expression.contains(run)); + let executes = EXECUTES.iter().any(|run| expression.contains(run)) && !says_expected(here, false) && !says_expected(above, true); + if runs || executes { + found.push((line, here.trim().to_string())); + } + } + if c == '\n' { + line += 1; + } + i += 1; + } + found +} + +fn rust_files(dir: &Path, out: &mut Vec) -> Result<(), String> { + for entry in std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? { + let path = entry.map_err(|e| format!("{}: {e}", dir.display()))?.path(); + if path.is_dir() { + rust_files(&path, out)?; + } else if path.extension().is_some_and(|e| e == "rs") && !path.file_name().is_some_and(|n| n.to_string_lossy().starts_with("tests_")) { + out.push(path); + } + } + Ok(()) +} + +pub fn run(root: &Path) -> Result<(), String> { + let mut files = Vec::new(); + for dir in DIRS { + rust_files(&root.join(dir), &mut files)?; + } + files.sort(); + let mut problems = Vec::new(); + for file in &files { + let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + for (line, code) in dropped(&text) { + problems.push(format!("{}:{line}: {code}", file.strip_prefix(root).unwrap_or(file).display())); + } + } + if problems.is_empty() { + println!("OK: no command's refusal is dropped in {} ({} files).", DIRS.join(", "), files.len()); + return Ok(()); + } + for p in &problems { + eprintln!("{p}"); + } + Err(format!( + "{} command result(s) dropped with `let _ =`: use `app.act(…)` so a refusal is said in a toast, `app.quiet(…)` (and say why) where one is expected, or deal with the `Result`; a `session.execute` that is meant to be dropped says so in a comment on its line or the line above: `{EXPECTED} `", + problems.len() + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_dropped_result_is_found() { + let text = "fn ui(app: &mut App) {\n if clicked {\n let _ = app.run(\"album.move\", json!({}));\n }\n}\n"; + assert_eq!(dropped(text), [(3, "let _ = app.run(\"album.move\", json!({}));".to_string())]); + assert_eq!(dropped(" let _ = self.run(\"x\", p);").len(), 1); + assert_eq!(dropped(" let _ = lightcraft_ui_egui::menubar::run_item(app, &cmd, params);").len(), 1); + assert_eq!(dropped(" let _ = app.run(\n \"photo.setMeta\",\n );").len(), 1, "a call over several lines"); + assert_eq!(dropped(" let _ = app.run_typed(\"mask.add\", p);").len(), 1, "keeping the kind doesn't keep the refusal"); + assert_eq!(dropped(" let _ = self.run_typed(\"mask.add\", p);").len(), 1); + } + + #[test] + fn saying_which_is_meant_passes() { + for ok in [ + " app.act(\"album.move\", json!({}));", + " app.quiet(\"library.select\", json!({}));", + " if let Err(e) = app.run(\"x\", p) { app.toast(ctx, e) }", + " let r = app.run(\"x\", p);", + " let ok = app.run(id, params).is_ok();", + " let _ = std::fs::remove_file(path);", + " // let _ = app.run(\"x\", p);", + ] { + assert!(dropped(ok).is_empty(), "{ok}"); + } + } + + #[test] + fn test_code_is_left_alone() { + let text = "fn ui() {}\n\n#[cfg(test)]\nmod tests {\n fn t() {\n let _ = app.run(\"x\", p);\n }\n}\n"; + assert!(dropped(text).is_empty()); + let before = "fn ui() {\n let _ = app.run(\"x\", p);\n}\n\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(dropped(before).len(), 1, "code before the test module still counts"); + assert!(dropped(&format!("#![cfg(test)]\n{DROP}")).is_empty(), "a file that is all test code"); + let inner = format!("{DROP}mod t {{\n #![cfg(test)]\n}}\n{DROP}"); + assert_eq!(dropped(&inner).len(), 2, "a module's own #![cfg(test)] does not excuse the file"); + } + + const DROP: &str = "fn ui(app: &mut App) {\n let _ = app.run(\"x\", p);\n}\n"; + + fn lines(text: &str) -> Vec { + dropped(text).into_iter().map(|(line, _)| line).collect() + } + + #[test] + fn a_test_module_declared_elsewhere_skips_only_itself() { + // panels/grid.rs: the attribute, a #[path], the declaration; then the whole file + let text = format!("//! Grid.\n\n#[cfg(test)]\n#[path = \"../tests_grid.rs\"]\nmod tests_grid;\n\n{DROP}"); + assert_eq!(lines(&text), [8]); + // lib.rs: a run of them + let text = format!("#[cfg(test)]\nmod tests_activity;\n#[cfg(test)]\nmod tests_scroll;\n{DROP}"); + assert_eq!(lines(&text), [6]); + // on one line + let text = format!("#[cfg(test)] mod tests_a;\n{DROP}"); + assert_eq!(lines(&text), [3]); + } + + #[test] + fn code_after_a_test_module_still_counts() { + // panels/detail.rs: production code below a test module + let text = format!("#[cfg(test)]\nmod tests {{\n fn t() {{\n let _ = app.run(\"x\", p);\n }}\n}}\n\n{DROP}"); + assert_eq!(lines(&text), [9]); + } + + #[test] + fn a_test_only_field_or_fn_skips_only_itself() { + // render.rs: a field of a struct, with generics and a comma of its own + let text = format!("struct R {{\n #[cfg(test)]\n pub seen: HashMap>,\n pub n: [u8; 3],\n}}\n{DROP}"); + assert_eq!(lines(&text), [7]); + // the last field, without a comma: the struct's brace isn't the field's + let text = format!("struct R {{\n #[cfg(test)]\n seen: u32\n}}\n{DROP}"); + assert_eq!(lines(&text), [6]); + // headless.rs: a fn inside an impl; what it drops is a test's business, what follows isn't + let text = "impl H {\n #[cfg(test)]\n pub fn poke>(&mut self, n: [u8; 2]) -> u8 {\n let _ = self.run(\"x\", p);\n 0\n }\n fn real(&mut self) {\n let _ = self.run(\"y\", p);\n }\n}\n"; + assert_eq!(lines(text), [8]); + // a statement + let text = "fn f(app: &mut App) {\n #[cfg(test)]\n let _ = app.run(\"x\", p);\n let _ = app.run(\"y\", p);\n}\n"; + assert_eq!(lines(text), [4]); + } + + #[test] + fn braces_in_strings_chars_and_comments_dont_count() { + let text = format!( + "#[cfg(test)]\nmod tests {{\n const A: &str = \"}}}} \\\" }}\";\n const B: char = '}}';\n const C: &str = r#\"}} \" }}\"#;\n // }}\n /* }} /* }} */ }} */\n fn t<'a>(x: &'a str, q: char) -> bool {{\n let _ = app.run(\"x\", p);\n q == '\\''\n }}\n}}\n{DROP}" + ); + assert_eq!(lines(&text), [14]); + // and what looks like a drop inside a string or a comment isn't one + assert!(dropped(" let s = \"let _ = app.run(x);\";\n /* let _ = app.run(y); */\n").is_empty()); + } + + #[test] + fn a_call_that_begins_on_the_next_line_is_found() { + let text = "fn f() {\n let _ =\n app.run(\"photo.setMeta\", json!({\"id\": id, \"title\": title}));\n}\n"; + assert_eq!(dropped(text), [(2, "let _ =".to_string())]); + assert_eq!(lines(" let _ = app\n .run(\"x\", p);\n"), [1], "broken before the dot"); + assert_eq!(lines(" let _ = app\n .session\n .execute(\"x\", &p);\n"), [1]); + // the statement ends at its semicolon: the next one is its own + assert!(dropped(" let _ = tx.send(1);\n app.run(\"x\", p)?;\n").is_empty()); + assert!(dropped(" let _unused = 1;\n let r = app.run(\"x\", p);\n").is_empty()); + } + + #[test] + fn going_round_run_is_found_too() { + assert_eq!(lines(" let _ = app.session.execute(\"x\", &p);"), [1]); + assert_eq!(lines(" let _ = self.session.execute(\"x\", &p);"), [1]); + assert!(dropped(" let r = app.session.execute(\"x\", &p);").is_empty()); + assert!(dropped(" app.session.execute(\"x\", &p)?;").is_empty()); + } + + #[test] + fn an_expected_refusal_says_so_with_a_reason() { + let above = " // refusal expected: the task may have finished since the row was drawn\n let _ = app.session.execute(\"activity.cancel\", &p);\n"; + assert!(dropped(above).is_empty()); + let same = " let _ = app.session.execute(\"x\", &p); // refusal expected: applied at start-up, nobody asked\n"; + assert!(dropped(same).is_empty()); + // a reason is wanted, and the comment has to be the line directly above + assert_eq!(lines(" // refusal expected:\n let _ = app.session.execute(\"x\", &p);\n"), [2]); + assert_eq!(lines(" // refusal expected\n let _ = app.session.execute(\"x\", &p);\n"), [2]); + assert_eq!(lines(" // refusal expected: yes\n\n let _ = app.session.execute(\"x\", &p);\n"), [3]); + assert_eq!(lines(" // it may be refused\n let _ = app.session.execute(\"x\", &p);\n"), [2]); + // `run` has `quiet` for that: no comment excuses it + assert_eq!(lines(" // refusal expected: because\n let _ = app.run(\"x\", p);\n"), [2]); + } + + #[test] + fn the_interface_drops_none() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + run(root).unwrap(); + } +} From 03f599d7919a20fa3924def80f46f70c42481db7 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 11:33:04 -0400 Subject: [PATCH 14/30] LR-LIB-FOLDER: a refusal keeps the toast the command made --- crates/ui-egui/src/lib.rs | 10 +++++++- crates/ui-egui/src/tests_refusals.rs | 35 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 809ed9cc346..854ae748fb1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -929,11 +929,19 @@ impl LightcraftApp { /// `let _ = app.session.execute(…)`, which goes round this), out of the interface: a widget /// says which of `act`, [`Self::quiet`] and [`Self::run`] it means. pub fn act(&mut self, id: &str, params: Value) -> Option { + let before = self.ui.toast.clone(); match self.run_told(id, params) { Ok(v) => Some(v), Err(refusal) => { let now = self.tick_now(); - self.ui.toast = Some((refusal.why, now + REFUSAL_SECONDS, None)); + // A toast the command made itself (a partial import report) says what did happen: + // keep it ahead of the reason rather than replacing it. + let said = match self.ui.toast.take() { + Some((made, ..)) if Some(&made) != before.as_ref().map(|t| &t.0) && made.contains(&refusal.why) => made, + Some((made, ..)) if Some(&made) != before.as_ref().map(|t| &t.0) => format!("{made} · {}", refusal.why), + _ => refusal.why, + }; + self.ui.toast = Some((said, now + REFUSAL_SECONDS, None)); None } } diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs index ce2ef72930c..c91643ba59a 100644 --- a/crates/ui-egui/src/tests_refusals.rs +++ b/crates/ui-egui/src/tests_refusals.rs @@ -22,6 +22,8 @@ //! - Given a reason that starts with a file's name or a path, then its spelling is kept; only a //! reason that starts with a word gets a capital. //! - Given a dialog open, when a key behind it is refused, then nothing is said. +//! - Given a command that made a toast of its own (a partial import report) and is then refused, +//! then the toast keeps what the command said and adds the reason after it. //! //! Real widgets, driven headlessly: //! - Given a photo whose original is missing, when Edit ▸ Auto is clicked, then the toast is the @@ -420,3 +422,36 @@ fn a_brush_size_key_on_a_vanished_spot_is_refused() { h.app.session.active_spot = None; assert!(h.app.run("brush.larger", json!({})).is_ok(), "with no spot it only sizes the brush"); } + +/// File ▸ Import Profiles & Presets… with a `.cube` and a local-adjustment preset, when the +/// library's preferences can't be saved: the import's own toast (what happened to the profiles) +/// and the refusal's reason are both shown, not only the reason. +#[test] +fn a_refusal_keeps_the_toast_the_command_made() { + let dir = std::env::temp_dir().join(format!("lc-refusal-toast-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let lib = dir.join("library"); + // a prefs.json that can't be read blocks saving the preferences for the session + std::fs::create_dir_all(lib.join("prefs.json")).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&lib, true).unwrap(); + let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let cube = dir.join("Warm.cube"); + let mut text = String::from("TITLE \"Warm\"\nLUT_3D_SIZE 2\n"); + for b in 0..2 { + for g in 0..2 { + for r in 0..2 { + text += &format!("{r} {g} {b}\n"); + } + } + } + std::fs::write(&cube, text).unwrap(); + let effect = dir.join("Soft.lceffect"); + std::fs::write(&effect, json!({"effects": [{"name": "Soft"}]}).to_string()).unwrap(); + let paths = [cube.to_string_lossy().to_string(), effect.to_string_lossy().to_string()]; + app.ui.toast = None; + assert_eq!(app.act("file.importPresets", json!({"paths": paths})), None, "the preset half is refused"); + let said = toast(&app).expect("a toast").to_string(); + assert!(said.contains("Import failed") && said.contains("prefs"), "what the import said is kept: {said}"); + assert!(said.contains("prefs.json couldn't be read"), "and why it was refused: {said}"); +} From d4f1109b68c8fed57a33c0b23e3a99c1dbff957d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 12:25:07 -0400 Subject: [PATCH 15/30] LR-LIB-FOLDER: refusal toasts join once, and a host dialog's command goes through act --- crates/ui-egui/src/lib.rs | 16 +++++++++++----- crates/ui-egui/src/pick.rs | 17 ++++++++++++++--- crates/ui-egui/src/tests_refusals.rs | 23 +++++++++++++++++++++-- 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 854ae748fb1..00c4ba0b980 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -254,6 +254,15 @@ impl Refusal { } } +/// What a refused command says to the person: the reason, behind the toast the command made +/// itself (a partial import report) when there is one. A toast that is the raw error, or holds +/// the reason already, is not repeated. +fn refusal_toast(made: Option, refusal: &Refusal) -> String { + let Some(made) = made else { return refusal.why.clone() }; + let made = if refusal.error.is_empty() { made } else { made.replace(&refusal.error, &refusal.why) }; + if made.to_lowercase().contains(&refusal.why.to_lowercase()) { made } else { format!("{made} · {}", refusal.why) } +} + /// 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 (ß). @@ -936,11 +945,8 @@ impl LightcraftApp { let now = self.tick_now(); // A toast the command made itself (a partial import report) says what did happen: // keep it ahead of the reason rather than replacing it. - let said = match self.ui.toast.take() { - Some((made, ..)) if Some(&made) != before.as_ref().map(|t| &t.0) && made.contains(&refusal.why) => made, - Some((made, ..)) if Some(&made) != before.as_ref().map(|t| &t.0) => format!("{made} · {}", refusal.why), - _ => refusal.why, - }; + let made = self.ui.toast.take().filter(|t| Some(t) != before.as_ref()).map(|t| t.0); + let said = refusal_toast(made, &refusal); self.ui.toast = Some((said, now + REFUSAL_SECONDS, None)); None } diff --git a/crates/ui-egui/src/pick.rs b/crates/ui-egui/src/pick.rs index 7ee3853ed80..b93c7617501 100644 --- a/crates/ui-egui/src/pick.rs +++ b/crates/ui-egui/src/pick.rs @@ -152,9 +152,7 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) { app.pending_picks = waiting; for (p, paths) in answered { let params = with_answer(&p.params, p.key, p.kind, &paths); - if let Err(e) = app.run(&p.command, params) { - app.toast_error(ctx, e); - } + app.act(&p.command, params); } } @@ -269,6 +267,19 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A command run after a host dialog is refused like any other the person started: the toast + /// says the reason, not the command's id (it used to be `run` plus the whole error). + #[test] + fn a_command_refused_after_its_dialog_says_why() { + let (mut h, asked) = app_with_picker(); + h.app.run("file.exportPresets", json!({"group": "No such group"})).unwrap(); + asked.lock().unwrap()[0].1.send(vec!["/tmp/lc-pick-refused.lcpreset".to_string()]).unwrap(); + h.step_until(SETTLE, |h| h.app.ui.toast.is_some()); + let said = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(said.contains("no presets to export") || said.contains("No presets to export"), "{said}"); + assert!(!said.contains("preset.export"), "the reason, without the command's id: {said}"); + } + #[test] fn without_a_picker_the_synchronous_dialog_answers_at_once() { let dir = std::env::temp_dir().join(format!("lc-pick-sync-{}", std::process::id())); diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs index c91643ba59a..de26622b00c 100644 --- a/crates/ui-egui/src/tests_refusals.rs +++ b/crates/ui-egui/src/tests_refusals.rs @@ -452,6 +452,25 @@ fn a_refusal_keeps_the_toast_the_command_made() { app.ui.toast = None; assert_eq!(app.act("file.importPresets", json!({"paths": paths})), None, "the preset half is refused"); let said = toast(&app).expect("a toast").to_string(); - assert!(said.contains("Import failed") && said.contains("prefs"), "what the import said is kept: {said}"); - assert!(said.contains("prefs.json couldn't be read"), "and why it was refused: {said}"); + assert!(said.starts_with("Import failed: ") && said.contains("prefs.json couldn't be read"), "what the import said is kept: {said}"); + assert_eq!(said.matches("couldn't be read").count(), 1, "the reason is not said twice: {said}"); + // the same refusal again while its toast is still up: the command's new toast is kept too + assert_eq!(app.act("file.importPresets", json!({"paths": paths})), None); + let again = toast(&app).expect("a toast"); + assert!(again.starts_with("Import failed: "), "{again}"); +} + +fn refusal(error: &str, why: &str) -> crate::Refusal { + crate::Refusal { error: error.into(), why: why.into(), kind: lightcraft_engine::ErrorKind::Other } +} + +/// The command's toast comes first, the reason after it; a toast that is the raw error, or +/// already says the reason (in either capitalisation), becomes the reason once. +#[test] +fn a_refused_commands_own_toast_and_the_reason_are_joined_once() { + let r = refusal("command `x.y` is not available right now: no photo selected", "No photo selected"); + assert_eq!(crate::refusal_toast(None, &r), "No photo selected"); + assert_eq!(crate::refusal_toast(Some("Imported 2 profiles".into()), &r), "Imported 2 profiles · No photo selected"); + assert_eq!(crate::refusal_toast(Some(r.error.clone()), &r), "No photo selected"); + assert_eq!(crate::refusal_toast(Some("Failed: no photo selected".into()), &r), "Failed: no photo selected"); } From acfb121f05c388c13de5471720e5191d75345968 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 17:59:44 -0400 Subject: [PATCH 16/30] LR-LIB-FOLDER: Auto straighten's refusal is told like every other command's --- crates/ui-egui/src/lib.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 00c4ba0b980..8bf93d52063 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1197,12 +1197,10 @@ impl LightcraftApp { /// Auto straighten (the crop panel's Auto, a double-click with the Straighten tool), saying so /// when it finds nothing to level by instead of leaving the photo as it is without a word. pub fn auto_straighten(&mut self, ctx: &egui::Context) { - match self.run("crop.autoStraighten", serde_json::json!({})) { - Ok(r) if r.get("changed").and_then(Value::as_bool) == Some(false) => { - self.toast(ctx, crate::i18n::tr("No horizon or vertical lines to level by")); - } - Ok(_) => {} - Err(e) => self.toast(ctx, e), + if let Some(r) = self.act("crop.autoStraighten", serde_json::json!({})) + && r.get("changed").and_then(Value::as_bool) == Some(false) + { + self.toast(ctx, crate::i18n::tr("No horizon or vertical lines to level by")); } } From d35af754173ca90afdf55ddfe1e3dccdc2734d40 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 14:29:05 -0400 Subject: [PATCH 17/30] LR-LIB-FOLDER: a refused command says why: the histogram and parametric curve drags, and Edit In's reason, follow it Main added drags (histogram zones, parametric curve) whose dropped results the refusals check flags, and Edit In now toasts its own error, so the test of a wrapped command expects that text with the reason in it once. --- crates/ui-egui/src/panels/edit.rs | 6 +++--- crates/ui-egui/src/panels/histogram.rs | 8 ++++---- crates/ui-egui/src/tests_refusals.rs | 18 ++++++++++++++---- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 65e211c1ac4..7eb564e0ff9 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -948,7 +948,7 @@ fn commit_interaction(app: &mut LightcraftApp, ui: &egui::Ui, dragging: bool, st if !dragging || !(stopped || released) { return false; } - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); true } @@ -989,7 +989,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: && near_curve(q) <= PARAM_GRAB { let x = from_screen_x(q); - let _ = app.run("develop.beginInteraction", json!({"label": "Parametric Curve"})); + app.act("develop.beginInteraction", json!({"label": "Parametric Curve"})); let region = model.region_at(x); let initial_amount = model.amounts.get(region).copied().unwrap_or(0.0); let start_pos = to_screen(x, model.at(x)); @@ -1016,7 +1016,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: } } if let Some((id, v)) = set { - let _ = app.run("develop.set", json!({"control": id, "value": v})); + app.act("develop.set", json!({"control": id, "value": v})); } let dropped = resp.drag_stopped(); if commit_interaction(app, ui, dragged.is_some(), dropped) { diff --git a/crates/ui-egui/src/panels/histogram.rs b/crates/ui-egui/src/panels/histogram.rs index 3f26b46bded..95a27d883fa 100644 --- a/crates/ui-egui/src/panels/histogram.rs +++ b/crates/ui-egui/src/panels/histogram.rs @@ -175,7 +175,7 @@ pub fn interact(app: &mut LightcraftApp, ui: &egui::Ui, resp: &Response, plot: R app.gesture = Some(Gesture::HistogramDrag { control, value: next }); let v = quantized(spec, next); if value_of(app, id, spec) != v { - let _ = app.run("develop.set", json!({"control": control, "value": v})); + app.act("develop.set", json!({"control": control, "value": v})); } } if resp.drag_stopped() { @@ -187,9 +187,9 @@ pub fn interact(app: &mut LightcraftApp, ui: &egui::Ui, resp: &Response, plot: R && let Some(zone) = pressed && let Some(spec) = zone.spec() { - let _ = app.run("develop.beginInteraction", json!({"label": spec.label})); + app.act("develop.beginInteraction", json!({"label": spec.label})); app.ui.dragging_control = Some(spec.id.to_string()); - let _ = app.run("develop.set", json!({"control": spec.id, "value": spec.default})); + app.act("develop.set", json!({"control": spec.id, "value": spec.default})); finish(app); } // the highlight and the readout follow the drag's locked zone, else the pointer's @@ -210,7 +210,7 @@ pub fn interact(app: &mut LightcraftApp, ui: &egui::Ui, resp: &Response, plot: R fn finish(app: &mut LightcraftApp) { app.gesture = None; app.ui.dragging_control = None; - let _ = app.run("develop.endInteraction", json!({})); + app.act("develop.endInteraction", json!({})); } /// A control's value on the photo, or its default when the photo has no settings yet. diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs index de26622b00c..5c825b15d07 100644 --- a/crates/ui-egui/src/tests_refusals.rs +++ b/crates/ui-egui/src/tests_refusals.rs @@ -122,21 +122,31 @@ fn a_refused_menu_item_says_why() { /// An interface command that wraps an engine command (Edit In, All Metadata…) hands on the /// engine's error as text ("command `photo.editExternal` is not available right now: no photo -/// selected"): the person reads the reason only, agents the whole of it as before. +/// selected"): the person reads the reason only, agents the whole of it as before. Edit In +/// says "Couldn't open the editor: …" itself, on every way in, and the reason replaces the raw text in that. #[test] fn an_interface_command_that_wraps_an_engine_command_says_the_reason_only() { let mut app = app(); app.session.selection = Default::default(); - for (id, wrapped) in [("photo.editInExternal", "photo.editExternal"), ("dialog.allMetadata", "photo.allMetadata")] { + for (id, wrapped, own_prefix) in + [("photo.editInExternal", "photo.editExternal", Some("Couldn't open the editor: ")), ("dialog.allMetadata", "photo.allMetadata", None)] + { app.ui.toast = None; let whole = app.run(id, json!({})).unwrap_err(); assert!(whole.contains(&format!("`{wrapped}`")), "agents get the engine's error as it was: {whole}"); - assert_eq!(toast(&app), None); + if own_prefix.is_none() { + assert_eq!(toast(&app), None); + } + app.ui.toast = None; assert_eq!(app.act(id, json!({})), None); let said = toast(&app).expect("a toast").to_string(); assert!(!said.contains(wrapped) && !said.contains("not available right now") && !said.contains("invalid parameters"), "{said}"); - assert!(whole.to_lowercase().ends_with(&said.to_lowercase()), "the reason, capitalised: {said} / {whole}"); + let reason = crate::engine_reason(&whole).expect("the engine's text"); + assert!(said.to_lowercase().ends_with(&reason.to_lowercase()), "the reason, capitalised: {said} / {whole}"); assert!(said.chars().next().is_some_and(char::is_uppercase), "{said}"); + if let Some(prefix) = own_prefix { + assert_eq!(said, format!("{prefix}{}", crate::sentence(reason)), "the command's own words with the reason in them, once"); + } } } From b3a5ec8e5bb6f812d5162afed5bca4e2ad7d52a2 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 22:33:45 -0400 Subject: [PATCH 18/30] LR-LIB-FOLDER: a key that follows one that opened a dialog in the same frame is not a command behind it --- crates/ui-egui/src/shortcuts.rs | 76 ++++++++++++++++++++-------- crates/ui-egui/src/tests_refusals.rs | 4 +- 2 files changed, 56 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 637bbc532d1..bddf63149c4 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -470,13 +470,17 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { let cull = |app: &mut LightcraftApp, id: &str, mut params: serde_json::Value, advance: bool| -> bool { compare::target_active(app, &mut params); let was = app.session.active(); - let ok = key_act(app, id, params).is_some(); + let ok = app.act(id, params).is_some(); if ok && (advance || app.ui.auto_advance) { compare::advance(app, was); } ok }; for (id, params) in aliased { + // a key of this frame opened a dialog (Shift+E): the keys after it are the dialog's, not commands behind it + if app.ui.dialog.is_some() { + break; + } // a slideshow: Space pauses / resumes if id == "view.zoomToggle" && app.ui.slideshow.is_some() { if let Ok(v) = app.run("slideshow.togglePause", json!({})) { @@ -495,14 +499,19 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { cull(app, id, params, advance); } else { // a command that can't run (an export with no folder…) says why instead of doing nothing - key_act(app, id, params); + app.act(id, params); } } let rotate_fires = fire.iter().any(|f| f == "crop.rotateAspect"); for f in fire { + // a key of this frame opened a dialog: the keys handled after it (aliases first, then the + // rest, whatever order they were pressed in) are the dialog's, not commands behind it + if app.ui.dialog.is_some() { + break; + } // a slideshow: ←/→ step (a cut) if app.ui.slideshow.is_some() && matches!(f.as_str(), "library.next" | "library.previous") { - key_act(app, if f == "library.next" { "slideshow.next" } else { "slideshow.previous" }, json!({})); + app.act(if f == "library.next" { "slideshow.next" } else { "slideshow.previous" }, json!({})); continue; } if let Some(rest) = f.strip_prefix("rate:") { @@ -524,13 +533,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { cull(app, "photo.flag", json!({"flag": "pick"}), true); } else if f == "view.softProof" && matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) { // S in a grid: expand / collapse the stack (Lightroom's Library binding) - key_act(app, "stack.toggle", json!({})); + app.act("stack.toggle", json!({})); } else if f == "grid:first" || f == "grid:last" { // Home / End in a grid: make the first / last photo of the view the active, selected one let vis = app.session.visible_cloned(); let edge = if f == "grid:first" { vis.first() } else { vis.last() }; if let Some(id) = edge { - key_act(app, "library.select", json!({"ids": [id.0], "active": id.0})); + app.act("library.select", json!({"ids": [id.0], "active": id.0})); } } else if let Some(step) = f.strip_prefix("grid:extend:") { // Shift+← / Shift+→ in a grid: the neighbour of the active photo joins the selection and @@ -546,7 +555,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { .and_then(|pos| usize::try_from(pos).ok()) .and_then(|pos| vis.get(pos)); if let Some(id) = neighbour { - key_act(app, "library.select", json!({"ids": [id.0], "mode": "add"})); + app.act("library.select", json!({"ids": [id.0], "mode": "add"})); } } else if compare::culling(app) && (f == "library.next" || f == "library.previous") { let d = if f == "library.next" { 1 } else { -1 }; @@ -573,7 +582,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } else { // in the full-screen preview (no panels) I cycles the info overlay instead if f == "panel.info" && app.ui.fullscreen { - key_act(app, "view.infoOverlay", json!({})); + app.act("view.infoOverlay", json!({})); continue; } // Delete acts on what's being edited: the active mask in the Masking panel; never the @@ -583,13 +592,13 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { match app.ui.right { R::Masking => { if app.session.active_mask.is_some() { - key_act(app, "mask.delete", json!({})); + app.act("mask.delete", json!({})); } continue; } R::Remove => { if app.session.active_spot.is_some() { - key_act(app, "spot.delete", json!({})); + app.act("spot.delete", json!({})); } continue; } @@ -623,7 +632,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } // B: the brush while editing; in the grids, add to the target album (Quick Collection) if f == "tool.brush" && matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) { - if let Some(r) = key_act(app, "album.toggleTarget", json!({})) { + if let Some(r) = app.act("album.toggleTarget", json!({})) { let n = app.session.selected().len(); let what = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); let name = r["name"].as_str().unwrap_or("Quick Collection").to_string(); @@ -642,7 +651,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { // swap once: twice would put the crop straight back (issue #1866). if f == "photo.reject" && app.ui.right == crate::state::RightPanel::Crop { if !rotate_fires { - key_act(app, "crop.rotateAspect", json!({})); + app.act("crop.rotateAspect", json!({})); } continue; } @@ -658,12 +667,12 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } // / refreshes the selected spot's source in the Remove tool (the filmstrip elsewhere) if f == "view.filmstrip" && app.ui.right == crate::state::RightPanel::Remove && app.session.active_spot.is_some() { - key_act(app, "spot.refreshSource", json!({})); + app.act("spot.refreshSource", json!({})); continue; } // Shift+O cycles the mask overlay colour while masking (the crop overlay elsewhere) if f == "view.cropOverlay" && app.ui.right == crate::state::RightPanel::Masking { - key_act(app, "view.maskOverlayColor", json!({})); + app.act("view.maskOverlayColor", json!({})); continue; } // while cropping: O cycles the guides, Shift+O their orientation @@ -674,7 +683,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { _ => None, }; if let Some((cmd, p)) = crop_key { - key_act(app, cmd, p); + app.act(cmd, p); continue; } } @@ -699,7 +708,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { } // a command that can't run (an export with no folder, nothing to undo…) says why // instead of doing nothing; its success is said only when it went through - if key_act(app, &f, json!({})).is_some() { + if app.act(&f, json!({})).is_some() { match f.as_str() { "photo.pick" => app.toast(ctx, crate::i18n::tr("Flagged as Pick")), "photo.reject" => app.toast(ctx, crate::i18n::tr("Flagged as Reject")), @@ -717,13 +726,6 @@ pub(crate) fn library_grid(app: &LightcraftApp) -> bool { matches!(app.ui.view, crate::state::ViewMode::PhotoGrid | crate::state::ViewMode::SquareGrid) } -/// Runs a key's command for the person ([`LightcraftApp::act`]: a refusal says why). With a -/// dialog open the keys still reach here, but the person is typing at the dialog, not asking for -/// the command behind it: a refusal there says nothing. -fn key_act(app: &mut LightcraftApp, id: &str, params: serde_json::Value) -> Option { - if app.ui.dialog.is_some() { app.quiet(id, params) } else { app.act(id, params) } -} - #[cfg(test)] mod tests { @@ -826,6 +828,36 @@ mod tests { assert!(h.app.session.selection.ids.is_empty()); } + /// Given two keys in one frame, the first of which (Shift+E) opens the Export dialog, when the + /// frame is handled, then the second (a rating) is not a command behind the dialog: no rating, + /// no toast. + #[test] + fn a_key_after_one_that_opens_a_dialog_in_the_same_frame_does_nothing() { + use lightcraft_catalog::PhotoId; + let mut h = library(); + h.app.ui.toast = None; + let press = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + h.events.push(press(egui::Key::E, egui::Modifiers::SHIFT)); + h.events.push(press(egui::Key::Num3, egui::Modifiers::NONE)); + h.step(); + assert!(h.app.ui.dialog.is_some(), "Shift+E opens Export"); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().rating, 0, "the rating key was the dialog's"); + assert!(h.app.ui.toast.is_none()); + } + + /// The same for a second alias (Shift+Z flags a Pick) after Shift+E in one frame. + #[test] + fn an_alias_after_one_that_opens_a_dialog_in_the_same_frame_does_nothing() { + use lightcraft_catalog::{Flag, PhotoId}; + let mut h = library(); + let press = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + h.events.push(press(egui::Key::E, egui::Modifiers::SHIFT)); + h.events.push(press(egui::Key::Z, egui::Modifiers::SHIFT)); + h.step(); + assert!(h.app.ui.dialog.is_some(), "Shift+E opens Export"); + assert_eq!(h.app.session.catalog.photo(PhotoId(1)).unwrap().flag, Flag::None, "the flag key was the dialog's"); + } + #[test] fn library_rating_labels_flags_and_undo() { use lightcraft_catalog::{ColorLabel, Flag, PhotoId}; diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs index 5c825b15d07..26dee85fe7c 100644 --- a/crates/ui-egui/src/tests_refusals.rs +++ b/crates/ui-egui/src/tests_refusals.rs @@ -164,8 +164,8 @@ fn a_reason_is_capitalised_only_when_it_starts_with_a_word() { } } -/// With a dialog open the keys behind it still run their commands, but nobody asked: a refused -/// one says nothing there, and says why once the dialog is gone. +/// With a dialog open the keys are the dialog's and reach no command behind it, so nothing is said +/// about a refusal there; once the dialog is gone, the same key says why. #[test] fn a_refused_key_behind_a_dialog_says_nothing() { let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "photoGrid"})); From 92b251badb58cb8ca0bd574b6e774a0479fb5ad0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 09:39:28 -0400 Subject: [PATCH 19/30] LR-LIB-FOLDER: the point color and red eye drags go through act, so a refused pick says why --- crates/ui-egui/src/panels/detail.rs | 6 +++--- crates/ui-egui/src/tests_refusals.rs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 67a8aa42532..a5701f8f834 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -1674,7 +1674,7 @@ fn general_interaction( && let Some(q) = resp.interact_pointer_pos() { let n = map.norm(q); - if let Ok(r) = app.run("pointColor.pick", json!({"x": n.x, "y": n.y})) { + if let Some(r) = app.act("pointColor.pick", json!({"x": n.x, "y": n.y})) { app.ui.point_color = r["index"].as_u64().unwrap_or(0) as usize; } app.ui.tool.clear(); @@ -2891,8 +2891,8 @@ fn eye_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response let half = ((sb - sa) / 2.0).abs() / per_long; if half.x > 0.002 && half.y > 0.002 { let c = map.norm(sa.lerp(sb, 0.5)); - let r = app.run("redeye.add", json!({"center": [c.x, c.y], "rx": half.x, "ry": half.y, "pet": app.ui.eye_pet})); - if let Ok(v) = r { + let r = app.act("redeye.add", json!({"center": [c.x, c.y], "rx": half.x, "ry": half.y, "pet": app.ui.eye_pet})); + if let Some(v) = r { app.ui.eye = v["index"].as_u64().unwrap_or(0) as usize; } } diff --git a/crates/ui-egui/src/tests_refusals.rs b/crates/ui-egui/src/tests_refusals.rs index 26dee85fe7c..4570c5a3c60 100644 --- a/crates/ui-egui/src/tests_refusals.rs +++ b/crates/ui-egui/src/tests_refusals.rs @@ -34,6 +34,8 @@ //! every frame of the drag, then the toast says why. //! - Given nothing selected, when 3 is pressed, or Cmd+Z with nothing to undo, then the toast is //! the reason and not "Rated ★★★" / "Undo"; when they go through, they still say so. +//! - Given eight Point Color samples, when the picker is clicked on the photo, then the toast is the +//! reason (at most 8) and nothing is added. use std::time::Duration; @@ -484,3 +486,20 @@ fn a_refused_commands_own_toast_and_the_reason_are_joined_once() { assert_eq!(crate::refusal_toast(Some(r.error.clone()), &r), "No photo selected"); assert_eq!(crate::refusal_toast(Some("Failed: no photo selected".into()), &r), "Failed: no photo selected"); } + +/// The Point Color picker, clicked on the photo after eight samples exist: the library refuses a +/// ninth, and the click used to drop that without a word. +#[test] +fn a_refused_point_color_pick_says_why() { + let mut h = headless(lightcraft_engine::Session::with_demo(), json!({"view": "detail", "right": "edit", "tool": "pointColor"})); + for i in 0..8 { + let r = h.app.session.execute("pointColor.pick", &json!({"x": 0.3 + 0.05 * f64::from(i), "y": 0.5})); + assert!(r.is_ok(), "sample {i}: {r:?}"); + } + let r = h.request("ui.click", json!({"x": 500.0, "y": 450.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let said = toast(&h.app).expect("a toast"); + assert!(said.to_lowercase().contains("at most 8"), "{said}"); + assert!(!said.contains("pointColor.pick"), "{said}"); +} From b326b21ad976adf351a76072ffd18531976acf77 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 10:38:17 -0400 Subject: [PATCH 20/30] LR-LIB-FOLDER: the refusals check moves to its own change, after this one --- CLAUDE.md | 8 +- crates/ui-egui/src/lib.rs | 6 +- xtask/src/ci_quick.rs | 2 +- xtask/src/main.rs | 6 +- xtask/src/refusals.rs | 410 -------------------------------------- 5 files changed, 9 insertions(+), 423 deletions(-) delete mode 100644 xtask/src/refusals.rs diff --git a/CLAUDE.md b/CLAUDE.md index a5eee09fedc..cb629fe73c8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,9 +66,9 @@ of it. Full standard: `../craftrules/standards/never-crash.md` with `app.act(id, params)`: a refusal shows its reason in a toast. It returns `None` then: say a success of your own only on `Some`, or it writes over the reason. `app.quiet(…)` is for the few calls where a refusal is expected (say why at the call); `app.run(…)` hands the `Result` back for code that deals with it (and for agents). Never - `let _ = app.run(…)`, nor `let _ = app.session.execute(…)` round it: `cargo xtask refusals` (in `ci`) fails on - both. A dropped `session.execute` that is meant (not a person's action, or already inside `run`) says so on its line - or the one above: `// refusal expected: `. Better still, don't offer what would be refused. + `let _ = app.run(…)`, nor `let _ = app.session.execute(…)` round it. A dropped `session.execute` that is meant + (not a person's action, or already inside `run`) says so on its line or the one above: + `// refusal expected: `. Better still, don't offer what would be refused. - **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind, label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses @@ -76,7 +76,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md` - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' - tests, layers, refusals, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR + tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bf93d52063..ae03f981473 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -934,9 +934,9 @@ impl LightcraftApp { /// 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. `cargo xtask refusals` keeps the dropped form, `let _ = app.run(…)` (and - /// `let _ = app.session.execute(…)`, which goes round this), out of the interface: a widget - /// says which of `act`, [`Self::quiet`] and [`Self::run`] it means. + /// the reason. A widget says which of `act`, [`Self::quiet`] and [`Self::run`] it means; it does + /// not drop `run`'s result (`let _ = app.run(…)`), nor `let _ = app.session.execute(…)`, which + /// goes round this, unless a comment says why: `// refusal expected: `. pub fn act(&mut self, id: &str, params: Value) -> Option { let before = self.ui.toast.clone(); match self.run_told(id, params) { diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index 452969ce1dc..3242c95afad 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -4,7 +4,7 @@ //! parity check, ~23 minutes cold. `--quick` looks at what changed since the merge base with //! `origin/main` (or `--base REF`), committed or not, and runs: //! -//! - fmt, layers, refusals, assets: always (seconds); +//! - fmt, layers, assets: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); //! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 38a9e065d03..088103f7800 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -11,7 +11,6 @@ mod ci_report; mod ico; mod layers; mod parity; -mod refusals; mod stats; mod version; mod web; @@ -38,7 +37,7 @@ commands: build the browser app (apps/lightcraft-web) into /web-site/; --serve serves it on http://127.0.0.1: (default 8080) ci [--hardware] [--summary-md] [--quick [--base REF]] - fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, refusals, assets, wasm + fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, wasm (stops at first failure). Tests run under cargo test (cargo nextest with LIGHTCRAFT_NEXTEST=1), without examples, then doctests with cargo test --doc; after them it prints the translation gaps report (never a failure). Writes @@ -49,7 +48,6 @@ commands: break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, LIGHTCRAFT_CI_LOCK=off to skip the lock) - refusals check that the interface drops no command's refusal (`let _ = app.run(…)`): act, quiet or deal with it corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -67,7 +65,6 @@ fn main() -> ExitCode { Some("ico") => ico::run(&rest), Some("version") => version::run(&root(), &rest), Some("layers") => cmd_layers(), - Some("refusals") => refusals::run(&root()), Some("assets") => assets::run(&root()), Some("bench") => bench::run(&root(), &rest), Some("parity") => parity::run(&root(), rest.contains(&"--write")), @@ -562,7 +559,6 @@ fn cmd_ci(args: &[&str]) -> Result<(), String> { steps.push(("parity", Box::new(|| parity::run(&root, false)))); } steps.push(("layers", Box::new(cmd_layers))); - steps.push(("refusals", Box::new(|| refusals::run(&root)))); steps.push(("assets", Box::new(|| assets::run(&root)))); if wants("wasm") { match plan.as_ref().filter(|p| !p.workspace_wide) { diff --git a/xtask/src/refusals.rs b/xtask/src/refusals.rs deleted file mode 100644 index 0f280304cbf..00000000000 --- a/xtask/src/refusals.rs +++ /dev/null @@ -1,410 +0,0 @@ -//! Refused commands are said, not dropped (`cargo xtask refusals`). -//! -//! The interface runs commands for the person at it. `LightcraftApp::run` hands the error back; -//! written as `let _ = app.run(…)` a refusal went nowhere: the click did nothing and nobody said -//! why. A widget now says which it means: `app.act(…)` (a toast gives the reason), -//! `app.quiet(…)` (a refusal is expected here; the call says why), or `run` with the `Result` -//! dealt with. This check keeps the dropped form out of the interface's code. -//! -//! Going round `run` drops it just the same: `let _ = app.session.execute(…)` is flagged too. -//! Where that is meant (not a person's action, or a refusal that means nothing to them), a -//! comment on the same line or the line directly above says so, with the reason: -//! `// refusal expected: the task may have finished by itself`. -//! -//! Test code may drop what it likes: `tests_*.rs` files aren't read, and whatever a -//! `#[cfg(test)]` applies to (a module, a `mod x;`, a fn, a field, a statement) is skipped, and -//! only that. `apps/lightcraft-web` is left out on purpose: what drops results there is its -//! benchmark (`bench.rs`), which times commands and has nobody to tell. -//! -//! This reads Rust as text, not as syntax. What is approximated: -//! - comments, strings (raw ones too) and char literals are blanked before anything is looked -//! for; a `'` is taken for a char literal when it closes within one character or starts with a -//! backslash, and for a lifetime otherwise; -//! - the item after `#[cfg(test)]` ends at the first `;` or `,` outside brackets (a `,` also -//! outside `<…>`, where `<` and `>` are counted as brackets unless the `>` belongs to `->` or -//! `=>`), or, when a `{` comes first, at the brace that closes it; so `a < b` in a test-only -//! constant can stretch the skip as far as the next `;` or `{…}`; -//! - only the exact attribute `#[cfg(test)]` (or `#![cfg(test)]` for a whole file) counts as -//! test code, not `cfg(all(test, …))` or a `cfg_attr`; -//! - a dropped result is a `let _ =` whose expression, up to its first `;`, contains one of the -//! calls below with white space taken out. `_ = …`, `.ok();` and `drop(…)` are not looked for. - -use std::path::{Path, PathBuf}; - -/// Where the interface's code is. -const DIRS: &[&str] = &["crates/ui-egui/src", "apps/lightcraft/src"]; - -/// A result dropped on the floor: what follows `let _ =` runs a command. -const RUNS: &[&str] = &["app.run(", "self.run(", "app.run_typed(", "self.run_typed(", "run_item("]; - -/// The same, going round `run` (and so round the interface's own commands and the toast). -const EXECUTES: &[&str] = &[".session.execute("]; - -/// What excuses a dropped `session.execute`, followed by the reason. -const EXPECTED: &str = "// refusal expected:"; - -const TEST_ONLY: &str = "#[cfg(test)]"; -const LET_UNDERSCORE: &str = "let _ ="; - -fn at(code: &[char], i: usize, what: &str) -> bool { - what.chars().enumerate().all(|(k, c)| code.get(i + k) == Some(&c)) -} - -fn is_ident(c: char) -> bool { - c.is_alphanumeric() || c == '_' -} - -fn after_ident(code: &[char], i: usize) -> bool { - i.checked_sub(1).and_then(|p| code.get(p)).is_some_and(|p| is_ident(*p)) -} - -/// Where the comment, string or char literal that starts at `i` ends (`None`: none starts here). -fn end_of_blank(src: &[char], i: usize) -> Option { - let n = src.len(); - let c = *src.get(i)?; - let mut j = i; - if at(src, i, "//") { - while j < n && src.get(j) != Some(&'\n') { - j += 1; - } - } else if at(src, i, "/*") { - let mut depth = 0usize; - while j < n { - if at(src, j, "/*") { - depth += 1; - j += 2; - } else if at(src, j, "*/") { - depth = depth.saturating_sub(1); - j += 2; - if depth == 0 { - break; - } - } else { - j += 1; - } - } - } else if c == '"' { - j += 1; - while j < n { - match src.get(j) { - Some('\\') => j += 2, - Some('"') => { - j += 1; - break; - } - _ => j += 1, - } - } - } else if c == 'r' && (!after_ident(src, i) || (src.get(i.wrapping_sub(1)) == Some(&'b') && !after_ident(src, i.saturating_sub(1)))) { - // r"…", r#"…"#, br#"…"#: ends at a quote followed by as many hashes - j += 1; - while src.get(j) == Some(&'#') { - j += 1; - } - if src.get(j) != Some(&'"') { - return None; - } - let hashes = j - i - 1; - j += 1; - while j < n && !(src.get(j) == Some(&'"') && (1..=hashes).all(|k| src.get(j + k) == Some(&'#'))) { - j += 1; - } - j += 1 + hashes; - } else if c == '\'' && src.get(i + 1) == Some(&'\\') { - // '\n', '\'', '\u{1F600}' - j += 3; - while j < n && src.get(j) != Some(&'\'') && src.get(j) != Some(&'\n') { - j += 1; - } - j += 1; - } else if c == '\'' && src.get(i + 2) == Some(&'\'') { - j += 3; - } else { - // code (a lone `'` is a lifetime's) - return None; - } - Some(j.min(n)) -} - -/// The text with comments and string and char literals blanked (newlines kept, so offsets and -/// line numbers are the text's). -fn code_only(text: &str) -> Vec { - let mut code: Vec = text.chars().collect(); - let mut i = 0; - while i < code.len() { - let Some(end) = end_of_blank(&code, i) else { - i += 1; - continue; - }; - for c in code.iter_mut().take(end).skip(i) { - if *c != '\n' { - *c = ' '; - } - } - i = end.max(i + 1); - } - code -} - -/// Where what `#[cfg(test)]` applies to ends: `from` is just past the attribute. -fn end_of_item(code: &[char], from: usize) -> usize { - let (mut round, mut square, mut angle) = (0usize, 0usize, 0usize); - let mut i = from; - while let Some(&c) = code.get(i) { - let outside = round == 0 && square == 0; - match c { - '(' => round += 1, - '[' => square += 1, - // a bracket that isn't the item's closes what the item is in (a test-only argument) - ')' if round == 0 => return i, - ']' if square == 0 => return i, - ')' => round -= 1, - ']' => square -= 1, - '<' => angle += 1, - '>' if !matches!(i.checked_sub(1).and_then(|p| code.get(p)), Some('-' | '=')) => angle = angle.saturating_sub(1), - ';' if outside => return i + 1, - ',' if outside && angle == 0 => return i + 1, - // the last field of a struct: the brace is the struct's - '}' if outside => return i, - '{' if outside => { - let mut depth = 0usize; - while let Some(&c) = code.get(i) { - i += 1; - match c { - '{' => depth += 1, - '}' => { - depth = depth.saturating_sub(1); - if depth == 0 { - return i; - } - } - _ => {} - } - } - return i; - } - _ => {} - } - i += 1; - } - i -} - -/// Whether the comment that excuses a dropped `session.execute` is on this line: the marker and -/// a reason after it. -fn says_expected(line: &str, whole_line: bool) -> bool { - let reason = if whole_line { line.trim_start().strip_prefix(EXPECTED) } else { line.split_once(EXPECTED).map(|(_, reason)| reason) }; - reason.is_some_and(|reason| !reason.trim().is_empty()) -} - -/// The offending lines of one file's text: `(line number, the line)`. Test code (a `tests_*.rs` -/// file is not passed in; whatever a `#[cfg(test)]` applies to is skipped) may drop what it likes. -pub fn dropped(text: &str) -> Vec<(usize, String)> { - let code = code_only(text); - let lines: Vec<&str> = text.lines().collect(); - let mut found = Vec::new(); - let (mut i, mut line) = (0usize, 1usize); - while let Some(&c) = code.get(i) { - // a file that is all test code says so at its head, before any item's body; the same - // attribute further in (a module's own) is that module's and stops nothing here - if at(&code, i, "#![cfg(test)]") && !code.iter().take(i).any(|c| *c == '{') { - return Vec::new(); - } - if at(&code, i, TEST_ONLY) { - let end = end_of_item(&code, i + TEST_ONLY.len()).max(i + 1); - line += code.iter().take(end).skip(i).filter(|c| **c == '\n').count(); - i = end; - continue; - } - let after = i + LET_UNDERSCORE.len(); - if at(&code, i, LET_UNDERSCORE) && !after_ident(&code, i) && code.get(after) != Some(&'=') { - // what is dropped, up to the statement's first `;` (a closure's later statements are - // their own), white space taken out so a call broken over lines reads as one - let expression: String = code.iter().skip(after).take_while(|c| **c != ';').filter(|c| !c.is_whitespace()).collect(); - let here = line.checked_sub(1).and_then(|l| lines.get(l)).copied().unwrap_or_default(); - let above = line.checked_sub(2).and_then(|l| lines.get(l)).copied().unwrap_or_default(); - let runs = RUNS.iter().any(|run| expression.contains(run)); - let executes = EXECUTES.iter().any(|run| expression.contains(run)) && !says_expected(here, false) && !says_expected(above, true); - if runs || executes { - found.push((line, here.trim().to_string())); - } - } - if c == '\n' { - line += 1; - } - i += 1; - } - found -} - -fn rust_files(dir: &Path, out: &mut Vec) -> Result<(), String> { - for entry in std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? { - let path = entry.map_err(|e| format!("{}: {e}", dir.display()))?.path(); - if path.is_dir() { - rust_files(&path, out)?; - } else if path.extension().is_some_and(|e| e == "rs") && !path.file_name().is_some_and(|n| n.to_string_lossy().starts_with("tests_")) { - out.push(path); - } - } - Ok(()) -} - -pub fn run(root: &Path) -> Result<(), String> { - let mut files = Vec::new(); - for dir in DIRS { - rust_files(&root.join(dir), &mut files)?; - } - files.sort(); - let mut problems = Vec::new(); - for file in &files { - let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; - for (line, code) in dropped(&text) { - problems.push(format!("{}:{line}: {code}", file.strip_prefix(root).unwrap_or(file).display())); - } - } - if problems.is_empty() { - println!("OK: no command's refusal is dropped in {} ({} files).", DIRS.join(", "), files.len()); - return Ok(()); - } - for p in &problems { - eprintln!("{p}"); - } - Err(format!( - "{} command result(s) dropped with `let _ =`: use `app.act(…)` so a refusal is said in a toast, `app.quiet(…)` (and say why) where one is expected, or deal with the `Result`; a `session.execute` that is meant to be dropped says so in a comment on its line or the line above: `{EXPECTED} `", - problems.len() - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_dropped_result_is_found() { - let text = "fn ui(app: &mut App) {\n if clicked {\n let _ = app.run(\"album.move\", json!({}));\n }\n}\n"; - assert_eq!(dropped(text), [(3, "let _ = app.run(\"album.move\", json!({}));".to_string())]); - assert_eq!(dropped(" let _ = self.run(\"x\", p);").len(), 1); - assert_eq!(dropped(" let _ = lightcraft_ui_egui::menubar::run_item(app, &cmd, params);").len(), 1); - assert_eq!(dropped(" let _ = app.run(\n \"photo.setMeta\",\n );").len(), 1, "a call over several lines"); - assert_eq!(dropped(" let _ = app.run_typed(\"mask.add\", p);").len(), 1, "keeping the kind doesn't keep the refusal"); - assert_eq!(dropped(" let _ = self.run_typed(\"mask.add\", p);").len(), 1); - } - - #[test] - fn saying_which_is_meant_passes() { - for ok in [ - " app.act(\"album.move\", json!({}));", - " app.quiet(\"library.select\", json!({}));", - " if let Err(e) = app.run(\"x\", p) { app.toast(ctx, e) }", - " let r = app.run(\"x\", p);", - " let ok = app.run(id, params).is_ok();", - " let _ = std::fs::remove_file(path);", - " // let _ = app.run(\"x\", p);", - ] { - assert!(dropped(ok).is_empty(), "{ok}"); - } - } - - #[test] - fn test_code_is_left_alone() { - let text = "fn ui() {}\n\n#[cfg(test)]\nmod tests {\n fn t() {\n let _ = app.run(\"x\", p);\n }\n}\n"; - assert!(dropped(text).is_empty()); - let before = "fn ui() {\n let _ = app.run(\"x\", p);\n}\n\n#[cfg(test)]\nmod tests {}\n"; - assert_eq!(dropped(before).len(), 1, "code before the test module still counts"); - assert!(dropped(&format!("#![cfg(test)]\n{DROP}")).is_empty(), "a file that is all test code"); - let inner = format!("{DROP}mod t {{\n #![cfg(test)]\n}}\n{DROP}"); - assert_eq!(dropped(&inner).len(), 2, "a module's own #![cfg(test)] does not excuse the file"); - } - - const DROP: &str = "fn ui(app: &mut App) {\n let _ = app.run(\"x\", p);\n}\n"; - - fn lines(text: &str) -> Vec { - dropped(text).into_iter().map(|(line, _)| line).collect() - } - - #[test] - fn a_test_module_declared_elsewhere_skips_only_itself() { - // panels/grid.rs: the attribute, a #[path], the declaration; then the whole file - let text = format!("//! Grid.\n\n#[cfg(test)]\n#[path = \"../tests_grid.rs\"]\nmod tests_grid;\n\n{DROP}"); - assert_eq!(lines(&text), [8]); - // lib.rs: a run of them - let text = format!("#[cfg(test)]\nmod tests_activity;\n#[cfg(test)]\nmod tests_scroll;\n{DROP}"); - assert_eq!(lines(&text), [6]); - // on one line - let text = format!("#[cfg(test)] mod tests_a;\n{DROP}"); - assert_eq!(lines(&text), [3]); - } - - #[test] - fn code_after_a_test_module_still_counts() { - // panels/detail.rs: production code below a test module - let text = format!("#[cfg(test)]\nmod tests {{\n fn t() {{\n let _ = app.run(\"x\", p);\n }}\n}}\n\n{DROP}"); - assert_eq!(lines(&text), [9]); - } - - #[test] - fn a_test_only_field_or_fn_skips_only_itself() { - // render.rs: a field of a struct, with generics and a comma of its own - let text = format!("struct R {{\n #[cfg(test)]\n pub seen: HashMap>,\n pub n: [u8; 3],\n}}\n{DROP}"); - assert_eq!(lines(&text), [7]); - // the last field, without a comma: the struct's brace isn't the field's - let text = format!("struct R {{\n #[cfg(test)]\n seen: u32\n}}\n{DROP}"); - assert_eq!(lines(&text), [6]); - // headless.rs: a fn inside an impl; what it drops is a test's business, what follows isn't - let text = "impl H {\n #[cfg(test)]\n pub fn poke>(&mut self, n: [u8; 2]) -> u8 {\n let _ = self.run(\"x\", p);\n 0\n }\n fn real(&mut self) {\n let _ = self.run(\"y\", p);\n }\n}\n"; - assert_eq!(lines(text), [8]); - // a statement - let text = "fn f(app: &mut App) {\n #[cfg(test)]\n let _ = app.run(\"x\", p);\n let _ = app.run(\"y\", p);\n}\n"; - assert_eq!(lines(text), [4]); - } - - #[test] - fn braces_in_strings_chars_and_comments_dont_count() { - let text = format!( - "#[cfg(test)]\nmod tests {{\n const A: &str = \"}}}} \\\" }}\";\n const B: char = '}}';\n const C: &str = r#\"}} \" }}\"#;\n // }}\n /* }} /* }} */ }} */\n fn t<'a>(x: &'a str, q: char) -> bool {{\n let _ = app.run(\"x\", p);\n q == '\\''\n }}\n}}\n{DROP}" - ); - assert_eq!(lines(&text), [14]); - // and what looks like a drop inside a string or a comment isn't one - assert!(dropped(" let s = \"let _ = app.run(x);\";\n /* let _ = app.run(y); */\n").is_empty()); - } - - #[test] - fn a_call_that_begins_on_the_next_line_is_found() { - let text = "fn f() {\n let _ =\n app.run(\"photo.setMeta\", json!({\"id\": id, \"title\": title}));\n}\n"; - assert_eq!(dropped(text), [(2, "let _ =".to_string())]); - assert_eq!(lines(" let _ = app\n .run(\"x\", p);\n"), [1], "broken before the dot"); - assert_eq!(lines(" let _ = app\n .session\n .execute(\"x\", &p);\n"), [1]); - // the statement ends at its semicolon: the next one is its own - assert!(dropped(" let _ = tx.send(1);\n app.run(\"x\", p)?;\n").is_empty()); - assert!(dropped(" let _unused = 1;\n let r = app.run(\"x\", p);\n").is_empty()); - } - - #[test] - fn going_round_run_is_found_too() { - assert_eq!(lines(" let _ = app.session.execute(\"x\", &p);"), [1]); - assert_eq!(lines(" let _ = self.session.execute(\"x\", &p);"), [1]); - assert!(dropped(" let r = app.session.execute(\"x\", &p);").is_empty()); - assert!(dropped(" app.session.execute(\"x\", &p)?;").is_empty()); - } - - #[test] - fn an_expected_refusal_says_so_with_a_reason() { - let above = " // refusal expected: the task may have finished since the row was drawn\n let _ = app.session.execute(\"activity.cancel\", &p);\n"; - assert!(dropped(above).is_empty()); - let same = " let _ = app.session.execute(\"x\", &p); // refusal expected: applied at start-up, nobody asked\n"; - assert!(dropped(same).is_empty()); - // a reason is wanted, and the comment has to be the line directly above - assert_eq!(lines(" // refusal expected:\n let _ = app.session.execute(\"x\", &p);\n"), [2]); - assert_eq!(lines(" // refusal expected\n let _ = app.session.execute(\"x\", &p);\n"), [2]); - assert_eq!(lines(" // refusal expected: yes\n\n let _ = app.session.execute(\"x\", &p);\n"), [3]); - assert_eq!(lines(" // it may be refused\n let _ = app.session.execute(\"x\", &p);\n"), [2]); - // `run` has `quiet` for that: no comment excuses it - assert_eq!(lines(" // refusal expected: because\n let _ = app.run(\"x\", p);\n"), [2]); - } - - #[test] - fn the_interface_drops_none() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); - run(root).unwrap(); - } -} From b7ae06f50afb6bf9f70e8ced1e2dd7981733d4a8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 20:28:19 -0400 Subject: [PATCH 21/30] 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/lib.rs | 11 ++++++++--- crates/ui-egui/src/tests_activity.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 48aee3c5887..003371b8dec 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1024,6 +1024,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) { @@ -1979,9 +1986,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 0a091a06627..91701d66033 100644 --- a/crates/ui-egui/src/tests_activity.rs +++ b/crates/ui-egui/src/tests_activity.rs @@ -590,3 +590,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 5f914d6888c319c95f67048b039c49e57e90d358 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 15 Oct 2026 16:46:34 -0400 Subject: [PATCH 22/30] 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/drop_overlay.rs | 2 +- crates/ui-egui/src/headless.rs | 1 + crates/ui-egui/src/import.rs | 140 +++++++++----- crates/ui-egui/src/lib.rs | 61 +++++- crates/ui-egui/src/lightroom_destination.rs | 2 +- crates/ui-egui/src/lightroom_import.rs | 2 +- crates/ui-egui/src/sync.rs | 198 ++++++++++++++++++-- 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 | 7 +- docs/whats-new.md | 12 ++ 50 files changed, 659 insertions(+), 159 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 80b52ecc731..9c712fbafa8 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 57459d00cf8..3c1f82ffeda 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/drop_overlay.rs b/crates/ui-egui/src/drop_overlay.rs index 8be75ee8881..5e0455c13fc 100644 --- a/crates/ui-egui/src/drop_overlay.rs +++ b/crates/ui-egui/src/drop_overlay.rs @@ -50,7 +50,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 c47bd27737e..37b8c2039bb 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/import.rs b/crates/ui-egui/src/import.rs index 74dcc6c4067..38a2a25b846 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/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, }; @@ -434,7 +435,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. - 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`). @@ -447,10 +448,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. +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 @@ -680,11 +702,11 @@ 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 { @@ -694,15 +716,14 @@ impl ScanTask { } } -/// 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(); @@ -710,9 +731,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) { @@ -726,6 +751,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); @@ -748,50 +775,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/lib.rs b/crates/ui-egui/src/lib.rs index 003371b8dec..c540aebbde4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -544,6 +544,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. @@ -680,6 +682,7 @@ impl LightcraftApp { sync: None, sync_owns_changes: false, sync_run: None, + sync_queued: None, lightroom: None, lightroom_last: None, lightroom_result: None, @@ -949,6 +952,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()?; @@ -1027,7 +1073,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) { - self.session.start_waiting(); + self.start_waiting(ctx); self.preview_build_status(ctx); } @@ -1975,6 +2021,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 @@ -2000,12 +2047,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>| { @@ -2015,7 +2058,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() { @@ -2204,7 +2247,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/lightroom_destination.rs b/crates/ui-egui/src/lightroom_destination.rs index 5fd781cfdd8..7009b0b76a6 100644 --- a/crates/ui-egui/src/lightroom_destination.rs +++ b/crates/ui-egui/src/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/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 3ebf9ce3e16..f41c39418c1 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 { @@ -350,8 +515,8 @@ pub fn poll_run(app: &mut LightcraftApp, ctx: &egui::Context) { run.commit = Some(commit); return; } - let (name, stopped, crashed, mut not_saved) = - (run.name.clone(), run.stopping, run.crashed.load(Ordering::Relaxed), std::mem::take(&mut run.not_saved)); + let (name, stopped, crashed, mut not_saved, left_alone) = + (run.name.clone(), run.stopping, run.crashed.load(Ordering::Relaxed), std::mem::take(&mut run.not_saved), run.left_alone); app.sync_run = None; let mut report = None; if let Err(e) = app.session.execute_fn("folder.synchronize", |s| { @@ -382,6 +547,9 @@ pub fn poll_run(app: &mut LightcraftApp, ctx: &egui::Context) { if let Some(e) = not_saved.first() { 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)); + } 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 8b6bf3dfdcd..227bd872fe3 100644 --- a/crates/ui-egui/src/tests_drop_import.rs +++ b/crates/ui-egui/src/tests_drop_import.rs @@ -237,18 +237,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); @@ -266,9 +285,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 014a149da25..ae5802f209f 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 2086f5ac8c3..4d17d7b00b9 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 080680b9ffe..9aa73148cc5 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-24 · **Change:** minor (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-24 · **Change:** minor (LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder wait for each other instead of refusing; earlier: 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 @@ -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/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/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) or while an import's scan runs or its review waits is refused with a toast, and the card says so (a drop while an import 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/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/panels/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 | @@ -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/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/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) | @@ -958,3 +958,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 6fbcfeff462f907963fc4d1edb61b8351bfb0677 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 18:26:28 -0400 Subject: [PATCH 23/30] =?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 91701d66033..9a1135fbb4b 100644 --- a/crates/ui-egui/src/tests_activity.rs +++ b/crates/ui-egui/src/tests_activity.rs @@ -533,10 +533,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; @@ -550,7 +550,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 227bd872fe3..01070d37639 100644 --- a/crates/ui-egui/src/tests_drop_import.rs +++ b/crates/ui-egui/src/tests_drop_import.rs @@ -264,6 +264,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 ae5802f209f..e13fd6aa18a 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 9aa73148cc5..9d53e3ab5de 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-24 · **Change:** minor (LR-BEHAV-BG-TASKS, LR-IMP-DRAGDROP: imports and Synchronize Folder wait for each other instead of refusing; earlier: 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-24 · **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: 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/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/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) | @@ -958,4 +958,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 d0d7368db113c603b2012cea6e2458cb83b43cf1 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 24 Oct 2026 18:47:35 -0400 Subject: [PATCH 24/30] 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/ui-egui/locales/cs-formats.json | 6 +- crates/ui-egui/locales/de-formats.json | 2 +- crates/ui-egui/locales/es-formats.json | 2 +- crates/ui-egui/locales/fi-formats.json | 2 +- crates/ui-egui/locales/fr-formats.json | 6 +- crates/ui-egui/locales/id-formats.json | 2 +- crates/ui-egui/locales/it-formats.json | 6 +- crates/ui-egui/locales/ja-formats.json | 2 +- crates/ui-egui/locales/ka-formats.json | 2 +- crates/ui-egui/locales/pl-formats.json | 6 +- crates/ui-egui/locales/pt-br-formats.json | 2 +- crates/ui-egui/locales/ru-formats.json | 2 +- crates/ui-egui/locales/sv-formats.json | 2 +- crates/ui-egui/locales/uk-formats.json | 2 +- crates/ui-egui/locales/vi-formats.json | 2 +- crates/ui-egui/locales/zh-hans-formats.json | 2 +- crates/ui-egui/locales/zh-hant-formats.json | 2 +- crates/ui-egui/src/import.rs | 53 +++++++++++---- crates/ui-egui/src/lib.rs | 18 +----- crates/ui-egui/src/panels/activity.rs | 7 +- crates/ui-egui/src/sync.rs | 66 ++++++++++++------- crates/ui-egui/src/tests_activity.rs | 4 ++ crates/ui-egui/src/tests_drop_import.rs | 66 +++++++++++++++++++ crates/ui-egui/src/tests_sync.rs | 71 ++++++++++++++++++++- docs/background-tasks.md | 14 ++-- docs/parity-checklist.md | 2 +- docs/whats-new.md | 11 ++-- 27 files changed, 272 insertions(+), 90 deletions(-) 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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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-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/src/import.rs b/crates/ui-egui/src/import.rs index 38a2a25b846..90d8cadc1e0 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -452,8 +452,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 @@ -468,13 +468,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. -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). +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 @@ -722,10 +751,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()); @@ -778,7 +803,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)); @@ -793,7 +818,7 @@ pub fn start_paths(app: &mut LightcraftApp, paths: Vec) -> Result= 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/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index 581bf56ea3a..9492c7a6e84 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -118,6 +118,11 @@ pub(crate) fn cancel(app: &mut LightcraftApp, id: u64) { let _ = app.session.execute("activity.cancel", &json!({"id": id})); } +/// 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() } +} + /// 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 f41c39418c1..4bea1f3aa8e 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,26 @@ 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); 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 +438,14 @@ 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()); + // 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 +476,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, } @@ -548,7 +568,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 9a1135fbb4b..24b29d0c7d2 100644 --- a/crates/ui-egui/src/tests_activity.rs +++ b/crates/ui-egui/src/tests_activity.rs @@ -554,6 +554,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 01070d37639..146edf75539 100644 --- a/crates/ui-egui/src/tests_drop_import.rs +++ b/crates/ui-egui/src/tests_drop_import.rs @@ -246,6 +246,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..1030b6f7c1d 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 diff --git a/docs/background-tasks.md b/docs/background-tasks.md index e13fd6aa18a..a7bbe9073b8 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 9d53e3ab5de..ac41cd20f2a 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -958,4 +958,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 e3c8e6a34bfece75604ad895050ae42192dec5e5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 17:39:04 -0400 Subject: [PATCH 25/30] Sidebars: several albums, keywords or folders are deleted, moved or labelled as one 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. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/keywords.rs | 60 +++++ crates/engine/src/cmd/keywords.rs | 48 +++- crates/engine/src/cmd/library.rs | 259 ++++++++++++++------ crates/engine/src/lib.rs | 2 + crates/engine/src/tests_batch_sidebar.rs | 293 +++++++++++++++++++++++ 5 files changed, 592 insertions(+), 70 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 6b0c97f5a34..8c240ee97f3 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -409,6 +409,66 @@ impl Catalog { Ok(Op::Batch { ops }) } + /// [`Self::delete_keyword_ops`] for several keywords at once: one batch, so one undo step. + 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())); + } + let goes = |k: &str| gone.iter().any(|g| is_under(k, g)); + 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())); + } + let moved = |k: &str| moves.iter().find(|(f, _)| is_under(k, f)).map(|(f, t)| 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 d11063194b3..8193164bce1 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -81,6 +81,30 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo { } } +/// 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`"))?; @@ -432,15 +456,26 @@ 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| { - 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")), }; + if p.get("keywords").is_some_and(|k| !k.is_null()) { + 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")?; // 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()) { @@ -556,9 +591,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.rs b/crates/engine/src/cmd/library.rs index a2107be6e71..8451ee1734a 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -376,36 +376,84 @@ 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 `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"))?; +/// 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"))); + 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}")))?); + 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"))?; +/// 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"))); + 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 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()); @@ -460,7 +508,7 @@ pub fn specs() -> Vec { "album" => { let mut albums = match p.get("ids") { None | Some(Value::Null) => vec![album_param(p, "id", C)?], - Some(v) => source_album_ids(v)?, + Some(v) => album_ids(v, C)?, }; 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()); @@ -477,7 +525,7 @@ pub fn specs() -> Vec { "libraryFolder" => { 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)?, + Some(v) => folder_paths(v, C)?, }; source_folders_check(s, &folders)?; let Some(own) = folders.pop() else { return Err(bad(C, "`paths` names no folder")) }; @@ -558,47 +606,64 @@ 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; } - s.filter.library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); + s.filter.library_folders.retain(|c| !within(c)); // 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 + s.also_library_folders.retain(|c| !within(c)); + // a filter put aside by Enable Filters must not bring a removed folder back 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)) { + if f.library_folder.as_deref().is_some_and(within) { f.library_folder = None; } - f.library_folders.retain(|c| !lightcraft_catalog::query::folder_within(c, path)); + f.library_folders.retain(|c| !within(c)); } 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)) { + if s.library_folder.as_deref().is_some_and(within) { s.library_folder = s.also_library_folders.pop(); if s.source == LibrarySource::LibraryFolder && s.library_folder.is_none() { s.source = LibrarySource::All; @@ -614,26 +679,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 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 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 label.is_none() && s.catalog.folder_record(path).is_none() { - return Ok(json!({"path": path, "label": label})); + 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)); + } } - 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})) + 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 })? + } + } + 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, _| { @@ -1363,11 +1448,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 { @@ -1377,34 +1473,63 @@ 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 })?; // 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 = s.also_albums.pop().map_or(LibrarySource::All, LibrarySource::Album); } + 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/lib.rs b/crates/engine/src/lib.rs index 83c1cd76544..9d8cd465b69 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1518,6 +1518,8 @@ mod tests_album_remove; #[cfg(test)] mod tests_albums_local; #[cfg(test)] +mod tests_batch_sidebar; +#[cfg(test)] mod tests_color; #[cfg(test)] mod tests_constrain_crop; diff --git a/crates/engine/src/tests_batch_sidebar.rs b/crates/engine/src/tests_batch_sidebar.rs new file mode 100644 index 00000000000..41d92f018d9 --- /dev/null +++ b/crates/engine/src/tests_batch_sidebar.rs @@ -0,0 +1,293 @@ +//! 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. +//! - 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 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 several_keywords_filtered_by_follow_a_move() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps"]); + tag(&mut s, ids[1], &["beach", "places"]); + s.execute("library.filter", &json!({"keywords": ["alps", "beach"]})).unwrap(); + s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + assert_eq!(s.filter.keywords, vec!["places|alps".to_string(), "places|beach".to_string()]); + assert_eq!(s.visible().len(), 2); +} + +#[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()); +} From db8191fc54bcc88fd914721c01921003ce48662f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 11:54:35 -0400 Subject: [PATCH 26/30] Sidebars: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates The row of choices, its menus (Delete, Cut, Copy, Paste, Move, Folder Color Label), the hints and questions for several rows in every language, the reason-only refusal on the control channel, and the docs, as one change so that every commit builds on its own: the new strings are in the catalogs of all 17 languages from the commit that adds them. --- crates/catalog/src/rules.rs | 16 + crates/engine/src/cmd/keywords.rs | 2 +- crates/engine/src/cmd/library.rs | 153 +++- crates/engine/src/tests_batch_sidebar.rs | 133 ++++ crates/ui-egui/locales/cs-formats.json | 21 +- crates/ui-egui/locales/cs.json | 28 +- crates/ui-egui/locales/de-formats.json | 21 +- crates/ui-egui/locales/de.json | 32 +- crates/ui-egui/locales/es-formats.json | 21 +- crates/ui-egui/locales/es.json | 29 + crates/ui-egui/locales/fi-formats.json | 21 +- crates/ui-egui/locales/fi.json | 28 +- crates/ui-egui/locales/fr-formats.json | 21 +- crates/ui-egui/locales/fr.json | 29 + crates/ui-egui/locales/id-formats.json | 21 +- crates/ui-egui/locales/id.json | 28 +- crates/ui-egui/locales/it-formats.json | 21 +- crates/ui-egui/locales/it.json | 28 +- crates/ui-egui/locales/ja-formats.json | 21 +- crates/ui-egui/locales/ja.json | 29 + crates/ui-egui/locales/ka-formats.json | 21 +- crates/ui-egui/locales/ka.json | 29 +- crates/ui-egui/locales/pl-formats.json | 21 +- crates/ui-egui/locales/pl.json | 30 +- crates/ui-egui/locales/pt-br-formats.json | 21 +- crates/ui-egui/locales/pt-br.json | 29 + crates/ui-egui/locales/ru-formats.json | 21 +- crates/ui-egui/locales/ru.json | 29 + crates/ui-egui/locales/sv-formats.json | 21 +- crates/ui-egui/locales/sv.json | 28 +- crates/ui-egui/locales/uk-formats.json | 21 +- crates/ui-egui/locales/uk.json | 29 + crates/ui-egui/locales/vi-formats.json | 21 +- crates/ui-egui/locales/vi.json | 29 +- crates/ui-egui/locales/zh-hans-formats.json | 21 +- crates/ui-egui/locales/zh-hans.json | 29 + crates/ui-egui/locales/zh-hant-formats.json | 21 +- crates/ui-egui/locales/zh-hant.json | 29 + crates/ui-egui/src/i18n.rs | 7 + crates/ui-egui/src/lib.rs | 32 +- crates/ui-egui/src/multi_select.rs | 219 ++++++ crates/ui-egui/src/panels/dialogs.rs | 11 +- crates/ui-egui/src/panels/grid.rs | 2 + crates/ui-egui/src/panels/keyword_list.rs | 74 +- crates/ui-egui/src/panels/left.rs | 107 ++- crates/ui-egui/src/panels/mod.rs | 1 + crates/ui-egui/src/panels/side_select.rs | 745 ++++++++++++++++++++ crates/ui-egui/src/shortcuts.rs | 4 + crates/ui-egui/src/state.rs | 7 + crates/ui-egui/src/tests_dialog_primary.rs | 4 + crates/ui-egui/src/tests_multi_select.rs | 743 +++++++++++++++++++ docs/parity-checklist.md | 5 +- docs/whats-new.md | 22 + 53 files changed, 3045 insertions(+), 91 deletions(-) create mode 100644 crates/ui-egui/src/multi_select.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/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 2976a2659bf..126df7e1431 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -1111,6 +1111,22 @@ impl RuleSet { out } + /// Give every Album rule, groups included, the album `to` makes of the one it names (a copy + /// of a set of albums tests the copies). A rule whose album isn't a valid id is left alone. + pub fn remap_albums(&mut self, to: &impl Fn(crate::AlbumId) -> crate::AlbumId) { + for rule in &mut self.rules { + match rule { + Rule::Group { group } => group.remap_albums(to), + Rule::Field { field, value, .. } if field == "album" => { + if let Some(id) = album_rule_id(value) { + *value = Value::from(to(id).0); + } + } + Rule::Field { .. } => {} + } + } + } + fn check_into(&self, cat: &Catalog, owner: Option, path: &mut Vec, out: &mut Vec) { for (i, rule) in self.rules.iter().enumerate() { path.push(i); diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 8193164bce1..a141c493904 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -82,7 +82,7 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo { } /// How many keywords one call may name (far more than a person chooses in a list). -const MAX_KEYWORDS: usize = 10_000; +const MAX_KEYWORDS: usize = 1000; /// The keywords a command names in `keywords`: a list of them, each once (whatever its case), /// none empty. diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 8451ee1734a..976b5463c1e 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -414,6 +414,10 @@ fn move_albums(s: &mut Session, p: &Value) -> Result { false }; let moving: Vec = ids.iter().copied().filter(|id| !inside_another(*id)).collect(); + // each inside another of them (a ring of folders, in a damaged library): nothing to move + if moving.is_empty() { + return Err(bad(C, "cycle in album folders")); + } for id in &moving { let name = s.catalog.album(*id).map(|a| a.name.clone()).unwrap_or_default(); if above.contains(id) { @@ -426,6 +430,116 @@ fn move_albums(s: &mut Session, p: &Value) -> Result { Ok(json!({"moved": moving.len()})) } +/// `album.duplicate`: everything is checked first, then the copies are made as one undo step. +fn duplicate_albums(s: &mut Session, p: &Value) -> Result { + const C: &str = "album.duplicate"; + /// How many albums one call may make (folders are copied with everything inside them). + const MAX_COPIES: usize = 10_000; + /// Where a copy goes: a folder that is there, or the copy of a folder being copied. + enum Place { + Final(Option), + CopyOf(AlbumId), + } + let ids = match p.get("ids") { + Some(v) if !v.is_null() => 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, format!("no such album {}", gone.0))); + } + // where the copies go: `parent` when given (null: the top level), else beside each original + let into = if p.get("parent").is_some() { Some(opt_album_param(p, "parent", C)?) } else { None }; + if let Some(Some(folder)) = into + && !s.catalog.album(folder).is_some_and(|a| a.folder) + { + return Err(bad(C, format!("album {} is not a folder of albums", folder.0))); + } + // of a folder and what is inside it, the folder is copied + 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 tops: Vec = ids.iter().copied().filter(|id| !inside_another(*id)).collect(); + if tops.is_empty() { + return Err(bad(C, "cycle in album folders")); + } + let mut children = std::collections::BTreeMap::>::new(); + for album in s.catalog.albums() { + if let Some(parent) = album.parent { + children.entry(parent).or_default().push(album.id); + } + } + // parent first: the original, where its copy goes, and whether the copy is named as one + let mut plan: Vec<(AlbumId, Place, bool)> = Vec::new(); + for top in &tops { + let Some(original) = s.catalog.album(*top) else { continue }; + let target = into.unwrap_or(original.parent); + // beside the original it says what it is; elsewhere it keeps its name + plan.push((*top, Place::Final(target), target == original.parent)); + let mut pending = vec![*top]; + 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")); + } + for child in children.get(&next).into_iter().flatten() { + plan.push((*child, Place::CopyOf(next), false)); + pending.push(*child); + } + if plan.len() > MAX_COPIES { + return Err(bad(C, format!("more than {MAX_COPIES} albums to copy"))); + } + } + } + let mut copy_of = std::collections::BTreeMap::::new(); + for (original, _, _) in &plan { + copy_of.insert(*original, s.catalog.alloc_album_id()); + } + let mut ops = Vec::with_capacity(plan.len()); + let mut made = Vec::new(); + for (original, place, renamed) in plan { + let (Some(from), Some(id)) = (s.catalog.album(original).cloned(), copy_of.get(&original).copied()) else { continue }; + let (parent, top) = match place { + Place::Final(parent) => { + made.push(id.0); + (parent, true) + } + Place::CopyOf(folder) => (copy_of.get(&folder).copied(), false), + }; + let name = if renamed { format!("{} copy", from.name) } else { from.name.clone() }; + // a place by hand: kept inside a copied folder; the copy itself is among other + // neighbours, where its original's place means nothing + let order = if top { None } else { from.order }; + // a smart album limited to an album that is copied with it goes by that album's copy + let smart = from.smart.clone().map(|mut rules| { + rules.album = rules.album.map(|a| copy_of.get(&a).copied().unwrap_or(a)); + for a in &mut rules.albums { + *a = copy_of.get(a).copied().unwrap_or(*a); + } + if let Some(set) = rules.rule_set.as_mut() { + set.remap_albums(&|a| copy_of.get(&a).copied().unwrap_or(a)); + } + rules + }); + // (there is one Quick Collection) + ops.push(Op::AddAlbum { album: Album { id, name, parent, quick: false, order, smart, ..from } }); + } + let label = if made.len() == 1 { "Duplicate Album".to_string() } else { format!("Duplicate {} Albums", made.len()) }; + s.commit(&label, Op::Batch { ops })?; + Ok(json!({"ids": made})) +} + /// 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; @@ -619,8 +733,7 @@ pub fn specs() -> Vec { return Err(bad(C, "`paths` names no folder")); } // 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(); + // (one pass over the library for the checks, one for the photos, however many folders) for path in &paths { let path = path.as_str(); if path.trim().is_empty() || lightcraft_catalog::query::folder_key(path).is_empty() { @@ -632,16 +745,17 @@ pub fn specs() -> Vec { 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() { + } + 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 covers_other_disks(s, path, &found) && !bool_or(p, "disk", false) { + if found.other_disks && !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))); } + let f = Filter { library_folders: paths.clone(), ..Default::default() }; + let ids = s.catalog.query(&f, &Sort::default()); 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)?; @@ -696,15 +810,15 @@ pub fn specs() -> Vec { return Err(bad(C, "`paths` names no folder")); } let mut ops = Vec::new(); + if paths.iter().any(|path| 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 found = if label.is_some() { s.catalog.folders_scan(&paths) } else { Vec::new() }; + if let Some((path, _)) = paths.iter().zip(&found).find(|(_, f)| !f.holds) { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } 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)); } @@ -1513,6 +1627,15 @@ pub fn specs() -> Vec { if several { Ok(json!({"deleted": ids.len()})) } else { ok() } } ), + cmd!( + "album.duplicate", + "Duplicate Album", + [], + None, + "{id | ids: [albumId], parent?: folderId|null} → {ids: the copies} — a copy of each album (the same photos; a smart album: the same rules; a folder: copies of everything inside it), beside the original as “name copy”, or in `parent` (null: the top level) under its own name; one undo step. Of a folder and an album inside it the folder is copied; one that can't be copied there refuses the whole call", + always, + duplicate_albums + ), cmd!( "album.move", "Move Album", diff --git a/crates/engine/src/tests_batch_sidebar.rs b/crates/engine/src/tests_batch_sidebar.rs index 41d92f018d9..0a515c55faa 100644 --- a/crates/engine/src/tests_batch_sidebar.rs +++ b/crates/engine/src/tests_batch_sidebar.rs @@ -291,3 +291,136 @@ fn several_folders_get_a_colour_label_as_one_step() { 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()); } + +// ---- album.duplicate (Copy, then Paste, in the Albums list) +// +// - Given an album with photos, when it is duplicated, then a second album "… copy" holds the +// same photos beside it, the original is untouched, and one undo takes the copy away. +// - A smart album's copy has the same rules; a folder's copy holds copies of what is inside it. +// - Given several albums, when they are duplicated into a folder, then every copy is inside it, +// as one undo step; of a folder and an album inside it, the folder is copied (once). +// - A copy into something that is not a folder, or of an album that is not there, is refused +// and nothing is copied. + +fn photos_of(s: &Session, id: u64) -> Vec { + s.catalog.album(AlbumId(id)).unwrap().photos.iter().map(|p| p.0).collect() +} + +fn fill(s: &mut Session, album: u64, ids: &[u64]) { + s.selection.ids = ids.iter().map(|i| PhotoId(*i)).collect(); + s.execute("album.addPhotos", &json!({"id": album, "ids": ids})).unwrap(); + s.selection.ids.clear(); +} + +fn names(s: &Session) -> Vec { + let mut n: Vec = s.catalog.albums().map(|a| a.name.clone()).collect(); + n.sort(); + n +} + +#[test] +fn an_album_is_duplicated_with_its_photos() { + let mut s = Session::new(); + let ids = photos(&mut s, 3); + let a = album(&mut s, json!({"name": "Alps"})); + fill(&mut s, a, &[ids[2], ids[0]]); + let steps = s.undo.len(); + let r = s.execute("album.duplicate", &json!({"id": a})).unwrap(); + let copy = r["ids"][0].as_u64().unwrap(); + assert_ne!(copy, a); + assert_eq!(s.catalog.album(AlbumId(copy)).unwrap().name, "Alps copy"); + assert_eq!(photos_of(&s, copy), vec![ids[2], ids[0]], "the same photos, in the album's order"); + assert_eq!(photos_of(&s, a), vec![ids[2], ids[0]], "the original is untouched"); + assert_eq!(s.undo.len(), steps + 1); + // the copy is its own album from then on + fill(&mut s, copy, &[ids[1]]); + assert_eq!(photos_of(&s, a).len(), 2); + undo(&mut s); + undo(&mut s); + assert!(!has_album(&s, copy) && has_album(&s, a)); +} + +#[test] +fn a_smart_album_and_a_folder_are_duplicated_with_what_makes_them() { + let mut s = Session::new(); + photos(&mut s, 2); + let smart = s.execute("album.createSmart", &json!({"name": "Rated", "rules": {"rating": 3}})).unwrap()["id"].as_u64().unwrap(); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inner = album(&mut s, json!({"name": "Inner", "folder": true, "parent": folder})); + album(&mut s, json!({"name": "Deep", "parent": inner})); + let steps = s.undo.len(); + // the folder, an album inside it (it goes with the folder) and the smart album + let r = s.execute("album.duplicate", &json!({"ids": [inner, folder, smart]})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 2, "the folder and the smart album: {r}"); + assert_eq!(s.undo.len(), steps + 1, "one step"); + assert_eq!(names(&s), vec!["Deep", "Deep", "Inner", "Inner", "Rated", "Rated copy", "Trips", "Trips copy"]); + let copy = s.catalog.albums().find(|a| a.name == "Rated copy").unwrap(); + assert_eq!(copy.smart.as_ref().map(|r| r.rating), Some(3)); + let trips = s.catalog.albums().find(|a| a.name == "Trips copy").unwrap().id; + let inner_copy = s.catalog.albums().find(|a| a.name == "Inner" && a.parent == Some(trips)).expect("inside the copied folder").id; + assert!(s.catalog.albums().any(|a| a.name == "Deep" && a.parent == Some(inner_copy))); + undo(&mut s); + assert_eq!(names(&s), vec!["Deep", "Inner", "Rated", "Trips"]); +} + +#[test] +fn a_copied_smart_album_tests_the_copy_of_an_album_inside_a_group() { + let mut s = Session::new(); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let sibling = album(&mut s, json!({"name": "Sibling", "parent": folder})); + let rules = + json!({"ruleSet": {"match": "all", "rules": [{"group": {"match": "any", "rules": [{"field": "album", "op": "is", "value": sibling}]}}]}}); + let smart = s.execute("album.createSmart", &json!({"name": "Nested", "rules": rules, "parent": folder})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("album.duplicate", &json!({"ids": [folder]})).unwrap(); + let copy = r["ids"][0].as_u64().unwrap(); + let sibling_copy = s.catalog.albums().find(|a| a.name == "Sibling" && a.parent == Some(AlbumId(copy))).unwrap().id; + let smart_copy = s.catalog.albums().find(|a| a.name == "Nested" && a.parent == Some(AlbumId(copy))).unwrap(); + let tested = smart_copy.smart.as_ref().and_then(|r| r.rule_set.as_ref()).unwrap().albums_tested(); + assert_eq!(tested, vec![sibling_copy], "it tests the copied sibling, not the original"); + let original = s.catalog.album(AlbumId(smart)).unwrap().smart.as_ref().and_then(|r| r.rule_set.as_ref()).unwrap().albums_tested(); + assert_eq!(original, vec![AlbumId(sibling)]); +} + +#[test] +fn several_albums_are_duplicated_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(); + let r = s.execute("album.duplicate", &json!({"ids": [a, b], "parent": folder})).unwrap(); + let copies: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(copies.len(), 2); + assert!(copies.iter().all(|c| parent_of(&s, *c) == Some(folder))); + let folder_id = AlbumId(folder); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None), "the originals stay where they are"); + assert_eq!(s.undo.len(), steps + 1); + // somewhere else, a copy keeps its name; beside the original it says it is a copy + assert!(s.catalog.albums().any(|x| x.name == "A" && x.parent == Some(folder_id))); + let again = s.execute("album.duplicate", &json!({"ids": [a], "parent": null})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(s.catalog.album(AlbumId(again)).unwrap().name, "A copy"); + // refused before anything is copied + let count = s.catalog.albums().count(); + assert!(s.execute("album.duplicate", &json!({"ids": [a, 4242]})).unwrap_err().to_string().contains("4242")); + assert!(s.execute("album.duplicate", &json!({"ids": [a], "parent": b})).is_err(), "not a folder"); + assert!(s.execute("album.duplicate", &json!({"ids": []})).is_err()); + assert_eq!(s.catalog.albums().count(), count); +} + +#[test] +fn a_copied_folder_keeps_the_order_inside_it_and_its_smart_albums_go_by_the_copies() { + let mut s = Session::new(); + photos(&mut s, 1); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let x = album(&mut s, json!({"name": "X", "parent": folder})); + let y = album(&mut s, json!({"name": "Y", "parent": folder})); + // by hand: Y before X + s.execute("album.reorder", &json!({"id": y, "before": x})).unwrap(); + let smart = s.execute("album.createSmart", &json!({"name": "S", "rules": {"album": x}})).unwrap()["id"].as_u64().unwrap(); + s.execute("album.move", &json!({"id": smart, "parent": folder})).unwrap(); + let copy = s.execute("album.duplicate", &json!({"id": folder})).unwrap()["ids"][0].as_u64().unwrap(); + let inside = |s: &Session, name: &str| s.catalog.albums().find(|a| a.name == name && a.parent == Some(AlbumId(copy))).cloned().unwrap(); + let (cx, cy, cs) = (inside(&s, "X"), inside(&s, "Y"), inside(&s, "S")); + assert!(cy.order.is_some() && cy.order < cx.order, "Y is still before X: {:?} {:?}", cy.order, cx.order); + assert_eq!(cs.smart.as_ref().and_then(|r| r.album), Some(cx.id), "limited to the copy of X, not to X"); + assert_eq!(s.catalog.album(AlbumId(copy)).unwrap().order, None, "the copy itself is listed by name"); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 0b49424366b..d1ed08ae85a 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Odstranit alba a složky alb ({n})?", + "{inside} more inside the folders go too.": "Smažou se i další uvnitř složek ({inside}).", + "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}", + "{n} albums": "Alba: {n}", + "{n} folders": "Složky: {n}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 2ffc8846ee3..5b51bcfbc6f 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2410,5 +2410,31 @@ "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", - "Starts next": "Začne jako další" + "Starts next": "Začne jako další", + "A folder can't go inside itself": "Složku nelze vložit do sebe samé", + "A keyword can't go inside itself": "Klíčové slovo nelze vložit do sebe samého", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Zkopírováno jako text: vložte jej do pole klíčových slov a přiřaďte tak klíčová slova fotografiím", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Zkopírováno: Vložit najdete v nabídce složky a pro nejvyšší úroveň v nabídce + u Alb", + "Create Keyword Tag Inside…": "Vytvořit značku klíčového slova uvnitř…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Vyjmuto: Vložit najdete v nabídce složky a pro nejvyšší úroveň v nabídce + u Alb", + "Cut: Paste is in the menu of the keyword they go inside": "Vyjmuto: Vložit najdete v nabídce klíčového slova, do kterého mají patřit", + "Delete Albums": "Odstranit alba", + "Delete Folder": "Odstranit složku", + "Delete Keywords": "Odstranit klíčová slova", + "Duplicate Album": "Duplikovat album", + "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ě", + "Paste Inside This Keyword": "Vložit do tohoto klíčového slova", + "Paste Into This Folder": "Vložit do této složky", + "Paste at Top Level": "Vložit na nejvyšší úroveň", + "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 5b5b38fa33f..796a57d0459 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "{n} Alben und Albumordner löschen?", + "{inside} more inside the folders go too.": "{inside} weitere in den Ordnern werden ebenfalls gelöscht.", + "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", + "{n} albums": "{n} Alben", + "{n} folders": "{n} Ordner" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index a809ebe4c3d..a3825fc2e8a 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1227,6 +1227,35 @@ "Remove Disk from Library…": "Datenträger aus Bibliothek entfernen…", "Remove Face Box": "Gesichtsrahmen entfernen", "Remove Folder from Library": "Ordner aus Bibliothek entfernen", + "A folder can't go inside itself": "Ein Ordner kann nicht in sich selbst liegen", + "A keyword can't go inside itself": "Ein Stichwort kann nicht in sich selbst liegen", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Als Text kopiert: in ein Stichwortfeld einfügen, um Fotos die Stichwörter zu geben", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Kopiert: „Einfügen“ steht im Menü eines Ordners und, für die oberste Ebene, im +-Menü der Alben", + "Create Keyword Tag Inside…": "Stichwort darin erstellen…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Ausgeschnitten: „Einfügen“ steht im Menü eines Ordners und, für die oberste Ebene, im +-Menü der Alben", + "Cut: Paste is in the menu of the keyword they go inside": "Ausgeschnitten: „Einfügen“ steht im Menü des Stichworts, in das sie kommen sollen", + "Delete Albums": "Alben löschen", + "Delete Folder": "Ordner löschen", + "Delete Keywords": "Stichwörter löschen", + "Duplicate Album": "Album duplizieren", + "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", + "Paste Inside This Keyword": "In dieses Stichwort einfügen", + "Paste Into This Folder": "In diesen Ordner einfügen", + "Paste at Top Level": "Auf oberster Ebene einfügen", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Die Fotos bleiben in „Alle Fotos“. Beim Löschen eines Ordners werden auch seine Alben gelöscht. Das lässt sich rückgängig machen.", + "Remove Folder Color Label": "Farbmarkierung des Ordners entfernen", + "Remove Folders from Library": "Ordner aus Bibliothek entfernen", + "Set Folder Color Label": "Farbmarkierung des Ordners festlegen", + "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.", "Remove a filter above, or choose Clear all": "Entferne oben einen Filter oder wähle „Alles löschen“", "Remove from Album": "Aus Album entfernen", "Remove from Favorites": "Aus Favoriten entfernen", @@ -2342,7 +2371,6 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", "Checking the GPU for faces": "GPU für Gesichter wird geprüft", - "Set Folder Color Label": "Ordner-Farbmarkierung festlegen", "Photo Below": "Foto darunter", "Photo Above": "Foto darüber", "Cycle Flag": "Markierung wechseln", @@ -2479,7 +2507,6 @@ "Enter to confirm, Esc to cancel": "Eingabetaste bestätigt, Esc bricht ab", "Show photos": "Fotos anzeigen", "The layout image can't be shown": "Das Layoutbild kann nicht angezeigt werden", - "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Fotos bleiben in „Alle Fotos“. Beim Löschen eines Ordners werden auch seine Alben gelöscht. Du kannst das rückgängig machen.", "No change": "Keine Änderung", "Search effects": "Effekte durchsuchen", "No effect presets yet": "Noch keine Effektvorgaben", @@ -2557,7 +2584,6 @@ "Edit In": "Bearbeiten in", "Face models (ONNX)": "Gesichtsmodelle (ONNX)", "ICC Profiles": "ICC-Profile", - "Remove Folder Color Label": "Ordner-Farbmarkierung entfernen", "Loupe Overlay": "Lupenüberlagerung", "2026-10-14": "14.10.2026", "Lightroom radial masks on the right side": "Lightroom-Radialmasken auf der richtigen Seite", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index aad6ee5face..680098dc304 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "¿Eliminar {n} álbumes y carpetas de álbumes?", + "{inside} more inside the folders go too.": "También se eliminan {inside} más que hay dentro de las carpetas.", + "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", + "{n} albums": "{n} álbumes", + "{n} folders": "{n} carpetas" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 3dc670f7089..36cde7eba86 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1234,6 +1234,35 @@ "Rename Photos never overwrites another photo when only the letter case changes (issue #95): on case-sensitive": "Cambiar nombre de las fotos nunca sobrescribe otra foto cuando solo cambian las mayúsculas y minúsculas (issue #95): en", "Rename Photos reports files it could not move back after a failure (issue #105), e.g. when a network share drops": "Cambiar nombre de las fotos indica los archivos que no pudo devolver a su sitio tras un fallo (issue #105), p. ej., cuando una carpeta de red se desconecta", "Remove Folder from Library": "Quitar carpeta de la biblioteca", + "A folder can't go inside itself": "Una carpeta no puede ir dentro de sí misma", + "A keyword can't go inside itself": "Una palabra clave no puede ir dentro de sí misma", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Copiado como texto: pégalo en un cuadro de palabras clave para dar las palabras clave a las fotos", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Copiado: Pegar está en el menú de una carpeta y, para el nivel superior, en el menú + de Álbumes", + "Create Keyword Tag Inside…": "Crear palabra clave dentro…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Cortado: Pegar está en el menú de una carpeta y, para el nivel superior, en el menú + de Álbumes", + "Cut: Paste is in the menu of the keyword they go inside": "Cortado: Pegar está en el menú de la palabra clave que las va a contener", + "Delete Albums": "Eliminar álbumes", + "Delete Folder": "Eliminar carpeta", + "Delete Keywords": "Eliminar palabras clave", + "Duplicate Album": "Duplicar álbum", + "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", + "Paste Inside This Keyword": "Pegar dentro de esta palabra clave", + "Paste Into This Folder": "Pegar en esta carpeta", + "Paste at Top Level": "Pegar en el nivel superior", + "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. Se puede deshacer.", + "Remove Folder Color Label": "Quitar etiqueta de color de la carpeta", + "Remove Folders from Library": "Quitar carpetas de la biblioteca", + "Set Folder Color Label": "Definir etiqueta de color de la carpeta", + "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.", "Remove a filter above, or choose Clear all": "Quitar un filtro arriba o elegir Borrar todo", "Remove from Album": "Quitar del álbum", "Remove from Favorites": "Quitar de Favoritos", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 8e85c136fb2..85a4961c382 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Poistetaanko {n} albumia ja albumikansiota?", + "{inside} more inside the folders go too.": "Kansioiden sisällä olevat {inside} muuta poistuvat myös.", + "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 poistuvat 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", + "{n} albums": "{n} albumia", + "{n} folders": "{n} kansiota" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e818f109e0b..aa370e39ad8 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2329,5 +2329,31 @@ "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", - "Starts next": "Alkaa seuraavaksi" + "Starts next": "Alkaa seuraavaksi", + "A folder can't go inside itself": "Kansio ei voi siirtyä itsensä sisään", + "A keyword can't go inside itself": "Avainsana ei voi siirtyä itsensä sisään", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Kopioitu tekstinä: liitä se avainsanakenttään antaaksesi avainsanat kuville", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Kopioitu: Liitä-komento on kansion valikossa ja Albumit-valikon + -painikkeen valikossa ylätasolle", + "Create Keyword Tag Inside…": "Luo avainsanatunniste sisään…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Leikattu: Liitä-komento on kansion valikossa ja Albumit-valikon + -painikkeen valikossa ylätasolle", + "Cut: Paste is in the menu of the keyword they go inside": "Leikattu: Liitä-komento on sen avainsanan valikossa, jonka sisään ne siirretään", + "Delete Albums": "Poista albumit", + "Delete Folder": "Poista kansio", + "Delete Keywords": "Poista avainsanat", + "Duplicate Album": "Monista albumi", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Siirtää näistä kansioista tuodut kuvat kohtaan Äskettäin poistetut; tiedostoihin ei kosketa", + "No photo has them; the keywords below them go too.": "Millään kuvalla ei ole niitä; niiden alla olevat avainsanat poistuvat myös.", + "One of them is a whole disk: remove a disk by itself": "Yksi niistä on kokonainen levy: poista levy erikseen", + "Paste Inside This Keyword": "Liitä tämän avainsanan sisään", + "Paste Into This Folder": "Liitä tähän kansioon", + "Paste at Top Level": "Liitä ylätasolle", + "Remove Folders from Library": "Poista kansiot kirjastosta", + "That includes the photos in the folders inside them.": "Mukana ovat niiden sisällä olevien kansioiden 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 b8442d2131e..3d2c0e0da6a 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Supprimer {n} albums et dossiers d'albums ?", + "{inside} more inside the folders go too.": "{inside} autres, à l'intérieur des dossiers, sont aussi supprimés.", + "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", + "{n} albums": "{n} albums", + "{n} folders": "{n} dossiers" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index ef1faa5f8d6..b7033daa145 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1168,6 +1168,35 @@ "Remove Disk from Library…": "Retirer le disque de la bibliothèque…", "Remove Face Box": "Retirer le cadre de visage", "Remove Folder from Library": "Retirer le dossier de la bibliothèque", + "A folder can't go inside itself": "Un dossier ne peut pas aller dans lui-même", + "A keyword can't go inside itself": "Un mot-clé ne peut pas aller dans lui-même", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Copié comme texte : collez-le dans un champ de mots-clés pour donner les mots-clés à des photos", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Copié : Coller se trouve dans le menu d'un dossier et, pour le niveau supérieur, dans le menu + des Albums", + "Create Keyword Tag Inside…": "Créer un mot-clé à l'intérieur…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Coupé : Coller se trouve dans le menu d'un dossier et, pour le niveau supérieur, dans le menu + des Albums", + "Cut: Paste is in the menu of the keyword they go inside": "Coupé : Coller se trouve dans le menu du mot-clé dans lequel ils vont", + "Delete Albums": "Supprimer les albums", + "Delete Folder": "Supprimer le dossier", + "Delete Keywords": "Supprimer les mots-clés", + "Duplicate Album": "Dupliquer l'album", + "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", + "Paste Inside This Keyword": "Coller dans ce mot-clé", + "Paste Into This Folder": "Coller dans ce dossier", + "Paste at Top Level": "Coller au niveau supérieur", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Les photos restent dans Toutes les photos. Supprimer un dossier supprime aussi ses albums. Cette action peut être annulée.", + "Remove Folder Color Label": "Retirer l'étiquette de couleur du dossier", + "Remove Folders from Library": "Retirer les dossiers de la bibliothèque", + "Set Folder Color Label": "Définir l'étiquette de couleur du dossier", + "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.", "Remove a filter above, or choose Clear all": "Retirez un filtre ci-dessus ou choisissez Tout effacer", "Remove from Album": "Retirer de l'album", "Remove from Favorites": "Retirer des favoris", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index c331f292705..898afe84657 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -309,5 +309,24 @@ "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}", + "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…": "Hapus {n} folder dari pustaka…", + "Add {n} Keywords to Selected Photos": "Tambahkan {n} kata kunci ke foto terpilih", + "Remove {n} Keywords from Selected Photos": "Hapus {n} kata kunci dari foto terpilih", + "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 dalam…", + "Delete {n} Keywords…": "Hapus {n} kata kunci…", + "Delete {n} albums?": "Hapus {n} album?", + "Delete {n} albums and folders of albums?": "Hapus {n} album dan folder album?", + "{inside} more inside the folders go too.": "{inside} lagi di dalam folder ikut terhapus.", + "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}.": "Hapus {n} folder dari pustaka? Foto yang diimpor dari sana: {count}.", + "…and {n} more": "…dan {n} lagi", + "{n} keywords": "{n} kata kunci", + "{n} albums": "{n} album", + "{n} folders": "{n} folder" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 00d6d0753ec..b526dcc7d19 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2341,5 +2341,31 @@ "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", - "Starts next": "Dimulai berikutnya" + "Starts next": "Dimulai berikutnya", + "A folder can't go inside itself": "Folder tidak bisa dimasukkan ke dalam dirinya sendiri", + "A keyword can't go inside itself": "Kata kunci tidak bisa dimasukkan ke dalam dirinya sendiri", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Disalin sebagai teks: tempel di kotak kata kunci untuk memberikan kata kunci ke foto", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Disalin: Tempel ada di menu folder, dan di menu + Album untuk tingkat teratas", + "Create Keyword Tag Inside…": "Buat tag kata kunci di dalam…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Dipotong: Tempel ada di menu folder, dan di menu + Album untuk tingkat teratas", + "Cut: Paste is in the menu of the keyword they go inside": "Dipotong: Tempel ada di menu kata kunci tempat semuanya dimasukkan", + "Delete Albums": "Hapus album", + "Delete Folder": "Hapus folder", + "Delete Keywords": "Hapus kata kunci", + "Duplicate Album": "Duplikat album", + "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 berkas 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 seluruh disk: hapus disk satu per satu", + "Paste Inside This Keyword": "Tempel di dalam kata kunci ini", + "Paste Into This Folder": "Tempel ke folder ini", + "Paste at Top Level": "Tempel di tingkat teratas", + "Remove Folders from Library": "Hapus folder dari pustaka", + "That includes the photos in the folders inside them.": "Itu mencakup foto di folder-folder 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 52b73fc3788..2e6ae6e5f61 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Eliminare {n} album e cartelle di album?", + "{inside} more inside the folders go too.": "Vengono eliminati anche altri {inside} dentro le cartelle.", + "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", + "{n} albums": "{n} album", + "{n} folders": "{n} cartelle" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 28d4a80c322..56e82b6ac22 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2363,5 +2363,31 @@ "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", - "Starts next": "Parte subito dopo" + "Starts next": "Parte subito dopo", + "A folder can't go inside itself": "Una cartella non può andare dentro sé stessa", + "A keyword can't go inside itself": "Una parola chiave non può andare dentro sé stessa", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Copiato come testo: incollalo in un campo delle parole chiave per assegnarle alle foto", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Copiato: Incolla si trova nel menu di una cartella e, per il livello superiore, nel menu + di Album", + "Create Keyword Tag Inside…": "Crea tag parola chiave all'interno…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Tagliato: Incolla si trova nel menu di una cartella e, per il livello superiore, nel menu + di Album", + "Cut: Paste is in the menu of the keyword they go inside": "Tagliato: Incolla si trova nel menu della parola chiave in cui devono andare", + "Delete Albums": "Elimina album", + "Delete Folder": "Elimina cartella", + "Delete Keywords": "Elimina parole chiave", + "Duplicate Album": "Duplica album", + "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", + "Paste Inside This Keyword": "Incolla in questa parola chiave", + "Paste Into This Folder": "Incolla in questa cartella", + "Paste at Top Level": "Incolla al livello superiore", + "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 ff5030690b0..d5378d01703 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "{n}個のアルバムとアルバムフォルダを削除しますか?", + "{inside} more inside the folders go too.": "フォルダ内のさらに{inside}個も削除されます。", + "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}個のキーワード", + "{n} albums": "{n}個のアルバム", + "{n} folders": "{n}個のフォルダ" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 2709a330ca9..cf183cac13e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1652,6 +1652,35 @@ "Sunday": "日曜日", "Unknown Date": "日付不明", "Remove Folder from Library": "フォルダをライブラリから除去", + "A folder can't go inside itself": "フォルダをそのフォルダ自身の中に入れることはできません", + "A keyword can't go inside itself": "キーワードをそのキーワード自身の中に入れることはできません", + "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つだけ選択してください", + "Copied as text: paste it in a keyword box to give the keywords to photos": "テキストとしてコピーしました。キーワード欄に貼り付けると、写真にキーワードを付けられます", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "コピーしました。「貼り付け」はフォルダのメニューにあります。最上位に貼り付けるにはアルバムの + メニューを使います", + "Create Keyword Tag Inside…": "この中にキーワードタグを作成…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "切り取りました。「貼り付け」はフォルダのメニューにあります。最上位に貼り付けるにはアルバムの + メニューを使います", + "Cut: Paste is in the menu of the keyword they go inside": "切り取りました。「貼り付け」は、移動先のキーワードのメニューにあります", + "Delete Albums": "アルバムを削除", + "Delete Folder": "フォルダを削除", + "Delete Keywords": "キーワードを削除", + "Duplicate Album": "アルバムを複製", + "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": "その中にディスク全体が含まれています。ディスクは単独で除去してください", + "Paste Inside This Keyword": "このキーワードの中に貼り付け", + "Paste Into This Folder": "このフォルダに貼り付け", + "Paste at Top Level": "最上位に貼り付け", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "写真は「すべての写真」に残ります。フォルダを削除すると、その中のアルバムも削除されます。この操作は取り消せます。", + "Remove Folder Color Label": "フォルダのカラーラベルを解除", + "Remove Folders from Library": "フォルダをライブラリから除去", + "Set Folder Color Label": "フォルダのカラーラベルを設定", + "That includes the photos in the folders inside them.": "その中にあるフォルダの写真も含まれます。", + "The photos stay in All Photos. Undo brings the albums back.": "写真は「すべての写真」に残ります。「取り消す」でアルバムが戻ります。", "Remove from Library…": "ライブラリから除去…", "This Computer": "このコンピュータ", "includes the folders inside it": "内側のフォルダを含む", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index ef610bd14cc..780892b819b 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "წავშალოთ {n} ალბომი და ალბომების საქაღალდე?", + "{inside} more inside the folders go too.": "საქაღალდეებში არსებული კიდევ {inside} ასევე წაიშლება.", + "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}", + "{n} albums": "ალბომები: {n}", + "{n} folders": "საქაღალდეები: {n}" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 98f22f908f9..9e76b550aac 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2736,5 +2736,32 @@ "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": "სხვა ბიბლიოთეკა გაიხსნა: არაფერი გაკეთებულა", - "Starts next": "დაიწყება შემდეგი" + "Starts next": "დაიწყება შემდეგი", + "A folder can't go inside itself": "საქაღალდე საკუთარ თავში ვერ მოთავსდება", + "A keyword can't go inside itself": "საკვანძო სიტყვა საკუთარ თავში ვერ მოთავსდება", + "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": "სახელის შესაცვლელად აირჩიეთ ერთი საკვანძო სიტყვა", + "Copied as text: paste it in a keyword box to give the keywords to photos": "დაკოპირდა ტექსტად: ჩასვით საკვანძო სიტყვების ველში, რომ ეს სიტყვები ფოტოებს მიანიჭოთ", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "დაკოპირდა: „ჩასმა“ საქაღალდის მენიუშია, ზედა დონისთვის კი — „ალბომების“ + მენიუში", + "Create Keyword Tag Inside…": "შიგნით საკვანძო სიტყვის შექმნა…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "ამოიჭრა: „ჩასმა“ საქაღალდის მენიუშია, ზედა დონისთვის კი — „ალბომების“ + მენიუში", + "Cut: Paste is in the menu of the keyword they go inside": "ამოიჭრა: „ჩასმა“ იმ საკვანძო სიტყვის მენიუშია, რომელშიც უნდა მოთავსდეს", + "Delete Albums": "ალბომების წაშლა", + "Delete Folder": "საქაღალდის წაშლა", + "Delete Keywords": "საკვანძო სიტყვების წაშლა", + "Duplicate Album": "ალბომის დუბლირება", + "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": "ერთ-ერთი მათგანი მთელი დისკია: დისკი ცალკე მოაშორეთ", + "Paste Inside This Keyword": "ამ საკვანძო სიტყვაში ჩასმა", + "Paste Into This Folder": "ამ საქაღალდეში ჩასმა", + "Paste at Top Level": "ზედა დონეზე ჩასმა", + "Remove Folder Color Label": "საქაღალდის ფერადი იარლიყის მოხსნა", + "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 ad311891b51..6d1b741cddb 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Usunąć albumy i foldery albumów ({n})?", + "{inside} more inside the folders go too.": "Usunięte zostaną też kolejne wewnątrz folderów ({inside}).", + "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}", + "{n} albums": "Albumy: {n}", + "{n} folders": "Foldery: {n}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index da7a834f42b..58a5d19f990 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2285,5 +2285,33 @@ "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", - "Starts next": "Rozpocznie się jako następne" + "Starts next": "Rozpocznie się jako następne", + "A folder can't go inside itself": "Folder nie może trafić do samego siebie", + "A keyword can't go inside itself": "Słowo kluczowe nie może trafić do samego siebie", + "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ę", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Skopiowano jako tekst: wklej go w pole słów kluczowych, aby nadać je zdjęciom", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Skopiowano: Wklej jest w menu folderu, a dla najwyższego poziomu w menu + Albumów", + "Create Keyword Tag Inside…": "Utwórz słowo kluczowe wewnątrz…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Wycięto: Wklej jest w menu folderu, a dla najwyższego poziomu w menu + Albumów", + "Cut: Paste is in the menu of the keyword they go inside": "Wycięto: Wklej jest w menu słowa kluczowego, do którego mają trafić", + "Delete Albums": "Usuń albumy", + "Delete Folder": "Usuń folder", + "Delete Keywords": "Usuń słowa kluczowe", + "Duplicate Album": "Duplikuj album", + "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", + "Paste Inside This Keyword": "Wklej do tego słowa kluczowego", + "Paste Into This Folder": "Wklej do tego folderu", + "Paste at Top Level": "Wklej na najwyższym poziomie", + "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żna to cofnąć.", + "Remove Folder Color Label": "Usuń etykietę kolorystyczną folderu", + "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." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 4960090f14f..0a5d0164f8c 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Excluir {n} álbuns e pastas de álbuns?", + "{inside} more inside the folders go too.": "Mais {inside} dentro das pastas também são excluídos.", + "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", + "{n} albums": "{n} álbuns", + "{n} folders": "{n} pastas" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e210d177197..c7b1353c562 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1188,6 +1188,35 @@ "Remove Disk from Library…": "Remover disco da biblioteca…", "Remove Face Box": "Remover caixa de rosto", "Remove Folder from Library": "Remover pasta da biblioteca", + "A folder can't go inside itself": "Uma pasta não pode ir para dentro de si mesma", + "A keyword can't go inside itself": "Uma palavra-chave não pode ir para dentro de si mesma", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Copiado como texto: cole em uma caixa de palavras-chave para dar as palavras-chave às fotos", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Copiado: Colar está no menu de uma pasta e, para o nível superior, no menu + de Álbuns", + "Create Keyword Tag Inside…": "Criar palavra-chave dentro…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Recortado: Colar está no menu de uma pasta e, para o nível superior, no menu + de Álbuns", + "Cut: Paste is in the menu of the keyword they go inside": "Recortado: Colar está no menu da palavra-chave que vai contê-las", + "Delete Albums": "Excluir álbuns", + "Delete Folder": "Excluir pasta", + "Delete Keywords": "Excluir palavras-chave", + "Duplicate Album": "Duplicar álbum", + "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", + "Paste Inside This Keyword": "Colar dentro desta palavra-chave", + "Paste Into This Folder": "Colar nesta pasta", + "Paste at Top Level": "Colar no nível superior", + "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 seus álbuns. É possível desfazer.", + "Remove Folder Color Label": "Remover rótulo de cor da pasta", + "Remove Folders from Library": "Remover pastas da biblioteca", + "Set Folder Color Label": "Definir rótulo de cor da pasta", + "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.", "Remove a filter above, or choose Clear all": "Remova um filtro acima ou escolha Limpar tudo", "Remove from Album": "Remover do álbum", "Remove from Favorites": "Remover dos favoritos", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index de63d603eac..fae1b799523 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Удалить альбомы и папки альбомов ({n})?", + "{inside} more inside the folders go too.": "Вместе с ними удаляется содержимое папок: ещё {inside}.", + "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}", + "{n} albums": "Альбомы: {n}", + "{n} folders": "Папки: {n}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index dabb4c10039..4f9709a4160 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1971,6 +1971,35 @@ "Remove Face Box": "Удалить рамку лица", "Remove Face Model": "Удалить модель лиц", "Remove Folder from Library": "Убрать папку из библиотеки", + "A folder can't go inside itself": "Папку нельзя поместить в саму себя", + "A keyword can't go inside itself": "Ключевое слово нельзя поместить в само себя", + "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": "Выберите только одно ключевое слово, чтобы переименовать его", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Скопировано как текст: вставьте в поле ключевых слов, чтобы назначить их фото", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Скопировано: «Вставить» находится в меню папки, а для верхнего уровня — в меню «+» раздела «Альбомы»", + "Create Keyword Tag Inside…": "Создать ключевое слово внутри…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Вырезано: «Вставить» находится в меню папки, а для верхнего уровня — в меню «+» раздела «Альбомы»", + "Cut: Paste is in the menu of the keyword they go inside": "Вырезано: «Вставить» находится в меню ключевого слова, внутрь которого их нужно поместить", + "Delete Albums": "Удалить альбомы", + "Delete Folder": "Удалить папку", + "Delete Keywords": "Удалить ключевые слова", + "Duplicate Album": "Дублировать альбом", + "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": "Одна из них — целый диск: убирайте диск отдельно", + "Paste Inside This Keyword": "Вставить в это ключевое слово", + "Paste Into This Folder": "Вставить в эту папку", + "Paste at Top Level": "Вставить на верхний уровень", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото остаются во «Всех фото». При удалении папки удаляются и её альбомы. Это действие можно отменить.", + "Remove Folder Color Label": "Убрать цветовую метку папки", + "Remove Folders from Library": "Убрать папки из библиотеки", + "Set Folder Color Label": "Назначить цветовую метку папке", + "That includes the photos in the folders inside them.": "Сюда входят и фото во вложенных в них папках.", + "The photos stay in All Photos. Undo brings the albums back.": "Фото остаются во «Всех фото». Команда «Отменить» вернёт альбомы.", "Remove a filter above, or choose Clear all": "Уберите фильтр выше или выберите «Очистить всё»", "Remove from Library…": "Убрать из библиотеки…", "Remove from Target Album": "Убрать из целевого альбома", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 1e71f5f9a6c..a6bf0e321e7 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -309,5 +309,24 @@ "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}", + "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 på valda foton", + "Remove {n} Keywords from Selected Photos": "Ta bort {n} nyckelord från valda foton", + "Show Photos with Any of {n} Keywords": "Visa foton med något av {n} nyckelord", + "Merge {n} Keywords into…": "Slå ihop {n} nyckelord med…", + "Delete {n} Keywords…": "Radera {n} nyckelord…", + "Delete {n} albums?": "Radera {n} album?", + "Delete {n} albums and folders of albums?": "Radera {n} album och albummappar?", + "{inside} more inside the folders go too.": "{inside} till inuti mapparna försvinner också.", + "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 försvinner också. Ångra tar tillbaka dem.", + "Remove {n} folders from the library? Photos imported from them: {count}.": "Ta bort {n} mappar från biblioteket? Foton importerade från dem: {count}.", + "…and {n} more": "…och {n} till", + "{n} keywords": "{n} nyckelord", + "{n} albums": "{n} album", + "{n} folders": "{n} mappar" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 16b96132f52..dde023f4d51 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2431,5 +2431,31 @@ "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", - "Starts next": "Startar härnäst" + "Starts next": "Startar härnäst", + "A folder can't go inside itself": "En mapp kan inte läggas i sig själv", + "A keyword can't go inside itself": "Ett nyckelord kan inte läggas i sig självt", + "Choose one album to rename it": "Välj ett album för att byta namn på det", + "Choose one folder to rename it": "Välj en mapp för att byta namn på den", + "Choose one folder to synchronize it": "Välj en mapp för att synkronisera den", + "Choose one keyword to create a keyword inside it": "Välj ett nyckelord för att skapa ett nyckelord i det", + "Choose one keyword to edit it": "Välj ett nyckelord för att redigera det", + "Choose one keyword to rename it": "Välj ett nyckelord för att byta namn på det", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Kopierat som text: klistra in det i en nyckelordsruta för att ge foton nyckelorden", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Kopierat: Klistra in finns i en mapps meny och i menyn + under Album för översta nivån", + "Create Keyword Tag Inside…": "Skapa nyckelordstagg i…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Urklippt: Klistra in finns i en mapps meny och i menyn + under Album för översta nivån", + "Cut: Paste is in the menu of the keyword they go inside": "Urklippt: Klistra in finns i menyn för det nyckelord de läggs i", + "Delete Albums": "Radera album", + "Delete Folder": "Radera mapp", + "Delete Keywords": "Radera nyckelord", + "Duplicate Album": "Duplicera album", + "Moves the photos imported from these folders to Recently Deleted; no file is touched": "Flyttar fotona som importerats från dessa mappar till Nyligen raderade; inga filer rörs", + "No photo has them; the keywords below them go too.": "Inget foto har dem; nyckelorden under dem försvinner 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", + "Paste Inside This Keyword": "Klistra in i detta nyckelord", + "Paste Into This Folder": "Klistra in i denna mapp", + "Paste at Top Level": "Klistra in på översta nivån", + "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 045d654b817..45e582260b6 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "Видалити альбоми й теки альбомів ({n})?", + "{inside} more inside the folders go too.": "Разом із ними видаляється вміст тек: ще {inside}.", + "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}", + "{n} albums": "Альбоми: {n}", + "{n} folders": "Теки: {n}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index cf2ff1448dd..42c398be38c 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1647,6 +1647,35 @@ "Sunday": "Неділя", "Unknown Date": "Невідома дата", "Remove Folder from Library": "Вилучити теку з бібліотеки", + "A folder can't go inside itself": "Теку не можна помістити в саму себе", + "A keyword can't go inside itself": "Ключове слово не можна помістити в саме себе", + "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": "Виберіть лише одне ключове слово, щоб перейменувати його", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Скопійовано як текст: вставте в поле ключових слів, щоб призначити їх фото", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Скопійовано: «Вставити» є в меню теки, а для верхнього рівня — у меню «+» розділу «Альбоми»", + "Create Keyword Tag Inside…": "Створити ключове слово всередині…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Вирізано: «Вставити» є в меню теки, а для верхнього рівня — у меню «+» розділу «Альбоми»", + "Cut: Paste is in the menu of the keyword they go inside": "Вирізано: «Вставити» є в меню ключового слова, усередину якого їх треба помістити", + "Delete Albums": "Видалити альбоми", + "Delete Folder": "Видалити теку", + "Delete Keywords": "Видалити ключові слова", + "Duplicate Album": "Дублювати альбом", + "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": "Одна з них — цілий диск: вилучайте диск окремо", + "Paste Inside This Keyword": "Вставити в це ключове слово", + "Paste Into This Folder": "Вставити в цю теку", + "Paste at Top Level": "Вставити на верхній рівень", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Фото залишаються в «Усіх фото». Видалення теки видаляє і її альбоми. Цю дію можна скасувати.", + "Remove Folder Color Label": "Вилучити кольорову мітку теки", + "Remove Folders from Library": "Вилучити теки з бібліотеки", + "Set Folder Color Label": "Задати кольорову мітку теки", + "That includes the photos in the folders inside them.": "Також включаються фото у вкладених у них теках.", + "The photos stay in All Photos. Undo brings the albums back.": "Фото залишаються в «Усіх фото». Скасування повертає альбоми.", "Remove from Library…": "Вилучити з бібліотеки…", "This Computer": "Цей комп’ютер", "includes the folders inside it": "включає вкладені теки", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 14bb4142c36..4e8a5814885 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -309,5 +309,24 @@ "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}", + "Export {n} Albums…": "Xuất {n} album…", + "Move {n} Albums to": "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 các ảnh đã chọn", + "Remove {n} Keywords from Selected Photos": "Gỡ {n} từ khóa khỏi các ả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…": "Gộ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} albums and folders of albums?": "Xóa {n} album và thư mục album?", + "{inside} more inside the folders go too.": "{inside} mục nữa bên trong các thư mục cũng bị xóa.", + "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.": "Ả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? Ảnh đã nhập từ đó: {count}.", + "…and {n} more": "…và {n} mục nữa", + "{n} keywords": "{n} từ khóa", + "{n} albums": "{n} album", + "{n} folders": "{n} thư mục" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 9d127ff71a1..bacef299b00 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2237,5 +2237,32 @@ "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", - "Starts next": "Bắt đầu tiếp theo" + "Starts next": "Bắt đầu tiếp theo", + "A folder can't go inside itself": "Một thư mục không thể nằm trong chính nó", + "A keyword can't go inside itself": "Một từ khóa không thể nằm trong chính nó", + "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", + "Choose one keyword to edit it": "Chọn một từ khóa để chỉnh sửa", + "Choose one keyword to rename it": "Chọn một từ khóa để đổi tên", + "Copied as text: paste it in a keyword box to give the keywords to photos": "Đã sao chép dưới dạng văn bản: dán vào ô từ khóa để gán các từ khóa cho ảnh", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "Đã sao chép: Dán nằm trong menu của thư mục và trong menu + của Album cho cấp cao nhất", + "Create Keyword Tag Inside…": "Tạo thẻ từ khóa bên trong…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "Đã cắt: Dán nằm trong menu của thư mục và trong menu + của Album cho cấp cao nhất", + "Cut: Paste is in the menu of the keyword they go inside": "Đã cắt: Dán nằm trong menu của từ khóa mà chúng được đưa vào", + "Delete Albums": "Xóa album", + "Delete Folder": "Xóa thư mục", + "Delete Keywords": "Xóa từ khóa", + "Duplicate Album": "Nhân bản album", + "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", + "Paste Inside This Keyword": "Dán vào bên trong từ khóa này", + "Paste Into This Folder": "Dán vào thư mục này", + "Paste at Top Level": "Dán ở cấp cao nhất", + "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.": "Các ảnh vẫn nằm trong Tất cả ảnh. Hoàn tác sẽ đưa các album trở lại.", + "Remove Folder Color Label": "Xóa nhãn màu thư mục" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index fa961db45e2..654696aa57f 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "要删除 {n} 个相册和相册文件夹吗?", + "{inside} more inside the folders go too.": "文件夹内的另外 {inside} 个也会被删除。", + "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} 个关键字", + "{n} albums": "{n} 个相册", + "{n} folders": "{n} 个文件夹" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index afdb746b3f8..a7f55364bab 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1677,6 +1677,35 @@ "繁體中文(台灣)": "繁體中文(台灣)", "In Recently Deleted": "在“最近删除”中", "Remove Folder from Library": "从图库中移除文件夹", + "A folder can't go inside itself": "文件夹不能放入其自身", + "A keyword can't go inside itself": "关键字不能放入其自身", + "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": "请只选择一个关键字以重命名", + "Copied as text: paste it in a keyword box to give the keywords to photos": "已复制为文本:粘贴到关键字框中即可将这些关键字赋予照片", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "已复制:“粘贴”位于文件夹的菜单中;要粘贴到顶层,请使用“相册”的 + 菜单", + "Create Keyword Tag Inside…": "在其中创建关键字标记…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "已剪切:“粘贴”位于文件夹的菜单中;要粘贴到顶层,请使用“相册”的 + 菜单", + "Cut: Paste is in the menu of the keyword they go inside": "已剪切:“粘贴”位于要放入的关键字的菜单中", + "Delete Albums": "删除相册", + "Delete Folder": "删除文件夹", + "Delete Keywords": "删除关键字", + "Duplicate Album": "创建相册副本", + "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": "其中一个是整个磁盘:请单独移除磁盘", + "Paste Inside This Keyword": "粘贴到此关键字中", + "Paste Into This Folder": "粘贴到此文件夹", + "Paste at Top Level": "粘贴到顶层", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在“所有照片”中。删除文件夹也会删除其中的相册。此操作可以撤销。", + "Remove Folder Color Label": "移除文件夹颜色标签", + "Remove Folders from Library": "从图库中移除文件夹", + "Set Folder Color Label": "设置文件夹颜色标签", + "That includes the photos in the folders inside them.": "其中也包括这些文件夹内各子文件夹中的照片。", + "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在“所有照片”中。撤销可恢复这些相册。", "Remove from Library…": "从图库中移除…", "This Computer": "此电脑", "includes the folders inside it": "包含其中的文件夹", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index b40a6592281..b7c34b08654 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -309,5 +309,24 @@ "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}", + "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} albums and folders of albums?": "要刪除 {n} 個相簿和相簿資料夾嗎?", + "{inside} more inside the folders go too.": "資料夾內的另外 {inside} 個也會被刪除。", + "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} 個關鍵字", + "{n} albums": "{n} 個相簿", + "{n} folders": "{n} 個資料夾" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 006e49fc447..676385aaa2e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1683,6 +1683,35 @@ "繁體中文(台灣)": "繁體中文(台灣)", "In Recently Deleted": "在「最近刪除」中", "Remove Folder from Library": "從照片庫移除資料夾", + "A folder can't go inside itself": "資料夾不能放入其自身", + "A keyword can't go inside itself": "關鍵字不能放入其自身", + "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": "請只選擇一個關鍵字以重新命名", + "Copied as text: paste it in a keyword box to give the keywords to photos": "已複製為文字:貼到關鍵字欄位中即可將這些關鍵字指定給照片", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level": "已複製:「貼上」位於資料夾的選單中;要貼到最上層,請使用「相簿」的 + 選單", + "Create Keyword Tag Inside…": "在其中建立關鍵字標記…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level": "已剪下:「貼上」位於資料夾的選單中;要貼到最上層,請使用「相簿」的 + 選單", + "Cut: Paste is in the menu of the keyword they go inside": "已剪下:「貼上」位於要放入的關鍵字的選單中", + "Delete Albums": "刪除相簿", + "Delete Folder": "刪除資料夾", + "Delete Keywords": "刪除關鍵字", + "Duplicate Album": "複製相簿", + "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": "其中一個是整個磁碟:請單獨移除磁碟", + "Paste Inside This Keyword": "貼到此關鍵字中", + "Paste Into This Folder": "貼到此資料夾", + "Paste at Top Level": "貼到最上層", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "照片仍保留在「所有照片」中。刪除資料夾也會刪除其中的相簿。此操作可以復原。", + "Remove Folder Color Label": "移除資料夾色彩標籤", + "Remove Folders from Library": "從照片庫移除資料夾", + "Set Folder Color Label": "設定資料夾色彩標籤", + "That includes the photos in the folders inside them.": "其中也包括這些資料夾內各子資料夾中的照片。", + "The photos stay in All Photos. Undo brings the albums back.": "照片仍保留在「所有照片」中。復原即可還原這些相簿。", "Remove from Library…": "從照片庫移除…", "This Computer": "這部電腦", "includes the folders inside it": "包含其中的資料夾", diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 9ba1cd5afb3..2b2332aeb6f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -386,6 +386,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 4fc9daddaa8..b441ee6e6da 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -31,6 +31,7 @@ pub mod menubar; pub mod menus; pub mod merge; mod model_setup; +pub mod multi_select; pub mod panels; pub mod pick; pub mod print_view; @@ -157,6 +158,8 @@ mod tests_menubar; #[cfg(test)] mod tests_merge_preview; #[cfg(test)] +mod tests_multi_select; +#[cfg(test)] mod tests_offline; #[cfg(test)] mod tests_open_lightroom; @@ -941,19 +944,22 @@ impl LightcraftApp { /// not drop `run`'s result (`let _ = app.run(…)`), nor `let _ = app.session.execute(…)`, which /// goes round this, unless a comment says why: `// refusal expected: `. pub fn act(&mut self, id: &str, params: Value) -> Option { + self.act_told(id, params).ok() + } + + /// [`Self::act`] for a caller that hands the whole error on (a dialog's confirmation answers the control channel + /// with it): the person is told the reason by a toast all the same. + pub(crate) fn act_told(&mut self, id: &str, params: Value) -> Result { let before = self.ui.toast.clone(); - match self.run_told(id, params) { - Ok(v) => Some(v), - Err(refusal) => { - let now = self.tick_now(); - // A toast the command made itself (a partial import report) says what did happen: - // keep it ahead of the reason rather than replacing it. - let made = self.ui.toast.take().filter(|t| Some(t) != before.as_ref()).map(|t| t.0); - let said = refusal_toast(made, &refusal); - self.ui.toast = Some((said, now + REFUSAL_SECONDS, None)); - None - } - } + self.run_told(id, params).map_err(|refusal| { + let now = self.tick_now(); + // A toast the command made itself (a partial import report) says what did happen: + // keep it ahead of the reason rather than replacing it. + let made = self.ui.toast.take().filter(|t| Some(t) != before.as_ref()).map(|t| t.0); + let said = refusal_toast(made, &refusal); + self.ui.toast = Some((said, now + REFUSAL_SECONDS, None)); + refusal.error + }) } /// Run a command whose refusal is expected here and means nothing to the person (it is @@ -2282,6 +2288,8 @@ 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); + // (what the sidebar lists took over of the keys is given back before the shortcuts look at them) + 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/multi_select.rs b/crates/ui-egui/src/multi_select.rs new file mode 100644 index 00000000000..c4d22c91c7b --- /dev/null +++ b/crates/ui-egui/src/multi_select.rs @@ -0,0 +1,219 @@ +//! 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 last one clicked 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…). + +/// 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 (a row inside a closed level is not among them, so a range never takes rows +/// that are not in sight); `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) { + self.rows = std::mem::take(&mut self.seen); + } + /// 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 and (on a Mac) Ctrl alone ask 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"))); + } + + #[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/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index f26b4332556..b2ff403c7da 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -252,6 +252,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { Dialog::KeywordTag { editing: None, .. } => "Create Keyword Tag", Dialog::KeywordTag { .. } => "Edit Keyword Tag", Dialog::DeleteKeyword { .. } => "Delete Keyword", + Dialog::Several(s) => super::side_select::several_title(s), Dialog::MoveKeyword { .. } => "Merge Keywords", Dialog::KeywordSet { .. } => "Edit Keyword Set", Dialog::MergeKeywords { .. } => "Merge Keywords", @@ -1262,6 +1263,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { }; 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::Several(s) => super::side_select::several_body(ui, s), Dialog::DeleteKeyword { keyword, count } => { let name = keyword.replace('|', " › "); ui.label(crate::i18n::tr_format!("Delete the keyword “{name}”?", name = name)); @@ -1439,6 +1441,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { Dialog::KeywordTag { editing: None, .. } => "Create", Dialog::KeywordTag { .. } => "Save", Dialog::RemoveFolder { .. } => "Remove", + Dialog::Several(s) => super::side_select::several_button(s), Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), Dialog::SynchronizeFolder { .. } if informational => "Close", @@ -1562,6 +1565,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { { 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(_)) => close = 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, .. } = &mut dlg { @@ -2028,6 +2034,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result app.run("keyword.delete", json!({"keyword": keyword})), + Dialog::Several(s) => super::side_select::several_run(app, s), Dialog::KeywordSet { replaces, name, slots, as_new } => { use lightcraft_catalog::keywords::same; let name = name.trim(); @@ -2497,7 +2504,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/grid.rs b/crates/ui-egui/src/panels/grid.rs index 45a731fe8c9..be120e86c80 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1301,7 +1301,9 @@ pub fn context_menu(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 1874f2f8afc..dead39e5e2e 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())); @@ -79,7 +83,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 +101,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(); @@ -129,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| { @@ -144,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())); @@ -164,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) { @@ -175,10 +216,12 @@ 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); + 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)); } @@ -284,9 +327,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)); @@ -351,6 +395,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)); @@ -386,6 +435,9 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[Pho app.act("library.filter", json!({"keyword": path})); } ui.separator(); + super::side_select::keyword_clip_items(app, ui, &[path.to_string()]); + super::side_select::keyword_paste_item(app, ui, path); + ui.separator(); if item(ui, "purge", crate::i18n::tr("Purge Unused Keywords"), true) { app.act("keyword.purgeUnused", json!({})); } @@ -572,7 +624,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/left.rs b/crates/ui-egui/src/panels/left.rs index 0b668e9a042..d005b992727 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -634,6 +634,8 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { if ui.button(crate::i18n::tr("Create Folder…")).clicked() { app.ui.dialog = Some(crate::state::Dialog::NewAlbum { name: String::new(), folder: true, parent: None, include_selected: false }); } + // albums taken with Cut or Copy go to the top level from here + super::side_select::album_paste_item(app, ui, None); // only once the albums were put in an order by hand if app.session.catalog.album_children_are_ordered(None) { ui.separator(); @@ -648,6 +650,7 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { 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 @@ -1228,15 +1231,14 @@ fn folder_tree( 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 = super::side_select::date_shown(app, key); + app.ui.side.dates.saw(key.to_string()); let resp = row(app, ui, &format!("date:{key}"), Icon::Clock, label, Some(count), sel, indent); if key.len() < 10 { tree_toggle(ui, &resp, indent, open_id, &mut open, format!("dateToggle:{key}")); } if resp.clicked() { - let v = if sel { serde_json::Value::Null } else { json!(key) }; - browse_all_photos(app, !sel); - app.act("library.filter", json!({"date": v})); + super::side_select::date_clicked(app, ui, key); } open } @@ -1296,7 +1298,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 = super::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)(); @@ -1309,6 +1312,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let problems = app.caches.smart_album_problems(&app.session.catalog).get(&a.id).cloned().unwrap_or_default(); let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let mut resp = row_sensed(app, ui, &format!("album:{}", a.id.0), icon, &label, None, Some(n), sel, indent, Sense::click_and_drag(), None); + super::side_select::outline(app, ui, super::side_select::SideList::Albums, sel, resp.rect, 8.0); if !problems.is_empty() { crate::widgets::register(ui, format!("albumProblem:{}", a.id.0), resp.rect); } @@ -1333,7 +1337,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare resp = resp.on_hover_text(tip); } if resp.clicked() { - app.act("library.source", json!({"kind": "album", "id": a.id.0})); + super::side_select::album_clicked(app, ui, a.id); } folder_menu(app, &resp, a); } @@ -1442,14 +1446,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 = super::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 = super::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); } @@ -1590,6 +1609,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 = super::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( @@ -1649,6 +1671,11 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response 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 = super::side_select::album_targets(app, a.id); + if several.len() > 1 { + return super::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| { @@ -1783,6 +1810,10 @@ fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) { } } }); + super::side_select::album_clip_items(app, ui, &[a.id.0]); + if a.folder { + super::side_select::album_paste_item(app, ui, Some(a.id)); + } if ui.button(crate::i18n::tr("Rename…")).clicked() { app.ui.dialog = Some(crate::state::Dialog::RenameAlbum { id: a.id.0, name: a.name.clone() }); } @@ -1864,10 +1895,14 @@ fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], 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 && super::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); @@ -1877,10 +1912,17 @@ fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], /// 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)); +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)), @@ -1889,6 +1931,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_sensed(app, ui, id, Icon::Folder, name, Some(&spoken), Some(n.count), sel, indent, Sense::click(), mark); folder_drop_target(app, ui, &resp, n, open_id, open); + super::side_select::outline(app, ui, super::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)); @@ -1900,8 +1943,7 @@ fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &s let resp = resp.on_hover_text(tip); if resp.clicked() && !toggled { if n.selectable { - // a source like an album or a Local folder: it replaces what the grid showed - app.act("library.source", json!({"kind": "libraryFolder", "path": n.path})); + super::side_select::folder_clicked(app, ui, &n.path); } else { *open = !*open; set_tree_open(ui, open_id, *open); @@ -2041,6 +2083,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 = super::side_select::folder_targets(app, &n.path); + if several.len() > 1 { + crate::widgets::context_menu(resp, |ui| super::side_select::folders_menu(app, ui, &several)); + return; + } if !n.volume { folder_menu_for_library(app, resp, n); } else if n.path != "/" { @@ -2217,8 +2265,10 @@ fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[KeywordNode 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 = super::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); @@ -2227,19 +2277,32 @@ fn keyword_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[KeywordNode } /// 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)); +#[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(app, ui, id, Icon::Tag, &n.name, Some(n.count), sel, indent); + super::side_select::outline(app, ui, super::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)); } 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); - app.act("library.filter", json!({"keyword": v})); + super::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 = super::side_select::keyword_targets(app, &n.path); + if several.len() > 1 { + return super::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() { app.act("photo.setMeta", json!({"addKeywords": [n.path]})); @@ -2248,6 +2311,8 @@ fn keyword_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &KeywordNode, id: app.act("photo.setMeta", json!({"removeKeywords": [n.path]})); } ui.separator(); + super::side_select::keyword_clip_items(app, ui, std::slice::from_ref(&n.path)); + super::side_select::keyword_paste_item(app, ui, &n.path); if ui.button(crate::i18n::tr("Rename Keyword…")).clicked() { app.ui.dialog = Some(crate::state::Dialog::RenameKeyword { from: n.path.clone(), to: n.path.clone() }); } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index e3300e04f14..4bc375a3302 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -32,6 +32,7 @@ pub mod rules_editor; pub mod rules_move; pub mod second; pub mod settings; +pub mod side_select; pub mod slide_layout; pub mod slide_overlays; pub mod slide_templates; 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..b884e2e2220 --- /dev/null +++ b/crates/ui-egui/src/panels/side_select.rs @@ -0,0 +1,745 @@ +//! 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, 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 +//! 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, 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. + 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, + /// What Cut or Copy in a sidebar menu took, for Paste in another row's menu. + pub clip: Option, +} + +/// Sidebar rows taken with Cut or Copy. +#[derive(Clone, Debug, PartialEq)] +pub enum SideClip { + /// Albums and folders of albums: Paste moves them (`cut`) or makes copies of them. + Albums { ids: Vec, cut: bool }, + /// Keywords that were cut: Paste nests them inside another keyword. (Copied keywords are text + /// on the system clipboard, for a keyword box.) + Keywords { keywords: Vec }, +} + +/// A confirmation before something happens to several rows at once. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum Several { + /// Delete albums and folders of albums: `albums` and `folders` of them named, with `inside` + /// more albums and folders inside those folders. + DeleteAlbums { ids: Vec, albums: usize, folders: usize, inside: usize }, + /// 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 +} +// (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)) +} + +/// 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() }; + } + 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 only while several 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() { + 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; +} + +/// 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(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 => { + 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; + s.albums.begin_frame(); + s.folders.begin_frame(); + s.keywords.begin_frame(); + s.dates.begin_frame(); +} + +// ---- Albums + +/// Whether album (or folder of albums) `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); + take_keys(app, SideList::Albums, how, albums_shown(app).len()); +} + +/// 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})), + }; +} + +/// 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 (and folders of 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(); + } + } + }); + album_clip_items(app, ui, ids); + 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("Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.")); + if delete.clicked() { + app.ui.dialog = Some(delete_albums_dialog(app, ids)); + ui.close(); + } +} + +/// The confirmation for deleting several albums: what is named, and what goes with the folders. +pub(crate) fn delete_albums_dialog(app: &LightcraftApp, ids: &[u64]) -> Dialog { + let cat = &app.session.catalog; + let named: Vec = ids.iter().map(|i| AlbumId(*i)).collect(); + let folders = named.iter().filter(|a| cat.album(**a).is_some_and(|a| a.folder)).count(); + let inside = cat + .albums() + .filter(|a| !named.contains(&a.id)) + .filter(|a| { + // inside one of the folders named, at any depth (a ring, in a damaged library, ends the walk) + let mut cur = a.parent; + for _ in 0..=cat.albums().count() { + match cur { + Some(p) if named.contains(&p) => return true, + Some(p) => cur = cat.album(p).and_then(|a| a.parent), + None => return false, + } + } + false + }) + .count(); + Dialog::Several(Several::DeleteAlbums { ids: ids.to_vec(), albums: named.len() - folders, folders, inside }) +} + +// ---- 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})), + }; + 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) + +/// 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})), + }; + 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. +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 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(); + keyword_clip_items(app, ui, keywords); + 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 `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()); + } + } + 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); + 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) +} + +// ---- Cut, Copy and Paste + +/// Cut and Copy for these albums, in an album's menu or the menu of several. +pub(crate) fn album_clip_items(app: &mut LightcraftApp, ui: &mut egui::Ui, ids: &[u64]) { + for (id, label, cut) in [("clip:cut", "Cut", true), ("clip:copy", "Copy", false)] { + if item(ui, id, crate::i18n::tr(label).to_string(), true).clicked() { + let names: Vec = ids.iter().filter_map(|i| app.session.catalog.album(AlbumId(*i))).map(|a| a.name.clone()).collect(); + // their names too, for wherever text is pasted + ui.ctx().copy_text(names.join("\n")); + app.ui.side.clip = Some(SideClip::Albums { ids: ids.to_vec(), cut }); + let said = if cut { + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level" + } else { + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level" + }; + app.toast(ui.ctx(), crate::i18n::tr(said).to_string()); + ui.close(); + } + } +} + +/// Paste for albums taken with Cut or Copy, into folder `parent` (`None`: the top level). Only +/// there while albums are held; cut albums move (one step), copied ones are duplicated. +pub(crate) fn album_paste_item(app: &mut LightcraftApp, ui: &mut egui::Ui, parent: Option) { + let Some(SideClip::Albums { ids, cut }) = app.ui.side.clip.clone() else { return }; + // what is still there + let ids: Vec = ids.into_iter().filter(|i| app.session.catalog.album(AlbumId(*i)).is_some()).collect(); + let label = if parent.is_some() { "Paste Into This Folder" } else { "Paste at Top Level" }; + // cut albums can't move into one of themselves, or into a folder inside one + let cat = &app.session.catalog; + let inside_itself = cut + && parent.is_some_and(|mut at| { + for _ in 0..=cat.albums().count() { + if ids.contains(&at.0) { + return true; + } + match cat.album(at).and_then(|a| a.parent) { + Some(p) => at = p, + None => break, + } + } + false + }); + let paste = item(ui, "clip:paste", crate::i18n::tr(label).to_string(), !ids.is_empty() && !inside_itself) + .on_disabled_hover_text(crate::i18n::tr("A folder can't go inside itself")); + if !paste.clicked() { + return; + } + let to = parent.map(|p| p.0); + if cut { + if app.act("album.move", json!({"ids": ids, "parent": to})).is_some() { + // moved: there is nothing left to paste + app.ui.side.clip = None; + app.ui.reveal_album = ids.last().copied(); + } + } else if let Some(r) = app.act("album.duplicate", json!({"ids": ids, "parent": to})) { + app.ui.reveal_album = r["ids"].as_array().and_then(|a| a.last()).and_then(serde_json::Value::as_u64); + } + ui.close(); +} + +/// Cut and Copy for these keywords, in a keyword's menu or the menu of several. Copy puts them on +/// the system clipboard as text (`a, b|c`), which a keyword box takes to give them to photos. +pub(crate) fn keyword_clip_items(app: &mut LightcraftApp, ui: &mut egui::Ui, keywords: &[String]) { + if item(ui, "clip:cut", crate::i18n::tr("Cut").to_string(), true).clicked() { + app.ui.side.clip = Some(SideClip::Keywords { keywords: keywords.to_vec() }); + app.toast(ui.ctx(), crate::i18n::tr("Cut: Paste is in the menu of the keyword they go inside").to_string()); + ui.close(); + } + if item(ui, "clip:copy", crate::i18n::tr("Copy").to_string(), true).clicked() { + ui.ctx().copy_text(keywords.join(", ")); + app.toast(ui.ctx(), crate::i18n::tr("Copied as text: paste it in a keyword box to give the keywords to photos").to_string()); + ui.close(); + } +} + +/// Paste for keywords that were cut, inside keyword `parent`: they are nested there, as one +/// step. Only there while keywords are held, and not on one of them. +pub(crate) fn keyword_paste_item(app: &mut LightcraftApp, ui: &mut egui::Ui, parent: &str) { + let Some(SideClip::Keywords { keywords }) = app.ui.side.clip.clone() else { return }; + let keywords: Vec = keywords.into_iter().filter(|k| app.session.catalog.has_keyword(k)).collect(); + let inside_itself = keywords.iter().any(|k| lightcraft_catalog::keywords::is_under(parent, k)); + let paste = item(ui, "clip:paste", crate::i18n::tr("Paste Inside This Keyword").to_string(), !keywords.is_empty() && !inside_itself) + .on_disabled_hover_text(crate::i18n::tr("A keyword can't go inside itself")); + if !paste.clicked() { + return; + } + let params = match keywords.as_slice() { + [one] => json!({"keyword": one, "parent": parent}), + many => json!({"keywords": many, "parent": parent}), + }; + if app.act("keyword.move", params).is_some() { + app.ui.side.clip = None; + let into = app.session.catalog.keyword_path(parent).unwrap_or_else(|| parent.to_string()); + // the upper ones moved, and what is below them with them + for k in keywords.iter().filter(|k| !keywords.iter().any(|o| !same_keyword(o, k) && lightcraft_catalog::keywords::is_under(k, o))) { + let leaf = k.rsplit('|').next().unwrap_or(k); + super::keyword_list::follow(app, k, &format!("{into}|{leaf}")); + } + } + ui.close(); +} + +// ---- 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) { + 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 { albums, folders, inside, .. } => { + let n = albums + folders; + ui.label(if *folders == 0 { + crate::i18n::tr_format!("Delete {n} albums?", n = n) + } else { + crate::i18n::tr_format!("Delete {n} albums and folders of albums?", n = n) + }); + if *inside > 0 { + dim(ui, crate::i18n::tr_format!("{inside} more inside the folders go too.", inside = inside)); + } + dim(ui, crate::i18n::tr("The photos stay in All Photos. Undo brings the albums back.").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 bddf63149c4..e513a414ab0 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -621,6 +621,10 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) { R::RedEye => continue, _ => {} } + // several sidebar rows just chosen with Cmd/Shift+click: it asks about them + if crate::panels::side_select::delete_asked(app, ctx) { + continue; + } // 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) if crate::menus::delete_in_album(app, ctx) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e365c4c7755..1b0d20e732f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1053,6 +1053,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>, @@ -1250,6 +1254,8 @@ pub enum Dialog { /// Photos that have it (or one below it). count: usize, }, + /// Delete or remove several sidebar rows at once (albums, keywords, folders), after asking. + Several(crate::panels::side_select::Several), /// Merge keywords into another one on every photo. MergeKeywords { from: Vec, @@ -1593,6 +1599,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_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 new file mode 100644 index 00000000000..e8d37d08cd9 --- /dev/null +++ b/crates/ui-egui/src/tests_multi_select.rs @@ -0,0 +1,743 @@ +//! 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, 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; 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. +//! - Given an album copied from its menu, when Paste is chosen in a folder's menu, then a copy +//! of it is inside the folder and the original stays; given albums cut, then Paste moves them +//! (one step) and there is nothing left to paste. +//! - Given keywords cut in the Keyword List, when Paste is chosen in another keyword's menu, then +//! they are nested inside it; Copy puts their names on the clipboard as text. + +use std::time::Duration; + +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}; + +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})); +} +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 { + 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"); + // 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(); + 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, &format!("source:folder:{folder}")); + shift_click(&mut h, &row(after)); + let chosen = shown(&h); + assert!(chosen.contains(&folder) && chosen.contains(&after), "{chosen:?}"); + 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], albums: 2, folders: 0, inside: 0 }))); + 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 the_question_before_deleting_albums_counts_what_is_inside_the_folders() { + let mut h = app("info"); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + let one = album(&mut h, "Sel In 1", Some(folder), &[]); + album(&mut h, "Sel In 2", Some(folder), &[]); + let loose = album(&mut h, "Sel Loose", None, &[]); + let d = crate::panels::side_select::delete_albums_dialog(&h.app, &[folder, loose, one]); + assert_eq!(d, Dialog::Several(Several::DeleteAlbums { ids: vec![folder, loose, one], albums: 2, folders: 1, inside: 1 })); +} + +#[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"); + 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 + }); + 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"); + 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_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"); + 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!(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 + 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])); + 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) +} + +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(); + 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()); +} + +#[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], albums: 2, folders: 0, inside: 0 }))); + 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); +} + +#[test] +fn copy_and_paste_duplicates_an_album_and_cut_and_paste_moves_several() { + use crate::panels::side_select::SideClip; + let mut h = app("info"); + let ([a, b, c, _], ids) = four_albums(&mut h); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + let folder_row = format!("source:folder:{folder}"); + let inside = |h: &Headless| -> Vec { + let mut n: Vec = h.app.session.catalog.albums().filter(|x| x.parent == Some(AlbumId(folder))).map(|x| x.name.clone()).collect(); + n.sort(); + n + }; + // nothing held: a folder's menu has no Paste + right_click(&mut h, &folder_row); + assert!(has(&h, "sideMenu:clip:copy") && !has(&h, "sideMenu:clip:paste")); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + // Copy one album, Paste into the folder: a copy, and the original stays + right_click(&mut h, &row(b)); + click(&mut h, "sideMenu:clip:copy"); + assert_eq!(h.app.ui.side.clip, Some(SideClip::Albums { ids: vec![b], cut: false })); + assert_eq!(h.app.copied.as_deref(), Some("Sel B"), "its name is on the clipboard as text"); + right_click(&mut h, &folder_row); + click(&mut h, "sideMenu:clip:paste"); + assert_eq!(inside(&h), vec!["Sel B"]); + assert_eq!(h.app.session.catalog.album(AlbumId(b)).unwrap().parent, None, "the original stays"); + let copy = h.app.session.catalog.albums().find(|x| x.parent == Some(AlbumId(folder))).unwrap(); + assert_eq!(copy.photos.iter().map(|p| p.0).collect::>(), vec![ids[1]], "with its photos"); + assert!(h.app.ui.side.clip.is_some(), "what was copied can be pasted again"); + // Cut two albums chosen together, Paste: both move, as one step, and nothing is held any more + click(&mut h, &row(a)); + cmd_click(&mut h, &row(c)); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:clip:cut"); + assert_eq!(h.app.ui.side.clip, Some(SideClip::Albums { ids: vec![a, c], cut: true })); + let undo = h.app.session.undo.len(); + right_click(&mut h, &folder_row); + click(&mut h, "sideMenu:clip:paste"); + assert_eq!(inside(&h), vec!["Sel A", "Sel B", "Sel C"]); + assert_eq!(h.app.session.undo.len(), undo + 1, "one step"); + assert_eq!(h.app.ui.side.clip, None); + right_click(&mut h, &folder_row); + assert!(!has(&h, "sideMenu:clip:paste")); +} + +#[test] +fn cut_and_paste_nests_keywords_and_copy_puts_them_on_the_clipboard() { + use crate::panels::side_select::SideClip; + let (mut h, ids) = keyword_list(); + click(&mut h, "keywordRow:Sel K1"); + cmd_click(&mut h, "keywordRow:Sel K3"); + right_click(&mut h, "keywordRow:Sel K3"); + click(&mut h, "sideMenu:clip:copy"); + assert_eq!(h.app.copied.as_deref(), Some("Sel K1, Sel K3")); + assert_eq!(h.app.ui.side.clip, None, "copied keywords are text, nothing is held to paste here"); + right_click(&mut h, "keywordRow:Sel K3"); + click(&mut h, "sideMenu:clip:cut"); + assert_eq!(h.app.ui.side.clip, Some(SideClip::Keywords { keywords: vec!["Sel K1".to_string(), "Sel K3".to_string()] })); + let undo = h.app.session.undo.len(); + right_click(&mut h, "keywordRow:Sel Parent"); + click(&mut h, "sideMenu:clip:paste"); + 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!(h.app.ui.side.clip, None); + assert_eq!(picked(&h), vec!["Sel Parent|Sel K1", "Sel Parent|Sel K3"], "still picked, where they are now"); +} + +// ---- 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() { + 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); +} + +/// 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(); + 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"]); + right_click(&mut h, "keywordRow:Sel K1"); + assert!(has(&h, "keywordMenu:delete") && !has(&h, "sideMenu:keywords:delete"), "one keyword's menu"); +} + +/// Cut albums are not pasted into one of themselves. +#[test] +fn cut_albums_are_not_pasted_into_themselves() { + let mut h = app("info"); + let folder = run(&mut h, "album.create", json!({"name": "Sel Folder", "folder": true}))["id"].as_u64().unwrap(); + let inner = run(&mut h, "album.create", json!({"name": "Sel Inner", "folder": true, "parent": folder}))["id"].as_u64().unwrap(); + right_click(&mut h, &format!("source:folder:{folder}")); + click(&mut h, "sideMenu:clip:cut"); + let undo = h.app.session.undo.len(); + for target in [folder, inner] { + right_click(&mut h, &format!("source:folder:{target}")); + assert!(has(&h, "sideMenu:clip:paste")); + click(&mut h, "sideMenu:clip:paste"); + assert_eq!(h.app.session.undo.len(), undo, "greyed out: nothing happens"); + assert!(h.app.ui.side.clip.is_some()); + ask(&mut h, "ui.key", json!({"key": "Escape"})); + } +} + +/// Another library's albums are not what was cut in this one. +#[test] +fn what_was_cut_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)); + right_click(&mut h, &row(c)); + click(&mut h, "sideMenu:clip:cut"); + assert!(h.app.ui.side.clip.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.clip.is_none() && h.app.ui.side.keys.is_none()); +} + +/// The menus and questions for several rows: in the nine languages LightCraft had when this was written, none of the words stay +/// English. (A string with no entry in a language's catalog is shown as written, so nothing else fails when +/// one is forgotten. A language added later is not asked for them here: it shows them in English until it +/// is translated.) +#[test] +fn the_words_of_several_rows_at_once_are_in_every_language() { + let words = [ + "A folder can't go inside itself", + "A keyword can't go inside itself", + "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", + "Copied as text: paste it in a keyword box to give the keywords to photos", + "Copied: Paste is in a folder's menu, and in the Albums + menu for the top level", + "Create Keyword Tag Inside…", + "Cut: Paste is in a folder's menu, and in the Albums + menu for the top level", + "Cut: Paste is in the menu of the keyword they go inside", + "Delete Albums", + "Delete Folder", + "Delete Keywords", + "Duplicate Album", + "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", + "Paste Inside This Keyword", + "Paste Into This Folder", + "Paste at Top Level", + "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.", + "Remove Folder Color Label", + "Remove Folders from Library", + "Set Folder Color Label", + "That includes the photos in the folders inside them.", + "The photos stay in All Photos. Undo brings the albums back.", + ]; + use crate::i18n::Locale::{Cs, De, Es, Fr, It, Ja, Ka, Pl, PtBr, Ru, Uk, ZhHans, ZhHant}; + for language in [Cs, De, Es, Fr, It, Ja, Ka, Pl, PtBr, Ru, Uk, ZhHans, ZhHant] { + for word in words { + assert_ne!(language.tr(word), word, "{language:?} has no entry for {word:?}"); + } + } +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 69464e9b8a6..3cd71ac48fd 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -94,7 +94,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-ALLPHOTOS | All photos | P0 | ✅ | `cmd:library.source`, `crates/ui-egui/src/panels/left.rs` | | | LR-LIB-RECENT-ADDED | Recently added | P1 | ✅ | `cmd:library.source` (`recentlyAdded`), `crates/engine/src/view.rs` (`RECENT_DAYS`) | photos imported in the 30 days up to the latest import, newest import first, grouped by import day | | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | -| LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests_albums_local.rs`, `crates/ui-egui/src/tests_panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | +| LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.duplicate`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests_albums_local.rs`, `crates/ui-egui/src/tests_panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests_panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | | LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | @@ -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`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `crates/engine/src/tests_multi_source.rs` | photos in the grid; 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`), `cmd:album.delete` / `cmd:album.move` / `cmd:album.duplicate` (`ids`), `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_multi_source.rs`, `crates/engine/src/tests_batch_sidebar.rs` | photos in the grid; and rows of the sidebars' lists: Cmd/Ctrl+click adds or takes away a row, Shift+click takes the rows between (as drawn: none inside a closed level), Cmd/Ctrl+Shift+click adds a range. Albums, Folders, Keywords and By Date in the left panel then show the photos of any of the rows chosen (albums and folders as the source, keywords and dates as the filter); in the Keyword List several keywords are picked. A plain click is unchanged. The menu of one of several rows acts on them all, as one undo step: Move to, Delete… and Export for albums, Color Label and Remove from Library… for folders, Add to / Remove from Selected Photos, Merge into… and Delete… for keywords; deleting or removing several asks first. Dragging one of several albums or keywords moves them all. Delete (the photos' delete shortcut) asks about several rows just chosen with Cmd/Shift+click, until the next click anywhere or any other change to what is shown or selected; after a plain click it stays the photos'. Cut / Copy / Paste in the menus: albums move or are duplicated into a folder or the top level, cut keywords are nested inside another, copied keywords are text for a keyword box. Not yet: several Local folders at once, arrow keys and Select All in a sidebar list, cut/copy/paste shortcuts there, an any/all switch for several keywords (it is any), Synchronize for several folders | | 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` | | @@ -960,3 +960,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 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-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-10-22 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars; their menus, drags, Delete and Cut / Copy / Paste act on them all; LR-LIB-ALBUM cites `album.duplicate`; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index 6d623fb23e2..dbfbfe3e9e6 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -846,6 +846,28 @@ is a larger target that lights up on its own, and taking a keyword off several photos at once now says which keyword left how many photos, and that Edit ▸ Undo puts it back. +### Several albums, folders, keywords or dates at once +- 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. The grid + shows the photos of any of them, each once. A plain click chooses one row alone, as before. +- In the Keyword List (right panel ▸ Keywords) the same clicks pick several keywords. +- 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 colour 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 neighbours 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. +- Cut, Copy and Paste in the albums' and keywords' menus: cut albums move into the folder where you choose Paste + (the Albums + menu pastes at the top level), copied albums are duplicated there with their photos; cut keywords + are nested inside the keyword where you choose Paste; copied keywords are text you can paste in a keyword box. +- For agents: `library.source` takes `ids` (albums) or `paths` (folders), `library.filter` takes `keywords` and + `dates`; `album.delete`, `album.move` and the new `album.duplicate` take `ids`, `keyword.delete` and + `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`. `library.state` lists + `albums` and `libraryFolders`. + ### HDR and panorama merges of CR2 keep their colour - Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come From 54a42970ffcd89e60d2da8ba5e9fe42a17154965 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 11:55:35 -0400 Subject: [PATCH 27/30] LR-BEHAV-MULTISELECT: 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, acting only on what 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. Waiting rows name what they are about (Request::subject, kept by Retry). Co-Authored-By: Claude --- crates/engine/src/activity.rs | 13 +- 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/control.rs | 3 +- crates/ui-egui/src/headless.rs | 1 + crates/ui-egui/src/import.rs | 2 +- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/panels/activity.rs | 7 +- crates/ui-egui/src/panels/dialogs.rs | 11 +- crates/ui-egui/src/panels/side_select.rs | 10 +- crates/ui-egui/src/state.rs | 44 +++ crates/ui-egui/src/sync.rs | 366 +++++++++++++++++++- crates/ui-egui/src/tests_drop_import.rs | 6 +- crates/ui-egui/src/tests_multi_select.rs | 1 - crates/ui-egui/src/tests_sync.rs | 177 +++++++++- docs/background-tasks.md | 5 +- docs/control-protocol.md | 2 +- docs/parity-checklist.md | 5 +- docs/whats-new.md | 10 + 53 files changed, 990 insertions(+), 72 deletions(-) diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 45d0e59e04e..13d1dfb19eb 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 a task retried says it 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] @@ -715,8 +718,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 64abdda53de..5f326fa9687 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -127,7 +127,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 35c2ff01689..0db25334fa6 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 d1ed08ae85a..4f731a5a213 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…a dalších {n}", "{n} keywords": "Klíčová slova: {n}", "{n} albums": "Alba: {n}", - "{n} folders": "Složky: {n}" + "{n} folders": "Složky: {n}", + "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 5b51bcfbc6f..694b2d427e2 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2415,7 +2415,6 @@ "A keyword can't go inside itself": "Klíčové slovo nelze vložit do sebe samého", "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", @@ -2436,5 +2435,16 @@ "Paste at Top Level": "Vložit na nejvyšší úroveň", "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í.", + "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 796a57d0459..a6d5d067e4c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…und {n} weitere", "{n} keywords": "{n} Stichwörter", "{n} albums": "{n} Alben", - "{n} folders": "{n} Ordner" + "{n} folders": "{n} Ordner", + "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 Filialdatei" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index a3825fc2e8a..f6699e5f130 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1231,7 +1231,6 @@ "A keyword can't go inside itself": "Ein Stichwort kann nicht in sich selbst liegen", "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", @@ -3468,5 +3467,16 @@ "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", - "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 680098dc304..63be21933f5 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…y {n} más", "{n} keywords": "{n} palabras clave", "{n} albums": "{n} álbumes", - "{n} folders": "{n} carpetas" + "{n} folders": "{n} carpetas", + "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: solo caben {n} más en la cola", + "Synchronize {n} Folders…": "Sincronizar {n} carpetas…", + "{n} new": "{n} nuevas", + "{n} moved": "{n} movidas", + "{n} missing": "{n} que faltan", + "{n} with changed sidecars": "{n} con archivo complementario cambiado" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 36cde7eba86..9ef874f2cc0 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1238,7 +1238,6 @@ "A keyword can't go inside itself": "Una palabra clave no puede ir dentro de sí misma", "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", @@ -2389,5 +2388,16 @@ "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", - "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": "Esperando a ser examinada", + "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 85a4961c382..fe47cee9fc2 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…ja {n} muuta", "{n} keywords": "{n} avainsanaa", "{n} albums": "{n} albumia", - "{n} folders": "{n} kansiota" + "{n} folders": "{n} kansiota", + "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": "{n} uutta", + "{n} moved": "{n} siirretty", + "{n} missing": "{n} puuttuu", + "{n} with changed sidecars": "{n} muuttunutta sivutiedostoa" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index aa370e39ad8..9ae4a6d0eea 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2334,7 +2334,6 @@ "A keyword can't go inside itself": "Avainsana ei voi siirtyä itsensä sisään", "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", @@ -2355,5 +2354,16 @@ "Paste at Top Level": "Liitä ylätasolle", "Remove Folders from Library": "Poista kansiot kirjastosta", "That includes the photos in the folders inside them.": "Mukana ovat niiden sisällä olevien kansioiden 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.", + "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 3d2c0e0da6a..e3ba2c44b21 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…et {n} de plus", "{n} keywords": "{n} mots-clés", "{n} albums": "{n} albums", - "{n} folders": "{n} dossiers" + "{n} folders": "{n} dossiers", + "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 : seulement {n} de plus peuvent attendre", + "Synchronize {n} Folders…": "Synchroniser {n} dossiers…", + "{n} new": "{n} nouvelles", + "{n} moved": "{n} déplacées", + "{n} missing": "{n} manquantes", + "{n} with changed sidecars": "{n} avec fichier annexe modifié" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index b7033daa145..9ed5209e90f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1172,7 +1172,6 @@ "A keyword can't go inside itself": "Un mot-clé ne peut pas aller dans lui-même", "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", @@ -2421,5 +2420,16 @@ "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", - "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 898afe84657..e688e4dc173 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…dan {n} lagi", "{n} keywords": "{n} kata kunci", "{n} albums": "{n} album", - "{n} folders": "{n} folder" + "{n} folders": "{n} folder", + "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 b526dcc7d19..faf9d5c06c4 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2346,7 +2346,6 @@ "A keyword can't go inside itself": "Kata kunci tidak bisa dimasukkan ke dalam dirinya sendiri", "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", @@ -2367,5 +2366,16 @@ "Paste at Top Level": "Tempel di tingkat teratas", "Remove Folders from Library": "Hapus folder dari pustaka", "That includes the photos in the folders inside them.": "Itu mencakup foto di folder-folder 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.", + "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 2e6ae6e5f61..d33020d56d1 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…e altri {n}", "{n} keywords": "{n} parole chiave", "{n} albums": "{n} album", - "{n} folders": "{n} cartelle" + "{n} folders": "{n} cartelle", + "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: ne possono attendere solo altre {n}", + "Synchronize {n} Folders…": "Sincronizza {n} cartelle…", + "{n} new": "{n} nuove", + "{n} moved": "{n} spostate", + "{n} missing": "{n} mancanti", + "{n} with changed sidecars": "{n} con file collaterale cambiato" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 56e82b6ac22..e7bb8823c79 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2368,7 +2368,6 @@ "A keyword can't go inside itself": "Una parola chiave non può andare dentro sé stessa", "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", @@ -2389,5 +2388,16 @@ "Paste at Top Level": "Incolla al livello superiore", "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.", + "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 analisi", + "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 d5378d01703..4effe972d47 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…ほか{n}個", "{n} keywords": "{n}個のキーワード", "{n} albums": "{n}個のアルバム", - "{n} folders": "{n}個のフォルダ" + "{n} folders": "{n}個のフォルダ", + "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 cf183cac13e..5463d48e918 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -1656,7 +1656,6 @@ "A keyword can't go inside itself": "キーワードをそのキーワード自身の中に入れることはできません", "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つだけ選択してください", @@ -2387,5 +2386,16 @@ "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": "別のライブラリが開かれました: 何も行われていません", - "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 780892b819b..e44dfee4115 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…და კიდევ {n}", "{n} keywords": "საკვანძო სიტყვები: {n}", "{n} albums": "ალბომები: {n}", - "{n} folders": "საქაღალდეები: {n}" + "{n} folders": "საქაღალდეები: {n}", + "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 9e76b550aac..1cabb059340 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2741,7 +2741,6 @@ "A keyword can't go inside itself": "საკვანძო სიტყვა საკუთარ თავში ვერ მოთავსდება", "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": "სახელის შესაცვლელად აირჩიეთ ერთი საკვანძო სიტყვა", @@ -2763,5 +2762,16 @@ "Remove Folder Color Label": "საქაღალდის ფერადი იარლიყის მოხსნა", "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.": "ფოტოები „ყველა ფოტოში“ რჩება. „დაბრუნება“ ალბომებს აღადგენს.", + "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 6d1b741cddb..d8e3445a11d 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…i {n} więcej", "{n} keywords": "Słowa kluczowe: {n}", "{n} albums": "Albumy: {n}", - "{n} folders": "Foldery: {n}" + "{n} folders": "Foldery: {n}", + "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 58a5d19f990..5025d8c4b78 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2290,7 +2290,6 @@ "A keyword can't go inside itself": "Słowo kluczowe nie może trafić do samego siebie", "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ę", @@ -2313,5 +2312,16 @@ "Remove Folder Color Label": "Usuń etykietę kolorystyczną folderu", "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." + "The photos stay in All Photos. Undo brings the albums back.": "Zdjęcia zostają we „Wszystkich zdjęciach”. Cofnij przywróci albumy.", + "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 przeszukanie", + "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 0a5d0164f8c..499d14a3256 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…e mais {n}", "{n} keywords": "{n} palavras-chave", "{n} albums": "{n} álbuns", - "{n} folders": "{n} pastas" + "{n} folders": "{n} pastas", + "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: só cabem mais {n} na fila", + "Synchronize {n} Folders…": "Sincronizar {n} pastas…", + "{n} new": "{n} novas", + "{n} moved": "{n} movidas", + "{n} missing": "{n} ausentes", + "{n} with changed sidecars": "{n} com arquivo auxiliar alterado" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index c7b1353c562..5c9fe906c77 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1192,7 +1192,6 @@ "A keyword can't go inside itself": "Uma palavra-chave não pode ir para dentro de si mesma", "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", @@ -2233,5 +2232,16 @@ "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", - "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 fae1b799523..073849137d7 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…и ещё {n}", "{n} keywords": "Ключевые слова: {n}", "{n} albums": "Альбомы: {n}", - "{n} folders": "Папки: {n}" + "{n} folders": "Папки: {n}", + "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 4f9709a4160..b722f782b26 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1975,7 +1975,6 @@ "A keyword can't go inside itself": "Ключевое слово нельзя поместить в само себя", "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": "Выберите только одно ключевое слово, чтобы переименовать его", @@ -2380,5 +2379,16 @@ "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": "Открыта другая библиотека: ничего не сделано", - "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 a6bf0e321e7..25c1312b72a 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…och {n} till", "{n} keywords": "{n} nyckelord", "{n} albums": "{n} album", - "{n} folders": "{n} mappar" + "{n} folders": "{n} mappar", + "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": "{n} nya", + "{n} moved": "{n} flyttade", + "{n} missing": "{n} saknas", + "{n} with changed sidecars": "{n} med ändrade sidofiler" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index dde023f4d51..cc526bc5269 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2436,7 +2436,6 @@ "A keyword can't go inside itself": "Ett nyckelord kan inte läggas i sig självt", "Choose one album to rename it": "Välj ett album för att byta namn på det", "Choose one folder to rename it": "Välj en mapp för att byta namn på den", - "Choose one folder to synchronize it": "Välj en mapp för att synkronisera den", "Choose one keyword to create a keyword inside it": "Välj ett nyckelord för att skapa ett nyckelord i det", "Choose one keyword to edit it": "Välj ett nyckelord för att redigera det", "Choose one keyword to rename it": "Välj ett nyckelord för att byta namn på det", @@ -2457,5 +2456,16 @@ "Paste at Top Level": "Klistra in på översta nivån", "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.", + "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 45e582260b6..82181fec08f 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…і ще {n}", "{n} keywords": "Ключові слова: {n}", "{n} albums": "Альбоми: {n}", - "{n} folders": "Теки: {n}" + "{n} folders": "Теки: {n}", + "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 42c398be38c..75aa5a105bc 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1651,7 +1651,6 @@ "A keyword can't go inside itself": "Ключове слово не можна помістити в саме себе", "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": "Виберіть лише одне ключове слово, щоб перейменувати його", @@ -2385,5 +2384,16 @@ "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": "Відкрито іншу бібліотеку: нічого не зроблено", - "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 4e8a5814885..48d6e127baf 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…và {n} mục nữa", "{n} keywords": "{n} từ khóa", "{n} albums": "{n} album", - "{n} folders": "{n} thư mục" + "{n} folders": "{n} thư mục", + "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 bacef299b00..3bffbaffe65 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2242,7 +2242,6 @@ "A keyword can't go inside itself": "Một từ khóa không thể nằm trong chính nó", "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", "Choose one keyword to edit it": "Chọn một từ khóa để chỉnh sửa", "Choose one keyword to rename it": "Chọn một từ khóa để đổi tên", @@ -2264,5 +2263,16 @@ "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.": "Các ảnh vẫn nằm trong Tất cả ảnh. Hoàn tác sẽ đưa các album trở lại.", - "Remove Folder Color Label": "Xóa nhãn màu thư mục" + "Remove Folder Color Label": "Xóa nhãn màu thư mục", + "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 654696aa57f..5103a6c1fd5 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…以及另外 {n} 个", "{n} keywords": "{n} 个关键字", "{n} albums": "{n} 个相册", - "{n} folders": "{n} 个文件夹" + "{n} folders": "{n} 个文件夹", + "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 a7f55364bab..ba995a201f1 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1681,7 +1681,6 @@ "A keyword can't go inside itself": "关键字不能放入其自身", "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": "请只选择一个关键字以重命名", @@ -2231,5 +2230,16 @@ "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": "已打开另一个图库:未执行任何操作", - "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 b7c34b08654..cac044222ec 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -328,5 +328,12 @@ "…and {n} more": "…以及另外 {n} 個", "{n} keywords": "{n} 個關鍵字", "{n} albums": "{n} 個相簿", - "{n} folders": "{n} 個資料夾" + "{n} folders": "{n} 個資料夾", + "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 676385aaa2e..ef21f248c46 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1687,7 +1687,6 @@ "A keyword can't go inside itself": "關鍵字不能放入其自身", "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": "請只選擇一個關鍵字以重新命名", @@ -2188,5 +2187,16 @@ "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": "已開啟另一個圖庫:未執行任何操作", - "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/control.rs b/crates/ui-egui/src/control.rs index 41fa664e93f..26e705c10bb 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -414,7 +414,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest "ui.dialog.confirm" => match app.ui.dialog.take() { Some(d) => { let r = crate::panels::dialogs::confirm_dialog(app, &d); - // the import review and the rule editor stay open on an error, as with their buttons + // the import review, the rule editor and the folders' Synchronize stay open on an error, as with their buttons if (r.is_err() && matches!( d, @@ -423,6 +423,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest | crate::state::Dialog::SmartRules { .. } | crate::state::Dialog::SaveEffect { .. } | crate::state::Dialog::CaptureTime { .. } + | 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/headless.rs b/crates/ui-egui/src/headless.rs index 37b8c2039bb..794037196ec 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/import.rs b/crates/ui-egui/src/import.rs index d4093ede375..7579fb55e88 100644 --- a/crates/ui-egui/src/import.rs +++ b/crates/ui-egui/src/import.rs @@ -453,7 +453,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/lib.rs b/crates/ui-egui/src/lib.rs index b441ee6e6da..4b8165a665a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -623,6 +623,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. @@ -760,6 +762,7 @@ impl LightcraftApp { sync_owns_changes: false, sync_run: None, sync_queued: None, + sync_scans: None, lightroom: None, lightroom_last: None, lightroom_result: None, @@ -2135,6 +2138,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/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index b96766d1f32..0e0ff558f91 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -121,7 +121,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. @@ -169,3 +169,8 @@ 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) } +} diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index b2ff403c7da..eb88eb312a7 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -287,6 +287,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { 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?", @@ -1311,6 +1312,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { 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), + d @ Dialog::SynchronizeFolders { .. } => crate::sync::many_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)); @@ -1444,8 +1446,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { Dialog::Several(s) => super::side_select::several_button(s), Dialog::LightroomCatalog { .. } => "Import Lightroom Catalog…", d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::ok_label(d), - Dialog::SynchronizeFolder { .. } if informational => "Close", - Dialog::SynchronizeFolder { .. } => "Synchronize", + Dialog::SynchronizeFolder { .. } | Dialog::SynchronizeFolders { .. } if informational => "Close", + Dialog::SynchronizeFolder { .. } | Dialog::SynchronizeFolders { .. } => "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", @@ -1469,6 +1471,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { &dlg, Dialog::DenoiseModel { accepted: false, .. } | Dialog::FaceModel { accepted: false, .. } | Dialog::SynchronizeFolder { counts: None, .. } ) + // the folders' Synchronize waits for every folder's scan + && (!matches!(&dlg, Dialog::SynchronizeFolders { .. }) || crate::sync::many_scanned(&dlg)) // 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; @@ -1559,6 +1563,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { | Dialog::KeywordTag { .. } | Dialog::KeywordSet { .. } | Dialog::SynchronizeFolder { .. } + | Dialog::SynchronizeFolders { .. } | Dialog::SaveEffect { .. } | Dialog::CaptureTime { .. } ) => @@ -2135,6 +2140,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) } @@ -2528,6 +2534,7 @@ 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)) } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/side_select.rs b/crates/ui-egui/src/panels/side_select.rs index b884e2e2220..a2a57a01487 100644 --- a/crates/ui-egui/src/panels/side_select.rs +++ b/crates/ui-egui/src/panels/side_select.rs @@ -383,7 +383,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 1b0d20e732f..43282e8f51c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1447,6 +1447,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 @@ -1482,6 +1497,35 @@ impl SyncCounts { } } +/// 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() + } +} + impl Default for UiState { fn default() -> Self { UiState { diff --git a/crates/ui-egui/src/sync.rs b/crates/ui-egui/src/sync.rs index 4bea1f3aa8e..465abbe582b 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,365 @@ 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 lower-cased names, to tell whether one folder is inside another. +fn names(path: &str) -> Vec { + lightcraft_catalog::query::folder_key(path).to_lowercase().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; + } + }; + let Some(mut scan) = app.sync_scans.take() else { return }; + if scan.guard.is_cancelled() || library != app.session.library_generation() { + 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 (done, total) = progress.counts(); + scan.guard.detail(&folders.get(i).map(|f| format!("{} · {done} / {total}", f.name)).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.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, (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 +710,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 146edf75539..73f6bb7d111 100644 --- a/crates/ui-egui/src/tests_drop_import.rs +++ b/crates/ui-egui/src/tests_drop_import.rs @@ -298,7 +298,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_multi_select.rs b/crates/ui-egui/src/tests_multi_select.rs index e8d37d08cd9..260a49e4cdb 100644 --- a/crates/ui-egui/src/tests_multi_select.rs +++ b/crates/ui-egui/src/tests_multi_select.rs @@ -708,7 +708,6 @@ fn the_words_of_several_rows_at_once_are_in_every_language() { "A keyword can't go inside itself", "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", diff --git a/crates/ui-egui/src/tests_sync.rs b/crates/ui-egui/src/tests_sync.rs index 1030b6f7c1d..c606216dec1 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"); @@ -598,3 +602,174 @@ 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; + } + 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"); + 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"); +} + +/// 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(); + 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"); +} diff --git a/docs/background-tasks.md b/docs/background-tasks.md index a7bbe9073b8..53f524ba6f4 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -67,7 +67,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 acting only on what its scan found; a waiting row names its folder + (`Request::subject`, which a Retry keeps). 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 4d17d7b00b9..484d2d31242 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,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/parity-checklist.md b/docs/parity-checklist.md index 3cd71ac48fd..ec9ab15e89f 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-24 · **Change:** minor (LR-BEHAV-MULTISELECT: several albums, folders, keywords or dates shown at once, for agents; 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: 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-24 · **Change:** minor (Synchronize N Folders for several folders chosen at once; LR-BEHAV-MULTISELECT: several albums, folders, keywords or dates shown at once, for agents; 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: 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 @@ -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`, `cmd:library.source` (`ids`, `paths`), `cmd:library.filter` (`keywords`, `dates`, `libraryFolders`, `albums`), `cmd:album.delete` / `cmd:album.move` / `cmd:album.duplicate` (`ids`), `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_multi_source.rs`, `crates/engine/src/tests_batch_sidebar.rs` | photos in the grid; and rows of the sidebars' lists: Cmd/Ctrl+click adds or takes away a row, Shift+click takes the rows between (as drawn: none inside a closed level), Cmd/Ctrl+Shift+click adds a range. Albums, Folders, Keywords and By Date in the left panel then show the photos of any of the rows chosen (albums and folders as the source, keywords and dates as the filter); in the Keyword List several keywords are picked. A plain click is unchanged. The menu of one of several rows acts on them all, as one undo step: Move to, Delete… and Export for albums, Color Label and Remove from Library… for folders, Add to / Remove from Selected Photos, Merge into… and Delete… for keywords; deleting or removing several asks first. Dragging one of several albums or keywords moves them all. Delete (the photos' delete shortcut) asks about several rows just chosen with Cmd/Shift+click, until the next click anywhere or any other change to what is shown or selected; after a plain click it stays the photos'. Cut / Copy / Paste in the menus: albums move or are duplicated into a folder or the top level, cut keywords are nested inside another, copied keywords are text for a keyword box. Not yet: several Local folders at once, arrow keys and Select All in a sidebar list, cut/copy/paste shortcuts there, an any/all switch for several keywords (it is any), Synchronize for several folders | +| 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` / `cmd:album.duplicate` (`ids`), `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_multi_source.rs`, `crates/engine/src/tests_batch_sidebar.rs` | photos in the grid; and rows of the sidebars' lists: Cmd/Ctrl+click adds or takes away a row, Shift+click takes the rows between (as drawn: none inside a closed level), Cmd/Ctrl+Shift+click adds a range. Albums, Folders, Keywords and By Date in the left panel then show the photos of any of the rows chosen (albums and folders as the source, keywords and dates as the filter); in the Keyword List several keywords are picked. A plain click is unchanged. The menu of one of several rows acts on them all, as one undo step: Move to, Delete… and Export for albums, Color Label and Remove from Library… for folders, Add to / Remove from Selected Photos, Merge into… and Delete… for keywords; deleting or removing several asks first. Dragging one of several albums or keywords moves them all. Delete (the photos' delete shortcut) asks about several rows just chosen with Cmd/Shift+click, until the next click anywhere or any other change to what is shown or selected; after a plain click it stays the photos'. Several folders' menu: Synchronize N Folders… (one dialog scans them one after another 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; a folder inside another chosen one is covered by it; whole disks, folders not there and folders up to date are passed over, saying why). Cut / Copy / Paste in the menus: albums move or are duplicated into a folder or the top level, cut keywords are nested inside another, copied keywords are text for a keyword box. Not yet: several Local folders at once, arrow keys and Select All in a sidebar list, cut/copy/paste shortcuts there, an any/all switch for several keywords (it is any) | | 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` | | @@ -961,3 +961,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 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-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-10-22 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars; their menus, drags, Delete and Cut / Copy / Paste act on them all; LR-LIB-ALBUM cites `album.duplicate`; statuses unchanged | +| 2026-10-22 | minor | LR-BEHAV-MULTISELECT, 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, acting only on 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 dbfbfe3e9e6..d5152c6541b 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,16 @@ ## 2026-10-24 +### 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. + ### 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 From f736ec866cb44e36669e41dbabaa20e12bb5a696 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 11:55:35 -0400 Subject: [PATCH 28/30] Sidebars: the closed-folder Shift+click test crosses a folder it can open and close, so it fails if hidden rows are taken --- crates/ui-egui/src/tests_multi_select.rs | 28 ++++++++++++++++-------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/tests_multi_select.rs b/crates/ui-egui/src/tests_multi_select.rs index 260a49e4cdb..9a1ea94580d 100644 --- a/crates/ui-egui/src/tests_multi_select.rs +++ b/crates/ui-egui/src/tests_multi_select.rs @@ -171,17 +171,27 @@ fn shift_click_takes_the_albums_between_and_a_plain_click_one_alone() { 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(); - 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]]); + // folders are listed above albums, so the range has to run from a row inside the first folder, across + // the second, to an album at the top level + let first = run(&mut h, "album.create", json!({"name": "Sel A Folder", "folder": true}))["id"].as_u64().unwrap(); + let anchor = album(&mut h, "Sel A", Some(first), &[ids[0]]); + let second = run(&mut h, "album.create", json!({"name": "Sel B Folder", "folder": true}))["id"].as_u64().unwrap(); + let inside = album(&mut h, "Sel Inside", Some(second), &[ids[0]]); + let last = album(&mut h, "Sel Z", None, &[ids[1]]); + // open, the range takes the album inside the second folder... assert!(has(&h, &row(inside)), "a folder starts open"); - click(&mut h, &format!("albumToggle:{folder}")); + click(&mut h, &row(anchor)); + shift_click(&mut h, &row(last)); + let open = shown(&h); + assert!(open.contains(&anchor) && open.contains(&inside) && open.contains(&last), "{open:?}"); + // ...closed, it does not: a row that is not in sight is not taken + click(&mut h, &format!("albumToggle:{second}")); assert!(!has(&h, &row(inside)), "closed"); - click(&mut h, &format!("source:folder:{folder}")); - shift_click(&mut h, &row(after)); - let chosen = shown(&h); - assert!(chosen.contains(&folder) && chosen.contains(&after), "{chosen:?}"); - assert!(!chosen.contains(&inside), "a row that is not in sight is not taken: {chosen:?}"); + click(&mut h, &row(anchor)); + shift_click(&mut h, &row(last)); + let closed = shown(&h); + assert!(closed.contains(&anchor) && closed.contains(&last), "{closed:?}"); + assert!(!closed.contains(&inside), "a row that is not in sight is not taken: {closed:?}"); } #[test] From 0078c757d18b9b8587cb99992dc5c631988c8b75 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 23:05:06 -0400 Subject: [PATCH 29/30] LR-BEHAV-MULTISELECT: What's New and parity wording for Cut, Copy and Paste of albums and keywords --- docs/parity-checklist.md | 3 ++- docs/whats-new.md | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ec9ab15e89f..6efd7c446aa 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-24 · **Change:** minor (Synchronize N Folders for several folders chosen at once; LR-BEHAV-MULTISELECT: several albums, folders, keywords or dates shown at once, for agents; 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: 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-24 · **Change:** minor (LR-BEHAV-MULTISELECT: Cut, Copy and Paste for albums and keywords; Synchronize N Folders for several folders chosen at once; LR-BEHAV-MULTISELECT: several albums, folders, keywords or dates shown at once, for agents; 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: 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 @@ -962,3 +962,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-10-22 | minor | LR-BEHAV-MULTISELECT: Cmd/Ctrl+click and Shift+click choose several albums, folders, keywords or dates in the sidebars; their menus, drags, Delete and Cut / Copy / Paste act on them all; LR-LIB-ALBUM cites `album.duplicate`; statuses unchanged | | 2026-10-22 | minor | LR-BEHAV-MULTISELECT, 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, acting only on the photos its scan found; waiting rows name their folder); status unchanged (✅) | +| 2026-10-21 | minor | LR-BEHAV-MULTISELECT: Cut / Copy / Paste in the albums' and keywords' menus; LR-LIB-ALBUM cites `album.duplicate`; statuses unchanged | diff --git a/docs/whats-new.md b/docs/whats-new.md index d5152c6541b..2b017ed692b 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,15 @@ ## 2026-10-24 +### Cut, Copy and Paste for albums and keywords +- In the menus of albums and keywords in the left panel and the Keyword List, Cut and Copy take the rows (one or + several chosen) and Paste puts them down: cut albums move into the folder where you choose Paste (the Albums + + menu pastes at the top level), copied albums are duplicated there with their photos, a copied smart album keeps its + rules and a copied folder everything inside it; cut keywords are nested inside the keyword where you choose Paste; + copied keywords are text you can paste in a keyword box. Paste is not offered where it would be refused, such as a + folder inside itself, and one Edit ▸ Undo takes back a paste. +- For agents: the new `album.duplicate` takes `id` or `ids` and an optional `parent` (null: the top level). + ### 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, From 1c0977d4ae6d761aa3edbeda583343942a292935 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 23:39:39 -0400 Subject: [PATCH 30/30] LR-BEHAV-MULTISELECT: What's New no longer says the sidebars' Cmd+click and Shift+click come later --- 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 2b017ed692b..3d4b723261b 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -196,8 +196,8 @@ - `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 + more of them. `library.state` lists `albums` and `libraryFolders`. The sidebars' Cmd+click and Shift+click use + this (see the entry below). 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.