Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
baea7d8
LRC-LIB-LIBFOLDERS: photos move to another folder in the background
nledford Oct 21, 2026
8cecad5
LRC-LIB-LIBFOLDERS: a move whose library changed says the files moved…
nledford Oct 21, 2026
40b9885
LRC-LIB-LIBFOLDERS: a move that finished as the app exits is followed…
nledford Oct 21, 2026
109ec64
LRC-LIB-LIBFOLDERS: the exit test waits for the worker, then looks once
nledford Oct 21, 2026
010911d
LRC-LIB-LIBFOLDERS: the test-only worker handle is not built for wasm32
nledford Oct 21, 2026
a1e6b8d
LRC-LIB-LIBFOLDERS: a library opened while photos move is refused bef…
nledford Oct 22, 2026
76e662a
LRC-LIB-LIBFOLDERS: undoing the import or a relink of a photo that is…
nledford Oct 25, 2026
ae63674
LRC-LIB-LIBFOLDERS: while photos move, nothing may take them out of t…
nledford Oct 25, 2026
cfa81a4
LRC-LIB-LIBFOLDERS: a background move that is refused says why in a t…
nledford Oct 25, 2026
06a5346
LRC-LIB-LIBFOLDERS: every refused background move is told in an error…
nledford Oct 25, 2026
4a723f4
LRC-LIB-LIBFOLDERS: planning a move looks up a photo already moving i…
nledford Oct 26, 2026
099ee8d
LRC-LIB-LIBFOLDERS: the background move's poll is named by its path w…
nledford Oct 28, 2026
45195eb
LRC-LIB-LIBFOLDERS: a move writes a record in the library before the …
nledford Oct 26, 2026
84c693f
LRC-LIB-LIBFOLDERS: a move cut short by a force-quit or a crash is fo…
nledford Oct 26, 2026
7150411
LRC-LIB-LIBFOLDERS: an "Unfinished moves" window says what the next o…
nledford Oct 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions apps/lightcraft-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
70 changes: 10 additions & 60 deletions crates/engine/src/cmd/browse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
Expand Down Expand Up @@ -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())
}

Expand Down Expand Up @@ -417,65 +417,14 @@ fn create_folder(s: &mut Session, p: &Value) -> Result<Value> {

/// `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<Value> {
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<crate::rename::RenamePlan> = Vec::new();
let mut taken: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut clashes: Vec<String> = 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.
Expand Down Expand Up @@ -510,6 +459,7 @@ fn follow_library_folder(chosen: &mut Option<String>, 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<usize, String> {
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"));
Expand Down
38 changes: 26 additions & 12 deletions crates/engine/src/cmd/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Value> {
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<PhotoId> = 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();
Expand All @@ -69,17 +92,8 @@ fn convert(s: &mut Session, p: &Value) -> Result<Value> {
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);
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/library/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,8 @@ pub fn specs() -> Vec<CommandSpec> {
"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),
Expand Down
4 changes: 4 additions & 0 deletions crates/engine/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
}
Expand Down
55 changes: 49 additions & 6 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}")]
Expand Down Expand Up @@ -331,6 +338,18 @@ pub struct Session {
pub library: Option<library::Library>,
/// 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<move_job::MoveTicket>,
/// Records of file moves now in the catalog ([`move_intent`]), removed once it is saved.
pub(crate) settled_moves: Vec<std::path::PathBuf>,
/// 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<PhotoId>,
/// 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<PhotoId>,
/// 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.
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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()
{
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand All @@ -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)
}
Expand Down
Loading
Loading