diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index c1f9d258c6d..bbd0e4d2f43 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -119,12 +119,15 @@ static ALLOC: dhat::Alloc = dhat::Alloc; /// Why `--library DIR` can't be opened; for a library open in another program, how to work with /// that one instead (issue #99). -/// Print the open library's warnings (an unlockable library, damaged settings files) on stderr: -/// stdout carries command results / MCP protocol messages only. +/// Print the open library's warnings (an unlockable library, damaged settings files, moves an +/// earlier run cut short) on stderr: stdout carries command results / MCP protocol messages only. fn library_warnings(session: &mut Session, who: &str) { for w in session.take_library_warnings() { eprintln!("{who}: warning: {w}"); } + if let Some(text) = session.take_recovered_moves().and_then(|r| r.notice()) { + eprintln!("{who}: {text}"); + } } fn library_error(dir: &str, e: lightcraft_engine::EngineError) -> String { diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 7b572fa0ede..899932c9c78 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -104,6 +104,8 @@ impl eframe::App for App { self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { + // a finished move's result is waiting for a frame that won't come: the library follows it now + self.0.finish_ready_move(); // (a size the window was just given is remembered too) self.0.ui.window = self.1.window_at_exit(self.0.ui.window); if let Err(e) = self.1.save(&self.0) { diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a58..357aac73fcd 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -72,8 +72,8 @@ impl Unit { #[serde(rename_all = "camelCase")] pub struct TaskInfo { pub id: u64, - /// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`, - /// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`. + /// A stable id: `import`, `export`, `scan`, `sync`, `move`, `previews`, `smartPreviews`, `lightroom`, `merge`, + /// `download`, `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`. pub kind: &'static str, /// English; the frontend translates it. pub label: String, diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index b24246592ef..60e84dad6cf 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -299,7 +299,7 @@ pub fn specs() -> Vec { "Move to Folder", [], None, - "{folder, ids?} — move the photos' files (default: the selection) with their XMP sidecars into `folder` on disk and relink them; virtual copies follow their master; across volumes the file is copied, verified and only then removed; never overwrites (a name taken in `folder` refuses the whole move); missing/offline and Local photos are refused; one undo step (undo moves them back) → {moved, folder}", + "{folder, ids?} — move the photos' files (default: the selection) with their XMP sidecars into `folder` on disk and relink them; virtual copies follow their master; across volumes the file is copied, verified and only then removed; never overwrites (a name taken in `folder` refuses the whole move); missing/offline and Local photos are refused; one undo step (undo moves them back); a record in the library lets the next open follow a move cut short (a force-quit). In the desktop app `background: true` moves the files on a worker thread (`activity.list` kind `move`; `ui.inspect` → `move`) → {moved, folder}", always, move_to_folder ), @@ -387,7 +387,7 @@ fn remove_empty_folder(path: &str) -> std::result::Result<(), String> { } /// A folder path parameter without trailing separators (`None` when missing or blank). -fn folder_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { +pub(crate) fn folder_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { str_param(p, key).map(|x| x.trim_end_matches(['/', '\\'])).filter(|x| !x.is_empty()) } @@ -417,65 +417,14 @@ fn create_folder(s: &mut Session, p: &Value) -> Result { /// `photo.moveToFolder`: move the photos' files (with their sidecars) into `folder` and relink /// them, as one undo step. Virtual copies follow their master's file. Never overwrites: a name -/// already taken in `folder` refuses the whole move. +/// already taken in `folder` refuses the whole move. Here it waits for the files; the app runs +/// the same job on a worker thread ([`crate::move_job`]). fn move_to_folder(s: &mut Session, p: &Value) -> Result { - const C: &str = "photo.moveToFolder"; - let folder = folder_param(p, "folder").ok_or_else(|| bad(C, "missing folder"))?; - let dir = Path::new(folder); - if !dir.is_dir() { - return Err(bad(C, format!("{folder} is not a folder (create it first with folder.create)"))); - } - let ids = s.targets(p)?; - if ids.is_empty() { - return Err(bad(C, "no photos to move: select some or give ids")); - } - let mut plans: Vec = Vec::new(); - let mut taken: std::collections::HashSet = std::collections::HashSet::new(); - let mut clashes: Vec = Vec::new(); - for id in ids { - let ph = s.catalog.photo(id).ok_or_else(|| bad(C, format!("no photo {}", id.0)))?; - if ph.local { - return Err(bad(C, format!("{} is not in the library (Local): add it first", ph.file_name))); - } - let lightcraft_catalog::Source::File { path } = &ph.source else { - return Err(bad(C, format!("{} has no file on disk", ph.file_name))); - }; - if plans.iter().any(|pl| pl.from_path.as_deref() == Some(path.as_str())) { - continue; // a virtual copy of a photo already moving - } - let src = Path::new(path); - if !src.is_file() { - return Err(bad(C, format!("{path} is missing or offline: find it first (Find Missing Photos)"))); - } - let Some(file) = src.file_name() else { return Err(bad(C, format!("{path}: no file name"))) }; - if src.parent() == Some(dir) { - continue; // already there - } - let to = dir.join(file); - let to_s = to.to_string_lossy().to_string(); - if to.exists() || !taken.insert(to_s.to_lowercase()) { - clashes.push(file.to_string_lossy().to_string()); - continue; - } - let name = ph.file_name.clone(); - plans.push(crate::rename::RenamePlan { id: id.0, from: name.clone(), to: name, from_path: Some(path.clone()), to_path: Some(to_s) }); - } - if !clashes.is_empty() { - let s_ = if clashes.len() == 1 { "" } else { "s" }; - return Err(bad( - C, - format!("{} already in {folder}: nothing was moved. Rename the photo{s_} first or choose another folder", clashes.join(", ")), - )); - } - let n = plans.len(); - if n == 0 { - return Ok(json!({"moved": 0, "folder": folder})); - } - let plural = |k: usize| if k == 1 { "" } else { "s" }; - let _task = s.activity.start("move", &format!("Moving {n} photo{}", plural(n)), crate::activity::Cancel::No); - let name = dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| folder.to_string()); - s.apply_file_plans(&crate::rename::RealFs, &plans, &|k| format!("Move {k} Photo{} to “{name}”", plural(k)))?; - Ok(json!({"moved": n, "folder": folder})) + let Some((work, finish)) = crate::move_job::start(s, p)? else { + return Ok(json!({"moved": 0, "folder": folder_param(p, "folder")})); + }; + let out = work.run(); + finish.finish(s, out) } /// After a folder moved from `from` to `to`: a browsed folder at or below it follows. @@ -510,6 +459,7 @@ fn follow_library_folder(chosen: &mut Option, from: &str, to: &str) { /// the photos inside, as one undo step: undo renames the folder back and restores the photos' /// paths, redo repeats the move — each refused (and reported) when the destination is taken. pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result::Result { + s.refuse_while_moving().map_err(|e| e.to_string())?; let (src, dst) = (Path::new(from), Path::new(to)); if !src.is_dir() { return Err(format!("{from} is not a folder")); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 0871e43528e..339f52b6f6d 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -4,7 +4,7 @@ use std::path::Path; -use lightcraft_catalog::{MediaKind, Op, Source}; +use lightcraft_catalog::{MediaKind, Op, PhotoId, Source}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_active, has_selection}; @@ -57,9 +57,32 @@ pub(crate) fn write_dng_with(file_bytes: Option<&crate::merge::ByteReader>, path Ok(out.to_string_lossy().to_string()) } +/// Why `ph` isn't converted, if it isn't. +fn not_convertible(ph: &lightcraft_catalog::Photo) -> Option<&'static str> { + if ph.kind != MediaKind::Raw { + Some("not a raw photo") + } else if ph.copy_of.is_some() { + Some("a virtual copy") + } else if ph.format.eq_ignore_ascii_case("DNG") { + Some("already a DNG") + } else { + None + } +} + fn convert(s: &mut Session, p: &Value) -> Result { const C: &str = "photo.convertToDng"; let ids = s.targets(p)?; + // before the first DNG is written: a raw on its way to another folder is read half-moved, and the + // DNG would be left next to a file that is no longer there + let moving: Vec = ids + .iter() + .copied() + .filter(|id| { + s.catalog.photo(*id).is_some_and(|ph| matches!(&ph.source, Source::File { path } if not_convertible(ph).is_none() && s.is_moving(path))) + }) + .collect(); + s.refuse_detaching(&moving)?; let mut ops = Vec::new(); let mut converted = Vec::new(); let mut skipped = Vec::new(); @@ -69,17 +92,8 @@ fn convert(s: &mut Session, p: &Value) -> Result { skipped.push(json!([id.0, "not a file"])); continue; }; - if ph.kind != MediaKind::Raw || ph.format.eq_ignore_ascii_case("DNG") || ph.copy_of.is_some() { - skipped.push(json!([ - id.0, - if ph.kind != MediaKind::Raw { - "not a raw photo" - } else if ph.copy_of.is_some() { - "a virtual copy" - } else { - "already a DNG" - } - ])); + if let Some(why) = not_convertible(&ph) { + skipped.push(json!([id.0, why])); continue; } let packet = crate::sidecar::sidecar_packet(&ph, &s.catalog); diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 2e7c1311d0c..fbbbc31afdb 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1349,6 +1349,8 @@ pub fn specs() -> Vec { "lastError": lib.last_error, // settings files that were unreadable or damaged at open (kept, defaults used) "settingsWarnings": lib.settings_warnings, + // moves an earlier run cut short, followed when the library opened (null: none) + "recoveredMoves": lib.recovered_moves, // changes applied in memory whose write failed (retried by every save) "unsavedOps": s.unsaved().map_or(0, |u| u.0), "unsavedError": s.unsaved().map(|u| u.1), diff --git a/crates/engine/src/errors.rs b/crates/engine/src/errors.rs index beb4cefb465..161fa98d749 100644 --- a/crates/engine/src/errors.rs +++ b/crates/engine/src/errors.rs @@ -27,6 +27,9 @@ pub enum ErrorKind { LightroomCatalog, /// The work was cancelled: not a failure. Cancelled, + /// Photos are being moved to another folder in the background and the change would clash with + /// the move: nothing was changed, and a frontend says so where the person sees it. + MoveInProgress, /// The feature needs this model, which is not installed (or still downloading). ModelMissing(AiModel), Other, @@ -44,6 +47,7 @@ impl EngineError { Self::LibraryInUse(_) => ErrorKind::LibraryInUse, Self::LightroomCatalog { .. } => ErrorKind::LightroomCatalog, Self::Cancelled(_) => ErrorKind::Cancelled, + Self::MoveInProgress(_) => ErrorKind::MoveInProgress, Self::ModelMissing { model, .. } => ErrorKind::ModelMissing(*model), Self::Other(_) => ErrorKind::Other, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..f2da77c6e4f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -57,6 +57,8 @@ pub mod media; pub mod memory; pub mod merge; mod model_download; +pub mod move_intent; +pub mod move_job; pub mod open_path; pub mod originals; mod pdf; @@ -120,6 +122,11 @@ pub enum EngineError { /// The work was cancelled (by the person, an agent or a newer request): not a failure. #[error("{0}")] Cancelled(String), + /// A background move of photos is running and this change would clash with it (open another + /// library, move other files, take a moving photo out of the library or point it at another + /// file): nothing was changed ([`ErrorKind::MoveInProgress`]). + #[error("{0}")] + MoveInProgress(String), /// The feature needs `model`, which is not installed (or still downloading): a frontend /// offers its download (terms first) on [`ErrorKind::ModelMissing`], not on the message. #[error("{msg}")] @@ -331,6 +338,18 @@ pub struct Session { pub library: Option, /// Identity of current library opening; refreshed only after a successful open. pub(crate) library_identity: Arc<()>, + /// The move to another folder running in the background, if any ([`move_job`]): other file + /// moves wait for it, and its photos' sidecars are written once it ends. + pub(crate) moving: std::sync::Weak, + /// Records of file moves now in the catalog ([`move_intent`]), removed once it is saved. + pub(crate) settled_moves: Vec, + /// Photos whose automatic sidecar write waits for their file to arrive at the folder it is + /// being moved to ([`move_job`]); written when the move ends. Not a failure: no notice. + pub(crate) held_sidecars: std::collections::BTreeSet, + /// The photos this session put on the list of held writes kept beside the move records + /// ([`move_intent`]): without the library's lock, it takes back only these, and leaves the + /// entries another run (or program) put there. + pub(crate) held_listed: std::collections::BTreeSet, /// XMP sidecar preferences (persisted with the library). pub xmp: sidecar::XmpPrefs, /// Parameters of the last export (`app.export` params, minus targets), persisted in prefs.json. @@ -501,6 +520,10 @@ impl Session { active_spot: None, library: None, library_identity: Arc::new(()), + moving: std::sync::Weak::new(), + settled_moves: Vec::new(), + held_sidecars: Default::default(), + held_listed: Default::default(), xmp: sidecar::XmpPrefs::default(), last_export: None, last_merge: Default::default(), @@ -612,7 +635,10 @@ impl Session { // persistence trouble (a failed compaction, an older queued change still unwritten by // a command that changed nothing) doesn't fail the command; `library.info` reports it. let produced = self.pending_log.len() > log_start; - if let Err(e @ EngineError::NotSaved(_)) = self.persist() + let saved = self.persist(); + // the records of moves this command settled go once the catalog that follows them is saved + self.clear_settled_moves(); + if let Err(e @ EngineError::NotSaved(_)) = saved && produced && r.is_ok() { @@ -630,6 +656,7 @@ impl Session { /// Apply an op as one undoable step. pub fn commit(&mut self, label: &str, op: Op) -> Result<()> { + self.refuse_detaching(&self.detached_moving_photos(&op))?; let fwd = op.clone(); let inv = self.apply_catalog(op)?; self.pending_log.push(fwd); @@ -842,29 +869,42 @@ impl Session { // The entry is detached from self.undo/self.redo: include it before any global // repair can retire, then retry revalidates it before moving its own packets. rename::validate_sidecars(fs, &entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; + // A step that would take a moving photo out of the library or point it at another file says how many. + self.refuse_detaching(&self.detached_moving_photos(&entry.op))?; // Repair discarded file steps before another path change can stale their exact paths. // Unrelated metadata history must remain usable while a sidecar is still unwritable. if entry.folder.is_some() || !entry.retry_sidecars.is_empty() || !self.file_moves(&entry.op).is_empty() { + self.refuse_while_moving()?; self.repair_sidecars_with(fs).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; } rename::retry_sidecars(fs, &mut entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; let op = &entry.op; + let moves = self.file_moves(op); + // noted before anything moves: a stop part-way is found and followed at the next open + let record = self.record_moves(&moves)?; let folder = entry.folder.as_ref(); - if let Some(f) = folder { - cmd::browse::folder_on_disk(&f.from, &f.to).map_err(|e| EngineError::Other(format!("can't move the folder back: {e}")))?; + if let Some(f) = folder + && let Err(e) = cmd::browse::folder_on_disk(&f.from, &f.to) + { + self.settle_moves(record); + return Err(EngineError::Other(format!("can't move the folder back: {e}"))); } let undo_folder = || { if let Some(f) = folder { let _ = cmd::browse::folder_on_disk(&f.to, &f.from); } }; - let moves = self.file_moves(op); - if let Err(mut e) = rename::move_all(fs, &moves) { + let moved = rename::move_all(fs, &moves); + if let Err(mut e) = moved { entry.retry_sidecars.append(&mut e.pending_sidecars); if e.stuck.is_empty() { undo_folder(); } - let (message, mut inverses) = self.follow_stuck(op, e, false); + let (message, mut inverses, followed) = self.follow_stuck(op, e, false); + // (a library that could not follow keeps the record for the next open) + if followed { + self.settle_moves(record); + } // A later successful retry observes the corrected paths. Retain their old paths // now, so the opposite history direction still restores the entire original step. inverses.append(&mut entry.retry_inverse); @@ -873,6 +913,7 @@ impl Session { } match self.apply_catalog(op.clone()) { Ok(inv) => { + self.settle_moves(record); if let Some(f) = folder { cmd::browse::follow_folder(self, &f.from, &f.to); } @@ -891,8 +932,10 @@ impl Session { let back: Vec<(String, String)> = moves.iter().rev().map(|(a, b)| (b.clone(), a.clone())).collect(); if let Err(mut be) = rename::move_all(fs, &back) { entry.retry_sidecars.append(&mut be.pending_sidecars); + // the files stay at the new place and the library doesn't point there: the record stays for the next open return Err(EngineError::Other(format!("{e}; the files could not all be moved back: {}", be.message))); } + self.settle_moves(record); undo_folder(); Err(e) } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b358..04eba6ddef4 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -98,6 +98,12 @@ pub struct Library { /// `settingsWarnings`; shown by the UI once, see [`Session::take_library_warnings`]). pub settings_warnings: Vec, warnings_reported: usize, + /// What following moves an earlier run cut short came to when the library opened + /// (`library.info` → `recoveredMoves`; handed out once, see + /// [`Session::take_recovered_moves`]: the app shows it in its own window). Not a settings + /// problem: kept apart from those. + pub recovered_moves: Option, + moves_reported: bool, /// Settings files that couldn't be read or set aside: never overwritten this session. blocked: Vec<&'static str>, /// Keeps other processes out of this library while it's open (last: released after the @@ -188,6 +194,11 @@ struct ViewFile { } impl Library { + /// Open without the lock that keeps a second program out (its file system can't lock + /// `catalog.lock`): another program may be working on the same files. + pub(crate) fn is_unprotected(&self) -> bool { + self.lock.as_ref().is_some_and(|l| !l.held()) + } pub fn journal(&self) -> &Journal { &self.journal } @@ -381,6 +392,9 @@ impl Session { /// Nothing is created; a library folder that exists gets its lock taken and released again. /// Opening can still fail afterwards (a damaged catalog, a disk going away). pub fn check_library(&self, dir: impl AsRef) -> Result { + // a switch checks first and only then closes this library: a move running in it is + // refused here, before anything is closed (closing itself stays open to quitting) + self.refuse_while_moving()?; let dir = dir.as_ref().to_path_buf(); if let Some(place) = crate::lightroom_folder::lightroom_catalog_at(&dir) { return Err(EngineError::LightroomCatalog { path: dir, catalog: place.catalog }); @@ -413,6 +427,9 @@ impl Session { /// created ([`crate::lightroom_folder`]); a LightCraft library always opens, whatever else /// its folder holds. pub fn open_library(&mut self, dir: impl AsRef, seed_demo: bool) -> Result<&LoadReport> { + // a move in progress belongs to the open library: refused before the target is touched + // (no folder or lock file made, and a lock held elsewhere doesn't hide the reason) + self.refuse_while_moving()?; let dir = dir.as_ref().to_path_buf(); if let Some(place) = crate::lightroom_folder::lightroom_catalog_at(&dir) { return Err(EngineError::LightroomCatalog { path: dir, catalog: place.catalog }); @@ -454,6 +471,8 @@ impl Session { /// Open `stores`; the new library takes `lock` once nothing can fail any more. fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option) -> Result<()> { let LibraryStores { dir, catalog, mut files, on_disk } = stores; + // a move in progress belongs to the open library: it finishes (or is stopped) first + self.refuse_while_moving()?; self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); // the current library may be these same files: let its background snapshot land first if let Some(old) = self.library.as_mut() @@ -483,6 +502,12 @@ impl Session { } self.undo.clear(); self.redo.clear(); + // photo ids are per library: none held back for a move carries over + self.held_sidecars.clear(); + self.held_listed.clear(); + // the records of moves this session had settled belong to the library it leaves: they stay + // on disk for the open that follows them (forgetting them here deletes none) + self.settled_moves.clear(); self.interaction = None; self.pending_log.clear(); self.selection = Selection::default(); @@ -590,9 +615,19 @@ impl Session { view_written, settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(settings.warnings).collect(), warnings_reported: 0, + recovered_moves: None, + moves_reported: false, blocked: settings.blocked, lock: lock.take(), }); + // moves an earlier run left unfinished (stopped part-way: a force-quit, a crash) + let recovered = self.recover_moves(); + if let Some(text) = recovered.notice() { + log::warn!("library: {text}"); + if let Some(lib) = self.library.as_mut() { + lib.recovered_moves = Some(recovered); + } + } // forget untouched Local records of folders not browsed for a while (journaled at once) if self.forget_local_days > 0 { let plan = self.forget_local(false, None); @@ -809,6 +844,18 @@ impl Session { new } + /// What following moves cut short came to when the library opened, handed out once (the CLI + /// prints [`Recovered::notice`] on stderr; the app shows it in its own window). + /// + /// [`Recovered::notice`]: crate::move_intent::Recovered::notice + pub fn take_recovered_moves(&mut self) -> Option { + let lib = self.library.as_mut()?; + if std::mem::replace(&mut lib.moves_reported, true) { + return None; + } + lib.recovered_moves.clone() + } + /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default). pub fn cache_bytes(&self) -> u64 { if self.cache_mb == 0 { crate::media::DISK_CACHE_BYTES } else { u64::from(self.cache_mb) << 20 } diff --git a/crates/engine/src/move_intent.rs b/crates/engine/src/move_intent.rs new file mode 100644 index 00000000000..83e5ccc7c0f --- /dev/null +++ b/crates/engine/src/move_intent.rs @@ -0,0 +1,548 @@ +//! A record of file moves in progress, written into the library before the first file moves and +//! removed once the library has saved where the files went. If LightCraft is stopped part-way (a +//! force-quit, a crash, a power cut), the record is still there the next time the library opens, +//! and [`Session::recover_moves`] brings the library up to date with the disk: +//! +//! * a file that reached its new place (and is gone from the old one): its photos point there, +//! and its XMP sidecars follow it; +//! * a file still at its old place and not at the new one: nothing to do; +//! * a file at both places: the copy at the new place is ours (nothing was there when the record +//! was written, and moves never replace a file). It is removed when it is the same file under a +//! second name or holds the same bytes; the library keeps the original. Otherwise both stay and +//! the person is told; +//! * a file at neither place, or gone from a folder that is gone too (its disk may just not be +//! connected, and a copy at the new place may never have been checked): the record keeps it +//! for the next time. +//! +//! The records live in `/moves/`, one file per batch, so a background move and a move +//! the session makes itself (a rename, an Undo) never share one. Beside them, `held-sidecars` +//! lists the photos whose automatic sidecar write waits for a running move to bring their file +//! (edits made meanwhile): the next open makes those writes, and no others. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use lightcraft_catalog::store::{FsStore, Store}; +use lightcraft_catalog::{Op, PhotoId, Source}; +use serde::{Deserialize, Serialize}; + +use crate::rename::{MoveFs, folded_path}; +use crate::{EngineError, Result, Session}; + +/// The folder of the library that holds the records. +const DIR: &str = "moves"; +/// The list of sidecar writes held back for a running move, in [`DIR`] (not a record: records end +/// in `.json`). +const HELD: &str = "held-sidecars"; +/// The records' format, so a later one can tell an older file apart. +const VERSION: u32 = 1; +/// Records larger than this aren't read (a damaged or planted file): 64 MiB is about half a +/// million moves. +const MAX_BYTES: u64 = 64 << 20; + +#[derive(Serialize, Deserialize, Default)] +struct Record { + version: u32, + /// (from, to) for each file, in the order they move. + moves: Vec<(String, String)>, +} + +/// A record on disk: removed once the library has saved the moves it names +/// ([`Session::settle_moves`]). +#[derive(Debug)] +pub(crate) struct MoveRecord { + path: PathBuf, +} + +/// Write the record of `moves` into the library folder `library`, durably, before any of them +/// is made. Callable from a worker thread. +pub(crate) fn write(library: &Path, moves: &[(String, String)]) -> std::io::Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = library.join(DIR); + let fresh = !dir.is_dir(); + std::fs::create_dir_all(&dir)?; + if fresh { + // the new folder's entry in the library folder must survive a power cut too + lightcraft_catalog::safe_file::sync_dir(library); + } + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); + let name = format!("move-{}-{stamp}-{}.json", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); + let bytes = serde_json::to_vec(&Record { version: VERSION, moves: moves.to_vec() }).map_err(std::io::Error::other)?; + FsStore::open(&dir)?.write_atomic(&name, &bytes)?; + Ok(MoveRecord { path: dir.join(name) }) +} + +/// What the records left by an earlier run came to (`library.info` → `recoveredMoves`, and the +/// notice the CLI prints and the app's window shows). +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Recovered { + /// Photos now pointing at the place their file had reached. + pub relinked: usize, + /// Copies at the new place removed (the original stayed where the library has it). + pub copies_removed: usize, + /// Files whose two places couldn't be decided on, records that can't be read, sidecars that + /// couldn't follow. + pub problems: Vec, + /// Moves kept for the next time: the old place can't be read (a disk not connected?). + pub waiting: usize, +} + +/// Something about a move cut short that the person has to know. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum MoveProblem { + /// The record (a path) can't be read; it stays as it is. + UnreadableRecord { record: String, error: String }, + /// The file is at both places; the library keeps `from`. + BothPlaces { from: String, to: String }, + /// The file reached `to`; one of its sidecars didn't follow. + SidecarStayed { to: String, error: String }, + /// The library couldn't take the relinks in. + NotFollowed { error: String }, + /// The relinks were made and couldn't be saved; the next open makes them again. + NotSaved { error: String }, + /// Records of moves are there and the library is open without its lock (another program + /// may be making them): nothing was touched. + Unprotected, +} + +impl std::fmt::Display for MoveProblem { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + MoveProblem::UnreadableRecord { record, error } => { + write!(f, "A record of a move ({record}) can't be read ({error}); it was left as it is.") + } + MoveProblem::BothPlaces { from, to } => write!(f, "{to} was being moved and is now at both places: the library keeps {from}."), + MoveProblem::SidecarStayed { to, error } => write!(f, "A sidecar of {to} couldn't follow it ({error})."), + MoveProblem::NotFollowed { error } => { + write!(f, "The library couldn't follow the files that were being moved ({error}); Find Missing Photos relinks them.") + } + MoveProblem::NotSaved { error } => write!(f, "The files that were being moved are followed, but that couldn't be saved ({error})."), + MoveProblem::Unprotected => write!( + f, + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved." + ), + } + } +} + +impl Recovered { + /// Nothing to tell. + pub fn is_empty(&self) -> bool { + self.relinked == 0 && self.copies_removed == 0 && self.problems.is_empty() && self.waiting == 0 + } + + /// The notice in English (the log, the CLI's stderr), or `None` when there is nothing to say. + pub fn notice(&self) -> Option { + if self.is_empty() { + return None; + } + let mut text = String::new(); + if self.relinked > 0 { + let (s, were) = if self.relinked == 1 { ("", "was") } else { ("s", "were") }; + text.push_str(&format!( + "{} photo{s} {were} being moved when LightCraft last closed: the library now points at where the files are. Edit → Undo moves them back.", + self.relinked + )); + } + if self.copies_removed > 0 { + let what = if self.copies_removed == 1 { + "1 copy of a file that was being moved was".to_string() + } else { + format!("{} copies of files that were being moved were", self.copies_removed) + }; + text.push_str(&format!(" {what} removed from the new place: the original was still where the library has it.")); + } + if self.waiting > 0 { + let (s, were) = if self.waiting == 1 { ("", "was") } else { ("s", "were") }; + text.push_str(&format!( + " {} file{s} that {were} being moved can't be reached (a disk not connected?): LightCraft looks again the next time this library opens.", + self.waiting + )); + } + for p in &self.problems { + text.push(' '); + text.push_str(&p.to_string()); + } + Some(text.trim().to_string()) + } +} + +/// Where one recorded move stands on disk. +enum Found { + /// Reached `to`: point the photos there. + Moved, + /// Still at `from` only, or settled already: nothing to do. + Stayed, + /// The old place doesn't answer (a disk not connected?): keep the move for next time. + Unknown, + /// Reached `to` (the photos point there), and a sidecar couldn't follow it: keep the move + /// for next time, which takes the sidecars along again. + SidecarsLeft, +} + +impl MoveRecord { + pub(crate) fn path(&self) -> &Path { + &self.path + } +} + +impl Session { + /// Write the record of `moves` (made by this session, on this thread) before making them; + /// `None` when the library has no folder of its own (nothing survives a restart there) or + /// there's nothing to move. + pub(crate) fn record_moves(&self, moves: &[(String, String)]) -> Result> { + let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()) else { return Ok(None) }; + if moves.is_empty() { + return Ok(None); + } + write(&dir, moves).map(Some).map_err(|e| EngineError::Other(format!("can't note the move in the library ({e}): nothing was moved"))) + } + + /// The moves `record` names are in the catalog now: the record goes once that is saved + /// (after the command, see [`Session::clear_settled_moves`]). + pub(crate) fn settle_moves(&mut self, record: Option) { + if let Some(r) = record { + self.settled_moves.push(r.path); + } + } + + /// Remove the records of settled moves once everything the library holds is saved; while a + /// save is failing they stay, and the next open finds the files where the record says. + pub(crate) fn clear_settled_moves(&mut self) { + if self.settled_moves.is_empty() || !self.pending_log.is_empty() { + return; + } + for path in std::mem::take(&mut self.settled_moves) { + if let Err(e) = std::fs::remove_file(&path) + && e.kind() != std::io::ErrorKind::NotFound + { + log::warn!("move record {}: {e}", path.display()); + } + } + } + + /// Keep the list of sidecar writes held back for a move ([`Session::held_sidecars`]) beside + /// the records, so a run that ends before the move does still makes them at the next open. + /// A listed write stays listed until it is made: while it is held, or after it failed (the + /// file not reachable yet); the list goes once none is left. + pub(crate) fn save_held_sidecars(&mut self) { + let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(DIR)) else { return }; + let mut ids: std::collections::BTreeSet = read_held(&dir).into_iter().collect(); + let waiting = |id: &PhotoId| self.held_sidecars.contains(id) || self.unsaved_sidecars.contains(id); + if self.library.as_ref().is_some_and(|l| l.is_unprotected()) { + // without the lock, the entries an earlier run (or another program) left wait for an + // open that has it: only what this session listed itself is taken back + ids.retain(|id| !self.held_listed.contains(id) || waiting(id)); + } else { + ids.retain(waiting); + } + ids.extend(self.held_sidecars.iter().copied()); + let listed: std::collections::BTreeSet = + self.held_listed.iter().chain(self.held_sidecars.iter()).copied().filter(|id| ids.contains(id)).collect(); + if ids.is_empty() { + if remove_held(&dir) { + self.held_listed = listed; + } + return; + } + let ids: Vec = ids.into_iter().collect(); + let written = serde_json::to_vec(&ids) + .map_err(std::io::Error::other) + .and_then(|bytes| std::fs::create_dir_all(&dir).and_then(|()| FsStore::open(&dir)?.write_atomic(HELD, &bytes))); + match written { + // (only a list that is written says what this session has listed) + Ok(()) => self.held_listed = listed, + Err(e) => log::warn!("held sidecar writes {}: {e}", dir.join(HELD).display()), + } + } + + /// Bring the library up to date with moves left unfinished (see the module docs): those of an + /// earlier run when the library opens, or of a move whose worker died. The relinks are one undo + /// step; what was done is returned for a notice. + pub fn recover_moves(&mut self) -> Recovered { + self.recover_own_move(None) + } + + /// [`Session::recover_moves`] (every record) when `own` is `None`. With `own`, the record this + /// process's own worker wrote and whose worker died: that record only, with the library's lock + /// or without it (no other program is making that move; the others were told when the library opened). + pub(crate) fn recover_own_move(&mut self, own: Option<&Path>) -> Recovered { + let locked = !self.library.as_ref().is_some_and(|l| l.is_unprotected()); + self.recover_records(&crate::rename::RealFs, locked, own) + } + + /// `locked`: this program holds the library's lock. Without it another program may be making + /// a move right now, and the records are its, so they are left exactly as they are. + #[cfg(test)] + pub(crate) fn recover_moves_with(&mut self, fs: &dyn MoveFs, locked: bool) -> Recovered { + self.recover_records(fs, locked, None) + } + + fn recover_records(&mut self, fs: &dyn MoveFs, locked: bool, own: Option<&Path>) -> Recovered { + let mut out = Recovered::default(); + let Some(dir) = self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(DIR)) else { return out }; + let Ok(entries) = std::fs::read_dir(&dir) else { return out }; + let mut files: Vec = entries.flatten().map(|e| e.path()).collect(); + files.sort(); + if !locked { + let ours = |p: &PathBuf| own == Some(p.as_path()); + // (a dead worker's own move: the other records were already reported when the library opened) + if own.is_none() && files.iter().any(|p| p.extension().is_some_and(|x| x == "json") && !self.settled_moves.contains(p) && !ours(p)) { + out.problems.push(MoveProblem::Unprotected); + } + // only the record of this process's own dead worker is followed + files.retain(ours); + if files.is_empty() { + return out; + } + } else if own.is_some() { + // a dead worker's move is told by its own record: those of earlier runs were followed when the library opened + files.retain(|p| own == Some(p.as_path())); + } + // the photos pointing at each file (a master and its virtual copies), looked up once a + // record is there to read + let mut at: Option>> = None; + let mut partials = HashMap::new(); + let mut ops = Vec::new(); + // (record, the moves to keep in it): written back, or removed when none is left + let mut done: Vec<(PathBuf, Vec<(String, String)>)> = Vec::new(); + for path in files { + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + if name.ends_with(".tmp") { + // a record cut short while it was written: nothing had moved yet + let _ = std::fs::remove_file(&path); + continue; + } + // this session's own records whose moves wait to be saved (they go once they are) + if !name.ends_with(".json") || self.settled_moves.contains(&path) { + continue; + } + let record = match read_record(&path) { + Ok(r) => r, + Err(e) => { + out.problems.push(MoveProblem::UnreadableRecord { record: path.display().to_string(), error: e }); + continue; + } + }; + let mut keep = Vec::new(); + let at = at.get_or_insert_with(|| { + let mut at: HashMap> = HashMap::new(); + for p in self.catalog.photos() { + if let Source::File { path } = &p.source { + at.entry(PathBuf::from(path)).or_default().push((p.id, p.file_name.clone())); + } + } + at + }); + for (from, to) in record.moves { + match recover_one(fs, locked, at, &mut partials, (&from, &to), &mut ops, &mut out) { + Found::Moved | Found::Stayed => {} + // the photos follow; the record keeps the move until its sidecars do too + Found::SidecarsLeft => keep.push((from, to)), + Found::Unknown => { + out.waiting += 1; + keep.push((from, to)); + } + } + } + done.push((path, keep)); + } + let n = ops.len(); + if n > 0 { + let s = if n == 1 { "" } else { "s" }; + if let Err(e) = self.commit(&format!("Finish Moving {n} Photo{s}"), Op::Batch { ops }) { + out.problems.push(MoveProblem::NotFollowed { error: e.to_string() }); + return out; + } + out.relinked = n; + } + // edits made while the files moved had their sidecar writes held back, and those were + // lost with the run: write them now, where the photos are (those that fail, a file not + // reachable yet, stay listed for the next time) + let held = if locked { read_held(&dir) } else { Vec::new() }; + if !held.is_empty() { + if self.xmp.auto_write { + self.auto_write_sidecar_ids(held); + self.save_held_sidecars(); + } else { + remove_held(&dir); + } + } + if n > 0 + && let Err(e) = self.persist() + { + // the records stay: the next open finds the files where they are and does this again + out.problems.push(MoveProblem::NotSaved { error: e.to_string() }); + return out; + } + for (path, keep) in done { + let kept = if keep.is_empty() { + std::fs::remove_file(&path).map_err(|e| e.to_string()) + } else { + serde_json::to_vec(&Record { version: VERSION, moves: keep }).map_err(|e| e.to_string()).and_then(|bytes| { + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + FsStore::open(&dir).and_then(|mut st| st.write_atomic(&name, &bytes)).map_err(|e| e.to_string()) + }) + }; + if let Err(e) = kept { + log::warn!("move record {}: {e}", path.display()); + } + } + out + } +} + +/// One recorded move: where the file is, and what the library does about it. `at`: the photos +/// pointing at each file, kept up to date as moves are followed; `partials`: see +/// [`remove_partials`]. +fn recover_one( + fs: &dyn MoveFs, + locked: bool, + at: &mut HashMap>, + partials: &mut HashMap>, + (from, to): (&str, &str), + ops: &mut Vec, + out: &mut Recovered, +) -> Found { + let (f, t) = (Path::new(from), Path::new(to)); + // the same file spelled another way (a change of letter case only): nothing to remove, ever + let respelling = folded_path(from) == folded_path(to) && fs.same_file(f, t); + if at.get(f).is_none_or(Vec::is_empty) { + // the library already follows the move (it was saved), or the photo is gone. A sidecar + // that couldn't follow its file last time is taken along now + if !respelling && at.get(t).is_some_and(|v| !v.is_empty()) && !fs.exists(f) && fs.is_file(t) { + return follow_sidecars(fs, from, to, out); + } + return Found::Stayed; + } + let moved = if respelling { + fs.listed(t) && !fs.listed(f) + } else { + match (fs.exists(f), fs.is_file(t)) { + // gone from a folder that is still there: it moved. With the folder gone too (a link + // to it is followed), its disk may just not be connected, and the copy at `to` was + // maybe never checked + (false, true) if f.parent().is_some_and(Path::is_dir) => true, + (false, true) => return Found::Unknown, + (true, false) => false, + (true, true) => { + // the copy at `to` is ours: drop it when that loses nothing. One file is dropped + // from `to` only when both names are really there (a move cut between link and + // unlink), never when they are one name spelled two ways + let same = if fs.same_file(f, t) { fs.listed(f) && fs.listed(t) } else { crate::rename::same_contents(f, t).unwrap_or(false) }; + // (without the lock, the copy may be another program's move in progress: left alone; + // a photo of the library at `to` is never a copy of ours) + if locked && same && at.get(t).is_none_or(Vec::is_empty) && fs.remove_file(t).is_ok() { + out.copies_removed += 1; + } else { + out.problems.push(MoveProblem::BothPlaces { from: from.to_string(), to: to.to_string() }); + } + false + } + (false, false) => return Found::Unknown, + } + }; + remove_partials(t, partials, locked); + if !moved { + return Found::Stayed; + } + let sidecars = if respelling { Found::Moved } else { follow_sidecars(fs, from, to, out) }; + let (old_name, new_name) = (file_name(f), file_name(t)); + let photos = at.remove(f).unwrap_or_default(); + for (id, file_name) in &photos { + // a rename changes the name the library shows; a move to another folder keeps it + let file_name = if *file_name == old_name { new_name.clone() } else { file_name.clone() }; + ops.push(Op::SetFile { id: *id, file_name, source: Source::File { path: to.to_string() } }); + } + at.entry(t.to_path_buf()).or_default().extend(photos.into_iter().map(|(id, _)| (id, new_name.clone()))); + sidecars +} + +/// Take the sidecars of the file that went from `from` to `to` along: [`Found::Moved`], or +/// [`Found::SidecarsLeft`] (named in the notice) when one couldn't follow. +fn follow_sidecars(fs: &dyn MoveFs, from: &str, to: &str, out: &mut Recovered) -> Found { + match crate::rename::finish_sidecars(fs, from, to) { + Ok(_) => Found::Moved, + Err(e) => { + out.problems.push(MoveProblem::SidecarStayed { to: to.to_string(), error: e }); + Found::SidecarsLeft + } + } +} + +fn file_name(p: &Path) -> String { + p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default() +} + +/// The sidecar writes a run held back for its move and couldn't make (none when the list is +/// missing, too large or unreadable: logged). +fn read_held(dir: &Path) -> Vec { + let path = dir.join(HELD); + let read = std::fs::metadata(&path) + .and_then(|m| if m.len() > MAX_BYTES { Err(std::io::Error::other(format!("{} bytes", m.len()))) } else { std::fs::read(&path) }); + match read.map_err(|e| e.to_string()).and_then(|b| serde_json::from_slice(&b).map_err(|e| e.to_string())) { + Ok(ids) => ids, + Err(e) => { + if path.exists() { + log::warn!("held sidecar writes {}: {e}", path.display()); + } + Vec::new() + } + } +} + +/// Whether the list is gone now. +fn remove_held(dir: &Path) -> bool { + let path = dir.join(HELD); + match std::fs::remove_file(&path) { + Ok(()) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => true, + Err(e) => { + log::warn!("held sidecar writes {}: {e}", path.display()); + false + } + } +} + +fn read_record(path: &Path) -> std::result::Result { + let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len(); + if len > MAX_BYTES { + return Err(format!("{len} bytes")); + } + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + let r: Record = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + if r.version > VERSION { + return Err(format!("written by a newer LightCraft (format {})", r.version)); + } + Ok(r) +} + +/// Hidden partial copies a cut-off copy left beside `to` (`..lc-partial--`, see +/// `RealFs::copy_no_replace`): never a photo, safe to remove (without the lock, only this process's own). `partials`: each folder's partial +/// copies, listed once however many files of a move went there (a folder of thousands is read +/// once, not once per file). +fn remove_partials(to: &Path, partials: &mut HashMap>, locked: bool) { + let (Some(dir), Some(name)) = (to.parent(), to.file_name()) else { return }; + // (without the lock, only this process's own: another program's may be being written) + let prefix = if locked { + format!(".{}.lc-partial-", name.to_string_lossy()) + } else { + format!(".{}.lc-partial-{}-", name.to_string_lossy(), std::process::id()) + }; + let listed = partials.entry(dir.to_path_buf()).or_insert_with(|| { + std::fs::read_dir(dir) + .map(|entries| entries.flatten().filter(|e| e.file_name().to_string_lossy().contains(".lc-partial-")).map(|e| e.path()).collect()) + .unwrap_or_default() + }); + listed.retain(|p| { + if p.file_name().is_some_and(|n| n.to_string_lossy().starts_with(&prefix)) { + let _ = std::fs::remove_file(p); + false + } else { + true + } + }); +} diff --git a/crates/engine/src/move_job.rs b/crates/engine/src/move_job.rs new file mode 100644 index 00000000000..4bd12daaf93 --- /dev/null +++ b/crates/engine/src/move_job.rs @@ -0,0 +1,403 @@ +//! Moving photos to another folder on disk (`photo.moveToFolder`) as a job in two halves, so the +//! app can run the slow part on a worker thread: copying a large raw or video to a NAS takes as +//! long as the network needs, and no frame should wait for it. +//! +//! * [`start`] (on the session): the checks that need only the library (Local photos, files the +//! library doesn't have, names clashing within the batch), the plan, and the activity row. +//! * [`MoveWork::run`] (anywhere): the checks that read the disk (the folder, each file, names +//! already taken there), the record of the move ([`crate::move_intent`]), then the files, one at +//! a time, reporting progress to the activity row. +//! * [`MoveFinish::finish`] (on the session): the library follows the files that moved, as one +//! undo step. +//! +//! While a move runs, the session refuses anything else that moves files or opens another library +//! ([`Session::refuse_while_moving`]), and doesn't write the XMP sidecars of the photos on their way +//! (they're written once the move ends, at the new place). + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, OnceLock, Weak}; + +use lightcraft_catalog::{Op, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::activity::{Cancel, TaskGuard, TaskHandle}; +use crate::cmd::bad; +use crate::move_intent::MoveRecord; +use crate::rename::{BatchMoveError, MoveFs, RealFs, RenamePlan, folded_path}; +use crate::{EngineError, Result, Session}; + +const C: &str = "photo.moveToFolder"; + +/// The files of a move in progress; the session holds it weakly ([`Session::moving`]), so the move +/// ends for the session when its [`MoveFinish`] goes, however it goes. +#[derive(Debug, Default)] +pub struct MoveTicket { + /// The old paths, folded (see [`folded_path`]). + paths: HashSet, +} + +impl MoveTicket { + fn holds(&self, path: &str) -> bool { + self.paths.contains(&folded_path(path)) + } +} + +/// The half of a move that reads and writes the disk ([`MoveWork::run`]); `Send`, for a worker. +pub struct MoveWork { + folder: String, + /// (from, to), one per file (a master and its virtual copies move once). + moves: Vec<(String, String)>, + /// Where the record of the move goes; `None` for a library without a folder of its own. + library: Option, + task: TaskHandle, + /// Where the worker put the record of the move, for [`MoveFinish::abandon`]. + record: Arc>, +} + +/// What [`MoveWork::run`] did, for [`MoveFinish::finish`]. +pub struct MoveOutcome(Ran); + +enum Ran { + /// Nothing moved, and why (a name taken, a file offline…). + Refused(String), + /// Every file moved. + Moved { record: Option }, + /// A file couldn't move: the earlier ones were moved back (what couldn't be is in `error`). + Failed { error: BatchMoveError, record: Option }, +} + +/// The half of a move that brings the library along ([`MoveFinish::finish`]); it holds the +/// activity row and the session's [`MoveTicket`]. +pub struct MoveFinish { + folder: String, + plans: Vec, + identity: Arc<()>, + ticket: Arc, + guard: TaskGuard, + record: Arc>, +} + +impl std::fmt::Debug for MoveFinish { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MoveFinish").field("folder", &self.folder).field("files", &self.plans.len()).finish() + } +} + +/// Plan the move `p` asks for (`{folder, ids?}`; the selection by default). `None` when every +/// photo is in that folder already. +pub fn start(s: &mut Session, p: &Value) -> Result> { + let folder = crate::cmd::browse::folder_param(p, "folder").ok_or_else(|| bad(C, "missing folder"))?; + let dir = Path::new(folder); + s.refuse_while_moving()?; + // refused before anything touches the disk, as it always was (one look at one folder; the + // worker looks again before the first file moves) + if !dir.is_dir() { + return Err(bad(C, format!("{folder} is not a folder (create it first with folder.create)"))); + } + let ids = s.targets(p).map_err(|e| match e { + EngineError::BadParams { cmd, msg } if cmd.is_empty() => bad(C, msg), + e => e, + })?; + if ids.is_empty() { + return Err(bad(C, "no photos to move: select some or give ids")); + } + let mut plans: Vec = Vec::new(); + let mut taken: HashSet = HashSet::new(); + // the source paths already in `plans`: one look per photo, not a scan of the plans (a selection has no size limit) + let mut planned: HashSet<&str> = HashSet::new(); + let mut clashes: Vec = Vec::new(); + for id in ids { + let ph = s.catalog.photo(id).ok_or_else(|| bad(C, format!("no photo {}", id.0)))?; + if ph.local { + return Err(bad(C, format!("{} is not in the library (Local): add it first", ph.file_name))); + } + let Source::File { path } = &ph.source else { + return Err(bad(C, format!("{} has no file on disk", ph.file_name))); + }; + if planned.contains(path.as_str()) { + continue; // a virtual copy of a photo already moving + } + let src = Path::new(path); + let Some(file) = src.file_name() else { return Err(bad(C, format!("{path}: no file name"))) }; + if src.parent() == Some(dir) { + continue; // already there + } + let to = dir.join(file).to_string_lossy().to_string(); + if !taken.insert(to.to_lowercase()) { + clashes.push(file.to_string_lossy().to_string()); + continue; + } + planned.insert(path.as_str()); + let name = ph.file_name.clone(); + plans.push(RenamePlan { id: id.0, from: name.clone(), to: name, from_path: Some(path.clone()), to_path: Some(to) }); + } + if !clashes.is_empty() { + return Err(bad(C, clash_message(&clashes, folder))); + } + if plans.is_empty() { + return Ok(None); + } + // a sidecar repair left by an earlier step goes first, as before any file move + s.repair_sidecars_with(&RealFs)?; + let moves: Vec<(String, String)> = plans.iter().filter_map(|pl| Some((pl.from_path.clone()?, pl.to_path.clone()?))).collect(); + let ticket = Arc::new(MoveTicket { paths: moves.iter().map(|(from, _)| folded_path(from)).collect() }); + s.moving = Arc::downgrade(&ticket); + let guard = s.activity.start("move", "Moving photos", Cancel::No); + guard.progress(0, moves.len() as u64); + let library = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); + let record = Arc::new(OnceLock::new()); + let work = MoveWork { folder: folder.to_string(), moves, library, task: guard.handle(), record: Arc::clone(&record) }; + let finish = MoveFinish { folder: folder.to_string(), plans, identity: Arc::clone(&s.library_identity), ticket, guard, record }; + Ok(Some((work, finish))) +} + +fn clash_message(names: &[String], folder: &str) -> String { + let s = if names.len() == 1 { "" } else { "s" }; + format!("{} already in {folder}: nothing was moved. Rename the photo{s} first or choose another folder", names.join(", ")) +} + +impl MoveWork { + /// Do the move on the disk (blocking: on a worker thread in the app). + pub fn run(self) -> MoveOutcome { + self.run_with(&RealFs) + } + + pub(crate) fn run_with(self, fs: &dyn MoveFs) -> MoveOutcome { + let MoveWork { folder, moves, library, task, record: slot } = self; + if !Path::new(&folder).is_dir() { + return MoveOutcome(Ran::Refused(format!("{folder} is not a folder (create it first with folder.create)"))); + } + let mut clashes = Vec::new(); + for (from, to) in &moves { + if !fs.is_file(Path::new(from)) { + return MoveOutcome(Ran::Refused(format!("{from} is missing or offline: find it first (Find Missing Photos)"))); + } + if fs.exists(Path::new(to)) { + clashes.push(name_of(to)); + } + } + if !clashes.is_empty() { + return MoveOutcome(Ran::Refused(clash_message(&clashes, &folder))); + } + // the record goes first: whatever stops this from here on, the next open finds the files + let record = match library.as_deref().map(|dir| crate::move_intent::write(dir, &moves)).transpose() { + Ok(r) => r, + Err(e) => return MoveOutcome(Ran::Refused(format!("can't note the move in the library ({e}): nothing was moved"))), + }; + if let Some(r) = &record { + let _ = slot.set(r.path().to_path_buf()); + } + let total = moves.len() as u64; + let ran = crate::rename::move_all_with(fs, &moves, &mut |k, (from, _)| { + task.progress(k as u64, total); + task.detail(&name_of(from)); + }); + match ran { + Ok(()) => { + task.progress(total, total); + MoveOutcome(Ran::Moved { record }) + } + Err(error) => MoveOutcome(Ran::Failed { error, record }), + } + } +} + +fn name_of(path: &str) -> String { + Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()) +} + +impl MoveFinish { + /// How many files the move is for. + pub fn files(&self) -> usize { + self.plans.len() + } + + /// The activity row's id (`activity.list`). + pub fn task_id(&self) -> u64 { + self.guard.id() + } + + /// The worker died part-way (a panic, logged; this path runs only then) and left no outcome: the move is over for the + /// session, the library follows whatever had moved (from the move's record, or, when none was + /// written because the library has no folder of its own, from the files themselves), and the + /// sidecars held back meanwhile are written where their photos now are. + pub fn abandon(self, s: &mut Session) -> crate::move_intent::Recovered { + let MoveFinish { plans, record, ticket, guard, .. } = self; + let own = record.get().cloned(); + drop((ticket, guard)); + let recovered = match own { + Some(own) => s.recover_own_move(Some(&own)), + // (a library with a folder wrote its record before the first file moved: none means nothing had) + None if s.library.as_ref().is_some_and(|l| l.on_disk) => crate::move_intent::Recovered::default(), + None => s.follow_arrived(&plans), + }; + let held: Vec = std::mem::take(&mut s.held_sidecars).into_iter().collect(); + if s.xmp.auto_write { + s.auto_write_sidecar_ids(held); + } + s.save_held_sidecars(); + recovered + } + + /// Point the photos whose files moved at their new place, as one undo step (labelled as + /// before: "Move 3 Photos to “Porto”", counting virtual copies). `{moved, folder}` (in files); + /// an error when nothing moved (`Refused`, `Failed`: the files went back, or the library + /// follows those that couldn't). The sidecars held back meanwhile are written after. + pub fn finish(self, s: &mut Session, out: MoveOutcome) -> Result { + let MoveFinish { folder, plans, identity, ticket, guard, record: _ } = self; + // the move is over for the session: other file work, and these photos' sidecars, may go on + drop(ticket); + drop(guard); + let held: Vec = std::mem::take(&mut s.held_sidecars).into_iter().collect(); + if !Arc::ptr_eq(&identity, &s.library_identity) { + // (opening a library is refused while a move runs; the record stays for that library) + return Err(EngineError::Other( + "another library was opened while photos were being moved: their library follows them when it opens".into(), + )); + } + let r = match out.0 { + Ran::Refused(why) => Err(bad(C, why)), + Ran::Failed { error, record } => { + let op = Op::Batch { ops: s.set_file_ops(&plans) }; + let (message, _, followed) = s.follow_stuck(&op, error, true); + // (a library that could not follow keeps the record for the next open) + if followed { + s.settle_moves(record); + } + Err(EngineError::Other(message)) + } + Ran::Moved { record } => s.follow_moved(&folder, &plans, record), + }; + // (a sidecar write the person switched off meanwhile isn't made now) + if s.xmp.auto_write { + s.auto_write_sidecar_ids(held); + } + s.save_held_sidecars(); + r + } +} + +fn label(n: usize, folder: &str) -> String { + let name = Path::new(folder).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| folder.to_string()); + format!("Move {n} Photo{} to “{name}”", if n == 1 { "" } else { "s" }) +} + +impl Session { + /// The library follows the files `done` moved: one undo step. When it can't (a failed + /// commit), the files go back (the record covers a stop meanwhile). + fn follow_moved(&mut self, folder: &str, done: &[RenamePlan], record: Option) -> Result { + let ops = self.set_file_ops(done); + if ops.is_empty() { + self.settle_moves(record); + return Ok(json!({"moved": 0, "folder": folder})); + } + match self.commit(&label(ops.len(), folder), Op::Batch { ops }) { + Ok(()) => { + self.settle_moves(record); + Ok(json!({"moved": done.len(), "folder": folder})) + } + Err(err) => { + let back: Vec<(String, String)> = done.iter().rev().filter_map(|pl| Some((pl.to_path.clone()?, pl.from_path.clone()?))).collect(); + let r = crate::rename::move_all(&RealFs, &back); + match r { + Ok(()) => { + self.settle_moves(record); + Err(err) + } + // the files stay at the new place and the library doesn't point there: the record stays for the next open + Err(e) => Err(EngineError::Other(format!("{err}; the moved files could not all be moved back: {}", e.message))), + } + } + } + } + + /// A move whose worker died and that wrote no record (the library has no folder of its own): + /// the photos whose file is at the new place and no longer at the old one follow it, as one + /// undo step. A file that did not arrive stays where the library has it. + fn follow_arrived(&mut self, plans: &[RenamePlan]) -> crate::move_intent::Recovered { + use crate::move_intent::{MoveProblem, Recovered}; + let arrived: Vec = plans + .iter() + .filter(|pl| match (&pl.from_path, &pl.to_path) { + (Some(from), Some(to)) => RealFs.is_file(Path::new(to)) && !RealFs.exists(Path::new(from)), + _ => false, + }) + .cloned() + .collect(); + let mut out = Recovered::default(); + // (the worker may have died between a photo file and its sidecars) + for (from, to) in arrived.iter().filter_map(|pl| Some((pl.from_path.as_deref()?, pl.to_path.as_deref()?))) { + if let Err(error) = crate::rename::finish_sidecars(&RealFs, from, to) { + out.problems.push(MoveProblem::SidecarStayed { to: to.to_string(), error }); + } + } + let ops = self.set_file_ops(&arrived); + if ops.is_empty() { + return out; + } + let n = ops.len(); + match self.commit(&format!("Finish Moving {n} Photo{}", if n == 1 { "" } else { "s" }), Op::Batch { ops }) { + Ok(()) => out.relinked = n, + Err(e) => out.problems.push(MoveProblem::NotFollowed { error: e.to_string() }), + } + out + } + + /// The move running in the background, if any. + pub fn move_running(&self) -> bool { + self.moving.strong_count() > 0 + } + + /// Anything else that moves files, or opens another library, waits for a running move: the + /// two would work on the same files, and the move's photos belong to this library. + pub(crate) fn refuse_while_moving(&self) -> Result<()> { + if self.move_running() { + return Err(EngineError::MoveInProgress("photos are being moved to another folder: wait for the move to finish".into())); + } + Ok(()) + } + + /// The photos `op` removes whose file is on its way to another folder (the undo of its import, + /// Delete Permanently, Empty Recently Deleted, the import's purge of a trashed photo), or + /// points at another file (Convert to DNG, Find Missing Photos, Locate, a Synchronize relink, + /// the undo of any of them): the move's finish finds no photo at the old place to point at the + /// new one, and a later undo would bring the photo back at a path the files have left. + pub(crate) fn detached_moving_photos(&self, op: &Op) -> Vec { + let mut found = Vec::new(); + if !self.move_running() { + return found; + } + let mut pending = vec![op]; + while let Some(op) = pending.pop() { + match op { + Op::Batch { ops } => pending.extend(ops), + Op::RemovePhoto { id } | Op::Relink { id, .. } => { + if let Some(Source::File { path }) = self.catalog.photo(*id).map(|p| &p.source) + && self.is_moving(path) + && !found.contains(id) + { + found.push(*id); + } + } + _ => {} + } + } + found + } + + /// Refuse a change that would detach `moving` (see [`Session::detached_moving_photos`]), + /// saying how many photos it is. Nothing to refuse when the list is empty. + pub(crate) fn refuse_detaching(&self, moving: &[PhotoId]) -> Result<()> { + match moving.len() { + 0 => Ok(()), + 1 => Err(EngineError::MoveInProgress("1 photo is being moved to another folder: wait for the move to finish".into())), + n => Err(EngineError::MoveInProgress(format!("{n} photos are being moved to another folder: wait for the move to finish"))), + } + } + + /// The file `path` is on its way to another folder (its sidecar waits until it arrives). + pub(crate) fn is_moving(&self, path: &str) -> bool { + Weak::upgrade(&self.moving).is_some_and(|t| t.holds(path)) + } +} diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 8b165245b1b..a76ab4219ad 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -38,12 +38,10 @@ mod plan; mod sidecar; mod tokens; -pub(crate) use fs::{MoveFs, RealFs}; -#[cfg(test)] -use fs::{folded_path, same_contents}; -pub(crate) use moves::move_all; +pub(crate) use fs::{MoveFs, RealFs, folded_path, same_contents}; #[cfg(test)] pub(crate) use moves::move_file_with; +pub(crate) use moves::{BatchMoveError, finish_sidecars, move_all, move_all_with}; pub use moves::{MoveError, move_file}; pub use plan::{plan_rename_photos, rename_photos}; #[cfg(test)] diff --git a/crates/engine/src/rename/fs.rs b/crates/engine/src/rename/fs.rs index 71de1a7843a..a513efed591 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -179,7 +179,7 @@ fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> { /// Whether files `a` and `b` hold the same bytes: lengths first, then 1 MiB chunks at a time, so /// a large raw or video is never read into memory whole. -pub(super) fn same_contents(a: &Path, b: &Path) -> std::io::Result { +pub(crate) fn same_contents(a: &Path, b: &Path) -> std::io::Result { const CHUNK: usize = 1 << 20; let (mut fa, mut fb) = (std::fs::File::open(a)?, std::fs::File::open(b)?); if fa.metadata()?.len() != fb.metadata()?.len() { @@ -220,7 +220,7 @@ pub(super) fn is_respelling(fs: &dyn MoveFs, from: &Path, to: &Path) -> bool { } /// Windows accepts both separators; spelling differences must not hide file identity. -pub(super) fn folded_path(path: &str) -> String { +pub(crate) fn folded_path(path: &str) -> String { if cfg!(windows) { path.replace('\\', "/").to_lowercase() } else { path.to_lowercase() } } diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 07d7fdfc3db..ef54515a8ca 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -19,6 +19,42 @@ impl std::fmt::Display for MoveError { } } +/// A sidecar candidate of [`sidecars`] that is there. An upper-case `.XMP` spelling that only +/// answers through a case-insensitive volume is the lower-case sidecar: it is tracked and moved +/// under its own name, so `a.xmp` doesn't become `b.XMP`. +fn sidecar_present(fs: &dyn MoveFs, (sc, _, upper): &(PathBuf, SidecarNaming, bool)) -> bool { + fs.is_file(sc) && (!*upper || fs.listed(sc)) +} + +/// The sidecars of the photo file `from` that go along to `to`, worked out lazily: each one is +/// looked at only when the one before it has moved (two spellings can name one file). +fn sidecar_moves<'a>(fs: &'a dyn MoveFs, from: &str, to: &'a str) -> impl Iterator + 'a { + sidecars(from).into_iter().filter(move |s| sidecar_present(fs, s)).map(move |(sc, naming, upper)| { + let mut dst = crate::sidecar::sidecar_path(to, naming); + if upper { + dst = dst.with_extension("XMP"); + } + // A stem sidecar another photo still uses is copied, not taken away (issue #92). + let copied = naming == SidecarNaming::Stem && fs.stem_sibling(&sc).is_some(); + SidecarMove { from: sc, to: dst, copied, companions: Vec::new() } + }) +} + +/// The photo file already went from `from` to `to`, and its sidecars may not have (the app was +/// stopped between the two): take them along, as [`move_file`] would have. Never overwrites: a +/// sidecar whose place is taken stays where it is. How many moved, or the first that couldn't. +pub(crate) fn finish_sidecars(fs: &dyn MoveFs, from: &str, to: &str) -> std::result::Result { + let mut moved = 0; + for m in sidecar_moves(fs, from, to) { + if !m.needed(fs) { + continue; + } + m.apply(fs).map_err(|e| format!("{} → {}: {e}", m.from.display(), m.to.display()))?; + moved += 1; + } + Ok(moved) +} + /// Move `from` to `to` (never over an existing file) together with its sidecars. On error the /// moves are undone; whatever can't be undone is named in the error (see [`MoveError`]). pub fn move_file(from: &str, to: &str) -> std::result::Result<(), MoveError> { @@ -37,22 +73,14 @@ pub(crate) fn move_file_with(fs: &dyn MoveFs, from: &str, to: &str) -> std::resu if fs.exists(t) && !is_respelling(fs, f, t) { return Err(fail(format!("{to} already exists"))); } - // An upper-case `.XMP` spelling that only answers through a case-insensitive volume is the - // lower-case sidecar: track and move it under its own name, so `a.xmp` doesn't become `b.XMP`. - let present = |(sc, _, upper): &(PathBuf, SidecarNaming, bool)| fs.is_file(sc) && (!*upper || fs.listed(sc)); - let mut packets: Vec = - sidecars(from).into_iter().filter(present).map(|(path, _, _)| RetainedPacket { version: fs.packet_version(&path).ok(), path }).collect(); + let mut packets: Vec = sidecars(from) + .into_iter() + .filter(|s| sidecar_present(fs, s)) + .map(|(path, _, _)| RetainedPacket { version: fs.packet_version(&path).ok(), path }) + .collect(); move_one(fs, f, t).map_err(|e| fail(format!("rename {from}: {e}")))?; let mut done: Vec = Vec::new(); - let mut remaining = sidecars(from).into_iter().filter(present).map(|(sc, naming, upper)| { - let mut dst = crate::sidecar::sidecar_path(to, naming); - if upper { - dst = dst.with_extension("XMP"); - } - // A stem sidecar another photo still uses is copied, not taken away (issue #92). - let copied = naming == SidecarNaming::Stem && fs.stem_sibling(&sc).is_some(); - SidecarMove { from: sc, to: dst, copied, companions: Vec::new() } - }); + let mut remaining = sidecar_moves(fs, from, to); while let Some(m) = remaining.next() { if !m.needed(fs) { continue; // never overwrite: the old sidecar stays where it was @@ -123,8 +151,19 @@ pub(crate) struct BatchMoveError { /// Move the files `moves` names, all or nothing: after a failure the earlier moves are undone. /// Moves that can't be undone (e.g. the network share went away) are reported, not ignored. pub(crate) fn move_all(fs: &dyn MoveFs, moves: &[(String, String)]) -> std::result::Result<(), BatchMoveError> { + move_all_with(fs, moves, &mut |_, _| {}) +} + +/// [`move_all`], telling `before(k, move)` before each move (`k` moved so far): progress for a +/// batch that runs on a worker. +pub(crate) fn move_all_with( + fs: &dyn MoveFs, + moves: &[(String, String)], + before: &mut dyn FnMut(usize, &(String, String)), +) -> std::result::Result<(), BatchMoveError> { let mut done: Vec<&(String, String)> = Vec::new(); for m in moves { + before(done.len(), m); let Err(e) = move_file_with(fs, &m.0, &m.1) else { done.push(m); continue; diff --git a/crates/engine/src/rename/plan.rs b/crates/engine/src/rename/plan.rs index 4c9620bf13c..d2959490dbc 100644 --- a/crates/engine/src/rename/plan.rs +++ b/crates/engine/src/rename/plan.rs @@ -172,26 +172,11 @@ impl Session { /// (all or nothing), then commit one undoable op, labelled `label(count)`, that points the /// photos (and their virtual copies) at the new paths. Undo moves the files back. pub(crate) fn apply_file_plans(&mut self, fs: &dyn MoveFs, plans: &[RenamePlan], label: &dyn Fn(usize) -> String) -> Result { + self.refuse_while_moving()?; // A partly completed rename can already have the requested photo name. Repair // its sidecars before treating that empty move list as a successful retry. self.repair_sidecars_with(fs)?; - let mut ops = Vec::new(); - let by_path: HashMap<&str, &RenamePlan> = plans.iter().filter_map(|p| p.from_path.as_deref().map(|f| (f, p))).collect(); - for p in self.catalog.photos() { - let plan = match &p.source { - Source::File { path } => by_path.get(path.as_str()).copied(), - Source::Demo { .. } => plans.iter().find(|x| x.id == p.id.0 && x.from_path.is_none()), - }; - let Some(plan) = plan else { continue }; - let source = match &plan.to_path { - Some(t) if matches!(&p.source, Source::File { path } if Path::new(path) == Path::new(t)) => p.source.clone(), - Some(t) => Source::File { path: t.clone() }, - None => p.source.clone(), - }; - if plan.to != p.file_name || source != p.source { - ops.push(Op::SetFile { id: p.id, file_name: plan.to.clone(), source }); - } - } + let ops = self.set_file_ops(plans); let n = ops.len(); let op = Op::Batch { ops }; let moves: Vec<(String, String)> = plans @@ -201,30 +186,65 @@ impl Session { _ => None, }) .collect(); - if let Err(e) = move_all(fs, &moves) { - return Err(EngineError::Other(self.follow_stuck(&op, e, true).0)); + // noted before anything moves: a stop part-way is found and followed at the next open + let record = self.record_moves(&moves)?; + let moved = move_all(fs, &moves); + if let Err(e) = moved { + let (message, _, followed) = self.follow_stuck(&op, e, true); + // (a library that could not follow keeps the record for the next open) + if followed { + self.settle_moves(record); + } + return Err(EngineError::Other(message)); } if n > 0 && let Err(err) = self.commit(&label(n), op) { let back: Vec<(String, String)> = moves.iter().rev().map(|(a, b)| (b.clone(), a.clone())).collect(); if let Err(e) = move_all(fs, &back) { + // the files stay at the new place and the library doesn't point there: the record stays for the next open return Err(EngineError::Other(format!("{err}; the renamed files could not all be moved back: {}", e.message))); } + self.settle_moves(record); return Err(err); } + self.settle_moves(record); Ok(n) } + /// The catalog changes that point the photos `plans` name (and their virtual copies, which + /// share the file) at their new names and paths. No file-system calls. + pub(crate) fn set_file_ops(&self, plans: &[RenamePlan]) -> Vec { + let mut ops = Vec::new(); + let by_path: HashMap<&str, &RenamePlan> = plans.iter().filter_map(|p| p.from_path.as_deref().map(|f| (f, p))).collect(); + for p in self.catalog.photos() { + let plan = match &p.source { + Source::File { path } => by_path.get(path.as_str()).copied(), + Source::Demo { .. } => plans.iter().find(|x| x.id == p.id.0 && x.from_path.is_none()), + }; + let Some(plan) = plan else { continue }; + let source = match &plan.to_path { + Some(t) if matches!(&p.source, Source::File { path } if Path::new(path) == Path::new(t)) => p.source.clone(), + Some(t) => Source::File { path: t.clone() }, + None => p.source.clone(), + }; + if plan.to != p.file_name || source != p.source { + ops.push(Op::SetFile { id: p.id, file_name: plan.to.clone(), source }); + } + } + ops + } + /// After a failed batch of moves for `op`: point the photos whose files stayed moved at /// their new paths (an undoable "partly" rename when `undoable`, otherwise a plain logged - /// change), so the library matches the disk. Returns the message and, for a history retry, - /// the correction's inverse file ops (so a retry doesn't lose the original paths). - pub(crate) fn follow_stuck(&mut self, op: &Op, e: BatchMoveError, undoable: bool) -> (String, Vec) { + /// change), so the library matches the disk. Returns the message, for a history retry the + /// correction's inverse file ops (so a retry doesn't lose the original paths), and whether the + /// library follows the files now (when not, the move's record has to stay for the next open). + pub(crate) fn follow_stuck(&mut self, op: &Op, e: BatchMoveError, undoable: bool) -> (String, Vec, bool) { let mut msg = e.message; let pending_sidecars = e.pending_sidecars; if e.stuck.is_empty() && (!undoable || pending_sidecars.is_empty()) { - return (msg, Vec::new()); + return (msg, Vec::new(), true); } let to: HashSet<&str> = e.stuck.iter().map(|m| m.1.as_str()).collect(); let mut keep = Vec::new(); @@ -254,6 +274,8 @@ impl Session { Err(e) => Err(e), } }; + // (with no file stuck at the new place there is nothing the library has to follow) + let followed = applied.is_ok() || n == 0; match applied { Ok(()) if n > 0 => msg .push_str(&format!(". {n} file{s} could not be moved back and kept the new name; the library now points there: {}", list.join(", "))), @@ -263,7 +285,7 @@ impl Session { list.join(", ") )), } - (msg, inverses) + (msg, inverses, followed) } /// Physical moves to the final `SetFile` destination of each photo. A merged history diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index d13b9512571..c1afeea64d3 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -785,6 +785,10 @@ impl Session { return Err(EngineError::Other(format!("{} is a virtual copy: its settings live only in the library", p.file_name))); } let orig = file_path(p).ok_or_else(|| EngineError::Other(format!("{} is not a file on disk", p.file_name)))?; + if self.is_moving(orig) { + // the file and its sidecar are on their way: a write now would land behind them + return Err(EngineError::Other(format!("{} is being moved: its sidecar is written once it arrives", p.file_name))); + } // A relative path would be taken from the working directory. if Path::new(orig).is_relative() || !Path::new(orig).is_file() { return Err(EngineError::Other(format!("{}: the original {orig} is missing; no XMP sidecar is written", p.file_name))); @@ -878,16 +882,24 @@ impl Session { self.auto_write_sidecar_ids(ids); } - fn auto_write_sidecar_ids(&mut self, ids: Vec) { + pub(crate) fn auto_write_sidecar_ids(&mut self, ids: Vec) { if ids.is_empty() { return; } let owners = StemOwners::among(&self.catalog, &ids); + let held = self.held_sidecars.len(); + // a write that failed before is made now: a list of held writes may name it + let mut made_late = false; for id in ids { + // on its way to another folder: written once it arrives (`move_job`), not a failure + if self.catalog.photo(id).and_then(|p| file_path(p)).is_some_and(|f| self.is_moving(f)) { + self.held_sidecars.insert(id); + continue; + } if self.catalog.photo(id).is_some_and(|p| file_path(p).is_some() && p.copy_of.is_none()) { match self.save_sidecar_with(id, &owners) { Ok(_) => { - self.unsaved_sidecars.remove(&id); + made_late |= self.unsaved_sidecars.remove(&id); } Err(e) => { // kept for a retry once the file is reachable: a network share that dropped out mustn't leave @@ -898,6 +910,11 @@ impl Session { } } } + if self.held_sidecars.len() > held || made_late { + // kept on disk too: a run that ends before the move does still writes them, and + // one made since leaves the list + self.save_held_sidecars(); + } } /// How many photos have an automatic sidecar write waiting (it failed: the folder offline, read-only or full). @@ -919,6 +936,7 @@ impl Session { None => { self.unsaved_sidecars.remove(&id); } + Some(path) if self.is_moving(&path) => {} Some(path) if self.media.availability.exists(&path) == Some(true) => ready.push(id), Some(_) => {} } @@ -937,6 +955,10 @@ impl Session { Err(e) => log::debug!("retry XMP: {e}"), } } + if written > 0 { + // a list of held writes may name them: the next open mustn't make them again + self.save_held_sidecars(); + } written } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..9152782c118 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -32,6 +32,7 @@ mod library; mod lightroom_folder; mod mask_effects; mod merge; +mod move_job; mod move_to_share; mod organize; mod persist; diff --git a/crates/engine/src/tests/move_job.rs b/crates/engine/src/tests/move_job.rs new file mode 100644 index 00000000000..a3889228635 --- /dev/null +++ b/crates/engine/src/tests/move_job.rs @@ -0,0 +1,974 @@ +//! Moving photos to another folder as a job the app runs off the UI thread (`move_job`), and the +//! record that lets the next open follow a move cut short (`move_intent`): +//! +//! * the activity row shows how far it has got; +//! * while a move runs, nothing else moves files or opens another library, and the moving photos' +//! sidecars are written once they arrive, at the new place; +//! * the checks that read the disk refuse on the worker, before anything moves; +//! * a record is on disk before the first file moves and gone once the library is saved; +//! * a move cut short (the app killed) is followed the next time the library opens. + +use std::cell::Cell; +use std::path::{Path, PathBuf}; + +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::rename::{MoveFs, RealFs}; + +/// A scratch folder with a library, `local/` and `share/`, gone with the test. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-movejob-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("local")).unwrap(); + std::fs::create_dir_all(dir.join("share")).unwrap(); + Scratch(dir) + } + fn path(&self, rel: &str) -> String { + self.0.join(rel).to_string_lossy().to_string() + } + fn library(&self) -> PathBuf { + self.0.join("library") + } + fn records(&self) -> Vec { + std::fs::read_dir(self.library().join("moves")) + .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).collect()) + .unwrap_or_default() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn open(dir: &Scratch) -> Session { + let mut s = Session::new(); + s.open_library(dir.library(), false).unwrap(); + s +} + +/// A photo file `path` in the library (journaled, so it survives a reopen). +fn add(s: &mut Session, path: &str, body: &str) -> PhotoId { + std::fs::write(path, body).unwrap(); + let id = s.catalog.alloc_photo_id(); + let name = Path::new(path).file_name().unwrap().to_string_lossy().to_string(); + let p = Photo::new(id, Source::File { path: path.into() }, &name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.execute_fn("test.add", |s| { + s.commit("Add", Op::AddPhoto { photo: Box::new(p) })?; + Ok(Value::Null) + }) + .unwrap(); + id +} + +fn file_of(s: &Session, id: PhotoId) -> String { + match &s.catalog.photo(id).unwrap().source { + Source::File { path } => path.clone(), + _ => panic!("not a file"), + } +} + +#[test] +fn the_activity_row_shows_progress_and_the_move_is_one_undo_step() { + let dir = Scratch::new("progress"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + std::fs::write(dir.path("local/a.xmp"), "").unwrap(); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + let steps = s.undo.len(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0, b.0], "folder": dir.path("share")})).unwrap().unwrap(); + let row = s.activity.list().into_iter().find(|t| t.kind == "move").unwrap(); + assert_eq!((row.label.as_str(), row.done, row.total, row.cancellable), ("Moving photos", 0, 2, false)); + // the files move while the session isn't asked for anything; the row has caught up when they are done + let out = work.run(); + let row = s.activity.list().into_iter().find(|t| t.kind == "move").unwrap(); + assert_eq!((row.done, row.total, row.detail.as_str()), (2, 2, "b.jpg")); + // the library only follows when the session finishes the move + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + let r = s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(r, json!({"moved": 2, "folder": dir.path("share")})); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg")); + assert_eq!(file_of(&s, b), dir.path("share/b.jpg")); + assert!(Path::new(&dir.path("share/a.xmp")).is_file() && !Path::new(&dir.path("local/a.xmp")).exists(), "the sidecar goes along"); + assert!(s.activity.list().is_empty(), "the row is gone"); + assert!(!s.move_running()); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Photos to “share”"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + assert!(Path::new(&dir.path("local/a.xmp")).is_file() && Path::new(&dir.path("local/b.jpg")).is_file()); +} + +#[test] +fn a_running_move_holds_back_other_file_moves_and_another_library() { + let dir = Scratch::new("busy"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + // a step that moved files, to undo while the next move runs + s.execute("photo.moveToFolder", &json!({"ids": [b.0], "folder": dir.path("share")})).unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + assert!(s.move_running()); + let busy = |r: crate::Result| { + let e = r.unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + }; + busy(s.execute("photo.moveToFolder", &json!({"ids": [b.0], "folder": dir.path("local")}))); + s.selection = crate::Selection::single(b); + busy(s.execute("photo.rename", &json!({"ids": [b.0], "template": "renamed"}))); + busy(s.execute("folder.rename", &json!({"path": dir.path("share"), "name": "nas"}))); + busy(s.execute("edit.undo", &json!({}))); + let other = dir.0.join("other-library"); + let e = Session::open_library(&mut s, &other, false).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + // a switch checks before it closes anything: refused there, the library stays open as it is + let e = s.check_library(&other).unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + // an edit that moves no file still goes + s.execute("photo.rate", &json!({"ids": [b.0], "rating": 3})).unwrap(); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + // and once it's over, all of it works again + s.execute("edit.undo", &json!({})).unwrap(); + s.open_library(&other, false).unwrap(); +} + +/// Undoing the import of a photo whose file is on its way to another folder is a catalog-only step +/// (no file to move), but it would leave the move's finish with no photo to point at the new place. +#[test] +fn undoing_the_import_of_a_moving_photo_waits_for_the_move() { + let dir = Scratch::new("busy-remove"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + let e = s.execute("edit.undo", &json!({})).unwrap_err().to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + assert!(s.catalog.photo(a).is_some(), "the photo stays while its file moves"); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg")); + // once the move is over, the steps undo in turn: the move, then the import + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.photo(a).is_none()); +} + +/// The same for undoing a relink (Convert to DNG, Find Missing Photos): it would point the photo +/// back at the old file while its current one is on its way to another folder. +#[test] +fn undoing_a_relink_of_a_moving_photo_waits_for_the_move() { + let dir = Scratch::new("busy-relink"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + std::fs::write(dir.path("local/a2.jpg"), "A2").unwrap(); + let to = dir.path("local/a2.jpg"); + s.execute_fn("test.relink", |s| { + s.commit("Relink", crate::cmd::missing::relink_op(a, &to))?; + Ok(Value::Null) + }) + .unwrap(); + assert_eq!(file_of(&s, a), to); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + let e = s.execute("edit.undo", &json!({})).unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + assert_eq!(file_of(&s, a), to, "the photo keeps pointing at the file that moves"); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a2.jpg")); +} + +/// A photo whose file is on its way to another folder is refused everything that would take it out +/// of the library or point it at another file; the library keeps it where the move's finish looks. +/// Run with the move in flight, then let it finish and check it still followed the file. +fn moving_one(tag: &str) -> (Scratch, Session, PhotoId, crate::move_job::MoveWork, crate::move_job::MoveFinish) { + let dir = Scratch::new(tag); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + (dir, s, a, work, finish) +} + +fn finish_and_check(s: &mut Session, dir: &Scratch, a: PhotoId, work: crate::move_job::MoveWork, finish: crate::move_job::MoveFinish) { + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(s, a), dir.path("share/a.jpg"), "the library followed the file"); +} + +#[test] +fn delete_permanently_waits_for_the_move_of_the_photos_it_would_remove() { + let dir = Scratch::new("busy-delete"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + let c = add(&mut s, &dir.path("local/c.jpg"), "C"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0, b.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.selection = crate::Selection::single(a); + let steps = s.undo.len(); + let err = s.execute("photo.deletePermanently", &json!({"ids": [a.0]})).unwrap_err(); + assert_eq!(err.kind(), crate::ErrorKind::MoveInProgress, "{err}"); + let e = err.to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + // a batch is refused as a whole when any of its photos moves, and says how many + let e = s.execute("photo.deletePermanently", &json!({"ids": [a.0, b.0, c.0]})).unwrap_err().to_string(); + assert_eq!(e, "2 photos are being moved to another folder: wait for the move to finish"); + assert!([a, b, c].iter().all(|id| s.catalog.photo(*id).is_some()), "nothing was removed"); + assert_eq!(s.undo.len(), steps); + // a photo that stays is not held back + s.execute("photo.deletePermanently", &json!({"ids": [c.0]})).unwrap(); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg")); + s.execute("photo.deletePermanently", &json!({"ids": [a.0]})).unwrap(); + assert!(s.catalog.photo(a).is_none(), "once the move is over it goes"); +} + +#[test] +fn empty_recently_deleted_waits_for_the_move_of_a_trashed_photo() { + let (dir, mut s, a, work, finish) = moving_one("busy-empty"); + // the photo is put in Recently Deleted while its file moves: that detaches nothing + s.selection = crate::Selection::single(a); + s.execute("photo.delete", &json!({"ids": [a.0]})).unwrap(); + let e = s.execute("library.emptyRecentlyDeleted", &json!({})).unwrap_err().to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + assert!(s.catalog.photo(a).is_some()); + finish_and_check(&mut s, &dir, a, work, finish); + s.execute("library.emptyRecentlyDeleted", &json!({})).unwrap(); + assert!(s.catalog.photo(a).is_none()); +} + +#[test] +fn the_imports_purge_of_a_trashed_photo_waits_for_its_move() { + let dir = Scratch::new("busy-purge"); + let mut s = open(&dir); + let path = dir.path("local/a.png"); + let img = + lightcraft_raster::Rgba8 { width: 24, height: 16, data: (0..24 * 16).map(|i| [(i % 24 * 9) as u8, (i / 24 * 11) as u8, 7, 255]).collect() }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let imported = s.execute("library.import", &json!({"paths": [path]})).unwrap(); + let a = PhotoId(imported["imported"][0].as_u64().unwrap()); + s.execute("photo.delete", &json!({"ids": [a.0]})).unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + // importing the same file as new would delete the trashed record its file belongs to + let e = s.execute("library.import", &json!({"paths": [path], "onDeleted": "fresh"})).unwrap_err().to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + assert!(s.catalog.photo(a).is_some_and(|p| p.deleted), "the trashed record stays"); + assert_eq!(s.catalog.len(), 1, "and nothing was added"); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a.png")); +} + +#[test] +fn convert_to_dng_waits_for_the_move_of_the_raw() { + let dir = Scratch::new("busy-convert"); + let mut s = open(&dir); + let path = dir.path("local/a.arw"); + std::fs::write(&path, "RAW").unwrap(); + let a = s.catalog.alloc_photo_id(); + let mut p = Photo::new(a, Source::File { path: path.clone() }, "a.arw", "ARW", 60, 40, "2026-01-01T10:00:00"); + p.kind = lightcraft_catalog::MediaKind::Raw; + s.execute_fn("test.add", |s| { + s.commit("Add", Op::AddPhoto { photo: Box::new(p) })?; + Ok(Value::Null) + }) + .unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.selection = crate::Selection::single(a); + let e = s.execute("photo.convertToDng", &json!({"ids": [a.0]})).unwrap_err().to_string(); + assert!(e.contains("1 photo is being moved to another folder"), "{e}"); + assert!(!Path::new(&dir.path("local/a.dng")).exists(), "no DNG was written beside the moving file"); + assert_eq!(file_of(&s, a), dir.path("local/a.arw")); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a.arw")); +} + +#[test] +fn find_missing_and_locate_wait_for_the_move_of_the_photos_they_would_relink() { + let (dir, mut s, a, work, finish) = moving_one("busy-find"); + std::fs::write(dir.path("local/a2.jpg"), "A2").unwrap(); + let from = dir.path("local/a.jpg"); + let to = dir.path("local/a2.jpg"); + let found = json!({"found": [{"id": a.0, "from": from, "to": to, "by": "name"}], "missing": 0, "ambiguous": []}); + let e = s.execute("library.findMissing", &found).unwrap_err().to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + let e = s.execute("photo.relink", &json!({"id": a.0, "path": to})).unwrap_err().to_string(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + assert_eq!(file_of(&s, a), from, "the photo keeps pointing at the file that moves"); + finish_and_check(&mut s, &dir, a, work, finish); +} + +#[test] +fn a_running_move_refuses_opening_before_touching_the_target() { + let dir = Scratch::new("busy-open"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + // a target that doesn't exist yet: refused without creating its folder or lock file + let missing = dir.0.join("not-yet"); + let e = s.open_library(&missing, false).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + assert!(!missing.exists(), "the refused open left nothing behind"); + // a target another holder has locked: the move is what's reported, not the lock + let held = dir.0.join("held"); + let _lock = { + let mut other = Session::new(); + other.open_library(&held, false).unwrap(); + other + }; + let e = s.open_library(&held, false).map(|_| ()).unwrap_err().to_string(); + assert!(e.contains("being moved"), "{e}"); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); +} + +#[test] +fn a_moving_photos_sidecar_is_written_once_it_arrives_where_it_arrives() { + let dir = Scratch::new("sidecar"); + let mut s = open(&dir); + s.xmp.auto_write = true; + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.selection = crate::Selection::single(a); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 4})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().rating, 4, "the edit is kept"); + assert!(!Path::new(&dir.path("local/a.xmp")).exists(), "nothing is written behind the moving file"); + assert_eq!(s.unsaved_sidecars(), 0, "held for the move, not a failed write to warn about"); + let held = dir.library().join("moves/held-sidecars"); + assert!(held.is_file(), "the held write is on disk too, for a run that ends before the move"); + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert!(!held.exists(), "and gone once it is made: the next open mustn't make it again"); + let xmp = std::fs::read_to_string(dir.path("share/a.xmp")).expect("written at the new place"); + assert!(xmp.contains("xmp:Rating=\"4\"") || xmp.contains("4"), "{xmp}"); + assert!(!Path::new(&dir.path("local/a.xmp")).exists()); + assert_eq!(s.unsaved_sidecars(), 0); +} + +#[test] +fn a_move_whose_worker_dies_is_followed_and_its_held_sidecars_are_written() { + let dir = Scratch::new("abandon"); + let mut s = open(&dir); + s.xmp.auto_write = true; + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.selection = crate::Selection::single(a); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 5})).unwrap(); + // the files moved, then the worker died before saying so: no outcome reaches the session + drop(work.run()); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the library follows the file"); + let xmp = std::fs::read_to_string(dir.path("share/a.xmp")).expect("the held sidecar is written where the photo is"); + assert!(xmp.contains("xmp:Rating=\"5\"") || xmp.contains("5"), "{xmp}"); + assert!(!s.move_running() && s.activity.list().is_empty()); + assert!(dir.records().is_empty(), "{:?}", dir.records()); +} + +#[test] +fn a_worker_that_dies_in_a_library_without_a_folder_still_has_its_files_followed() { + // no library folder: no record is written, so nothing but the plans says where the files went + let dir = Scratch::new("abandon-no-record"); + let mut s = Session::new(); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0, b.0], "folder": dir.path("share")})).unwrap().unwrap(); + drop(work.run()); + // a file that never arrived (the worker died before it): it stays where it is + std::fs::rename(dir.path("share/b.jpg"), dir.path("local/b.jpg")).unwrap(); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + assert_eq!(r["problems"], json!([]), "{r}"); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the library follows the file that arrived"); + assert_eq!(file_of(&s, b), dir.path("local/b.jpg"), "and leaves the one that did not"); + assert!(!s.move_running() && s.activity.list().is_empty()); +} + +#[test] +fn without_a_record_a_sidecar_the_worker_did_not_reach_follows_its_photo() { + let dir = Scratch::new("abandon-no-record-sidecar"); + let mut s = Session::new(); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + drop(work.run()); + // the worker died between the photo file and its sidecar + std::fs::write(dir.path("local/a.xmp"), "").unwrap(); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + assert_eq!(r["problems"], json!([]), "{r}"); + assert!(Path::new(&dir.path("share/a.xmp")).is_file() && !Path::new(&dir.path("local/a.xmp")).exists(), "{r}"); +} + +#[test] +fn a_dead_workers_message_is_not_about_the_records_of_earlier_runs() { + let dir = Scratch::new("abandon-earlier-records"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + // a record an earlier run left that this version can't read (the open reported it; it stays as it is) + let earlier = dir.library().join("moves/move-1-0-0.json"); + std::fs::create_dir_all(earlier.parent().unwrap()).unwrap(); + std::fs::write(&earlier, "not a record").unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + drop(work.run()); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + assert_eq!(r["problems"], json!([]), "every file of this move was followed: {r}"); + assert_eq!(std::fs::read_to_string(&earlier).unwrap(), "not a record", "left as it is"); +} + +#[test] +fn a_file_with_the_same_bytes_that_is_another_photo_of_the_library_is_never_removed_as_a_copy() { + let dir = Scratch::new("copy-is-a-photo"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "same"); + let b = add(&mut s, &dir.path("share/a.jpg"), "same"); + // a record whose move was refused at the first file (the name was taken) and then cut short + crate::move_intent::write(&dir.library(), &[(dir.path("local/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + let r = s.recover_moves(); + assert_eq!(r.copies_removed, 0, "{r:?}"); + assert!(matches!(r.problems.as_slice(), [crate::move_intent::MoveProblem::BothPlaces { .. }]), "{r:?}"); + assert!(Path::new(&dir.path("share/a.jpg")).is_file(), "another photo's file stays"); + assert_eq!((file_of(&s, a), file_of(&s, b)), (dir.path("local/a.jpg"), dir.path("share/a.jpg"))); +} + +#[test] +fn checks_that_read_the_disk_refuse_on_the_worker_before_anything_moves() { + let dir = Scratch::new("refuse"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + // the name is taken after the move was planned: the worker sees it + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0, b.0], "folder": dir.path("share")})).unwrap().unwrap(); + std::fs::write(dir.path("share/b.jpg"), "someone else's").unwrap(); + let out = work.run(); + let e = s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap_err().to_string(); + assert!(e.contains("b.jpg already in") && e.contains("nothing was moved"), "{e}"); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + assert!(Path::new(&dir.path("local/a.jpg")).is_file() && !Path::new(&dir.path("share/a.jpg")).exists()); + assert_eq!(std::fs::read_to_string(dir.path("share/b.jpg")).unwrap(), "someone else's"); + assert!(dir.records().is_empty(), "no record for a move that never began"); + assert!(!s.move_running()); +} + +#[test] +fn held_sidecars_are_not_written_when_auto_write_was_switched_off_during_the_move() { + let dir = Scratch::new("autowrite-off"); + let mut s = open(&dir); + s.xmp.auto_write = true; + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.selection = crate::Selection::single(a); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 4})).unwrap(); + s.xmp.auto_write = false; + let out = work.run(); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert!(!Path::new(&dir.path("share/a.xmp")).exists() && !Path::new(&dir.path("local/a.xmp")).exists()); + assert_eq!(s.unsaved_sidecars(), 0); +} + +/// The disk, checking that the move's record is in the library before the first file moves. +struct Recorded<'a> { + dir: &'a Scratch, + /// What the record names (a file name). + needle: &'static str, + seen: Cell, +} + +impl MoveFs for Recorded<'_> { + fn exists(&self, p: &Path) -> bool { + RealFs.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + RealFs.is_file(p) + } + fn same_file(&self, a: &Path, b: &Path) -> bool { + RealFs.same_file(a, b) + } + fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + if !self.seen.get() { + let records = self.dir.records(); + assert_eq!(records.len(), 1, "the record is written before the first file moves"); + let text = std::fs::read_to_string(&records[0]).unwrap(); + assert!(text.contains(self.needle), "{text}"); + self.seen.set(true); + } + RealFs.rename_no_replace(a, b) + } + fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + RealFs.copy_no_replace(a, b) + } + fn remove_file(&self, p: &Path) -> std::io::Result<()> { + RealFs.remove_file(p) + } + fn stem_sibling(&self, sidecar: &Path) -> Option { + RealFs.stem_sibling(sidecar) + } +} + +#[test] +fn the_record_is_on_disk_before_the_first_file_moves_and_gone_once_saved() { + let dir = Scratch::new("record"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + let fs = Recorded { dir: &dir, needle: "share", seen: Cell::new(false) }; + let out = work.run_with(&fs); + assert!(fs.seen.get()); + s.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).unwrap(); + assert!(dir.records().is_empty(), "{:?}", dir.records()); +} + +#[test] +fn a_rename_and_its_undo_note_their_files_before_the_first_moves() { + let dir = Scratch::new("rename-record"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let plan = crate::rename::RenamePlan { + id: a.0, + from: "a.jpg".into(), + to: "b.jpg".into(), + from_path: Some(dir.path("local/a.jpg")), + to_path: Some(dir.path("local/b.jpg")), + }; + let fs = Recorded { dir: &dir, needle: "b.jpg", seen: Cell::new(false) }; + s.execute_fn("photo.rename", |s| Ok(json!({"renamed": s.apply_rename_with(&fs, &[plan])?}))).unwrap(); + assert!(fs.seen.get(), "the rename moved a file with no record"); + assert!(dir.records().is_empty(), "{:?}", dir.records()); + // the Undo moves the file back, noted the same way + let fs = Recorded { dir: &dir, needle: "a.jpg", seen: Cell::new(false) }; + s.execute_fn("edit.undo", |s| Ok(json!({"label": s.undo_step_with(&fs)?}))).unwrap(); + assert!(fs.seen.get(), "the Undo moved a file with no record"); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + assert!(dir.records().is_empty(), "{:?}", dir.records()); +} + +#[test] +fn a_move_cut_short_is_followed_when_the_library_opens_again() { + let dir = Scratch::new("crash"); + let (a, b, c, d, e, h); + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + std::fs::write(dir.path("local/a.xmp"), "").unwrap(); + b = add(&mut s, &dir.path("local/b.jpg"), "B"); + c = add(&mut s, &dir.path("local/c.jpg"), "C"); + d = add(&mut s, &dir.path("local/d.jpg"), "D"); + std::fs::create_dir_all(dir.path("usb")).unwrap(); + e = add(&mut s, &dir.path("usb/e.jpg"), "E"); + h = add(&mut s, &dir.path("local/h.jpg"), "H"); + let mut moves: Vec<(String, String)> = + ["a", "b", "c", "d"].iter().map(|f| (dir.path(&format!("local/{f}.jpg")), dir.path(&format!("share/{f}.jpg")))).collect(); + moves.push((dir.path("usb/e.jpg"), dir.path("share/e.jpg"))); + moves.push((dir.path("local/h.jpg"), dir.path("share/h.jpg"))); + crate::move_intent::write(&dir.library(), &moves).unwrap(); + // killed part-way: a's file arrived and its sidecar didn't; b's copy arrived and the + // original wasn't removed yet; c never started; d's disk isn't connected now; e's copy + // arrived (maybe never checked) and its drive is unplugged now + std::fs::rename(dir.path("local/a.jpg"), dir.path("share/a.jpg")).unwrap(); + std::fs::copy(dir.path("local/b.jpg"), dir.path("share/b.jpg")).unwrap(); + std::fs::write(dir.path("share/.b.jpg.lc-partial-1-0"), "cut off").unwrap(); + std::fs::remove_file(dir.path("local/d.jpg")).unwrap(); + std::fs::copy(dir.path("usb/e.jpg"), dir.path("share/e.jpg")).unwrap(); + std::fs::rename(dir.path("usb"), dir.path("usb-unplugged")).unwrap(); + // h: cut between linking the new name and unlinking the old (same volume) + std::fs::hard_link(dir.path("local/h.jpg"), dir.path("share/h.jpg")).unwrap(); + // (the app is gone: no finish, no save of a move) + } + let mut s = open(&dir); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the library follows the file that arrived"); + assert_eq!(std::fs::read_to_string(dir.path("share/a.xmp")).unwrap(), "", "and its sidecar follows it"); + assert!(!Path::new(&dir.path("local/a.xmp")).exists()); + assert_eq!(file_of(&s, b), dir.path("local/b.jpg"), "the original stays where the library has it"); + assert!(!Path::new(&dir.path("share/b.jpg")).exists(), "our copy of it is removed"); + assert!(!Path::new(&dir.path("share/.b.jpg.lc-partial-1-0")).exists(), "a partial copy is removed"); + assert_eq!(file_of(&s, c), dir.path("local/c.jpg")); + assert_eq!(file_of(&s, d), dir.path("local/d.jpg")); + assert_eq!(file_of(&s, e), dir.path("usb/e.jpg"), "a source whose folder is gone may only be unplugged: not followed"); + assert_eq!(file_of(&s, h), dir.path("local/h.jpg")); + assert!(Path::new(&dir.path("local/h.jpg")).is_file() && !Path::new(&dir.path("share/h.jpg")).exists(), "the second name goes, the file stays"); + assert!(s.take_library_warnings().is_empty(), "a move cut short isn't a settings problem"); + let info = s.execute("library.info", &json!({})).unwrap(); + assert_eq!(info["recoveredMoves"]["relinked"], 1, "{info}"); + let recovered = s.take_recovered_moves().unwrap(); + assert_eq!((recovered.relinked, recovered.waiting), (1, 2), "{recovered:?}"); + assert!(s.take_recovered_moves().is_none(), "handed out once"); + let notice = recovered.notice().unwrap(); + assert!(notice.contains("1 photo was being moved") && notice.contains("2 files that were being moved"), "{notice}"); + // d's and e's moves are kept for the next open; the rest of the record is done + let records = dir.records(); + assert_eq!(records.len(), 1); + let text = std::fs::read_to_string(&records[0]).unwrap(); + assert!(text.contains("d.jpg") && text.contains("e.jpg") && !text.contains("a.jpg"), "{text}"); + // the relink is one undo step that moves the file back + assert_eq!(s.undo.last().unwrap().label, "Finish Moving 1 Photo"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); + assert!(Path::new(&dir.path("local/a.jpg")).is_file()); + drop(s); + // and the relink was saved: it survives the next open, which has nothing more to do for a + let s = open(&dir); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg")); +} + +#[test] +fn edits_held_back_during_a_move_cut_short_reach_the_sidecar_at_the_next_open() { + let dir = Scratch::new("held-restart"); + let (a, b); + { + let mut s = open(&dir); + s.xmp.auto_write = true; + s.save_prefs().unwrap(); + a = add(&mut s, &dir.path("local/a.jpg"), "photo"); + // b moves too, untouched: its sidecar is another app's and must stay as it is + b = add(&mut s, &dir.path("local/b.jpg"), "other"); + std::fs::write(dir.path("local/b.xmp"), "").unwrap(); + s.selection = crate::Selection::single(a); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 1})).unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0, b.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 5})).unwrap(); + assert!(s.held_sidecars.contains(&a), "the write waits for the file to arrive"); + drop(work.run()); + // the app is gone after the file moved and before the move finished + drop(finish); + } + let mut s = open(&dir); + s.selection = crate::Selection::single(a); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg")); + assert_eq!(s.catalog.photo(a).unwrap().rating, 5); + let xmp = std::fs::read_to_string(dir.path("share/a.xmp")).unwrap(); + assert!(xmp.contains("xmp:Rating=\"5\"") || xmp.contains("5"), "{xmp}"); + // reading the sidecar back keeps the edit + s.execute("photo.readMetadataFromFile", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.catalog.photo(a).unwrap().rating, 5); + assert_eq!(file_of(&s, b), dir.path("share/b.jpg")); + assert_eq!(std::fs::read_to_string(dir.path("share/b.xmp")).unwrap(), "", "only held writes are made"); + assert!(!dir.library().join("moves/held-sidecars").exists(), "the list goes once its writes are made"); +} + +#[test] +fn a_held_write_whose_photo_is_out_of_reach_waits_for_the_open_that_reaches_it() { + let dir = Scratch::new("held-waiting"); + std::fs::create_dir_all(dir.path("usb")).unwrap(); + let a; + { + let mut s = open(&dir); + s.xmp.auto_write = true; + s.save_prefs().unwrap(); + a = add(&mut s, &dir.path("usb/a.jpg"), "photo"); + s.selection = crate::Selection::single(a); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 5})).unwrap(); + crate::move_intent::write(&dir.library(), &[(dir.path("usb/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + // the app is gone before the first file moved, and the disk is unplugged after + drop((work, finish)); + } + std::fs::rename(dir.path("usb"), dir.path("usb-unplugged")).unwrap(); + let held = dir.library().join("moves/held-sidecars"); + { + let s = open(&dir); + assert_eq!(file_of(&s, a), dir.path("usb/a.jpg"), "the move waits"); + assert!(held.is_file(), "the write it couldn't make stays listed"); + } + std::fs::rename(dir.path("usb-unplugged"), dir.path("usb")).unwrap(); + let s = open(&dir); + assert_eq!(file_of(&s, a), dir.path("usb/a.jpg"), "the file never left"); + let xmp = std::fs::read_to_string(dir.path("usb/a.xmp")).unwrap(); + assert!(xmp.contains("xmp:Rating=\"5\"") || xmp.contains("5"), "{xmp}"); + assert!(!held.exists(), "made at last, and the list goes"); +} + +#[test] +fn a_listed_write_made_later_in_the_session_leaves_the_list() { + let dir = Scratch::new("held-late"); + let mut s = open(&dir); + s.xmp.auto_write = true; + let a = add(&mut s, &dir.path("local/a.jpg"), "photo"); + // a held write that failed when its move ended (the share dropped out): listed, waiting + s.held_sidecars.insert(a); + s.save_held_sidecars(); + s.held_sidecars.clear(); + s.unsaved_sidecars.insert(a); + s.save_held_sidecars(); + let held = dir.library().join("moves/held-sidecars"); + assert!(held.is_file()); + // the next edit writes it: the next open mustn't write it again over what's there by then + s.selection = crate::Selection::single(a); + s.execute("photo.rate", &json!({"ids": [a.0], "rating": 3})).unwrap(); + assert_eq!(s.unsaved_sidecars(), 0); + assert!(!held.exists()); +} + +/// The disk, refusing to move sidecars (a lock another app holds on them). +struct SidecarsStuck; + +impl MoveFs for SidecarsStuck { + fn exists(&self, p: &Path) -> bool { + RealFs.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + RealFs.is_file(p) + } + fn same_file(&self, a: &Path, b: &Path) -> bool { + RealFs.same_file(a, b) + } + fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + if a.extension().is_some_and(|x| x == "xmp") { + return Err(std::io::Error::other("in use")); + } + RealFs.rename_no_replace(a, b) + } + fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + RealFs.copy_no_replace(a, b) + } + fn remove_file(&self, p: &Path) -> std::io::Result<()> { + RealFs.remove_file(p) + } + fn stem_sibling(&self, sidecar: &Path) -> Option { + RealFs.stem_sibling(sidecar) + } +} + +#[test] +fn a_sidecar_that_could_not_follow_its_file_is_taken_along_the_next_time() { + let dir = Scratch::new("sidecar-stuck"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + std::fs::write(dir.path("local/a.xmp"), "").unwrap(); + crate::move_intent::write(&dir.library(), &[(dir.path("local/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + // cut short after the file moved and before its sidecar did + std::fs::rename(dir.path("local/a.jpg"), dir.path("share/a.jpg")).unwrap(); + let r = s.recover_moves_with(&SidecarsStuck, true); + assert_eq!(r.relinked, 1); + assert!(matches!(r.problems.as_slice(), [crate::move_intent::MoveProblem::SidecarStayed { .. }]), "{r:?}"); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the photo follows its file"); + assert_eq!(dir.records().len(), 1, "the record keeps the move for its sidecar"); + // the next time, the sidecar follows; the photo isn't relinked again + let r = s.recover_moves_with(&RealFs, true); + assert_eq!((r.relinked, r.problems.len()), (0, 0), "{r:?}"); + assert_eq!(std::fs::read_to_string(dir.path("share/a.xmp")).unwrap(), ""); + assert!(!Path::new(&dir.path("local/a.xmp")).exists()); + assert!(dir.records().is_empty()); +} + +#[test] +fn a_library_open_without_its_lock_leaves_every_record_and_file_as_it_is() { + let dir = Scratch::new("unlocked"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let b = add(&mut s, &dir.path("local/b.jpg"), "B"); + let record = [(dir.path("local/a.jpg"), dir.path("share/a.jpg")), (dir.path("local/b.jpg"), dir.path("share/b.jpg"))]; + crate::move_intent::write(&dir.library(), &record).unwrap(); + // another program may be in the middle of this move: a's file has arrived, b's copy is being made + std::fs::rename(dir.path("local/a.jpg"), dir.path("share/a.jpg")).unwrap(); + std::fs::copy(dir.path("local/b.jpg"), dir.path("share/b.jpg")).unwrap(); + std::fs::write(dir.path("share/.b.jpg.lc-partial-1-0"), "being written").unwrap(); + std::fs::write(dir.library().join("moves/x.tmp"), "being written").unwrap(); + let before = std::fs::read(&dir.records()[0]).unwrap(); + let r = s.recover_moves_with(&RealFs, false); + assert!(matches!(r.problems.as_slice(), [crate::move_intent::MoveProblem::Unprotected]), "{r:?}"); + assert_eq!((r.relinked, r.copies_removed), (0, 0), "{r:?}"); + assert!(Path::new(&dir.path("share/b.jpg")).is_file() && Path::new(&dir.path("local/b.jpg")).is_file()); + assert!(Path::new(&dir.path("share/.b.jpg.lc-partial-1-0")).exists(), "a partial file may be being written"); + assert!(dir.library().join("moves/x.tmp").exists(), "a record being written may be another program's"); + assert_eq!((file_of(&s, a), file_of(&s, b)), (dir.path("local/a.jpg"), dir.path("local/b.jpg")), "nothing is followed"); + assert_eq!(std::fs::read(&dir.records()[0]).unwrap(), before, "the record is as it was"); + // with the lock, the same state is followed and settled + let r = s.recover_moves_with(&RealFs, true); + assert_eq!((r.relinked, r.copies_removed), (1, 1), "{r:?}"); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg")); + assert!(!Path::new(&dir.path("share/b.jpg")).exists()); + assert!(dir.records().is_empty()); +} + +#[test] +fn a_library_that_cannot_be_locked_leaves_the_move_for_an_open_that_can() { + let dir = Scratch::new("unlockable"); + let a; + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + crate::move_intent::write(&dir.library(), &[(dir.path("local/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + s.held_sidecars.insert(a); + s.save_held_sidecars(); + // the app is killed after the file arrived + std::fs::rename(dir.path("local/a.jpg"), dir.path("share/a.jpg")).unwrap(); + } + // a library whose lock file can't be locked (a directory stands in for a file system without locks) + let lock = dir.library().join("catalog.lock"); + let _ = std::fs::remove_file(&lock); + std::fs::create_dir_all(&lock).unwrap(); + { + let mut s = open(&dir); + let r = s.take_recovered_moves().expect("the open says it left the move alone"); + assert!(matches!(r.problems.as_slice(), [crate::move_intent::MoveProblem::Unprotected]), "{r:?}"); + assert_eq!(file_of(&s, a), dir.path("local/a.jpg"), "nothing is followed without the lock"); + s.save_held_sidecars(); + assert!(dir.library().join("moves/held-sidecars").is_file(), "the edits the earlier run held back wait for an open with the lock"); + assert_eq!(dir.records().len(), 1); + } + std::fs::remove_dir_all(&lock).unwrap(); + let s = open(&dir); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the next open with the lock follows it"); + assert!(dir.records().is_empty()); +} + +/// Make the library unlockable (a directory stands in for a lock file) before it is opened. +fn make_unlockable(dir: &Scratch) { + let lock = dir.library().join("catalog.lock"); + let _ = std::fs::remove_file(&lock); + std::fs::create_dir_all(&lock).unwrap(); +} + +#[test] +fn without_the_lock_only_the_writes_this_session_listed_leave_the_held_list() { + let dir = Scratch::new("unlocked-held"); + let (a, b); + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + b = add(&mut s, &dir.path("local/b.jpg"), "B"); + } + make_unlockable(&dir); + let held = dir.library().join("moves/held-sidecars"); + // an earlier run (or another program) left b's write on the list + std::fs::create_dir_all(dir.library().join("moves")).unwrap(); + std::fs::write(&held, serde_json::to_vec(&[b]).unwrap()).unwrap(); + let mut s = open(&dir); + s.held_sidecars.insert(a); + s.save_held_sidecars(); + let listed = |p: &Path| -> Vec { serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap() }; + assert_eq!(listed(&held), vec![a, b]); + // the move ends and a's write is made: it leaves the list, b's entry isn't this session's to take back + s.held_sidecars.clear(); + s.save_held_sidecars(); + assert_eq!(listed(&held), vec![b], "the entry another run left stays for an open with the lock"); +} + +#[test] +fn without_the_lock_a_worker_that_dies_still_has_its_own_move_followed() { + let dir = Scratch::new("unlocked-abandon"); + let a; + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + add(&mut s, &dir.path("local/b.jpg"), "B"); + } + make_unlockable(&dir); + // another program's record, which stays untouched + let other = crate::move_intent::write(&dir.library(), &[(dir.path("local/b.jpg"), dir.path("share/b.jpg"))]).unwrap(); + let mut s = open(&dir); + let taken = s.take_recovered_moves().expect("the open leaves the other record alone"); + assert!(matches!(taken.problems.as_slice(), [crate::move_intent::MoveProblem::Unprotected]), "{taken:?}"); + let before = std::fs::read(other.path()).unwrap(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + // the files moved, then the worker died before saying so + drop(work.run()); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["relinked"], 1, "{r}"); + // (the other program's record was reported when the library opened; every file this process moved was followed) + assert_eq!(r["problems"], json!([]), "no `unprotected` when only this worker's own record was followed: {r}"); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the library follows the file this process moved"); + assert_eq!(dir.records().len(), 1, "only the other program's record is left"); + assert_eq!(std::fs::read(other.path()).unwrap(), before); +} + +#[test] +fn a_list_that_could_not_be_written_is_not_counted_as_listed() { + let dir = Scratch::new("unlocked-held-fail"); + let a; + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + } + make_unlockable(&dir); + let mut s = open(&dir); + // the list can't be written (a folder stands in its place) + std::fs::create_dir_all(dir.library().join("moves/held-sidecars")).unwrap(); + s.held_sidecars.insert(a); + s.save_held_sidecars(); + assert!(!s.held_listed.contains(&a), "the disk doesn't name it, so a later save mustn't treat a stray entry as this session's"); +} + +#[test] +fn without_the_lock_a_dead_workers_cleanup_leaves_the_copies_and_partials_another_program_may_own() { + let dir = Scratch::new("unlocked-abandon-both"); + let a; + { + let mut s = open(&dir); + a = add(&mut s, &dir.path("local/a.jpg"), "A"); + } + make_unlockable(&dir); + let mut s = open(&dir); + let _ = s.take_recovered_moves(); + let (work, finish) = crate::move_job::start(&mut s, &json!({"ids": [a.0], "folder": dir.path("share")})).unwrap().unwrap(); + drop(work.run()); + // another program is moving the same photo to the same folder: its copy is at both places, its partial is being written + std::fs::copy(dir.path("share/a.jpg"), dir.path("local/a.jpg")).unwrap(); + std::fs::write(dir.path("share/.a.jpg.lc-partial-1-0"), "being written").unwrap(); + let r = s.execute_fn("photo.moveToFolder", |s| Ok(json!(finish.abandon(s)))).unwrap(); + assert_eq!(r["copiesRemoved"], 0, "{r}"); + assert!(Path::new(&dir.path("share/a.jpg")).is_file() && Path::new(&dir.path("local/a.jpg")).is_file(), "{r}"); + assert!(Path::new(&dir.path("share/.a.jpg.lc-partial-1-0")).exists(), "another process's partial copy stays"); +} + +#[test] +fn the_records_of_one_session_are_followed_when_the_library_is_opened_again() { + let dir = Scratch::new("reopen"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let record = crate::move_intent::write(&dir.library(), &[(dir.path("local/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + std::fs::rename(dir.path("local/a.jpg"), dir.path("share/a.jpg")).unwrap(); + // the move ended, but the library didn't follow (or its change isn't saved): the record waits for the save + s.settle_moves(Some(record)); + s.open_library(dir.library(), false).unwrap(); + assert_eq!(file_of(&s, a), dir.path("share/a.jpg"), "the open follows a record the session had not seen saved"); + assert!(dir.records().is_empty()); +} + +#[test] +fn a_settled_record_stays_while_the_library_has_changes_not_yet_saved() { + let dir = Scratch::new("settled-unsaved"); + let mut s = open(&dir); + add(&mut s, &dir.path("local/a.jpg"), "A"); + let record = crate::move_intent::write(&dir.library(), &[(dir.path("local/a.jpg"), dir.path("share/a.jpg"))]).unwrap(); + s.settle_moves(Some(record)); + // a save that is failing leaves changes queued: the record must outlive them + s.pending_log.push(Op::Batch { ops: Vec::new() }); + s.clear_settled_moves(); + assert_eq!(dir.records().len(), 1, "the record goes only once the library has saved what follows the move"); + s.pending_log.clear(); + s.clear_settled_moves(); + assert!(dir.records().is_empty(), "{:?}", dir.records()); +} + +#[test] +fn the_library_says_whether_it_followed_the_files_that_could_not_go_back() { + let dir = Scratch::new("unfollowed"); + let mut s = open(&dir); + let a = add(&mut s, &dir.path("local/a.jpg"), "A"); + let (from, to) = (dir.path("local/a.jpg"), dir.path("share/a.jpg")); + let stuck = || crate::rename::BatchMoveError { message: "stopped".into(), stuck: vec![(from.clone(), to.clone())], pending_sidecars: Vec::new() }; + let set_file = |id| Op::SetFile { id, file_name: "a.jpg".into(), source: Source::File { path: to.clone() } }; + // the photo is gone: the library can't point at the file, which stays at the new place (the record stays) + let (message, _, followed) = s.follow_stuck(&set_file(PhotoId(9999)), stuck(), false); + assert!(!followed, "{message}"); + assert!(message.contains("the library could not follow"), "{message}"); + let (_, _, followed) = s.follow_stuck(&set_file(a), stuck(), false); + assert!(followed); + assert_eq!(file_of(&s, a), to); +} + +#[test] +fn removed_copies_are_told() { + let r = crate::move_intent::Recovered { copies_removed: 2, ..Default::default() }; + assert!(!r.is_empty()); + assert!(r.notice().unwrap().contains("2 copies of files that were being moved were removed"), "{:?}", r.notice()); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..23dc76e0293 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -104,7 +104,6 @@ "Matches: {}": "Shody: {}", "Merging… {stage} {:.0}%": "Slučování… {stage} {:.0}%", "Move {what} to Recently Deleted?": "Přesunout {what} do nedávno odstraněných?", - "Moved {} photo(s)": "Přesunuto fotografií: {}", "Moved; {} photo(s) relinked": "Přesunuto; znovu propojeno fotografií: {}", "Named ({named_n})": "Pojmenované ({named_n})", "New Folder in “{name}”": "Nová složka v „{name}“", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Fotografie, které se přesouvaly, když se LightCraft naposledy zavřel: {}. Knihovna teď ukazuje tam, kde soubory jsou; Úpravy → Zpět je vrátí.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Přesouvané soubory, které teď nejsou dostupné (nepřipojený disk?): {}. LightCraft se podívá znovu při příštím otevření této knihovny.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Záznam o přesunu ({}) nelze přečíst ({}); zůstal, jak byl.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} se přesouval a je teď na obou místech: knihovna ponechává {1}.", + "A sidecar of {} couldn't follow it ({}).": "Přidružený soubor XMP k {} se s ním nepřesunul ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Knihovna nemohla následovat soubory, které se přesouvaly ({}); Najít chybějící fotografie je znovu propojí.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Knihovna následuje soubory, které se přesouvaly, ale nepodařilo se to uložit ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Kopie odstraněné z nového místa, protože originál byl stále tam, kde ho knihovna má: {}." } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524d..887e29920bc 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2408,5 +2408,10 @@ "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", + "Moving photos": "Přesouvání fotografií", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Přesun zastavila chyba (viz protokol). Knihovna následuje soubory, které už byly přesunuty.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Přesun zastavila chyba (viz protokol). Knihovna nemusí následovat všechny soubory, které už byly přesunuty: ztracené znovu propojí Najít chybějící fotografie.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Tato knihovna je otevřená bez zámku, proto se přerušené přesuny nechají beze změny, dokud se knihovna neotevře se zámkem; přesunuté soubory znovu propojí Najít chybějící fotografie.", + "Unfinished moves": "Nedokončené přesuny" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..6a8506650cf 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -248,7 +248,6 @@ "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Übersprungen: {n} lokale Fotos{0:.0} – Alben enthalten Bibliotheksfotos (zuerst zu „Meine Fotos“ hinzufügen)", "New Folder in “{name}”": "Neuer Ordner in „{name}“", - "Moved {} photo(s)": "{} Foto(s) verschoben", "not added to Apple Photos: {e}": "nicht zu Apple Fotos hinzugefügt: {e}", "{n} added to Apple Photos album “{album}”": "{n} zum Apple-Fotos-Album „{album}“ hinzugefügt", "{n} added to Apple Photos": "{n} zu Apple Fotos hinzugefügt", @@ -305,5 +304,13 @@ "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{})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Fotos, die beim letzten Beenden von LightCraft verschoben wurden: {}. Die Bibliothek zeigt jetzt dorthin, wo die Dateien sind; Bearbeiten → Rückgängig holt sie zurück.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Verschobene Dateien, die gerade nicht erreichbar sind (ein nicht verbundenes Laufwerk?): {}. LightCraft sieht beim nächsten Öffnen dieser Bibliothek wieder nach.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Ein Verschiebeeintrag ({}) kann nicht gelesen werden ({}); er bleibt unverändert.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} wurde verschoben und liegt jetzt an beiden Orten: Die Bibliothek behält {1}.", + "A sidecar of {} couldn't follow it ({}).": "Eine Begleitdatei von {} konnte nicht mitgenommen werden ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Die Bibliothek konnte den verschobenen Dateien nicht folgen ({}); Fehlende Fotos suchen verknüpft sie neu.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Die Bibliothek folgt den verschobenen Dateien, aber das konnte nicht gespeichert werden ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Kopien am neuen Ort entfernt, weil das Original noch dort lag, wo die Bibliothek es führt: {}." } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782f..1a181b20051 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2343,6 +2343,9 @@ "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", + "Moving photos": "Fotos werden verschoben", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Das Verschieben wurde durch einen Fehler angehalten (siehe Protokoll). Die Bibliothek folgt den Dateien, die schon verschoben waren.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Das Verschieben wurde durch einen Fehler angehalten (siehe Protokoll). Die Bibliothek folgt möglicherweise nicht allen Dateien, die schon verschoben waren: Fehlende Fotos suchen verknüpft die verlorenen wieder.", "Set Folder Color Label": "Ordner-Farbmarkierung festlegen", "Photo Below": "Foto darunter", "Photo Above": "Foto darüber", @@ -3440,5 +3443,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", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Diese Bibliothek ist ohne ihre Sperre geöffnet; abgebrochene Verschiebungen bleiben daher unverändert, bis sie mit der Sperre geöffnet wird. Fehlende Fotos suchen verknüpft verschobene Dateien neu.", + "Unfinished moves": "Unvollständige Verschiebungen" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..f44c82f043f 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -248,7 +248,6 @@ "{what} merge cancelled": "Combinación {what} cancelada", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Fotos locales omitidas: {n}{0:.0} — los álbumes contienen fotos de la biblioteca (añádelas primero a Mis fotos)", "New Folder in “{name}”": "Nueva carpeta en «{name}»", - "Moved {} photo(s)": "{} foto(s) movida(s)", "not added to Apple Photos: {e}": "no se añadieron a Fotos de Apple: {e}", "{n} added to Apple Photos album “{album}”": "{n} añadidas al álbum “{album}” de Fotos de Apple", "{n} added to Apple Photos": "{n} añadidas a Fotos de Apple", @@ -305,5 +304,13 @@ "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{})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Fotos que se estaban moviendo cuando LightCraft se cerró por última vez: {}. La biblioteca ahora apunta a donde están los archivos; Editar → Deshacer las devuelve.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Archivos en traslado a los que no se puede acceder ahora (¿un disco desconectado?): {}. LightCraft volverá a buscarlos la próxima vez que se abra esta biblioteca.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "No se puede leer un registro de traslado ({}) ({}); se ha dejado como estaba.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} se estaba moviendo y ahora está en ambos lugares: la biblioteca conserva {1}.", + "A sidecar of {} couldn't follow it ({}).": "Un archivo complementario de {} no pudo seguirlo ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "La biblioteca no pudo seguir a los archivos que se estaban moviendo ({}); Buscar fotos que faltan los vuelve a vincular.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "La biblioteca sigue a los archivos que se estaban moviendo, pero no se pudo guardar ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Copias eliminadas del lugar nuevo porque el original seguía donde la biblioteca lo tiene: {}." } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff2..81ca8f6b8a5 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2358,5 +2358,10 @@ "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", + "Moving photos": "Moviendo fotos", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Un error detuvo el movimiento (consulta el registro). La biblioteca sigue los archivos que ya se habían movido.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Un error detuvo el movimiento (consulta el registro). Puede que la biblioteca no siga todos los archivos que ya se habían movido: Buscar fotos que faltan vuelve a enlazar los que perdió.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Esta biblioteca está abierta sin su bloqueo, así que los movimientos interrumpidos se dejan tal cual hasta que se abra con el bloqueo; Buscar fotos que faltan vuelve a enlazar los archivos que se movieron.", + "Unfinished moves": "Movimientos sin terminar" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9f..1f47243585e 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -130,7 +130,6 @@ "Move {n} photo{} to “{}”?": "Siirretäänkö kuvat kohteeseen ”{1}” ({n}){0:.0}?", "Move {what} to Recently Deleted?": "Siirretäänkö {what} Äskettäin poistettuihin?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Siirretty kuvia kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.", - "Moved {} photo(s)": "Siirretty kuvia: {}", "Moved; {} photo(s) relinked": "Siirretty; yhdistetty uudelleen kuvia: {}", "Named ({named_n})": "Nimetyt ({named_n})", "New Folder in “{name}”": "Uusi kansio kohteessa ”{name}”", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Kuvia siirrettiin, kun LightCraft suljettiin viimeksi: {}. Kirjasto osoittaa nyt sinne, missä tiedostot ovat; Muokkaa → Kumoa siirtää ne takaisin.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Siirrettäviä tiedostoja, joihin ei nyt saada yhteyttä (levy ei ole kytketty?): {}. LightCraft yrittää uudelleen, kun tämä kirjasto avataan seuraavan kerran.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Siirron tietuetta ({}) ei voi lukea ({}); se jätettiin ennalleen.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} oli siirrettävänä ja on nyt molemmissa paikoissa: kirjasto pitää kohteen {1}.", + "A sidecar of {} couldn't follow it ({}).": "Tiedoston {} sivutiedosto ei voinut seurata sitä ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Kirjasto ei voinut seurata siirrettäviä tiedostoja ({}); Etsi puuttuvat kuvat yhdistää ne uudelleen.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Kirjasto seuraa siirrettäviä tiedostoja, mutta sitä ei voitu tallentaa ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Uudesta paikasta poistetut kopiot, koska alkuperäinen oli yhä siellä, missä kirjasto sen tuntee: {}." } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a36..504c43a303e 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1191,6 +1191,9 @@ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "Siirtää kaikki tältä levyltä tuodut kuvat Äskettäin poistettuihin; tiedostoihin ei kosketa", "Moves the files and their XMP sidecars into this folder; never overwrites": "Siirtää tiedostot ja niiden XMP-sivutiedostot tähän kansioon; ei koskaan korvaa mitään", "Moves the photos imported from this folder to Recently Deleted; no file is touched": "Siirtää tästä kansiosta tuodut kuvat Äskettäin poistettuihin; tiedostoihin ei kosketa", + "Moving photos": "Kuvia siirretään", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Virhe pysäytti siirron (katso loki). Kirjasto seuraa jo siirrettyjä tiedostoja.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Virhe pysäytti siirron (katso loki). Kirjasto ei välttämättä seuraa kaikkia jo siirrettyjä tiedostoja: Etsi puuttuvat kuvat yhdistää menetetyt uudelleen.", "Multi": "Useita", "Muted": "Hillitty", "Muted Film": "Hillitty filmi", @@ -2327,5 +2330,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", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Tämä kirjasto on avattu ilman lukitusta, joten keskeytyneet siirrot jätetään ennalleen, kunnes kirjasto avataan lukituksen kanssa; Etsi puuttuvat kuvat yhdistää siirretyt tiedostot uudelleen.", + "Unfinished moves": "Keskeneräiset siirrot" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..0d4aa3c687c 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -248,7 +248,6 @@ "{what} merge cancelled": "Fusion {what} annulée", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Photos locales ignorées : {n}{0:.0} — les albums contiennent des photos de la bibliothèque (ajoutez-les d’abord à Mes photos)", "New Folder in “{name}”": "Nouveau dossier dans « {name} »", - "Moved {} photo(s)": "{} photo(s) déplacée(s)", "not added to Apple Photos: {e}": "non ajouté à Apple Photos : {e}", "{n} added to Apple Photos album “{album}”": "{n} ajouté(s) à l'album Apple Photos « {album} »", "{n} added to Apple Photos": "{n} ajouté(s) à Apple Photos", @@ -305,5 +304,13 @@ "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{})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Photos en cours de déplacement à la dernière fermeture de LightCraft : {}. La bibliothèque pointe maintenant là où sont les fichiers ; Modifier → Annuler les remet en place.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Fichiers en cours de déplacement inaccessibles pour l'instant (un disque non connecté ?) : {}. LightCraft vérifiera à la prochaine ouverture de cette bibliothèque.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Un relevé de déplacement ({}) est illisible ({}) ; il a été laissé tel quel.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} était en cours de déplacement et se trouve maintenant aux deux endroits : la bibliothèque garde {1}.", + "A sidecar of {} couldn't follow it ({}).": "Un fichier annexe de {} n'a pas pu le suivre ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "La bibliothèque n'a pas pu suivre les fichiers en cours de déplacement ({}) ; Rechercher les photos manquantes les relie à nouveau.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "La bibliothèque suit les fichiers qui étaient en cours de déplacement, mais cela n'a pas pu être enregistré ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Copies supprimées du nouvel emplacement, car l’original se trouvait toujours là où la bibliothèque le place : {}." } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda6..ef1c6af8844 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2390,5 +2390,10 @@ "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 :", + "Moving photos": "Déplacement des photos", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Une erreur a arrêté le déplacement (voir le journal). La bibliothèque suit les fichiers déjà déplacés.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Une erreur a arrêté le déplacement (voir le journal). La bibliothèque peut ne pas suivre tous les fichiers déjà déplacés : Rechercher les photos manquantes rétablit le lien de ceux qu’elle a perdus.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Cette bibliothèque est ouverte sans son verrou : les déplacements interrompus sont laissés tels quels jusqu’à une ouverture avec le verrou ; Rechercher les photos manquantes relie à nouveau les fichiers déplacés.", + "Unfinished moves": "Déplacements inachevés" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221e..0c979db36f8 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -251,7 +251,6 @@ "{what} merge cancelled": "Penggabungan {what} dibatalkan", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "{n} foto Lokal{:.0} dilewati: album hanya dapat berisi foto pustaka (tambahkan ke Foto saya terlebih dahulu)", "New Folder in “{name}”": "Folder baru di “{name}”", - "Moved {} photo(s)": "{} foto dipindahkan", "not added to Apple Photos: {e}": "tidak ditambahkan ke Apple Photos: {e}", "{n} added to Apple Photos album “{album}”": "{n} ditambahkan ke album Apple Photos “{album}”", "{n} added to Apple Photos": "{n} ditambahkan ke Apple Photos", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Foto yang sedang dipindahkan saat LightCraft terakhir ditutup: {}. Pustaka sekarang menunjuk ke lokasi file; Edit → Urungkan memindahkannya kembali.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "File yang sedang dipindahkan dan tidak dapat dijangkau sekarang (disk tidak terhubung?): {}. LightCraft akan memeriksa lagi saat pustaka ini dibuka berikutnya.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Catatan pemindahan ({}) tidak dapat dibaca ({}); catatan dibiarkan apa adanya.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} sedang dipindahkan dan kini berada di kedua tempat: pustaka mempertahankan {1}.", + "A sidecar of {} couldn't follow it ({}).": "File sidecar milik {} tidak dapat mengikutinya ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Pustaka tidak dapat mengikuti file yang sedang dipindahkan ({}); Cari foto hilang menautkannya kembali.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Pustaka mengikuti file yang sedang dipindahkan, tetapi itu tidak dapat disimpan ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Salinan yang dihapus dari lokasi baru, karena file aslinya masih berada di tempat pustaka mencatatnya: {}." } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb8..140643d1a53 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1191,6 +1191,9 @@ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "Memindahkan semua foto yang diimpor dari disk ini ke Baru dihapus; tidak ada file yang diubah", "Moves the files and their XMP sidecars into this folder; never overwrites": "Memindahkan file beserta file sidecar XMP-nya ke folder ini; file yang sudah ada tidak akan ditimpa", "Moves the photos imported from this folder to Recently Deleted; no file is touched": "Memindahkan foto yang diimpor dari folder ini ke Baru dihapus; file di disk tidak diubah", + "Moving photos": "Memindahkan foto", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Pemindahan dihentikan oleh kesalahan (lihat log). Pustaka mengikuti file yang sudah dipindahkan.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Pemindahan dihentikan oleh kesalahan (lihat log). Pustaka mungkin tidak mengikuti semua file yang sudah dipindahkan: Cari foto hilang menautkan kembali file yang terlepas.", "Multi": "Multi", "Muted": "Redup", "Muted Film": "Film Kalem", @@ -2339,5 +2342,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", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Pustaka ini terbuka tanpa kuncinya, sehingga pemindahan yang terputus dibiarkan apa adanya sampai pustaka dibuka dengan kunci; Cari foto hilang menautkan kembali file yang sudah dipindahkan.", + "Unfinished moves": "Pemindahan yang belum selesai" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..67a64a38638 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -240,7 +240,6 @@ "{what} merge cancelled": "Unione {what} annullata", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Foto locali saltate: {n}{0:.0}; gli album contengono foto della libreria (prima aggiungile a Le mie foto)", "New Folder in “{name}”": "Nuova cartella in “{name}”", - "Moved {} photo(s)": "Foto spostate: {}", "not added to Apple Photos: {e}": "non aggiunte a Foto di Apple: {e}", "{n} added to Apple Photos album “{album}”": "Aggiunte all'album “{album}” di Foto di Apple: {n}", "{n} added to Apple Photos": "Aggiunte a Foto di Apple: {n}", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Foto in spostamento all'ultima chiusura di LightCraft: {}. La libreria ora punta a dove si trovano i file; Modifica → Annulla le riporta indietro.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "File in spostamento non raggiungibili ora (un disco non collegato?): {}. LightCraft controllerà di nuovo alla prossima apertura di questa libreria.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Impossibile leggere un registro di spostamento ({}) ({}); è stato lasciato com'era.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} era in spostamento e ora si trova in entrambi i posti: la libreria tiene {1}.", + "A sidecar of {} couldn't follow it ({}).": "Un file collaterale di {} non è riuscito a seguirlo ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "La libreria non è riuscita a seguire i file in spostamento ({}); Trova foto mancanti li ricollega.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "La libreria segue i file che erano in spostamento, ma non è stato possibile salvarlo ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Copie rimosse dalla nuova posizione, perché l’originale era ancora dove la libreria lo registra: {}." } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d15..3685a50604e 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2332,6 +2332,9 @@ "Image on Black": "Immagine su nero", "Image on White": "Immagine su bianco", "White on Black": "Bianco su nero", + "Moving photos": "Spostamento delle foto", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Un errore ha interrotto lo spostamento (vedi il registro). La libreria segue i file già spostati.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Un errore ha interrotto lo spostamento (vedi il registro). La libreria potrebbe non seguire tutti i file già spostati: Trova foto mancanti ricollega quelli persi.", "View Options…": "Opzioni di visualizzazione…", "View Options": "Opzioni di visualizzazione", "Loupe View": "Vista lente", @@ -2361,5 +2364,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", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Questa libreria è aperta senza il suo blocco, quindi gli spostamenti interrotti restano come sono finché non viene aperta con il blocco; Trova foto mancanti ricollega i file spostati.", + "Unfinished moves": "Spostamenti incompleti" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..4b9bb0ac7b5 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -252,7 +252,6 @@ "{what} merge cancelled": "{what}合成をキャンセルしました", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "ローカル写真{n}枚をスキップしました{0:.0}:アルバムに入れられるのはライブラリの写真です(先にマイフォトに追加してください)", "New Folder in “{name}”": "「{name}」に新規フォルダ", - "Moved {} photo(s)": "{} 枚の写真を移動しました", "not added to Apple Photos: {e}": "Appleの写真に追加されませんでした:{e}", "{n} added to Apple Photos album “{album}”": "{n}件をAppleの写真のアルバム「{album}」に追加しました", "{n} added to Apple Photos": "{n}件をAppleの写真に追加しました", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "前回 LightCraft を閉じたときに移動中だった写真: {}。ライブラリはファイルの現在の場所を指すようになりました。編集 → 取り消す で元に戻せます。", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "移動中のファイルのうち、今はアクセスできないもの (ディスクが接続されていない?): {}。次にこのライブラリを開いたときにもう一度確認します。", + "A record of a move ({}) can't be read ({}); it was left as it is.": "移動の記録 ({}) を読み込めません ({})。そのまま残しました。", + "{} was being moved and is now at both places: the library keeps {}.": "{0} は移動中で、現在両方の場所にあります。ライブラリは {1} を使います。", + "A sidecar of {} couldn't follow it ({}).": "{} のサイドカーを一緒に移動できませんでした ({})。", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "移動中だったファイルにライブラリを合わせられませんでした ({})。見つからない写真を探す で再リンクできます。", + "The files that were being moved are followed, but that couldn't be saved ({}).": "移動中だったファイルにライブラリを合わせましたが、保存できませんでした ({})。", + "Copies removed from the new place, because the original was still where the library has it: {}.": "元のファイルがライブラリの記録どおりの場所に残っていたため、新しい場所から削除したコピー:{}。" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd7..61432f8f197 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2356,5 +2356,10 @@ "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 カタログの読み込みを完了してください", + "Moving photos": "写真を移動中", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "エラーのため移動が停止しました(ログを参照)。ライブラリは移動済みのファイルに追従します。", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "エラーのため移動が停止しました(ログを参照)。ライブラリが移動済みのすべてのファイルに追従していない場合があります。見つからなくなったものは「見つからない写真を探す」で再リンクできます。", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "このライブラリはロックなしで開かれているため、中断された移動は、ロック付きで開かれるまでそのままにされます。移動済みのファイルは「見つからない写真を探す」で再リンクできます。", + "Unfinished moves": "未完了の移動" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..c79b4dcd9dd 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -104,7 +104,6 @@ "Matches: {}": "დამთხვევა: {}", "Merging… {stage} {:.0}%": "გაერთიანება… {stage} {:.0}%", "Move {what} to Recently Deleted?": "გადავიდეს {what} ახლახან წაშლილებში?", - "Moved {} photo(s)": "გადატანილია ფოტო: {}", "Moved; {} photo(s) relinked": "გადატანილია; ხელახლა დაკავშირდა ფოტო: {}", "Named ({named_n})": "სახელიანი ({named_n})", "New Folder in “{name}”": "ახალი საქაღალდე „{name}“-ში", @@ -298,12 +297,20 @@ "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}", "Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}", "Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}", "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}", + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადატანილია ფოტო: {n}{0:.0}. რედაქტირება → გაუქმება დააბრუნებს მათ.", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "ფოტოები, რომლებიც LightCraft-ის ბოლო დახურვისას გადაიტანებოდა: {}. ბიბლიოთეკა ახლა მიუთითებს იქ, სადაც ფაილებია; რედაქტირება → გაუქმება დააბრუნებს მათ.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "გადასატანი ფაილები, რომლებიც ახლა მიუწვდომელია (დისკი არ არის მიერთებული?): {}. LightCraft კვლავ შეამოწმებს ამ ბიბლიოთეკის შემდეგ გახსნისას.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "გადატანის ჩანაწერი ({}) ვერ იკითხება ({}); ის უცვლელად დარჩა.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} გადაიტანებოდა და ახლა ორივე ადგილზეა: ბიბლიოთეკა ინახავს {1}-ს.", + "A sidecar of {} couldn't follow it ({}).": "{}-ის თანმხლები ფაილი ვერ გაჰყვა მას ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "ბიბლიოთეკამ ვერ გაჰყვა გადასატან ფაილებს ({}); დაკარგული ფოტოების მოძებნა ხელახლა დააკავშირებს მათ.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "ბიბლიოთეკა მიჰყვება გადატანილ ფაილებს, მაგრამ ამის შენახვა ვერ მოხერხდა ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "ახალი ადგილიდან წაშლილი ასლები, რადგან ორიგინალი კვლავ იქ იყო, სადაც ბიბლიოთეკას უწერია: {}." } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c40770018..437f490f7a3 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2734,5 +2734,10 @@ "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-ის კატალოგის იმპორტი", + "Moving photos": "ფოტოების გადატანა", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "გადატანა შეცდომის გამო შეჩერდა (იხილეთ ჟურნალი). ბიბლიოთეკა მიჰყვება უკვე გადატანილ ფაილებს.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "გადატანა შეცდომის გამო შეჩერდა (იხილეთ ჟურნალი). ბიბლიოთეკამ შეიძლება ყველა უკვე გადატანილ ფაილს ვერ მიჰყვეს: დაკარგულებს „დაკარგული ფოტოების მოძებნა“ თავიდან დააკავშირებს.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "ეს ბიბლიოთეკა ჩაკეტვის გარეშეა გახსნილი, ამიტომ შეწყვეტილი გადატანები უცვლელად რჩება, სანამ ბიბლიოთეკა ჩაკეტვით არ გაიხსნება; გადატანილ ფაილებს „დაკარგული ფოტოების მოძებნა“ თავიდან დააკავშირებს.", + "Unfinished moves": "დაუსრულებელი გადატანები" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..53fd489a5ed 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -234,7 +234,6 @@ "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Geometria z Lightrooma dla {path} nie została zachowana; zapisane przekształcenie Upright nie jest obsługiwane.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Geometria z Lightrooma dla {path} nie została zachowana; zapisane przekształcenie jest pomijane, ponieważ Upright jest wyłączony.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Geometria z Lightrooma dla {path} nie została zachowana; tryb {mode} zostanie obliczony ponownie.", - "Moved {} photo(s)": "Przeniesione zdjęcia: {}", "New Folder in “{name}”": "Nowy folder w „{name}”", "Restored {} photo{} from Recently Deleted": "Przywrócone z Ostatnio usuniętych zdjęcia: {}{:.0}", "XMP adjustments were not imported for {path}: {fields}.": "Korekty XMP dla {path} nie zostały zaimportowane: {fields}.", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Zdjęcia przenoszone podczas ostatniego zamknięcia LightCraft: {}. Biblioteka wskazuje teraz miejsce, w którym są pliki; Edytuj → Cofnij przywróci je.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Przenoszone pliki, które są teraz niedostępne (niepodłączony dysk?): {}. LightCraft sprawdzi ponownie przy następnym otwarciu tej biblioteki.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Nie można odczytać zapisu przeniesienia ({}) ({}); pozostawiono go bez zmian.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} był przenoszony i jest teraz w obu miejscach: biblioteka zachowuje {1}.", + "A sidecar of {} couldn't follow it ({}).": "Plik pomocniczy {} nie mógł zostać przeniesiony razem z nim ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Biblioteka nie mogła podążyć za przenoszonymi plikami ({}); Znajdź brakujące zdjęcia połączy je ponownie.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Biblioteka podąża za przenoszonymi plikami, ale nie udało się tego zapisać ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Kopie usunięte z nowego miejsca, ponieważ oryginał nadal był tam, gdzie biblioteka go ma: {}." } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62ad..22055aa2293 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2283,5 +2283,10 @@ "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", + "Moving photos": "Przenoszenie zdjęć", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Przenoszenie zatrzymał błąd (zobacz dziennik). Biblioteka podąża za plikami, które już przeniesiono.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Przenoszenie zatrzymał błąd (zobacz dziennik). Biblioteka może nie podążać za wszystkimi plikami, które już przeniesiono: Znajdź brakujące zdjęcia łączy ponownie te, które utraciła.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Ta biblioteka jest otwarta bez blokady, więc przerwane przenoszenia pozostają bez zmian, dopóki biblioteka nie zostanie otwarta z blokadą; Znajdź brakujące zdjęcia ponownie łączy przeniesione pliki.", + "Unfinished moves": "Nieukończone przenoszenia" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..5b65d003934 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -252,7 +252,6 @@ "{what} merge cancelled": "{what} mesclagem cancelada", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Fotos locais ignoradas: {n}{0:.0} — álbuns contêm fotos da biblioteca (adicione-as às Minhas fotos primeiro)", "New Folder in “{name}”": "Nova pasta em “{name}”", - "Moved {} photo(s)": "{} foto(s) movida(s)", "not added to Apple Photos: {e}": "não adicionadas ao Fotos da Apple: {e}", "{n} added to Apple Photos album “{album}”": "{n} adicionadas ao álbum “{album}” do Fotos da Apple", "{n} added to Apple Photos": "{n} adicionadas ao Fotos da Apple", @@ -305,5 +304,13 @@ "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{})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Fotos sendo movidas quando o LightCraft foi fechado pela última vez: {}. A biblioteca agora aponta para onde os arquivos estão; Editar → Desfazer as traz de volta.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Arquivos sendo movidos que não podem ser acessados agora (um disco desconectado?): {}. O LightCraft verifica de novo na próxima vez que esta biblioteca for aberta.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Um registro de movimentação ({}) não pode ser lido ({}); ele foi deixado como estava.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} estava sendo movido e agora está nos dois lugares: a biblioteca mantém {1}.", + "A sidecar of {} couldn't follow it ({}).": "Um arquivo XMP auxiliar de {} não conseguiu acompanhá-lo ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "A biblioteca não conseguiu acompanhar os arquivos que estavam sendo movidos ({}); Localizar fotos ausentes os vincula de novo.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "A biblioteca acompanha os arquivos que estavam sendo movidos, mas isso não pôde ser salvo ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Cópias removidas do novo local, porque o original ainda estava onde a biblioteca o registra: {}." } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b7..7bc031d8800 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2202,5 +2202,10 @@ "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", + "Moving photos": "Movendo fotos", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Um erro interrompeu a movimentação (veja o registro). A biblioteca acompanha os arquivos que já tinham sido movidos.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Um erro interrompeu a movimentação (veja o registro). A biblioteca pode não acompanhar todos os arquivos que já tinham sido movidos: Localizar fotos ausentes vincula de novo os que ela perdeu.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Esta biblioteca está aberta sem o bloqueio, então as movimentações interrompidas ficam como estão até que ela seja aberta com o bloqueio; Localizar fotos ausentes vincula de novo os arquivos que foram movidos.", + "Unfinished moves": "Movimentações inacabadas" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..53e30e2e3d9 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -248,7 +248,6 @@ "{what} merge cancelled": "{what}: слияние отменено", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Пропущено локальных фото: {n}{0:.0} — в альбомах только фото из библиотеки (сначала добавьте их в «Мои фото»)", "New Folder in “{name}”": "Новая папка в «{name}»", - "Moved {} photo(s)": "Перемещено фото: {}", "not added to Apple Photos: {e}": "не добавлено в Apple Фото: {e}", "{n} added to Apple Photos album “{album}”": "Добавлено в альбом «{album}» Apple Фото: {n}", "{n} added to Apple Photos": "Добавлено в Apple Фото: {n}", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Фото, которые перемещались при последнем закрытии LightCraft: {}. Библиотека теперь указывает туда, где находятся файлы; Правка → Отменить вернёт их.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Перемещаемые файлы, которые сейчас недоступны (диск не подключён?): {}. LightCraft проверит снова при следующем открытии этой библиотеки.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Запись о перемещении ({}) не читается ({}); она оставлена как есть.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} перемещался и теперь находится в обоих местах: библиотека оставляет {1}.", + "A sidecar of {} couldn't follow it ({}).": "XMP-файл для {} не удалось переместить вместе с ним ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Библиотека не смогла последовать за перемещавшимися файлами ({}); «Найти отсутствующие фото» свяжет их заново.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Библиотека следует за перемещавшимися файлами, но сохранить это не удалось ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Копии, удалённые из нового места, потому что оригинал оставался там, где его хранит библиотека: {}." } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df045..59711db54e4 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2349,5 +2349,10 @@ "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, прежде чем добавлять фото", + "Moving photos": "Перемещение фото", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Перемещение остановлено из-за ошибки (см. журнал). Библиотека следует за уже перемещёнными файлами.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Перемещение остановлено из-за ошибки (см. журнал). Библиотека может не следовать за всеми уже перемещёнными файлами: «Найти отсутствующие фото» заново свяжет потерянные.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Эта библиотека открыта без блокировки, поэтому прерванные перемещения остаются как есть, пока библиотека не будет открыта с блокировкой; «Найти отсутствующие фото» заново свяжет перемещённые файлы.", + "Unfinished moves": "Незавершённые перемещения" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c4..ddd1135f78c 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -123,7 +123,6 @@ "Merging… {stage} {:.0}%": "Sammanfogar… {stage} {:.0}%", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Typsnitt: {} (OFL). Ikoner: original.", "Move {what} to Recently Deleted?": "Vill du flytta {what} till Nyligen raderade?", - "Moved {} photo(s)": "Flyttade {} foto(n)", "Moved; {} photo(s) relinked": "Flyttat; {} foto(n) har länkats om", "Named ({named_n})": "Namngivna ({named_n})", "New Folder in “{name}”": "Ny mapp i ”{name}”", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Foton som flyttades när LightCraft stängdes senast: {}. Biblioteket pekar nu dit filerna finns; Redigera → Ångra flyttar tillbaka dem.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Filer som flyttades och inte kan nås nu (en disk som inte är ansluten?): {}. LightCraft tittar igen nästa gång biblioteket öppnas.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "En post om en flyttning ({}) kan inte läsas ({}); den lämnades som den var.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} höll på att flyttas och finns nu på båda platserna: biblioteket behåller {1}.", + "A sidecar of {} couldn't follow it ({}).": "En sidofil till {} kunde inte följa med ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Biblioteket kunde inte följa de filer som flyttades ({}); Sök efter saknade foton länkar om dem.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Biblioteket följer de filer som flyttades, men det kunde inte sparas ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Kopior som togs bort från den nya platsen, eftersom originalet fortfarande låg där biblioteket har det: {}." } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5d..c2518b3671c 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2429,5 +2429,10 @@ "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", + "Moving photos": "Flyttar foton", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Flyttningen stoppades av ett fel (se loggen). Biblioteket följer de filer som redan flyttats.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Flyttningen stoppades av ett fel (se loggen). Biblioteket följer kanske inte alla filer som redan flyttats: Sök efter saknade foton länkar om de som tappats bort.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Det här biblioteket är öppet utan sitt lås, så avbrutna flyttningar lämnas som de är tills det öppnas med låset; Sök efter saknade foton länkar om de filer som flyttats.", + "Unfinished moves": "Ofullständiga flyttningar" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..fc932ad74c4 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -248,7 +248,6 @@ "{what} merge cancelled": "Об’єднання {what} скасовано", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "Пропущено локальних фото: {n}{0:.0} — в альбомах лише фото з бібліотеки (спершу додайте їх до моїх фото)", "New Folder in “{name}”": "Нова тека в «{name}»", - "Moved {} photo(s)": "Переміщено фото: {}", "not added to Apple Photos: {e}": "не додано до Apple Фото: {e}", "{n} added to Apple Photos album “{album}”": "Додано до альбому Apple Фото «{album}»: {n}", "{n} added to Apple Photos": "Додано до Apple Фото: {n}", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Фото, що переміщувалися під час останнього закриття LightCraft: {}. Бібліотека тепер вказує туди, де є файли; Редагування → Скасувати поверне їх.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Файли, що переміщуються, зараз недоступні (диск не під'єднано?): {}. LightCraft перевірить знову під час наступного відкриття цієї бібліотеки.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Запис про переміщення ({}) не читається ({}); його залишено як є.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} переміщувався і тепер є в обох місцях: бібліотека залишає {1}.", + "A sidecar of {} couldn't follow it ({}).": "Супровідний файл {} не вдалося перемістити разом із ним ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Бібліотека не змогла слідувати за файлами, що переміщувалися ({}); «Знайти відсутні фото» зв'яже їх знову.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Бібліотека слідує за файлами, що переміщувалися, але зберегти це не вдалося ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Копії, видалені з нового місця, бо оригінал усе ще лежав там, де його зберігає бібліотека: {}." } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe0..d800cc57622 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2354,5 +2354,10 @@ "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, перш ніж додавати фото", + "Moving photos": "Переміщення фото", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Переміщення зупинено через помилку (див. журнал). Бібліотека слідує за вже переміщеними файлами.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Переміщення зупинено через помилку (див. журнал). Бібліотека може не слідувати за всіма вже переміщеними файлами: «Знайти відсутні фото» заново пов’яже втрачені.", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Цю бібліотеку відкрито без блокування, тому перервані переміщення залишаються як є, доки її не відкриють із блокуванням; «Знайти відсутні фото» заново пов’яже переміщені файли.", + "Unfinished moves": "Незавершені переміщення" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff060..7a0cc14d9a8 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -130,7 +130,6 @@ "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Move {what} to Recently Deleted?": "Chuyển {what} vào Đã xóa gần đây?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", - "Moved {} photo(s)": "Đã di chuyển {} ảnh", "Moved; {} photo(s) relinked": "Đã di chuyển; liên kết lại {} ảnh", "Named ({named_n})": "Có tên ({named_n})", "New Folder in “{name}”": "Thư mục mới trong «{name}»", @@ -305,5 +304,13 @@ "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})", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "Ảnh đang được di chuyển khi LightCraft đóng lần trước: {}. Thư viện giờ trỏ tới nơi các tệp đang ở; Chỉnh sửa → Hoàn tác sẽ chuyển chúng về.", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "Các tệp đang được di chuyển mà hiện không truy cập được (ổ đĩa chưa kết nối?): {}. LightCraft sẽ kiểm tra lại vào lần mở thư viện này tiếp theo.", + "A record of a move ({}) can't be read ({}); it was left as it is.": "Không đọc được bản ghi về một lần di chuyển ({}) ({}); bản ghi được giữ nguyên.", + "{} was being moved and is now at both places: the library keeps {}.": "{0} đang được di chuyển và giờ nằm ở cả hai nơi: thư viện giữ {1}.", + "A sidecar of {} couldn't follow it ({}).": "Sidecar của {} không thể đi theo tệp ({}).", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "Thư viện không thể theo các tệp đang được di chuyển ({}); Tìm ảnh bị thiếu sẽ liên kết lại chúng.", + "The files that were being moved are followed, but that couldn't be saved ({}).": "Thư viện đi theo các tệp đang được di chuyển, nhưng không lưu được ({}).", + "Copies removed from the new place, because the original was still where the library has it: {}.": "Các bản sao đã bị xóa khỏi vị trí mới vì bản gốc vẫn ở nơi thư viện ghi nhận: {}." } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81c..44264162832 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1097,6 +1097,9 @@ "Moves every photo imported from this disk to Recently Deleted; no file is touched": "Chuyển mọi ảnh nhập từ đĩa này sang Đã xóa gần đây; không đụng tệp", "Moves the files and their XMP sidecars into this folder; never overwrites": "Chuyển tệp và sidecar XMP vào thư mục này; không bao giờ ghi đè", "Moves the photos imported from this folder to Recently Deleted; no file is touched": "Chuyển ảnh nhập từ thư mục này sang Đã xóa gần đây; không đụng tệp", + "Moving photos": "Đang di chuyển ảnh", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "Việc di chuyển bị dừng do lỗi (xem nhật ký). Thư viện đi theo các tệp đã được di chuyển.", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "Việc di chuyển bị dừng do lỗi (xem nhật ký). Thư viện có thể không đi theo mọi tệp đã được di chuyển: Tìm ảnh bị thiếu sẽ liên kết lại những tệp bị mất.", "Muted": "Dịu", "Muted Film": "Phim dịu", "My Photos": "Ảnh của tôi", @@ -2235,5 +2238,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", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "Thư viện này được mở mà không có khóa, nên các lần di chuyển bị gián đoạn được giữ nguyên cho đến khi thư viện được mở với khóa; Tìm ảnh bị thiếu sẽ liên kết lại các tệp đã được di chuyển.", + "Unfinished moves": "Lần di chuyển chưa hoàn tất" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..244ef4ac343 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -252,7 +252,6 @@ "{what} merge cancelled": "已取消 {what} 合并", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "已跳过 {n} 张本地照片{0:.0}:相册只能收录图库中的照片(请先添加到我的照片)", "New Folder in “{name}”": "在“{name}”中新建文件夹", - "Moved {} photo(s)": "已移动 {} 张照片", "not added to Apple Photos: {e}": "未添加到 Apple 照片:{e}", "{n} added to Apple Photos album “{album}”": "已将 {n} 个添加到 Apple 照片相册“{album}”", "{n} added to Apple Photos": "已将 {n} 个添加到 Apple 照片", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "上次关闭 LightCraft 时正在移动的照片:{}。图库现在指向文件所在的位置;编辑 → 撤销 可移回。", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "正在移动但现在无法访问的文件(磁盘未连接?):{}。下次打开此图库时 LightCraft 会再次检查。", + "A record of a move ({}) can't be read ({}); it was left as it is.": "无法读取移动记录({})({});已保持原样。", + "{} was being moved and is now at both places: the library keeps {}.": "{0} 正在移动,现在两个位置都有:图库保留 {1}。", + "A sidecar of {} couldn't follow it ({}).": "{} 的附属文件未能随之移动({})。", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "图库未能跟随正在移动的文件({});查找缺失的照片 可重新链接它们。", + "The files that were being moved are followed, but that couldn't be saved ({}).": "图库已跟随正在移动的文件,但无法保存({})。", + "Copies removed from the new place, because the original was still where the library has it: {}.": "已从新位置删除的副本(原文件仍在图库记录的位置):{}。" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a6251..671d32cf133 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2200,5 +2200,10 @@ "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 目录的导入", + "Moving photos": "正在移动照片", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "移动因出错而停止(见日志)。图库会跟随已移动的文件。", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "移动因出错而停止(见日志)。图库可能没有跟随所有已移动的文件:用“查找缺失的照片”可重新关联丢失的文件。", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "此图库未取得锁就被打开,因此被中断的移动会保持原样,直到图库带锁打开;用“查找缺失的照片”可重新关联已移动的文件。", + "Unfinished moves": "未完成的移动" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..32f5cb1b38e 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -252,7 +252,6 @@ "{what} merge cancelled": "已取消{what}合併", "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)": "已略過 {n} 張本機照片{0:.0}:相簿只能收錄照片庫中的照片(請先加入我的照片)", "New Folder in “{name}”": "在「{name}」中新增資料夾", - "Moved {} photo(s)": "已移動 {} 張照片", "not added to Apple Photos: {e}": "未加入 Apple 照片:{e}", "{n} added to Apple Photos album “{album}”": "已將 {n} 個加入 Apple 照片相簿「{album}」", "{n} added to Apple Photos": "已將 {n} 個加入 Apple 照片", @@ -305,5 +304,13 @@ "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}", + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.": "上次關閉 LightCraft 時正在移動的照片:{}。照片庫現在指向檔案所在的位置;編輯 → 復原 可移回。", + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.": "正在移動但目前無法存取的檔案(磁碟未連接?):{}。下次開啟此照片庫時 LightCraft 會再次檢查。", + "A record of a move ({}) can't be read ({}); it was left as it is.": "無法讀取移動記錄({})({});已保持原樣。", + "{} was being moved and is now at both places: the library keeps {}.": "{0} 正在移動,現在兩個位置都有:照片庫保留 {1}。", + "A sidecar of {} couldn't follow it ({}).": "{} 的附屬檔案未能隨之移動({})。", + "The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.": "照片庫未能跟隨正在移動的檔案({});尋找遺失的照片 可重新連結它們。", + "The files that were being moved are followed, but that couldn't be saved ({}).": "照片庫已跟隨正在移動的檔案,但無法儲存({})。", + "Copies removed from the new place, because the original was still where the library has it: {}.": "已從新位置刪除的副本(原始檔案仍在照片庫記錄的位置):{}。" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec87..88613ae5bef 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2157,5 +2157,10 @@ "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 目錄的匯入", + "Moving photos": "正在移動照片", + "Moving was stopped by an error (see the log). The library follows the files that had moved.": "移動因發生錯誤而停止(見記錄)。照片庫會跟隨已移動的檔案。", + "Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.": "移動因發生錯誤而停止(見記錄)。照片庫可能沒有跟隨所有已移動的檔案:用「尋找遺失的照片」可重新連結遺失的檔案。", + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.": "此照片庫未取得鎖定就被開啟,因此被中斷的移動會保持原樣,直到照片庫以鎖定開啟;用「尋找遺失的照片」可重新連結已移動的檔案。", + "Unfinished moves": "未完成的移動" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fa10210f0a3..c0594b5362d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -42,9 +42,11 @@ impl LightcraftApp { headless_host: false, notices: vec![], updates_rt: Default::default(), + move_notice: None, quit_prompt: None, notice_input: Default::default(), quit_confirmed: false, + quit_cuts_move: false, control_rx: None, pending_screenshots: vec![], pending_gestures: vec![], @@ -105,6 +107,8 @@ impl LightcraftApp { sync: None, sync_owns_changes: false, sync_run: None, + move_run: None, + last_move: None, lightroom: None, lightroom_last: None, lightroom_result: None, @@ -272,6 +276,11 @@ impl LightcraftApp { if id == "faces.detect" && e.kind == ErrorKind::ModelMissing(AiModel::FaceDetector) { panels::faces::offer_detector(self); } + // a move running in the background is in the way: said wherever the command came from (a menu, a key, a + // button), since the status line isn't drawn + if e.kind == ErrorKind::MoveInProgress { + self.toast_move_in_progress(&e.message); + } } Ok(v) if id == "faces.detect" => self.ui.status = detect_summary(v), Ok(v) if id == "faces.renamePerson" => { @@ -526,6 +535,21 @@ impl LightcraftApp { self.ui.toast = Some((text.into(), t + 6.0, None)); } + /// Tell the person that a background move of photos is in the way of what they asked (stays 6 s). The time is the + /// app clock's, which a menu click that arrives before the next frame reads as well. + fn toast_move_in_progress(&mut self, text: &str) { + let now = self.tick_now(); + self.ui.toast = Some((text.to_string(), now + 6.0, None)); + } + + /// Called as the app exits, before the library is saved and closed: a move whose worker has + /// already finished (its result waiting for the next frame) is applied now, so the catalog + /// matches the files. A worker still running is abandoned, as quitting always did. + pub fn finish_ready_move(&mut self) { + let ctx = self.tasks.repaint.clone().unwrap_or_default(); + crate::move_task::poll(self, &ctx); + } + /// The process is about to end (settings and library are saved by then): make sure nothing is /// inside the GPU driver when it does (issue #620: a render running on a worker thread while /// the process exits crashes in the driver). No GPU work starts from here on; the render diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 6e92091c780..7786639a678 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -60,6 +60,7 @@ impl LightcraftApp { import::poll_scan(self, ctx); sync::poll(self, ctx); sync::poll_run(self, ctx); + crate::move_task::poll(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 // gate cannot express that (a slow discarded first pass would re-run it). diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index caacbc59088..d77b96d44d3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -139,6 +139,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "status": app.ui.status, "copied": app.copied, "notices": app.notices, + "moveNotice": app.move_notice, "quitPrompt": app.quit_prompt.as_ref().map(crate::QuitPrompt::text), // how hard the background face scan may work right now, and why it is judged so (see `panels::faces::scan_pace`) "faceScan": {"pace": app.caches.faces_pace, "focused": app.caches.faces_in_front, "pending": app.caches.faces_pending, "indexed": app.caches.faces_indexed}, @@ -148,6 +149,8 @@ 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(), + // photos being moved to another folder (`photo.moveToFolder {background: true}`), and how the last move ended + "move": {"running": app.move_run.as_ref().map(crate::move_task::MoveRun::status), "last": app.last_move}, // every long-running task in flight, as the activity stack shows them (`activity.list`) "activity": app.session.activity.list(), // commands waiting on a native file dialog shown off the UI thread (`pick`) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 64628822031..005dc157dfb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -475,16 +475,10 @@ fn confirmed(app: &mut LightcraftApp, ctx: &egui::Context, dlg: &mut Dialog) -> crate::panels::grid::toast_skipped(app, ctx, &r); closed = true; } - // a move says how it went, or why nothing moved - Ok(r) if matches!(dlg, Dialog::MovePhotos { .. }) => { - if let Dialog::MovePhotos { name, .. } = dlg { - let text = crate::panels::left::moved_text(r["moved"].as_u64().unwrap_or(0), name); - app.toast(ctx, text); - } - closed = true; - } + // a move that began says how it went when it ends (`move_task`); one that can't, why now + Ok(_) if matches!(dlg, Dialog::MovePhotos { .. }) => closed = true, Err(e) if matches!(dlg, Dialog::MovePhotos { .. }) => { - app.toast(ctx, e); + app.toast_error(ctx, e); closed = true; } // photos whose capture time doesn't read are left as they were: say so diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 6b8998c33c8..0b87ce3a23b 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -215,7 +215,8 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result { diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index e1f506d5b46..70a42670a1f 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -24,6 +24,8 @@ pub struct ImportTask { /// The library photos the skipped duplicates match (shown when nothing new was added). existing: Vec, pub failed: usize, + /// Why a batch was left alone while photos were being moved to another folder (not counted as failed). + refused: Option, /// Move: originals moved, and sources left in place (reported by the engine with a reason). pub moved: usize, pub kept: usize, @@ -360,6 +362,11 @@ fn commit_batch(app: &mut LightcraftApp, task: &mut ImportTask, prepared: lightc task.first = ["imported", "restored"].iter().find_map(|k| v[*k].as_array().and_then(|a| a.first()).and_then(Value::as_u64)); } } + Err(e) if e.kind() == lightcraft_engine::ErrorKind::MoveInProgress => { + // a photo the import would replace or restore is being moved: this batch was left alone + log::warn!("import: {e}"); + task.refused = Some(e.to_string()); + } Err(e) => { log::warn!("import: {e}"); task.failed += n; @@ -455,6 +462,7 @@ fn finish(app: &mut LightcraftApp, ctx: &egui::Context, task: ImportTask) { if task.imported == 0 && task.restored == 0 && task.failed == 0 + && task.refused.is_none() && task.warnings.is_empty() && !task.cancelled && show_existing(app, ctx, &task.existing) @@ -463,7 +471,11 @@ fn finish(app: &mut LightcraftApp, ctx: &egui::Context, task: ImportTask) { } let mut msg = import_summary(app, &task); if task.warnings.is_empty() { - app.toast(ctx, msg); + if task.refused.is_some() { + app.toast_for(ctx, msg, 8.0); + } else { + app.toast(ctx, msg); + } } else { msg.push_str("\n\n"); msg.push_str(&xmp_warnings_text(&task.warnings)); @@ -475,6 +487,8 @@ fn finish(app: &mut LightcraftApp, ctx: &egui::Context, task: ImportTask) { fn quiet_finish(app: &mut LightcraftApp, ctx: &egui::Context, task: &ImportTask) { if !task.warnings.is_empty() { app.toast_for(ctx, xmp_warnings_text(&task.warnings), 8.0); + } else if task.auto && task.refused.is_some() { + app.toast_for(ctx, task.refused.clone().unwrap_or_default(), 8.0); } else if task.auto && task.imported > 0 { app.toast(ctx, crate::i18n::tr_format!("Auto Import: added {} photo{}", task.imported, crate::i18n::plural_s(task.imported))); } else if !task.auto && task.failed > 0 { @@ -510,6 +524,11 @@ fn import_summary(app: &LightcraftApp, task: &ImportTask) -> String { if task.failed > 0 { msg.push_str(&crate::i18n::tr_format!(" · {} not readable", task.failed)); } + if let Some(why) = &task.refused { + // (the batches it left alone were not imported: the reason, not "not readable") + msg.push_str("\n\n"); + msg.push_str(why); + } msg } diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 8e41e8dd422..bb125bb8e07 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -11,6 +11,9 @@ pub(crate) fn can_switch_library(app: &LightcraftApp) -> Result<(), String> { if app.import.is_some() || app.scan.is_some() { return Err("wait for the import to finish before switching libraries".into()); } + if app.move_run.is_some() { + return Err("wait for the photos being moved to arrive before switching libraries".into()); + } Ok(()) } @@ -68,6 +71,8 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result let previous_dir = app.session.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()); let previous = previous_dir.as_ref().map(|d| d.to_string_lossy().into_owned()); app.session.close_library().map_err(|e| e.to_string())?; + // what the open of the library being left found of its moves isn't about the next one + app.move_notice = None; let opened = app.session.open_library(&dir, false).map(|_| ()).map_err(|e| format!("{path}: {e}")); app.lightroom_last = None; app.lightroom_result = None; diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index ab49563cbb8..bd79210998b 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.move_run.is_some() || self.app.import.is_some() || self.app.export.is_some() || self.app.session.denoise_busy() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9db7035c1d0..db04e9ff5b0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,6 +23,7 @@ pub mod lightroom_import; pub mod links; pub mod menus; mod model_setup; +pub mod move_task; pub mod panels; pub mod pick; pub mod recheck; @@ -158,12 +159,17 @@ pub struct LightcraftApp { /// Warnings to show one at a time (damaged settings files…, issue #103). pub notices: Vec, pub(crate) updates_rt: updates_ui::Runtime, + /// What following moves an earlier run cut short came to, shown once under its own title + /// ([`panels::notices::recovered_text`]); not a settings problem. + pub move_notice: Option, /// Quitting was stopped to ask first: changes couldn't be saved, or tasks are running. pub quit_prompt: Option, /// Keyboard/focus/input state for the prompt above, including its one-frame creation barrier. pub(crate) notice_input: panels::notices::PromptInput, /// Quit Anyway was chosen: the window may close with unsaved changes. pub quit_confirmed: bool, + /// Quit Anyway was chosen while photos were moving: the move (which has no ✕) is cut short. + pub quit_cuts_move: bool, control_rx: Option>, pending_screenshots: Vec, /// Synthetic-input control requests waiting for a fresh layout and delivery (plan §4.5). @@ -295,6 +301,10 @@ pub struct LightcraftApp { pub sync_owns_changes: bool, /// A Synchronize Folder at work in the background. pub sync_run: Option, + /// Photos being moved to another folder in the background (`move_task`). + pub move_run: Option, + /// How the last background move ended (`ui.inspect` → `move.last`). + pub last_move: Option, /// A Lightroom catalog inspect/import in progress. pub lightroom: Option, /// Last terminal Lightroom result, exposed by the command's status/wait response. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index c88a502078d..c47da3ccb5f 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -168,6 +168,10 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option Option>; 12] = [ ui_commands_1, ui_commands_2, diff --git a/crates/ui-egui/src/move_task.rs b/crates/ui-egui/src/move_task.rs new file mode 100644 index 00000000000..03c17ccd05c --- /dev/null +++ b/crates/ui-egui/src/move_task.rs @@ -0,0 +1,175 @@ +//! Moving photos to another folder in the app (a drop on a Folders row, Move Selected Photos Here, +//! Move to Folder…): the files move on a worker thread, so a large move to a slow NAS doesn't +//! freeze the window. The activity stack shows it ("Moving photos", k of N, the file in hand). The +//! library follows the files between frames ([`poll`]), as one undo step; see +//! `lightcraft_engine::move_job`. + +use std::sync::mpsc::{Receiver, TryRecvError}; + +use lightcraft_engine::move_job::{MoveFinish, MoveOutcome}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; + +/// A move at work: its files on a worker thread, the library's half here. +pub struct MoveRun { + rx: Receiver, + finish: Option, + folder: String, + /// The folder's name, as the toast says it. + name: String, + /// The worker, so a test can wait until it has sent its result. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) worker: Option>, +} + +impl MoveRun { + /// `ui.inspect` → `move.running`. + pub fn status(&self) -> Value { + json!({"folder": self.folder, "files": self.finish.as_ref().map(MoveFinish::files), "task": self.finish.as_ref().map(MoveFinish::task_id)}) + } +} + +/// A move that never ends, with its row, for tests of what the window does while one runs: the +/// sender keeps the worker alive, the guard keeps the row. +#[cfg(test)] +pub(crate) fn stalled(app: &mut LightcraftApp) -> (std::sync::mpsc::Sender, lightcraft_engine::activity::TaskGuard) { + let (tx, rx) = std::sync::mpsc::channel(); + let guard = app.session.activity.start("move", "Moving photos", lightcraft_engine::activity::Cancel::No); + app.move_run = Some(MoveRun { + rx, + finish: None, + folder: String::new(), + name: String::new(), + #[cfg(all(test, not(target_arch = "wasm32")))] + worker: None, + }); + (tx, guard) +} + +/// The name a toast gives the folder `path`. +fn name_of(path: &str) -> String { + let trimmed = path.trim_end_matches(['/', '\\']); + std::path::Path::new(trimmed).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()) +} + +/// Start moving photos into a folder on disk: `params` as `photo.moveToFolder` takes them +/// (`{folder, ids?}`; the selection by default). Returns at once: `{background: true, files}` +/// while it runs, or `{moved: 0, folder}` when every photo is there already (said in a toast). An error when the move can't begin (Local photos, another move +/// running…), also logged, shown in the status line as `LightcraftApp::run` does, and told in an error toast +/// (a menu, key or button caller drops the returned error, so the toast is what tells the person why nothing moved). +pub fn start(app: &mut LightcraftApp, ctx: &egui::Context, params: &Value) -> Result { + start_inner(app, ctx, params).inspect_err(|e| { + log::warn!("photo.moveToFolder: {e}"); + app.ui.status = e.clone(); + app.toast_error(ctx, e.clone()); + }) +} + +fn start_inner(app: &mut LightcraftApp, ctx: &egui::Context, params: &Value) -> Result { + let raw = params.get("folder").and_then(Value::as_str).unwrap_or_default(); + let path = raw.trim_end_matches(['/', '\\']).to_string(); + let name = name_of(raw); + let started = lightcraft_engine::move_job::start(&mut app.session, params).map_err(|e| e.to_string())?; + let Some((work, finish)) = started else { + app.toast(ctx, crate::panels::left::moved_text(0, &name)); + return Ok(json!({"moved": 0, "folder": path})); + }; + let files = finish.files(); + let (tx, rx) = std::sync::mpsc::channel(); + let repaint = app.tasks.repaint.clone().unwrap_or_else(|| ctx.clone()); + let job = move || { + // (a panic here ends the worker: `poll` sees the channel closed and lets the library + // follow whatever had moved, from the move's record) + if let Ok(out) = lightcraft_engine::guard::catch("move to folder", || work.run()) { + let _ = tx.send(out); + } + repaint.request_repaint(); + }; + #[cfg(not(target_arch = "wasm32"))] + #[cfg_attr(not(test), allow(unused_variables))] + let worker = std::thread::Builder::new().name("lc-move".into()).spawn(job).map_err(|e| format!("can't start the move: {e}"))?; + #[cfg(target_arch = "wasm32")] + job(); + app.move_run = Some(MoveRun { + rx, + finish: Some(finish), + folder: path, + name, + #[cfg(all(test, not(target_arch = "wasm32")))] + worker: Some(worker), + }); + Ok(json!({"background": true, "files": files})) +} + +/// Bring the library along once the files have moved (called every frame): one undo step, the +/// photos that left the view leave the selection, and a toast says how it went. +pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some(run) = app.move_run.as_mut() else { return }; + let out = match run.rx.try_recv() { + Ok(out) => Some(out), + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + Err(TryRecvError::Disconnected) => None, + }; + let Some(mut run) = app.move_run.take() else { return }; + let Some(finish) = run.finish.take() else { return }; + let result = match out { + Some(out) => app.session.execute_fn("photo.moveToFolder", |s| finish.finish(s, out)).map_err(|e| e.to_string()), + None => { + // the worker died part-way (logged): the move is over; the library follows what moved + let mut recovered = None; + let r = app + .session + .execute_fn("photo.moveToFolder", |s| { + let r = finish.abandon(s); + let value = json!(r); + recovered = Some(r); + Ok(value) + }) + .map_err(|e| e.to_string()); + log::warn!("move to {}: stopped by an error; recovered: {r:?}", run.folder); + // said only when every moved file was followed (the log has the rest) + Err(if recovered.is_some_and(|r| r.problems.is_empty() && r.waiting == 0) { + crate::i18n::tr("Moving was stopped by an error (see the log). The library follows the files that had moved.").to_string() + } else { + crate::i18n::tr("Moving was stopped by an error (see the log). The library may not follow every file that had moved: Find Missing Photos relinks the ones it lost.").to_string() + }) + } + }; + // photos that left the view leave the selection, so nothing done next (Delete, an edit) + // reaches photos no longer on screen + let visible: std::collections::HashSet = app.session.visible_cloned().into_iter().collect(); + let sel = &mut app.session.selection; + sel.ids.retain(|id| visible.contains(id)); + if sel.active.is_some_and(|a| !visible.contains(&a)) { + sel.active = sel.ids.first().copied(); + } + match &result { + Ok(r) => app.toast(ctx, crate::panels::left::moved_text(r["moved"].as_u64().unwrap_or(0), &run.name)), + Err(e) => app.toast_for(ctx, e.clone(), 12.0), + } + app.last_move = Some(match result { + Ok(r) => r, + Err(e) => json!({"error": e, "folder": run.folder}), + }); +} + +/// Wait for a running move and bring the library along (tests, and commands asked to wait). +/// `false` on timeout. +pub fn wait(app: &mut LightcraftApp, ctx: &egui::Context, timeout: std::time::Duration) -> bool { + let t0 = web_time::Instant::now(); + loop { + poll(app, ctx); + if app.move_run.is_none() { + return true; + } + if t0.elapsed() > timeout { + return false; + } + #[cfg(not(target_arch = "wasm32"))] + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 5064b8d401c..a4d2e6f1ed8 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1390,17 +1390,16 @@ fn context_menu_file_actions(app: &mut LightcraftApp, ui: &mut egui::Ui) { let can_pick = app.services.pick_folder.is_some() || app.services.picker.is_some(); if can_pick && ui.button(crate::i18n::tr("Move to Folder…")).clicked() { // the folder dialog goes through the shared picker (off the UI thread where the host has - // one: then photo.moveToFolder runs when it closes) + // one: then photo.moveToFolder runs when it closes); the move itself runs in the background let req = crate::pick::PickRequest::folder(crate::i18n::tr("Move to Folder…")); - let picked = - crate::pick::ask(app, "photo.moveToFolder", &json!({}), "folder", req, |s| s.pick_folder.as_mut().and_then(|f| f()).map(|x| vec![x])); + let picked = crate::pick::ask(app, "photo.moveToFolder", &json!({"background": true}), "folder", req, |s| { + s.pick_folder.as_mut().and_then(|f| f()).map(|x| vec![x]) + }); if let crate::pick::Picked::Now(v) = picked && let Some(into) = v.into_iter().next() { - match app.run("photo.moveToFolder", json!({"folder": into})) { - Ok(r) => app.toast(ui.ctx(), crate::i18n::tr_format!("Moved {} photo(s)", r["moved"])), - Err(e) => app.toast(ui.ctx(), e), - } + // (a refusal is told in a toast by `start`) + let _ = crate::move_task::start(app, ui.ctx(), &json!({"folder": into})); } } if ui.button(crate::i18n::tr("Reload from Disk")).clicked() { diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 27b86aa0d58..56b5609e7b9 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -23,7 +23,7 @@ pub use albums::{album_drag_feedback, auto_scroll_speed}; use albums::{albums_rows, drag_auto_scroll}; pub(crate) use dates::browse_all_photos; use dates::date_rows; -pub(crate) use folders::{folder_row_of, move_photos, moved_text}; +pub(crate) use folders::{folder_row_of, moved_text}; use folders::{folder_rows, reveal_chosen}; use keywords::keyword_rows; pub(crate) use local::{fs_cached, fs_cached_running, same_folder}; diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 20c1bbce130..137fb8a9b84 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -426,7 +426,7 @@ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::R let library = app.session.library_generation(); app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, dont_ask: false, library }); } else { - move_photos_here(app, ui.ctx(), Some(&ids), &n.path, &name); + move_photos_here(app, ui.ctx(), Some(&ids), &n.path); } } } @@ -456,24 +456,6 @@ fn spring_open(ui: &egui::Ui, n: &FolderNode, open_id: egui::Id, open: &mut bool } } -/// Move photos (`ids`, else the selection) into the folder `path` on disk (`photo.moveToFolder`). -/// Photos that leave the view leave the selection, so nothing done next (Delete, an edit) reaches -/// photos no longer on screen. How many moved, or why none did. -pub(crate) fn move_photos(app: &mut LightcraftApp, ids: Option<&[u64]>, path: &str) -> Result { - let mut params = json!({"folder": path}); - if let Some(ids) = ids { - params["ids"] = json!(ids); - } - let r = app.run("photo.moveToFolder", params)?; - let visible: std::collections::HashSet = app.session.visible_cloned().into_iter().collect(); - let sel = &mut app.session.selection; - sel.ids.retain(|id| visible.contains(id)); - if sel.active.is_some_and(|a| !visible.contains(&a)) { - sel.active = sel.ids.first().copied(); - } - Ok(r["moved"].as_u64().unwrap_or(0)) -} - /// What a move of `n` photos into the folder `name` says: how many moved and that Undo moves them /// back, or that they were there already. pub(crate) fn moved_text(n: u64, name: &str) -> String { @@ -484,12 +466,15 @@ pub(crate) fn moved_text(n: u64, name: &str) -> String { } } -/// [`move_photos`], saying how it went in a toast. -fn move_photos_here(app: &mut LightcraftApp, ctx: &egui::Context, ids: Option<&[u64]>, path: &str, name: &str) { - match move_photos(app, ids, path) { - Ok(n) => app.toast(ctx, moved_text(n, name)), - Err(e) => app.toast(ctx, e), +/// Move photos (`ids`, else the selection) into the folder `path` on disk, in the background +/// (`move_task`: a toast says how it went once it ends); a toast says why when it can't begin. +fn move_photos_here(app: &mut LightcraftApp, ctx: &egui::Context, ids: Option<&[u64]>, path: &str) { + let mut params = json!({"folder": path}); + if let Some(ids) = ids { + params["ids"] = json!(ids); } + // (a refusal is told in a toast by `start`) + let _ = crate::move_task::start(app, ctx, ¶ms); } /// The context menu of a Folders row: a folder's own, a disk's (remove it), none for the @@ -637,7 +622,7 @@ fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &F .on_hover_text(crate::i18n::tr("Moves the files and their XMP sidecars into this folder; never overwrites")) .clicked() { - move_photos_here(app, ui.ctx(), None, path, &name); + move_photos_here(app, ui.ctx(), None, path); ui.close(); } if app.services.reveal.is_some() diff --git a/crates/ui-egui/src/panels/notices.rs b/crates/ui-egui/src/panels/notices.rs index 96e356bb444..312be41509a 100644 --- a/crates/ui-egui/src/panels/notices.rs +++ b/crates/ui-egui/src/panels/notices.rs @@ -1,18 +1,23 @@ //! Things the user must not miss (issue #103): settings files that were damaged or unreadable when -//! the library opened (and host warnings such as a damaged `ui.json`), and quitting while changes -//! are only in memory or while tasks that would be cut short are running (issue #345). +//! the library opened (and host warnings such as a damaged `ui.json`), moves an earlier run cut +//! short, and quitting while changes are only in memory or while tasks that would be cut short are +//! running (issue #345). use egui::{Align2, RichText, vec2}; +use lightcraft_engine::move_intent::{MoveProblem, Recovered}; use crate::theme::Tokens; use crate::widgets::WidgetHit; use crate::{LightcraftApp, QuitPrompt}; -/// Collect the library's settings-file warnings (each is shown once), and the no-GPU notice once the GPU device has -/// been tried. +/// Collect the library's settings-file warnings (each is shown once), what following moves an earlier run cut short +/// came to, and the no-GPU notice once the GPU device has been tried. pub fn logic(app: &mut LightcraftApp) { let new = app.session.take_library_warnings(); app.notices.extend(new); + if let Some(r) = app.session.take_recovered_moves() { + app.move_notice = recovered_text(&r); + } use lightcraft_engine::gpu; if app.gpu_notice && app.gpu_applied == Some(true) && gpu::ready() { app.gpu_notice = false; @@ -56,6 +61,51 @@ fn unsaved_message(n: usize, e: &str) -> String { crate::i18n::tr_format!("{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.", s, lost, n = n, e = e) } +/// What following moves an earlier run cut short came to, in the person's language; `None` when there is nothing to +/// say. +pub fn recovered_text(r: &Recovered) -> Option { + use crate::i18n::tr_format; + if r.is_empty() { + return None; + } + let mut parts = Vec::new(); + if r.relinked > 0 { + parts.push(tr_format!( + "Photos being moved when LightCraft last closed: {}. The library now points at where the files are; Edit → Undo moves them back.", + r.relinked + )); + } + if r.waiting > 0 { + parts.push(tr_format!( + "Files being moved that can't be reached now (a disk not connected?): {}. LightCraft looks again the next time this library opens.", + r.waiting + )); + } + if r.copies_removed > 0 { + parts.push(tr_format!("Copies removed from the new place, because the original was still where the library has it: {}.", r.copies_removed)); + } + for p in &r.problems { + parts.push(match p { + MoveProblem::UnreadableRecord { record, error } => { + tr_format!("A record of a move ({}) can't be read ({}); it was left as it is.", record, error) + } + MoveProblem::BothPlaces { from, to } => tr_format!("{} was being moved and is now at both places: the library keeps {}.", to, from), + MoveProblem::SidecarStayed { to, error } => tr_format!("A sidecar of {} couldn't follow it ({}).", to, error), + MoveProblem::NotFollowed { error } => { + tr_format!("The library couldn't follow the files that were being moved ({}); Find Missing Photos relinks them.", error) + } + MoveProblem::NotSaved { error } => { + tr_format!("The files that were being moved are followed, but that couldn't be saved ({}).", error) + } + MoveProblem::Unprotected => crate::i18n::tr( + "This library is open without its lock, so moves that were cut short are left as they are until it opens with the lock; Find Missing Photos relinks files that moved.", + ) + .to_string(), + }); + } + Some(parts.join(" ")) +} + /// The window may close now (`true`), or the quit prompt is shown (`false`). Running tasks that /// can be cancelled (an import, an export…) are asked about first; then changes that couldn't be /// written are retried — the log, then a snapshot of everything in memory. @@ -64,7 +114,14 @@ pub fn may_close(app: &mut LightcraftApp) -> bool { return true; } // before the library is touched: a Cancel here keeps working with it - let running = app.session.activity.running_cancellable(); + let mut running = app.session.activity.running_cancellable(); + // photos on their way to another folder can't be stopped, but quitting cuts the move short + if app.move_run.is_some() + && !app.quit_cuts_move + && let Some(task) = app.session.activity.list().into_iter().find(|t| t.kind == "move") + { + running.push(task); + } if !running.is_empty() { let names = running.iter().map(|t| crate::i18n::tr(&t.label)).collect::>().join(", "); app.quit_prompt = Some(QuitPrompt::Tasks(tasks_message(running.len(), &names))); @@ -102,11 +159,12 @@ enum Choice { /// the main view or a `Middle` dialog. The control channel and raw keyboard/event handlers do not /// go through that hit test, however: they must consult this explicit barrier as well. pub(crate) fn prompt_layer(app: &LightcraftApp) -> Option { - let id = match (&app.quit_prompt, app.notices.is_empty()) { - (Some(QuitPrompt::Tasks(_)), _) => "quit-tasks", - (Some(QuitPrompt::Unsaved(_)), _) => "quit-unsaved", - (None, false) => "settings-notice", - (None, true) => return None, + let id = match (&app.quit_prompt, app.move_notice.is_some(), app.notices.is_empty()) { + (Some(QuitPrompt::Tasks(_)), ..) => "quit-tasks", + (Some(QuitPrompt::Unsaved(_)), ..) => "quit-unsaved", + (None, true, _) => "move-notice", + (None, false, false) => "settings-notice", + (None, false, true) => return None, }; Some(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique(id))) } @@ -138,10 +196,11 @@ struct PromptKey { /// Identity of the prompt currently owning input: its layer, text and, for the settings-notice /// queue, the number of notices remaining, including the one shown. `None` when no prompt is up. fn prompt_key(app: &LightcraftApp) -> Option { - let (layer, text, queue_len) = match (&app.quit_prompt, app.notices.first()) { - (Some(prompt), _) => (prompt_layer(app)?, prompt.text().to_string(), 0), - (None, Some(text)) => (prompt_layer(app)?, text.clone(), app.notices.len()), - (None, None) => return None, + let (layer, text, queue_len) = match (&app.quit_prompt, &app.move_notice, app.notices.first()) { + (Some(prompt), ..) => (prompt_layer(app)?, prompt.text().to_string(), 0), + (None, Some(text), _) => (prompt_layer(app)?, text.clone(), 0), + (None, None, Some(text)) => (prompt_layer(app)?, text.clone(), app.notices.len()), + (None, None, None) => return None, }; Some(PromptKey { layer, text, queue_len }) } @@ -536,10 +595,14 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { app.quit_prompt = None; if buttons.get(i).is_some_and(|(_, _, choice)| *choice == Choice::QuitAnyway) { app.session.activity.cancel_all(); + // a move can't be stopped, so choosing to quit is what lets it be cut short + app.quit_cuts_move = true; // unsaved changes still get their own question if may_close(app) { app.ui.quit = true; } + } else { + app.quit_cuts_move = false; } return; } @@ -570,7 +633,17 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { app.quit_confirmed = true; app.ui.quit = true; } - Some(Choice::Cancel | Choice::Ok) | None => app.quit_prompt = None, + Some(Choice::Cancel | Choice::Ok) | None => { + app.quit_prompt = None; + app.quit_cuts_move = false; + } + } + return; + } + if let Some(text) = app.move_notice.clone() { + let buttons = [("moveNoticeOk", "OK", Choice::Ok)]; + if window(ctx, "move-notice", "Unfinished moves", &text, &buttons, &mut app.notice_input).is_some() { + app.move_notice = None; } return; } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 3a102a29a90..1e9bddfd283 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -51,6 +51,7 @@ mod masking_layout; mod menubar; mod merge_preview; mod model_setup; +mod move_notice; mod offline; mod open_lightroom; pub(super) mod panels; diff --git a/crates/ui-egui/src/tests/folder_drop.rs b/crates/ui-egui/src/tests/folder_drop.rs index b7a51513174..2f12ee48153 100644 --- a/crates/ui-egui/src/tests/folder_drop.rs +++ b/crates/ui-egui/src/tests/folder_drop.rs @@ -1,7 +1,8 @@ //! Photos dragged from the grid onto a Folders row move there on disk: the row lights up, the //! dragged label says where they will go, a closed folder held under the pointer opens, and a -//! release asks first (unless the person said not to), then moves the files (one undo step). -//! Photos that can't go there, or are there already, say so and stay where they are. +//! release asks first (unless the person said not to), then moves the files in the background +//! (one undo step; `move_task`). Photos that can't go there, or are there already, say so and +//! stay where they are. use std::path::{Path, PathBuf}; @@ -109,6 +110,11 @@ fn toast(h: &Headless) -> String { h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default() } +/// Let the background move end, as the frames that follow it do. +fn settle(h: &mut Headless) { + assert!(crate::move_task::wait(&mut h.app, &h.view.ctx, std::time::Duration::from_secs(20)), "the move ended"); +} + #[test] fn photos_dropped_on_a_folder_move_there_on_disk() { let (root, trip, home) = folders("move"); @@ -138,6 +144,7 @@ fn photos_dropped_on_a_folder_move_there_on_disk() { assert!(trip.join("beach.png").is_file(), "not before Move"); h.step(); click(&mut h, "button:dialogOk"); + settle(&mut h); // Then the file moved, the photo follows it, and the toast says Undo moves it back assert!(home.join("beach.png").is_file() && !trip.join("beach.png").exists(), "moved on disk"); let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).unwrap(); @@ -239,6 +246,7 @@ fn photos_that_leave_the_view_leave_the_selection() { release(&mut h, target.center()); h.step(); click(&mut h, "button:dialogOk"); + settle(&mut h); assert!(home.join("beach.png").is_file(), "moved"); // it left trip's view, and the selection with it: a Delete next can't reach it unseen assert!(!h.app.session.selection.contains(lightcraft_catalog::PhotoId(beach)), "{:?}", h.app.session.selection); @@ -315,6 +323,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { // the question, with Don't ask again ticked click(&mut h, "check:moveDontAsk"); click(&mut h, "button:dialogOk"); + settle(&mut h); assert!(home.join("beach.png").is_file()); assert!(!h.app.ui.settings.ask_before_move, "kept in Settings"); // the next drop goes at once @@ -323,6 +332,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { h.step(); let target = folder_row(&h, &home).unwrap(); drop_beach(&mut h, dunes, target); + settle(&mut h); assert!(h.app.ui.dialog.is_none(), "not asked"); assert!(home.join("dunes.png").is_file(), "moved at once"); let _ = std::fs::remove_dir_all(&root); @@ -346,3 +356,140 @@ fn a_question_left_open_while_another_library_opens_moves_nothing() { assert!(trip.join("beach.png").is_file() && !home.join("beach.png").exists(), "nothing moved"); let _ = std::fs::remove_dir_all(&root); } + +#[test] +fn a_background_move_shows_its_progress_and_holds_back_other_moves_until_it_ends() { + let (root, trip, home) = folders("background"); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + let (beach, garden) = (id_of(&h, "beach.png"), id_of(&h, "garden.png")); + // When an agent asks for the move in the background, the call comes back at once + let r = h.app.run("photo.moveToFolder", json!({"ids": [beach], "folder": home.to_string_lossy(), "background": true})).unwrap(); + assert_eq!(r, json!({"background": true, "files": 1})); + // Then the activity stack shows it, with how far it has got and no ✕ (it can't be stopped) + let row = h.app.session.activity.list().into_iter().find(|t| t.kind == "move").expect("a row for the move"); + assert_eq!((row.label.as_str(), row.total, row.cancellable), ("Moving photos", 1, false)); + let inspect = crate::control::inspect(&h.app, &h.view.ctx); + assert_eq!(inspect["move"]["running"]["files"], 1, "{}", inspect["move"]); + // and, until it ends, another move waits for it, and Quit asks first + let e = h.app.run("photo.moveToFolder", json!({"ids": [garden], "folder": trip.to_string_lossy()})).unwrap_err(); + assert!(e.contains("being moved"), "{e}"); + assert_eq!(toast(&h), e, "said where the person sees it: the status line isn't drawn"); + // so is a change that would take the moving photo out of the library, whichever menu or button asked + h.app.ui.toast = None; + h.app.run("library.select", json!({"ids": [beach]})).unwrap(); + let e = h.app.run("photo.deletePermanently", json!({"ids": [beach]})).unwrap_err(); + assert_eq!(e, "1 photo is being moved to another folder: wait for the move to finish"); + assert_eq!(toast(&h), e); + assert!(h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).is_some()); + assert!(!crate::panels::notices::may_close(&mut h.app), "Quit asks while the move runs"); + assert!(format!("{:?}", h.app.quit_prompt).contains("Moving photos"), "{:?}", h.app.quit_prompt); + h.app.quit_prompt = None; + settle(&mut h); + // Once it ends: the file moved, the photo follows, the row is gone and the end is reported + assert!(home.join("beach.png").is_file() && !trip.join("beach.png").exists()); + let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).unwrap(); + assert!(matches!(&photo.source, lightcraft_catalog::Source::File { path } if Path::new(path) == home.join("beach.png"))); + assert!(h.app.session.activity.list().is_empty()); + assert!(toast(&h).starts_with("Moved 1 photo to “home”."), "{}", toast(&h)); + let inspect = crate::control::inspect(&h.app, &h.view.ctx); + assert_eq!(inspect["move"]["running"], serde_json::Value::Null); + assert_eq!(inspect["move"]["last"], json!({"moved": 1, "folder": home.to_string_lossy()})); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_background_move_refused_for_another_running_move_says_so_in_a_toast() { + let (root, trip, home) = folders("background-refused"); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + let (beach, garden) = (id_of(&h, "beach.png"), id_of(&h, "garden.png")); + h.app.run("photo.moveToFolder", json!({"ids": [beach], "folder": home.to_string_lossy(), "background": true})).unwrap(); + // a menu, key or button that asks for the move in the background drops the returned error: the toast is what the person sees + let e = h.app.run("photo.moveToFolder", json!({"ids": [garden], "folder": trip.to_string_lossy(), "background": true})).unwrap_err(); + assert!(e.contains("being moved"), "{e}"); + assert_eq!(toast(&h), e, "said where the person sees it"); + // and it stays up for 6 s of the app clock + h.app.ui.toast = None; + let _ = h.app.run("photo.moveToFolder", json!({"ids": [garden], "folder": trip.to_string_lossy(), "background": true})); + let expires = h.app.ui.toast.as_ref().map(|(_, until, _)| *until).expect("a toast"); + assert!((expires - (h.app.tick_now() + 6.0)).abs() < 1.0, "{expires}"); + settle(&mut h); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_move_started_from_the_grid_or_a_folder_row_that_is_refused_says_so_for_as_long_as_an_error() { + // the Folders rows and the grid's Move to Folder… start a move through `move_task::start` directly + let (root, trip, home) = folders("start-refused"); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + let (beach, garden) = (id_of(&h, "beach.png"), id_of(&h, "garden.png")); + h.app.run("photo.moveToFolder", json!({"ids": [beach], "folder": home.to_string_lossy(), "background": true})).unwrap(); + h.app.ui.toast = None; + let ctx = h.view.ctx.clone(); + let e = crate::move_task::start(&mut h.app, &ctx, &json!({"ids": [garden], "folder": trip.to_string_lossy()})).unwrap_err(); + assert!(e.contains("being moved"), "{e}"); + let (text, until, _) = h.app.ui.toast.clone().expect("the refusal is told"); + assert_eq!(text, e); + assert!(until - h.app.tick_now() > 5.0, "an error stays 6 s, not the 1.4 s of a plain toast: {}", until - h.app.tick_now()); + settle(&mut h); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_move_refused_when_the_question_is_answered_stays_up_as_long_as_an_error() { + let (root, trip, home) = folders("question-refused"); + std::fs::copy(trip.join("beach.png"), trip.join("dunes.png")).unwrap(); + let mut h = app(&[(trip.join("beach.png"), false), (trip.join("dunes.png"), false), (home.join("garden.png"), false)]); + click(&mut h, &format!("libraryFolderToggle:{}", folder_key(&root))); + let target = folder_row(&h, &home).unwrap(); + let (beach, dunes) = (id_of(&h, "beach.png"), id_of(&h, "dunes.png")); + h.app.session.selection = lightcraft_engine::Selection::single(lightcraft_catalog::PhotoId(beach)); + drop_beach(&mut h, beach, target); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::MovePhotos { .. })), "{:?}", h.app.ui.dialog); + // another move starts while the question is up: the answer is refused + // (started on the engine and never run: it holds the library as a move on a worker would) + let _held = lightcraft_engine::move_job::start(&mut h.app.session, &json!({"ids": [dunes], "folder": home.to_string_lossy()})).unwrap(); + h.app.ui.toast = None; + click(&mut h, "button:dialogOk"); + let (text, until, _) = h.app.ui.toast.clone().expect("the refusal is told"); + assert!(text.contains("being moved"), "{text}"); + assert!(until - h.app.tick_now() > 5.0, "an error stays 6 s, not the 1.4 s of a plain toast: {}", until - h.app.tick_now()); + settle(&mut h); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn quit_anyway_quits_while_a_move_without_a_stop_button_runs() { + let (root, _trip, _home) = folders("quit"); + let mut h = app(&[]); + let _stalled = crate::move_task::stalled(&mut h.app); + assert!(!crate::panels::notices::may_close(&mut h.app), "Quit asks while the move runs"); + for _ in 0..3 { + h.step(); + } + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:quitAnyway"), "the prompt is shown"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:quitAnyway"}), std::time::Duration::from_secs(10))["ok"], true); + assert!(h.quit_requested(), "Quit Anyway quits instead of asking again"); + // Cancel keeps working, and the next quit asks again + h.app.ui.quit = false; + h.app.quit_cuts_move = false; + assert!(!crate::panels::notices::may_close(&mut h.app)); + let _ = std::fs::remove_dir_all(&root); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_move_that_finished_as_the_app_exits_is_followed_by_the_library() { + let (root, trip, home) = folders("exit"); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + let beach = id_of(&h, "beach.png"); + h.app.run("photo.moveToFolder", json!({"ids": [beach], "folder": home.to_string_lossy(), "background": true})).unwrap(); + // no frame runs `poll`: wait until the worker has finished (so its result is sent), then the + // exit path gets exactly one look + h.app.move_run.as_mut().unwrap().worker.take().unwrap().join().unwrap(); + assert!(home.join("beach.png").is_file()); + h.app.finish_ready_move(); + let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).unwrap(); + assert!(matches!(&photo.source, lightcraft_catalog::Source::File { path } if Path::new(path) == home.join("beach.png")), "{:?}", photo.source); + assert!(h.app.move_run.is_none()); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/ui-egui/src/tests/move_notice.rs b/crates/ui-egui/src/tests/move_notice.rs new file mode 100644 index 00000000000..47b2efc0f76 --- /dev/null +++ b/crates/ui-egui/src/tests/move_notice.rs @@ -0,0 +1,87 @@ +//! What the app says when the library opens and finds moves an earlier run cut short +//! (`lightcraft_engine::move_intent`): its own window ("Unfinished moves"), not a settings problem. + +use std::time::Duration; + +use lightcraft_engine::move_intent::{MoveProblem, Recovered}; +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::notices::recovered_text; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(30); + +#[test] +fn nothing_to_say_when_nothing_was_left() { + assert_eq!(recovered_text(&Recovered::default()), None); +} + +#[test] +fn the_notice_says_what_was_followed_what_waits_and_what_went_wrong() { + let r = Recovered { + relinked: 2, + waiting: 1, + problems: vec![MoveProblem::BothPlaces { from: "/a/x.jpg".into(), to: "/b/x.jpg".into() }], + ..Default::default() + }; + let text = recovered_text(&r).expect("something to say"); + assert!(text.contains("Photos being moved when LightCraft last closed: 2."), "{text}"); + assert!(text.contains("can't be reached now (a disk not connected?): 1."), "{text}"); + assert!(text.contains("/b/x.jpg was being moved and is now at both places: the library keeps /a/x.jpg."), "{text}"); +} + +#[test] +fn the_notice_tells_removed_copies_and_a_library_left_alone_for_want_of_its_lock() { + let copies = recovered_text(&Recovered { copies_removed: 2, ..Default::default() }).expect("removed copies are told"); + assert!(copies.contains("Copies removed from the new place, because the original was still where the library has it: 2."), "{copies}"); + let alone = recovered_text(&Recovered { problems: vec![MoveProblem::Unprotected], ..Default::default() }).expect("said"); + assert!(alone.contains("open without its lock") && alone.contains("Find Missing Photos"), "{alone}"); +} + +#[test] +fn a_library_that_followed_moves_shows_the_notice_once_and_ok_closes_it() { + let dir = std::env::temp_dir().join(format!("lc-move-notice-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut session = lightcraft_engine::Session::new(); + session.open_library(&dir, false).unwrap(); + session.library.as_mut().unwrap().recovered_moves = Some(Recovered { relinked: 3, ..Default::default() }); + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for _ in 0..4 { + h.step(); + } + let notice = h.app.move_notice.clone().expect("the notice is taken from the library"); + assert!(notice.contains("Photos being moved when LightCraft last closed: 3."), "{notice}"); + assert_eq!(crate::control::inspect(&h.app, &h.view.ctx)["moveNotice"], json!(notice)); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:moveNoticeOk"), "the window has its OK"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:moveNoticeOk"}), T)["ok"], true); + for _ in 0..3 { + h.step(); + } + assert_eq!(h.app.move_notice, None); + assert!(h.app.session.take_recovered_moves().is_none(), "said once"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_notice_of_a_library_does_not_outlive_a_switch_to_another() { + let dir = std::env::temp_dir().join(format!("lc-move-notice-switch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (first, second) = (dir.join("first"), dir.join("second")); + let mut other = lightcraft_engine::Session::new(); + other.open_library(&second, false).unwrap(); + drop(other); + let mut session = lightcraft_engine::Session::new(); + session.open_library(&first, false).unwrap(); + session.library.as_mut().unwrap().recovered_moves = Some(Recovered { relinked: 3, ..Default::default() }); + let app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for _ in 0..4 { + h.step(); + } + assert!(h.app.move_notice.is_some(), "the first library's notice is up"); + crate::panels::settings::open_library(&mut h.app, &json!({"path": second.to_string_lossy()})).expect("the switch goes through"); + assert_eq!(h.app.move_notice, None, "it said something about the library that was left"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 0c9281dfc22..4f95985e5e2 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -32,7 +32,7 @@ guard.detail(&file_name); `SyncRun`…), or move it into the worker thread. Dropping it removes the row, also when the worker panics, so a dead job never leaves a stuck bar. A worker that only reports progress takes a `TaskHandle` (`guard.handle()`, `Clone + Send`). -- **`kind`** is a stable camelCase id that agents filter by (`export`, `import`, `scan`, `sync`, `previews`, +- **`kind`** is a stable camelCase id that agents filter by (`export`, `import`, `scan`, `sync`, `move`, `previews`, `download`, `faces`, `cache`, `focus`…). **`label`** is a short English name in sentence case ("Building previews"). The stack shows it translated, so add it to every catalog in `crates/ui-egui/locales/`. - **Progress:** `progress(done, total)`. A `total` of 0 means the amount of work isn't known yet, and the bar sweeps. @@ -44,7 +44,9 @@ guard.detail(&file_name); - `Cancel::Flag(Arc)` adopts the flag the job already checks. The row's ✕, `activity.cancel` and the job's own Cancel then all set the same atomic. - `Cancel::Yes`: the job polls `guard.is_cancelled()` itself. - - `Cancel::No`: the job can't stop; it gets no ✕ and doesn't make Quit ask. + - `Cancel::No`: the job can't stop; it gets no ✕ and doesn't make Quit ask. The one exception is the move to another + folder: it has no ✕, but quitting cuts it short, so Quit asks first + (`crates/ui-egui/src/panels/notices.rs`, `may_close`). - `set_cancellable(false)` for a phase that has to finish once started (a Lightroom import adding its photos). - **Quiet periodic work** shows no row: the auto-import folder listing runs every few seconds through `tasks::spawn(.., None, ..)`. @@ -62,6 +64,7 @@ guard.detail(&file_name); | Find Missing Photos | `crates/ui-egui/src/tasks.rs` | a generic background task with a row (`kind: Some(..)`) | | Reload from Disk | `crates/ui-egui/src/reload.rs`, `crates/engine/src/cmd/reload.rs` | a command split into plan / probe / apply so the app reads the files on a worker thread (`tasks::spawn_tracked`: progress and `Cancel::Flag`); the result is committed through `Session::execute_fn` (undo step, save, XMP auto-write), and dropped for a photo a later-started reload has already updated; `wait: true` runs it in place | | Reading focus points | `crates/engine/src/focus_scan.rs` | a worker paced by the UI's per-frame pump (`focus.pump {pace}`); `Cancel::Flag`; commits in batches without undo steps | +| Moving photos to another folder | `crates/engine/src/move_job.rs`, `crates/ui-egui/src/move_task.rs` | split a job into a session half (plan, row, finish) and a `Send` worker half; the library follows the files once the worker is done; hold back conflicting commands while it runs; a record on disk so a force-quit part-way is followed at the next open (`crates/engine/src/move_intent.rs`) | ## Testing diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 36294c78756..fd60b6690de 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`), `moveNotice` (what the open found of moves an earlier run cut short, shown once in the "Unfinished moves" window; OK = `button:moveNoticeOk`), `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.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,6 +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: "photo.moveToFolder", params}` | `{folder, ids?, background?}` | Moves the photos' files (default: the selection) and their XMP sidecars into `folder` on disk, as one undo step → `{moved, folder}`. With `background: true` (what a drop on a Folders row and the menus use) it returns `{background: true, files}` at once (`{moved: 0, folder}`, as without it, when every photo is there already) and the files move on a worker thread: `activity.list` shows it (kind `move`, how many files have moved and the one in hand), and `ui.inspect` → `move` has `running` (`{folder, files, task}`) and `last` (the result, or `{error, folder}`). While it runs, other file moves, an Undo or Redo that moves files and opening another library are refused, and so is anything that would take a moving photo out of the library or point it at another file: `photo.deletePermanently`, `library.emptyRecentlyDeleted`, an import that replaces a trashed photo (`onDeleted: fresh`), `photo.convertToDng`, `library.findMissing`, `photo.relink`, a Synchronize Folder relink, and the Undo or Redo of such a step. The error says how many of the photos are moving (`3 photos are being moved to another folder: wait for the move to finish`) and nothing is changed: the rest of a batch isn't done either. A record of the move in the library lets the next open follow one cut short (a force-quit or a crash): `library.info` → `recoveredMoves` says what it did (`{relinked, copiesRemoved, waiting, problems}`, or `null`), and `ui.inspect` → `moveNotice` is the text of the "Unfinished moves" window until OK is pressed | | `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 | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..03cf29298e1 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (LRC-LIB-LIBFOLDERS: a move cut short is followed at the next open; earlier: LRC-LIB-LIBFOLDERS, LR-LIB-RENAME: a move to another folder, a rename or an Undo / Redo that moves files writes a record in the library first; earlier: LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: moves to another folder run in the background; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -461,7 +461,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos, Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) and moves to another folder 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, or while photos move to another folder (that move has no ✕, but quitting cuts it short); agents and `ui.inspect` (`activity`) see the same list. 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) | @@ -703,7 +703,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | -| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | +| LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; the files move on a worker thread, shown in the activity stack (“Moving photos”, k of N, the file in hand); while it runs, other file moves, an Undo or Redo that moves files and opening another library are refused with a message until it ends, and so is anything that would take a moving photo out of the library or point it at another file (Delete Permanently, Empty Recently Deleted, an import that replaces a trashed photo, Convert to DNG, Find Missing Photos, Locate, a Synchronize relink and the undo of those steps; the message says how many photos are moving and nothing is changed), and the moving photos' XMP sidecars are written once they arrive, at the new place; a record in the library (`moves/`, written before the first file moves) lets the next open follow a move cut short by a force-quit or a crash: photos whose file arrived point there and their sidecars follow, a copy that arrived while the original stayed is removed when it is the same file or the same bytes, and a move whose old place can't be reached (a disk not connected?) waits for the next open; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); a name clash on moving photos is refused rather than renamed -1, -2; Undo and Redo of a move still run on the UI thread (no progress); a move under way can't be stopped, and quitting while one runs (Quit Anyway, after the prompt) cuts it short, which the next open follows (a file half copied to another disk leaves a hidden `.lc-partial` file there until that open removes it; in a library opened without its lock, because its file system can't lock it, no record is followed or touched, since another program may be making the move); folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) | | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/dialogs/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 47 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/widgets/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/widgets/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents | | LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | | @@ -959,3 +959,6 @@ 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 | LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: photos moved to another folder (`photo.moveToFolder`, a drop on a Folders row, Move Selected Photos Here, Move to Folder…) move on a worker thread with a row in the activity stack that shows how many files have moved; one undo step; other file moves and opening another library wait for it, as do Delete Permanently, Empty Recently Deleted, Convert to DNG, Find Missing Photos, Locate and the other changes that would take a moving photo out of the library or point it at another file (the message says how many photos are moving); Quit asks first, as the move has no ✕ but quitting cuts it short; the moving photos' XMP sidecars are written once they arrive. LRC-LIB-LIBFOLDERS drops its stale "photos can't yet be dragged onto a folder row" limit; statuses unchanged (✅) | +| 2026-10-26 | patch | LRC-LIB-LIBFOLDERS, LR-LIB-RENAME: a move to another folder, a rename and an Undo / Redo that moves files write a record into the library folder (`moves/`) before the first file moves, and remove it once the library has saved where the files went (kept while a save is failing or the library couldn't follow); nothing reads a record yet, so a move cut short leaves it in place for a later part; statuses unchanged (✅) | +| 2026-10-26 | minor | LRC-LIB-LIBFOLDERS: a record in the library, written before the first file of a move to another folder, a rename or an Undo / Redo that moves files moves, lets the next open follow a move cut short by a force-quit or a crash: photos whose file arrived point there (one undo step) and their sidecars follow, a copy that arrived while the original stayed is removed when it is the same file or holds the same bytes, and an "Unfinished moves" window says what was found; edits held back during a move reach their sidecars then too; statuses unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..554676152dc 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,17 @@ # What's new in LightCraft +## 2026-10-26 + +### A move cut short is followed at the next open +- If LightCraft is force-quit or crashes part-way through a move, or you choose Quit Anyway, the next time the + library opens, the photos whose files reached the new folder point there (their sidecars follow), the others stay, + and an "Unfinished moves" window says what was found. Edits made while the files were moving reach their XMP + sidecars then too. A file that was half copied to another disk leaves a hidden `.lc-partial` file in the new folder, + which that open removes; a copy that reached the new folder while the original stayed is removed only when it is the + same file or holds the same bytes. In a library that was opened without its lock (some network shares can't lock + it), nothing is followed or removed, because another program may be making the move: use File ▸ Find Missing + Photos… to relink files that moved. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock @@ -104,6 +116,18 @@ ## 2026-10-21 +### Moving photos to a NAS no longer freezes the window +- Moving photos to another folder (dropping them on a Folders row, Move Selected Photos Here, Move to Folder…) now + runs in the background. The activity stack shows "Moving photos" with how many have moved and the file in hand, + and a toast says how it ended. The photos move as one step Edit ▸ Undo takes back. +- While a move runs, editing, rating and keywording go on as usual; the moving photos' XMP sidecars are written once + they arrive. Another move, a rename, Undo or Redo of a file move and opening another library are refused until it + ends, and so is anything that would take a moving photo out of the library or point it at another file: Delete + Permanently, Empty Recently Deleted, importing a file again as a new photo over its trashed record, Convert to DNG, + Find Missing Photos, Locate and the Undo of those steps. A message pops up saying how many photos are moving, and + nothing is changed; try again once the move is done. +- Quitting while photos are moving asks first. + ### Settings window - Settings is one size on every tab and stays where it is as you go through them; before, each tab made its own size and the tabs moved under the pointer. The tabs stay in place while a long page scrolls (in a very short