diff --git a/Cargo.lock b/Cargo.lock index bc85e8b972..10e96f9be1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4389,6 +4389,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 8a31d6b20c..7ada442531 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -451,7 +451,7 @@ async fn boot(opts: Options, bridge: Option) -> Boot { if !granted { notice( "This browser may delete LightCraft's library when it runs short of space (persistent storage wasn't granted). \ - Keep your original photos elsewhere and use File ▸ Back Up Library… now and then.", + Keep your original photos elsewhere and use File → Back Up Library… now and then.", ); } }); @@ -587,7 +587,7 @@ impl WebApp { if backend.is_some() { notice( "LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \ - elsewhere and back up with File ▸ Back Up Library….", + elsewhere and back up with File → Back Up Library….", ); } // previews are large (≤ 2560 px, f32): keep few in a 32-bit address space diff --git a/apps/lightcraft-web/src/workers.rs b/apps/lightcraft-web/src/workers.rs index 56f7abea4a..40f6252068 100644 --- a/apps/lightcraft-web/src/workers.rs +++ b/apps/lightcraft-web/src/workers.rs @@ -319,6 +319,7 @@ impl Workers { quick: None, display: None, frame: None, + slide_photo: None, }; g.done.push((b.slot, r, 0.0)); } @@ -390,8 +391,10 @@ impl Workers { }); } g.remote_done += 1; + let mut slide_photo = None; let rendered = match (rendered, &b.slide) { (Ok(mut r), Some(slide)) => { + slide_photo = Some([r.image.width, r.image.height]); r.image = slide.compose(&r.image); Ok(r) } @@ -411,6 +414,7 @@ impl Workers { quick: None, display: None, frame: None, + slide_photo, }, ms, )); @@ -466,6 +470,7 @@ impl RenderOffload for Workers { quick: None, display: None, frame: None, + slide_photo: None, }; g.done.push((slot, r, 0.0)); return None; diff --git a/apps/lightcraft/src/editors.rs b/apps/lightcraft/src/editors.rs index 3ca748f473..87f2cb6144 100644 --- a/apps/lightcraft/src/editors.rs +++ b/apps/lightcraft/src/editors.rs @@ -120,7 +120,7 @@ fn launcher(app: &str) -> Result { return Ok(if cfg!(target_os = "macos") { Launcher::MacApp(app.to_string()) } else { Launcher::Program(PathBuf::from(app)) }); } find_photocraft().ok_or_else(|| { - "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings ▸ External Editing.".to_string() + "PhotoCraft isn't installed. Get it from getartcraft.com/apps/photocraft, or give where it is in Settings → External Editing.".to_string() }) } diff --git a/apps/lightcraft/src/gpu_crash.rs b/apps/lightcraft/src/gpu_crash.rs index 3b74223151..fe13a26650 100644 --- a/apps/lightcraft/src/gpu_crash.rs +++ b/apps/lightcraft/src/gpu_crash.rs @@ -51,7 +51,7 @@ pub(crate) fn gpu_crash_check_at(marker: Option, in_memory: pub(crate) fn gpu_crash_notice(what: &str) -> String { format!( "LightCraft closed unexpectedly while starting the GPU last time ({what}), so GPU rendering is now off and photos render on the CPU. \ - To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; to try another graphics backend, start LightCraft with \ + To try the GPU again, turn on Settings → Performance → Use the GPU for rendering; to try another graphics backend, start LightCraft with \ LIGHTCRAFT_GPU_BACKEND=dx12, vulkan or off (see docs/gpu-pipeline.md → Troubleshooting)." ) } @@ -90,7 +90,7 @@ pub(crate) fn gpu_lost_check_at(marker: Option<&std::path::Path>, in_memory: boo } Some(format!( "LightCraft stopped last time after the graphics driver reset the GPU ({}) while photos rendered on it, so GPU rendering \ - is now off and photos render on the CPU. To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; \ + is now off and photos render on the CPU. To try the GPU again, turn on Settings → Performance → Use the GPU for rendering; \ an up-to-date graphics driver may help.", reason.trim() )) diff --git a/apps/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index 2a4d86c237..953ca43eb9 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -77,7 +77,7 @@ pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, Some(LaunchPath::Refused { path, why }) => { log::warn!("not importing {path} given at launch: {why}"); notices - .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File ▸ Import Photos…")); + .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File → Import Photos…")); } None => {} } @@ -126,7 +126,7 @@ pub(crate) fn stopped_text(error: &str, lost: Option<&str>) -> String { match lost { Some(reason) => format!( "{error}. The graphics driver reset the GPU ({reason}). LightCraft renders on the CPU from its next start; \ - Settings ▸ Performance ▸ Use the GPU for rendering turns the GPU back on" + Settings → Performance → Use the GPU for rendering turns the GPU back on" ), None => error.to_string(), } diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 0eb126c40f..470b00bbd9 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -409,7 +409,7 @@ fn create_folder(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("{path} already exists: choose another name"))); } folder_on_disk("", &path).map_err(|e| bad(C, e))?; - let undo = crate::FolderMove { from: path.clone(), to: String::new() }; + let undo = crate::FolderMove { from: path.clone(), to: String::new(), on_disk: true }; if let Err(e) = s.commit_with_folder(&format!("Create Folder “{name}”"), Op::Batch { ops: vec![] }, undo) { let _ = remove_empty_folder(&path); return Err(e); @@ -555,7 +555,7 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: let name = Path::new(to).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let renamed = src.parent() == dst.parent(); let label = if renamed { format!("Rename Folder to “{name}”") } else { format!("Move Folder “{name}”") }; - let folder = crate::FolderMove { from: to.to_string(), to: from.to_string() }; + let folder = crate::FolderMove { from: to.to_string(), to: from.to_string(), on_disk: true }; if let Err(e) = s.commit_with_folder(&label, Op::Batch { ops }, folder) { // the catalog didn't take it: put the folder back where the photos still point let back = rename_folder_on_disk(to, from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default(); diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index c847852261..664683a513 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -1,7 +1,7 @@ //! Assisted culling: score photos for focus and clipping, group similar shots taken close //! together (bursts) and mark the sharpest of each group; optionally reject blurry ones and pick -//! each group's best. Scores are kept on the photos (rules / smart albums: `sharpness`, -//! `bestOfGroup`). +//! each group's best, and stack each burst with its best photo on top. Scores are kept on the +//! photos (rules / smart albums: `sharpness`, `bestOfGroup`). use lightcraft_catalog::{Analysis, Flag, Op, PhotoId}; use serde_json::{Value, json}; @@ -29,6 +29,10 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); let (gap, same) = burst_params(p)?; + let stack_groups = match p.get("stackGroups") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + }; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -83,10 +87,53 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); } + let mut stacks = 0; + if stack_groups { + // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked + // from its other photos when two or more remain, with the sharpest of those on top. + let index = s.catalog.stack_index(); + let mut members: std::collections::BTreeMap> = Default::default(); + for (i, g) in group_of.iter().enumerate() { + if let (Some(g), Some(r)) = (g, rows.get(i)) + && !index.contains_key(&r.0) + && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) + { + members.entry(*g).or_default().push((r.0, r.2)); + } + } + for group in members.values() { + let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { + continue; + }; + let photos: Vec = group.iter().map(|m| m.0).collect(); + if photos.len() >= 2 + && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + { + ops.push(op); + stacks += 1; + } + } + } if !ops.is_empty() { s.commit("Assisted Culling", Op::Batch { ops })?; } - Ok(json!({"photos": out, "groups": best.len(), "rejected": rejected, "picked": picked, "failed": failed})) + if stacks > 0 { + // a photo now hidden inside a collapsed stack must not stay the active one: its stack's + // top takes over, and the rest of the selection (what was culled) stays selected + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); + } + } + Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -121,7 +168,7 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", always, analyze ), diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 711bebb102..611a841033 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -313,7 +313,7 @@ pub fn specs() -> Vec { "Face Models on the GPU", [], None, - "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings ▸ Faces), `false` checks the GPU again", + "{cpuOnly?: bool} → {cpuOnly, detection, recognition}: where the face models run, each as {checking, device, why} (null until it is loaded). The GPU is used only after a background check shows it gives the CPU's results faster; `cpuOnly: true` keeps every face model on the CPU (Settings → Faces), `false` checks the GPU again", always, gpu ), diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rs index 1ea39d04c1..dc7bbe0ee0 100644 --- a/crates/engine/src/cmd/face_models.rs +++ b/crates/engine/src/cmd/face_models.rs @@ -511,7 +511,7 @@ fn enable(s: &mut Session, p: &Value) -> Result { let usable = st.embedder.as_deref().is_some_and(|id| installed_models(&dir).iter().any(|i| i.manifest.id == id && i.manifest.role == Role::Embedder)); if on && !usable { - return Err(bad(C, "choose a recognition model first (Settings ▸ Faces ▸ Use)")); + return Err(bad(C, "choose a recognition model first (Settings → Faces → Use)")); } st.enabled = on; write_settings(&dir, &st)?; diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index d811f80209..8d36dcd750 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -145,7 +145,7 @@ fn reverse(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "none of these photos has a GPS position")); } let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo ▸ Download Place Names)")))?; + let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Download Place Names)")))?; // a large selection shows in the activity stack and can be stopped let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes)); let mut ops = Vec::new(); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4bf9654250..81073eac14 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -15,6 +15,7 @@ mod specs; pub(crate) use filters::covers_other_disks; pub use import::{ImportRequest, import_batch_done, import_params, list_auto_import_folder}; +pub(crate) use selection::select_after_deletion; pub use specs::specs; #[cfg(test)] diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index c52ead86d0..99d065b2b7 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -92,6 +92,8 @@ pub fn import_params(s: &Session, p: &Value) -> Result { metadata_preset, convert_dng: bool_or(p, "dng", false), local: bool_or(p, "local", false), + // (only the Lightroom import makes records of duplicates) + read_duplicates: false, recipe: crate::cmd::recipe_param(p, "library.import")?, }; let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); diff --git a/crates/engine/src/cmd/library/selection.rs b/crates/engine/src/cmd/library/selection.rs index 40130adb9d..034466d150 100644 --- a/crates/engine/src/cmd/library/selection.rs +++ b/crates/engine/src/cmd/library/selection.rs @@ -3,7 +3,7 @@ use super::{AlbumId, Flag, Op, PhotoId, Result, Selection, Session, Value, bad, /// The selection after photos left the view (deleted, or rated, flagged or labelled out of it). /// Its callers end an open edit (a slider drag) before their own change, as moving to the next /// photo does, so it is its own undo step and comes first. -pub(super) fn select_after_deletion(s: &mut Session, before: &[PhotoId]) { +pub(crate) fn select_after_deletion(s: &mut Session, before: &[PhotoId]) { let at = before.iter().position(|id| Some(*id) == s.selection.active); let remaining: std::collections::HashSet<_> = s.visible_cloned().into_iter().collect(); s.selection.ids.retain(|id| remaining.contains(id)); diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 0c77d709cd..c9d1ea78d1 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -156,13 +156,13 @@ fn relink(s: &mut Session, p: &Value) -> Result { } /// The stored content hash of a photo, without the `:dupN` suffix duplicates get. -fn stored_hash(p: &Photo) -> Option<&str> { +pub(crate) fn stored_hash(p: &Photo) -> Option<&str> { p.content_hash.as_deref().map(|h| h.split(':').next().unwrap_or(h)).filter(|h| !h.is_empty()) } /// The content hash of the file at `path` (as import computes it), if it can be read. Read in /// pieces: the file is whatever is on the disk, of any size. -fn file_hash(path: &str) -> Option { +pub(crate) fn file_hash(path: &str) -> Option { use std::io::Read; // the opened file must be regular (a FIFO or device would never end), and no more than its size at open is read let file = std::fs::File::open(path).ok()?; @@ -171,7 +171,7 @@ fn file_hash(path: &str) -> Option { } /// The content hash of what `r` gives, read in pieces (the hash import computes of the whole). -fn hash_reader(mut r: impl std::io::Read) -> Option { +pub(crate) fn hash_reader(mut r: impl std::io::Read) -> Option { let mut hasher = lightcraft_preview::Hasher128::new(); let mut piece = vec![0u8; 1 << 16]; loop { diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 51f094866e..a382cb774a 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -8,12 +8,15 @@ //! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset` //! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear` //! * `print.exportPdf {path, ids?}` -//! * `print.template.list|save|apply|delete`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.list|save|apply|delete|move`, `print.template.export|import` (`.lcprint` files) +//! * `print.template.folder.create|rename|delete`: the Template Browser's folders use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, f64_req}; use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size}; -use crate::print::template::{FILE_EXT, MAX_FILE, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name, unique_name}; +use crate::print::template::{ + DEFAULT_FOLDER, FILE_EXT, MAX_FILE, MAX_FOLDERS, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_folder, clean_name, sort_folders, unique_name, +}; use crate::{Result, Session}; fn rect_json(r: &Rect) -> Value { @@ -270,18 +273,65 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { // ---- templates ------------------------------------------------------------------------------ fn template_list(s: &Session) -> Value { - json!({"templates": s.print_templates.iter().map(|t| json!({"name": t.name, "style": t.settings.pointer("/layout/style"), "settings": t.settings})).collect::>()}) + let count = |f: Option<&str>| s.print_templates.iter().filter(|t| t.folder.as_deref() == f).count(); + let folders = std::iter::once(json!({"name": DEFAULT_FOLDER, "default": true, "templates": count(None)})) + .chain(s.print_template_folders.iter().map(|f| json!({"name": f, "default": false, "templates": count(Some(f))}))); + json!({ + "folders": folders.collect::>(), + "templates": s.print_templates.iter().map(|t| json!({ + "name": t.name, + "folder": t.folder.as_deref().unwrap_or(DEFAULT_FOLDER), + "style": t.settings.pointer("/layout/style"), + "settings": t.settings, + })).collect::>(), + }) } fn template_name(p: &Value, id: &str) -> Result { clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e)) } -/// Save the preferences after a change to the templates; if that fails, the templates go back to -/// `before`, so the list matches what is saved and a retry does the same thing. -fn save_templates(s: &mut Session, before: Vec) -> Result<()> { +/// The folder `name` names: `None` for [`DEFAULT_FOLDER`], else the listed folder's spelling. +fn find_folder(s: &Session, name: &str, id: &str) -> Result> { + let name = name.trim(); + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Ok(None); + } + s.print_template_folders + .iter() + .find(|f| f.eq_ignore_ascii_case(name)) + .cloned() + .map(Some) + .ok_or_else(|| bad(id, format!("no print template folder `{name}` (see print.template.list)"))) +} + +/// The `folder` parameter: not given (`None`), or the folder it names (see [`find_folder`]). +fn folder_param(s: &Session, p: &Value, id: &str) -> Result>> { + match p.get("folder") { + None => Ok(None), + Some(Value::String(f)) => find_folder(s, f, id).map(Some), + Some(_) => Err(bad(id, "`folder` must be a folder name")), + } +} + +/// A user folder named by `key`: the listed folder's spelling. [`DEFAULT_FOLDER`] is refused. +fn user_folder(s: &Session, p: &Value, key: &str, id: &str) -> Result { + let name = p.get(key).and_then(Value::as_str).ok_or_else(|| bad(id, format!("missing `{key}`")))?; + find_folder(s, name, id)?.ok_or_else(|| bad(id, format!("“{DEFAULT_FOLDER}” can't be renamed or deleted"))) +} + +/// The templates and folders before a change, put back by [`save_templates`] when it fails. +type Before = (Vec, Vec); + +fn before(s: &Session) -> Before { + (s.print_templates.clone(), s.print_template_folders.clone()) +} + +/// Save the preferences after a change to the templates or folders; if that fails, both go back +/// to `before`, so the list matches what is saved and a retry does the same thing. +fn save_templates(s: &mut Session, before: Before) -> Result<()> { if let Err(e) = s.save_prefs() { - s.print_templates = before; + (s.print_templates, s.print_template_folders) = before; return Err(e); } Ok(()) @@ -290,14 +340,20 @@ fn save_templates(s: &mut Session, before: Vec) -> Result<()> { fn template_save(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.save"; let name = template_name(p, ID)?; - let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; - let before = s.print_templates.clone(); + let folder = folder_param(s, p, ID)?; + let mut t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?; + let before = before(s); match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) { - Some(x) => *x = t, + Some(x) => { + // a replaced template stays in its folder unless the call names another + t.folder = folder.unwrap_or_else(|| x.folder.clone()); + *x = t; + } None => { if s.print_templates.len() >= MAX_TEMPLATES { return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first"))); } + t.folder = folder.flatten(); s.print_templates.push(t); } } @@ -305,6 +361,95 @@ fn template_save(s: &mut Session, p: &Value) -> Result { Ok(template_list(s)) } +fn template_move(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.move"; + let name = template_name(p, ID)?; + let folder = folder_param(s, p, ID)?.ok_or_else(|| bad(ID, "missing `folder`"))?; + let i = s + .print_templates + .iter() + .position(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?; + let moved = s.print_templates.get(i).is_some_and(|t| t.folder != folder); + if moved { + let before = before(s); + if let Some(t) = s.print_templates.get_mut(i) { + t.folder = folder; + } + save_templates(s, before)?; + } + let mut out = template_list(s); + out["moved"] = json!(moved); + Ok(out) +} + +fn folder_create(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.create"; + let name = clean_folder(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `name`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&name)) { + return Err(bad(ID, format!("there is already a folder named “{name}”"))); + } + if s.print_template_folders.len() >= MAX_FOLDERS { + return Err(bad(ID, format!("at most {MAX_FOLDERS} folders; delete one first"))); + } + let before = before(s); + s.print_template_folders.push(name.clone()); + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(name); + Ok(out) +} + +fn folder_rename(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.rename"; + let from = user_folder(s, p, "name", ID)?; + let to = clean_folder(p.get("to").and_then(Value::as_str).ok_or_else(|| bad(ID, "missing `to`"))?).map_err(|e| bad(ID, e))?; + if s.print_template_folders.iter().any(|f| f.eq_ignore_ascii_case(&to) && *f != from) { + return Err(bad(ID, format!("there is already a folder named “{to}”"))); + } + if to == from { + let mut out = template_list(s); + out["name"] = json!(to); + return Ok(out); + } + let before = before(s); + for f in &mut s.print_template_folders { + if *f == from { + f.clone_from(&to); + } + } + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(from.as_str()) { + t.folder = Some(to.clone()); + } + } + sort_folders(&mut s.print_template_folders); + save_templates(s, before)?; + let mut out = template_list(s); + out["name"] = json!(to); + Ok(out) +} + +fn folder_delete(s: &mut Session, p: &Value) -> Result { + const ID: &str = "print.template.folder.delete"; + let name = user_folder(s, p, "name", ID)?; + let before = before(s); + s.print_template_folders.retain(|f| *f != name); + let mut moved = 0usize; + for t in &mut s.print_templates { + if t.folder.as_deref() == Some(name.as_str()) { + t.folder = None; + moved += 1; + } + } + save_templates(s, before)?; + let mut out = template_list(s); + out["deleted"] = json!(name); + out["moved"] = json!(moved); + Ok(out) +} + fn template_apply(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.apply"; let name = template_name(p, ID)?; @@ -320,9 +465,9 @@ fn template_apply(s: &mut Session, p: &Value) -> Result { fn template_delete(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.delete"; let name = template_name(p, ID)?; - let before = s.print_templates.clone(); + let before = before(s); s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name)); - if s.print_templates.len() == before.len() { + if s.print_templates.len() == before.0.len() { return Err(bad(ID, format!("no print template `{name}`"))); } save_templates(s, before)?; @@ -356,6 +501,7 @@ fn template_export(s: &mut Session, p: &Value) -> Result { fn template_import(s: &mut Session, p: &Value) -> Result { const ID: &str = "print.template.import"; let path = std::path::Path::new(template_path(p, ID)?); + let folder = folder_param(s, p, ID)?.flatten(); let meta = std::fs::metadata(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?; if !meta.is_file() { return Err(bad(ID, format!("{}: not a file", path.display()))); @@ -371,7 +517,8 @@ fn template_import(s: &mut Session, p: &Value) -> Result { let name = unique_name(&t.name, &s.print_templates); let renamed = name != t.name; t.name = name.clone(); - let before = s.print_templates.clone(); + t.folder = folder; + let before = before(s); s.print_templates.push(t); save_templates(s, before)?; let mut out = template_list(s); @@ -405,17 +552,31 @@ pub fn specs() -> Vec { cmd!(query "print.exportPdf", "Print to PDF", [], None, "{path, ids?: photo ids (default selection)} → {path, pages, photos, bytes}; prints the current print.get settings; replaces an existing output, never an original", always, export_pdf), - cmd!(query "print.template.list", "Print Templates", [], None, "{} → {templates: [{name, style, settings}]}", always, |s, _| Ok(template_list(s))), + cmd!(query "print.template.list", "Print Templates", [], None, + "{} → {folders: [{name, default, templates: count}] (\"User Templates\" first, then the others by name), templates: [{name, folder, style, settings}]}", + always, |s, _| Ok(template_list(s))), cmd!(query "print.template.save", "Save Print Template", [], None, - "{name} — saves the layout, image settings, page and job (not the cells' photos or the guides); an existing name (any case) is replaced → print.template.list", + "{name, folder?}: saves the layout, image settings, page and job (not the cells' photos or the guides) in `folder` (default \"User Templates\"); an existing name (any case) is replaced and stays in its folder unless `folder` is given → print.template.list", always, template_save), cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply), cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete), + cmd!(query "print.template.move", "Move Print Template to Folder", [], None, + "{name, folder}: lists the template in another Template Browser folder (\"User Templates\" or one made with print.template.folder.create); its name and settings stay → print.template.list + {moved: false when it was already there}", + always, template_move), + cmd!(query "print.template.folder.create", "New Print Template Folder", [], None, + "{name}: a Template Browser folder (1 to 80 characters without control characters, not \"User Templates\", unique ignoring ASCII case, at most 100); the name is a label, not a path, so `/` and `\\` are kept as typed; kept while empty → print.template.list + {name}", + always, folder_create), + cmd!(query "print.template.folder.rename", "Rename Print Template Folder", [], None, + "{name, to}: renames a folder and keeps its templates in it; \"User Templates\" can't be renamed → print.template.list + {name}", + always, folder_rename), + cmd!(query "print.template.folder.delete", "Delete Print Template Folder", [], None, + "{name}: deletes a folder; its templates move to \"User Templates\", which can't be deleted → print.template.list + {deleted, moved: templates moved}", + always, folder_delete), cmd!(query "print.template.export", "Export Print Template", [], None, - "{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}", + "{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}, without the template's folder; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}", always, template_export), cmd!(query "print.template.import", "Import Print Template", [], None, - "{path: a .lcprint file (at most 256 KB)}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", + "{path: a .lcprint file (at most 256 KB), folder? (default \"User Templates\")}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}", always, template_import), ] } diff --git a/crates/engine/src/cmd/slideshow.rs b/crates/engine/src/cmd/slideshow.rs index ffbfe8be65..9dc27eae2f 100644 --- a/crates/engine/src/cmd/slideshow.rs +++ b/crates/engine/src/cmd/slideshow.rs @@ -366,7 +366,7 @@ pub fn specs() -> Vec { "Slideshow Playback Settings", [], None, - "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual}", + "{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it), panAndZoom?: bool (each photo moves and zooms slowly over its slide, on its own path), panAndZoomAmount?: 0 (low) to 1 (high)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual, panAndZoom, panAndZoomAmount}", always, playback ), diff --git a/crates/engine/src/denoise/model.rs b/crates/engine/src/denoise/model.rs index 253668c2c9..70dea39ffe 100644 --- a/crates/engine/src/denoise/model.rs +++ b/crates/engine/src/denoise/model.rs @@ -412,7 +412,7 @@ pub fn serving(dir: Option<&Path>, id: Option<&str>, run_on: RunOn) -> Result i.to_string(), None => read_settings(&dir).model.ok_or_else(|| { - format!("no denoise model is selected in {} (install one in Settings ▸ AI Denoise, or name it with --model)", dir.display()) + format!("no denoise model is selected in {} (install one in Settings → AI Denoise, or name it with --model)", dir.display()) })?, }; let installed = installed_models(&dir) diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 96ce93d0c1..c90035eb6c 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -39,13 +39,17 @@ mod commit; mod defaults; mod files; mod job; +mod reads; mod scan; mod types; +pub(crate) use commit::start_from_file; #[cfg(not(target_arch = "wasm32"))] pub(crate) use commit::workers; pub use commit::{batch_size, civil, commit_prepared, system_clock}; pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults}; +#[cfg(test)] +use files::expand_knowing; pub use files::{ EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline, launch_path, launch_path_until, @@ -54,6 +58,7 @@ pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with}; #[cfg(test)] use job::PreparedItem; pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with}; +pub use reads::{MAX_SKIPPED, MAX_STUCK_READERS, ReadWatch, STALL_AFTER, StalledRead, StuckReaders}; pub(crate) use scan::scan_files; pub use scan::{ ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, @@ -66,6 +71,17 @@ pub use types::{ OnDeleted, Organize, }; +mod listed_folders; +pub use listed_folders::ListedFolders; + +#[cfg(test)] +#[path = "import/tests_listed_folders.rs"] +mod tests_listed_folders; + #[cfg(test)] #[path = "import/tests_known.rs"] mod tests_known; + +#[cfg(test)] +#[path = "import/tests_pool.rs"] +mod tests_pool; diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 016ce01393..1a14297249 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,7 +1,7 @@ use super::defaults::apply_import_defaults; use super::files::copy_into; use super::job::{Prepared, PreparedItem, ReadyFile}; -use super::types::{Duplicate, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; +use super::types::{Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// A batch's items in file order while its transfers are pending ([`ImportJob::run_plan`]). @@ -181,6 +181,22 @@ fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool } } +/// What a new record takes from its file, as a file import gives it: the file's metadata and +/// capture time, the import defaults, then its XMP sidecar. Returns the sidecar when it said +/// anything (labels read through the library's label names). +pub(crate) fn start_from_file(s: &Session, p: &mut Photo, file: FileFacts, now: &str) -> Option { + let FileFacts { meta, captured, orientation, sidecar } = file; + p.meta = meta; + p.captured = captured; + apply_import_defaults(s, p); + let sc = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default())?; + // the photo is upright as the file's own orientation turns it, when the file states one + // (after the check above: an orientation alone isn't a sidecar that said something) + let sc = crate::sidecar::SidecarData { orientation: orientation.or(sc.orientation), ..sc }; + crate::sidecar::merge_into(p, &sc, now); + Some(sc) +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -252,25 +268,20 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare purge.push(*old); } } - let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default()); - // the photo is upright as the file's own orientation turns it, when the file states one - let sidecar = sidecar.map(|sc| crate::sidecar::SidecarData { orientation: info.orientation.or(sc.orientation), ..sc }); // a copy is catalogued under its new name let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone()); let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now); p.kind = info.kind; p.file_size = info.file_size; - p.captured = info.captured; - p.meta = info.meta; p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; p.embedded_lens = info.embedded_lens; p.set_preview_only(info.preview_only.clone()); - apply_import_defaults(s, &mut p); - if let Some(sc) = &sidecar { - crate::sidecar::merge_into(&mut p, sc, &now); + if let Some(sc) = + start_from_file(s, &mut p, FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar }, &now) + { report.sidecars += 1; - report.warnings.extend(sc.warnings.iter().cloned().map(|mut warning| { + report.warnings.extend(sc.warnings.into_iter().map(|mut warning| { warning.path = path.clone(); warning })); diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index b4a5e44190..074df065e9 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -114,14 +114,42 @@ pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk: /// ([`expand_report`], handing the listing of every folder that is walked to `note`, as /// [`expand_noting`] does.) -fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option) -> Expansion { +fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, note: Option) -> Expansion { + expand_report_knowing(paths, skip, limits, note, false, &|_| false) +} + +/// [`expand_noting`], taking the paths `known_file` says are files as files without asking the +/// disk (a review hands over thousands of them, and telling a file from a folder is a round trip +/// each on a network share). With `timed`, each folder's modification time goes to `note` too +/// ([`crate::walk::files_in_noting_timed`]). +pub(super) fn expand_knowing( + paths: &[String], + skip: Option<&Path>, + limits: crate::walk::Limits, + note: Option, + timed: bool, + known_file: &dyn Fn(&Path) -> bool, +) -> (Vec, bool) { + let e = expand_report_knowing(paths, skip, limits, note, timed, known_file); + (e.files, e.truncated) +} + +/// [`expand_knowing`] keeping the walks' diagnostics ([`Expansion`]). +pub(super) fn expand_report_knowing( + paths: &[String], + skip: Option<&Path>, + limits: crate::walk::Limits, + mut note: Option, + timed: bool, + known_file: &dyn Fn(&Path) -> bool, +) -> Expansion { let mut out = Expansion::default(); for p in paths { let p = Path::new(p); if skip.is_some_and(|s| p == s) { continue; } - if p.is_dir() { + if !known_file(p) && p.is_dir() { // XMP sidecars are read with their photos, not skipped: they are left out of the count let mut sidecars = 0usize; let keep = |f: &Path| { @@ -132,6 +160,7 @@ fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::wa keep }; let w = match note.as_mut() { + Some(note) if timed => crate::walk::files_in_noting_timed(p, skip, limits, keep, &mut **note), Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note), None => crate::walk::files_in(p, skip, limits, keep), }; diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ca906c6192..c7c35e91e1 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,7 +1,7 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand, probe_all, reusable_probes, sidecars_of}; +use super::files::{Seen, expand_knowing, probe_all, reusable_probes, sidecars_of}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; -use super::{HashMap, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; +use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// Import files/folders. See the module docs. pub fn import(s: &mut Session, paths: &[String], mode: ImportMode) -> crate::Result { @@ -45,7 +45,9 @@ pub struct ImportJob { file_bytes: Option, /// Probes from a preceding scan (not read again). pub(super) cache: HashMap, - naming: crate::sidecar::SidecarNaming, + pub(super) naming: crate::sidecar::SidecarNaming, + /// The `.xmp` names in the folders [`ImportJob::expand`] listed. + pub(super) listed: ListedFolders, now: String, /// Next rename number; `None` once the final representable value has been reserved. seq: Option, @@ -144,7 +146,7 @@ impl Prepared { existing: Some(existing), reason: if existing_path.is_some() { "path" } else { "content" }, hash: info.content_hash, - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured })), + file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed }))); @@ -198,6 +200,7 @@ impl ImportJob { file_bytes: s.media.file_bytes.clone(), cache: std::mem::take(&mut s.import_probes), naming: s.xmp.naming, + listed: ListedFolders::default(), now: (s.clock)(), total: Default::default(), done: Default::default(), @@ -215,10 +218,35 @@ impl ImportJob { self.prepare_files(files, cancel) } + /// Hand the job the folders the review that started it listed ([`ScanOutput::listed`]). + #[must_use] + pub fn with_listed(mut self, listed: ListedFolders) -> Self { + self.listed = listed; + self + } + /// Expand `paths` (folders recursively, the library's own folder skipped) into the files an /// import would handle; counted in [`ImportJob::total`]. - pub fn expand(&self, paths: &[String]) -> Vec { - let files = expand(paths, self.lib_dir.as_deref()); + pub fn expand(&mut self, paths: &[String]) -> Vec { + // (a file the review listed is a file: no round trip to a share to ask) + let mut listed = std::mem::take(&mut self.listed); + let mut walked = ListedFolders::default(); + // (the folders' times are looked at now, not as an earlier batch found them) + listed.new_batch(); + let (files, _) = expand_knowing( + paths, + self.lib_dir.as_deref(), + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|p| listed.is_known_file(p), + ); + listed.absorb(walked); + listed.forget_files(); + self.listed = listed; self.total.fetch_add(files.len(), std::sync::atomic::Ordering::Relaxed); files } @@ -254,6 +282,7 @@ impl ImportJob { use std::sync::atomic::Ordering::Relaxed; // the library as it was, kept for the ownership of the shared stem sidecars below let library = self.look_up_library(); + self.listed.new_batch(); let opts = self.opts.clone(); let mode = self.mode; let mut out = Prepared { scanned: files.len(), items: Vec::new() }; @@ -299,16 +328,17 @@ impl ImportJob { // names asked of the disk, which on a network share made a folder of thousands of photos wait // a round trip per name, one name after another. let asked: Vec<&str> = todo.iter().zip(&probed).filter(|(_, p)| p.is_ok()).map(|(f, _)| f.as_str()).collect(); - // (a file whose content the library has is skipped below as a duplicate: it asks the disk nothing) + // (a file whose content the library has is skipped below as a duplicate: it asks the disk + // nothing, unless the import makes a record of it from its file and sidecar, #2589) + let skipped = !opts.local && !opts.read_duplicates; let known: std::collections::HashSet<&str> = todo .iter() .zip(&probed) - .filter(|(_, p)| !opts.local && p.as_ref().is_ok_and(|i| i.content_hash.as_ref().is_some_and(|h| self.by_hash.contains_key(h)))) + .filter(|(_, p)| skipped && p.as_ref().is_ok_and(|i| i.content_hash.as_ref().is_some_and(|h| self.by_hash.contains_key(h)))) .map(|(f, _)| f.as_str()) .collect(); let mut found = - sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { crate::sidecar::find_sidecar_for_import(&stems, self.naming, f) }) - .into_iter(); + sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { self.listed.find_for_import(&stems, self.naming, f) }).into_iter(); // Files are planned one by one, in order (duplicates, sidecars, names, folders); their // copies or moves — the slow part, reading and writing every byte and verifying it — are // collected and run on several threads (issue #367), then their outcomes take their places. @@ -338,13 +368,14 @@ impl ImportJob { break; } } - // same bytes as a library photo: skipped below, once its capture time is known + // same bytes as a library photo: skipped below, once its capture time is known (and, + // when the import makes a record of it, once it is read as a file import reads it) let duplicate_of = info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing))); // the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files - // and names the copy when the file itself has none (a duplicate needs only that time) + // and names the copy when the file itself has none (a skipped duplicate needs only that time) let raw = info.kind == MediaKind::Raw; - let packet = if duplicate_of.is_some() && info.captured.is_some() { + let packet = if duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates { None } else { found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw)) @@ -371,7 +402,7 @@ impl ImportJob { existing, reason: "content", hash: Some(hash), - file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured })), + file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), })); continue; } diff --git a/crates/engine/src/import/listed_folders.rs b/crates/engine/src/import/listed_folders.rs new file mode 100644 index 0000000000..d8eac72c40 --- /dev/null +++ b/crates/engine/src/import/listed_folders.rs @@ -0,0 +1,166 @@ +//! What an import (or the review before it) learned of the folders it listed: the files in them +//! and the `.xmp` names. +//! +//! Looking for a photo's sidecar asks the disk about up to nine names ([`sidecar_candidates`]). +//! On a network share a name that is not there costs a round trip as much as one that is, so a +//! folder with no `.xmp` at all cost nine for each of its photos. Telling a file from a folder +//! (`is_dir`) is a round trip too, for each of the thousands of files a review hands over. The +//! listing that found those files already has both answers. +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::SystemTime; + +use crate::sidecar::{SidecarNaming, find_sidecar, sidecar_candidates}; +use crate::walk::EntryKind; + +/// One listed folder. +#[derive(Debug, Default)] +struct Folder { + /// The names listed as files (links are not: the disk says where they lead). + files: HashSet, + /// The `.xmp` names, lower-cased. Only for a folder that was listed completely, with plain + /// ASCII names (the names a file system treats alike in other cases are the ones we can fold + /// ourselves): for any other the disk decides, as before. + xmp: Option>, + /// The folder's modification time when it was listed: a file added, removed or replaced since + /// changes it, and the `.xmp` and file names are then not trusted (a listing taken by a review + /// can be hours old). + modified: Option, +} + +/// The folders listed so far (see the module docs). The review's scan hands its listing to the +/// import that review starts ([`crate::import::ImportJob::with_listed`]), and nowhere else. +/// The `.xmp` names and the file names of a folder are trusted only while its modification time +/// is what it was when it was listed (looked at once per folder per batch: [`ListedFolders::new_batch`]); a +/// volume whose folders keep no usable time (it can't be read) is probed as before. +#[derive(Debug, Default)] +pub struct ListedFolders { + folders: HashMap, + /// folder → whether its time is still the listed one, for the batch being handled. + checked: Mutex>, + /// How often the disk was asked after all about a sidecar (for the tests). + pub(crate) asked: AtomicUsize, + /// How many folders' times were looked at (for the tests). + pub(crate) looked: AtomicUsize, + /// The threads that looked a sidecar up for an import (for the tests: the lookups of a batch are + /// not made one after another by the thread that plans it). + #[cfg(test)] + pub(crate) lookers: Mutex>, +} + +impl ListedFolders { + /// Take the listing of `folder` from the walk ([`crate::walk::files_in_noting`]), with the + /// folder's time as the walk read it before listing (`None`: too recent to vouch for, or unreadable). + pub(crate) fn note(&mut self, folder: &Path, entries: Vec<(OsString, EntryKind)>, complete: bool, modified: Option) { + let mut listed = Folder { modified, ..Default::default() }; + let mut xmp = (complete && listed.modified.is_some()).then(HashSet::new); + for (name, kind) in entries { + // (a name that is no text is not one a path can be compared with) + let Some(name) = name.to_str() else { + xmp = None; + continue; + }; + if let Some(set) = &mut xmp { + if name.is_ascii() { + let lower = name.to_ascii_lowercase(); + if lower.ends_with(".xmp") { + set.insert(lower); + } + } else { + // (not ours to say what another name's other case is) + xmp = None; + } + } + if kind == EntryKind::File && crate::import::is_supported(Path::new(name)) { + listed.files.insert(name.to_string()); + } + } + listed.xmp = xmp; + self.folders.insert(folder.to_path_buf(), listed); + } + + /// A new batch of files is handled: look at the folders' times again. A folder's time is looked at + /// once per batch, by the first lookup in it (a look for each photo would cost the round trip each + /// that the listing saves), so a sidecar added there while the batch is handled is not seen until + /// the next batch. + pub(crate) fn new_batch(&self) { + self.checked.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + + /// The names of files are needed to take a path for a file (once the files are expanded, no more). + pub(crate) fn forget_files(&mut self) { + for f in self.folders.values_mut() { + f.files = HashSet::new(); + } + } + + /// Whether `dir` is as it was listed. + fn unchanged(&self, dir: &Path, listed: Option) -> bool { + // (no time to compare with: not trusted, and the disk is not asked) + let Some(listed) = listed else { return false }; + let mut checked = self.checked.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(known) = checked.get(dir) { + return *known; + } + self.looked.fetch_add(1, Ordering::Relaxed); + let now = std::fs::metadata(dir).and_then(|m| m.modified()).ok(); + let same = now == Some(listed); + checked.insert(dir.to_path_buf(), same); + same + } + + /// Take over `walked`'s folders, which are newer than the ones held for them. + pub(crate) fn absorb(&mut self, walked: ListedFolders) { + self.folders.extend(walked.folders); + } + + /// Whether a listing says `path` is a file, as it was found: the disk need not be asked. + /// Only while its folder is as it was listed (a file may have been replaced by a folder since; + /// a folder with no usable time is never trusted). + pub(crate) fn is_known_file(&self, path: &Path) -> bool { + let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return false }; + // (the path ends in that name: no `/.` or separator after it, which the disk would resolve) + path.to_str().is_some_and(|p| p.ends_with(name)) + && self.folders.get(dir).is_some_and(|f| f.files.contains(name) && self.unchanged(dir, f.modified)) + } + + /// Whether the listing of `original`'s folder shows that none of its sidecar names is there. + /// `false` where it can't say: the folder was not listed (or not completely), or a name is + /// one the disk may resolve another way. + fn rules_out(&self, original: &str, naming: SidecarNaming) -> bool { + let path = Path::new(original); + let Some(dir) = path.parent() else { return false }; + let Some((xmp, modified)) = self.folders.get(dir).and_then(|f| Some((f.xmp.as_ref()?, f.modified))) else { return false }; + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + if !original.ends_with(name) || crate::sync::asks_the_disk(name) || !crate::sync::plain_name(name) || !self.unchanged(dir, modified) { + return false; + } + sidecar_candidates(original, naming) + .all(|c| c.file_name().and_then(|n| n.to_str()).is_some_and(|n| crate::sync::plain_name(n) && !xmp.contains(&n.to_ascii_lowercase()))) + } + + /// [`crate::sidecar::find_sidecar_for_import`], without asking the disk where the listing shows + /// there is none: a file that owns its stem sidecar ([`crate::sidecar::ImportStems`]) is looked + /// up as [`ListedFolders::find`] does; one that doesn't reads only its own `.xmp`. + pub(crate) fn find_for_import(&self, stems: &crate::sidecar::ImportStems, naming: SidecarNaming, original: &str) -> Option { + #[cfg(test)] + self.lookers.lock().unwrap_or_else(|e| e.into_inner()).insert(std::thread::current().id()); + if stems.owns(original) { + return self.find(original, naming); + } + self.asked.fetch_add(1, Ordering::Relaxed); + crate::sidecar::find_sidecar_for_import(stems, naming, original) + } + + /// [`find_sidecar`], without asking the disk where the listing shows there is none. + pub(crate) fn find(&self, original: &str, naming: SidecarNaming) -> Option { + if self.rules_out(original, naming) { + return None; + } + self.asked.fetch_add(1, Ordering::Relaxed); + find_sidecar(original, naming) + } +} diff --git a/crates/engine/src/import/reads.rs b/crates/engine/src/import/reads.rs new file mode 100644 index 0000000000..fb3291bea0 --- /dev/null +++ b/crates/engine/src/import/reads.rs @@ -0,0 +1,624 @@ +//! The file reads of an import (or a scan) that can stop answering (LR-BEHAV-BG-TASKS). +//! +//! **Not used yet:** this is the tested core. The import, the scans and Synchronize Folder move onto it in the +//! changes that follow (✕ ending them at once, then the activity row naming the stalled file and offering Skip), so +//! nothing outside this module's tests calls [`Pool::run`] today. +//! +//! A network drive that drops its connection leaves a read blocked inside the operating system, and a blocked read +//! cannot be interrupted. An import that waited for every read (as a scope of threads does: it cannot end before each +//! thread has) hung with it, and the only way out was to quit. Here the reads run on detached threads that pull their +//! jobs from a shared queue ([`Pool::run`]), and the calling thread only coordinates. It looks every +//! 250 ms at: +//! +//! - **✕:** the run stops at once. Jobs under way are given [`CANCEL_GRACE`] to finish (what they made is kept, as +//! before), then abandoned; jobs still queued are never started. +//! - **A stall:** a job that has made no progress for [`ReadWatch::stall_after`] is published +//! ([`ReadWatch::stalled`]), for the activity row to name ("Waiting for IMG_0457.jpg · 14 s"). Progress is a byte +//! read or written, or the end of a step: work that takes long without waiting on the disk (queueing for memory, +//! encoding a DNG) says so with [`progressed`], so a healthy slow job is never reported. +//! - **Skip:** [`ReadWatch::skip`] gives up the one read the row names (the longest without progress; the next is +//! named afterwards). It is reported as failed ("skipped: no answer after N s"), its thread is abandoned (it stays +//! blocked until the system lets it go, and its late result is dropped, never applied; it keeps its memory permit +//! until then) and a fresh thread takes its place, so the run goes on with the same number of readers. +//! - **A drive that is gone:** the [`MAX_SKIPPED`]th skipped read ends the run with an error ([`ReadWatch::ended`]) +//! instead of leaving yet another thread blocked. +//! +//! - **Earlier runs:** an abandoned read stays blocked after its run is over, and the next run builds a new pool. The +//! abandoned threads still alive are counted across runs ([`StuckReaders`], [`MAX_STUCK_READERS`]), whichever drive +//! they wait on; once that many are blocked, a run is not started (and a Skip starts no replacement reader) and the +//! run ends with an error saying so, so repeated cancel and restart cannot pile up blocked threads. The count is +//! looked at when a run starts and after each Skip; ✕ can still abandon the readers of the runs under way (at most +//! [`crate::import::workers`] per pool, and Synchronize Folder runs two) on top, so the bound is the cap plus that. +//! +//! Several pools can run at once under one [`ReadWatch`] (Synchronize Folder probes the new files while it checks +//! the library's photos): the watch names the longest stall of all, and Skip acts on the pool that has it. + +// (no caller outside the tests yet, see above: the tests use all of it, so only the non-test build allows it. On wasm32 +// the pool is not built at all, which the follow-up keeps allowing) +#![cfg_attr(not(test), allow(dead_code))] + +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use web_time::Instant; + +/// A read that has made no progress for this long is reported as stalled. +pub const STALL_AFTER: Duration = Duration::from_secs(10); +/// The skipped reads that end a run with an error: each leaves a thread blocked until the system lets it go. +pub const MAX_SKIPPED: usize = 4; +/// The abandoned reads that keep a new run from starting, over all runs of the process (eight runs' worth of +/// [`MAX_SKIPPED`]). It is looked at when a run starts and after a Skip, and ✕ can abandon the readers of the runs +/// under way on top: the blocked threads stay bounded by this plus a few runs' readers, not unbounded. +pub const MAX_STUCK_READERS: usize = 32; +/// How often the coordinating thread looks at ✕, Skip and the readers. +const POLL: Duration = Duration::from_millis(250); +/// Once ✕ is pressed, how long jobs under way get to finish before they are abandoned. +const CANCEL_GRACE: Duration = Duration::from_millis(400); + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// How many abandoned reader threads are still alive (blocked in the operating system), shared by every run that +/// uses it. A thread counts from the moment it is abandoned until it truly exits, however long after its run ended. +#[derive(Debug)] +pub struct StuckReaders { + alive: AtomicUsize, + cap: usize, +} + +impl StuckReaders { + pub fn new(cap: usize) -> Self { + StuckReaders { alive: AtomicUsize::new(0), cap } + } + + /// The process-wide count: the session will start with it, once the readers are wired in. + pub fn global() -> std::sync::Arc { + static GLOBAL: std::sync::OnceLock> = std::sync::OnceLock::new(); + GLOBAL.get_or_init(|| std::sync::Arc::new(StuckReaders::new(MAX_STUCK_READERS))).clone() + } + + /// Abandoned readers still blocked. + pub fn alive(&self) -> usize { + self.alive.load(Ordering::SeqCst) + } + + fn full(&self) -> bool { + self.alive() >= self.cap + } +} + +/// A read that has gone without progress ([`ReadWatch::stalled`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StalledRead { + /// The file's name. + pub what: String, + /// How long it has been without progress. + pub waited: Duration, +} + +/// What the reads of an import or scan are doing, shared between the run (which publishes it) and whoever shows it +/// and offers Skip. Everything is behind `&self`: hand out clones of the `Arc`. +#[derive(Debug)] +pub struct ReadWatch { + stall_after_ms: AtomicU64, + poll_ms: AtomicU64, + /// The longest stall of each running pool: (pool, the file's name, since when). + stalls: Mutex>, + pools: AtomicU64, + /// Skip was asked for this read (its name and since when it stalled). + skip: Mutex>, + skipped: AtomicUsize, + ended: Mutex>, + stuck: std::sync::Arc, +} + +impl Default for ReadWatch { + fn default() -> Self { + ReadWatch { + stall_after_ms: AtomicU64::new(millis(STALL_AFTER)), + poll_ms: AtomicU64::new(millis(POLL)), + stalls: Mutex::new(Vec::new()), + pools: AtomicU64::new(0), + skip: Mutex::new(None), + skipped: AtomicUsize::new(0), + ended: Mutex::new(None), + stuck: StuckReaders::global(), + } + } +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) +} + +impl ReadWatch { + /// A watch whose runs count their abandoned readers in `stuck` (the session's, once the readers are wired in). + pub fn with_stuck(after: Duration, stuck: std::sync::Arc) -> Self { + ReadWatch { stuck, ..ReadWatch::new(after) } + } + + /// A watch that calls a read stalled after `after` ([`STALL_AFTER`] by default). + pub fn new(after: Duration) -> Self { + let watch = ReadWatch::default(); + watch.set_stall_after(after); + watch + } + + /// How long a read goes without progress before it counts as stalled. + pub fn stall_after(&self) -> Duration { + Duration::from_millis(self.stall_after_ms.load(Ordering::Relaxed)) + } + + pub fn set_stall_after(&self, after: Duration) { + self.stall_after_ms.store(millis(after), Ordering::Relaxed); + } + + /// How often the reads are looked at, for tests that cannot wait a quarter of a second. + #[cfg(test)] + pub(crate) fn set_poll(&self, every: Duration) { + self.poll_ms.store(millis(every).max(1), Ordering::Relaxed); + } + + fn poll(&self) -> Duration { + Duration::from_millis(self.poll_ms.load(Ordering::Relaxed)) + } + + /// The read that has gone longest without progress, if one has for [`ReadWatch::stall_after`]. + pub fn stalled(&self) -> Option { + let stalls = lock(&self.stalls); + stalls.iter().min_by_key(|(_, _, since)| *since).map(|(_, what, since)| StalledRead { what: what.clone(), waited: since.elapsed() }) + } + + fn register_pool(&self) -> u64 { + self.pools.fetch_add(1, Ordering::Relaxed) + } + + /// Say which read of `pool` has stalled the longest (`None`: none has). + fn publish(&self, pool: u64, stalled: Option<(String, Instant)>) { + let mut stalls = lock(&self.stalls); + stalls.retain(|(p, ..)| *p != pool); + if let Some((what, since)) = stalled { + stalls.push((pool, what, since)); + } + // a Skip is for the read that was named: one that answered meanwhile (or was given up) takes it with it + let mut asked = lock(&self.skip); + if asked.as_ref().is_some_and(|(what, since)| !stalls.iter().any(|(_, w, s)| w == what && s == since)) { + *asked = None; + } + } + + /// Give up the read that is named ([`ReadWatch::stalled`]), at the next look: only that read, and only while it is + /// still the one named (a Skip for a read that answered meanwhile does nothing). Nothing happens when no read is + /// stalled. + pub fn skip(&self) { + let stalls = lock(&self.stalls); + *lock(&self.skip) = stalls.iter().min_by_key(|(_, _, since)| *since).map(|(_, what, since)| (what.clone(), *since)); + } + + /// Whether Skip was asked for the read `shown` (the one the row named when it was asked) and that read is the one + /// named now, which is `pool`'s; asking clears it. + fn take_skip_for(&self, pool: u64, shown: &(String, Instant)) -> bool { + let stalls = lock(&self.stalls); + let named_here = + stalls.iter().min_by_key(|(_, _, since)| *since).is_some_and(|(p, what, since)| *p == pool && (what, since) == (&shown.0, &shown.1)); + named_here && lock(&self.skip).take().is_some_and(|asked| asked == *shown) + } + + /// How many reads were given up by Skip so far. + pub fn skipped(&self) -> usize { + self.skipped.load(Ordering::Relaxed) + } + + /// Why the run cannot go on, once it cannot: too many reads were skipped, or a reader could not be started. + pub fn ended(&self) -> Option { + lock(&self.ended).clone() + } + + fn blocked_elsewhere(&self) -> String { + format!( + "a drive is not answering: {} reads that were given up are still waiting for it (try again later, or restart LightCraft)", + self.stuck.alive() + ) + } + + fn end(&self, why: String) { + lock(&self.ended).get_or_insert(why); + } +} + +/// How one job of a [`Pool::run`] came out. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +pub(super) enum Outcome { + Done(R), + /// It was skipped, or its worker panicked: why. + Failed(String), + /// Never started, or cut off before it finished: by ✕, or because the run ended (too many reads skipped, too many + /// given-up reads still blocked, or a reader that could not be started). + Unreached, +} + +/// Where one run of reads happens ([`Pool::run`]). +#[cfg(not(target_arch = "wasm32"))] +pub(super) struct Pool<'a> { + pub watch: &'a ReadWatch, + /// ✕: set from outside (the activity row's, or the run's own). + pub cancel: &'a AtomicBool, + /// Thread names: `-`. + pub name: &'static str, + /// Reads at once. + pub threads: usize, +} + +/// A thread of the pool. It is *abandoned* when its job is given up: it never takes another job, and what it +/// finishes with goes to the `late` handler. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Worker { + /// The job it is on (its index) and when it last made progress. + busy: Mutex>, + abandoned: std::sync::Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + /// The pool thread this is, for [`progressed`]. + static CURRENT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// The abandon flag of the pool thread this is (`None` on any other thread), for the memory gate to tell the permits of +/// reads that were given up from the others. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn abandon_flag() -> Option> { + CURRENT.with(|current| current.borrow().as_ref().map(|worker| worker.abandoned.clone())) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn abandon_flag() -> Option> { + None +} + +/// The job on this thread has made progress (a chunk read or written, a wait for memory over, a step done): its +/// stall clock starts again. Does nothing on a thread that is not a pool's. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn progressed() { + CURRENT.with(|current| { + if let Some(worker) = current.borrow().as_ref() + && let Some(busy) = lock(&worker.busy).as_mut() + { + busy.1 = Instant::now(); + } + }); +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn progressed() {} + +type Message = (usize, Result); + +/// Where the workers hand in what they finished, until the run is over: a late hand-in is refused, so that its sender +/// disposes of it. +#[cfg(not(target_arch = "wasm32"))] +struct Inbox(Mutex>>>); + +#[cfg(not(target_arch = "wasm32"))] +impl Inbox { + fn hand_in(&self, message: Message) -> Result<(), Message> { + match lock(&self.0).as_ref() { + Some(tx) => tx.send(message).map_err(|e| e.0), + None => Err(message), + } + } + + fn close(&self) { + *lock(&self.0) = None; + } +} + +#[cfg(not(target_arch = "wasm32"))] +type Work = std::sync::Arc R + Send + Sync>; + +/// What every thread of one run shares. +#[cfg(not(target_arch = "wasm32"))] +struct Shared { + jobs: Mutex>, + inbox: Inbox, + work: Work, + late: std::sync::Arc, + init: std::sync::Arc, + /// The run is over: a job still queued is not started. + over: AtomicBool, + stuck: std::sync::Arc, +} + +/// Gives up the thread's place in the [`StuckReaders`] count when it exits, if it was abandoned. +#[cfg(not(target_arch = "wasm32"))] +struct Exit(std::sync::Arc, std::sync::Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Exit { + fn drop(&mut self) { + if self.0.abandoned.load(Ordering::SeqCst) { + self.1.alive.fetch_sub(1, Ordering::SeqCst); + } + } +} + +/// Abandon `w` (its job is given up), counting it until its thread exits. Call with its `busy` lock held and `Some`. +#[cfg(not(target_arch = "wasm32"))] +fn abandon(w: &Worker, stuck: &StuckReaders) { + if !w.abandoned.swap(true, Ordering::SeqCst) { + stuck.alive.fetch_add(1, Ordering::SeqCst); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn worker_loop(me: std::sync::Arc, shared: std::sync::Arc>) { + let _exit = Exit(me.clone(), shared.stuck.clone()); + CURRENT.with(|current| *current.borrow_mut() = Some(me.clone())); + // (a reader that cannot be set up still takes jobs: one that died here would be handed jobs it never takes) + if let Err(why) = crate::guard::catch("import", || (shared.init)()) { + log::warn!("import: a reader's set-up failed: {why}"); + } + loop { + // (the lock is held while waiting: the other idle workers queue behind it, and a worker blocked in a read does + // not hold it) + let next = lock(&shared.jobs).recv(); + let Ok((i, job)) = next else { return }; + // (checked and claimed under one lock: the end-of-run sweep sets `over` first, so it either sees this job and + // abandons the thread, or the thread sees `over` and never starts it) + { + let mut busy = lock(&me.busy); + if shared.over.load(Ordering::SeqCst) || me.abandoned.load(Ordering::SeqCst) { + return; + } + *busy = Some((i, Instant::now())); + } + let result = crate::guard::catch("import", || (shared.work)(job)); + // decided under the lock the coordinator abandons under, so that it never abandons the next job by mistake + let abandoned = { + let mut busy = lock(&me.busy); + *busy = None; + me.abandoned.load(Ordering::SeqCst) + }; + if abandoned { + if let Ok(r) = result { + (shared.late)(r); + } + return; + } + if let Err((_, Ok(r))) = shared.inbox.hand_in((i, result)) { + (shared.late)(r); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Pool<'_> { + fn halted(&self) -> bool { + self.cancel.load(Ordering::Relaxed) || self.watch.ended().is_some() + } + + /// Run `jobs` on [`Pool::threads`] detached threads; the outcome of each, in order. `label` names job `i` for the + /// row; `work` does one; `late` disposes of a result that arrives after its job was given up (nothing may be + /// applied: a copy that was made is taken back); `init` runs first on each new thread; `on_done` counts each job + /// settled (`None`: failed). + /// + /// Jobs are handed out by this thread, no more than there are readers at a time, so that ✕ stops the run + /// within a file or two. If no thread can be started the jobs run here, one after another. + pub(super) fn run( + &self, + jobs: Vec, + label: &dyn Fn(usize) -> String, + work: Work, + late: std::sync::Arc, + init: std::sync::Arc, + on_done: &dyn Fn(Option<&R>), + ) -> Vec> { + use std::sync::Arc; + use std::sync::mpsc; + let total = jobs.len(); + let mut outcomes: Vec> = (0..total).map(|_| Outcome::Unreached).collect(); + if total == 0 || self.halted() { + return outcomes; + } + if self.watch.stuck.full() { + self.watch.end(self.watch.blocked_elsewhere()); + return outcomes; + } + let pool = self.watch.register_pool(); + let (job_tx, job_rx) = mpsc::channel::<(usize, J)>(); + let (result_tx, result_rx) = mpsc::channel::>(); + let shared = Arc::new(Shared { + jobs: Mutex::new(job_rx), + inbox: Inbox(Mutex::new(Some(result_tx))), + work: work.clone(), + late: late.clone(), + init, + over: AtomicBool::new(false), + stuck: self.watch.stuck.clone(), + }); + let start = |n: usize| -> std::io::Result> { + let me = Arc::new(Worker::default()); + let (mine, shared) = (me.clone(), shared.clone()); + std::thread::Builder::new().name(format!("{}-{n}", self.name)).spawn(move || worker_loop(mine, shared))?; + Ok(me) + }; + let mut live: Vec> = Vec::new(); + for n in 0..self.threads.clamp(1, total) { + match start(n) { + Ok(w) => live.push(w), + Err(e) => { + log::warn!("import: could not start a reader: {e}"); + break; + } + } + } + if live.is_empty() { + // no thread to be had: read here, one after another + for (job, slot) in jobs.into_iter().zip(outcomes.iter_mut()) { + if self.halted() { + break; + } + *slot = match crate::guard::catch("import", || work(job)) { + Ok(r) => { + on_done(Some(&r)); + Outcome::Done(r) + } + Err(e) => { + on_done(None); + Outcome::Failed(e) + } + }; + } + return outcomes; + } + let mut jobs: Vec> = jobs.into_iter().map(Some).collect(); + let mut started = live.len(); + let (mut next, mut outstanding) = (0usize, 0usize); + let mut halted_at: Option = None; + let settle = |outcomes: &mut Vec>, outstanding: &mut usize, (i, result): Message| { + let Some(slot) = outcomes.get_mut(i) else { return }; + if !matches!(slot, Outcome::Unreached) { + // its job was given up already: this is the late answer + if let Ok(r) = result { + late(r); + } + return; + } + *outstanding = outstanding.saturating_sub(1); + *slot = match result { + Ok(r) => { + on_done(Some(&r)); + Outcome::Done(r) + } + Err(e) => { + on_done(None); + Outcome::Failed(e) + } + }; + }; + loop { + if halted_at.is_none() && self.halted() { + halted_at = Some(Instant::now()); + } + if halted_at.is_none() { + while outstanding < live.len() && next < total { + let Some(job) = jobs.get_mut(next).and_then(Option::take) else { + next += 1; + continue; + }; + if job_tx.send((next, job)).is_err() { + self.watch.end("the readers stopped unexpectedly".into()); + break; + } + next += 1; + outstanding += 1; + } + } + if outstanding == 0 && (halted_at.is_some() || next >= total) { + break; + } + if let Some(at) = halted_at + && (self.watch.ended().is_some() || at.elapsed() >= CANCEL_GRACE) + { + break; + } + match result_rx.recv_timeout(self.watch.poll()) { + Ok(message) => settle(&mut outcomes, &mut outstanding, message), + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + // jobs without progress: the longest is published for the row, and given up when Skip was asked for + let after = self.watch.stall_after(); + let stalled = live + .iter() + .enumerate() + .filter_map(|(k, w)| (*lock(&w.busy)).filter(|(_, since)| since.elapsed() >= after).map(|(i, since)| (k, i, since))) + .min_by_key(|&(_, _, since)| since); + self.watch.publish(pool, stalled.map(|(_, i, since)| (label(i), since))); + if let Some((k, i, since)) = stalled + && halted_at.is_none() + && self.watch.take_skip_for(pool, &(label(i), since)) + && let Some(w) = live.get(k) + { + { + let busy = lock(&w.busy); + if *busy != Some((i, since)) { + continue; // it answered just now + } + abandon(w, &self.watch.stuck); + } + live.remove(k); + let secs = since.elapsed().as_secs(); + if let Some(slot) = outcomes.get_mut(i) { + *slot = Outcome::Failed(format!("skipped: no answer after {secs} s")); + } + on_done(None); + outstanding = outstanding.saturating_sub(1); + let skipped = self.watch.skipped.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if skipped >= MAX_SKIPPED { + self.watch.end(format!("the drive is not answering ({} is the last file it stopped on)", label(i))); + } else if self.watch.stuck.full() { + self.watch.end(self.watch.blocked_elsewhere()); + } else { + match start(started) { + Ok(w) => { + started += 1; + live.push(w); + } + Err(e) => self.watch.end(format!("could not start a reader: {e}")), + } + } + } + } + // Over (or stopped): jobs still queued are not started, and the readers still at one are abandoned: they + // dispose of their own results. What arrived already is taken, so nothing is lost between the last look and + // here. + shared.over.store(true, Ordering::SeqCst); + for w in &live { + let busy = lock(&w.busy); + if busy.is_some() { + abandon(w, &self.watch.stuck); + } + } + drop(job_tx); + shared.inbox.close(); + while let Ok(message) = result_rx.try_recv() { + settle(&mut outcomes, &mut outstanding, message); + } + self.watch.publish(pool, None); + outcomes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A Skip is for the read that was named when it was asked: once that read answered and another is named, the + /// request does nothing. + #[test] + fn a_stale_skip_does_nothing() { + let watch = ReadWatch::default(); + let old = Instant::now(); + watch.publish(0, Some(("a.jpg".into(), old))); + watch.skip(); + // a.jpg answered; b.jpg stalled since + watch.publish(0, Some(("b.jpg".into(), Instant::now()))); + assert!(watch.skip.lock().unwrap().is_none(), "the request went with the read it was for"); + assert!(!watch.take_skip_for(0, &("b.jpg".into(), Instant::now()))); + // a request for the read that is named is taken, once + let now = Instant::now(); + watch.publish(0, Some(("b.jpg".into(), now))); + watch.skip(); + assert!(watch.take_skip_for(0, &("b.jpg".into(), now))); + assert!(!watch.take_skip_for(0, &("b.jpg".into(), now))); + // nothing named: Skip asks for nothing + watch.publish(0, None); + watch.skip(); + assert!(watch.skip.lock().unwrap().is_none()); + } +} diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index aaae16c7a4..5941d83194 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,6 +1,6 @@ -use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes}; +use super::files::{Seen, expand, expand_report_knowing, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; -use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; +use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; /// What a [`scan`] needs from the session, so it can run on another thread (a folder on a network /// share can take minutes to read). @@ -12,6 +12,8 @@ pub struct ScanInput { /// ([`library_hashes`]), on the scan's thread. library: std::sync::Arc, cache: HashMap, + /// The folders the scan listed, for the import that follows. + listed: ListedFolders, } /// The library's photos of `files`: path → (photo, its summary as a candidate that is there @@ -83,6 +85,8 @@ pub struct ScanOutput { pub unreadable: usize, /// Files inside the folders that are not a supported photo type (XMP sidecars not counted). pub unsupported: usize, + /// The folders the scan listed (kept with the probes, for the import that follows). + pub listed: ListedFolders, } impl ScanInput { @@ -91,7 +95,13 @@ impl ScanInput { // (no table of the library here: this is the session's thread, and the library may hold // millions of photos. The scan looks up what it finds) let library = std::sync::Arc::new(s.catalog.clone()); - let input = ScanInput { probe: s.media.file_probe.clone(), skip, library, cache: std::mem::take(&mut s.import_probes) }; + let input = ScanInput { + probe: s.media.file_probe.clone(), + skip, + library, + cache: std::mem::take(&mut s.import_probes), + listed: ListedFolders::default(), + }; (input, paths.to_vec()) } @@ -303,8 +313,21 @@ pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput { /// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it /// has) when `progress.cancel` is set. -pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput { - let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default()); +pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput { + let listed = &mut input.listed; + let expansion = expand_report_knowing( + paths, + input.skip.as_deref(), + crate::walk::Limits::default(), + // (always `true`: nothing here stops the walk. `progress.cancel` is read only once it is over, in + // `scan_files`, which stops the probing and returns what it has) + Some(&mut |dir, names, complete, modified| { + listed.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); let mut out = scan_files(input, expansion.files, progress); out.truncated = expansion.truncated; out.unreadable = expansion.unreadable; @@ -314,7 +337,7 @@ pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> /// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks' /// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has -/// them ([`expand_report`]). +/// them ([`expand_report`](super::files::expand_report)). pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &ScanProgress) -> ScanOutput { use std::sync::atomic::Ordering::Relaxed; let by_path = library_files(&input.library, &files); @@ -376,5 +399,5 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc out.push(c); } // (the walks' diagnostics are [`scan_with`]'s: these files were found already) - ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 } + ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0, listed: input.listed } } diff --git a/crates/engine/src/import/tests_listed_folders.rs b/crates/engine/src/import/tests_listed_folders.rs new file mode 100644 index 0000000000..5c7e7f4130 --- /dev/null +++ b/crates/engine/src/import/tests_listed_folders.rs @@ -0,0 +1,394 @@ +//! An import asks the disk for a photo's sidecar only where the folder's listing leaves room for +//! one: on a network share every name asked about is a round trip, found or not. +use super::*; +use crate::sidecar::SidecarNaming; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; + +fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-listed-sidecars-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Make `dir` and the folders in it an hour old, so the walk vouches for their times +/// (`walk::TIME_GRAIN`, two seconds) without the test waiting. +fn settle(dir: &Path) { + let hour_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + if e.file_type().is_ok_and(|t| t.is_dir()) { + settle(&e.path()); + } + } + set_folder_time(dir, hour_ago); +} + +/// Set a folder's modification time (Unix: a plain handle; Windows: one opened for attributes, +/// with backup semantics, which is how a folder is opened there). +fn set_folder_time(dir: &Path, at: std::time::SystemTime) { + #[cfg(windows)] + let handle = { + use std::os::windows::fs::OpenOptionsExt; + // FILE_WRITE_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS + std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir) + }; + #[cfg(not(windows))] + let handle = std::fs::File::open(dir); + handle.unwrap().set_modified(at).unwrap(); +} + +fn modified(dir: &Path) -> Option { + std::fs::metadata(dir).and_then(|m| m.modified()).ok() +} + +fn xmp(rating: u8) -> String { + format!( + r#" +"# + ) +} + +/// An import of files that are not read (the probe says "a JPEG") with the naming `naming`. +fn job(naming: SidecarNaming) -> ImportJob { + let mut s = Session::new(); + let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap(); + job.naming = naming; + job.probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), ..ProbeInfo::default() }))); + job +} + +/// (file name → the rating its sidecar gave, `None`: no sidecar) in the order imported. +fn ratings(p: Prepared) -> Vec<(String, Option)> { + p.items + .into_iter() + .map(|i| match i { + PreparedItem::Ready(r) => (Path::new(&r.path).file_name().unwrap().to_string_lossy().to_string(), r.sidecar.and_then(|sc| sc.rating)), + other => panic!("not ready: {other:?}"), + }) + .collect() +} + +/// Given folders listed completely that hold no `.xmp`, when their files are imported, then no +/// sidecar name is asked of the disk (it was nine names for every file); and files named one by +/// one, whose folders nobody listed, are asked about as before. +#[test] +fn a_listed_folder_without_sidecars_is_not_asked_about_them() { + let root = scratch("none"); + let mut named = Vec::new(); + for folder in 0..50 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..20 { + let f = dir.join(format!("IMG_{n:04}.jpg")); + std::fs::write(&f, b"x").unwrap(); + named.push(f.to_string_lossy().to_string()); + } + } + settle(&root); + let cancel = AtomicBool::new(false); + + let mut listed = job(SidecarNaming::Stem); + let p = listed.prepare(&[root.to_string_lossy().to_string()], &cancel); + assert_eq!(p.items.len(), 1000); + assert_eq!(listed.listed.asked.load(Relaxed), 0, "1,000 files in 50 listed folders: no disk probe"); + + let mut by_name = job(SidecarNaming::Stem); + let p = by_name.prepare(&named, &cancel); + assert_eq!(p.items.len(), 1000); + assert_eq!(by_name.listed.asked.load(Relaxed), 1000, "files named directly keep their disk probes"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given sidecars in every case and naming, when the folder is imported, then each is read, and +/// only the photo without one is not asked about. +#[test] +fn sidecars_in_the_listing_are_read_in_any_case() { + for naming in [SidecarNaming::Stem, SidecarNaming::Full] { + let root = scratch("cases"); + let write = |name: &str, rating: u8| std::fs::write(root.join(name), xmp(rating)).unwrap(); + for p in ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg"] { + std::fs::write(root.join(p), b"x").unwrap(); + } + write("a.xmp", 1); + write("b.XMP", 2); + write("c.Xmp", 3); + write("d.jpg.xmp", 4); + write("e.JPG.XMP", 5); + settle(&root); + let mut job = job(naming); + let found = ratings(job.prepare(&[root.to_string_lossy().to_string()], &AtomicBool::new(false))); + let expect: Vec<(String, Option)> = + [("a.jpg", Some(1)), ("b.jpg", Some(2)), ("c.jpg", Some(3)), ("d.jpg", Some(4)), ("e.jpg", Some(5)), ("f.jpg", None)] + .into_iter() + .map(|(n, r)| (n.to_string(), r)) + .collect(); + let mut found = found; + found.sort(); + assert_eq!(found, expect, "{naming:?}"); + assert_eq!(job.listed.asked.load(Relaxed), 5, "{naming:?}: the five with a sidecar are asked about, f.jpg is not"); + let _ = std::fs::remove_dir_all(&root); + } +} + +/// A folder the walk did not list completely, or whose names the listing can't compare as the +/// disk does (not ASCII), is not trusted: its photos are asked about as before. +#[test] +fn a_listing_that_cannot_say_leaves_the_disk_to_decide() { + let root = scratch("cannot-say"); + let (whole, partial, accents) = (root.join("whole"), root.join("partial"), root.join("accents")); + for d in [&whole, &partial, &accents] { + std::fs::create_dir_all(d).unwrap(); + } + let in_ = |d: &Path, n: &str| d.join(n).to_string_lossy().to_string(); + let mut l = listed_folders::ListedFolders::default(); + let file = |n: &str| (std::ffi::OsString::from(n), crate::walk::EntryKind::File); + l.note(&partial, vec![file("a.jpg")], false, modified(&partial)); + l.note(&accents, vec![file("é.jpg"), file("a.jpg")], true, modified(&accents)); + l.note(&whole, vec![file("a.jpg"), file("b.xmp")], true, modified(&whole)); + let naming = SidecarNaming::Stem; + // (a folder that is not on disk any more has no time to compare: asked about, too) + l.note(Path::new("/p/gone"), vec![file("a.jpg")], true, Some(std::time::SystemTime::UNIX_EPOCH)); + // (a folder too recent to vouch for, as the walk reports it: no time) + let recent = root.join("recent"); + std::fs::create_dir_all(&recent).unwrap(); + l.note(&recent, vec![file("a.jpg")], true, None); + let cases = [ + in_(&partial, "a.jpg"), + in_(&accents, "a.jpg"), + in_(&root.join("unlisted"), "a.jpg"), + in_(&whole, "b.jpg"), + in_(&whole, "a~1.jpg"), + in_(&whole, "nul.jpg"), + "/p/gone/a.jpg".to_string(), + in_(&recent, "a.jpg"), + ]; + for original in &cases { + let before = l.asked.load(Relaxed); + assert!(l.find(original, naming).is_none()); + assert_eq!(l.asked.load(Relaxed), before + 1, "{original}: the disk is asked"); + } + let before = l.asked.load(Relaxed); + assert!(l.find(&in_(&whole, "a.jpg"), naming).is_none()); + assert_eq!(l.asked.load(Relaxed), before, "a listed folder with no a.xmp: the disk is not asked"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a review (the scan before the Add Photos dialog) of folders without sidecars, and an +/// import of the files it listed, when the files are handled, then neither a sidecar name nor +/// "is it a folder" is asked of the disk for them; and the sidecar the review's listing shows is +/// read. +#[test] +fn an_import_after_a_review_trusts_the_folders_the_review_listed() { + let root = scratch("review"); + for folder in 0..20 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..10 { + std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap(); + } + } + std::fs::write(root.join("f07").join("IMG_0003.xmp"), xmp(4)).unwrap(); + settle(&root); + let mut s = Session::new(); + s.media.file_probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() }))); + let (input, paths) = ScanInput::new(&mut s, &[root.to_string_lossy().to_string()]); + let out = scan_with(input, &paths, &ScanProgress::default()); + let selected: Vec = out.candidates.iter().map(|c| c.path.clone()).collect(); + assert_eq!(selected.len(), 200); + // (what the app does with the scan's output) + s.import_probes = out.probes; + let listed = out.listed; + + let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap().with_listed(listed); + let p = job.prepare(&selected, &AtomicBool::new(false)); + assert_eq!(job.listed.asked.load(Relaxed), 1, "only the photo with a sidecar in the listing is asked about"); + let found = ratings(p); + assert_eq!(found.len(), 200); + assert_eq!(found.iter().filter(|(_, r)| r.is_some()).collect::>(), [&("IMG_0003.jpg".to_string(), Some(4))]); + let _ = std::fs::remove_dir_all(&root); +} + +/// A path the listing calls a file is not asked about (here the disk holds a folder by that +/// name, which only a look at the disk would find) while its folder is as it was listed; one it +/// does not list still is. +#[test] +fn a_file_the_listing_does_not_know_is_still_checked() { + let root = scratch("known"); + for name in ["known.jpg", "unknown.jpg"] { + std::fs::create_dir_all(root.join(name)).unwrap(); + std::fs::write(root.join(name).join("inner.jpg"), b"x").unwrap(); + } + settle(&root); + let mut job = job(SidecarNaming::Stem); + // (the folder is as listed: its time is the one the listing holds) + job.listed.note(&root, vec![("known.jpg".into(), crate::walk::EntryKind::File)], true, modified(&root)); + let (known, unknown) = (root.join("known.jpg"), root.join("unknown.jpg")); + let files = job.expand(&[known.to_string_lossy().to_string(), unknown.to_string_lossy().to_string()]); + assert_eq!(files, [known.to_string_lossy().to_string(), unknown.join("inner.jpg").to_string_lossy().to_string()]); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a review whose listing was kept, when a sidecar appears in a folder afterwards (the +/// review was left open, or cancelled, and something else added it), then the import that gets +/// the listing still reads it: a folder that changed since it was listed is probed. +#[test] +fn a_folder_that_changed_since_it_was_listed_is_probed() { + let root = scratch("stale"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + settle(&root); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + assert_eq!(files.len(), 3); + // a sidecar arrives, more than a clock tick after the listing + std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap(); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + let found = ratings(job.prepare_files(files, &AtomicBool::new(false))); + assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}"); + assert_eq!(job.listed.asked.load(Relaxed), 3, "the folder is asked about, photo by photo"); + let _ = std::fs::remove_dir_all(&root); +} + +/// A batch looks at the time of each folder its files are in, once: not once per file, and not +/// once per folder that was listed. +#[test] +fn a_batch_looks_at_each_of_its_folders_once() { + let root = scratch("looks"); + for folder in 0..50 { + let dir = root.join(format!("f{folder:02}")); + std::fs::create_dir_all(&dir).unwrap(); + for n in 0..20 { + std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap(); + } + } + settle(&root); + let mut job = job(SidecarNaming::Stem); + let files = job.expand(&[root.to_string_lossy().to_string()]); + assert_eq!(files.len(), 1000); + let in_folders = |names: &[&str]| -> Vec { + files.iter().filter(|f| Path::new(f).parent().and_then(Path::file_name).is_some_and(|d| names.iter().any(|n| d == *n))).cloned().collect() + }; + let cancel = AtomicBool::new(false); + let first = job.prepare_files(in_folders(&["f00", "f01"]), &cancel); + assert_eq!(first.items.len(), 40); + assert_eq!(job.listed.looked.load(Relaxed), 2, "40 files in 2 of the 50 listed folders"); + job.prepare_files(in_folders(&["f01", "f02", "f03"]), &cancel); + assert_eq!(job.listed.looked.load(Relaxed), 2 + 3, "the next batch looks again, at its own 3"); + assert_eq!(job.listed.asked.load(Relaxed), 0); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given photos named one by one (no listing to rule a sidecar out), when a batch of them is +/// handled, then their sidecars are not looked up one after another by the thread that plans the +/// batch: each is a few names asked of the disk, a round trip apiece on a network share, so the +/// lookups of a batch run together (`sidecars_of`). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_batchs_sidecars_are_looked_up_off_the_thread_that_plans_it() { + let root = scratch("lookers"); + let files: Vec = (0..6) + .map(|n| { + let f = root.join(format!("IMG_{n:04}.jpg")); + std::fs::write(&f, b"x").unwrap(); + f.to_string_lossy().to_string() + }) + .collect(); + let mut job = job(SidecarNaming::Stem); + let prepared = job.prepare_files(files, &AtomicBool::new(false)); + assert_eq!(prepared.items.len(), 6); + assert_eq!(job.listed.asked.load(Relaxed), 6, "each photo's sidecar is asked of the disk"); + let lookers = job.listed.lookers.lock().unwrap(); + assert!(!lookers.is_empty(), "no lookups were made"); + assert!(!lookers.contains(&std::thread::current().id()), "a lookup was made by the thread that plans the batch, one after another"); + drop(lookers); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a folder listed in the same clock tick as its files were made, when a sidecar is +/// written into it right after the listing and the folder's time reads as it did before (a +/// volume that keeps folder times to the second or two), then the import still reads it: a +/// time too recent to vouch for is not trusted. (The test puts the folder's time back.) +#[test] +fn a_sidecar_written_in_the_tick_of_the_listing_is_read() { + let root = scratch("racy"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + let at_listing = modified(&root).unwrap(); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap(); + set_folder_time(&root, at_listing); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + let found = ratings(job.prepare_files(files, &AtomicBool::new(false))); + assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Given a review whose listing was kept, when a listed file is replaced by a folder holding a +/// photo afterwards, then the import's expansion walks that folder: a name in a folder that +/// changed since it was listed is not trusted to still be a file. +#[test] +fn a_listed_file_replaced_by_a_folder_is_expanded() { + let root = scratch("replaced"); + for n in 0..3 { + std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap(); + } + settle(&root); + let mut walked = ListedFolders::default(); + let (files, _) = expand_knowing( + &[root.to_string_lossy().to_string()], + None, + crate::walk::Limits::default(), + Some(&mut |dir, names, complete, modified| { + walked.note(dir, names, complete, modified); + true + }), + true, + &|_| false, + ); + assert_eq!(files.len(), 3); + std::fs::remove_file(root.join("a1.jpg")).unwrap(); + std::fs::create_dir(root.join("a1.jpg")).unwrap(); + std::fs::write(root.join("a1.jpg").join("inside.jpg"), b"x").unwrap(); + let mut job = job(SidecarNaming::Stem).with_listed(walked); + // (the paths handed to the import are the files the review listed) + let found = job.expand(&files); + assert!(found.iter().any(|f| f.ends_with("inside.jpg")), "{found:?}"); + assert_eq!(found.len(), 3, "{found:?}"); + let _ = std::fs::remove_dir_all(&root); +} + +/// A folder noted with no time (too recent to vouch for, or the volume keeps none) is not +/// trusted, and finding that out costs no look at the disk. +#[test] +fn a_folder_without_a_listed_time_costs_no_look() { + let root = scratch("no-time"); + std::fs::write(root.join("a.jpg"), b"x").unwrap(); + let mut l = ListedFolders::default(); + l.note(&root, vec![("a.jpg".into(), crate::walk::EntryKind::File)], true, None); + assert!(!l.is_known_file(&root.join("a.jpg"))); + assert_eq!(l.looked.load(Relaxed), 0); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/engine/src/import/tests_pool.rs b/crates/engine/src/import/tests_pool.rs new file mode 100644 index 0000000000..3de4da6239 --- /dev/null +++ b/crates/engine/src/import/tests_pool.rs @@ -0,0 +1,477 @@ +//! The detached readers on their own ([`super::reads`]): the pool is driven with fake reads that hang, make progress, +//! panic and answer late, with no import around it. What a stalled read looks like to the person is up to whoever uses +//! the pool; these tests are about what the pool does: ✕, naming the stalled read, Skip, the cap, a late answer. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use super::reads::{MAX_SKIPPED, MAX_STUCK_READERS, Outcome, Pool, ReadWatch, StuckReaders, abandon_flag, progressed}; + +/// How long a read may go without progress before the tests call it stalled. Long next to anything a test does between +/// two signs of progress (a few milliseconds), so that a busy machine delaying a thread does not name a healthy read. +const STALL: Duration = Duration::from_millis(500); + +/// A read that does not answer until `open`. +#[derive(Clone, Default)] +struct Gate(Arc<(Mutex, Condvar)>); + +impl Gate { + fn wait(&self) { + let (open, bell) = &*self.0; + let mut open = open.lock().unwrap(); + while !*open { + open = bell.wait(open).unwrap(); + } + } + + fn open(&self) { + *self.0.0.lock().unwrap() = true; + self.0.1.notify_all(); + } +} + +fn stuck() -> Arc { + Arc::new(StuckReaders::new(MAX_STUCK_READERS)) +} + +/// A watch that looks every 10 ms (not 250) and counts its abandoned readers in `stuck`. +fn watch(stuck: &Arc) -> Arc { + let watch = ReadWatch::with_stuck(STALL, stuck.clone()); + watch.set_poll(Duration::from_millis(10)); + Arc::new(watch) +} + +/// Run `work` over `jobs` on `threads` readers, job `i` named "job"; results that arrive late go to `late`. +fn run( + watch: &ReadWatch, + cancel: &AtomicBool, + threads: usize, + jobs: Vec, + work: impl Fn(J) -> R + Send + Sync + 'static, + late: impl Fn(R) + Send + Sync + 'static, +) -> Vec> { + let pool = Pool { watch, cancel, name: "test-read", threads }; + pool.run(jobs, &|i| format!("job{i}"), Arc::new(work), Arc::new(late), Arc::new(|| {}), &|_| {}) +} + +/// [`run`] on a thread of its own, so that the test can watch it and press ✕ or Skip meanwhile. +fn run_in_background( + watch: &Arc, + cancel: &Arc, + threads: usize, + jobs: Vec, + work: impl Fn(J) -> R + Send + Sync + 'static, + late: impl Fn(R) + Send + Sync + 'static, +) -> JoinHandle>> { + let (watch, cancel) = (watch.clone(), cancel.clone()); + std::thread::spawn(move || run(&watch, &cancel, threads, jobs, work, late)) +} + +/// Wait for `condition` for up to 30 s (a hung test is worse than a slow one). +fn wait_until(what: &str, mut condition: impl FnMut() -> bool) { + let until = Instant::now() + Duration::from_secs(30); + while !condition() { + assert!(Instant::now() < until, "gave up waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Wait for a run started with [`run_in_background`] to end, for up to 30 s: a run that never ends fails the test +/// instead of hanging it. +fn join_within(handle: JoinHandle) -> R { + wait_until("the run to end", || handle.is_finished()); + handle.join().unwrap() +} + +fn is_skipped(outcome: &Outcome) -> bool { + matches!(outcome, Outcome::Failed(why) if why.starts_with("skipped: no answer after ")) +} + +#[test] +fn every_job_is_done_and_counted_in_its_own_slot() { + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let counted = AtomicUsize::new(0); + let pool = Pool { watch: &watch, cancel: &cancel, name: "test-read", threads: 3 }; + let outcomes = pool.run((0..10u32).collect(), &|i| format!("job{i}"), Arc::new(|n: u32| n * 2), Arc::new(|_| {}), Arc::new(|| {}), &|r| { + assert!(r.is_some()); + counted.fetch_add(1, Relaxed); + }); + let got: Vec = outcomes.iter().map(|o| if let Outcome::Done(n) = o { *n } else { u32::MAX }).collect(); + assert_eq!(got, (0..10).map(|n| n * 2).collect::>()); + assert_eq!(counted.load(Relaxed), 10); + assert_eq!((watch.skipped(), watch.ended(), watch.stalled()), (0, None, None)); + assert_eq!(stuck.alive(), 0); +} + +#[test] +fn a_panicking_job_fails_only_itself() { + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let outcomes = run( + &watch, + &cancel, + 2, + vec![1u32, 2, 3, 4], + |n| { + assert_ne!(n, 3, "a read that panics"); + n + }, + |_| {}, + ); + assert!(matches!(outcomes[0], Outcome::Done(1)) && matches!(outcomes[1], Outcome::Done(2)) && matches!(outcomes[3], Outcome::Done(4))); + assert!(matches!(&outcomes[2], Outcome::Failed(_)), "{:?}", outcomes[2]); + assert_eq!(watch.ended(), None, "one failed read does not end the run"); +} + +/// Given reads that hang, +/// When ✕ is pressed, +/// Then the run ends at once with what answered so far, the hung reads are left behind and the jobs still queued never +/// start. +#[test] +fn cancel_ends_the_run_while_reads_hang() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let (gate, started) = (Gate::default(), Arc::new(AtomicUsize::new(0))); + let (g, s) = (gate.clone(), started.clone()); + let run = run_in_background( + &watch, + &cancel, + 2, + (0..8u32).collect(), + move |n| { + s.fetch_add(1, Relaxed); + if n < 2 { + g.wait(); + } + n + }, + |_| {}, + ); + wait_until("both readers to be on a hung read", || started.load(Relaxed) == 2); + let pressed = Instant::now(); + cancel.store(true, Relaxed); + let outcomes = join_within(run); + assert!(pressed.elapsed() < Duration::from_secs(3), "the run took {:?} to end", pressed.elapsed()); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Unreached)), "{outcomes:?}"); + assert_eq!(started.load(Relaxed), 2, "no queued job was started"); + assert_eq!(stuck.alive(), 2, "the two readers that were left behind are counted"); + gate.open(); + wait_until("the readers left behind to exit", || stuck.alive() == 0); + assert_eq!(started.load(Relaxed), 2, "and they took no job on their way out"); +} + +/// Given a read that makes progress now and then for much longer than the stall time, +/// Then it is never named. +#[test] +fn a_slow_read_that_keeps_progressing_is_never_named() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![()], + |()| { + for _ in 0..120 { + std::thread::sleep(Duration::from_millis(20)); + progressed(); + } + }, + |_| {}, + ); + let mut named = None; + wait_until("the run to end", || { + named = named.take().or(watch.stalled()); + run.is_finished() + }); + assert!(matches!(join_within(run)[0], Outcome::Done(()))); + assert_eq!(named, None, "a read that goes on is not stalled (it ran for {:?}, the stall time is {STALL:?})", Duration::from_millis(2400)); +} + +/// Given a read that does not progress, +/// Then it is named after the stall time, and nothing is named once it answers. +#[test] +fn a_read_without_progress_is_named_until_it_answers() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + wait_until("the read to be named", || watch.stalled().is_some()); + let named = watch.stalled().unwrap(); + assert_eq!(named.what, "job0"); + assert!(named.waited >= STALL, "{named:?}"); + gate.open(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); + assert_eq!(watch.stalled(), None); +} + +/// Given two reads that both hang, +/// When Skip is asked for, +/// Then only the one that is named (the longest without progress) is given up, a fresh reader takes its place so that +/// the other jobs go on, and the other read is named next. +#[test] +fn skip_gives_up_only_the_read_that_is_named() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gates = [Gate::default(), Gate::default()]; + let hung = gates.clone(); + let late = Arc::new(Mutex::new(Vec::new())); + let l = late.clone(); + let reading = run_in_background( + &watch, + &cancel, + 2, + vec![0usize, 1, 2, 3], + move |n| { + if let Some(gate) = hung.get(n) { + gate.wait(); + } + n + }, + move |n| l.lock().unwrap().push(n), + ); + // (which of the two is named first depends on which reader took its job first) + wait_until("a read to be named", || watch.stalled().is_some()); + let first: usize = watch.stalled().unwrap().what.trim_start_matches("job").parse().unwrap(); + let second = 1 - first; + watch.skip(); + wait_until("the other read to be named after it", || watch.stalled().is_some_and(|s| s.what == format!("job{second}"))); + assert_eq!(watch.skipped(), 1); + gates[second].open(); + let outcomes = join_within(reading); + assert!(is_skipped(&outcomes[first]), "{:?}", outcomes[first]); + assert!(matches!(outcomes[second], Outcome::Done(n) if n == second), "the other hung read was not skipped: {:?}", outcomes[second]); + assert!(matches!(outcomes[2], Outcome::Done(2)) && matches!(outcomes[3], Outcome::Done(3)), "a fresh reader goes on"); + assert_eq!((watch.skipped(), watch.ended()), (1, None)); + assert_eq!(stuck.alive(), 1, "the given-up read is still blocked, and counted"); + assert!(late.lock().unwrap().is_empty()); + gates[first].open(); + wait_until("the given-up read to exit", || stuck.alive() == 0); +} + +/// Given a given-up read that answers after all, +/// Then its result goes to the late handler (which disposes of it: nothing is applied), and the job stays failed. +#[test] +fn a_late_answer_from_a_given_up_read_goes_to_the_late_handler() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let late = Arc::new(Mutex::new(Vec::new())); + let l = late.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![7u32, 8], + move |n| { + if n == 7 { + g.wait(); + } + n + }, + move |n| l.lock().unwrap().push(n), + ); + wait_until("job0 to be named", || watch.stalled().is_some()); + watch.skip(); + let outcomes = join_within(run); + assert!(is_skipped(&outcomes[0]) && matches!(outcomes[1], Outcome::Done(8)), "{outcomes:?}"); + gate.open(); + wait_until("the late answer", || !late.lock().unwrap().is_empty()); + assert_eq!(*late.lock().unwrap(), vec![7]); + assert!(is_skipped(&outcomes[0]), "the job stays failed"); + wait_until("the given-up read to exit", || stuck.alive() == 0); +} + +/// A Skip asked for when nothing has stalled, or for a read that answered meanwhile, gives up nothing. +#[test] +fn a_skip_with_nothing_stalled_does_nothing() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + |n| { + std::thread::sleep(Duration::from_millis(150)); + n + }, + |_| {}, + ); + watch.skip(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); + assert_eq!((watch.skipped(), watch.ended(), stuck.alive()), (0, None, 0)); + // and a request made before the next stall is not kept for it + let gate = Gate::default(); + let g = gate.clone(); + let run = run_in_background( + &watch, + &cancel, + 1, + vec![0u32], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + watch.skip(); + wait_until("the read to be named", || watch.stalled().is_some()); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(watch.skipped(), 0, "a Skip made while nothing was named is not kept"); + gate.open(); + assert!(matches!(join_within(run)[0], Outcome::Done(0))); +} + +/// Given a drive whose reads all hang, +/// When each stalled read is skipped as it is named, +/// Then the fourth skip ends the run with an error naming the last file, instead of leaving more threads blocked. +#[test] +fn the_fourth_skipped_read_ends_the_run() { + let (stuck, cancel) = (stuck(), Arc::new(AtomicBool::new(false))); + let watch = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let started = Arc::new(AtomicUsize::new(0)); + let s = started.clone(); + let run = run_in_background( + &watch, + &cancel, + 2, + (0..12u32).collect(), + move |n| { + s.fetch_add(1, Relaxed); + g.wait(); + n + }, + |_| {}, + ); + // (Skip is asked for only once every reader is on a read: the two first ones, then the replacement each Skip + // started, so that how many readers are left behind at the end does not depend on how quickly a thread starts) + wait_until("the run to end", || { + if watch.stalled().is_some() && started.load(Relaxed) == watch.skipped() + 2 { + watch.skip(); + } + run.is_finished() + }); + let outcomes = join_within(run); + assert_eq!(MAX_SKIPPED, 4); + assert_eq!(watch.skipped(), MAX_SKIPPED); + let why = watch.ended().expect("the run ended with an error"); + assert!(why.contains("not answering") && why.contains("job"), "{why}"); + assert_eq!(outcomes.iter().filter(|o| is_skipped(o)).count(), MAX_SKIPPED); + assert!(outcomes.iter().all(|o| is_skipped(o) || matches!(o, Outcome::Unreached)), "{outcomes:?}"); + // (the four given up, and the one reader still on a read when the run ended: it is left behind too, and no fifth + // reader was started) + assert_eq!(stuck.alive(), MAX_SKIPPED + 1); + gate.open(); + wait_until("the given-up reads to exit", || stuck.alive() == 0); +} + +/// Given too many given-up reads still blocked (of any run, on any drive), +/// Then a run does not start (and says why), and does once the reads let go. +#[test] +fn a_run_does_not_start_while_too_many_given_up_reads_are_blocked() { + let (stuck, cancel) = (Arc::new(StuckReaders::new(1)), Arc::new(AtomicBool::new(false))); + let first = watch(&stuck); + let gate = Gate::default(); + let g = gate.clone(); + let reading = run_in_background( + &first, + &cancel, + 1, + vec![0u32, 1], + move |n| { + g.wait(); + n + }, + |_| {}, + ); + wait_until("the read to be named", || first.stalled().is_some()); + first.skip(); + let outcomes = join_within(reading); + assert!(is_skipped(&outcomes[0]) && matches!(outcomes[1], Outcome::Unreached), "{outcomes:?}"); + let why = first.ended().expect("the cap ended the run"); + assert!(why.contains("still waiting"), "{why}"); + // another run, another watch, the same count + let second = watch(&stuck); + let started = Arc::new(AtomicUsize::new(0)); + let s = started.clone(); + let outcomes = run( + &second, + &cancel, + 2, + vec![1u32, 2], + move |n| { + s.fetch_add(1, Relaxed); + n + }, + |_| {}, + ); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Unreached)), "{outcomes:?}"); + assert_eq!(started.load(Relaxed), 0, "nothing was started"); + assert!(second.ended().is_some_and(|why| why.contains("still waiting"))); + gate.open(); + wait_until("the given-up read to exit", || stuck.alive() == 0); + let third = watch(&stuck); + let outcomes = run(&third, &cancel, 2, vec![1u32, 2], |n| n, |_| {}); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Done(_))), "{outcomes:?}"); +} + +/// Given an `init` that panics on every reader, +/// Then the jobs are still read: a reader that could not be set up is not left waiting for a job it never takes. +#[test] +fn a_panicking_init_does_not_strand_the_jobs() { + let stuck = stuck(); + let watch = watch(&stuck); + let pool_watch = watch.clone(); + let reading = std::thread::spawn(move || { + let cancel = AtomicBool::new(false); + let pool = Pool { watch: &pool_watch, cancel: &cancel, name: "test-read", threads: 2 }; + pool.run( + vec![1u32, 2, 3], + &|i| format!("job{i}"), + Arc::new(|n| n), + Arc::new(|_| {}), + Arc::new(|| panic!("a reader that cannot be set up")), + &|_| {}, + ) + }); + let outcomes = join_within(reading); + assert!(outcomes.iter().all(|o| matches!(o, Outcome::Done(_))), "{outcomes:?}"); +} + +/// `progressed` and the abandon flag belong to the pool's threads: elsewhere they do nothing. +#[test] +fn progress_and_the_abandon_flag_belong_to_the_pool_threads() { + progressed(); + assert!(abandon_flag().is_none()); + let (stuck, cancel) = (stuck(), AtomicBool::new(false)); + let watch = watch(&stuck); + let outcomes = run(&watch, &cancel, 1, vec![()], |()| abandon_flag().map(|f| f.load(Relaxed)), |_| {}); + assert!(matches!(outcomes[0], Outcome::Done(Some(false))), "{outcomes:?}"); +} + +#[test] +fn a_watch_calls_a_read_stalled_after_the_time_it_is_given() { + let watch = ReadWatch::default(); + assert_eq!(watch.stall_after(), super::STALL_AFTER); + watch.set_stall_after(Duration::from_secs(3)); + assert_eq!(watch.stall_after(), Duration::from_secs(3)); + assert_eq!((watch.stalled(), watch.skipped(), watch.ended()), (None, 0, None)); +} diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index aab839931b..298ff98746 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -67,6 +67,10 @@ pub struct ImportOptions { pub metadata_preset: Option, /// Copy: raws are copied as DNG (Copy as DNG). pub convert_dng: bool, + /// A duplicate by content is read as a new file is, its XMP sidecar included: the Lightroom + /// import makes a record of its own from it ([`Duplicate::file`], #2589). Any other import + /// skips it without looking up its sidecar (a round trip per name on a network share, #2954). + pub read_duplicates: bool, /// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5), /// applied to every imported photo *after* its XMP sidecar, camera default and import preset, /// as one more History step (`Import adjustments`). Only the named controls change; the recipe @@ -171,6 +175,11 @@ pub struct FileFacts { /// The capture time a file import gives it: the file's, else its XMP sidecar's, else the /// file's modification time. pub captured: Option, + /// The file's own orientation, when it states one ([`crate::media::ProbeInfo::orientation`]): it turns what its + /// sidecar's regions were drawn on, the photo as stored, upright (#2674). + pub orientation: Option, + /// Its XMP sidecar (or a raw's embedded XMP), which a file import merges into the record. + pub sidecar: Option, } #[derive(Clone, Debug, Default, Serialize)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd67b755f9..458f38b8fd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,6 +74,7 @@ pub mod print_pdf; pub mod profile_refs; pub mod proof; pub(crate) mod read_file; +pub mod relocate; pub mod rename; pub mod segment; pub mod sidecar; @@ -122,7 +123,7 @@ pub enum EngineError { /// The folder (or file) asked for is a Lightroom Classic catalog or part of one, not a /// LightCraft library (issue #891): nothing was created or opened. `catalog`: the `.lrcat` /// to import with `library.importLightroom`, when one was found. - #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File ▸ Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] + #[error("{} is a Lightroom Classic catalog, not a LightCraft library; import it into a LightCraft library with File → Import Lightroom Catalog…{}", path.display(), catalog.as_ref().map_or(String::new(), |c| format!(" ({})", c.display())))] LightroomCatalog { path: std::path::PathBuf, catalog: Option }, /// The work was cancelled (by the person, an agent or a newer request): not a failure. #[error("{0}")] @@ -143,7 +144,8 @@ pub struct UndoEntry { pub label: String, pub op: Op, /// A folder to rename on disk (`from` → `to`) before `op` is applied: Rename / Move Folder - /// (whose `op` relinks the photos inside). Never overwrites; refused when `to` exists. An + /// (whose `op` relinks the photos inside; a located folder, `on_disk: false`, renames nothing + /// and only follows). Never overwrites; refused when `to` exists. An /// empty `to` removes the (empty) folder `from`, an empty `from` creates `to` (Create Folder). pub folder: Option, /// Inverses of logged path corrections from a partially failed history step. @@ -174,16 +176,20 @@ fn single_photo(op: &Op, depth: usize) -> Option { } } -/// A folder renamed or moved on disk as part of an undo step. +/// A folder renamed or moved on disk as part of an undo step, or (`on_disk: false`) a folder +/// located where it already is, which moves no file. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FolderMove { pub from: String, pub to: String, + /// The step renames the folder on disk. `false` for a folder located where it already is + /// (`folder.updateLocation`): only the photos and the view follow, no file is touched. + pub on_disk: bool, } impl FolderMove { fn reversed(&self) -> Self { - Self { from: self.to.clone(), to: self.from.clone() } + Self { from: self.to.clone(), to: self.from.clone(), on_disk: self.on_disk } } } @@ -358,6 +364,9 @@ pub struct Session { pub print: print::template::PrintSettings, /// Saved print templates (`print.template.*`), persisted in prefs.json. pub print_templates: Vec, + /// The Template Browser's folders besides [`print::template::DEFAULT_FOLDER`], sorted by name + /// (`print.template.folder.*`), persisted in prefs.json. + pub print_template_folders: Vec, /// Metadata presets (`metadata.*`), persisted in prefs.json. pub metadata_presets: Vec, /// Saved filter-bar settings (`filter.*`), persisted in prefs.json. @@ -531,6 +540,7 @@ impl Session { export_presets: Vec::new(), print: Default::default(), print_templates: Vec::new(), + print_template_folders: Vec::new(), metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), @@ -882,17 +892,19 @@ impl Session { rename::validate_sidecars(fs, &entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; // 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() { + // the folder to rename on disk, if the step has one + let on_disk = entry.folder.as_ref().filter(|f| f.on_disk); + if on_disk.is_some() || !entry.retry_sidecars.is_empty() || !self.file_moves(&entry.op).is_empty() { 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 folder = entry.folder.as_ref(); - if let Some(f) = folder { + if let Some(f) = on_disk { cmd::browse::folder_on_disk(&f.from, &f.to).map_err(|e| EngineError::Other(format!("can't move the folder back: {e}")))?; } let undo_folder = || { - if let Some(f) = folder { + if let Some(f) = on_disk { let _ = cmd::browse::folder_on_disk(&f.to, &f.from); } }; @@ -911,8 +923,10 @@ impl Session { } match self.apply_catalog(op.clone()) { Ok(inv) => { - if let Some(f) = folder { - cmd::browse::follow_folder(self, &f.from, &f.to); + match folder { + Some(f) if f.on_disk => cmd::browse::follow_folder(self, &f.from, &f.to), + Some(f) => relocate::follow_located(self, &f.from, &f.to), + None => {} } if entry.retry_inverse.is_empty() { Ok(inv) diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index e0b7c496c4..daca499f6f 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -296,6 +296,8 @@ struct PrefsFile { export_presets: Vec, /// Print templates. print_templates: Vec, + /// Print Template Browser folders, empty ones included. + print_template_folders: Vec, /// Metadata presets. metadata_presets: Vec, /// Filter presets. @@ -635,6 +637,8 @@ impl Session { // (the built-ins are looked up first); it gets a name of its own instead self.rename_shadowing_export_presets(); self.print_templates = prefs.print_templates; + self.print_template_folders = prefs.print_template_folders; + crate::print::template::tidy_folders(&mut self.print_template_folders, &mut self.print_templates); self.metadata_presets = prefs.metadata_presets; self.filter_presets = prefs.filter_presets; self.curve_presets = prefs.curve_presets; @@ -957,6 +961,7 @@ impl Session { last_merge: self.last_merge.clone(), export_presets: self.export_presets.clone(), print_templates: self.print_templates.clone(), + print_template_folders: self.print_template_folders.clone(), metadata_presets: self.metadata_presets.clone(), filter_presets: self.filter_presets.clone(), curve_presets: self.curve_presets.clone(), diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index c92e0d4503..d6692d58d3 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -1255,8 +1255,8 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co // The new record takes only what the bytes determine from the photo with the same // bytes, never that photo's own state: not its Recently Deleted (#2589), virtual copy, // edits, history, versions, ratings, capture time or the metadata a person writes. Its - // metadata and capture time are what its own file gives it, as a file import reads them - // (copyright, creator…); the catalog's capture time, when it has one, applies on top. + // metadata and capture time are what its own file and XMP sidecar give it, as a file + // import reads them (copyright, caption, creator…); the catalog's apply on top. let name = Path::new(&src.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| src.path.clone()); let mut p = Photo::new( s.catalog.alloc_photo_id(), @@ -1275,25 +1275,27 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co p.embedded_lens = duplicate.embedded_lens; p.preview_only = duplicate.preview_only.clone(); p.preview_checked = duplicate.preview_checked.clone(); - if let Some(file) = file { - p.meta = file.meta.clone(); - p.captured = file.captured.clone(); - } else { + let file = file.cloned().unwrap_or_else(|| { // (the file wasn't read: only the exposure description, which no command edits; // not GPS, which placing a photo on the map does, nor the capture time, which // Edit Capture Time does) let m = &duplicate.meta; - p.meta.camera = m.camera.clone(); - p.meta.lens = m.lens.clone(); - p.meta.focal_mm = m.focal_mm; - p.meta.aperture = m.aperture; - p.meta.shutter = m.shutter.clone(); - p.meta.iso = m.iso; - p.meta.focus = m.focus.clone(); - } - // the settings a file import gives it (as-shot white balance, embedded lens - // corrections, the default preset); the catalog's settings apply on top - crate::import::apply_import_defaults(s, &mut p); + let meta = lightcraft_catalog::Meta { + camera: m.camera.clone(), + lens: m.lens.clone(), + focal_mm: m.focal_mm, + aperture: m.aperture, + shutter: m.shutter.clone(), + iso: m.iso, + focus: m.focus.clone(), + ..Default::default() + }; + crate::import::FileFacts { meta, ..Default::default() } + }); + // as a file import of it: its file's metadata and capture time, the import defaults + // (as-shot white balance, embedded lens corrections, the default preset), its XMP + // sidecar; the catalog's settings and metadata apply on top + crate::import::start_from_file(s, &mut p, file, &now); p } else { let id = s.catalog.alloc_photo_id(); diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 4218cb8513..0bdef04326 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -214,6 +214,8 @@ fn a_content_duplicate_of_a_trashed_photo_or_virtual_copy_is_a_new_live_photo() file: Some(Box::new(crate::import::FileFacts { meta: lightcraft_catalog::Meta { camera: "Same Camera".into(), ..Default::default() }, captured: None, + orientation: None, + sidecar: None, })), }], ..Default::default() @@ -356,6 +358,181 @@ fn a_content_duplicate_keeps_the_rights_metadata_and_capture_time_in_its_file() assert_eq!(new.captured.as_deref(), Some("2024-05-06T07:08:09"), "{r}"); std::fs::remove_dir_all(dir).unwrap(); } +/// A content duplicate's XMP sidecar goes into its new record as it does for a file import of it +/// (caption, copyright…) when the catalog doesn't restate them, also when its file has a capture +/// time of its own (#2589). +#[test] +fn a_content_duplicate_keeps_what_its_sidecar_says() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-duplicate-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Photos")).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(dir.join("Photos/test.ARW"), b"same bytes").unwrap(); + std::fs::write( + dir.join("Photos/test.xmp"), + r#" + +Harbour at dawn +© Sidecar Author +"#, + ) + .unwrap(); + std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap(); + let mut s = crate::Session::new(); + let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| p.meta.caption = "Other photo's caption".into()); + s.media.file_probe = Some(Arc::new(|_| { + Ok(crate::media::ProbeInfo { + format: "ARW".into(), + width: 20, + height: 10, + content_hash: Some("same-bytes".into()), + captured: Some("2024-05-06T07:08:09".into()), + ..Default::default() + }) + })); + let mut job = crate::lightroom_job::LightroomJob::new(&mut s, source, false).unwrap(); + let prepared = job.prepare(&AtomicBool::new(false)).unwrap(); + let r = crate::lightroom_job::commit_prepared(&mut s, prepared).unwrap().report; + let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}")); + assert_eq!((new.meta.caption.as_str(), new.meta.copyright.as_str()), ("Harbour at dawn", "© Sidecar Author"), "{r}"); + assert_eq!(new.captured.as_deref(), Some("2024-05-06T07:08:09"), "the file's own capture time: {r}"); + std::fs::remove_dir_all(dir).unwrap(); +} +/// A file that becomes a content duplicate only after it was prepared (another import added a photo +/// with its bytes while the catalog was read) is turned into one just before the commit +/// (`revalidate_add`); its new record keeps what its sidecar says all the same (#2589). +#[test] +fn a_file_that_turns_out_to_be_a_content_duplicate_at_commit_keeps_what_its_sidecar_says() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-late-duplicate-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Photos")).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(dir.join("Photos/test.ARW"), b"same bytes").unwrap(); + std::fs::write( + dir.join("Photos/test.xmp"), + r#" + +Harbour at dawn +© Sidecar Author +"#, + ) + .unwrap(); + std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap(); + let mut s = crate::Session::new(); + s.media.file_probe = Some(Arc::new(|_| { + Ok(crate::media::ProbeInfo { + format: "ARW".into(), + width: 20, + height: 10, + content_hash: Some("same-bytes".into()), + captured: Some("2024-05-06T07:08:09".into()), + ..Default::default() + }) + })); + // prepared while the library has no photo with the file's bytes: the file is ready to add + let mut job = crate::lightroom_job::LightroomJob::new(&mut s, source, false).unwrap(); + let prepared = job.prepare(&AtomicBool::new(false)).unwrap(); + // then a photo with the same bytes arrives before the commit (the library is still the one + // the job was prepared for: the commit checks its identity, not its photos) + let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| p.meta.caption = "Other photo's caption".into()); + let r = crate::lightroom_job::commit_prepared(&mut s, prepared).unwrap().report; + assert_eq!(s.catalog.photos().count(), 2, "{r}"); + let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}")); + assert_eq!((new.meta.caption.as_str(), new.meta.copyright.as_str()), ("Harbour at dawn", "© Sidecar Author"), "{r}"); + assert_eq!(s.catalog.photo(other).unwrap().meta.caption, "Other photo's caption", "{r}"); + std::fs::remove_dir_all(dir).unwrap(); +} +/// A content duplicate's sidecar regions drawn on its photo as stored (its stored size as +/// `AppliedToDimensions`, no `mwg-rs:Rotation`) land on the upright photo, turned by its file's own +/// orientation as a file import of it turns them (#2674): the record's size is its file's upright one, +/// and the catalog's orientation is a develop rotation on top of it (#2589). +#[test] +fn a_content_duplicates_sidecar_regions_are_turned_by_its_files_orientation() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-duplicate-regions-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Photos")).unwrap(); + let source = dir.join("source.lrcat"); + std::fs::write(dir.join("Photos/test.ARW"), b"same bytes").unwrap(); + std::fs::write( + dir.join("Photos/test.xmp"), + r#" + + + + + + + +"#, + ) + .unwrap(); + std::fs::write(&source, native_catalog(&photo_tables((dir.to_str().unwrap(), "")))).unwrap(); + let mut s = crate::Session::new(); + // stored 32 × 24, a quarter turn clockwise upright: 24 × 32 (the size the new record takes) + let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| (p.width, p.height) = (24, 32)); + s.media.file_probe = Some(Arc::new(|_| { + Ok(crate::media::ProbeInfo { + format: "ARW".into(), + width: 24, + height: 32, + content_hash: Some("same-bytes".into()), + captured: Some("2024-05-06T07:08:09".into()), + orientation: Some(lightcraft_geom::Orientation::Rotate90), + ..Default::default() + }) + })); + let mut job = crate::lightroom_job::LightroomJob::new(&mut s, source, false).unwrap(); + let prepared = job.prepare(&AtomicBool::new(false)).unwrap(); + let r = crate::lightroom_job::commit_prepared(&mut s, prepared).unwrap().report; + let new = s.catalog.photos().find(|p| p.id != other).unwrap_or_else(|| panic!("no new record: {r}")); + assert_eq!(new.meta.regions.len(), 1, "{r}"); + let b = new.meta.regions[0].rect; + let got = [b.x0, b.y0, b.x1, b.y1]; + assert!( + got.iter().zip([0.525, 0.2, 0.675, 0.3]).all(|(g, w)| (g - w).abs() < 1e-9), + "the box is where the photo as stored had the face: {got:?}" + ); + std::fs::remove_dir_all(dir).unwrap(); +} +/// Only the Lightroom import reads a content duplicate's XMP sidecar: any other import skips the +/// duplicate without looking its sidecar up (#2954), so the same file beside the same sidecar +/// reaches the report with no sidecar unless the import makes a record of it (#2589). +#[test] +fn only_an_import_that_makes_a_record_of_a_content_duplicate_reads_its_sidecar() { + let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-duplicate-skip-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("test.ARW"); + std::fs::write(&file, b"same bytes").unwrap(); + std::fs::write( + dir.join("test.xmp"), + r#" + +Harbour at dawn +"#, + ) + .unwrap(); + let paths = [file.to_string_lossy().into_owned()]; + for read_duplicates in [false, true] { + let mut s = crate::Session::new(); + let other = library_photo(&mut s, "/elsewhere/a.ARW", |p| p.meta.caption = "Other photo's caption".into()); + s.media.file_probe = + Some(Arc::new(|_| Ok(crate::media::ProbeInfo { format: "ARW".into(), content_hash: Some("same-bytes".into()), ..Default::default() }))); + let opts = crate::import::ImportOptions { read_duplicates, ..Default::default() }; + let r = crate::import::import_with(&mut s, &paths, &opts).unwrap(); + assert!(r.imported.is_empty() && s.catalog.photos().count() == 1, "{read_duplicates}: {r:?}"); + let [d] = r.duplicates.as_slice() else { panic!("{read_duplicates}: {r:?}") }; + assert_eq!((d.reason, d.existing), ("content", Some(other.0)), "{read_duplicates}"); + let caption = d.file.as_ref().and_then(|f| f.sidecar.as_ref()).and_then(|sc| sc.caption.clone()); + if read_duplicates { + assert_eq!(caption.as_deref(), Some("Harbour at dawn"), "the Lightroom import reads it: {r:?}"); + } else { + assert_eq!(caption, None, "a skipped duplicate's sidecar isn't looked up: {r:?}"); + } + } + std::fs::remove_dir_all(dir).unwrap(); +} /// A catalog photo matched (by path) to a library photo in Recently Deleted leaves it there, as /// the import was set up to do (a Lightroom import doesn't restore, see `OnDeleted`), and the report /// counts it so the photos don't go missing unexplained (#2589). A new virtual copy of it is diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index defdb850f0..7a039fe0f1 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -207,8 +207,10 @@ pub struct LightroomJob { impl LightroomJob { /// Snapshot session state only. This constructor performs no filesystem work. pub fn new(s: &mut crate::Session, path: PathBuf, update_existing: bool) -> crate::Result { - // a photo deleted here stays deleted: the catalog's record is matched, not restored - let opts = ImportOptions { mode: ImportMode::Add, on_deleted: crate::import::OnDeleted::Skip, ..ImportOptions::default() }; + // a photo deleted here stays deleted: the catalog's record is matched, not restored; a + // duplicate by content becomes a record of its own, so its file and sidecar are read (#2589) + let opts = + ImportOptions { mode: ImportMode::Add, on_deleted: crate::import::OnDeleted::Skip, read_duplicates: true, ..ImportOptions::default() }; let import = ImportJob::new(s, opts)?; let archive_dir = s.library.as_ref().filter(|library| library.on_disk).map(|library| library.dir.join("Interop")); let progress = LightroomProgress { diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index f7163b0693..c3d9047d3f 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -59,6 +59,7 @@ impl QuickJob { quick: None, display: None, frame: None, + slide_photo: None, }) } @@ -77,6 +78,7 @@ impl QuickJob { quick, display: None, frame: None, + slide_photo: None, }; let rendered = |image: Rgba8| { let histogram = Histogram::of_srgb8(&image); diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index af7d10e268..f9c7a2a204 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -91,6 +91,9 @@ pub struct RenderResult { /// The result as a texture on the window's GPU device ([`RenderJob::on_screen`]); `rendered` /// then holds its histogram and an empty image. pub frame: Option, + /// A slide job's result: the size in pixels of the photo's render the slide was composed + /// from, which sets where the slide's layout put the photo ([`RenderJob::with_slide`]). + pub slide_photo: Option<[usize; 2]>, } impl RenderJob { @@ -216,6 +219,7 @@ impl RenderJob { quick: None, display: None, frame: None, + slide_photo: None, } } @@ -235,6 +239,7 @@ impl RenderJob { let slide = self.slide.clone(); let mut r = self.run_photo(); if let (Some(slide), Ok(rendered)) = (slide, r.rendered.as_mut()) { + r.slide_photo = Some([rendered.image.width, rendered.image.height]); rendered.image = slide.compose(&rendered.image); rendered.deep = None; } @@ -291,6 +296,7 @@ impl RenderJob { quick: Some(QuickSource::Cached), display: None, frame: None, + slide_photo: None, }; } if let Some((cache, key)) = &self.cache @@ -310,6 +316,7 @@ impl RenderJob { quick: None, display: None, frame: None, + slide_photo: None, }; } // a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough @@ -331,6 +338,7 @@ impl RenderJob { quick: None, display: None, frame: None, + slide_photo: None, }; } let was_loaded = matches!(self.source, SourceRef::Loaded(_)); @@ -369,6 +377,7 @@ impl RenderJob { quick: None, display: None, frame: None, + slide_photo: None, }; } let pixels_needed = @@ -393,6 +402,7 @@ impl RenderJob { quick: None, display: None, frame: Some(frame), + slide_photo: None, }; } Some(OnScreen::Pixels(r)) => (r, None), @@ -453,6 +463,7 @@ impl RenderJob { quick: None, display, frame: None, + slide_photo: None, } } Err(e) => self.failed(e), diff --git a/crates/engine/src/print/template.rs b/crates/engine/src/print/template.rs index 7bb5336129..6a98aec5ad 100644 --- a/crates/engine/src/print/template.rs +++ b/crates/engine/src/print/template.rs @@ -38,6 +38,11 @@ const FILE_FORMAT: &str = "lightcraft.printTemplate"; const FILE_VERSION: u64 = 1; /// Largest template file read, bytes. pub const MAX_FILE: u64 = 256 * 1024; +/// The Template Browser folder a template is in until it is moved to another. It always exists +/// and can't be renamed or deleted. +pub const DEFAULT_FOLDER: &str = "User Templates"; +/// Most Template Browser folders kept, besides [`DEFAULT_FOLDER`]. +pub const MAX_FOLDERS: usize = 100; /// A saved print template: the layout, image settings, page and job of a print, without the /// photos assigned to cells and without the guides (a view preference). The settings are kept as @@ -47,9 +52,59 @@ pub const MAX_FILE: u64 = 256 * 1024; #[serde(rename_all = "camelCase")] pub struct PrintTemplate { pub name: String, + /// The Template Browser folder the template is listed in; `None`: [`DEFAULT_FOLDER`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, pub settings: serde_json::Value, } +/// A folder name: trimmed, 1 to [`MAX_NAME`] characters, no control characters, and not +/// [`DEFAULT_FOLDER`] in any case. +pub fn clean_folder(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) { + return Err(format!("a folder name is 1 to {MAX_NAME} characters without control characters")); + } + if name.eq_ignore_ascii_case(DEFAULT_FOLDER) { + return Err(format!("“{DEFAULT_FOLDER}” is always there; choose another name")); + } + Ok(name.to_string()) +} + +/// Sorts `folders` by name, ignoring case. +pub fn sort_folders(folders: &mut [String]) { + folders.sort_by_cached_key(|f| f.to_lowercase()); +} + +/// Makes folders and templates read from the preferences consistent: folders with a bad, reserved +/// or repeated name and those past [`MAX_FOLDERS`] are dropped; a template in a folder that isn't +/// listed gets the folder listed when its name is good and there is room, and goes to +/// [`DEFAULT_FOLDER`] otherwise; each template's folder takes the listed folder's spelling. +pub fn tidy_folders(folders: &mut Vec, templates: &mut [PrintTemplate]) { + let mut kept: Vec = Vec::new(); + for f in folders.iter() { + if let Ok(f) = clean_folder(f) + && kept.len() < MAX_FOLDERS + && !kept.iter().any(|k| k.eq_ignore_ascii_case(&f)) + { + kept.push(f); + } + } + for t in templates.iter_mut() { + let Some(f) = t.folder.take() else { continue }; + if let Some(k) = kept.iter().find(|k| k.eq_ignore_ascii_case(f.trim())) { + t.folder = Some(k.clone()); + } else if let Ok(f) = clean_folder(&f) + && kept.len() < MAX_FOLDERS + { + kept.push(f.clone()); + t.folder = Some(f); + } + } + sort_folders(&mut kept); + *folders = kept; +} + /// A template name: trimmed, 1 to [`MAX_NAME`] characters, no control characters. pub fn clean_name(name: &str) -> Result { let name = name.trim(); @@ -71,7 +126,7 @@ impl PrintTemplate { if let Some(o) = value.as_object_mut() { o.remove("guides"); } - Ok(Self { name: clean_name(name)?, settings: value }) + Ok(Self { name: clean_name(name)?, folder: None, settings: value }) } /// The settings, checked: unknown fields, hostile numbers and inconsistent layouts are errors. @@ -106,7 +161,7 @@ impl PrintTemplate { } let name = clean_name(v.get("name").and_then(serde_json::Value::as_str).ok_or("a print template file needs a `name`")?)?; let settings = v.get("settings").cloned().ok_or("a print template file needs `settings`")?; - let checked = PrintTemplate { name: name.clone(), settings }.settings(&Guides::default())?; + let checked = PrintTemplate { name: name.clone(), folder: None, settings }.settings(&Guides::default())?; Self::new(&name, &checked) } } @@ -163,7 +218,7 @@ mod tests { for name in ["", " ", "a\nb", &"x".repeat(MAX_NAME + 1)] { assert!(PrintTemplate::new(name, &PrintSettings::default()).is_err(), "{name:?}"); } - let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), settings: v }.settings(&Guides::default()).is_err(); + let bad = |v: serde_json::Value| PrintTemplate { name: "t".into(), folder: None, settings: v }.settings(&Guides::default()).is_err(); assert!(bad(json!("text"))); assert!(bad(json!({"surprise": 1}))); assert!(bad(json!({"job": {"ppi": 1e30}}))); diff --git a/crates/engine/src/relocate.rs b/crates/engine/src/relocate.rs new file mode 100644 index 0000000000..973e863f0d --- /dev/null +++ b/crates/engine/src/relocate.rs @@ -0,0 +1,618 @@ +//! Locating a library folder that is somewhere else now (`folder.updateLocation`, issues #1112 and #1116). +//! +//! A folder of the library can stop being where the library looks for it without LightCraft +//! having moved it: it was renamed or moved in the file manager, its disk is mounted under +//! another name, or its catalog came from another computer (a Lightroom catalog written on +//! Windows names `D:\Photos\…`, which is nowhere on Linux). Synchronize Folder can only say the +//! folder isn't there. Locating it says where it is now: every photo below the old folder (those +//! in the folders inside it and in Recently Deleted too) points at the same place below the new +//! one, and what the library knows about the folders (their colour labels) goes along. Only the +//! catalog changes; no file is touched, and it is one undo step. +//! +//! It is done in three parts, so the app never waits on a disk in a frame: +//! +//! 1. [`Relocation::new`] reads the request against the session: it works out where each photo's +//! file would be and refuses what needs no disk to refuse (no file-system access). It keeps +//! the places and what the library recorded of the files, not the library. +//! 2. [`Relocation::look`] reads the disk, never the session, so it can run on a worker thread: +//! it tells for each place whether the photo's file is there. +//! 3. [`Located::commit`] relinks the photos, on the session as it is by then. +//! +//! Looking is the guard against choosing the wrong folder (one level too high or too low is the +//! likely mistake), and a file being at a place does not make it the photo's ([`Sought`]): +//! +//! * a place that is, as the library has it, the file of another photo of the folder (the new +//! place is inside the folder, or the folder inside it) is taken only when the file's content +//! is the photo's. Otherwise the step is refused, whatever was asked: the photo would show +//! the other photo's picture under its own edits. The same file can be reached by many paths +//! (other letter case on a disk that doesn't tell case apart, a link at or below either +//! folder), so while the folder is still on disk where the library has it, the photos' files +//! are told by what they are on disk ([`FileId`]), not by how their paths are spelled; a +//! place written with `..` is refused. (One share mounted twice is two disks to this.) +//! * a file inside the folder that was only looked at in Local is taken for the library's photo +//! coming to its place when its content is the photo's, where the library recorded that; +//! * a file of another size than the library recorded is not the file it knew: it is not counted +//! as found; +//! * a folder with none of the files is not the folder, and one with only some of them (or with +//! files of another size) is taken only on request (`incomplete`). Files that aren't there +//! then stay missing at the new place, where Synchronize Folder finds them. +//! +//! Paths are compared by folder identity ([`lightcraft_catalog::query::folder_key`]), not by +//! [`std::path::Path`]: on Linux and macOS `D:\Photos\a.jpg` is one file name to `Path`. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering::Relaxed; +use std::sync::{Arc, Mutex, PoisonError}; + +use lightcraft_catalog::query::{folder_key, folder_rest}; +use lightcraft_catalog::{Catalog, Filter, Op, PhotoId, Sort, Source}; +use serde_json::{Value, json}; + +use crate::import::ScanProgress; +use crate::{EngineError, FolderMove, Result, Session}; + +fn invalid(msg: impl Into) -> EngineError { + EngineError::Other(msg.into()) +} + +/// A request to locate folder `from` at `to`, checked as far as the session alone can tell. +pub struct Relocation { + /// The folder as the library knows it. + pub from: String, + /// Where it is said to be now (absolute, spelled the way this computer spells paths). + pub to: String, + /// The photos that would follow the folder. + photos: Vec, + /// The places [`Relocation::look`] looks at. + files: Vec, + /// Which library that is ([`Located::commit`] is for no other). + library: Arc<()>, +} + +/// A place a file of the folder would be, and what tells whether the file there is the photo's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Sought { + pub path: String, + /// The size the library recorded for the file (0: none, as for photos of a catalog that + /// came from another app). + size: u64, + /// The contents the library recorded for the photos that would be here (a virtual copy + /// shares its photo's file); empty when it recorded none. + hashes: Vec, + /// Where the photos that would be here are now, as the library has them. + now: Vec, + /// The place is, as the library has it, the file of another photo of the folder: only its + /// content tells whose the file there is. + claimed: bool, + /// The place is a file of the folder that was only looked at in Local: nothing says it is + /// the photo's, so its content is asked where the library recorded the photo's. + browsed: bool, + /// A library photo's (not only one's in Recently Deleted or browsed in Local, which nobody + /// is looking for): counted in [`Located::total`]. + counted: bool, +} + +/// What is at a place ([`Sought`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Seen { + /// No file. + Missing, + /// A file of the size the library recorded (of the photo's content, at a claimed place). + Same, + /// A file, and the library recorded no size to tell by. + Unverified, + /// A file of another size. + Different, + /// A file at a claimed place that is not known to be the photo's. + Claimed, +} + +/// What a file is on disk, however its path is spelled. +#[cfg(unix)] +type FileId = (u64, u64); +#[cfg(not(unix))] +type FileId = PathBuf; + +/// What the file or folder at `path` is on disk (links followed), if it is there. +fn file_id(path: &Path, meta: Option<&std::fs::Metadata>) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let read; + let meta = match meta { + Some(m) => m, + None => { + read = std::fs::metadata(path).ok()?; + &read + } + }; + Some((meta.dev(), meta.ino())) + } + #[cfg(not(unix))] + { + // (no file id in std here: the path as the system spells it, links and letter case resolved) + let _ = meta; + std::fs::canonicalize(path).ok() + } +} + +/// The files of the folder's photos where the library has them now, by what they are on disk: +/// a file at the new place can be one of them under another path (a place inside the folder, a +/// link at or below either folder). Empty when the folder is not on disk where the library has +/// it (the usual case: nothing of `from` is looked at then). +fn files_now(photos: &[RelocatedPhoto], from: &str, progress: &ScanProgress) -> HashMap { + let mut out = HashMap::new(); + if file_id(Path::new(from), None).is_none() { + return out; + } + for r in photos { + if progress.cancel.load(Relaxed) { + break; + } + if let Some(id) = file_id(Path::new(&r.from), None) { + out.entry(id).or_insert_with(|| r.from.clone()); + } + } + out +} + +impl Sought { + /// What is at the place. `theirs`: the files of the folder's photos as they are on disk now + /// ([`files_now`]). + fn seen(&self, theirs: &HashMap) -> Seen { + let Ok(meta) = std::fs::metadata(&self.path) else { return Seen::Missing }; + if !meta.is_file() { + return Seen::Missing; + } + // another photo's file under another spelling of its path (a photo's own file, where + // the new place is another name for the folder itself, is its own) + let theirs = || { + !theirs.is_empty() && file_id(Path::new(&self.path), Some(&meta)).and_then(|id| theirs.get(&id)).is_some_and(|at| !self.now.contains(at)) + }; + if self.claimed || theirs() || (self.browsed && !self.hashes.is_empty()) { + // the photo's file has the photo's size and content (read only here, and in pieces: + // files shared by the two folders are rare, and reading every file of a folder on a + // network share takes hours) + let proven = !self.hashes.is_empty() + && (self.size == 0 || self.size == meta.len()) + && crate::cmd::missing::file_hash(&self.path).is_some_and(|c| self.hashes.iter().all(|h| *h == c)); + return if proven { Seen::Same } else { Seen::Claimed }; + } + match self.size { + 0 => Seen::Unverified, + n if n == meta.len() => Seen::Same, + _ => Seen::Different, + } + } +} + +/// What [`look_at`] saw at the places of the library's files. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Tally { + /// Files that are there and not known to be other files… + pub found: usize, + /// …those among them the library recorded no size for. + pub unverified: usize, + /// Files there of another size than the library recorded. + pub different: usize, + /// Claimed places whose file is not known to be the photo's, and one of them. + claimed: usize, + claimed_example: Option, +} + +/// One photo of the folder and where its file is once the folder is located. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RelocatedPhoto { + pub id: PhotoId, + /// Its file as the library has it; a photo that has left it by [`Located::commit`] is skipped. + pub from: String, + pub to: String, +} + +/// What [`Relocation::look`] found: the photos that would follow the folder, and how many of +/// the library's files are at the new place. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Located { + pub from: String, + pub to: String, + pub photos: Vec, + /// Files of library photos (not those in Recently Deleted or only browsed in Local; a + /// virtual copy shares its photo's file) that are at the new place and not known to be + /// other files… + pub found: usize, + /// …of this many. + pub total: usize, + /// Those of `found` the library recorded no size for: a file is there, and nothing tells + /// whether it is the photo's. + pub unverified: usize, + /// Files at the new place of another size than the library recorded (not in `found`). + pub different: usize, + /// The library the photos are of: one opened meanwhile is not touched. + library: Arc<()>, +} + +impl Relocation { + /// Read a request to locate folder `path` of the library at `to`. Refused: the startup disk, + /// a folder no library photo was imported from, a whole disk or a folder that holds disks + /// without `disk` (as for Synchronize Folder), the place the library already looks, and the + /// library's own folder, and a place where a file is already another photo's (one not of + /// this folder; two photos would share one file). No file-system access. + pub fn new(s: &Session, path: &str, to: &str, disk: bool) -> Result { + if cfg!(target_arch = "wasm32") { + // (no disk to look at: every folder would be "not a folder") + return Err(invalid("locating a folder is not supported in the web version: it has no disk to look for the photos' files on")); + } + if path.trim().is_empty() { + return Err(invalid("missing `folder`")); + } + if to.trim().is_empty() { + return Err(invalid("missing `path`")); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(invalid("choose a folder, not the whole startup disk")); + } + let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + let ids = s.catalog.query(&f, &Sort::default()); + if ids.is_empty() { + return Err(invalid(format!("{path}: no photo in the library was imported from it"))); + } + if !disk && (lightcraft_catalog::folders::is_disk_root(path) || crate::cmd::library::covers_other_disks(s, path, &ids)) { + return Err(invalid(format!("{path} is a whole disk or holds disks: pass `disk: true` to locate it"))); + } + let abs = std::path::absolute(to).map_err(|e| invalid(format!("{to}: {e}")))?; + // (one place has one spelling to compare by: `a/b/../b` is not told from `a/b` as written) + if abs.components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return Err(invalid(format!("{to}: give the folder's full path, without `..`"))); + } + // (rebuilt from its parts: no trailing separator, so the photos' paths are joined cleanly) + let abs: PathBuf = abs.components().collect(); + let to = abs.to_string_lossy().to_string(); + if folder_key(path) == folder_key(&to) { + return Err(invalid(format!("{to} is where the library already looks for this folder"))); + } + if s.library.as_ref().is_some_and(|l| l.on_disk && abs.starts_with(&l.dir)) { + return Err(invalid(format!("{to} is inside the library's own folder, which is no place for photos"))); + } + let Destinations { photos, files } = destinations(&s.catalog, path, &to); + let moving: HashSet = photos.iter().map(|r| r.id).collect(); + let places: HashSet = photos.iter().map(|r| r.to.clone()).collect(); + // (said before any file is looked for; [`Located::commit`] asks again of the library as it is then) + giving_way(&s.catalog, &moving, &places, &to).map_err(invalid)?; + Ok(Relocation { from: path.to_string(), to, photos, files, library: Arc::clone(&s.library_identity) }) + } + + /// Whether the folder's files are at the new place. Reads the disk, never the session. + /// Refused when `to` is not a folder, or when a file there is another photo's of this + /// folder and not known to be the photo's that would point at it ([`Sought`]). + /// + /// `progress` counts the places looked at; with its `cancel` set the looking stops early + /// and is refused: what was seen until then says nothing. + pub fn look(self, progress: &ScanProgress) -> std::result::Result { + let Relocation { from, to, photos, files, library } = self; + if !Path::new(&to).is_dir() { + return Err(format!("{to} is not a folder")); + } + let total = files.iter().filter(|f| f.counted).count(); + let theirs = files_now(&photos, &from, progress); + // (a place only a photo in Recently Deleted or a kept Local record would point at is + // looked at where a file there can be another photo's) + let files: Vec = files.into_iter().filter(|f| f.counted || f.claimed || !theirs.is_empty()).collect(); + let Tally { found, unverified, different, claimed, claimed_example } = look_at(&files, &theirs, progress); + if progress.cancel.load(Relaxed) { + // (places not looked at may be other photos' files: what was seen says nothing) + return Err("locating the folder was stopped: nothing was changed".to_string()); + } + if let Some(first) = claimed_example { + let n = claimed; + let (s, verb, is) = if n == 1 { ("", "belongs", "is") } else { ("s", "belong", "are") }; + return Err(format!( + "{n} file{s} in {to} {verb} to other photos of this folder, or {is} another picture than the library recorded for the photo, as far as the library can tell (such as {first}): choose the folder its files are in now. \ + (The folder as the library has it and the chosen one share files; a file there is taken for a photo only when the library recorded the photo's content and the file has it.)" + )); + } + Ok(Located { from, to, photos, found, total, unverified, different, library }) + } + + /// The places [`Relocation::look`] looks at (tests). + #[cfg(test)] + pub(crate) fn files(&self) -> &[Sought] { + &self.files + } +} + +/// Where the photos of a folder would be, and the places to look at. +struct Destinations { + photos: Vec, + /// Each place once (a virtual copy shares its photo's file). + files: Vec, +} + +fn destinations(catalog: &Catalog, from: &str, to: &str) -> Destinations { + let base = PathBuf::from(to); + let mut photos: Vec = Vec::new(); + let mut files: Vec = Vec::new(); + let mut at: HashMap = HashMap::new(); + // A record of only having looked at a file in Local is no photo of the folder: it stays (the + // place on disk did not move), and gives way where a photo of the library comes to its file + // ([`giving_way`]) — also when that file is in a folder inside this one. + let browsed: HashSet = catalog + .photos() + .filter(|p| p.local && !p.deleted) + .filter_map(|p| match &p.source { + Source::File { path } if folder_rest(path, from).is_some() => Some(path.clone()), + _ => None, + }) + .collect(); + let looked: HashSet = catalog.local_records_of(&browsed).untouched.into_iter().collect(); + let mut looked_at: HashSet<&str> = HashSet::new(); + for p in catalog.photos() { + let Source::File { path } = &p.source else { continue }; + if looked.contains(&p.id) { + looked_at.insert(path.as_str()); + continue; + } + let Some(rest) = folder_rest(path, from).filter(|r| !r.is_empty()) else { continue }; + // joined by the platform, so the result is spelled like a path read from this disk + let dest = rest.iter().fold(base.clone(), |d, name| d.join(name)).to_string_lossy().to_string(); + let i = *at.entry(dest.clone()).or_insert_with(|| { + files.push(Sought { path: dest.clone(), size: 0, hashes: Vec::new(), now: Vec::new(), claimed: false, browsed: false, counted: false }); + files.len() - 1 + }); + if let Some(f) = files.get_mut(i) { + f.counted |= p.in_library(); + if !f.now.contains(path) { + f.now.push(path.clone()); + } + if f.size == 0 { + f.size = p.file_size; + } + if let Some(h) = crate::cmd::missing::stored_hash(p).filter(|h| !f.hashes.iter().any(|x| x == h)) { + f.hashes.push(h.to_string()); + } + } + photos.push(RelocatedPhoto { id: p.id, from: path.clone(), to: dest }); + } + // a place one of the photos is at now is that photo's file, as far as the library knows + let now: HashSet<&str> = photos.iter().map(|r| r.from.as_str()).collect(); + for f in &mut files { + f.claimed = now.contains(f.path.as_str()); + f.browsed = looked_at.contains(f.path.as_str()); + } + Destinations { photos, files } +} + +/// The records that give way when the photos `moving` point at `places` (every place one of +/// them would be, the library's or not), so that no file has two records: Local records of +/// those files that are only a record of having looked ([`Catalog::local_records_of`]). +/// Refused when a place is another photo's already — a library photo's, or one's in Recently +/// Deleted (restoring it would make two) — or a Local record's that holds something of the +/// person's. Paths are compared as written, as everywhere in the library. +fn giving_way(catalog: &Catalog, moving: &HashSet, places: &HashSet, to: &str) -> std::result::Result, String> { + let taken: Vec<&str> = catalog + .photos() + .filter(|p| (!p.local || p.deleted) && !moving.contains(&p.id)) + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.as_str()), + _ => None, + }) + .filter(|f| places.contains(*f)) + .collect(); + if let Some(first) = taken.first() { + let n = taken.len(); + let are = if n == 1 { "is" } else { "are" }; + return Err(format!( + "{n} file{} in {to} {are} already in the library, Recently Deleted included (such as {first}): the folder can't be located there", + plural(n) + )); + } + let local = catalog.local_records_of(places); + let kept: Vec<&(PhotoId, String)> = local.kept.iter().filter(|(id, _)| !moving.contains(id)).collect(); + if let Some((_, first)) = kept.first() { + let n = kept.len(); + let were = if n == 1 { "was" } else { "were" }; + return Err(format!( + "{n} file{} in {to} {were} rated, edited or put in an album while browsing it in Local (such as {first}): the library's photos can't take their place", + plural(n) + )); + } + Ok(local.untouched.into_iter().filter(|id| !moving.contains(id)).collect()) +} + +fn plural(n: usize) -> &'static str { + if n == 1 { "" } else { "s" } +} + +/// What is at each of `files`, looked at on several threads (a network share answers each +/// slowly). `progress.total` / `done` follow; stops early when `progress.cancel` is set, with +/// what was seen so far. +pub fn look_at(files: &[Sought], theirs: &HashMap, progress: &ScanProgress) -> Tally { + use std::sync::atomic::AtomicUsize; + progress.total.store(files.len(), Relaxed); + progress.done.store(0, Relaxed); + if cfg!(target_arch = "wasm32") { + return Tally::default(); + } + let cancel = &progress.cancel; + let (found, unverified, different, claimed, next) = + (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let example: Mutex> = Mutex::new(None); + let work = || { + while !cancel.load(Relaxed) { + let Some(f) = files.get(next.fetch_add(1, Relaxed)) else { break }; + match f.seen(theirs) { + Seen::Claimed => { + claimed.fetch_add(1, Relaxed); + example.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(|| f.path.clone()); + } + // (a place only a photo in Recently Deleted or a Local record would point at is + // looked at for whose file it is, not counted) + _ if !f.counted => {} + Seen::Same => { + found.fetch_add(1, Relaxed); + } + Seen::Unverified => { + found.fetch_add(1, Relaxed); + unverified.fetch_add(1, Relaxed); + } + Seen::Different => { + different.fetch_add(1, Relaxed); + } + Seen::Missing => {} + } + progress.done.fetch_add(1, Relaxed); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + let n = crate::import::workers(files.len()); + if n > 1 { + std::thread::scope(|sc| { + // (a thread the system won't start: the others, or this one, do its share) + let started = (0..n).filter(|_| std::thread::Builder::new().spawn_scoped(sc, work).is_ok()).count(); + if started == 0 { + work(); + } + }); + } else { + work(); + } + } + #[cfg(target_arch = "wasm32")] + work(); + Tally { + found: found.into_inner(), + unverified: unverified.into_inner(), + different: different.into_inner(), + claimed: claimed.into_inner(), + claimed_example: example.into_inner().unwrap_or_else(PoisonError::into_inner), + } +} + +impl Located { + /// Why this is not (or not plainly) the folder, if it isn't: none of the files are there, or + /// only some (the others are not there, or are of another size than the library recorded) + /// and `incomplete` wasn't said. + pub fn refusal(&self, incomplete: bool) -> Option { + let Located { from, to, found, total, different, .. } = self; + // files of another size are said: they are what tells a disk laid out alike from the folder + let others = match *different { + 0 => String::new(), + 1 => "; 1 file there is not the one the library recorded (another size)".to_string(), + n => format!("; {n} files there are not the ones the library recorded (another size)"), + }; + if *found == 0 { + return Some(format!( + "none of the {total} file{} of {from} {} in {to}{others}: choose the folder it is now", + plural(*total), + if *total == 1 { "is" } else { "are" } + )); + } + (found < total && !incomplete).then(|| { + format!( + "only {found} of the {total} files of {from} are in {to}{others}: pass `incomplete: true` to locate it there anyway (files that aren't there stay missing)" + ) + }) + } + + /// Point the photos at the new place, with the folders' records, as one undo step (undo and + /// redo move no file). Checked against the session as it is now: a photo that is no longer + /// where [`Relocation::look`] saw it (relinked or removed meanwhile) is left alone, and what + /// is at the new place is asked again. Records of files there that were only browsed in + /// Local, untouched, go as the library's photos take their place (a file has one record; + /// otherwise Synchronize Folder would offer every file as new); undo brings them back. + /// → `{folder, path, relinked, found, unverified, different, notFound, replacedLocal}`. + pub fn commit(self, s: &mut Session, incomplete: bool) -> Result { + // (photo ids mean something else in another library) + if !Arc::ptr_eq(&self.library, &s.library_identity) { + return Err(invalid("another library was opened meanwhile: the folder was not located")); + } + if let Some(why) = self.refusal(incomplete) { + return Err(invalid(why)); + } + let Located { from, to, photos, found, total, unverified, different, .. } = self; + let before = s.visible_cloned(); + let mut ops: Vec = Vec::new(); + let mut moving: HashSet = HashSet::new(); + let mut places: HashSet = HashSet::new(); + for r in photos { + let Some(p) = s.catalog.photo(r.id) else { continue }; + if !matches!(&p.source, Source::File { path } if *path == r.from) { + continue; + } + moving.insert(r.id); + places.insert(r.to.clone()); + ops.push(Op::Relink { id: r.id, file_name: p.file_name.clone(), source: Source::File { path: r.to }, format: None }); + } + let relinked = ops.len(); + if relinked == 0 { + return Err(invalid(format!("{from} holds no photo any more: the library changed meanwhile"))); + } + // the library may have changed while the files were looked for (a folder browsed, a photo + // imported or relinked): what is at the new place is asked of it as it is now + let replaced = giving_way(&s.catalog, &moving, &places, &to).map_err(invalid)?; + // what the library knows about the folder (and those inside it) goes along, in the same + // step; what it knows about folders already at the new place stays + ops.extend(s.catalog.folder_records_located(&from, &to)); + ops.extend(replaced.iter().map(|id| Op::RemovePhoto { id: *id })); + let name = lightcraft_catalog::folders::folder_label(&to); + // (the undo direction: the new place → the old one; nothing is renamed on disk) + let back = FolderMove { from: to.clone(), to: from.clone(), on_disk: false }; + s.commit_with_folder(&format!("Locate Folder “{name}”"), Op::Batch { ops }, back)?; + follow_located(s, &from, &to); + if !replaced.is_empty() { + crate::cmd::library::select_after_deletion(s, &before); + } + Ok(json!({ + "folder": from, + "path": to, + "relinked": relinked, + "found": found, + "unverified": unverified, + "different": different, + "notFound": total.saturating_sub(found).saturating_sub(different), + "replacedLocal": replaced.len(), + })) + } +} + +/// After a folder was located (`from` → `to`), or that was undone: a library folder being shown +/// (as the source or in the filter) at or below `from` is shown at the same place below `to`, +/// if its photos left it. One that still holds photos is another folder that was there all +/// along (a folder of the library at the new place, chosen since) and stays. A folder browsed +/// in Local is a place on disk, which did not move, and stays too. +pub(crate) fn follow_located(s: &mut Session, from: &str, to: &str) { + let moved = |s: &Session, chosen: &Option| -> Option { + let c = chosen.as_deref()?; + let rest = folder_rest(c, from)?; + let f = Filter { library_folder: Some(c.to_string()), ..Default::default() }; + if !s.catalog.query(&f, &Sort::default()).is_empty() { + return None; + } + Some(rest.iter().fold(PathBuf::from(to), |p, name| p.join(name)).to_string_lossy().to_string()) + }; + if let Some(now) = moved(s, &s.library_folder) { + s.library_folder = Some(now); + } + if let Some(now) = moved(s, &s.filter.library_folder) { + s.filter.library_folder = Some(now); + } + if let Some(f) = s.shelved_filter.as_ref() + && let Some(now) = moved(s, &f.library_folder) + && let Some(f) = s.shelved_filter.as_mut() + { + f.library_folder = Some(now); + } +} + +/// The three parts in one go, on the calling thread, for a caller whose thread is its own to +/// spend: the `folder.updateLocation` command of the CLI and headless MCP (registered with the +/// app's part of this feature, which does the looking on a worker thread instead). +pub fn relocate(s: &mut Session, path: &str, to: &str, disk: bool, incomplete: bool) -> Result { + let plan = Relocation::new(s, path, to, disk)?; + let task = s.activity.start("relocate", "Locating folder", crate::activity::Cancel::No); + task.detail(&lightcraft_catalog::folders::folder_label(&plan.from)); + let located = plan.look(&ScanProgress::default()).map_err(invalid)?; + drop(task); + located.commit(s, incomplete) +} diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index 8b165245b1..d1677498ea 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -38,9 +38,9 @@ mod plan; mod sidecar; mod tokens; -pub(crate) use fs::{MoveFs, RealFs}; #[cfg(test)] -use fs::{folded_path, same_contents}; +use fs::{LIST_FOLDER_AT, ListedSources, folded_path, same_contents}; +pub(crate) use fs::{MoveFs, RealFs}; pub(crate) use moves::move_all; #[cfg(test)] pub(crate) use moves::move_file_with; @@ -71,5 +71,9 @@ pub struct RenamePlan { pub to_path: Option, } +#[cfg(test)] +#[path = "rename/tests_listed_sources.rs"] +mod tests_listed_sources; + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/engine/src/rename/fs.rs b/crates/engine/src/rename/fs.rs index 30b6a3e30c..52a86e7545 100644 --- a/crates/engine/src/rename/fs.rs +++ b/crates/engine/src/rename/fs.rs @@ -1,5 +1,5 @@ use super::sidecar::PacketVersion; -use super::{Path, PathBuf, SidecarNaming}; +use super::{HashMap, HashSet, Path, PathBuf, SidecarNaming}; /// Every sidecar that may belong to `path` (both naming conventions, `.xmp` and `.XMP`). pub(super) fn sidecars(path: &str) -> Vec<(PathBuf, SidecarNaming, bool)> { @@ -41,6 +41,18 @@ pub(crate) trait MoveFs { Err(_) => true, } } + /// The names in folder `dir`, or `None` when it can't be listed or holds more than `budget` + /// entries (it stops reading at that many, so a huge folder is never collected). + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { + let mut names = Vec::new(); + for entry in std::fs::read_dir(dir).ok()? { + if names.len() == budget { + return None; + } + names.push(entry.ok()?.file_name()); + } + Some(names) + } /// Content observed in a packet, independent of its pathname or inode. Model volumes /// override this; disk implementations stream a bounded buffer without retaining the XML. fn packet_version(&self, path: &Path) -> std::io::Result { @@ -199,6 +211,134 @@ fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result { + inner: &'a dyn MoveFs, + /// folder → the `.xmp` names in it, lower-cased. + pub(super) folders: std::cell::RefCell>>, +} + +impl<'a> ListedSources<'a> { + pub(super) fn new(inner: &'a dyn MoveFs, moves: &[(String, String)]) -> Self { + Self::with_budget(inner, moves, LIST_ENTRIES_AT_MOST) + } + + /// As [`Self::new`], with at most `budget` directory entries listed over all folders. + pub(super) fn with_budget(inner: &'a dyn MoveFs, moves: &[(String, String)], mut budget: usize) -> Self { + let mut leaving: HashMap<&Path, usize> = HashMap::new(); + for (from, _) in moves { + if let Some(dir) = Path::new(from).parent().filter(|d| !d.as_os_str().is_empty()) { + *leaving.entry(dir).or_default() += 1; + } + } + let mut folders = HashMap::new(); + for (dir, n) in leaving { + if n < LIST_FOLDER_AT { + continue; + } + let Some(names) = inner.list_dir(dir, budget) else { continue }; + // (an override that lists more than the budget it was given breaks the contract: not trusted) + let Some(left) = budget.checked_sub(names.len()) else { continue }; + budget = left; + // (any name that is no ASCII text: the listing can't say what another name's other case is) + let xmp: Option> = names + .iter() + .map(|n| n.to_str().filter(|n| n.is_ascii()).map(str::to_ascii_lowercase)) + .collect::>>() + .map(|v| v.into_iter().filter(|n| n.ends_with(".xmp")).collect()); + if let Some(xmp) = xmp { + folders.insert(dir.to_path_buf(), xmp); + } + } + ListedSources { inner, folders: std::cell::RefCell::new(folders) } + } + + /// Whether the listing shows `p`, a sidecar name, is not there. + fn surely_absent(&self, p: &Path) -> bool { + let folders = self.folders.borrow(); + let (Some(xmp), Some(name)) = (p.parent().and_then(|d| folders.get(d)), p.file_name().and_then(|n| n.to_str())) else { return false }; + p.to_str().is_some_and(|s| s.ends_with(name)) + && name.len() > ".xmp".len() + && name.to_ascii_lowercase().ends_with(".xmp") + && crate::sync::plain_name(name) + && !crate::sync::asks_the_disk(name) + && !xmp.contains(&name.to_ascii_lowercase()) + } + + /// A file arrived at `p`: a `.xmp` joins its folder's names (one that leaves changes nothing: + /// a name listed that is gone is asked about, and found missing, as before). + fn arrived(&self, p: &Path) { + let Some(dir) = p.parent() else { return }; + let mut folders = self.folders.borrow_mut(); + let Some(xmp) = folders.get_mut(dir) else { return }; + match p.file_name().and_then(|n| n.to_str()).filter(|n| n.is_ascii()) { + Some(name) if name.to_ascii_lowercase().ends_with(".xmp") => { + xmp.insert(name.to_ascii_lowercase()); + } + Some(_) => {} + None => { + folders.remove(dir); + } + } + } +} + +impl MoveFs for ListedSources<'_> { + fn exists(&self, p: &Path) -> bool { + self.inner.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + !self.surely_absent(p) && self.inner.is_file(p) + } + fn same_file(&self, a: &Path, b: &Path) -> bool { + self.inner.same_file(a, b) + } + fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + let moved = self.inner.rename_no_replace(a, b); + if moved.is_ok() { + self.arrived(b); + } + moved + } + fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { + let copied = self.inner.copy_no_replace(a, b); + if copied.is_ok() { + self.arrived(b); + } + copied + } + fn remove_file(&self, p: &Path) -> std::io::Result<()> { + self.inner.remove_file(p) + } + fn stem_sibling(&self, sidecar: &Path) -> Option { + self.inner.stem_sibling(sidecar) + } + fn listed(&self, p: &Path) -> bool { + self.inner.listed(p) + } + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { + self.inner.list_dir(dir, budget) + } + fn packet_version(&self, path: &Path) -> std::io::Result { + self.inner.packet_version(path) + } +} + /// Move `a` to `b` on another volume: copy (never replacing), compare the copy with the original /// byte for byte, and only then remove the original. A copy that doesn't match is removed. fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> { diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 07d7fdfc3d..88ffc75fb1 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -1,4 +1,4 @@ -use super::fs::{MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars}; +use super::fs::{ListedSources, MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars}; use super::sidecar::{RetainedPacket, SidecarMove, advance_packets, note_companions, packet_aliases}; use super::{HashMap, HashSet, Op, Path, PathBuf, SidecarNaming, Source}; @@ -123,6 +123,8 @@ 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> { + let listed = ListedSources::new(fs, moves); + let fs: &dyn MoveFs = &listed; let mut done: Vec<&(String, String)> = Vec::new(); for m in moves { let Err(e) = move_file_with(fs, &m.0, &m.1) else { diff --git a/crates/engine/src/rename/tests_listed_sources.rs b/crates/engine/src/rename/tests_listed_sources.rs new file mode 100644 index 0000000000..394f87419f --- /dev/null +++ b/crates/engine/src/rename/tests_listed_sources.rs @@ -0,0 +1,201 @@ +//! Moving photos out of a folder asks the disk for their sidecars only where a listing of the +//! folder leaves room for one: on a network share each name asked about is a round trip. +use super::*; +use std::cell::Cell; + +/// The disk, counting the questions about `.xmp` names and the listings. +struct Counting { + can_list: bool, + /// `list_dir` returns every name whatever the budget (an override that breaks the contract). + ignores_budget: bool, + xmp_asked: Cell, + listings: Cell, +} + +impl Counting { + fn new(can_list: bool) -> Self { + Counting { can_list, ignores_budget: false, xmp_asked: Cell::new(0), listings: Cell::new(0) } + } + + fn ignoring_the_budget() -> Self { + Counting { ignores_budget: true, ..Counting::new(true) } + } +} + +impl MoveFs for Counting { + fn exists(&self, p: &Path) -> bool { + RealFs.exists(p) + } + fn is_file(&self, p: &Path) -> bool { + if p.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) { + self.xmp_asked.set(self.xmp_asked.get() + 1); + } + 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<()> { + 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) + } + fn list_dir(&self, dir: &Path, budget: usize) -> Option> { + self.listings.set(self.listings.get() + 1); + let budget = if self.ignores_budget { usize::MAX } else { budget }; + if self.can_list { RealFs.list_dir(dir, budget) } else { None } + } +} + +fn scratch(tag: &str) -> (PathBuf, PathBuf) { + let root = std::env::temp_dir().join(format!("lc-listed-sources-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (from, to) = (root.join("from"), root.join("to")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::create_dir_all(&to).unwrap(); + (from, to) +} + +/// `n` photos `p00.jpg`… in `from`, moved to `to` under the same names. +fn moves(from: &Path, to: &Path, n: usize) -> Vec<(String, String)> { + (0..n) + .map(|i| { + let name = format!("p{i:02}.jpg"); + (from.join(&name).to_string_lossy().to_string(), to.join(name).to_string_lossy().to_string()) + }) + .collect() +} + +fn names_lower(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_lowercase()).collect(); + v.sort(); + v +} + +/// Given 50 photos in a folder without sidecars, when they are moved, then no sidecar name is +/// asked of the disk (it was eight questions for each photo), and the folder is listed once. +#[test] +fn photos_leaving_a_listed_folder_without_sidecars_ask_the_disk_nothing() { + let (from, to) = scratch("none"); + for (src, _) in moves(&from, &to, 50) { + std::fs::write(src, b"x").unwrap(); + } + let fs = Counting::new(true); + move_all(&fs, &moves(&from, &to, 50)).unwrap(); + assert_eq!((fs.xmp_asked.get(), fs.listings.get()), (0, 1)); + assert_eq!(names_lower(&to).len(), 50); + assert!(names_lower(&from).is_empty()); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} + +/// Given sidecars in every case and naming among the photos, when they are moved and moved back +/// (undo), then each goes with its photo each way, and only the photos that have one are asked +/// about. +#[test] +fn sidecars_in_the_listing_move_with_their_photos_and_back() { + let (from, to) = scratch("cases"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + // stem and full names, in lower and upper case (the spellings a move looks for) + for sc in ["p00.xmp", "p01.XMP", "p02.jpg.xmp", "p03.jpg.XMP"] { + std::fs::write(from.join(sc), b"").unwrap(); + } + let before = names_lower(&from); + let fs = Counting::new(true); + move_all(&fs, &all).unwrap(); + assert!(names_lower(&from).is_empty(), "everything left, sidecars with their photos: {:?}", names_lower(&from)); + assert_eq!(names_lower(&to), before); + // (the four photos with a sidecar are asked about; the eight others are not) + assert!(fs.xmp_asked.get() > 0 && fs.xmp_asked.get() < 12 * 8, "{}", fs.xmp_asked.get()); + + let back: Vec<(String, String)> = all.iter().map(|(a, b)| (b.clone(), a.clone())).collect(); + move_all(&fs, &back).unwrap(); + assert_eq!(names_lower(&from), before); + assert!(names_lower(&to).is_empty()); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} + +/// A folder that can't be listed, and one with too few photos to list, keep the probes: a +/// sidecar there is still moved with its photo. +#[test] +fn a_folder_that_cannot_be_listed_or_is_too_small_is_probed_photo_by_photo() { + for (can_list, photos) in [(false, 12), (true, LIST_FOLDER_AT - 1)] { + let (from, to) = scratch("probed"); + let all = moves(&from, &to, photos); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + let fs = Counting::new(can_list); + move_all(&fs, &all).unwrap(); + assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "{can_list} {photos}"); + assert!(fs.xmp_asked.get() >= photos * 4, "each photo is probed: {}", fs.xmp_asked.get()); + assert_eq!(fs.listings.get(), usize::from(can_list && photos >= LIST_FOLDER_AT) + usize::from(!can_list), "{can_list} {photos}"); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); + } +} + +/// Given a folder that holds more entries than the listing budget, when its photos are moved, +/// then the folder is not collected (the read stops at the budget) and each photo's sidecar is +/// still probed and moved with it. +#[test] +fn a_folder_past_the_listing_budget_is_not_listed_and_is_probed_photo_by_photo() { + let (from, to) = scratch("budget"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + // 13 entries: 12 photos and a sidecar + assert!(RealFs.list_dir(&from, 12).is_none(), "one entry past the budget"); + assert_eq!(RealFs.list_dir(&from, 13).map(|n| n.len()), Some(13), "a budget of exactly its size lists it"); + + let fs = Counting::new(true); + let listed = ListedSources::with_budget(&fs, &all, 12); + assert!(listed.folders.borrow().is_empty(), "the folder is past the budget"); + let listed = ListedSources::with_budget(&fs, &all, 13); + assert_eq!(listed.folders.borrow().len(), 1, "and within it, listed"); + + // the move itself goes photo by photo: every photo asks the disk, the sidecar still follows + let probing = Counting::new(true); + let listed = ListedSources::with_budget(&probing, &all, 12); + for (a, b) in &all { + move_file_with(&listed, a, b).unwrap(); + } + assert!(probing.xmp_asked.get() >= 12 * 4, "each photo is probed: {}", probing.xmp_asked.get()); + assert!(names_lower(&to).contains(&"p00.xmp".to_string())); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} + +/// Given a `list_dir` override that returns more names than the budget it was given (the trait +/// documents `None` then), when the listing is collected, then the folder is skipped: the budget +/// neither underflows nor wraps, and the photos' sidecars are probed one by one as before. +#[test] +fn a_listing_larger_than_its_budget_is_skipped_not_counted_below_zero() { + let (from, to) = scratch("overlist"); + let all = moves(&from, &to, 12); + for (src, _) in &all { + std::fs::write(src, b"x").unwrap(); + } + std::fs::write(from.join("p00.XMP"), b"").unwrap(); + + let fs = Counting::ignoring_the_budget(); + let listed = ListedSources::with_budget(&fs, &all, 5); + assert_eq!(fs.listings.get(), 1, "the folder was asked for"); + assert!(listed.folders.borrow().is_empty(), "13 names against a budget of 5: not trusted"); + + for (a, b) in &all { + move_file_with(&listed, a, b).unwrap(); + } + assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "the sidecar still follows its photo"); + let _ = std::fs::remove_dir_all(from.parent().unwrap()); +} diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index 1e4bf6e8d9..8b90382b8e 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -385,7 +385,7 @@ fn render(job: &mut Job) -> Result { Err(e) => { return Err(match &job.missing { Some(path) => format!( - "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. Library ▸ Find Missing Photos can relink it." + "This photo's file is missing (moved or deleted), so it can't be analyzed for AI masks: {path}. File → Find Missing Photos… can relink it." ), None => format!("couldn't render the photo for AI masks: {e}"), }); diff --git a/crates/engine/src/slide_template/tests.rs b/crates/engine/src/slide_template/tests.rs index 9d3e9c807b..241e069929 100644 --- a/crates/engine/src/slide_template/tests.rs +++ b/crates/engine/src/slide_template/tests.rs @@ -39,7 +39,11 @@ fn ids(s: &mut Session) -> Vec { /// A look different from the defaults in every section. fn custom(s: &mut Session) { - run(s, "slideshow.playback", json!({"slideDuration": 7.5, "fadeDuration": 0.5, "fadeColor": "#102030", "randomOrder": true, "repeat": false})); + run( + s, + "slideshow.playback", + json!({"slideDuration": 7.5, "fadeDuration": 0.5, "fadeColor": "#102030", "randomOrder": true, "repeat": false, "panAndZoom": true, "panAndZoomAmount": 0.8}), + ); run( s, "slideshow.layout", diff --git a/crates/engine/src/slide_title.rs b/crates/engine/src/slide_title.rs index 0acda876d1..e59e61fe13 100644 --- a/crates/engine/src/slide_title.rs +++ b/crates/engine/src/slide_title.rs @@ -364,6 +364,7 @@ impl TitleCompose { display: None, gpu_fallback: None, frame: None, + slide_photo: None, } } } diff --git a/crates/engine/src/slideshow.rs b/crates/engine/src/slideshow.rs index 0e1c1294de..9b14d5708a 100644 --- a/crates/engine/src/slideshow.rs +++ b/crates/engine/src/slideshow.rs @@ -1,6 +1,6 @@ //! Slideshow playback: the settings of Lightroom Classic's Playback panel and the timeline that //! plays the photos in view (durations, fades, random order, repeat, pause, stepping, manual -//! advance), between an optional intro and ending screen (the Titles panel, +//! advance, pan and zoom), between an optional intro and ending screen (the Titles panel, //! [`crate::slide_title`]). //! //! No UI here: [`Playback`] is a pure state machine driven with injected times (seconds on any @@ -14,6 +14,7 @@ //! with the `slideshow.playback` command. use lightcraft_catalog::PhotoId; +use lightcraft_slideshow::{Motion, View}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -23,7 +24,7 @@ pub const SLIDE_MAX: f64 = 120.0; /// Longest fade (seconds); a fade is never longer than the slide duration. pub const FADE_MAX: f64 = 10.0; -/// How playback runs (Lightroom Classic's Playback panel, without music and pan & zoom). +/// How playback runs (Lightroom Classic's Playback panel, without music). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PlaybackSettings { @@ -43,6 +44,10 @@ pub struct PlaybackSettings { /// Manual slideshow: a slide stays up until ← / → (or the controls) change it; the slide /// duration is not used for playback then. pub manual: bool, + /// Pan and zoom: each photo moves and zooms slowly over its slide's time, on its own path. + pub pan_and_zoom: bool, + /// How much it moves: 0 (Low) to 1 (High). + pub pan_and_zoom_amount: f64, } impl Default for PlaybackSettings { @@ -55,18 +60,22 @@ impl Default for PlaybackSettings { repeat: true, prepare_previews: true, manual: false, + pan_and_zoom: false, + pan_and_zoom_amount: 0.5, } } } impl PlaybackSettings { - /// The settings with every value in range (a non-finite duration takes the default; the fade - /// is never longer than the slide). + /// The settings with every value in range (a non-finite duration or amount takes the default; + /// the fade is never longer than the slide). pub fn sanitized(mut self) -> Self { let d = PlaybackSettings::default(); self.slide_duration = if self.slide_duration.is_finite() { self.slide_duration.clamp(SLIDE_MIN, SLIDE_MAX) } else { d.slide_duration }; let fade = if self.fade_duration.is_finite() { self.fade_duration } else { d.fade_duration }; self.fade_duration = fade.clamp(0.0, FADE_MAX).min(self.slide_duration); + self.pan_and_zoom_amount = + if self.pan_and_zoom_amount.is_finite() { self.pan_and_zoom_amount.clamp(0.0, 1.0) } else { d.pan_and_zoom_amount }; self } @@ -79,6 +88,8 @@ impl PlaybackSettings { "repeat": self.repeat, "preparePreviews": self.prepare_previews, "manual": self.manual, + "panAndZoom": self.pan_and_zoom, + "panAndZoomAmount": self.pan_and_zoom_amount, }) } @@ -96,9 +107,14 @@ impl PlaybackSettings { "repeat" => s.repeat = boolean(k, v)?, "preparePreviews" => s.prepare_previews = boolean(k, v)?, "manual" => s.manual = boolean(k, v)?, + "panAndZoom" => s.pan_and_zoom = boolean(k, v)?, + "panAndZoomAmount" => match v.as_f64() { + Some(x) if (0.0..=1.0).contains(&x) => s.pan_and_zoom_amount = x, + _ => return Err(format!("`{k}` must be a finite number from 0 (low) to 1 (high), not {v}")), + }, other => { return Err(format!( - "unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual)" + "unknown setting `{other}` (slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual, panAndZoom, panAndZoomAmount)" )); } } @@ -229,6 +245,16 @@ pub struct Frame { pub fade_color: Option<[u8; 3]>, } +/// The pan and zoom views at a moment of playback (`None`: the slide shows its whole picture, as +/// a title screen always does, and every slide when pan and zoom is off). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PanZoom { + /// The current slide's view. + pub current: Option, + /// The view of the slide being faded out: where its motion ended. + pub from: Option, +} + /// Where the timeline is: the intro, the photos, or the ending. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Phase { @@ -261,6 +287,13 @@ pub struct Playback { started: f64, /// The slide fading out (until the transition ends). from: Option, + /// The pan and zoom key of the slide fading out. + from_key: Option, + /// Times a single photo repeating has started over (each time on a new path). + reps: u64, + /// Where a single repeating photo's last path ended: its new path starts there, so the + /// picture does not jump when it starts over. + rep_start: Option, /// Paused at this time. paused_at: Option, ended: bool, @@ -319,6 +352,9 @@ impl Playback { ending: None, started: now, from: None, + from_key: None, + reps: 0, + rep_start: None, paused_at: None, ended: false, held: None, @@ -516,8 +552,11 @@ impl Playback { } let Some(next) = self.upcoming(1).first().copied() else { if self.settings.repeat { - // a single photo repeating: nothing to change to + // a single photo repeating: nothing to change to (its pan and zoom starts again, + // on a new path from where the last one ended) + self.rep_start = self.motion(self.current()).map(|m| m.end); self.started = now; + self.reps = self.reps.wrapping_add(1); return Tick::Idle; } self.ended = true; @@ -529,14 +568,67 @@ impl Playback { } self.held = None; let old = self.current(); + let old_key = self.motion_key(old); let t = self.advance(); if let Tick::Advanced(new) = t { self.started = now; self.from = (self.fade_to(new) > 0.0).then_some(old); + self.from_key = self.from.and(old_key); + self.rep_start = None; } t } + /// The pan and zoom path of `item` up now (`None` for a title screen): from its key, starting + /// where the last path ended when a single photo repeats. + fn motion(&self, item: Item) -> Option { + let m = Motion::new(self.motion_key(item)?, self.settings.pan_and_zoom_amount); + Some(Motion { start: self.rep_start.unwrap_or(m.start), ..m }) + } + + /// The pan and zoom key of `item` up in the current pass (`None` for a title screen): the + /// seed, the pass, the photo and the repeats of a single photo, so every photo has its own + /// path, a new one in each pass, and the same seed plays the same paths. + fn motion_key(&self, item: Item) -> Option { + let photo = item.photo()?; + let mut st = self.seed ^ 0x7061_6e7a_6f6f_6d00; + for v in [self.pass, photo.0, self.reps] { + st = splitmix(&mut st) ^ v; + } + Some(splitmix(&mut st)) + } + + /// Where each slide's picture is at `now` with pan and zoom on: the current photo moves from + /// its start view (as it comes up, its fade in included) to its end view over its duration, + /// frozen while paused and held at the start in a manual slideshow (no slide is ever due + /// there); a photo fading out stays at its end view. Both are `None` with pan and zoom off. + pub fn pan_zoom(&self, now: f64) -> PanZoom { + if !self.settings.pan_and_zoom { + return PanZoom { current: None, from: None }; + } + let amount = self.settings.pan_and_zoom_amount; + let current = self.current(); + let t = if self.settings.manual { + 0.0 + } else { + let d = self.duration(current); + if d > 0.0 { (self.clock(now) - self.started) / d } else { 1.0 } + }; + let from = self.frame(now).from.and(self.from_key).map(|k| Motion::new(k, amount).at(1.0)); + PanZoom { current: self.motion(current).map(|m| m.at(t)), from } + } + + /// Whether pan and zoom moves the current photo at `now`: on, playing (not paused, not a + /// manual slideshow), a photo up and its time not over. A slide whose time is over while the + /// next one is not ready yet stays at its end view. + pub fn pan_zoom_moving(&self, now: f64) -> bool { + self.settings.pan_and_zoom + && self.paused_at.is_none() + && !self.settings.manual + && self.current().photo().is_some() + && self.remaining(now) > 0.0 + } + /// What to draw at `now`. pub fn frame(&self, now: f64) -> Frame { let now = self.clock(now); @@ -597,6 +689,8 @@ impl Playback { t = Tick::Advanced(self.current()); } self.from = None; + self.from_key = None; + self.rep_start = None; self.held = None; self.started = now; if self.paused_at.is_some() { diff --git a/crates/engine/src/slideshow/tests.rs b/crates/engine/src/slideshow/tests.rs index d329d5993d..b0acee1afe 100644 --- a/crates/engine/src/slideshow/tests.rs +++ b/crates/engine/src/slideshow/tests.rs @@ -212,6 +212,205 @@ fn a_manual_slideshow_moves_only_with_the_arrows() { assert!(d.merged(&json!({"manual": "yes"})).is_err()); } +#[test] +fn pan_and_zoom_moves_each_photo_over_its_slide_on_its_own_path() { + // off: every slide shows its whole picture + let p = Playback::new(ids(3), None, settings(4.0, 1.0), 1, 0.0).unwrap(); + assert_eq!(p.pan_zoom(2.0), PanZoom { current: None, from: None }); + + let s = PlaybackSettings { pan_and_zoom: true, repeat: true, ..settings(4.0, 1.0) }; + let mut p = Playback::new(ids(3), None, s.clone(), 9, 0.0).unwrap().with_titles(Some(2.0), None); + assert_eq!(p.pan_zoom(1.0).current, None, "a title screen doesn't move"); + assert_eq!(p.tick(2.0, all_ready), Tick::Advanced(ph(1))); + let m1 = Motion::new(p.motion_key(ph(1)).unwrap(), 0.5); + assert_eq!(p.pan_zoom(2.0).current, Some(m1.start), "a photo comes up at its start view"); + assert_eq!(p.pan_zoom(2.5).from, None, "the intro fading out doesn't move either"); + assert_eq!(p.pan_zoom(4.0).current, Some(m1.at(0.5)), "half way through its 4 s, fade in included"); + // paused: frozen + p.toggle_pause(4.0); + assert_eq!(p.pan_zoom(100.0).current, Some(m1.at(0.5))); + p.toggle_pause(100.0); + assert_eq!(p.pan_zoom(101.0).current, Some(m1.at(0.75)), "and carries on from there"); + // the next photo: its own path from its start; the one fading out stays at its end view + assert_eq!(p.tick(102.0, all_ready), Tick::Advanced(ph(2))); + let z = p.pan_zoom(102.5); + let m2 = Motion::new(p.motion_key(ph(2)).unwrap(), 0.5); + assert_ne!(m1, m2, "every photo has its own path"); + assert_eq!(z.current, Some(m2.at(0.125))); + assert_eq!(z.from, Some(m1.end)); + assert_eq!(p.pan_zoom(103.5).from, None, "after the fade"); + // a slide that is due but not ready holds its end view + assert_eq!(p.tick(106.0, |i| i != ph(3)), Tick::Waiting(ph(3))); + assert_eq!(p.pan_zoom(110.0).current, Some(m2.end)); + // the same seed plays the same paths; another seed other ones + let q = Playback::new(ids(3), None, s.clone(), 9, 0.0).unwrap(); + assert_eq!(q.motion_key(ph(1)).map(|k| Motion::new(k, 0.5)), Some(m1)); + let r = Playback::new(ids(3), None, s, 10, 0.0).unwrap(); + assert_ne!(r.motion_key(ph(1)), q.motion_key(ph(1))); +} + +#[test] +fn pan_and_zoom_paths_change_each_pass_and_hold_in_a_manual_slideshow() { + let s = PlaybackSettings { pan_and_zoom: true, repeat: true, ..settings(4.0, 1.0) }; + // a new pass: a new path for the same photo + let mut p = Playback::new(ids(2), None, PlaybackSettings { fade_duration: 0.0, ..s.clone() }, 9, 0.0).unwrap(); + let first = p.pan_zoom(0.0).current; + p.tick(4.0, all_ready); + assert_eq!(p.tick(8.0, all_ready), Tick::Advanced(ph(1))); + assert_ne!(p.pan_zoom(8.0).current, first, "a fresh path in the next pass"); + // a single photo repeating starts again on a new path + let mut p = Playback::new(ids(1), None, s.clone(), 9, 0.0).unwrap(); + let first = p.pan_zoom(0.0).current; + let ended = p.pan_zoom(4.0).current; + assert_eq!(p.tick(4.0, all_ready), Tick::Idle); + assert_ne!(p.pan_zoom(4.0).current, first); + assert_eq!(p.pan_zoom(4.0).current, ended, "the new path starts where the last one ended: no jump"); + let second_end = p.pan_zoom(8.0).current; + assert_ne!(second_end, ended, "and goes somewhere new"); + assert_eq!(p.tick(8.0, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(8.0).current, second_end, "again"); + assert_ne!(p.pan_zoom(12.0).current, second_end); + // the amount sets the zoom + let close = |amount: f64| { + let p = Playback::new(ids(1), None, PlaybackSettings { pan_and_zoom_amount: amount, ..s.clone() }, 9, 0.0).unwrap(); + let m = Motion::new(p.motion_key(ph(1)).unwrap(), amount); + m.start.zoom.max(m.end.zoom) + }; + assert!(close(1.0) > close(0.0)); + // the playback view follows the path for its amount + let view = |amount: f64| { + let p = Playback::new(ids(1), None, PlaybackSettings { pan_and_zoom_amount: amount, ..s.clone() }, 9, 0.0).unwrap(); + let m = Motion::new(p.motion_key(ph(1)).unwrap(), amount); + let (a, b) = (p.pan_zoom(0.0).current.unwrap(), p.pan_zoom(100.0).current.unwrap()); + assert_eq!((a, b), (m.at(0.0), m.at(1.0)), "the view at amount {amount} starts and ends on its path"); + a.zoom.max(b.zoom) + }; + assert!(view(1.0) > view(0.5) && view(0.5) > view(0.0), "the amount sets the zoom of the playback view"); + // a manual slideshow holds each photo at its start view; ← / → start the next one there + let mut p = Playback::new(ids(3), None, PlaybackSettings { manual: true, ..s }, 9, 0.0).unwrap(); + let start = Motion::new(p.motion_key(ph(1)).unwrap(), 0.5).start; + assert_eq!(p.pan_zoom(500.0).current, Some(start)); + p.step(1, 500.0); + assert_eq!(p.pan_zoom(900.0).current, Some(Motion::new(p.motion_key(ph(2)).unwrap(), 0.5).start)); +} + +#[test] +fn pan_and_zoom_settings_round_trip_and_are_checked() { + let d = PlaybackSettings::default(); + assert!(!d.pan_and_zoom, "off by default"); + assert_eq!(d.pan_and_zoom_amount, 0.5); + let m = d.merged(&json!({"panAndZoom": true, "panAndZoomAmount": 0.8})).unwrap(); + assert!(m.pan_and_zoom); + assert_eq!((m.to_json()["panAndZoom"].clone(), m.to_json()["panAndZoomAmount"].clone()), (json!(true), json!(0.8))); + for out in [json!(3), json!(-1), json!(1.0001), json!(-0.0001)] { + assert!(d.merged(&json!({"panAndZoomAmount": out})).is_err(), "{out} is outside 0 to 1"); + } + assert_eq!(d.merged(&json!({"panAndZoomAmount": 0})).unwrap().pan_and_zoom_amount, 0.0); + assert_eq!(d.merged(&json!({"panAndZoomAmount": 1})).unwrap().pan_and_zoom_amount, 1.0); + let saved = PlaybackSettings { pan_and_zoom_amount: 3.0, ..d.clone() }.sanitized(); + assert_eq!(saved.pan_and_zoom_amount, 1.0, "a saved value outside the range is clamped when read"); + assert!(d.merged(&json!({"panAndZoom": "on"})).is_err()); + assert!(d.merged(&json!({"panAndZoomAmount": "high"})).is_err()); + let s = PlaybackSettings { pan_and_zoom_amount: f64::NAN, ..d.clone() }.sanitized(); + assert_eq!(s.pan_and_zoom_amount, 0.5, "not finite: the default"); + let off = d.merged(&json!({"panAndZoomAmount": 0.2, "panAndZoom": false})).unwrap(); + assert_eq!(off.pan_and_zoom_amount, 0.2, "the amount is kept with the effect off"); +} + +#[test] +fn pan_and_zoom_shows_the_start_the_middle_and_the_end_of_a_slide() { + let s = PlaybackSettings { pan_and_zoom: true, ..settings(4.0, 1.0) }; + let mut p = Playback::new(ids(2), None, s, 5, 10.0).unwrap(); + let first = p.current(); + let m = Motion::new(p.motion_key(first).unwrap(), 0.5); + assert_ne!(m.start, m.end, "the photo moves"); + assert_eq!(p.tick(10.0, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(10.0).current, Some(m.start), "at 0"); + let half = p.pan_zoom(12.0).current.unwrap(); + assert_eq!(half, m.at(0.5), "half way"); + for (a, b, mid) in [(m.start.zoom, m.end.zoom, half.zoom), (m.start.x, m.end.x, half.x), (m.start.y, m.end.y, half.y)] { + assert!((mid - (a + b) / 2.0).abs() < 1e-12, "half way along the path: {half:?}"); + } + assert_eq!(p.tick(13.99, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(14.0).current, Some(m.end), "at the end"); + assert_eq!(p.pan_zoom(30.0).current, Some(m.end), "a slide that runs over stays at its end"); + let Tick::Advanced(next) = p.tick(14.0, all_ready) else { panic!("the next slide comes up at 14") }; + let m2 = Motion::new(p.motion_key(next).unwrap(), 0.5); + assert_eq!(p.pan_zoom(14.0), PanZoom { current: Some(m2.start), from: Some(m.end) }, "the next one starts at its start"); +} + +#[test] +fn pan_and_zoom_moves_only_while_a_photo_plays_out_its_time() { + let s = PlaybackSettings { pan_and_zoom: true, ..settings(4.0, 1.0) }; + let mut p = Playback::new(ids(2), None, s.clone(), 5, 0.0).unwrap(); + for now in [0.0, 2.0, 3.99] { + assert!(p.pan_zoom_moving(now), "moving at {now}"); + } + // its time is over and the next slide is not ready: it holds its end view, so nothing moves + let next = p.upcoming(1)[0]; + assert_eq!(p.tick(4.0, |i| i != next), Tick::Waiting(next)); + assert!(!p.pan_zoom_moving(4.0) && !p.pan_zoom_moving(9.0)); + assert_eq!(p.tick(9.0, all_ready), Tick::Advanced(next)); + assert!(p.pan_zoom_moving(9.0), "the next photo moves"); + p.toggle_pause(10.0); + assert!(!p.pan_zoom_moving(11.0), "paused"); + let off = Playback::new(ids(2), None, settings(4.0, 1.0), 5, 0.0).unwrap(); + assert!(!off.pan_zoom_moving(1.0), "off"); + let manual = Playback::new(ids(2), None, PlaybackSettings { manual: true, ..s.clone() }, 5, 0.0).unwrap(); + assert!(!manual.pan_zoom_moving(1.0), "a manual slideshow holds its start view"); + let titled = Playback::new(ids(2), None, s, 5, 0.0).unwrap().with_titles(Some(2.0), None); + assert!(!titled.pan_zoom_moving(1.0), "a title screen does not move"); +} + +#[test] +fn pan_and_zoom_stops_while_paused_and_carries_on_after() { + let s = PlaybackSettings { pan_and_zoom: true, ..settings(4.0, 1.0) }; + let mut p = Playback::new(ids(2), None, s, 5, 0.0).unwrap(); + let m1 = Motion::new(p.motion_key(p.current()).unwrap(), 0.5); + assert!(p.toggle_pause(1.0)); + for now in [1.0, 2.0, 50.0] { + assert_eq!(p.pan_zoom(now).current, Some(m1.at(0.25)), "paused at {now}"); + } + assert_eq!(p.tick(50.0, all_ready), Tick::Idle, "no slide change while paused"); + assert!(!p.toggle_pause(50.0)); + assert_eq!(p.pan_zoom(50.0).current, Some(m1.at(0.25)), "it resumes where it stopped"); + assert_eq!(p.pan_zoom(52.0).current, Some(m1.at(0.75))); + assert_eq!(p.tick(52.99, all_ready), Tick::Idle); + let Tick::Advanced(next) = p.tick(53.0, all_ready) else { panic!("the slide had 3 s left after the pause") }; + let m2 = Motion::new(p.motion_key(next).unwrap(), 0.5); + // paused during the fade: both photos hold their views, and the fade waits too + assert!(p.toggle_pause(53.5)); + assert_eq!(p.pan_zoom(80.0), PanZoom { current: Some(m2.at(0.125)), from: Some(m1.end) }); + assert_eq!(p.tick(80.0, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(80.0).from, Some(m1.end)); + assert!(!p.toggle_pause(80.0)); + assert_eq!(p.pan_zoom(80.25), PanZoom { current: Some(m2.at(0.1875)), from: Some(m1.end) }); + assert_eq!(p.tick(80.5, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(80.5), PanZoom { current: Some(m2.at(0.25)), from: None }, "the fade is over after its second"); +} + +#[test] +fn pan_and_zoom_moves_through_a_fade_that_overlaps_it() { + // a 2 s fade in a 4 s slide, straight and through a color: the new photo moves from its start + // view as it fades in, and the old one shows at its end view until the fade is over + for color in [None, Some([0, 0, 0])] { + let s = PlaybackSettings { pan_and_zoom: true, fade_color: color, ..settings(4.0, 2.0) }; + let mut p = Playback::new(ids(2), None, s, 5, 0.0).unwrap(); + let old = p.current(); + let m1 = Motion::new(p.motion_key(old).unwrap(), 0.5); + let Tick::Advanced(new) = p.tick(4.0, all_ready) else { panic!("the next slide comes up at 4") }; + let m2 = Motion::new(p.motion_key(new).unwrap(), 0.5); + for (now, t, progress) in [(4.0, 0.0, 0.0), (5.0, 0.25, 0.5), (5.5, 0.375, 0.75)] { + let f = p.frame(now); + assert_eq!((f.current, f.from), (new, Some(old)), "{color:?} at {now}"); + assert!((f.progress - progress).abs() < 1e-6, "{color:?} at {now}: {f:?}"); + assert_eq!(p.pan_zoom(now), PanZoom { current: Some(m2.at(t)), from: Some(m1.end) }, "{color:?} at {now}"); + } + assert_eq!(p.tick(6.0, all_ready), Tick::Idle); + assert_eq!(p.pan_zoom(6.0), PanZoom { current: Some(m2.at(0.5)), from: None }, "{color:?}: the fade is over, the move goes on"); + } +} + #[test] fn a_single_photo_repeats_without_changing() { let mut p = Playback::new(ids(1), None, settings(1.0, 0.5), 1, 0.0).unwrap(); diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 6b09ed09f5..7ad8715a44 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -231,7 +231,7 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { std::slice::from_ref(&folder), scan.skip(), crate::walk::Limits::default(), - Some(&mut |dir, names, complete| { + Some(&mut |dir, names, complete, _| { use std::sync::atomic::Ordering::Relaxed; progress.folders_listed.fetch_add(1, Relaxed); let files = names.iter().filter(|(_, kind)| *kind == crate::walk::EntryKind::File).count(); @@ -426,7 +426,7 @@ struct Listed { /// Whether the disk is asked about `name` whatever the listing holds: a name Windows takes for /// a device (`NUL`, `aux.jpg`: there in every folder, or not openable where it is listed). -fn asks_the_disk(name: &str) -> bool { +pub(crate) fn asks_the_disk(name: &str) -> bool { let stem = name.split('.').next().unwrap_or_default().trim_end_matches(' ').to_ascii_lowercase(); // (`COM` and `LPT` with any one digit, the superscript ones Windows also takes among them) let numbered = ["com", "lpt"].iter().any(|port| { @@ -439,7 +439,7 @@ fn asks_the_disk(name: &str) -> bool { /// Whether `name` can only be found under itself in some case: ASCII, and nothing in it that a /// file system resolves another way (a short name with `~`, a stream after `:`, dots or spaces /// at its end, which Windows drops). -fn plain_name(name: &str) -> bool { +pub(crate) fn plain_name(name: &str) -> bool { name.is_ascii() && !name.contains(['~', ':']) && !name.ends_with(['.', ' ']) && !name.is_empty() } diff --git a/crates/engine/src/sync/tests_listing.rs b/crates/engine/src/sync/tests_listing.rs index 099b5dd0f9..ff15069c7a 100644 --- a/crates/engine/src/sync/tests_listing.rs +++ b/crates/engine/src/sync/tests_listing.rs @@ -151,7 +151,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { .collect(); // (`dir.jpg` is gone, though a sidecar of its name is there) let mut l = Listing::default(); - let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { l.note(d, names, complete); true }); @@ -174,7 +174,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { l.asked.load(std::sync::atomic::Ordering::Relaxed) }; let mut with = Listing::default(); - crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { with.note(d, names, complete); true }); @@ -191,7 +191,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() { // a folder of plain names only: the disk is asked nothing at all let sub = dir.join("sub"); let mut only_plain = Listing::default(); - crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| { + crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| { only_plain.note(d, names, complete); true }); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 958c122871..91eb92dbb5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -50,6 +50,7 @@ mod preview_prep; mod print; mod process; mod recheck; +mod relocate; mod segment; mod settings_files; mod shelved_folder; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index f0f778f34e..a9ef56ebe2 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -1634,6 +1634,168 @@ fn assisted_culling_burst_limits_are_adjustable() { let _ = std::fs::remove_dir_all(&dir); } +/// A box blur of radius `r`: the larger `r`, the lower the focus score. +fn soften(img: &lightcraft_raster::Rgb32f, r: usize) -> lightcraft_raster::Rgb32f { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out +} + +/// Write a linear image as an sRGB PNG. +fn save_png(img: &lightcraft_raster::Rgb32f, path: &std::path::Path) { + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(path, png).unwrap(); +} + +/// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its +/// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step, +/// and a second run neither makes another stack nor splits the existing one. +#[test] +fn assisted_culling_stacks_each_burst_best_on_top() { + let dir = temp_dir("cull-stack"); + let scene = lightcraft_scenes::demo_library()[0].render(480, 320); + let save = |img: &lightcraft_raster::Rgb32f, name: &str| save_png(img, &dir.join(name)); + save(&soften(&scene, 3), "a_soft.png"); + save(&scene, "b_sharp.png"); + save(&soften(&scene, 6), "c_softer.png"); + save(&lightcraft_scenes::demo_library()[7].render(480, 320), "d_other.png"); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).collect(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s, n); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s, "a_soft.png"), by_name(&s, "b_sharp.png"), by_name(&s, "c_softer.png"), by_name(&s, "d_other.png")); + // a photo named twice is measured and stacked once + let mut twice = ids.clone(); + twice.push(sharp.0); + s.selection = crate::Selection { ids: vec![soft, sharp, softer, other], active: Some(soft) }; + let r = s.execute("photo.analyze", &json!({"ids": twice, "stackGroups": true})).unwrap(); + assert_eq!((r["stacks"].clone(), r["groups"].clone()), (json!(1), json!(1)), "{r}"); + // the active photo went into the collapsed stack: its top takes over, the loose photo stays selected + assert_eq!(s.selection.active, Some(sharp)); + assert!(s.selection.ids.contains(&other) && s.selection.ids.contains(&sharp) && !s.selection.ids.contains(&soft), "{:?}", s.selection.ids); + let st = s.catalog.stack_of(sharp).unwrap().clone(); + assert!(st.collapsed && st.top() == sharp, "the sharpest photo tops the stack"); + let mut members = st.photos.clone(); + members.sort(); + let mut want = vec![soft, sharp, softer]; + want.sort(); + assert_eq!(members, want); + assert!(s.catalog.stack_of(other).is_none(), "the unrelated photo stays loose"); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some_and(|a| a.best)); + // one undo step removes the stack and the analysis together + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + assert!(s.catalog.photo(sharp).unwrap().analysis.is_none()); + // without `stackGroups` nothing is stacked + let r = s.execute("photo.analyze", &json!({"ids": ids})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert!(s.catalog.stacks().next().is_none()); + s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(s.catalog.stacks().count(), 1); + // a second run leaves the stack as it is + let before = s.catalog.stack_of(sharp).unwrap().clone(); + let commits = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 0, "{r}"); + assert_eq!(s.catalog.stacks().count(), 1); + assert_eq!(s.catalog.stack_of(sharp).unwrap(), &before); + assert!(s.commits() > commits); + // a burst partly stacked already: the loose photos are stacked among themselves when two remain + let mut s2 = Session::new().with_fs(); + s2.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + for (i, n) in ["a_soft.png", "b_sharp.png", "c_softer.png", "d_other.png"].iter().enumerate() { + let id = by_name(&s2, n); + s2.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T10:00:0{i}")) }).unwrap(); + } + let (soft, sharp, softer, other) = + (by_name(&s2, "a_soft.png"), by_name(&s2, "b_sharp.png"), by_name(&s2, "c_softer.png"), by_name(&s2, "d_other.png")); + let ids: Vec = [soft, sharp, softer, other].iter().map(|p| p.0).collect(); + s2.execute("stack.group", &json!({"ids": [soft.0, other.0]})).unwrap(); + let r = s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 1, "{r}"); + assert!(s2.catalog.stack_of(soft).unwrap().photos.contains(&other), "the existing stack is untouched"); + let st = s2.catalog.stack_of(sharp).unwrap(); + assert!(st.top() == sharp && st.photos.len() == 2 && st.photos.contains(&softer)); + // a non-boolean value is refused before anything changes + let n = s2.commits(); + assert!(s2.execute("photo.analyze", &json!({"ids": ids, "stackGroups": "yes"})).is_err()); + assert_eq!(s2.commits(), n); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Assisted culling with `stackGroups` (#2277): two bursts make two stacks in one undo step, and a +/// deleted photo is measured but left out of its burst's stack, even when it is the sharpest. +#[test] +fn assisted_culling_stacks_two_bursts_and_leaves_deleted_photos_out() { + let dir = temp_dir("cull-stack-two"); + let (one, two) = (lightcraft_scenes::demo_library()[0].render(480, 320), lightcraft_scenes::demo_library()[7].render(480, 320)); + let files = [ + ("a_soft.png", soften(&one, 3), "10:00:00"), + ("b_sharp.png", one.clone(), "10:00:01"), + ("c_softer.png", soften(&one, 6), "10:00:02"), + ("d_sharp.png", two.clone(), "10:05:00"), + ("e_soft.png", soften(&two, 4), "10:05:01"), + ]; + for (name, img, _) in &files { + save_png(img, &dir.join(name)); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (name, _, at) in &files { + let id = by_name(&s, name); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T{at}")) }).unwrap(); + } + let [soft, sharp, softer, d, e] = files.map(|f| by_name(&s, f.0)); + let ids: Vec = [soft, sharp, softer, d, e].iter().map(|p| p.0).collect(); + s.commit("t", lightcraft_catalog::Op::SetDeleted { id: sharp, deleted: true }).unwrap(); + let n = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!((r["groups"].clone(), r["stacks"].clone()), (json!(2), json!(2)), "{r}"); + assert_eq!(s.commits(), n + 1, "analysis and both stacks are one undo step"); + // the deleted photo is measured, but its burst is stacked from the other two + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some()); + assert!(s.catalog.stack_of(sharp).is_none(), "a deleted photo is never stacked"); + let st = s.catalog.stack_of(soft).unwrap(); + assert!(st.collapsed && st.top() == soft && st.photos.len() == 2 && st.photos.contains(&softer), "{st:?}"); + let st = s.catalog.stack_of(d).unwrap(); + assert!(st.collapsed && st.top() == d && st.photos.len() == 2 && st.photos.contains(&e), "{st:?}"); + // one undo removes both stacks + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index c0ded23ddb..a5b0a842b6 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -403,7 +403,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s .execute( "slideshow.playback", - &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "manual": true}), + &json!({"slideDuration": 6, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "manual": true, "panAndZoom": true, "panAndZoomAmount": 0.25}), ) .unwrap(); assert_eq!(r["fadeColor"], "#000000"); @@ -417,7 +417,7 @@ fn slideshow_playback_settings_persist_with_the_library() { let r = s.execute("slideshow.playback", &json!({})).unwrap(); assert_eq!( r, - json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true, "manual": true}) + json!({"slideDuration": 6.0, "fadeDuration": 2.5, "fadeColor": "#000000", "randomOrder": true, "repeat": false, "preparePreviews": true, "manual": true, "panAndZoom": true, "panAndZoomAmount": 0.25}) ); drop(s); // out-of-range values written by hand are clamped when the library opens diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index 5a35adb5ba..b9eec984c7 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -410,6 +410,223 @@ fn templates_export_to_a_file_and_import_from_one() { assert!(fails(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})).contains("at most")); } +/// The names of the folders `print.template.list` gives, User Templates first. +fn folder_names(r: &Value) -> Vec { + r["folders"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap().to_string()).collect() +} + +/// Each template's name and folder, in the order `print.template.list` gives them. +fn template_folders(r: &Value) -> Vec<(String, String)> { + r["templates"].as_array().unwrap().iter().map(|t| (t["name"].as_str().unwrap().into(), t["folder"].as_str().unwrap().into())).collect() +} + +fn pair(name: &str, folder: &str) -> (String, String) { + (name.into(), folder.into()) +} + +#[test] +fn template_folders_hold_templates_and_survive_reopening() { + let files = MemStore::new(); + let open = |files: &MemStore| { + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + s + }; + let mut s = open(&files); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(r["folders"], json!([{"name": "User Templates", "default": true, "templates": 0}])); + + // a folder is kept while it is empty, and the folders are listed by name after User Templates + let r = run(&mut s, "print.template.folder.create", json!({"name": " Weddings "})); + assert_eq!(r["name"], "Weddings"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Proofs", "Weddings"], "{r}"); + + // a template is saved into a folder, or into User Templates when none is named + run(&mut s, "print.set", json!({"layout": {"style": "contactSheet", "grid": {"columns": 4, "rows": 5}}})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "weddings"})); + let r = run(&mut s, "print.template.save", json!({"name": "Plain"})); + assert_eq!(template_folders(&r), [pair("Sheet", "Weddings"), pair("Plain", "User Templates")]); + assert_eq!(r["folders"][2], json!({"name": "Weddings", "default": false, "templates": 1})); + // saving over a name keeps its folder unless the call names another + run(&mut s, "print.set", json!({"layout": {"grid": {"columns": 6}}})); + let r = run(&mut s, "print.template.save", json!({"name": "sheet"})); + assert_eq!(template_folders(&r), [pair("sheet", "Weddings"), pair("Plain", "User Templates")]); + let r = run(&mut s, "print.template.save", json!({"name": "Plain", "folder": "Proofs"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "Proofs")); + + // a move changes only the folder; a move to where it is already does nothing + let settings = r["templates"][0]["settings"].clone(); + let r = run(&mut s, "print.template.move", json!({"name": "SHEET", "folder": "Proofs"})); + assert_eq!((r["moved"].as_bool(), template_folders(&r)[0].clone()), (Some(true), pair("sheet", "Proofs"))); + assert_eq!(r["templates"][0]["settings"], settings); + let r = run(&mut s, "print.template.move", json!({"name": "Sheet", "folder": "proofs"})); + assert_eq!(r["moved"], false); + let r = run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "user templates"})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + run(&mut s, "print.template.move", json!({"name": "Plain", "folder": "Weddings"})); + + // a rename takes the folder's templates along; a change of case is a rename too + let r = run(&mut s, "print.template.folder.rename", json!({"name": "proofs", "to": "Contact Sheets"})); + assert_eq!(folder_names(&r), ["User Templates", "Contact Sheets", "Weddings"]); + assert_eq!(template_folders(&r)[0], pair("sheet", "Contact Sheets")); + let r = run(&mut s, "print.template.folder.rename", json!({"name": "contact sheets", "to": "contact sheets"})); + assert_eq!(template_folders(&r)[0], pair("sheet", "contact sheets")); + + // the folders and where each template is survive reopening the library + let mut again = open(&files); + let r = run(&mut again, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets", "Weddings"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "Weddings")]); + run(&mut again, "print.template.apply", json!({"name": "Sheet"})); + assert_eq!(again.print.layout.grid.columns, 6); + + // deleting a folder keeps its templates: they go to User Templates + let r = run(&mut s, "print.template.folder.delete", json!({"name": "WEDDINGS"})); + assert_eq!((r["deleted"].as_str(), r["moved"].as_u64()), (Some("Weddings"), Some(1))); + assert_eq!(folder_names(&r), ["User Templates", "contact sheets"]); + assert_eq!(template_folders(&r), [pair("sheet", "contact sheets"), pair("Plain", "User Templates")]); + let r = run(&mut open(&files), "print.template.list", json!({})); + assert_eq!(template_folders(&r)[1], pair("Plain", "User Templates")); + + // refusals change nothing + let before = run(&mut s, "print.template.list", json!({})); + for (id, p, why) in [ + ("print.template.folder.create", json!({}), "missing `name`"), + ("print.template.folder.create", json!({"name": " "}), "folder name"), + ("print.template.folder.create", json!({"name": "a\tb"}), "folder name"), + ("print.template.folder.create", json!({"name": "x".repeat(81)}), "folder name"), + ("print.template.folder.create", json!({"name": "user templates"}), "always there"), + ("print.template.folder.create", json!({"name": "Contact Sheets"}), "already a folder"), + ("print.template.folder.rename", json!({"name": "User Templates", "to": "Mine"}), "can't be renamed"), + ("print.template.folder.rename", json!({"name": "Nope", "to": "Mine"}), "no print template folder"), + ("print.template.folder.rename", json!({"name": "contact sheets"}), "missing `to`"), + ("print.template.folder.rename", json!({"name": "contact sheets", "to": "User Templates"}), "always there"), + ("print.template.folder.delete", json!({"name": "User Templates"}), "can't be renamed or deleted"), + ("print.template.folder.delete", json!({"name": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet"}), "missing `folder`"), + ("print.template.move", json!({"name": "Sheet", "folder": "Nope"}), "no print template folder"), + ("print.template.move", json!({"name": "Sheet", "folder": 3}), "`folder` must be"), + ("print.template.save", json!({"name": "New", "folder": null}), "`folder` must be"), + ("print.template.import", json!({"path": "x.lcprint", "folder": null}), "`folder` must be"), + ("print.template.move", json!({"name": "Nope", "folder": "User Templates"}), "no print template `Nope`"), + ("print.template.save", json!({"name": "New", "folder": "Nope"}), "no print template folder"), + ("print.template.import", json!({"path": "x.lcprint", "folder": "Nope"}), "no print template folder"), + ] { + let e = fails(&mut s, id, p.clone()); + assert!(e.contains(why), "{id} {p}: {e}"); + } + run(&mut s, "print.template.folder.create", json!({"name": "Second"})); + assert!(fails(&mut s, "print.template.folder.rename", json!({"name": "second", "to": "CONTACT SHEETS"})).contains("already a folder")); + run(&mut s, "print.template.folder.delete", json!({"name": "Second"})); + assert_eq!(run(&mut s, "print.template.list", json!({})), before); + + // a full list of folders takes no more + while s.print_template_folders.len() < crate::print::template::MAX_FOLDERS { + let n = s.print_template_folders.len(); + run(&mut s, "print.template.folder.create", json!({"name": format!("F{n}")})); + } + assert!(fails(&mut s, "print.template.folder.create", json!({"name": "One more"})).contains("at most")); +} + +#[test] +fn templates_import_into_a_folder_and_export_without_it() { + let mut s = Session::with_demo(); + let scratch = Scratch::new("folders"); + let file = scratch.0.join("proofs.lcprint"); + run(&mut s, "print.template.folder.create", json!({"name": "Proofs"})); + run(&mut s, "print.template.save", json!({"name": "Sheet", "folder": "Proofs"})); + run(&mut s, "print.template.export", json!({"name": "Sheet", "path": file.to_string_lossy()})); + let doc: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let mut keys: Vec<&String> = doc.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!(keys, ["format", "name", "settings", "version"], "a .lcprint file stays version 1, without the folder"); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy()})); + assert_eq!(template_folders(&r)[1], pair("Sheet (2)", "User Templates")); + let r = run(&mut s, "print.template.import", json!({"path": file.to_string_lossy(), "folder": "proofs"})); + assert_eq!(template_folders(&r)[2], pair("Sheet (3)", "Proofs")); +} + +#[test] +fn templates_from_before_folders_are_in_user_templates() { + let files = MemStore::new(); + let old = json!({"printTemplates": [ + {"name": "Old", "settings": {"layout": {"style": "contactSheet"}}}, + {"name": "Kept", "folder": "Family", "settings": {}}, + {"name": "Spelled", "folder": " family ", "settings": {}}, + {"name": "Bad", "folder": "a\nb", "settings": {}}, + {"name": "Reserved", "folder": "USER TEMPLATES", "settings": {}} + ], "printTemplateFolders": ["Empty", "", "empty", "User Templates", "Family"]}); + files.set("prefs.json", serde_json::to_vec(&old).unwrap()); + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + assert!(s.take_library_warnings().is_empty()); + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "Empty", "Family"]); + assert_eq!( + template_folders(&r), + [ + pair("Old", "User Templates"), + pair("Kept", "Family"), + pair("Spelled", "Family"), + pair("Bad", "User Templates"), + pair("Reserved", "User Templates") + ] + ); + run(&mut s, "print.template.apply", json!({"name": "Old"})); +} + +#[test] +fn template_folders_with_and_without_templates_and_with_path_characters() { + let files = MemStore::new(); + let mut s = Session::with_demo(); + let stores = LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + let kept: Vec = files.files.lock().unwrap().keys().cloned().collect(); + let no_new_files = |files: &MemStore| files.files.lock().unwrap().keys().all(|k| kept.contains(k) || k == "prefs.json"); + + // a folder name is a label in prefs.json, not a path: `/`, `\` and `..` are kept as typed + for name in ["Clients/2024", r"a\b", ".."] { + let r = run(&mut s, "print.template.folder.create", json!({"name": name})); + assert_eq!(r["name"], name); + } + let r = run(&mut s, "print.template.list", json!({})); + assert_eq!(folder_names(&r), ["User Templates", "..", r"a\b", "Clients/2024"]); + assert!(no_new_files(&files), "folders make no files of their own"); + assert!(fails(&mut s, "print.template.folder.create", json!({"name": "clients/2024"})).contains("already a folder")); + + // an empty folder is renamed and deleted like one with templates; nothing moves + let r = run(&mut s, "print.template.folder.rename", json!({"name": "..", "to": "Empty"})); + assert_eq!(folder_names(&r), ["User Templates", r"a\b", "Clients/2024", "Empty"]); + assert_eq!(r["folders"][3], json!({"name": "Empty", "default": false, "templates": 0})); + let r = run(&mut s, "print.template.folder.delete", json!({"name": "Empty"})); + assert_eq!((r["deleted"].as_str(), r["moved"].as_u64()), (Some("Empty"), Some(0))); + assert_eq!(folder_names(&r), ["User Templates", r"a\b", "Clients/2024"]); + + // templates move into a folder and out of it again + run(&mut s, "print.template.save", json!({"name": "One", "folder": "Clients/2024"})); + run(&mut s, "print.template.save", json!({"name": "Two"})); + run(&mut s, "print.template.save", json!({"name": "Three", "folder": r"a\b"})); + let r = run(&mut s, "print.template.move", json!({"name": "Two", "folder": "Clients/2024"})); + assert_eq!(template_folders(&r), [pair("One", "Clients/2024"), pair("Two", "Clients/2024"), pair("Three", r"a\b")]); + let r = run(&mut s, "print.template.move", json!({"name": "Three", "folder": "User Templates"})); + assert_eq!(template_folders(&r)[2], pair("Three", "User Templates")); + + // a folder with templates is renamed with them; deleting it moves every one to User Templates + let r = run(&mut s, "print.template.folder.rename", json!({"name": "clients/2024", "to": "Clients/2025"})); + assert_eq!(template_folders(&r)[..2], [pair("One", "Clients/2025"), pair("Two", "Clients/2025")]); + let r = run(&mut s, "print.template.folder.delete", json!({"name": "Clients/2025"})); + assert_eq!(r["moved"], 2); + assert_eq!(template_folders(&r), [pair("One", "User Templates"), pair("Two", "User Templates"), pair("Three", "User Templates")]); + // a new folder under a deleted folder's name starts empty + let r = run(&mut s, "print.template.folder.create", json!({"name": "Clients/2025"})); + assert_eq!(r["folders"][2], json!({"name": "Clients/2025", "default": false, "templates": 0})); + assert!(no_new_files(&files)); +} + /// A library whose `prefs.json` can't be read, so saving the preferences fails. #[derive(Clone, Default)] struct PrefsUnreadable(MemStore); @@ -442,7 +659,13 @@ fn template_changes_that_cant_be_saved_are_undone() { LibraryStores { dir: "print".into(), catalog: Box::new(MemStore::new()), files: Box::new(PrefsUnreadable::default()), on_disk: false }; s.open_library_in(stores, false).unwrap(); s.print_templates.push(crate::print::template::PrintTemplate::new("Proofs", &s.print).unwrap()); - let names = |s: &Session| s.print_templates.iter().map(|t| (t.name.clone(), t.settings.clone())).collect::>(); + s.print_template_folders.push("Family".into()); + let names = |s: &Session| { + ( + s.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone(), t.settings.clone())).collect::>(), + s.print_template_folders.clone(), + ) + }; let kept = names(&s); let scratch = Scratch::new("unsaved"); let file = scratch.0.join("proofs.lcprint"); @@ -454,10 +677,18 @@ fn template_changes_that_cant_be_saved_are_undone() { ("print.template.save", json!({"name": "proofs"})), ("print.template.delete", json!({"name": "Proofs"})), ("print.template.import", json!({"path": file.to_string_lossy()})), + ("print.template.move", json!({"name": "Proofs", "folder": "Family"})), + ("print.template.folder.create", json!({"name": "Work"})), + ("print.template.folder.rename", json!({"name": "Family", "to": "Home"})), + ("print.template.folder.delete", json!({"name": "Family"})), ] { assert!(fails(&mut s, id, p.clone()).contains("prefs.json"), "{id} {p}"); assert_eq!(names(&s), kept, "{id} {p}"); } + // a rename to the same spelling changes nothing, so it writes nothing and doesn't fail + let r = run(&mut s, "print.template.folder.rename", json!({"name": "family", "to": " Family "})); + assert_eq!(r["name"], "Family"); + assert_eq!(names(&s), kept); } #[test] @@ -503,6 +734,10 @@ fn every_print_command_is_registered_with_a_description() { "print.template.delete", "print.template.export", "print.template.import", + "print.template.move", + "print.template.folder.create", + "print.template.folder.rename", + "print.template.folder.delete", ] { let c = crate::find_command(id).unwrap_or_else(|| panic!("{id} missing")); assert!(c.params.len() > 3, "{id}"); diff --git a/crates/engine/src/tests/relocate.rs b/crates/engine/src/tests/relocate.rs new file mode 100644 index 0000000000..6fb345e15d --- /dev/null +++ b/crates/engine/src/tests/relocate.rs @@ -0,0 +1,964 @@ +//! Locating a library folder that is somewhere else now (see [`crate::relocate`]; issue #1112). +//! +//! Scenarios, in the words of someone whose folder is not where the library looks for it: +//! +//! * Given a folder of the library that was moved or renamed outside LightCraft (or whose +//! catalog came from another computer), when the person says where it is now, its photos — +//! those in the folders inside it and in Recently Deleted too — point at the same places below +//! the new folder. No file is touched, and it is one undo step. +//! * A path written by Windows (`D:\Photos\…`) is located on a computer that spells paths `/…`. +//! * What the library knows about the folder (its colour label) and the folder being shown +//! follow; undo brings both back. +//! * A folder that holds none of the photos' files is refused: it is not the folder. One that +//! holds only some is refused unless the person says so; the others then stay missing there. +//! Looking for the files can run apart from the session, and can be stopped. +//! * A folder whose files the library already has is refused, as are the folder itself, the +//! library's own folder, a path that is no folder, and a folder that is not the library's. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +use lightcraft_catalog::{ColorLabel, Filter, Op, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::relocate::{Relocation, look_at}; + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-relocate-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + fn path(&self, rel: &str) -> String { + self.0.join(rel).components().collect::().to_string_lossy().into_owned() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A small procedural PNG (distinct per seed). +fn write_png(path: &str, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(Path::new(path).parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// A library holding `trip/a.png` and `trip/day1/b.png`. +fn library(dir: &Scratch) -> Session { + write_png(&dir.path("trip/a.png"), 1); + write_png(&dir.path("trip/day1/b.png"), 2); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("trip")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + s +} + +/// The folder moved away whole, outside LightCraft: `trip` is now `archive/journey`. +fn moved_away(dir: &Scratch) -> String { + std::fs::create_dir_all(dir.0.join("archive")).unwrap(); + std::fs::rename(dir.0.join("trip"), dir.0.join("archive/journey")).unwrap(); + dir.path("archive/journey") +} + +/// Where the library looks for each photo's file. +fn files(s: &Session) -> Vec { + let mut v: Vec = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + v.sort(); + v +} + +/// [`crate::relocate::relocate`] with the parameters named as an agent would give them +/// (`{folder, path, disk?, incomplete?}`). +fn update_location(s: &mut Session, params: &Value) -> crate::Result { + let flag = |key: &str| params.get(key).and_then(Value::as_bool).unwrap_or(false); + let text = |key: &str| params[key].as_str().unwrap().to_string(); + crate::relocate::relocate(s, &text("folder"), &text("path"), flag("disk"), flag("incomplete")) +} + +fn relocate(s: &mut Session, from: &str, to: &str) -> Value { + update_location(s, &json!({"folder": from, "path": to})).unwrap() +} + +fn refused(s: &mut Session, params: Value) -> String { + let (before, steps) = (files(s), s.undo.len()); + let e = update_location(s, ¶ms).unwrap_err().to_string(); + assert_eq!(files(s), before, "a refusal changes nothing"); + assert_eq!(s.undo.len(), steps, "and leaves no undo step"); + e +} + +#[test] +fn a_folder_moved_outside_lightcraft_is_located_and_its_photos_follow() { + let dir = Scratch::new("follow"); + let mut s = library(&dir); + let now = moved_away(&dir); + assert_eq!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().len(), 2, "both are missing first"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); + assert_eq!(r["path"], json!(now)); + assert_eq!(files(&s), [dir.path("archive/journey/a.png"), dir.path("archive/journey/day1/b.png")]); + assert!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().is_empty(), "nothing is missing any more"); + let scan = s.execute("folder.scanChanges", &json!({"path": now})).unwrap(); + for key in ["new", "missing", "moved", "metadata"] { + assert!(scan[key].as_array().unwrap().is_empty(), "{key}: the library is up to date with the folder: {scan}"); + } +} + +#[test] +fn locating_is_one_undo_step_and_touches_no_file() { + let dir = Scratch::new("undo"); + let mut s = library(&dir); + let before = files(&s); + let now = moved_away(&dir); + let steps = s.undo.len(); + + relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(s.undo.len(), steps + 1); + let after = files(&s); + + s.undo_step().unwrap(); + assert_eq!(files(&s), before, "undo points the photos back"); + assert!(Path::new(&now).join("a.png").is_file() && !dir.0.join("trip").exists(), "and moves nothing on disk"); + s.redo_step().unwrap(); + assert_eq!(files(&s), after); + assert!(Path::new(&now).join("day1/b.png").is_file() && !dir.0.join("trip").exists()); +} + +/// Point every photo of the library at the same place below `root`, as a catalog from +/// another computer would have it. +fn as_written_elsewhere(s: &mut Session, dir: &Scratch, root: &str, sep: &str) { + let ops = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => { + let rel: Vec = + Path::new(path).strip_prefix(&dir.0).unwrap().components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); + Some(Op::Relink { + id: p.id, + file_name: p.file_name.clone(), + source: Source::File { path: format!("{root}{}", rel.join(sep)) }, + format: None, + }) + } + _ => None, + }) + .collect(); + s.commit("elsewhere", Op::Batch { ops }).unwrap(); +} + +#[test] +fn a_folder_of_a_windows_catalog_is_located_on_this_computer() { + let dir = Scratch::new("windows"); + let mut s = library(&dir); + as_written_elsewhere(&mut s, &dir, "D:\\Photos\\", "\\"); + assert_eq!(files(&s), ["D:\\Photos\\trip\\a.png", "D:\\Photos\\trip\\day1\\b.png"]); + + let r = relocate(&mut s, "D:\\Photos\\trip", &dir.path("trip")); + + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")], "spelled the way this computer spells paths"); +} + +#[test] +fn a_whole_disk_is_located_only_on_request() { + let dir = Scratch::new("disk"); + let mut s = library(&dir); + as_written_elsewhere(&mut s, &dir, "D:\\", "\\"); + + let e = refused(&mut s, json!({"folder": "D:\\", "path": dir.path("")})); + assert!(e.contains("disk: true"), "{e}"); + + let r = update_location(&mut s, &json!({"folder": "D:\\", "path": dir.path(""), "disk": true})).unwrap(); + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")]); +} + +#[test] +fn photos_in_recently_deleted_follow_their_folder() { + let dir = Scratch::new("trash"); + let mut s = library(&dir); + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let now = moved_away(&dir); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + // (the one in the trash is not looked for, but restoring it must find its file) + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(1)), "{r}"); + assert_eq!(files(&s), [dir.path("archive/journey/a.png"), dir.path("archive/journey/day1/b.png")]); +} + +#[test] +fn the_folders_colour_labels_follow() { + let dir = Scratch::new("labels"); + let mut s = library(&dir); + s.execute("folder.label", &json!({"path": dir.path("trip"), "label": "red"})).unwrap(); + s.execute("folder.label", &json!({"path": dir.path("trip/day1"), "label": "blue"})).unwrap(); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!(s.catalog.folder_color_label(&now), Some(ColorLabel::Red)); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/day1")), Some(ColorLabel::Blue)); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip")), None, "nothing is left at the old place"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip")), Some(ColorLabel::Red), "undo brings the labels back with the photos"); + assert_eq!(s.catalog.folder_color_label(&now), None); +} + +#[test] +fn the_folder_being_shown_follows_and_comes_back_on_undo() { + let dir = Scratch::new("shown"); + let mut s = library(&dir); + s.execute("library.source", &json!({"kind": "libraryFolder", "path": dir.path("trip/day1")})).unwrap(); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("archive/journey/day1").as_str())); + assert_eq!(s.visible().len(), 1, "its photo is still the one shown"); + + s.undo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("trip/day1").as_str())); + s.redo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("archive/journey/day1").as_str())); +} + +#[test] +fn the_filter_set_aside_by_enable_filters_follows_too() { + let dir = Scratch::new("shelved"); + let mut s = library(&dir); + let before = Filter { library_folder: Some(dir.path("trip/day1")), ..Default::default() }; + s.shelved_filter = Some(before); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + let shelved = |s: &Session| s.shelved_filter.as_ref().and_then(|f| f.library_folder.clone()); + assert_eq!(shelved(&s), Some(dir.path("archive/journey/day1"))); + + s.undo_step().unwrap(); + assert_eq!(shelved(&s), Some(dir.path("trip/day1"))); +} + +/// A folder named with a space at its edge is that folder, not the one without the space. +#[cfg(unix)] +#[test] +fn names_with_spaces_at_their_edge_are_not_trimmed() { + let dir = Scratch::new("edge-space"); + write_png(&dir.path("trip /a.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("trip ")]})).unwrap(); + std::fs::rename(dir.0.join("trip "), dir.0.join("moved ")).unwrap(); + + let r = relocate(&mut s, &dir.path("trip "), &dir.path("moved ")); + + assert_eq!(r["relinked"].as_u64(), Some(1), "{r}"); + assert_eq!(files(&s), [dir.path("moved /a.png")]); +} + +#[test] +fn a_folder_that_holds_none_of_the_photos_is_refused() { + let dir = Scratch::new("none"); + let mut s = library(&dir); + moved_away(&dir); + // one level too high: the files are in `archive/journey`, not in `archive` + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("archive")})); + assert!(e.contains("none of the 2 files"), "{e}"); + // and saying "anyway" does not make it the folder + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("archive"), "incomplete": true})); + assert!(e.contains("none of the 2 files"), "{e}"); +} + +#[test] +fn a_folder_that_holds_only_some_is_located_only_on_request() { + let dir = Scratch::new("some"); + let mut s = library(&dir); + let now = moved_away(&dir); + std::fs::remove_file(Path::new(&now).join("a.png")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("1 of the 2 files") && e.contains("incomplete: true"), "{e}"); + + let r = update_location(&mut s, &json!({"folder": dir.path("trip"), "path": now, "incomplete": true})).unwrap(); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(1), Some(1)), "{r}"); + // the one that isn't there is missing at the new place, where Synchronize Folder finds it + let missing = s.execute("library.missing", &json!({})).unwrap(); + assert_eq!(missing.as_array().unwrap().len(), 1); + assert_eq!(missing[0]["path"], json!(dir.path("archive/journey/a.png"))); +} + +#[test] +fn a_folder_whose_files_the_library_already_has_is_refused() { + let dir = Scratch::new("taken"); + let mut s = library(&dir); + write_png(&dir.path("copy/a.png"), 3); + write_png(&dir.path("copy/day1/b.png"), 4); + s.execute("library.import", &json!({"paths": [dir.path("copy")]})).unwrap(); + assert_eq!(s.catalog.len(), 4); + std::fs::remove_dir_all(dir.0.join("trip")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("copy")})); + assert!(e.contains("already in the library"), "{e}"); +} + +#[test] +fn only_a_missing_or_moved_library_folder_and_a_real_folder_are_taken() { + let dir = Scratch::new("refusals"); + let mut s = library(&dir); + let trip = dir.path("trip"); + std::fs::create_dir_all(dir.0.join("empty")).unwrap(); + + for (params, why) in [ + (json!({"folder": trip, "path": trip}), "already looks"), + (json!({"folder": trip, "path": format!("{trip}{}", std::path::MAIN_SEPARATOR)}), "already looks"), + (json!({"folder": trip, "path": dir.path("nowhere")}), "is not a folder"), + (json!({"folder": trip, "path": dir.path("trip/a.png")}), "is not a folder"), + (json!({"folder": dir.path("empty"), "path": trip}), "no photo in the library"), + (json!({"folder": "/", "path": trip}), "startup disk"), + ] { + let e = refused(&mut s, params.clone()); + assert!(e.contains(why), "{params}: {e}"); + } +} + +#[test] +fn the_librarys_own_folder_is_no_place_for_photos() { + let dir = Scratch::new("own"); + write_png(&dir.path("trip/a.png"), 1); + let lib = dir.path("lib"); + let mut s = Session::new().with_fs(); + s.open_library(Path::new(&lib), false).unwrap(); + s.execute("library.import", &json!({"paths": [dir.path("trip")]})).unwrap(); + std::fs::create_dir_all(dir.0.join("lib/inside")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("lib/inside")})); + assert!(e.contains("library's own"), "{e}"); +} + +#[test] +fn the_plan_names_each_file_once_and_the_count_can_be_stopped() { + let dir = Scratch::new("count"); + let mut s = library(&dir); + // a virtual copy shares its photo's file: one file to look for + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap(); + let now = moved_away(&dir); + + let plan = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap(); + assert_eq!(plan.files().len(), 2, "{:?}", plan.files()); + let progress = crate::import::ScanProgress::default(); + assert_eq!(look_at(plan.files(), &Default::default(), &progress).found, 2); + assert_eq!((progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)), (2, 2)); + + // ✕ on its row in the activity stack + let stopped = crate::import::ScanProgress::default(); + stopped.cancel.store(true, Ordering::Relaxed); + assert_eq!(look_at(plan.files(), &Default::default(), &stopped).found, 0, "nothing more is looked for"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(3), Some(2)), "the copy follows its photo: {r}"); + assert!(s.catalog.photo(PhotoId(id.0)).is_some()); +} + +#[test] +fn hostile_parameters_are_refused_not_crashed_on() { + let dir = Scratch::new("hostile"); + let mut s = library(&dir); + for params in [ + json!({"folder": "", "path": ""}), + json!({"folder": "..", "path": "."}), + json!({"folder": dir.path("trip"), "path": "\0"}), + json!({"folder": "\\\\?\\", "path": dir.path("trip"), "disk": true}), + ] { + refused(&mut s, params); + } +} + +#[test] +fn a_new_place_already_browsed_in_local_does_not_bring_its_files_in_twice() { + let dir = Scratch::new("browsed"); + let mut s = library(&dir); + let now = moved_away(&dir); + // looking for the photos, the person browsed the folder where they are now + s.execute("library.browse", &json!({"path": now})).unwrap(); + s.execute("library.browse", &json!({"path": dir.path("archive/journey/day1")})).unwrap(); + let records = s.catalog.len(); + assert!(records > 2, "browsing catalogued the files as Local records"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(r["relinked"], json!(2), "{r}"); + + let scan = s.execute("folder.scanChanges", &json!({"path": now})).unwrap(); + assert!(scan["new"].as_array().unwrap().is_empty(), "the library's photos are these files: {scan}"); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 2); +} + +#[test] +fn undo_brings_the_local_records_back_and_work_done_while_browsing_is_not_given_up() { + let dir = Scratch::new("browsed-undo"); + let mut s = library(&dir); + let now = moved_away(&dir); + s.execute("library.browse", &json!({"path": now})).unwrap(); + let records = s.catalog.len(); + let local = s.catalog.photos().find(|p| p.local).map(|p| p.id).unwrap(); + // the photo being looked at in Local is one of those that give way + s.execute("library.select", &json!({"ids": [local.0]})).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(r["replacedLocal"], json!(records - 2), "{r}"); + assert!(s.catalog.photo(local).is_none()); + assert!(s.selection.ids.iter().all(|id| s.catalog.photo(*id).is_some()), "nothing that is gone stays selected"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.len(), records, "undo brings the Local records back"); + assert_eq!(files(&s).iter().filter(|f| f.starts_with(&dir.path("trip"))).count(), 2); + + // a rating given while browsing is the person's work: the library's photo can't replace it + s.execute("library.select", &json!({"ids": [local.0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("while browsing it in Local"), "{e}"); +} + +#[test] +fn what_was_found_is_not_applied_to_a_library_opened_meanwhile() { + let dir = Scratch::new("switched"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap(); + // File › Open Library while the files were looked for: its photo ids mean other photos + s.library_identity = std::sync::Arc::new(()); + let (before, steps) = (files(&s), s.undo.len()); + + let e = located.commit(&mut s, false).unwrap_err().to_string(); + + assert!(e.contains("another library"), "{e}"); + assert_eq!(files(&s), before, "nothing landed in the other library"); + assert_eq!(s.undo.len(), steps); +} + +#[test] +fn a_photo_relinked_while_the_files_were_looked_for_is_left_where_it_is() { + let dir = Scratch::new("meanwhile"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap(); + // meanwhile the person located one photo by hand, somewhere else + write_png(&dir.path("elsewhere/a.png"), 1); + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.relink", &json!({"id": id.0, "path": dir.path("elsewhere/a.png")})).unwrap(); + + let r = located.commit(&mut s, false).unwrap(); + + assert_eq!(r["relinked"], json!(1), "{r}"); + assert_eq!(files(&s), [dir.path("archive/journey/day1/b.png"), dir.path("elsewhere/a.png")], "its own choice stands"); +} + +/// What `look` found for `trip` → `to`, the files not yet relinked. +fn looked(s: &Session, dir: &Scratch, to: &str) -> crate::relocate::Located { + Relocation::new(s, &dir.path("trip"), to, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap() +} + +#[test] +fn a_new_place_browsed_while_the_files_were_looked_for_still_has_one_record_per_file() { + let dir = Scratch::new("browsed-meanwhile"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = looked(&s, &dir, &now); + // meanwhile the person clicked the folder in Local + s.execute("library.browse", &json!({"path": now})).unwrap(); + let local = s.catalog.photos().filter(|p| p.local).count(); + assert!(local > 0); + + let r = located.commit(&mut s, false).unwrap(); + + assert_eq!(r["replacedLocal"], json!(local), "{r}"); + let mut seen = std::collections::HashSet::new(); + assert!(files(&s).into_iter().all(|f| seen.insert(f)), "one record per file: {:?}", files(&s)); +} + +#[test] +fn a_file_that_became_another_photos_while_the_files_were_looked_for_is_not_shared() { + let dir = Scratch::new("taken-meanwhile"); + let mut s = library(&dir); + write_png(&dir.path("other/x.png"), 9); + s.execute("library.import", &json!({"paths": [dir.path("other")]})).unwrap(); + let now = moved_away(&dir); + let located = looked(&s, &dir, &now); + // meanwhile another photo was pointed at one of the files + let other = s.catalog.photos().find(|p| p.file_name == "x.png").map(|p| p.id).unwrap(); + s.execute("photo.relink", &json!({"id": other.0, "path": dir.path("archive/journey/a.png")})).unwrap(); + let (before, steps) = (files(&s), s.undo.len()); + + let e = located.commit(&mut s, false).unwrap_err().to_string(); + + assert!(e.contains("already in the library"), "{e}"); + assert_eq!((files(&s), s.undo.len()), (before, steps), "nothing changed"); +} + +#[test] +fn a_browsed_record_in_recently_deleted_at_the_new_place_is_not_doubled() { + let dir = Scratch::new("local-trash"); + let mut s = library(&dir); + let now = moved_away(&dir); + s.execute("library.browse", &json!({"path": now})).unwrap(); + let local = s.catalog.photos().find(|p| p.local).map(|p| p.id).unwrap(); + s.catalog.apply(Op::SetDeleted { id: local, deleted: true }).unwrap(); + + // restoring it later would make a second photo of the file + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("Recently Deleted included"), "{e}"); +} + +/// A library that also holds `archive/journey/phone/p.png` (labelled red), with the files of +/// `trip` moved into `archive/journey` behind its back. +fn moved_into_a_folder_of_the_library(dir: &Scratch) -> (Session, String) { + let mut s = library(dir); + write_png(&dir.path("archive/journey/phone/p.png"), 7); + s.execute("library.import", &json!({"paths": [dir.path("archive/journey/phone")]})).unwrap(); + s.execute("folder.label", &json!({"path": dir.path("archive/journey/phone"), "label": "red"})).unwrap(); + std::fs::rename(dir.0.join("trip/a.png"), dir.0.join("archive/journey/a.png")).unwrap(); + std::fs::rename(dir.0.join("trip/day1"), dir.0.join("archive/journey/day1")).unwrap(); + std::fs::remove_dir(dir.0.join("trip")).unwrap(); + (s, dir.path("archive/journey")) +} + +#[test] +fn folders_of_the_library_already_at_the_new_place_keep_their_labels() { + let dir = Scratch::new("labels-there"); + let (mut s, now) = moved_into_a_folder_of_the_library(&dir); + s.execute("folder.label", &json!({"path": dir.path("trip/day1"), "label": "blue"})).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/phone")), Some(ColorLabel::Red), "it was there all along"); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/day1")), Some(ColorLabel::Blue), "and the located one's came along"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/phone")), Some(ColorLabel::Red)); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip/day1")), Some(ColorLabel::Blue)); +} + +#[test] +fn undo_leaves_a_view_that_did_not_move_where_it_is() { + let dir = Scratch::new("view-stays"); + let (mut s, now) = moved_into_a_folder_of_the_library(&dir); + relocate(&mut s, &dir.path("trip"), &now); + // a folder of the library that was at the new place all along, chosen since + let phone = dir.path("archive/journey/phone"); + s.execute("library.source", &json!({"kind": "libraryFolder", "path": phone})).unwrap(); + s.undo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(phone.as_str()), "its photos never moved"); + s.redo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(phone.as_str())); + + // and a folder browsed in Local is a place on disk + s.execute("library.browse", &json!({"path": dir.path("archive/journey/day1")})).unwrap(); + let browsed = s.browse.as_ref().map(|b| b.path.clone()); + assert!(browsed.is_some()); + s.undo_step().unwrap(); + assert_eq!(s.browse.as_ref().map(|b| b.path.clone()), browsed, "the folder on disk is where it was"); +} + +#[test] +fn a_folder_whose_files_went_into_a_folder_inside_it_is_located_there() { + let dir = Scratch::new("inside"); + let mut s = library(&dir); + // everything in `trip` was put into `trip/2019` + std::fs::create_dir_all(dir.0.join("2019")).unwrap(); + std::fs::rename(dir.0.join("trip/a.png"), dir.0.join("2019/a.png")).unwrap(); + std::fs::rename(dir.0.join("trip/day1"), dir.0.join("2019/day1")).unwrap(); + std::fs::rename(dir.0.join("2019"), dir.0.join("trip/2019")).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &dir.path("trip/2019")); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(files(&s), [dir.path("trip/2019/a.png"), dir.path("trip/2019/day1/b.png")]); + s.undo_step().unwrap(); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")]); +} + +// ── Is the file there the photo's? (review of #1122) ───────────────────────────────────────── +// +// * A file being at the new place does not make it the photo's. A place that is, as the library +// has it, another photo's file of the same folder (the new place is inside the folder, or the +// folder inside it) is taken only when the file's content is the photo's; "anyway" does not +// cover it, and neither does a library that recorded no sizes or contents. +// * A file of another size than the library recorded is not counted as found: it is said, and +// taken only on request. A folder where no file is the library's is not the folder. + +/// A library holding `a/x.png` and `a/b/x.png`: the same name one level apart. +fn same_name_one_level_apart(dir: &Scratch) -> Session { + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/b/x.png"), 2); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + s +} + +/// As a catalog from another app leaves its photos: no size and no content recorded. +fn forget_sizes_and_contents(s: &mut Session) { + let ops: Vec = s + .catalog + .photos() + // (a record of having looked in Local stays as browsing left it: untouched) + .filter(|p| !p.local) + .map(|p| Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: 0, + content_hash: None, + preview_only: None, + preview_checked: String::new(), + }) + .collect(); + s.commit("Forget", Op::Batch { ops }).unwrap(); +} + +#[test] +fn a_place_inside_the_folder_never_gives_a_photo_another_photos_file() { + let dir = Scratch::new("nested"); + let mut s = same_name_one_level_apart(&dir); + // one level too low: `a/b/x.png` is the other photo's file, and nothing moved + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": incomplete})); + assert!(e.contains("other photos of this folder") && e.contains(dir.path("a/b/x.png").as_str()), "incomplete {incomplete}: {e}"); + } +} + +#[test] +fn nor_when_the_library_recorded_no_size_and_no_content() { + let dir = Scratch::new("nested-blind"); + let mut s = same_name_one_level_apart(&dir); + forget_sizes_and_contents(&mut s); + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": incomplete})); + assert!(e.contains("other photos of this folder"), "incomplete {incomplete}: {e}"); + } +} + +#[test] +fn nor_a_photo_in_recently_deleted() { + let dir = Scratch::new("nested-deleted"); + let mut s = same_name_one_level_apart(&dir); + write_png(&dir.path("a/k.png"), 3); + s.execute("library.import", &json!({"paths": [dir.path("a/k.png")]})).unwrap(); + let upper = s.catalog.photos().find(|p| matches!(&p.source, Source::File { path } if *path == dir.path("a/x.png"))).map(|p| p.id).unwrap(); + s.execute("photo.delete", &json!({"ids": [upper.0]})).unwrap(); + // `k.png` is in `a/b` too, so one of the library's two files is found there + std::fs::copy(dir.path("a/k.png"), dir.path("a/b/k.png")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "restoring it would show the other photo's file: {e}"); +} + +#[test] +fn files_that_did_go_one_level_down_are_told_by_their_content() { + let dir = Scratch::new("shifted"); + let mut s = same_name_one_level_apart(&dir); + let upper = s.catalog.photos().find(|p| matches!(&p.source, Source::File { path } if *path == dir.path("a/x.png"))).map(|p| p.id).unwrap(); + // everything in `a` was put into `a/b`: `a/b/x.png` went to `a/b/b/x.png`, `a/x.png` to `a/b/x.png` + std::fs::create_dir_all(dir.0.join("a/b/b")).unwrap(); + std::fs::rename(dir.0.join("a/b/x.png"), dir.0.join("a/b/b/x.png")).unwrap(); + std::fs::rename(dir.0.join("a/x.png"), dir.0.join("a/b/x.png")).unwrap(); + + let r = relocate(&mut s, &dir.path("a"), &dir.path("a/b")); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); + assert!(matches!(&s.catalog.photo(upper).unwrap().source, Source::File { path } if *path == dir.path("a/b/x.png"))); + assert!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().is_empty()); + + // without contents recorded nothing tells the two apart: refused rather than guessed + s.undo_step().unwrap(); + forget_sizes_and_contents(&mut s); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b")})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +/// Another picture under the same name (not the size the library recorded). +fn write_other(path: &str) { + let (w, h) = (40usize, 30usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i * 7) as u8, (i * 3) as u8, (i / 5) as u8, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + assert_ne!(bytes.len() as u64, std::fs::metadata(path).unwrap().len(), "the test needs another size"); + std::fs::write(path, bytes).unwrap(); +} + +#[test] +fn a_file_of_another_size_is_not_counted_as_found() { + let dir = Scratch::new("other-size"); + let mut s = library(&dir); + let now = moved_away(&dir); + write_other(&dir.path("archive/journey/a.png")); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!( + e.contains("1 of the 2 files") && e.contains("1 file there is not the one the library recorded") && e.contains("incomplete: true"), + "{e}" + ); + + // on request it is taken: the file was changed where it lies, as files are + let r = update_location(&mut s, &json!({"folder": dir.path("trip"), "path": now, "incomplete": true})).unwrap(); + assert_eq!( + (r["relinked"].as_u64(), r["found"].as_u64(), r["different"].as_u64(), r["notFound"].as_u64()), + (Some(2), Some(1), Some(1), Some(0)), + "{r}" + ); +} + +#[test] +fn a_folder_where_no_file_is_the_librarys_is_not_the_folder() { + let dir = Scratch::new("other-disk"); + let mut s = library(&dir); + let now = moved_away(&dir); + // the same names in the same folders, other pictures: another disk laid out alike + write_other(&dir.path("archive/journey/a.png")); + write_other(&dir.path("archive/journey/day1/b.png")); + + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now, "incomplete": incomplete})); + assert!( + e.contains("none of the 2 files") && e.contains("2 files there are not the ones the library recorded"), + "incomplete {incomplete}: {e}" + ); + } +} + +#[test] +fn a_file_whose_size_the_library_never_recorded_is_taken_and_said() { + let dir = Scratch::new("no-size"); + let mut s = library(&dir); + forget_sizes_and_contents(&mut s); + let now = moved_away(&dir); + write_other(&dir.path("archive/journey/a.png")); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!((r["found"].as_u64(), r["unverified"].as_u64(), r["different"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); +} + +// ── The same place under another spelling (second review) ──────────────────────────────────── +// +// * A place inside the folder is the same place however it is written: with `..`, in other +// letter case on a disk that doesn't tell case apart, or through a link. +// * The folder inside the chosen one is the same mistake the other way round. +// * A file only browsed in Local at the new place is not "another photo": its record gives way. +// * Looking that was stopped found nothing out. + +fn at(s: &Session, path: &str) -> PhotoId { + s.catalog.photos().find(|p| matches!(&p.source, Source::File { path: q } if q == path)).map(|p| p.id).unwrap() +} + +#[test] +#[cfg(unix)] +fn a_place_written_with_dot_dot_is_refused() { + let dir = Scratch::new("dotdot"); + let mut s = same_name_one_level_apart(&dir); + let to = format!("{}{sep}b{sep}..{sep}b", dir.path("a"), sep = std::path::MAIN_SEPARATOR); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": to, "incomplete": true})); + assert!(e.contains("`..`"), "{e}"); +} + +#[test] +fn a_place_inside_the_folder_in_other_letter_case_is_the_same_place() { + let dir = Scratch::new("case"); + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/B/x.png"), 2); + if !Path::new(&dir.path("a/b/x.png")).is_file() { + lightcraft_testkit::skip!(System, "this disk tells `B` from `b`, so `a/b` is no folder"); + return; + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_to_a_place_inside_the_folder_is_the_same_place() { + let dir = Scratch::new("link"); + let mut s = same_name_one_level_apart(&dir); + std::os::unix::fs::symlink(dir.path("a/b"), dir.path("link")).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("link"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_to_the_folder_itself_gives_no_photo_another_photos_file() { + let dir = Scratch::new("link-self"); + let mut s = library(&dir); + forget_sizes_and_contents(&mut s); + std::os::unix::fs::symlink(dir.path("trip"), dir.path("link")).unwrap(); + // every file there is the photo's own, under another name + let r = relocate(&mut s, &dir.path("trip"), &dir.path("link")); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +#[test] +fn the_folder_inside_the_chosen_one_is_the_same_mistake() { + let dir = Scratch::new("too-high"); + write_png(&dir.path("a/b/x.png"), 1); + write_png(&dir.path("a/b/b/x.png"), 2); + write_png(&dir.path("a/b/k.png"), 3); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a/b")]})).unwrap(); + std::fs::copy(dir.path("a/b/k.png"), dir.path("a/k.png")).unwrap(); + forget_sizes_and_contents(&mut s); + // one level too high: `a/b/x.png` would be taken for the photo of `a/b/b/x.png` + let e = refused(&mut s, json!({"folder": dir.path("a/b"), "path": dir.path("a"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +#[test] +fn a_file_only_browsed_in_local_at_a_place_inside_the_folder_gives_way() { + let dir = Scratch::new("nested-local"); + write_png(&dir.path("a/x.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + let photo = at(&s, &dir.path("a/x.png")); + // the file went one level down, and the folder it is in now was looked at in Local + std::fs::create_dir_all(dir.0.join("a/b")).unwrap(); + std::fs::rename(dir.0.join("a/x.png"), dir.0.join("a/b/x.png")).unwrap(); + s.execute("library.browse", &json!({"path": dir.path("a/b")})).unwrap(); + assert_eq!(s.catalog.len(), 2, "the library's photo and the record of having looked"); + + for blind in [false, true] { + if blind { + s.undo_step().unwrap(); + forget_sizes_and_contents(&mut s); + } + let r = relocate(&mut s, &dir.path("a"), &dir.path("a/b")); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["replacedLocal"].as_u64()), (Some(1), Some(1), Some(1)), "blind {blind}: {r}"); + assert_eq!(files(&s), [dir.path("a/b/x.png")], "one record for the one file"); + assert!(s.catalog.photo(photo).is_some_and(|p| p.in_library())); + } +} + +#[test] +fn a_claimed_file_of_another_size_than_the_photos_is_not_read_to_be_refused() { + let dir = Scratch::new("claimed-size"); + let mut s = same_name_one_level_apart(&dir); + write_other(&dir.path("a/b/x.png")); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +#[test] +fn looking_that_was_stopped_found_nothing_out() { + let dir = Scratch::new("stopped"); + let s = library(&dir); + let now = moved_away(&dir); + let stopped = crate::import::ScanProgress::default(); + stopped.cancel.store(true, Ordering::Relaxed); + let e = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&stopped).unwrap_err(); + assert!(e.contains("stopped"), "{e}"); +} + +#[test] +fn a_files_content_read_in_pieces_is_the_content_import_recorded() { + let bytes: Vec = (0..300_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + let pieces = crate::cmd::missing::hash_reader(&bytes[..]).unwrap(); + assert_eq!(pieces, lightcraft_preview::hash_bytes(&bytes).to_string()); +} + +// ── Third review: files shared below the two folders, and a browsed file that is another picture ─ + +#[cfg(unix)] +#[test] +fn a_link_inside_the_folder_to_the_chosen_place_is_seen() { + let dir = Scratch::new("link-below-from"); + write_png(&dir.path("big/2023/x.png"), 2); + write_png(&dir.path("pics/x.png"), 1); + std::os::unix::fs::symlink(dir.path("big/2023"), dir.path("pics/2023")).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("pics/x.png"), dir.path("pics/2023/x.png")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + // `big/2023/x.png` is the file of the photo at `pics/2023/x.png` + let e = refused(&mut s, json!({"folder": dir.path("pics"), "path": dir.path("big/2023"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_inside_the_chosen_place_back_to_the_folder_is_seen() { + let dir = Scratch::new("link-below-to"); + let mut s = Session::new().with_fs(); + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/sub/x.png"), 2); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + std::fs::create_dir_all(dir.0.join("new")).unwrap(); + std::fs::copy(dir.path("a/x.png"), dir.path("new/x.png")).unwrap(); + std::os::unix::fs::symlink(dir.path("a"), dir.path("new/sub")).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + // `new/sub/x.png` is `a/x.png`: the other photo's file + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("new"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[test] +fn a_browsed_file_inside_the_folder_that_is_another_picture_is_not_taken_for_the_photo() { + let dir = Scratch::new("nested-local-other"); + write_png(&dir.path("a/x.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + // nothing moved: one level down lies another picture of the same name (and size), looked at in Local + write_png(&dir.path("a/b/x.png"), 2); + s.execute("library.browse", &json!({"path": dir.path("a/b")})).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("another picture than the library recorded"), "{e}"); +} + +#[test] +#[cfg(unix)] +fn a_relative_place_with_dot_dot_is_told_to_be_written_in_full() { + let dir = Scratch::new("dotdot-relative"); + // (Windows resolves `..` itself when it makes the path absolute: unix only, like the other `..` test) + let mut s = library(&dir); + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": ".."})); + assert!(e.contains("full path"), "{e}"); +} diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index ce2e2cbdf6..cc79b5165c 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -627,6 +627,25 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() { let _ = std::fs::remove_dir_all(&src); } +/// A sidecar that says nothing beside a photo whose file states an orientation isn't one the import counts: the +/// file's orientation goes to a sidecar that said something, not into an empty one (#2674, #2589). +#[test] +fn an_empty_sidecar_beside_a_turned_photo_is_not_counted() { + let src = temp_dir("regions-empty-sidecar"); + let file = src.join("p.jpg"); + write_turned_jpeg(&file, None); + std::fs::write( + src.join("p.xmp"), + r#""#, + ) + .unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!(r["sidecars"], 0, "{r}"); + let _ = std::fs::remove_dir_all(&src); +} + /// Review of #2857: a photo whose Exif states no orientation, but whose XMP says `tiff:Orientation=6`, is shown as /// stored (LightCraft turns by the Exif alone), so boxes drawn on its stored frame are right as written: at import /// and when the file's metadata is read again, which must agree. diff --git a/crates/engine/src/walk.rs b/crates/engine/src/walk.rs index f0c4033dd6..c3173968a5 100644 --- a/crates/engine/src/walk.rs +++ b/crates/engine/src/walk.rs @@ -94,9 +94,24 @@ pub enum EntryKind { /// What [`files_in_noting`] hands over for each folder it lists: the folder, the name and kind /// of every entry in it (hidden ones too), and whether that is all of them (not when the walk -/// stopped inside the folder, or an entry could not be read). It answers whether to go on: `false` -/// ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows). -pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool) -> bool; +/// stopped inside the folder, or an entry could not be read), and the folder's modification time when the walk read +/// it and it was old enough to show a later change ([`files_in_noting_timed`]; else `None`). It answers whether to go +/// on: `false` ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows). +pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool, Option) -> bool; + +/// How old a folder's modification time must be, when the folder is read, for a change after the +/// listing to show in it. File systems keep folder times in whole seconds (HFS+, ext3) or two +/// (FAT, and SMB1's DOS times): a file added in the same tick as the listing would leave the +/// time as it was. Two seconds is the coarsest of them (git's "racily clean" rule, for the same reason). +const TIME_GRAIN: std::time::Duration = std::time::Duration::from_secs(2); + +/// `dir`'s modification time, when it is old enough ([`TIME_GRAIN`]) that a change after now +/// would move it: read before the folder is listed, so nothing added during the listing hides. +fn settled_time(dir: &Path) -> Option { + let modified = std::fs::metadata(dir).and_then(|m| m.modified()).ok()?; + let now = std::time::SystemTime::now(); + modified.checked_add(TIME_GRAIN).filter(|t| *t <= now).map(|_| modified) +} /// The files below folder `root` that `keep` accepts. Hidden entries (names starting with `.`) /// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops @@ -123,7 +138,13 @@ pub fn files_in_entering( /// find its files has, with that, the answer to "is this name there" for everything in it, and /// need not ask the disk again (a round trip for each name on a network share). pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { - walk(root, skip, limits, keep, |_| true, Some(note)) + walk(root, skip, limits, keep, |_| true, Some((note, false))) +} + +/// [`files_in_noting`], also reading each folder's modification time (before it is listed; a round +/// trip on a network share) and handing it over when it is old enough to show a later change. +pub fn files_in_noting_timed(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked { + walk(root, skip, limits, keep, |_| true, Some((note, true))) } fn walk( @@ -132,7 +153,7 @@ fn walk( limits: Limits, mut keep: impl FnMut(&Path) -> bool, mut enter: impl FnMut(&Path) -> bool, - mut note: Option, + mut note: Option<(NoteFolder, bool)>, ) -> Walked { let mut out = Walked::default(); // canonical folders reached through a link, so a link loop is walked at most once @@ -160,6 +181,7 @@ fn walk( out.truncated = true; continue; } + let modified = if note.as_ref().is_some_and(|n| n.1) { settled_time(&path) } else { None }; let Ok(rd) = std::fs::read_dir(&path) else { out.unreadable = out.unreadable.saturating_add(1); continue; @@ -227,8 +249,8 @@ fn walk( }; children.push((p, dir)); } - if let (Some(note), Some(listed)) = (note.as_mut(), listed) - && !note(&path, listed, complete) + if let (Some((note, _)), Some(listed)) = (note.as_mut(), listed) + && !note(&path, listed, complete, modified) { break; } @@ -292,7 +314,7 @@ mod tests { #[cfg(unix)] std::os::unix::fs::symlink(root.join("a.jpg"), root.join("link.jpg")).unwrap(); let mut noted: Vec<(PathBuf, Vec<(String, EntryKind)>, bool)> = Vec::new(); - let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete| { + let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete, _| { let mut entries: Vec<(String, EntryKind)> = entries.into_iter().map(|(n, k)| (n.to_string_lossy().to_string(), k)).collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); noted.push((dir.to_path_buf(), entries, complete)); @@ -308,7 +330,7 @@ mod tests { // stopped inside the first folder: its listing is not all of it let mut cut = Vec::new(); - let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete| { + let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete, _| { cut.push((dir.to_path_buf(), entries.len(), complete)); true }); diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/src/clip.rs b/crates/segment/src/clip.rs index b69c148a4f..18a82b3dd0 100644 --- a/crates/segment/src/clip.rs +++ b/crates/segment/src/clip.rs @@ -74,7 +74,7 @@ impl TextEncoder { let h = l.ln1.forward(&x)?; x = (&x + l.attn.forward(&h, &h, &h, Some(&bias))?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } Ok(self.final_ln.forward(&x)?) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..ffbd0bde6c --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,551 @@ +//! Fused CPU kernels for the model's elementwise work, attention and upsampling. +//! +//! On the CPU, candle runs bias adds, activations, the rotary encoding and layout copies (window +//! partitioning, splitting and merging heads) one element at a time on one thread, batched matrix +//! products one pair at a time and transposed convolutions one output channel at a time: in the +//! 32-layer ViT that was more than half of the encode time on a 12-core CPU, and most of a text +//! prompt went to attention over 5184 tokens. The elementwise kernels do the same arithmetic in +//! the same order (bit-identical results), fused into fewer passes over memory and spread over +//! the rayon pool that candle's matrix products use. Attention in cache-sized blocks and the +//! transposed convolutions as one product change how gemm blocks its sums: those results move +//! by float rounding (as they do between two CPUs, gemm picking its blocking from the caches). + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp1, CustomOp2, CustomOp3, D, IndexOp, Layout, Shape, Tensor, bail}; +use candle_nn::{ConvTranspose2d, Linear}; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// A `b × h × w` token grid (row-major, `heads × head_dim` channels) attended in non-overlapping +/// `win × win` windows, or as a whole when `win` is 0. +#[derive(Clone, Copy, Debug)] +pub struct Grid { + pub b: usize, + pub h: usize, + pub w: usize, + pub win: usize, + pub heads: usize, + pub head_dim: usize, +} + +impl Grid { + /// Window height and width. + fn window(&self) -> (usize, usize) { + if self.win == 0 { (self.h, self.w) } else { (self.win, self.win) } + } + + /// Windows per image (down, across). + fn per_image(&self) -> (usize, usize) { + let (wh, ww) = self.window(); + (self.h / wh, self.w / ww) + } + + fn windows(&self) -> usize { + let (nh, nw) = self.per_image(); + self.b * nh * nw + } + + fn tokens(&self) -> usize { + let (wh, ww) = self.window(); + wh * ww + } + + fn channels(&self) -> usize { + self.heads * self.head_dim + } + + fn check(&self) -> candle_core::Result<()> { + let (wh, ww) = self.window(); + if wh == 0 || ww == 0 || !self.h.is_multiple_of(wh) || !self.w.is_multiple_of(ww) || !self.head_dim.is_multiple_of(2) { + bail!("grid {self:?}: windows must tile the grid"); + } + Ok(()) + } + + /// The grid row (token index in row-major order) of token `t` of window `win`. + fn row(&self, win: usize, t: usize) -> usize { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (win / (nh * nw), win % (nh * nw)); + let (y, x) = (i / nw * wh + t / ww, i % nw * ww + t % ww); + (b * self.h + y) * self.w + x + } + + /// The window and the token within it of grid row `row`. + fn window_of(&self, row: usize) -> (usize, usize) { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (row / (self.h * self.w), row % (self.h * self.w)); + let (y, x) = (i / self.w, i % self.w); + ((b * nh + y / wh) * nw + x / ww, y % wh * ww + x % ww) + } +} + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// `residual + (x · Wᵀ + b)`, shaped like `residual`. +pub fn linear_add(x: &Tensor, l: &Linear, residual: &Tensor) -> Result { + Ok(product(x, l)?.apply_op3_no_bwd(bias(l)?, &residual.contiguous()?, &BiasAdd)?) +} + +/// The projection `x · Wᵀ + b` of the grid's tokens (`x`: `[b, h, w, C]`), split into heads per +/// window: `[windows, heads, tokens, head_dim]`, with the rotary encoding (`cos`, `sin`: +/// `[tokens, head_dim]`) applied when given, then multiplied by `scale`. +pub fn heads(x: &Tensor, l: &Linear, grid: Grid, rope: Option<(&[f32], &[f32])>, scale: f32) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &Heads { grid, rope, scale })?) +} + +/// Attention scores computed per task (elements): a block of query rows against all keys, +/// small enough (256 KB) to stay in a core's L2 cache between the two products and the softmax. +/// 4 MB blocks were 3× slower for the detector's 5184-token attention (8 heads of 32). +const SCORE_TILE: usize = 1 << 16; + +/// `nn::sdpa` on `[B, H, L, d]` tensors (`bias` `[B or 1, H or 1, Lq or 1, Lk]`): the same +/// operations (scores × `scale` unless it is 1, plus the bias, softmax, × v), but candle +/// multiplies batched matrices one pair after another, each spread over all threads, which is +/// slow for 9 windows × 16 heads of 576 tokens or 8 heads of 5184; here every (batch, head, +/// block of query rows) is a task of its own. +pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + let (b, h, lq, _) = q.dims4()?; + let (lk, dv) = (k.dim(2)?, v.dim(3)?); + let bias = match bias { + Some(t) => Some((t, t.dims4()?)), + None => None, + }; + let rows = (SCORE_TILE / lk.max(1)).clamp(1, lq.max(1)); + let tasks: Vec<(usize, usize, usize)> = (0..b * h).flat_map(|i| (0..lq).step_by(rows).map(move |r| (i / h, i % h, r))).collect(); + let out = tasks + .par_iter() + .map(|&(bi, hi, r)| -> Result { + let n = rows.min(lq - r); + let mut att = q.i((bi, hi))?.narrow(0, r, n)?.matmul(&k.i((bi, hi))?.t()?)?; + if scale != 1.0 { + att = (att * scale)?; + } + if let Some((t, (tb, th, tq, _))) = bias { + let t = t.i((if tb == 1 { 0 } else { bi }, if th == 1 { 0 } else { hi }))?; + att = att.broadcast_add(&if tq == 1 { t } else { t.narrow(0, r, n)? })?; + } + Ok(candle_nn::ops::softmax_last_dim(&att)?.matmul(&v.i((bi, hi))?)?) + }) + .collect::>>()?; + Ok(Tensor::cat(&out, 0)?.reshape((b, h, lq, dv))?) +} + +/// Attention over `q`, `k`, `v` from [`heads`] (`q` already scaled), merged back to the grid: +/// `[b, h, w, C]`. +pub fn attention(q: &Tensor, k: &Tensor, v: &Tensor, grid: Grid) -> Result { + Ok(sdpa(q, k, v, None, 1.0)?.apply_op1_no_bwd(&Merge { grid })?) +} + +/// `ConvTranspose2d` with a 2 × 2 kernel and stride 2 (the neck's upsampling) on `x` +/// `[1, Cin, H, W]`, then GELU when `gelu`: `[1, Cout, 2H, 2W]`. The kernel windows don't overlap, +/// so this is one product `[H·W, Cin] × [Cin, Cout·4]` and a reordering with the bias; candle +/// computes it one output channel at a time (~50 GFLOP/s here). +pub fn upsample2(x: &Tensor, ct: &ConvTranspose2d, gelu: bool) -> Result { + let (b, cin, h, w) = x.dims4()?; + let (wi, cout, kh, kw) = ct.weight().dims4()?; + let c = ct.config(); + if b != 1 || wi != cin || (kh, kw, c.stride, c.padding, c.output_padding, c.dilation) != (2, 2, 2, 0, 0, 1) { + return Err(Error::Model(format!("upsample2: {:?} with a {:?} kernel", x.dims(), ct.weight().dims()))); + } + let y = x.reshape((cin, h * w))?.t()?.matmul(&ct.weight().reshape((cin, cout * 4))?)?; + let bias = match ct.bias() { + Some(b) => b.clone(), + None => Tensor::zeros(cout, candle_core::DType::F32, x.device())?, + }; + Ok(y.apply_op2_no_bwd(&bias, &Unpatch { h, w, gelu })?) +} + +/// `relu(group_norm(x))` over `[B, C, …]` with `groups` groups and per-channel `weight`, `bias`. +/// candle's `GroupNorm` makes eight single-threaded passes over the 288² pixel decoder maps. +pub fn group_norm_relu(x: &Tensor, weight: &Tensor, bias: &Tensor, groups: usize, eps: f64) -> Result { + Ok(x.contiguous()?.apply_op3_no_bwd(weight, bias, &GroupNormRelu { groups, eps })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BiasAdd; + +impl CustomOp3 for BiasAdd { + fn name(&self) -> &'static str { + "bias-residual-add" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b, r) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let n = rows(x, b)?; + if r.len() != x.len() { + bail!("residual of {} for {} values", r.len(), x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).zip(r.par_chunks(n)).for_each(|((o, x), r)| { + for (((o, x), b), r) in o.iter_mut().zip(x).zip(b).zip(r) { + *o = r + (x + b); + } + }); + Ok((CpuStorage::F32(out), l3.shape().clone())) + } +} + +struct Heads<'a> { + grid: Grid, + rope: Option<(&'a [f32], &'a [f32])>, + scale: f32, +} + +impl CustomOp2 for Heads<'_> { + fn name(&self) -> &'static str { + "split-heads-rope" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let (x, bias) = (values(s1, l1)?, values(s2, l2)?); + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if bias.len() != c || x.len() != g.b * g.h * g.w * c { + bail!("heads: {} values with a bias of {} for {g:?}", x.len(), bias.len()); + } + if let Some((cos, sin)) = self.rope + && (cos.len() != n * d || sin.len() != n * d) + { + bail!("rotary tables of {} and {} for {n} tokens", cos.len(), sin.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n * d).enumerate().for_each(|(i, o)| { + let (win, head) = (i / g.heads, i % g.heads); + let bias = &bias[head * d..][..d]; + for (t, o) in o.chunks_exact_mut(d).enumerate() { + let x = &x[g.row(win, t) * c + head * d..][..d]; + for ((o, x), b) in o.iter_mut().zip(x).zip(bias) { + *o = x + b; + } + if let Some((cos, sin)) = self.rope { + // x·cos + rotate_pairwise(x)·sin, rotate_pairwise mapping (a, b) to (−b, a) + let (cos, sin) = (&cos[t * d..][..d], &sin[t * d..][..d]); + for ((o, cos), sin) in o.as_chunks_mut::<2>().0.iter_mut().zip(cos.as_chunks::<2>().0).zip(sin.as_chunks::<2>().0) { + let [a, b] = *o; + *o = [a * cos[0] + -b * sin[0], b * cos[1] + a * sin[1]]; + } + } + for o in o.iter_mut() { + *o *= self.scale; + } + } + }); + let shape = Shape::from((g.windows(), g.heads, n, d)); + Ok((CpuStorage::F32(out), shape)) + } +} + +struct GroupNormRelu { + groups: usize, + eps: f64, +} + +impl CustomOp3 for GroupNormRelu { + fn name(&self) -> &'static str { + "group-norm-relu" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, w, b) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let dims = l1.shape().dims(); + let (batch, c) = match dims { + [batch, c, _, ..] => (*batch, *c), + _ => bail!("group norm of {dims:?}"), + }; + if c == 0 || self.groups == 0 || !c.is_multiple_of(self.groups) || w.len() != c || b.len() != c || x.is_empty() { + bail!("group norm: {dims:?} in {} groups, {} weights", self.groups, w.len()); + } + let hw = x.len() / (batch * c); + let per = c / self.groups * hw; + // mean and σ per (image, group), as candle computes them (f32 sums in order) + let n = (1.0 / per as f64) as f32; + let stats: Vec<(f32, f32)> = x + .par_chunks(per) + .map(|g| { + let mean = g.iter().fold(0f32, |s, v| s + v) * n; + let var = g.iter().fold(0f32, |s, v| s + (v - mean) * (v - mean)) * n; + (mean, (var + self.eps as f32).sqrt()) + }) + .collect(); + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(hw).zip(x.par_chunks(hw)).enumerate().for_each(|(row, (o, x))| { + let ch = row % c; + let (mean, sd) = stats[row / c * self.groups + ch / (c / self.groups)]; + for (o, x) in o.iter_mut().zip(x) { + *o = ((x - mean) / sd * w[ch] + b[ch]).max(0f32); + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +/// `[H·W, Cout·2·2]` patches (+ bias, then GELU) to `[1, Cout, 2H, 2W]`. +struct Unpatch { + h: usize, + w: usize, + gelu: bool, +} + +impl CustomOp2 for Unpatch { + fn name(&self) -> &'static str { + "unpatch-2x2" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (y, bias) = (values(s1, l1)?, values(s2, l2)?); + let (h, w, cout) = (self.h, self.w, bias.len()); + if y.len() != h * w * cout * 4 { + bail!("unpatch: {} values for {h} × {w} × {cout} × 4", y.len()); + } + let mut out = vec![0f32; y.len()]; + // one output row (channel c, row 2·r + i) at a time + out.par_chunks_mut(2 * w).enumerate().for_each(|(row, o)| { + let (c, r, i) = (row / (2 * h), row % (2 * h) / 2, row % 2); + for (x, o) in o.as_chunks_mut::<2>().0.iter_mut().enumerate() { + let p = &y[(r * w + x) * cout * 4 + c * 4 + i * 2..][..2]; + for (o, p) in o.iter_mut().zip(p) { + let v = p + bias[c]; + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v }; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, cout, 2 * h, 2 * w)))) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +struct Merge { + grid: Grid, +} + +impl CustomOp1 for Merge { + fn name(&self) -> &'static str { + "merge-heads" + } + + fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let x = values(s, l)?; + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if x.len() != g.windows() * g.heads * n * d { + bail!("merge: {} values for {g:?}", x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(c).enumerate().for_each(|(row, o)| { + let (win, t) = g.window_of(row); + for (head, o) in o.chunks_exact_mut(d).enumerate() { + o.copy_from_slice(&x[((win * g.heads + head) * n + t) * d..][..d]); + } + }); + Ok((CpuStorage::F32(out), Shape::from((g.b, g.h, g.w, c)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::{ConvTranspose2dConfig, Module}; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + /// The kernels against candle's tensor operations: equal up to float rounding (on x86-64 most + /// are bit-identical; the matrix products may block differently). + fn close(name: &str, got: &Tensor, want: &Tensor) { + assert_eq!(got.dims(), want.dims(), "{name}: shape"); + let (got, want): (Vec, Vec) = (got.flatten_all().unwrap().to_vec1().unwrap(), want.flatten_all().unwrap().to_vec1().unwrap()); + let scale = want.iter().fold(1e-6f32, |m, v| m.max(v.abs())); + let err = got.iter().zip(&want).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(err <= 1e-5 * scale, "{name}: max error {err} (scale {scale})"); + } + + #[test] + fn sdpa_matches_the_tensor_ops() { + // 1000 keys: blocks of 65 query rows, the last one short + let (q, k, v) = (randn(&[2, 3, 150, 8]), randn(&[2, 3, 1000, 8]), randn(&[2, 3, 1000, 5])); + let biases = + [None, Some(randn(&[1, 1, 1, 1000])), Some(randn(&[1, 3, 150, 1000])), Some(randn(&[2, 1, 150, 1000])), Some(randn(&[2, 3, 1, 1000]))]; + for (i, bias) in biases.iter().enumerate() { + for scale in [0.35, 1.0] { + let got = sdpa(&q, &k, &v, bias.as_ref(), scale).unwrap(); + let want = crate::nn::sdpa_tensors(&q, &k, &v, bias.as_ref(), scale).unwrap(); + close(&format!("bias {i}, scale {scale}"), &got, &want); + } + } + } + + #[test] + fn fused_linears_match_the_tensor_ops() { + let x = randn(&[3, 5, 7]); + let l = Linear::new(randn(&[6, 7]), Some(randn(&[6]))); + let y = l.forward(&x).unwrap().reshape((15, 6)).unwrap(); + close("gelu", &linear_act(&x, &l, true).unwrap(), &y.gelu_erf().unwrap()); + close("relu", &linear_act(&x, &l, false).unwrap(), &y.relu().unwrap()); + let r = randn(&[3, 5, 6]); + close("residual", &linear_add(&x, &l, &r).unwrap(), &(&r + l.forward(&x).unwrap()).unwrap()); + assert!(linear_act(&x, &Linear::new(randn(&[6, 7]), None), true).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + close("box bias", &box_bias(&ey, &ex).unwrap(), &want); + } + + #[test] + fn upsampling_matches_the_transposed_convolution() { + let x = randn(&[1, 6, 3, 4]); + let cfg = ConvTranspose2dConfig { stride: 2, ..Default::default() }; + let ct = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), Some(randn(&[5])), cfg); + let want = ct.forward(&x).unwrap(); + close("upsample", &upsample2(&x, &ct, false).unwrap(), &want); + close("upsample + gelu", &upsample2(&x, &ct, true).unwrap(), &want.gelu_erf().unwrap()); + let other = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), None, ConvTranspose2dConfig::default()); + assert!(upsample2(&x, &other, false).is_err()); + } + + #[test] + fn group_norm_matches_candle() { + let x = randn(&[2, 6, 4, 5]); + let (w, b) = (randn(&[6]), randn(&[6])); + let want = candle_nn::GroupNorm::new(w.clone(), b.clone(), 6, 3, 1e-5).unwrap().forward(&x).unwrap().relu().unwrap(); + close("group norm", &group_norm_relu(&x, &w, &b, 3, 1e-5).unwrap(), &want); + assert!(group_norm_relu(&x, &w, &b, 4, 1e-5).is_err()); + } + + #[test] + fn window_indexing_round_trips() { + for win in [0, 3] { + let g = Grid { b: 2, h: 6, w: 9, win, heads: 1, head_dim: 2 }; + g.check().unwrap(); + let mut seen = vec![false; g.b * g.h * g.w]; + for w in 0..g.windows() { + for t in 0..g.tokens() { + let row = g.row(w, t); + assert_eq!(g.window_of(row), (w, t)); + seen[row] = true; + } + } + assert!(seen.iter().all(|s| *s)); + } + assert!(Grid { b: 1, h: 6, w: 9, win: 4, heads: 1, head_dim: 2 }.check().is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index 3099af44af..73608dd30a 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -7,12 +7,14 @@ //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. use candle_core::{D, Device, IndexOp, Module, Tensor}; -use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; +use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; -use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::nn::{ + Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec, +}; +use crate::{Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; @@ -92,7 +94,7 @@ pub struct Detector { prompt_attn: Attention, prompt_ln: LayerNorm, pixel_convs: Vec, - pixel_norms: Vec, + pixel_norms: Vec, instance_proj: Conv2d, semantic_proj: Conv2d, mask_embedder: Vec, @@ -157,7 +159,7 @@ impl Detector { prompt_attn: Attention::new(HIDDEN, HIDDEN, HEADS, m.pp("prompt_cross_attn"))?, prompt_ln: ln(HIDDEN, TORCH_LN_EPS, m.pp("prompt_cross_attn_norm"))?, pixel_convs: (0..3).map(|i| Ok(candle_nn::conv2d(HIDDEN, HIDDEN, 3, conv3, p.pp(format!("conv_layers.{i}")))?)).collect::>()?, - pixel_norms: (0..3).map(|i| Ok(candle_nn::group_norm(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))?)).collect::>()?, + pixel_norms: (0..3).map(|i| GroupNormRelu::new(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))).collect::>()?, instance_proj: candle_nn::conv2d(HIDDEN, HIDDEN, 1, Conv2dConfig::default(), m.pp("instance_projection"))?, semantic_proj: candle_nn::conv2d(HIDDEN, 1, 1, Conv2dConfig::default(), m.pp("semantic_projection"))?, mask_embedder: (0..3).map(|i| linear(HIDDEN, HIDDEN, m.pp(format!("mask_embedder.layers.{i}")))).collect::>()?, @@ -188,6 +190,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -222,7 +227,7 @@ impl Detector { let h = l.ln2.forward(&x)?; x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; let h = l.ln3.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } let memory = x; @@ -241,7 +246,7 @@ impl Detector { h = l.text_ln.forward(&(&h + l.text_attn.forward(&q, &text, &text, Some(&text_bias))?)?)?; let q = (&h + &qpos)?; h = l.vision_ln.forward(&(&h + l.vision_attn.forward(&q, &key_pos, &memory, Some(&bias))?)?)?; - h = l.mlp_ln.forward(&(&h + l.mlp.forward(&h)?)?)?; + h = l.mlp_ln.forward(&l.mlp.forward_add(&h, &h)?)?; let qh = self.out_ln.forward(&h.narrow(1, 1, QUERIES)?)?; boxes = candle_nn::ops::sigmoid(&(self.box_head.forward(&qh)? + inverse_sigmoid(&boxes)?)?)?; let p = self.presence_head.forward(&self.presence_ln.forward(&h.narrow(1, 0, 1)?)?)?; @@ -270,7 +275,7 @@ impl Detector { let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { return Err(Error::Model("pixel decoder".into())); }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + prev = norm.forward(&conv.forward(&prev)?)?; } let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 98a47d9888..567cb84abf 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -29,6 +29,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; diff --git a/crates/segment/src/neck.rs b/crates/segment/src/neck.rs index c4f716dd6f..46cbebf1e5 100644 --- a/crates/segment/src/neck.rs +++ b/crates/segment/src/neck.rs @@ -8,8 +8,8 @@ use candle_core::{Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, ConvTranspose2d, ConvTranspose2dConfig, VarBuilder}; -use crate::Result; use crate::vit::HIDDEN; +use crate::{Result, cpu}; pub const FPN: usize = 256; @@ -64,8 +64,11 @@ impl Neck { pub fn forward(&self, x: &Tensor, n: usize) -> Result> { let mut out = Vec::with_capacity(n); for l in self.levels.iter().take(n) { + let cpu = x.device().is_cpu(); let y = match &l.scale { + Scale::Up4(a, b) if cpu => cpu::upsample2(&cpu::upsample2(x, a, true)?, b, false)?, Scale::Up4(a, b) => b.forward(&a.forward(x)?.gelu_erf()?)?, + Scale::Up2(a) if cpu => cpu::upsample2(x, a, false)?, Scale::Up2(a) => a.forward(x)?, Scale::Same => x.clone(), Scale::Down2 => x.max_pool2d(2)?, diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..0749d9c72a 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -25,8 +25,17 @@ pub fn linear(i: usize, o: usize, vb: VarBuilder) -> Result { const SCORE_BLOCK: usize = 64 << 20; /// Scaled dot-product attention on `[B, H, L, d]` tensors, with an optional additive bias -/// broadcastable to `[B, H, Lq, Lk]`. Heads are processed in groups to bound memory. +/// broadcastable to `[B, H, Lq, Lk]` (on the CPU: [`cpu::sdpa`]). pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + if q.device().is_cpu() && bias.is_none_or(|t| t.rank() == 4) { + return cpu::sdpa(q, k, v, bias, scale); + } + sdpa_tensors(q, k, v, bias, scale) +} + +/// [`sdpa`] with candle's tensor operations (any device). Heads are processed in groups to bound +/// memory. +pub fn sdpa_tensors(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { let (b, h, lq, _) = q.dims4()?; let lk = k.dim(2)?; let per_head = b.saturating_mul(lq).saturating_mul(lk).max(1); @@ -97,6 +106,11 @@ impl Attention { Ok(self.o.forward(x)?) } + /// The q, k, v and output projections. + pub fn projections(&self) -> [&Linear; 4] { + [&self.q, &self.k, &self.v, &self.o] + } + /// `q`, `k`, `v`: `[B, L, hidden]`; `bias` broadcastable to `[B, heads, Lq, Lk]`. pub fn forward(&self, q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>) -> Result { let (b, lq, _) = q.dims3()?; @@ -132,6 +146,14 @@ impl Mlp { let x = if self.gelu { x.gelu_erf()? } else { x.relu()? }; Ok(self.fc2.forward(&x)?) } + + /// `residual + forward(x)`; on the CPU with the bias adds, activation and residual add fused. + pub fn forward_add(&self, x: &Tensor, residual: &Tensor) -> Result { + if !x.device().is_cpu() { + return Ok((residual + self.forward(x)?)?); + } + cpu::linear_add(&cpu::linear_act(x, &self.fc1, self.gelu)?, &self.fc2, residual) + } } /// `Sam3DecoderMLP`: `layer1 … layerN` with ReLU between (2 or 3 layers). @@ -188,6 +210,30 @@ impl FeedForward { } } +/// `nn.GroupNorm` followed by ReLU (the pixel decoder's), fused on the CPU. +pub struct GroupNormRelu { + norm: candle_nn::GroupNorm, + weight: Tensor, + bias: Tensor, + groups: usize, + eps: f64, +} + +impl GroupNormRelu { + pub fn new(groups: usize, channels: usize, eps: f64, vb: VarBuilder) -> Result { + let (weight, bias) = (vb.get(channels, "weight")?, vb.get(channels, "bias")?); + let norm = candle_nn::GroupNorm::new(weight.clone(), bias.clone(), channels, groups, eps)?; + Ok(Self { norm, weight, bias, groups, eps }) + } + + pub fn forward(&self, x: &Tensor) -> Result { + if x.device().is_cpu() { + return cpu::group_norm_relu(x, &self.weight, &self.bias, self.groups, self.eps); + } + Ok(self.norm.forward(x)?.relu()?) + } +} + /// Layer norm over the channel axis of an NCHW tensor (`Sam3TrackerLayerNorm`, channels_first). pub fn ln_channels(x: &Tensor, norm: &LayerNorm) -> Result { let x = x.permute((0, 2, 3, 1))?; diff --git a/crates/segment/src/vit.rs b/crates/segment/src/vit.rs index 16b09a729b..1f356ad547 100644 --- a/crates/segment/src/vit.rs +++ b/crates/segment/src/vit.rs @@ -8,8 +8,8 @@ use candle_core::{D, Device, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, VarBuilder}; -use crate::nn::{Attention, Mlp, ln, sdpa}; -use crate::{Error, Result}; +use crate::nn::{Attention, Mlp, ln, sdpa_tensors}; +use crate::{Error, Result, cpu}; pub const IMAGE: usize = 1008; pub const PATCH: usize = 14; @@ -19,14 +19,26 @@ pub const HIDDEN: usize = 1024; const HEADS: usize = 16; const HEAD_DIM: usize = HIDDEN / HEADS; const LAYERS: usize = 32; +const INTERMEDIATE: usize = 4736; const WINDOW: usize = 24; const GLOBAL: [usize; 4] = [7, 15, 23, 31]; const PRETRAIN_GRID: usize = 336 / PATCH; const EPS: f64 = 1e-6; +/// The attention score scale, `HEAD_DIM^-0.5`. A power of two, so scaling the queries instead +/// of the scores (on the CPU) gives the same scores, bit for bit. +const SCALE: f32 = 0.125; +const _: () = assert!(HEAD_DIM == 64); + +/// Cosine and sine tables `[N, head_dim]`, also as plain values for the CPU kernels. +struct Rope { + cos: Tensor, + sin: Tensor, + values: (Vec, Vec), +} /// Cosine and sine tables `[N, head_dim]` for a `side × side` grid whose coordinates are scaled /// by `scale` (`Sam3ViTRotaryEmbedding`: x frequencies then y, each duplicated pairwise). -fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tensor)> { +fn rope_tables(side: usize, scale: f64, device: &Device) -> Result { let spatial = HEAD_DIM / 2; let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); let n = side * side; @@ -44,7 +56,7 @@ fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tens } } } - Ok((Tensor::from_vec(cos, (n, HEAD_DIM), device)?, Tensor::from_vec(sin, (n, HEAD_DIM), device)?)) + Ok(Rope { cos: Tensor::from_slice(&cos, (n, HEAD_DIM), device)?, sin: Tensor::from_slice(&sin, (n, HEAD_DIM), device)?, values: (cos, sin) }) } /// `x·cos + rotate_pairwise(x)·sin`, where rotate_pairwise maps (a, b) pairs to (−b, a). @@ -71,7 +83,12 @@ struct Layer { impl Layer { /// `x`: `[B, H, W, C]`. - fn forward(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn forward(&self, x: &Tensor, rope: &Rope) -> Result { + if x.device().is_cpu() { self.forward_cpu(x, rope) } else { self.forward_tensors(x, rope) } + } + + /// With candle's tensor operations (any device). + fn forward_tensors(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let y = self.ln1.forward(x)?; let y = match (h.checked_div(self.window), w.checked_div(self.window)) { @@ -90,21 +107,37 @@ impl Layer { Ok((x + y)?) } + /// [`Self::forward`] on the CPU: the same arithmetic, with the window partitioning, head + /// split, rotary encoding, bias adds, GELU and residual adds in fused parallel kernels. + fn forward_cpu(&self, x: &Tensor, rope: &Rope) -> Result { + let (b, h, w, _) = x.dims4()?; + let grid = cpu::Grid { b, h, w, win: self.window, heads: HEADS, head_dim: HEAD_DIM }; + let y = self.ln1.forward(x)?; + let [q, k, v, o] = self.attn.projections(); + let table = Some((rope.values.0.as_slice(), rope.values.1.as_slice())); + let q = cpu::heads(&y, q, grid, table, SCALE)?; + let k = cpu::heads(&y, k, grid, table, 1.0)?; + let v = cpu::heads(&y, v, grid, None, 1.0)?; + let att = cpu::attention(&q, &k, &v, grid)?; + let x = cpu::linear_add(&att, o, x)?; + self.mlp.forward_add(&self.ln2.forward(&x)?, &x) + } + /// RoPE self-attention over `[B, H, W, C]`. - fn attend(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attend(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let seq = x.reshape((b, h * w, c))?; Ok(self.attn_rope(&seq, rope)?.reshape((b, h, w, c))?) } - fn attn_rope(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attn_rope(&self, x: &Tensor, rope: &Rope) -> Result { let (b, n, _) = x.dims3()?; let split = |t: Tensor| -> Result { Ok(t.reshape((b, n, HEADS, HEAD_DIM))?.transpose(1, 2)?.contiguous()?) }; let (q, k, v) = self.attn.qkv(x)?; - let q = apply_rope(&split(q)?, &rope.0, &rope.1)?; - let k = apply_rope(&split(k)?, &rope.0, &rope.1)?; + let q = apply_rope(&split(q)?, &rope.cos, &rope.sin)?; + let k = apply_rope(&split(k)?, &rope.cos, &rope.sin)?; let v = split(v)?; - let o = sdpa(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; + let o = sdpa_tensors(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; let o = o.transpose(1, 2)?.reshape((b, n, HIDDEN))?; self.attn.out(&o) } @@ -115,8 +148,8 @@ pub struct Vit { pos: Tensor, ln_pre: LayerNorm, layers: Vec, - rope_window: (Tensor, Tensor), - rope_global: (Tensor, Tensor), + rope_window: Rope, + rope_global: Rope, } impl Vit { @@ -141,7 +174,7 @@ impl Vit { ln1: ln(HIDDEN, EPS, l.pp("layer_norm1"))?, attn: Attention::new(HIDDEN, HIDDEN, HEADS, l.pp("attention"))?, ln2: ln(HIDDEN, EPS, l.pp("layer_norm2"))?, - mlp: Mlp::new(HIDDEN, 4736, true, l.pp("mlp"))?, + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, l.pp("mlp"))?, window: if GLOBAL.contains(&i) { 0 } else { WINDOW }, }); } @@ -168,3 +201,57 @@ impl Vit { Ok(x.permute((0, 3, 1, 2))?.contiguous()?) } } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use candle_core::DType; + + use super::*; + + /// A layer with random weights. + fn layer(window: usize) -> Layer { + let d = Device::Cpu; + let mut t = HashMap::new(); + let mut add = |name: String, shape: &[usize], mean: f32| { + t.insert(name, Tensor::randn(mean, 0.05f32, shape, &d).unwrap()); + }; + for n in ["layer_norm1", "layer_norm2"] { + add(format!("{n}.weight"), &[HIDDEN], 1.0); + add(format!("{n}.bias"), &[HIDDEN], 0.0); + } + for n in ["q_proj", "k_proj", "v_proj", "o_proj"] { + add(format!("attention.{n}.weight"), &[HIDDEN, HIDDEN], 0.0); + add(format!("attention.{n}.bias"), &[HIDDEN], 0.0); + } + add("mlp.fc1.weight".into(), &[INTERMEDIATE, HIDDEN], 0.0); + add("mlp.fc1.bias".into(), &[INTERMEDIATE], 0.0); + add("mlp.fc2.weight".into(), &[HIDDEN, INTERMEDIATE], 0.0); + add("mlp.fc2.bias".into(), &[HIDDEN], 0.0); + let vb = VarBuilder::from_tensors(t, DType::F32, &d); + Layer { + ln1: ln(HIDDEN, EPS, vb.pp("layer_norm1")).unwrap(), + attn: Attention::new(HIDDEN, HIDDEN, HEADS, vb.pp("attention")).unwrap(), + ln2: ln(HIDDEN, EPS, vb.pp("layer_norm2")).unwrap(), + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, vb.pp("mlp")).unwrap(), + window, + } + } + + #[test] + fn cpu_kernels_match_the_tensor_ops() { + // two images each: 12 × 24 tokens in 6 × 6 windows, and 12 × 12 with global attention + for (window, (h, w), side, scale) in [(6, (12, 24), 6, 1.0), (0, (12, 12), 12, 0.5)] { + let x = Tensor::randn(0f32, 1.0, (2, h, w, HIDDEN), &Device::Cpu).unwrap(); + let (l, rope) = (layer(window), rope_tables(side, scale, &Device::Cpu).unwrap()); + let want = l.forward_tensors(&x, &rope).unwrap().flatten_all().unwrap().to_vec1::().unwrap(); + let got = l.forward_cpu(&x, &rope).unwrap(); + assert_eq!(got.dims(), x.dims()); + let got = got.flatten_all().unwrap().to_vec1::().unwrap(); + let err = want.iter().zip(&got).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + // the same arithmetic (one attention block per window here): equal on x86-64 + assert!(err <= 1e-5, "window {window}: max error {err}"); + } + } +} diff --git a/crates/slideshow/src/lib.rs b/crates/slideshow/src/lib.rs index 5827491d92..7de62086cd 100644 --- a/crates/slideshow/src/lib.rs +++ b/crates/slideshow/src/lib.rs @@ -1,6 +1,7 @@ //! Slideshow slides for LightCraft: the settings of Lightroom Classic's Slideshow Layout, Options //! and Backdrop panels ([`SlideSettings`]) and the CPU composer that draws one slide from a -//! rendered photo ([`compose`]). +//! rendered photo ([`compose`]), and the pan and zoom path a slide's photo follows during +//! playback ([`Motion`]). //! //! No UI and no catalog here: playback, the settings preview, the `slideshow.preview` command and //! (later) slideshow export all call [`compose`], so every one of them draws the same pixels. @@ -17,7 +18,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod compose; +mod motion; mod settings; pub use compose::{Layout, Rect, compose, compose_with, layout, photo_size}; +pub use motion::{Motion, View, ZOOM_HIGH, ZOOM_LOW}; pub use settings::{Aspect, MARGIN_MAX, MAX_SIDE, SHADOW_OFFSET_MAX, SHADOW_RADIUS_MAX, STROKE_MAX, SlideSettings, hex, parse_color}; diff --git a/crates/slideshow/src/motion.rs b/crates/slideshow/src/motion.rs new file mode 100644 index 0000000000..3f4a47db0a --- /dev/null +++ b/crates/slideshow/src/motion.rs @@ -0,0 +1,157 @@ +//! Pan and zoom (the Playback panel's Pan And Zoom): which part of a photo shows at each moment of +//! its slide. +//! +//! A [`Motion`] runs at constant speed from one [`View`] to another over the slide's time. A view +//! is a window of the photo in normalized coordinates (0–1 across and down) with the photo's own +//! aspect, so it never reaches past the photo's edges and is the same at any resolution. The path +//! comes from a key (playback derives it from its seed, the pass and the photo): the same key +//! always gives the same path, and different keys give different ones. + +/// Zoom of the closer view at amount 0 (Low) and at amount 1 (High). +pub const ZOOM_LOW: f64 = 1.01; +pub const ZOOM_HIGH: f64 = 1.12; +/// The wider view's share of the closer view's zoom above 1. +const WIDE_SHARE: f64 = 0.25; + +/// A window of the photo: its zoom (1 = the whole photo) and its center (0–1 across and down). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct View { + pub zoom: f64, + pub x: f64, + pub y: f64, +} + +impl View { + /// The whole photo. + pub const FULL: View = View { zoom: 1.0, x: 0.5, y: 0.5 }; + + /// The window as (x0, y0, x1, y1), inside 0–1: a zoom below 1 or not finite is 1, and the + /// center is kept far enough from the edges for the window to fit. + pub fn window(&self) -> (f64, f64, f64, f64) { + let z = if self.zoom.is_finite() { self.zoom.max(1.0) } else { 1.0 }; + let h = 0.5 / z; + let c = |v: f64| if v.is_finite() { v.clamp(h, 1.0 - h) } else { 0.5 }; + let (x, y) = (c(self.x), c(self.y)); + (x - h, y - h, x + h, y + h) + } +} + +/// A slide's pan and zoom: from `start` when the slide comes up to `end` when its time is over. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Motion { + pub start: View, + pub end: View, +} + +/// SplitMix64 step. +fn mix(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// A number in 0–1 from `state`. +fn unit(state: &mut u64) -> f64 { + (mix(state) >> 11) as f64 / (1u64 << 53) as f64 +} + +impl Motion { + /// The path for `key` at `amount` (0 = Low, 1 = High; clamped, not finite = 0.5). One end is + /// the closer view (zoom [`ZOOM_LOW`] at Low to [`ZOOM_HIGH`] at High), the other a wider one; + /// whether the slide zooms in or out and where each view sits come from the key. + pub fn new(key: u64, amount: f64) -> Motion { + let a = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.5 }; + let close = ZOOM_LOW + (ZOOM_HIGH - ZOOM_LOW) * a; + let wide = 1.0 + (close - 1.0) * WIDE_SHARE; + let mut st = key; + let (z0, z1) = if unit(&mut st) < 0.5 { (wide, close) } else { (close, wide) }; + let mut place = |z: f64| { + let room = 1.0 - 1.0 / z; + View { zoom: z, x: 0.5 / z + room * unit(&mut st), y: 0.5 / z + room * unit(&mut st) } + }; + let start = place(z0); + let end = place(z1); + Motion { start, end } + } + + /// The view at `t` (0 = the slide's start, 1 = its end; clamped, not finite = 0). Zoom and + /// center move linearly; the window stays inside the photo all the way. + pub fn at(&self, t: f64) -> View { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + let l = |a: f64, b: f64| a + (b - a) * t; + View { zoom: l(self.start.zoom, self.end.zoom), x: l(self.start.x, self.end.x), y: l(self.start.y, self.end.y) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn inside(v: View) -> bool { + let (x0, y0, x1, y1) = v.window(); + x0 >= 0.0 && y0 >= 0.0 && x1 <= 1.0 + 1e-12 && y1 <= 1.0 + 1e-12 && x1 > x0 && y1 > y0 + } + + #[test] + fn the_same_key_gives_the_same_path_and_other_keys_other_paths() { + assert_eq!(Motion::new(7, 0.5), Motion::new(7, 0.5)); + let paths: Vec = (0..32).map(|k| Motion::new(k, 0.5)).collect(); + for (i, a) in paths.iter().enumerate() { + for b in &paths[i + 1..] { + assert_ne!(a, b, "every key has its own path"); + } + } + assert!(paths.iter().any(|m| m.start.zoom < m.end.zoom) && paths.iter().any(|m| m.start.zoom > m.end.zoom), "in and out"); + } + + #[test] + fn the_amount_sets_how_far_it_zooms() { + for k in 0..64 { + let low = Motion::new(k, 0.0); + let high = Motion::new(k, 1.0); + let close = |m: &Motion| m.start.zoom.max(m.end.zoom); + assert!((close(&low) - ZOOM_LOW).abs() < 1e-12, "{low:?}"); + assert!((close(&high) - ZOOM_HIGH).abs() < 1e-12, "{high:?}"); + assert!(low.start.zoom > 1.0 && low.end.zoom > 1.0, "Low still moves a little"); + } + assert_eq!(Motion::new(3, 7.0), Motion::new(3, 1.0), "clamped"); + assert_eq!(Motion::new(3, f64::NAN), Motion::new(3, 0.5)); + } + + #[test] + fn the_window_never_leaves_the_photo() { + for k in 0..256 { + let m = Motion::new(k, (k % 5) as f64 / 4.0); + for i in 0..=20 { + let v = m.at(i as f64 / 20.0); + assert!(inside(v), "key {k} at {i}: {v:?} {:?}", v.window()); + } + } + let m = Motion::new(1, 1.0); + assert_eq!(m.at(-1.0), m.start); + assert_eq!(m.at(2.0), m.end); + assert_eq!(m.at(f64::NAN), m.start); + assert_eq!(View::FULL.window(), (0.0, 0.0, 1.0, 1.0)); + assert_eq!(View { zoom: f64::NAN, x: 9.0, y: -1.0 }.window(), (0.0, 0.0, 1.0, 1.0), "bad values: the whole photo"); + assert_eq!(View { zoom: 2.0, x: 0.0, y: 1.0 }.window(), (0.0, 0.5, 0.5, 1.0), "the center is moved in"); + } + + /// The window takes the same share of the photo's width and height at every moment, so it + /// keeps the photo's shape whatever the photo's aspect. The slideshow's drawing of very narrow + /// and very wide photos is tested in the app. + #[test] + fn the_window_takes_the_same_share_of_width_and_height() { + for k in 0..64 { + for amount in [0.0, 0.5, 1.0] { + let m = Motion::new(k, amount); + for i in 0..=10 { + let (x0, y0, x1, y1) = m.at(i as f64 / 10.0).window(); + assert!(((x1 - x0) - (y1 - y0)).abs() < 1e-12, "key {k} at {i}: {:?}", (x0, y0, x1, y1)); + assert!(x1 - x0 < 1.0, "key {k} at {i}: zoomed in"); + } + } + } + } +} diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 980434b317..728059b0e3 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -124,6 +124,7 @@ fn micro(points: usize, pending: bool) { quick: None, pixels: None, native: None, + slide_photo: None, }, ); } diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 2c119c9fe5..f62de3260a 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -35,7 +35,7 @@ "Add Keyword “{keywords}”": "Přidat klíčové slovo „{keywords}“", "Adding photos… {} of {}": "Přidávání fotografií… {} z {}", "All {n} selected photos move by the same amount.": "Všech {n} vybraných fotografií se posune o stejnou hodnotu.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Již v knihovně, v nedávno odstraněných: vybrané fotografie: {}{:.0} · pravé tlačítko → Obnovit, nebo Trvale odstranit pro nový import", "Already in the library: {} photo{} selected in All Photos": "Již v knihovně: ve všech fotografiích vybráno: {}{:.0}", "Auto ({})": "Automaticky ({})", "Auto Import: added {} photo{}": "Automatický import: přidáno fotografií: {}{:.0}", @@ -83,7 +83,7 @@ "Imported {n} point curve preset{}": "Importovaná přednastavení bodové křivky: {n}{:.0}", "Imported {n} preset{}": "Importovaná přednastavení: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importovaná přednastavení: {n}{0:.0}, nečitelné soubory: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importované profily: {profiles}{:.0} (Prohlížeč profilů → jejich skupiny)", "Imported {} photo{}": "Importováno fotografií: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Ve frontě na redukci šumu pomocí AI (před vámi: {ahead})…", "Insert at the cursor (also written {})": "Vložit na pozici kurzoru (také se zapisuje {})", @@ -212,7 +212,7 @@ "{n} photo{}": "fotografií: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Odpovídající fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", "{n} photo{} now · updates automatically as photos change": "Aktuální fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", + "{n} similar photo{} · View → Clear Filters to see all": "Podobné fotografie: {n}{:.0} · Zobrazení → Zrušit filtry zobrazí všechny", "{n} tasks are still running: {names}. Quitting stops them.": "Stále běží úlohy: {n}: {names}. Ukončení aplikace je zastaví.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -258,7 +258,7 @@ "Create the keyword “{name}”": "Vytvořit klíčové slovo „{name}“", "new, inside {parent}": "nové, pod {parent}", "Keywords of {n} selected photos": "Klíčová slova vybraných fotografií (počet: {n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Klíčové slovo „{name}“ bylo odebráno z fotografií v počtu {n}. Úpravy → Zpět jej vrátí.", "Inside: {names}": "Uvnitř: {names}", " in {g} group{}": " ve skupinách: {g}{:.0}", " · kept, not applied: {}": " · zachováno, nepoužito: {}", @@ -269,7 +269,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Odstranit přednastavení efektů v počtu {n}{:.0}? Tuto akci nelze vrátit zpět.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Exportováno přednastavení efektů: {0}{1:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importováno efektů masek: {e}{:.0} (Maskování → Efekt)", "Update “{name}” with Current Settings": "Aktualizovat „{name}“ podle aktuálního nastavení", "{n} preset{}": "Přednastavení: {n}{:.0}", "{count} more warnings.": "Další varování: {count}.", @@ -283,6 +283,7 @@ "Exported to {path}": "Exportováno do {path}", "Saved template {name}": "Uložena šablona {name}", "Imported {name}": "Importováno: {name}", + "Moved {name} to {folder}": "{name} přesunuto do složky {folder}", "Skipped {problem}": "Přeskočeno: {problem}", "…and {more} more": "…a další: {more}", "Template preview: {name}": "Náhled šablony: {name}", @@ -326,5 +327,7 @@ "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek", ", rating {} of 5": ", hodnocení: {} z 5" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index c2943c21a8..39eaa5a400 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1366,8 +1366,7 @@ "Photo Grid": "Mřížka fotografií", "Photo Grid (G)": "Mřížka fotografií (G)", "Photo Merge": "Sloučení fotografií", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Fotografie → Upravit v externím editoru (⇧⌘E) vykreslí 16bitovou kopii TIFF, přidá ji do sady s originálem a otevře v této aplikaci (název aplikace v macOS, jinde cesta k programu).", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Fotografie → Upravit v → Upravit v PhotoCraft (⇧⌘E nebo pravé tlačítko na fotografii) vykreslí kopii s vašimi úpravami, přidá ji do sady s originálem a otevře v PhotoCraft. Po uložení se kopie zde aktualizuje. Do PSD ukládá PhotoCraft přímo. Umístění ponechte prázdné, pokud nepoužíváte přenosnou kopii.", "PhotoCraft": "PhotoCraft", "Photos": "Fotografie", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Fotografie upravené v HDR: JPEG s mapou zisku HDR (správné zobrazení všude, jasnější světla na displejích HDR), AVIF jako 10bitový, PNG a JPEG XL jako 16bitové Rec. 2020 PQ; TIFF vyžaduje 32bitová čísla s plovoucí řádovou čárkou", @@ -1558,7 +1557,7 @@ "Remove location info": "Odebrat informace o poloze", "Remove missing photos from the library": "Odebrat chybějící fotografie z knihovny", "Remove shortcut": "Odebrat zkratku", - "Remove this face box (undo with Edit ▸ Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", + "Remove this face box (undo with Edit → Undo)": "Odebrat tento rámeček obličeje (vrátit přes Úpravy → Zpět)", "Remove this filter": "Odebrat tento filtr", "Remove this group": "Odebrat tuto skupinu", "Remove this rule": "Odebrat toto pravidlo", @@ -1598,7 +1597,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Obnoví všechny křivky: bodové (všechny kanály) i parametrickou (dvojklik na kanál obnoví pouze tento kanál)", "Reset all edits": "Obnovit všechny úpravy", "Reset all edits (Cmd+Shift+R)": "Obnovit všechny úpravy (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Inteligentní alba se aktualizují automaticky: změňte jejich pravidla nebo použijte Fotografie → Odstranit fotografii", "LightCraft stopped": "LightCraft se neočekávaně ukončil", "Zoom to Focus Point": "Přiblížit na zaostřovací bod", "Focus": "Zaostření", @@ -1644,7 +1643,7 @@ "Revert": "Vrátit změny", "Review": "Zkontrolovat", "Review Import": "Zkontrolovat import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Pravé tlačítko na fotografii → Nastavit jako referenční fotografii, pak Zobrazení → Referenční zobrazení (Shift+R)", "Right-click a preset to delete it": "Přednastavení odstraníte kliknutím pravým tlačítkem", "Rights Usage Terms": "Podmínky použití práv", "Rotate": "Otočit", @@ -2482,6 +2481,10 @@ "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", "Bottom bar": "Dolní lišta", + "User Templates": "Uživatelské šablony", + "Delete Folder": "Odstranit složku", + "Folder name": "Název složky", + "Its templates move to User Templates.": "Její šablony se přesunou do složky Uživatelské šablony.", "Welcome to LightCraft": "Vítejte v LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Rychlá a nedestruktivní knihovna fotografií a vývojář RAW: originály zůstanou nedotčené a každou úpravu lze později znovu prohlédnout nebo vrátit.", "Bring photos in with File › Import Photos…": "Fotografie importujete přes Soubor › Importovat fotografie…", @@ -2510,6 +2513,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Vypne animace přiblížení a načítacích indikátorů. Prolínání zůstává. Dokud to zde nezměníte, řídí se nastavením Omezit pohyb v systému.", "Use the system setting": "Použít nastavení systému", "Turns off zoom and spinner animations. Fades stay.": "Vypne animace přiblížení a načítacích indikátorů. Prolínání zůstává.", + "Drag to move, or use the arrow keys": "Přetažením přesunete, nebo použijte šipky", + "A group can't go inside itself": "Skupinu nelze vložit do sebe samé", + "Groups can't nest any deeper": "Skupiny nelze vnořovat hlouběji", "Stack — click to expand (S)": "Sada — kliknutím rozbalíte (S)", "Stack — click to collapse (S)": "Sada — kliknutím sbalíte (S)", "Virtual copy": "Virtuální kopie", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index a09786eb28..867e14b5a5 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -26,7 +26,7 @@ "Adjustments: {n}": "Anpassungen: {n}", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", "Already in the library: {} photo{} selected in All Photos": "Bereits in der Bibliothek: {} Foto{} in „Alle Fotos“ ausgewählt", "Auto ({})": "Automatisch ({})", "Auto Import: added {} photo{}": "Automatischer Import: {} Foto{} hinzugefügt", @@ -76,7 +76,7 @@ "Imported {n} point curve preset{}": "Importierte Punktkurvenvorgaben: {n}{:.0}", "Imported {n} preset{}": "Importierte Vorgaben: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Importierte Vorgaben: {n}{0:.0}, nicht lesbare Dateien: {f}{1:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importierte Profile: {profiles}{:.0} (Profilbrowser → jeweilige Gruppen)", "Imported {} photo{}": "{} Foto{} importiert", "Insert at the cursor (also written {})": "An Cursorposition einfügen (auch als {} geschrieben)", "Label Set: {name}": "Farbmarkierungssatz: {name}", @@ -201,7 +201,7 @@ "… and {more} more": "… und {more} weitere", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft kann diese RAW-Variante noch nicht dekodieren ({}). Du bearbeitest die eingebettete JPEG-Vorschau der Kamera. Sie enthält bereits deren Bildstil (z. B. Monochrom) und Weißabgleich.", "Filtered: {label}": "Gefiltert: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", + "{n} similar photo{} · View → Clear Filters to see all": "Ähnliche Fotos: {n}{:.0} · Ansicht → Filter löschen zeigt alle Fotos", "Moved; {} photo(s) relinked": "Verschoben; {} Foto(s) neu verknüpft", "{} label (click more labels to show any of them)": "Farbmarkierung {} (weitere Farbmarkierungen auswählen, um alle passenden Fotos zu zeigen)", ", {} label": ", Farbmarkierung: {}", @@ -249,7 +249,7 @@ "Create the keyword “{name}”": "Stichwort „{name}“ erstellen", "new, inside {parent}": "neu, in {parent}", "Keywords of {n} selected photos": "Stichwörter von {n} ausgewählten Fotos", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "„{name}“ von {n} Fotos entfernt. Bearbeiten → Rückgängig stellt es wieder her.", "1 task is still running: {names}. Quitting stops it.": "1 Aufgabe läuft noch: {names}. Beenden bricht sie ab.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} Aufgaben laufen noch: {names}. Beenden bricht sie ab.", "{what} merge cancelled": "{what}-Zusammenfügung abgebrochen", @@ -270,7 +270,7 @@ "Delete {n} effect preset{}? This can't be undone.": "{n} Effektvorgabe(n) löschen?{:.0} Dies kann nicht rückgängig gemacht werden.", "Effect: {name}": "Effekt: {name}", "Exported {} effect preset{}": "Exportierte Effektvorgaben: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} Maskeneffekt(e) importiert{:.0} (Maskieren → Effekt)", "Update “{name}” with Current Settings": "„{name}“ mit aktuellen Einstellungen aktualisieren", "{n} preset{}": "{n} Vorgabe(n){:.0}", "{name} opened in the other editor": "{name} im anderen Editor geöffnet", @@ -287,6 +287,7 @@ "Exported to {path}": "Exportiert nach {path}", "Saved template {name}": "Vorlage {name} gespeichert", "Imported {name}": "{name} importiert", + "Moved {name} to {folder}": "{name} nach {folder} verschoben", "Skipped {problem}": "Übersprungen: {problem}", "…and {more} more": "…und {more} weitere", "Template preview: {name}": "Vorlagenvorschau: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} von {m}: {what}. Mit den Pfeiltasten verschieben", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppe {n} von {m}: erfülle {mode}, {count} darin. Mit den Pfeiltasten verschieben", ", rating {} of 5": ", Bewertung: {} von 5" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index c1af309f7c..991ca0b761 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -1087,7 +1087,6 @@ "Photo Grid (G)": "Fotoraster (G)", "Photo Merge": "Fotos zusammenfügen", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "Fotomenü. Auch der Filmstreifen besitzt das Fotokontextmenü. Wird eine Datei erneut hinzugefügt, die unter „Zuletzt gelöscht“ liegt,", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → In externem Editor bearbeiten (⇧⌘E) rendert eine 16-Bit-TIFF-Kopie, stapelt sie mit dem Original und öffnet sie hier (App-Name unter macOS, sonst Programmpfad).", "Photos": "Fotos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "In HDR bearbeitete Fotos: JPEG mit HDR-Gain-Map (sieht überall richtig aus, hellere Lichter auf HDR-Bildschirmen), AVIF mit 10 Bit, PNG und JPEG XL mit 16 Bit Rec. 2020 PQ; TIFF braucht 32-Bit-Gleitkomma", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "Fotos unter „Zuletzt gelöscht“ können in der App wiederhergestellt werden: Rechtsklick → Wiederherstellen oder Endgültig löschen, auch im", @@ -1220,6 +1219,7 @@ "Refresh View": "Ansicht aktualisieren", "Reject": "Ablehnen", "Reject below focus": "Unter Schärfegrenzwert ablehnen", + "Stack each burst, best photo on top": "Jede Serie stapeln, bestes Foto oben", "Burst: shots at most this far apart": "Serie: Aufnahmen höchstens so weit auseinander", "Burst: how alike (loose … strict)": "Serie: wie ähnlich (locker … streng)", "Lower it when a panning or moving burst splits into several groups.": "Senken, wenn eine Mitzieher- oder Bewegungsserie in mehrere Gruppen zerfällt.", @@ -1252,7 +1252,7 @@ "Remove from survey": "Aus Übersicht entfernen", "Remove location info": "Ortsinformationen entfernen", "Remove shortcut": "Tastenkürzel entfernen", - "Remove this face box (undo with Edit ▸ Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", + "Remove this face box (undo with Edit → Undo)": "Diesen Gesichtsrahmen entfernen (rückgängig über Bearbeiten → Rückgängig)", "Remove this filter": "Diesen Filter entfernen", "Remove this group": "Diese Gruppe entfernen", "Remove this rule": "Diese Regel entfernen", @@ -1308,7 +1308,7 @@ "Revert": "Zurück zum letzten Stand", "Review": "Überprüfung", "Review Import": "Import überprüfen", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Rechtsklick auf ein Foto → Als Referenzfoto festlegen, dann Ansicht → Referenzansicht (Umschalt+R)", "Right-click a preset to delete it": "Rechtsklick auf eine Vorgabe, um sie zu löschen", "Rights Usage Terms": "Nutzungsbedingungen", "Rotate": "Drehen", @@ -2328,7 +2328,7 @@ "Tidying the thumbnail cache": "Miniaturcache wird aufgeräumt", "Checking free disk space": "Freier Speicherplatz wird geprüft", "Reset all edits (Cmd+Shift+R)": "Alle Bearbeitungen zurücksetzen (⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smart-Alben aktualisieren sich selbst: Ändere ihre Regeln oder verwende Foto → Foto löschen", "LightCraft stopped": "LightCraft wurde beendet", "Zoom to Focus Point": "Auf Fokuspunkt zoomen", "Focus": "Fokus", @@ -3518,6 +3518,10 @@ "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "User Templates": "Benutzervorlagen", + "Delete Folder": "Ordner löschen", + "Folder name": "Ordnername", + "Its templates move to User Templates.": "Seine Vorlagen werden nach „Benutzervorlagen“ verschoben.", "Welcome to LightCraft": "Willkommen bei LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Eine schnelle, zerstörungsfreie Fotobibliothek und Raw-Entwickler: Ihre Originale bleiben unberührt, und jede Bearbeitung lässt sich jederzeit ansehen oder zurücksetzen.", "Bring photos in with File › Import Photos…": "Fotos holen Sie mit Datei › Fotos importieren…in die Bibliothek.", @@ -3545,6 +3549,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Schaltet Zoom- und Ladeanimationen ab. Überblendungen bleiben erhalten. Folgt der Systemeinstellung „Bewegung reduzieren“, bis Sie sie hier ändern.", "Use the system setting": "Systemeinstellung verwenden", "Turns off zoom and spinner animations. Fades stay.": "Schaltet Zoom- und Ladeanimationen ab. Überblendungen bleiben erhalten.", + "Drag to move, or use the arrow keys": "Zum Verschieben ziehen oder die Pfeiltasten verwenden", + "A group can't go inside itself": "Eine Gruppe kann nicht in sich selbst liegen", + "Groups can't nest any deeper": "Gruppen lassen sich nicht tiefer verschachteln", "Stack — click to expand (S)": "Stapel — Klicken zum Aufklappen (S)", "Stack — click to collapse (S)": "Stapel — Klicken zum Zuklappen (S)", "Virtual copy": "Virtuelle Kopie", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 88b785c6f0..50b868a3e7 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -26,7 +26,7 @@ "Adjustments: {n}": "Ajustes: {n}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", "Already in the library: {} photo{} selected in All Photos": "Ya en la biblioteca: {0} foto{1} seleccionada{1} en Todas las fotos", "Auto ({})": "Automático ({})", "Auto Import: added {} photo{}": "Importación automática: {0} foto{1} añadida{1}", @@ -76,7 +76,7 @@ "Imported {n} point curve preset{}": "{n} ajuste{0} preestablecido{0} de curva de puntos importado{0}", "Imported {n} preset{}": "{n} ajuste{0} preestablecido{0} importado{0}", "Imported {n} preset{}, {f} file{} not readable": "{n} ajuste{0} preestablecido{0} importado{0}, {f} archivo{1} ilegible{1}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Perfiles importados: {profiles}{:.0} (Explorador de perfiles → sus grupos)", "Imported {} photo{}": "{0} foto{1} importada{1}", "Insert at the cursor (also written {})": "Insertar en el cursor (también se escribe {})", "Label Set: {name}": "Conjunto de etiquetas: {name}", @@ -202,7 +202,7 @@ "… and {more} more": "… y {more} más", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft aún no puede decodificar esta variante RAW ({}). Se está editando la vista previa JPEG incrustada de la cámara, que ya incluye el estilo de imagen de la cámara (p. ej. Monocromo) y el balance de blancos.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "Fotos similares: {n}{:.0} · Vista → Borrar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) de nuevo", "{} label (click more labels to show any of them)": "Etiqueta {} (hacer clic en más etiquetas para mostrar cualquiera de ellas)", ", {} label": ", etiqueta {}", @@ -250,7 +250,7 @@ "Create the keyword “{name}”": "Crear la palabra clave “{name}”", "new, inside {parent}": "nueva, dentro de {parent}", "Keywords of {n} selected photos": "Palabras clave de {n} fotos seleccionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” quitada de {n} fotos. Editar → Deshacer la devuelve.", "1 task is still running: {names}. Quitting stops it.": "1 tarea sigue en curso: {names}. Salir la detiene.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tareas siguen en curso: {names}. Salir las detiene.", "{what} merge cancelled": "Combinación {what} cancelada", @@ -271,7 +271,7 @@ "Delete {n} effect preset{}? This can't be undone.": "¿Eliminar {n} ajuste(s) preestablecido(s) de efecto?{:.0} No se puede deshacer.", "Effect: {name}": "Efecto: {name}", "Exported {} effect preset{}": "Ajustes de efecto exportados: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efecto(s) de máscara importado(s){:.0} (Máscaras → Efecto)", "Update “{name}” with Current Settings": "Actualizar «{name}» con los ajustes actuales", "{n} preset{}": "{n} ajuste(s){:.0}", "{name} opened in the other editor": "{name} abierto en el otro editor", @@ -288,6 +288,7 @@ "Exported to {path}": "Exportado a {path}", "Saved template {name}": "Plantilla {name} guardada", "Imported {name}": "Se importó {name}", + "Moved {name} to {folder}": "{name} se movió a {folder}", "Skipped {problem}": "Omitido: {problem}", "…and {more} more": "…y {more} más", "Template preview: {name}": "Vista previa de la plantilla: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Regla {n} de {m}: {what}. Mover con las teclas de flecha", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: coincidir con {mode}, {count} dentro. Mover con las teclas de flecha", ", rating {} of 5": ", valoración: {} de 5" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index a153fdab88..40a7f31562 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -1094,7 +1094,6 @@ "Photo Grid": "Cuadrícula de fotos", "Photo Grid (G)": "Cuadrícula de fotos (G)", "Photo Merge": "Combinación de fotos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Editar en el editor externo (⇧⌘E) renderiza una copia TIFF de 16 bits, la apila con el original y la abre aquí (un nombre de aplicación en macOS, una ruta de programa en otros sistemas).", "Photos": "Fotos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Fotos editadas en HDR: JPEG con mapa de ganancia HDR (se ve bien en todas partes, con luces más brillantes en pantallas HDR), AVIF a 10 bits, PNG y JPEG XL a 16 bits Rec. 2020 PQ; TIFF necesita coma flotante de 32 bits", "Photos per bracket (0 = auto)": "Fotos por horquillado (0 = automático)", @@ -1258,7 +1257,7 @@ "Remove from survey": "Quitar de Encuesta", "Remove location info": "Quitar información de ubicación", "Remove shortcut": "Quitar método abreviado", - "Remove this face box (undo with Edit ▸ Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", + "Remove this face box (undo with Edit → Undo)": "Quitar este recuadro de cara (deshacer con Editar → Deshacer)", "Remove this filter": "Quitar este filtro", "Remove this group": "Quitar este grupo", "Remove this rule": "Quitar esta regla", @@ -1314,7 +1313,7 @@ "Revert": "Revertir", "Review": "Revisión", "Review Import": "Revisar importación", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic derecho en una foto → Definir como foto de referencia y, después, Vista → Vista de referencia (Mayús+R)", "Right-click a preset to delete it": "Clic derecho en un ajuste preestablecido para eliminarlo", "Rights Usage Terms": "Condiciones de uso de los derechos", "Rotate": "Rotar", @@ -2331,7 +2330,7 @@ "Tidying the thumbnail cache": "Ordenando la caché de miniaturas", "Checking free disk space": "Comprobando el espacio libre en disco", "Reset all edits (Cmd+Shift+R)": "Restablecer todas las ediciones (Cmd+Mayús+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Los álbumes inteligentes se actualizan solos: cambie sus reglas o use Foto → Eliminar foto", "LightCraft stopped": "LightCraft se detuvo", "Focus Point": "Punto de enfoque", "Zoom to Focus Point": "Zoom al punto de enfoque", @@ -2437,6 +2436,10 @@ "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "User Templates": "Plantillas del usuario", + "Delete Folder": "Eliminar carpeta", + "Folder name": "Nombre de la carpeta", + "Its templates move to User Templates.": "Sus plantillas se moverán a Plantillas del usuario.", "Welcome to LightCraft": "Bienvenido a LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Un gestor de fotos y revelado RAW rápido y no destructivo: tus originales permanecen intactos y cada edición se puede revisar o restablecer.", "Bring photos in with File › Import Photos…": "Importa fotos con Archivo › Importar fotos…", @@ -2464,6 +2467,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Desactiva las animaciones del zoom y de los indicadores de actividad. Los fundidos se mantienen. Sigue el ajuste Reducir movimiento del sistema hasta que lo cambies aquí.", "Use the system setting": "Usar el ajuste del sistema", "Turns off zoom and spinner animations. Fades stay.": "Desactiva las animaciones del zoom y de los indicadores de actividad. Los fundidos se mantienen.", + "Drag to move, or use the arrow keys": "Arrastra para mover, o usa las teclas de flecha", + "A group can't go inside itself": "Un grupo no puede ir dentro de sí mismo", + "Groups can't nest any deeper": "Los grupos no se pueden anidar más", "Stack — click to expand (S)": "Pila — clic para expandir (S)", "Stack — click to collapse (S)": "Pila — clic para contraer (S)", "Virtual copy": "Copia virtual", diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 2ba3870615..f0798061a7 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -39,7 +39,7 @@ "Add Keyword “{keywords}”": "Lisää avainsana ”{keywords}”", "Adding photos… {} of {}": "Lisätään kuvia… {} / {}", "All {n} selected photos move by the same amount.": "Kaikkia valittuja kuvia ({n}) siirretään saman verran.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Jo kirjastossa, Äskettäin poistetuissa: valittuja kuvia {}{:.0} · napsauta hiiren kakkospainikkeella → Palauta tai Poista pysyvästi tuodaksesi uudelleen", "Already in the library: {} photo{} selected in All Photos": "Jo kirjastossa (Kaikki kuvat): valittuja kuvia {}{:.0}", "Already in “{}”": "Jo kohteessa ”{}”", "Applied {name}": "{name} käytetty", @@ -96,12 +96,13 @@ "Import failed: {e}": "Tuonti epäonnistui: {e}", "Import photos with File → Import Photos… ({}), or drop them here": "Tuo kuvia valitsemalla Tiedosto → Tuo kuvia… ({}) tai pudota ne tähän", "Import warnings ({n}):\n{warnings}": "Tuontivaroitukset ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", + "Imported {e} mask effect{} (Masking → Effect)": "Tuotuja maskitehosteita: {e}{:.0} (Maskaus → Tehoste)", "Imported {name}": "{name} tuotu", + "Moved {name} to {folder}": "{name} siirretty kansioon {folder}", "Imported {n} point curve preset{}": "Tuotuja pistekäyrän esiasetuksia: {n}{:.0}", "Imported {n} preset{}": "Tuotuja esiasetuksia: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Tuotuja esiasetuksia: {n}{:.0}, ei luettavissa olevia tiedostoja: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Tuotuja profiileja: {profiles}{:.0} (Profiiliselain → niiden ryhmät)", "Imported {} photo{}": "Tuotuja kuvia: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Jonossa tekoälykohinanpoistoon ({ahead} edellä)…", "Insert at the cursor (also written {})": "Lisää kohdistimen kohtaan (kirjoitetaan myös {})", @@ -162,7 +163,7 @@ "Remove “{}” from Favorites": "Poista ”{}” suosikeista", "Removed from {}": "Poistettu kohteesta {}", "Removed {what} from {name}": "{what} poistettu kohteesta {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "”{name}” poistettu {n} kuvalta. Muokkaa → Kumoa palauttaa sen.", "Rename {n} Photos…": "Nimeä uudelleen {n} kuvaa…", "Rename “{name}”": "Nimeä uudelleen ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Nimeää uudelleen kasvoja koko kirjastossa: {n}{:.0}. Tiedostoja ei muuteta.", @@ -255,7 +256,7 @@ "{n} preset{}": "Esiasetuksia: {n}{:.0}", "{n} raws can now be developed from their raw data": "Raw-kuvia, jotka voidaan nyt kehittää raakadatastaan: {n}", "{n} selected photo{} · {pages} page{}": "Valittuja kuvia: {n} · sivuja: {pages}{:.0}{:.0}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", + "{n} similar photo{} · View → Clear Filters to see all": "Samankaltaisia kuvia: {n}{:.0} · Näytä → Tyhjennä suodattimet näyttääksesi kaikki", "{n} tasks are still running: {names}. Quitting stops them.": "Käynnissä olevia tehtäviä: {n}: {names}. Lopettaminen pysäyttää ne.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", @@ -323,5 +324,7 @@ "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä", ", rating {} of 5": ", luokitus: {} / 5" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index f9b51c9f41..b6e61397ac 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -1421,7 +1421,7 @@ "Photo Grid": "Kuvaruudukko", "Photo Grid (G)": "Kuvaruudukko (G)", "Photo Merge": "Kuvien yhdistäminen", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Kuva → Muokkaa ohjelmassa → Muokkaa PhotoCraftissa (⇧⌘E tai napsauta kuvaa hiiren kakkospainikkeella) renderöi kopion muokkauksineen, pinoaa sen alkuperäisen kanssa ja avaa sen PhotoCraftissa. Tallenna siellä, niin kopio päivittyy täällä. PSD-muodossa PhotoCraft tallentaa suoraan siihen. Jätä sijainti tyhjäksi, ellet käytä kannettavaa kopiota.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Kuva → Muokkaa ulkoisessa muokkausohjelmassa (⇧⌘E) renderöi 16-bittisen TIFF-kopion, pinoaa sen alkuperäisen kanssa ja avaa sen täällä (macOS:ssä sovelluksen nimi, muualla ohjelman polku).", "PhotoCraft": "PhotoCraft", "Photos": "Kuvat", @@ -1626,7 +1626,7 @@ "Remove missing photos from the library": "Poista puuttuvat kuvat kirjastosta", "Remove region": "Poista alue", "Remove shortcut": "Poista pikakuvake", - "Remove this face box (undo with Edit ▸ Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", + "Remove this face box (undo with Edit → Undo)": "Poista tämä kasvorajaus (kumoa kohdasta Muokkaa → Kumoa)", "Remove this filter": "Poista tämä suodatin", "Remove this group": "Poista tämä ryhmä", "Remove this rule": "Poista tämä sääntö", @@ -1690,7 +1690,7 @@ "Review": "Tarkistus", "Review Import": "Tarkista tuonti", "Right": "Oikea", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Napsauta kuvaa hiiren kakkospainikkeella → Aseta vertailukuvaksi, sitten Näytä → Vertailunäkymä (Shift+R)", "Right-click a preset to delete it": "Poista esiasetus napsauttamalla sitä hiiren kakkospainikkeella", "Rights Usage Terms": "Oikeuksien käyttöehdot", "Rotate": "Kierrä", @@ -1900,7 +1900,7 @@ "Smart Album Rule Fields": "Älyalbumin sääntökentät", "Smart Preview Status": "Älyesikatselun tila", "Smart Previews Location": "Älyesikatseluiden sijainti", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Älyalbumit päivittyvät automaattisesti: muuta niiden sääntöjä tai käytä Kuva → Poista kuva", "Smart preview available": "Älyesikatselu saatavilla", "Smart previews": "Älyesikatselut", "Smart previews folder changed": "Älyesikatseluiden kansio muuttui", @@ -2413,12 +2413,19 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", + "User Templates": "Käyttäjän mallipohjat", + "Delete Folder": "Poista kansio", + "Folder name": "Kansion nimi", + "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat.", "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", "Reduce Motion": "Vähennä liikettä", "Reduce motion": "Vähennä liikettä", "Turns off zoom and spinner animations. Fades stay.": "Poistaa zoomaus- ja pyörivät animaatiot käytöstä. Häivytykset säilyvät.", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Poistaa zoomaus- ja pyörivät animaatiot käytöstä. Häivytykset säilyvät. Seuraa järjestelmän Vähennä liikettä -asetusta, kunnes muutat sitä täällä.", "Use the system setting": "Käytä järjestelmän asetusta", + "Drag to move, or use the arrow keys": "Siirrä vetämällä tai käytä nuolinäppäimiä", + "A group can't go inside itself": "Ryhmää ei voi siirtää itsensä sisään", + "Groups can't nest any deeper": "Ryhmiä ei voi sisentää syvemmälle", "Right-click ▸ Locate Missing File… to find it again.": "Napsauta hiiren kakkospainikkeella → Paikanna puuttuva tiedosto… löytääksesi sen uudelleen.", "Right-click ▸ Reload from Disk to try again.": "Napsauta hiiren kakkospainikkeella → Lataa levyltä uudelleen yrittääksesi uudelleen.", "Stack — click to collapse (S)": "Pino — napsauta tiivistääksesi (S)", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index f0493e2571..4833055b7d 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -26,7 +26,7 @@ "Adjustments: {n}": "Réglages : {n}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", "Already in the library: {} photo{} selected in All Photos": "Déjà dans la bibliothèque : {} photo{} sélectionnée(s) dans Toutes les photos", "Auto ({})": "Automatique ({})", "Auto Import: added {} photo{}": "Importation automatique : {} photo{} ajoutée(s)", @@ -69,7 +69,7 @@ "Imported {n} point curve preset{}": "{n} préréglage{} de courbe à points importé(s)", "Imported {n} preset{}": "{n} préréglage{} importé(s)", "Imported {n} preset{}, {f} file{} not readable": "{n} préréglage{} importé(s), {f} fichier{} illisible(s)", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Les fichiers annexes XMP de {n} photos n'ont pas pu être écrits (leur dossier est-il hors ligne ?). LightCraft continue d'essayer.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Le profil XMP « {profile} » n’a pas été appliqué à {path} ; les couleurs peuvent différer de Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La géométrie Lightroom de {path} n’a pas été conservée ; {mode} sera recalculé.", @@ -202,7 +202,7 @@ "… and {more} more": "… et {more} de plus", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ne peut pas encore décoder cette variante RAW ({}). Vous modifiez l’aperçu JPEG intégré de l’appareil photo, qui inclut déjà le style d’image (par ex. monochrome) et la balance des blancs de l’appareil.", "Filtered: {label}": "Filtré : {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", + "{n} similar photo{} · View → Clear Filters to see all": "{n} photo{} similaire(s) · Affichage → Effacer les filtres pour tout voir", "Moved; {} photo(s) relinked": "Déplacé ; {} photo(s) de nouveau associée(s)", "{} label (click more labels to show any of them)": "Étiquette {} (cliquez sur « autres étiquettes » pour afficher celles de votre choix)", ", {} label": ", étiquette {}", @@ -250,7 +250,7 @@ "Create the keyword “{name}”": "Créer le mot-clé « {name} »", "new, inside {parent}": "nouveau, dans {parent}", "Keywords of {n} selected photos": "Mots-clés de {n} photos sélectionnées", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "« {name} » retiré de {n} photos. Modifier → Annuler le rétablit.", "1 task is still running: {names}. Quitting stops it.": "1 tâche est encore en cours : {names}. Quitter l'arrête.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tâches sont encore en cours : {names}. Quitter les arrête.", "{what} merge cancelled": "Fusion {what} annulée", @@ -271,7 +271,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Supprimer {n} paramètre(s) prédéfini(s) d’effet ?{:.0} Cette action est irréversible.", "Effect: {name}": "Effet : {name}", "Exported {} effect preset{}": "Paramètres d’effet exportés : {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} effet(s) de masque importé(s){:.0} (Masquage → Effet)", "Update “{name}” with Current Settings": "Mettre à jour « {name} » avec les réglages actuels", "{n} preset{}": "{n} paramètre(s){:.0}", "{name} opened in the other editor": "{name} ouvert dans l’autre éditeur", @@ -288,6 +288,7 @@ "Exported to {path}": "Exporté vers {path}", "Saved template {name}": "Modèle {name} enregistré", "Imported {name}": "{name} importé", + "Moved {name} to {folder}": "{name} déplacé vers {folder}", "Skipped {problem}": "Ignoré : {problem}", "…and {more} more": "…et {more} de plus", "Template preview: {name}": "Aperçu du modèle : {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Règle {n} sur {m} : {what}. Déplacer avec les flèches", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Groupe {n} sur {m} : correspondre à {mode}, {count} à l’intérieur. Déplacer avec les flèches", ", rating {} of 5": ", note : {} sur 5" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index aa62fc8173..77a33e3164 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -1036,7 +1036,6 @@ "Photo Grid": "Grille de photos", "Photo Grid (G)": "Grille de photos (G)", "Photo Merge": "Fusion de photos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Photo → Modifier dans l'éditeur externe (⇧⌘E) génère une copie TIFF 16 bits, l'empile avec l'original et l'ouvre ici (un nom d'application sur macOS, un chemin de programme ailleurs).", "Photos": "Photos", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Photos retouchées en HDR : JPEG avec carte de gain HDR (correct partout, hautes lumières plus vives sur les écrans HDR), AVIF en 10 bits, PNG et JPEG XL en 16 bits Rec. 2020 PQ ; le TIFF exige du 32 bits flottant", "Photos per bracket (0 = auto)": "Photos par bracketing (0 = auto)", @@ -1192,7 +1191,7 @@ "Remove from survey": "Retirer de la vue multiple", "Remove location info": "Supprimer les informations de lieu", "Remove shortcut": "Supprimer le raccourci", - "Remove this face box (undo with Edit ▸ Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", + "Remove this face box (undo with Edit → Undo)": "Retirer ce cadre de visage (annuler avec Édition → Annuler)", "Remove this filter": "Retirer ce filtre", "Remove this group": "Retirer ce groupe", "Remove this rule": "Retirer cette règle", @@ -1242,7 +1241,7 @@ "Revert": "Rétablir l'original", "Review": "Révision", "Review Import": "Vérifier l'importation", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic droit sur une photo → Définir comme photo de référence, puis Affichage → Vue de référence (Maj+R)", "Right-click a preset to delete it": "Clic droit sur un préréglage pour le supprimer", "Rights Usage Terms": "Conditions d'utilisation des droits", "Rotate": "Pivoter", @@ -2326,7 +2325,7 @@ "Tidying the thumbnail cache": "Rangement du cache des miniatures", "Checking free disk space": "Vérification de l'espace disque libre", "Reset all edits (Cmd+Shift+R)": "Réinitialiser toutes les retouches (Cmd+Maj+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Les albums intelligents se mettent à jour d'eux-mêmes : modifiez leurs règles ou utilisez Photo → Supprimer la photo", "LightCraft stopped": "LightCraft s’est arrêté", "Focus Point": "Point de mise au point", "Zoom to Focus Point": "Zoomer sur le point de mise au point", @@ -3620,6 +3619,10 @@ "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "User Templates": "Modèles utilisateur", + "Delete Folder": "Supprimer le dossier", + "Folder name": "Nom du dossier", + "Its templates move to User Templates.": "Ses modèles sont déplacés vers Modèles utilisateur.", "Welcome to LightCraft": "Bienvenue dans LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Une bibliothèque photo rapide et non destructive, et un outil de développement RAW : vos originaux restent intacts, et chaque modification peut être revue ou annulée.", "Bring photos in with File › Import Photos…": "Importez des photos avec Fichier › Importer des photos…", @@ -3647,6 +3650,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Désactive les animations du zoom et des indicateurs d’activité. Les fondus restent. Suit le réglage Réduire les animations du système tant que vous ne le changez pas ici.", "Use the system setting": "Utiliser le réglage du système", "Turns off zoom and spinner animations. Fades stay.": "Désactive les animations du zoom et des indicateurs d’activité. Les fondus restent.", + "Drag to move, or use the arrow keys": "Faites glisser pour déplacer, ou utilisez les flèches", + "A group can't go inside itself": "Un groupe ne peut pas se placer dans lui-même", + "Groups can't nest any deeper": "Les groupes ne peuvent pas être imbriqués plus profondément", "Stack — click to expand (S)": "Pile — cliquer pour déplier (S)", "Stack — click to collapse (S)": "Pile — cliquer pour replier (S)", "Virtual copy": "Copie virtuelle", diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 4eb5e48e3d..129971f036 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -123,7 +123,7 @@ "Adding photos… {} of {}": "Menambahkan foto… {} dari {}", " ({} in Recently Deleted)": " ({} di Baru dihapus)", "Already in the library: {} photo{} selected in All Photos": "Sudah ada di pustaka: {} foto{:.0} dipilih di Semua foto", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Sudah ada di pustaka, di Baru dihapus: {} foto{:.0} dipilih · klik kanan → Pulihkan, atau Hapus permanen untuk mengimpor ulang", "Auto ({})": "Otomatis ({})", "Build 1:1 Previews ({scope})": "Buat pratinjau 1:1 ({scope})", "Build Smart Previews ({scope})": "Buat pratinjau pintar ({scope})", @@ -173,7 +173,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan terpandu yang tersimpan tidak didukung.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "Geometri Lightroom untuk {path} tidak dipertahankan; transformasi Tegakkan yang tersimpan tidak didukung.", "XMP adjustments were not imported for {path}: {fields}.": "Penyesuaian XMP untuk {path} tidak diimpor: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} profil diimpor{:.0} (Penjelajah profil → grup masing-masing)", "Insert at the cursor (also written {})": "Sisipkan di posisi kursor (dapat juga ditulis {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Font: {} (OFL). Ikon: orisinal.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Menerapkan “{k}”: klik foto untuk menambahkan atau menghapusnya · Esc untuk berhenti", @@ -203,7 +203,7 @@ "{} — show their photos": "{} — tampilkan foto orang ini", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft belum dapat mendekode varian raw ini ({}). Anda sedang mengedit pratinjau JPEG bawaan kamera, yang sudah menyertakan gaya gambar kamera (mis. Monokrom) dan keseimbangan putihnya.", "Filtered: {label}": "Difilter: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto serupa{:.0} · Tampilan → Hapus filter untuk melihat semua", "Moved; {} photo(s) relinked": "Dipindahkan; {} foto ditautkan ulang", "{} label (click more labels to show any of them)": "Label {} (klik label lain untuk ikut menampilkan foto berlabel tersebut)", ", {} label": ", label {}", @@ -250,7 +250,7 @@ "Create the keyword “{name}”": "Buat kata kunci “{name}”", "new, inside {parent}": "baru, di dalam {parent}", "Keywords of {n} selected photos": "Kata kunci {n} foto yang dipilih", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” dihapus dari {n} foto. Edit → Urungkan akan mengembalikannya.", "1 task is still running: {names}. Quitting stops it.": "1 tugas masih berjalan: {names}. Jika keluar sekarang, tugas ini akan dihentikan.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tugas masih berjalan: {names}. Jika keluar sekarang, semua tugas ini akan dihentikan.", "{what} merge cancelled": "Penggabungan {what} dibatalkan", @@ -271,7 +271,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Hapus {n} preset efek{:.0}? Tindakan ini tidak dapat diurungkan.", "Effect: {name}": "Efek: {name}", "Exported {} effect preset{}": "{} preset efek diekspor{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efek masker{:.0} diimpor (Masker → Efek)", "Update “{name}” with Current Settings": "Perbarui “{name}” dengan pengaturan saat ini", "{n} preset{}": "{n} preset{:.0}", "{name} opened in the other editor": "{name} dibuka di editor lain", @@ -286,6 +286,7 @@ "Exported to {path}": "Diekspor ke {path}", "Saved template {name}": "Templat {name} disimpan", "Imported {name}": "{name} diimpor", + "Moved {name} to {folder}": "{name} dipindahkan ke {folder}", "Skipped {problem}": "Dilewati: {problem}", "…and {more} more": "…dan {more} lainnya", "Template preview: {name}": "Pratinjau templat: {name}", @@ -326,5 +327,7 @@ "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah", ", rating {} of 5": ", rating: {} dari 5" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index cb301dca22..c4816c93a7 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -1405,7 +1405,7 @@ "Photo Grid": "Grid foto", "Photo Grid (G)": "Grid foto (G)", "Photo Merge": "Gabung foto", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Edit di → Edit di PhotoCraft (⇧⌘E, atau klik kanan foto) merender salinan beserta hasil edit Anda, menumpuknya dengan foto asli, lalu membukanya di PhotoCraft. Simpan di sana, dan salinan di sini ikut diperbarui. Jika berformat PSD, PhotoCraft menyimpan langsung ke file tersebut. Kosongkan lokasi kecuali Anda menggunakan salinan portabel.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Edit di editor eksternal (⇧⌘E) membuat salinan TIFF 16-bit, menumpuknya dengan file asli, lalu membukanya dengan program yang diisi di sini (nama aplikasi di macOS, jalur program di sistem lain).", "PhotoCraft": "PhotoCraft", "Photos": "Foto", @@ -1615,7 +1615,7 @@ "Remove location info": "Hapus info lokasi", "Remove missing photos from the library": "Keluarkan foto yang hilang dari pustaka", "Remove shortcut": "Hapus pintasan", - "Remove this face box (undo with Edit ▸ Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", + "Remove this face box (undo with Edit → Undo)": "Hapus kotak wajah ini (urungkan lewat Edit → Urungkan)", "Remove this filter": "Hapus filter ini", "Remove this group": "Hapus grup ini", "Remove this rule": "Hapus aturan ini", @@ -1682,7 +1682,7 @@ "Review": "Tinjauan", "Review Import": "Tinjau impor", "Right": "Kanan", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Klik kanan foto → Jadikan foto referensi, lalu Tampilan → Tampilan referensi (Shift+R)", "Right-click a preset to delete it": "Klik kanan preset untuk menghapusnya", "Rights Usage Terms": "Ketentuan penggunaan", "Rotate": "Putar", @@ -1900,7 +1900,7 @@ "Smart Album Rule Fields": "Kolom aturan album pintar", "Smart Preview Status": "Status pratinjau pintar", "Smart Previews Location": "Lokasi pratinjau pintar", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Album pintar diperbarui secara otomatis: ubah aturannya, atau gunakan Foto → Hapus foto", "Smart preview available": "Pratinjau pintar tersedia", "Smart previews": "Pratinjau pintar", "Smart previews folder changed": "Folder pratinjau pintar diubah", @@ -2427,12 +2427,19 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", + "User Templates": "Templat pengguna", + "Delete Folder": "Hapus folder", + "Folder name": "Nama folder", + "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna.", "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", "Reduce Motion": "Kurangi gerakan", "Reduce motion": "Kurangi gerakan", "Turns off zoom and spinner animations. Fades stay.": "Menonaktifkan animasi zoom dan indikator putar. Efek memudar tetap ada.", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Menonaktifkan animasi zoom dan indikator putar. Efek memudar tetap ada. Mengikuti pengaturan Kurangi Gerakan sistem sampai Anda mengubahnya di sini.", "Use the system setting": "Gunakan pengaturan sistem", + "Drag to move, or use the arrow keys": "Seret untuk memindahkan, atau gunakan tombol panah", + "A group can't go inside itself": "Grup tidak dapat dimasukkan ke dalam dirinya sendiri", + "Groups can't nest any deeper": "Grup tidak dapat disarangkan lebih dalam", "Right-click ▸ Locate Missing File… to find it again.": "Klik kanan → Temukan file hilang… untuk menemukannya lagi.", "Right-click ▸ Reload from Disk to try again.": "Klik kanan → Muat ulang dari disk untuk mencoba lagi.", "Stack — click to collapse (S)": "Tumpukan — klik untuk menciutkan (S)", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 5216c6ce31..ca1418892c 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Aggiunto a {name}: {what}", "Adding photos… {} of {}": "Aggiunta delle foto… {} di {}", "All {n} selected photos move by the same amount.": "Tutte le {n} foto selezionate si spostano della stessa quantità.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Già nella libreria, in Eliminate di recente: foto selezionate {}{:.0} · clic destro → Ripristina, oppure Elimina definitivamente per importarle da capo", "Already in the library: {} photo{} selected in All Photos": "Già nella libreria (selezionate in Tutte le foto): {}{:.0}", "Auto ({})": "Automatico ({})", "Auto Import: added {} photo{}": "Importazione automatica · foto aggiunte: {}{:.0}", @@ -73,7 +73,7 @@ "Imported {n} point curve preset{}": "Preset di curva a punti importati: {n}{:.0}", "Imported {n} preset{}": "Preset importati: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Preset importati: {n}{:.0}, file illeggibili: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Profili importati: {profiles}{:.0} (Browser dei profili → i loro gruppi)", "Imported {} photo{}": "Foto importate: {}{:.0}", "Insert at the cursor (also written {})": "Inserisci al cursore (si scrive anche {})", "Label Set: {name}": "Set di etichette: {name}", @@ -196,7 +196,7 @@ "… and {more} more": "… e altre {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft non sa ancora decodificare questa variante raw ({}). Stai modificando l'anteprima JPEG incorporata dalla fotocamera, che contiene già lo stile immagine della fotocamera (ad es. Monocromatico) e il bilanciamento del bianco.", "Filtered: {label}": "Filtrate: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", + "{n} similar photo{} · View → Clear Filters to see all": "Foto simili: {n}{:.0} · Visualizza → Cancella filtri per vederle tutte", "Moved; {} photo(s) relinked": "Spostata; foto ricollegate: {}", "{} label (click more labels to show any of them)": "Etichetta {} (fai clic su altre etichette per mostrarne una qualsiasi)", ", {} label": ", etichetta {}", @@ -271,7 +271,7 @@ "Keywords of {n} selected photos": "Parole chiave delle foto selezionate: {n}", "new, inside {parent}": "nuova, dentro {parent}", "Delete these {n} effect presets?": "Eliminare questi preset effetto ({n})?", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "{photos} catalog records processed; {collections} collections.": "Record del catalogo elaborati: {photos}; raccolte: {collections}.", "Skipped {problem}": "Saltato: {problem}", "Updated {name}": "{name} aggiornato", @@ -285,11 +285,12 @@ "{n} JPEG files": "File JPEG: {n}", "Exported {} effect preset{}": "Preset effetto esportati: {}{:.0}", "Imported {name}": "{name} importato", + "Moved {name} to {folder}": "{name} spostato in {folder}", "{n} pages": "Pagine: {n}", " · kept, not applied: {}": " · conservato, non applicato: {}", "Delete the effect preset “{name}”?": "Eliminare il preset effetto “{name}”?", "{n} raws can now be developed from their raw data": "Raw che ora si possono sviluppare dai loro dati raw: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Inside: {names}": "Al suo interno: {names}", "Template preview: {name}": "Anteprima del modello: {name}", "{n} photo{} in view · {slides} slide{} · {time}": "Foto nella vista: {n} · diapositive: {slides} · {time}{:.0}{:.0}", @@ -326,5 +327,7 @@ "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce", ", rating {} of 5": ", valutazione: {} su 5" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index dd3969baf2..2388641baf 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -1045,7 +1045,6 @@ "Photo Grid": "Griglia foto", "Photo Grid (G)": "Griglia foto (G)", "Photo Merge": "Unione di foto", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Modifica nell'editor esterno (⇧⌘E) genera una copia TIFF a 16 bit, la mette in pila con l'originale e la apre qui (il nome di un'app su macOS, il percorso di un programma altrove).", "Photos": "Foto", "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Foto modificate in HDR: JPEG con gain map HDR (si vede bene ovunque, luci più brillanti sugli schermi HDR), AVIF a 10 bit, PNG e JPEG XL a 16 bit Rec. 2020 PQ; il TIFF richiede virgola mobile a 32 bit", "Photos per bracket (0 = auto)": "Foto per bracketing (0 = automatico)", @@ -1203,7 +1202,7 @@ "Remove from survey": "Rimuovi dalla panoramica", "Remove location info": "Rimuovi le informazioni sulla posizione", "Remove shortcut": "Rimuovi scorciatoia", - "Remove this face box (undo with Edit ▸ Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", + "Remove this face box (undo with Edit → Undo)": "Rimuovi questo riquadro del volto (annulla con Modifica → Annulla)", "Remove this filter": "Rimuovi questo filtro", "Remove this group": "Rimuovi questo gruppo", "Remove this rule": "Rimuovi questa regola", @@ -1240,7 +1239,7 @@ "Reset all curves: point curves (all channels) and parametric (double-click a channel to reset only that one)": "Reimposta tutte le curve: curve a punti (tutti i canali) e parametrica (doppio clic su un canale per reimpostare solo quello)", "Reset all edits": "Ripristina tutte le modifiche", "Reset all edits (Cmd+Shift+R)": "Reimposta tutte le modifiche (Cmd+Maiusc+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Gli album smart si aggiornano da soli: cambia le loro regole, oppure usa Foto → Elimina foto", "LightCraft stopped": "LightCraft si è chiuso", "Zoom to Focus Point": "Zoom sul punto di messa a fuoco", "Focus": "Messa a fuoco", @@ -1278,7 +1277,7 @@ "Revert": "Ripristina", "Review": "Revisione", "Review Import": "Rivedi importazione", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clic destro su una foto → Imposta come foto di riferimento, poi Visualizza → Vista di riferimento (Maiusc+R)", "Right-click a preset to delete it": "Clic destro su un preset per eliminarlo", "Rights Usage Terms": "Condizioni d'uso dei diritti", "Rotate": "Ruota", @@ -1841,7 +1840,7 @@ "Monitor profile": "Profilo monitor", "None (the display is treated as sRGB)": "Nessuno (lo schermo viene trattato come sRGB)", "Other editor": "Altro editor", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", "PhotoCraft": "PhotoCraft", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Le foto vengono mostrate attraverso il profilo ICC del monitor, così i colori sono corretti su schermi calibrati e a gamut esteso, e la vista Dettaglio usa tutto il gamut dello schermo. Istogramma, cache delle anteprime ed esportazioni non cambiano.", "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Le foto restano in Tutte le foto. Eliminando una cartella si eliminano anche i suoi album. Puoi annullare l'operazione.", @@ -2600,6 +2599,10 @@ "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", "Bottom bar": "Barra inferiore", + "User Templates": "Modelli utente", + "Delete Folder": "Elimina cartella", + "Folder name": "Nome della cartella", + "Its templates move to User Templates.": "I suoi modelli vengono spostati in Modelli utente.", "Welcome to LightCraft": "Benvenuto in LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Una libreria fotografica veloce e non distruttiva, e uno sviluppatore RAW: gli originali restano intatti e ogni modifica si può rivedere o annullare.", "Bring photos in with File › Import Photos…": "Importa le foto con File › Importa foto…", @@ -2628,6 +2631,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Disattiva le animazioni dello zoom e degli indicatori di attività. Le dissolvenze restano. Segue l’impostazione Riduci movimento del sistema finché non la cambi qui.", "Use the system setting": "Usa l’impostazione del sistema", "Turns off zoom and spinner animations. Fades stay.": "Disattiva le animazioni dello zoom e degli indicatori di attività. Le dissolvenze restano.", + "Drag to move, or use the arrow keys": "Trascina per spostare, oppure usa le frecce", + "A group can't go inside itself": "Un gruppo non può stare dentro se stesso", + "Groups can't nest any deeper": "I gruppi non si possono annidare più in profondità", "Stack — click to expand (S)": "Pila — clic per espandere (S)", "Stack — click to collapse (S)": "Pila — clic per comprimere (S)", "Virtual copy": "Copia virtuale", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index fd5e086656..8cf5d56c85 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -125,7 +125,7 @@ "Adding photos… {} of {}": "写真を追加中:{1}枚中{0}枚", " ({} in Recently Deleted)": "(うち{}枚は最近削除した写真)", "Already in the library: {} photo{} selected in All Photos": "ライブラリに登録済み:すべての写真で{}枚を選択しました{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "ライブラリの「最近削除した写真」にあります:{}枚を選択しました{:.0}・右クリック → 復元、または完全に削除してから読み込み直し", "Auto ({})": "自動 ({})", "Build 1:1 Previews ({scope})": "1:1プレビューを作成({scope})", "Build Smart Previews ({scope})": "スマートプレビューを作成({scope})", @@ -176,7 +176,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。ガイド付き Upright の保存された変換はサポートされていません。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "{path} の Lightroom ジオメトリは保持されませんでした。保存された Upright の変換はサポートされていません。", "XMP adjustments were not imported for {path}: {fields}.": "{path} の XMP 調整は読み込まれませんでした:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles}個のプロファイルを読み込みました{:.0}(プロファイルブラウザー → 各グループ)", "Insert at the cursor (also written {})": "カーソル位置に挿入({}とも表記可)", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。フォント:{}(OFL)。アイコン:オリジナル", "Painting “{k}”: click photos to add or remove it · Esc stops": "「{k}」を適用中:写真をクリックして付け外し・Escで終了", @@ -206,7 +206,7 @@ "{} — show their photos": "{} — この人物の写真を表示", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraftはこのRAWの形式({})をまだデコードできません。カメラの埋め込みJPEGプレビューを編集しています。このプレビューには、カメラのピクチャースタイル(モノクロなど)とホワイトバランスがすでに反映されています", "Filtered: {label}": "フィルター適用中:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", + "{n} similar photo{} · View → Clear Filters to see all": "似た写真{n}枚{:.0}・すべて表示するには「表示 → フィルターを解除」", "Moved; {} photo(s) relinked": "移動しました。{}枚の写真の参照先を更新しました", "{} label (click more labels to show any of them)": "{}ラベル(ほかのラベルもクリックすると、いずれかに一致する写真を表示)", ", {} label": "、{}ラベル", @@ -254,7 +254,7 @@ "Create the keyword “{name}”": "キーワード「{name}」を作成", "new, inside {parent}": "新規、{parent} の中", "Keywords of {n} selected photos": "選択した写真{n}枚のキーワード", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "「{name}」を写真{n}枚から削除しました。「編集」→「取り消す」で元に戻せます。", "1 task is still running: {names}. Quitting stops it.": "1件のタスクが実行中です:{names}。終了すると停止します。", "{n} tasks are still running: {names}. Quitting stops them.": "{n}件のタスクが実行中です:{names}。終了すると停止します。", "{what} merge cancelled": "{what}合成をキャンセルしました", @@ -275,7 +275,7 @@ "Delete {n} effect preset{}? This can't be undone.": "効果プリセット{n}件を削除しますか?{:.0}元に戻せません。", "Effect: {name}": "効果:{name}", "Exported {} effect preset{}": "効果プリセットを{}件書き出しました{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", + "Imported {e} mask effect{} (Masking → Effect)": "マスク効果を{e}件読み込みました{:.0}(マスク → 効果)", "Update “{name}” with Current Settings": "「{name}」を現在の設定で更新", "{n} preset{}": "{n}件のプリセット{:.0}", "{name} opened in the other editor": "{name}を別のエディタで開きました", @@ -292,6 +292,7 @@ "Exported to {path}": "{path} に書き出しました", "Saved template {name}": "テンプレート {name} を保存しました", "Imported {name}": "{name} を読み込みました", + "Moved {name} to {folder}": "{name} を {folder} に移動しました", "Skipped {problem}": "スキップ: {problem}", "…and {more} more": "…ほか {more} 件", "Template preview: {name}": "テンプレートのプレビュー: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", + "Rule {n} of {m}: {what}. Move with the arrow keys": "条件 {n}/{m}:{what}。矢印キーで移動", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "グループ {n}/{m}:一致条件 {mode}、中に {count} 件。矢印キーで移動", ", rating {} of 5": "、評価: 5段階中{}" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 314ac96a95..d68575ac8c 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -731,7 +731,7 @@ "Remove a filter above, or choose Clear all": "上のフィルターを解除するか、「すべて解除」を選択してください", "Remove from Target Album": "追加先アルバムから除去", "Remove shortcut": "ショートカットを削除", - "Remove this face box (undo with Edit ▸ Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", + "Remove this face box (undo with Edit → Undo)": "この顔の枠を除去(「編集 → 取り消す」で元に戻せます)", "Rename Component": "構成要素の名前を変更", "Rename Folder": "フォルダ名を変更", "Rename Mask": "マスク名を変更", @@ -1060,7 +1060,6 @@ "Photo Grid": "写真グリッド", "Photo Grid (G)": "写真グリッド(G)", "Photo Merge": "写真を合成", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "「写真 → 外部エディターで編集」(⇧⌘E)で16ビットTIFFコピーを作成し、元画像とスタックにまとめて開きます。Macではアプリ名を指定してください", "Photos": "写真", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "ローカルで参照しただけの写真は、この期間フォルダを開いていなければカタログから外します。ファイルはディスクに残り、再びフォルダを開くと表示されます", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "このフォルダに転送された写真は、転送が完了すると自動で追加されます", @@ -1191,7 +1190,7 @@ "Reverse the order": "逆順にする", "Review": "レビュー", "Review Import": "読み込み内容を確認", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "写真を右クリックして参照写真に設定し、「表示 → 参照表示」(⇧R)を選択してください", "Right-click a preset to delete it": "プリセットを右クリックして削除", "Rights Usage Terms": "利用条件", "Rotate": "回転", @@ -2329,7 +2328,7 @@ "Tidying the thumbnail cache": "サムネールキャッシュを整理中", "Checking free disk space": "ディスクの空き容量を確認中", "Reset all edits (Cmd+Shift+R)": "すべての編集をリセット(⌘⇧R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "スマートアルバムは自動で更新されます。ルールを変更するか、写真 → 写真を削除を使ってください", "LightCraft stopped": "LightCraftが終了しました", "Focus Point": "フォーカスポイント", "Zoom to Focus Point": "フォーカスポイントにズーム", @@ -2435,6 +2434,10 @@ "Tool strip": "ツールバー", "Bottom bar": "下部バー", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "User Templates": "ユーザーテンプレート", + "Delete Folder": "フォルダを削除", + "Folder name": "フォルダ名", + "Its templates move to User Templates.": "中のテンプレートは「ユーザーテンプレート」に移動します。", "Welcome to LightCraft": "LightCraft へようこそ", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "高速で非破壊の写真ライブラリと RAW 現像ソフトです。元の写真は変わらず、どの編集もあとから見直したり元に戻したりできます。", "Bring photos in with File › Import Photos…": "ファイル › 写真を読み込む…で写真を読み込みます。", @@ -2462,6 +2465,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "ズームとスピナーのアニメーションをオフにします。フェードはそのまま残ります。ここで変更するまで、システムの「視差効果を減らす」設定に従います。", "Use the system setting": "システム設定に従う", "Turns off zoom and spinner animations. Fades stay.": "ズームとスピナーのアニメーションをオフにします。フェードはそのまま残ります。", + "Drag to move, or use the arrow keys": "ドラッグして移動、または矢印キーを使います", + "A group can't go inside itself": "グループを自分自身の中に入れることはできません", + "Groups can't nest any deeper": "グループはこれ以上深く入れ子にできません", "Stack — click to expand (S)": "スタック — クリックして展開 (S)", "Stack — click to collapse (S)": "スタック — クリックして折りたたむ (S)", "Virtual copy": "仮想コピー", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 6507fc207e..373fafdefa 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -35,7 +35,7 @@ "Add Keyword “{keywords}”": "საკვანძო სიტყვის „{keywords}“ დამატება", "Adding photos… {} of {}": "ფოტოების დამატება… {} / {}", "All {n} selected photos move by the same amount.": "მონიშნული ფოტოები ({n}) ერთი და იმავე სიდიდით გადაინაცვლებს.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "უკვე ბიბლიოთეკაშია, ახლახან წაშლილებში: მონიშნულია ფოტო: {}{:.0} · მარჯვენა დაწკაპუნება → აღდგენა, ან სამუდამოდ წაშლა თავიდან იმპორტისთვის", "Already in the library: {} photo{} selected in All Photos": "უკვე ბიბლიოთეკაშია: „ყველა ფოტოში“ მონიშნულია ფოტო: {}{:.0}", "Auto ({})": "ავტომატური ({})", "Auto Import: added {} photo{}": "ავტოიმპორტი: დაემატა ფოტო: {}{:.0}", @@ -84,7 +84,7 @@ "Imported {n} point curve preset{}": "იმპორტირებულია წერტილოვანი მრუდის პრესეტი: {n}{:.0}", "Imported {n} preset{}": "იმპორტირებულია პრესეტი: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "იმპორტირებულია პრესეტი: {n}{:.0}, ვერ იკითხება ფაილი: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", + "Imported {profiles} profile{} (Profile browser → their groups)": "იმპორტირებულია პროფილი: {profiles}{:.0} (პროფილების ბრაუზერი → მათი ჯგუფები)", "Imported {} photo{}": "იმპორტირებულია ფოტო: {}{:.0}", "In line for AI Denoise ({ahead} ahead)…": "AI ხმაურის მოცილების რიგში (წინ არის: {ahead})…", "Insert at the cursor (also written {})": "კურსორის ადგილას ჩასმა (ასევე იწერება როგორც {})", @@ -212,7 +212,7 @@ "{n} photo{}": "ფოტო: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "შესაბამისი ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", "{n} photo{} now · updates automatically as photos change": "ახლა ფოტო: {n}{:.0} · ავტომატურად განახლდება ფოტოების ცვლილებისას", - "{n} similar photo{} · View ▸ Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", + "{n} similar photo{} · View → Clear Filters to see all": "მსგავსი ფოტო: {n}{:.0} · ყველას სანახავად: ხედი → ფილტრების გასუფთავება", "{n} tasks are still running: {names}. Quitting stops them.": "ჯერ კიდევ მიმდინარეობს ამოცანები ({n}): {names}. გასვლა მათ შეწყვეტს.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -269,12 +269,13 @@ "Effect: {name}": "ეფექტი: {name}", "Exported to {path}": "ექსპორტირებულია: {path}", "Exported {} effect preset{}": "ექსპორტირებულია ეფექტის პრესეტი: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "იმპორტირებულია ნიღბის ეფექტი: {e}{:.0} (ნიღბვა → ეფექტი)", + "Imported {e} mask effect{} (Masking → Effect)": "იმპორტირებულია ნიღბის ეფექტი: {e}{:.0} (ნიღბვა → ეფექტი)", "Imported {name}": "იმპორტირებულია: {name}", + "Moved {name} to {folder}": "{name} გადატანილია: {folder}", "Keywords of {n} selected photos": "მონიშნული ფოტოების ({n}) საკვანძო სიტყვები", "LightCraft stopped unexpectedly: {e}": "LightCraft მოულოდნელად შეწყდა: {e}", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft მოულოდნელად შეწყდა: {e}\n\nდეტალები ჟურნალის ფაილშია: {path}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "„{name}“ მოშორდა ფოტოებს ({n}). რედაქტირება → დაბრუნება მას უკან აბრუნებს.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "„{name}“ მოშორდა ფოტოებს ({n}). რედაქტირება → დაბრუნება მას უკან აბრუნებს.", "Inside: {names}": "შიგნით: {names}", "Renames {n} face{} across the library. The files are not changed.": "სახეებს ({n}){:.0} მთელ ბიბლიოთეკაში ეცვლება სახელი. ფაილები არ იცვლება.", "Saved template {name}": "შაბლონი შენახულია: {name}", @@ -329,5 +330,7 @@ "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით", ", rating {} of 5": ", შეფასება: {} 5-დან" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 7f6c7d07ff..c99377c7a6 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1503,9 +1503,8 @@ "Photo Merge": "ფოტოების გაერთიანება", "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Canon CR2-ის (და სხვა RAW ფაილების, რომელთა ფერსაც LightCraft კამერის საკუთარი JPEG-იდან არგებს, როგორიცაა NEF და", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "„ფოტო“ მენიუში. კადრების ზოლსაც აქვს ფოტოს კონტექსტური მენიუ. ახლახან წაშლილში მყოფი ფაილის ხელახლა დამატება აღარ", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", "Photo › Assisted Culling…": "ფოტო › დამხმარე გადარჩევა…", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "ფოტო → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (⇧⌘E, ან მარჯვენა დაწკაპუნება ფოტოზე) არენდერებს ასლს თქვენი ცვლილებებით, ორიგინალთან ერთ დასტაში აერთიანებს და PhotoCraft-ში ხსნის. იქ შენახვისას ასლი აქაც განახლდება. PSD-ის შემთხვევაში PhotoCraft პირდაპირ მასში ინახავს. მდებარეობა ცარიელი დატოვეთ, თუ პორტატულ ასლს არ იყენებთ.", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "ფოტო → რედაქტირება გარე რედაქტორში (⇧⌘E) ქმნის 16-ბიტიან TIFF ასლს, ორიგინალთან ერთად დასტაში აერთიანებს და აქ ხსნის (macOS-ზე აპის სახელი, სხვაგან — პროგრამის მისამართი).", "Photos": "ფოტოები", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "ფოტოები თქვენი მონიტორის ICC პროფილით ნაჩვენებია, ამიტომ ფერები სწორია ფართო ფერთა გამისა და დაკალიბრებულ ეკრანებზე, ხოლო დეტალური ხედი ეკრანის მთელ ფერთა გამას იყენებს. ჰისტოგრამაზე, წინასწარი ხედების ქეშებსა და ექსპორტზე ეს გავლენას არ ახდენს.", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "ახლახან წაშლილში მყოფი ფოტოების აღდგენა შეიძლება აპიდან: მარჯვენა დაწკაპუნება → აღდგენა (ან სამუდამოდ წაშლა), აგრეთვე", @@ -1715,7 +1714,7 @@ "Remove location info": "მდებარეობის ინფორმაციის წაშლა", "Remove missing photos from the library": "დაკარგული ფოტოების ბიბლიოთეკიდან ამოშლა", "Remove shortcut": "მალსახმობის წაშლა", - "Remove this face box (undo with Edit ▸ Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", + "Remove this face box (undo with Edit → Undo)": "ამ სახის ჩარჩოს წაშლა (დაბრუნება: რედაქტირება → დაბრუნება)", "Remove this filter": "ამ ფილტრის მოშორება", "Remove this group": "ამ ჯგუფის წაშლა", "Remove this rule": "ამ წესის წაშლა", @@ -1780,7 +1779,7 @@ "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "მარჯვენა დაწკაპუნება საქაღალდეზე (ან სასტარტოს გარდა სხვა დისკზე) გვერდითი ზოლის საქაღალდეების სექციაში → საქაღალდის", "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "მარჯვენა დაწკაპუნება საქაღალდეზე → ახალი → ალბომის შექმნა… / სმარტ-ალბომის შექმნა… / სმარტ-ალბომის შექმნა ფილტრიდან… / საქაღალდის შექმნა…", "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "მარჯვენა დაწკაპუნება ფოტოზე → რედაქტირება სხვა პროგრამაში → რედაქტირება PhotoCraft-ში (ან ფოტო → რედაქტირება სხვა პროგრამაში, ⇧⌘E) არენდერებს ასლს თქვენი ცვლილებებით, ათავსებს მას", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "დაწკაპეთ ფოტოზე მარჯვენა ღილაკით → ეტალონურ ფოტოდ დაყენება, შემდეგ ხედი → ეტალონური ხედი (Shift+R)", "Right-click a preset to delete it": "პრესეტის წასაშლელად დაწკაპეთ მასზე მარჯვენა ღილაკით", "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "მარჯვენა დაწკაპუნება → ახალი საკვანძო სიტყვების ამ საკვანძო სიტყვაში ჩასმა: + ღილაკით ან ზემოთ ველში აკრეფილი ახალი საკვანძო სიტყვები", "Rights Usage Terms": "უფლებების გამოყენების პირობები", @@ -3724,12 +3723,19 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", + "User Templates": "მომხმარებლის შაბლონები", + "Delete Folder": "საქაღალდის წაშლა", + "Folder name": "საქაღალდის სახელი", + "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“.", "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", "Reduce Motion": "მოძრაობის შემცირება", "Reduce motion": "მოძრაობის შემცირება", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "გამორთავს მასშტაბირებისა და მიმდინარეობის ინდიკატორის ანიმაციებს. გაბუნდოვნება შენარჩუნდება. სანამ აქ არ შეცვლით, სისტემის „მოძრაობის შემცირების“ პარამეტრს მისდევს.", "Use the system setting": "სისტემის პარამეტრის გამოყენება", "Turns off zoom and spinner animations. Fades stay.": "გამორთავს მასშტაბირებისა და მიმდინარეობის ინდიკატორის ანიმაციებს. გაბუნდოვნება შენარჩუნდება.", + "Drag to move, or use the arrow keys": "გადასატანად გადაიტანეთ ან გამოიყენეთ ისრები", + "A group can't go inside itself": "ჯგუფს საკუთარ თავში ვერ ჩადებთ", + "Groups can't nest any deeper": "ჯგუფების უფრო ღრმად ჩადგმა შეუძლებელია", "Stack — click to expand (S)": "დასტა — დააწკაპუნეთ გასაშლელად (S)", "Stack — click to collapse (S)": "დასტა — დააწკაპუნეთ ჩასაკეცად (S)", "Virtual copy": "ვირტუალური ასლი", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 0520af2d58..1ceeb7db52 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -25,7 +25,7 @@ "Added {what} to {name}": "Dodano {what} do {name}", "Adding photos… {} of {}": "Dodawanie zdjęć… {} z {}", "All {n} selected photos move by the same amount.": "Wszystkie {n} zaznaczone zdjęcia zostaną przesunięte o tę samą wartość.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Już w bibliotece, w Ostatnio usuniętych — zaznaczone zdjęcia: {}{:.0} · kliknij prawym przyciskiem → Przywróć albo Usuń trwale, aby zaimportować ponownie", "Already in the library: {} photo{} selected in All Photos": "Już w bibliotece — zaznaczone zdjęcia we Wszystkich zdjęciach: {}{:.0}", "Auto ({})": "Automatycznie ({})", "Auto Import: added {} photo{}": "Automatyczny import — dodane zdjęcia: {}{:.0}", @@ -66,7 +66,7 @@ "Imported {n} point curve preset{}": "Zaimportowane ustawienia krzywej punktowej: {n}{:.0}", "Imported {n} preset{}": "Zaimportowane ustawienia wstępne: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Zaimportowane ustawienia wstępne: {n}{:.0}, nieczytelne pliki: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Zaimportowane profile: {profiles}{:.0} (Przeglądarka profili → odpowiednie grupy)", "Imported {} photo{}": "Zaimportowane zdjęcia: {}{:.0}", "Insert at the cursor (also written {})": "Wstaw w miejscu kursora (zostanie też zapisane {})", "Label Set: {name}": "Zestaw etykiet: {name}", @@ -187,7 +187,7 @@ "… and {more} more": "… i jeszcze {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft nie obsługuje jeszcze tego wariantu RAW ({}). Edytujesz podgląd JPEG osadzony przez aparat, zawierający już styl obrazu aparatu (np. monochromatyczny) i balans bieli.", "Filtered: {label}": "Filtrowanie: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", + "{n} similar photo{} · View → Clear Filters to see all": "Podobne zdjęcia: {n}{:.0} · Widok → Wyczyść filtry, aby zobaczyć wszystkie", "Moved; {} photo(s) relinked": "Przeniesiono; ponownie powiązane zdjęcia: {}", "{} label (click more labels to show any of them)": "{} etykieta (kliknij kolejne etykiety, aby wyświetlić dowolną z nich)", ", {} label": ", {} etykieta", @@ -263,7 +263,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Usunąć ustawienia efektów ({n})?{:.0} Tej operacji nie można cofnąć.", "Effect: {name}": "Efekt: {name}", "Exported {} effect preset{}": "Wyeksportowane ustawienia efektów: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Zaimportowane efekty masek: {e}{:.0} (Maskowanie → Efekt)", "Update “{name}” with Current Settings": "Zaktualizuj „{name}” bieżącymi ustawieniami", "{n} preset{}": "Ustawienia: {n}{:.0}", "{count} more warnings.": "Pozostałe ostrzeżenia: {count}.", @@ -277,6 +277,7 @@ "Exported to {path}": "Wyeksportowano do {path}", "Saved template {name}": "Zapisano szablon {name}", "Imported {name}": "Zaimportowano {name}", + "Moved {name} to {folder}": "Przeniesiono {name} do {folder}", "Skipped {problem}": "Pominięto: {problem}", "…and {more} more": "…i jeszcze {more}", "Template preview: {name}": "Podgląd szablonu: {name}", @@ -291,7 +292,7 @@ "Create the keyword “{name}”": "Utwórz słowo kluczowe „{name}”", "new, inside {parent}": "nowe, w {parent}", "Keywords of {n} selected photos": "Słowa kluczowe zaznaczonych zdjęć ({n})", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Usunięto „{name}” ze zdjęć ({n}). Edytuj → Cofnij przywraca.", "LightCraft stopped unexpectedly: {e}\n\nThe log file has the details: {path}": "LightCraft nieoczekiwanie zakończył działanie: {e}\n\nSzczegóły są w pliku dziennika: {path}", "LightCraft stopped unexpectedly: {e}": "LightCraft nieoczekiwanie zakończył działanie: {e}", "Renames {n} face{} across the library. The files are not changed.": "Zmienia nazwę twarzy w całej bibliotece (twarze: {n}).{:.0} Pliki nie są zmieniane.", @@ -326,5 +327,7 @@ "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami", ", rating {} of 5": ", ocena: {} na 5" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 56162c1337..12f9b320b1 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -1165,7 +1165,7 @@ "Remove from survey": "Usuń z widoku przeglądu", "Remove location info": "Usuń informacje o lokalizacji", "Remove shortcut": "Usuń skrót klawiszowy", - "Remove this face box (undo with Edit ▸ Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", + "Remove this face box (undo with Edit → Undo)": "Usuń tę ramkę twarzy (cofnij przez Edycja → Cofnij)", "Remove this filter": "Usuń ten filtr", "Remove this group": "Usuń tę grupę", "Remove this rule": "Usuń tę regułę", @@ -1218,7 +1218,7 @@ "Revert": "Cofnij zmiany", "Review": "Przegląd", "Review Import": "Sprawdź import", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Kliknij zdjęcie prawym przyciskiem → Ustaw jako zdjęcie referencyjne, a potem Widok → Widok referencyjny (Shift+R)", "Right-click a preset to delete it": "Kliknij ustawienie wstępne prawym przyciskiem, aby je usunąć", "Rights Usage Terms": "Warunki korzystania z praw", "Rotate": "Obróć", @@ -1938,7 +1938,6 @@ "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "Maski Obiekt i Opis korzystają z modelu segmentacji SAM 3 firmy Meta. Nie jest on częścią LightCraft; wszystkie pozostałe funkcje działają bez niego.", "Panasonic and Leica raws (RW2, RWL and the older RAW files, DMC-LX1 to DC-S1R II) develop from the raw data in": "Pliki RAW Panasonic i Leica (RW2, RWL i starsze RAW, od DMC-LX1 do DC-S1R II) są wywoływane z danych RAW w", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "menu Zdjęcie. Pasek zdjęć ma także menu kontekstowe. Ponowne dodanie pliku znajdującego się w Ostatnio usuniętych nie", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Zdjęcie → Edytuj w edytorze zewnętrznym (⇧⌘E) tworzy 16-bitową kopię TIFF, grupuje ją z oryginałem i otwiera w wybranym programie (nazwa aplikacji w macOS, ścieżka programu w pozostałych systemach).", "Photos in Recently Deleted can be restored from the app: right-click ▸ Restore (or Delete Permanently), also in the": "Zdjęcia w Ostatnio usuniętych można przywrócić w aplikacji: kliknij prawym przyciskiem → Przywróć (lub Usuń trwale), również w", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Zdjęcia widoczne w widoku Lokalnie, lecz nigdy niedodane ani niezmienione, są usuwane z katalogu, jeśli ich folder nie był przeglądany przez określony czas (sprawdzane przy otwieraniu biblioteki). Pliki pozostają na dysku; ponowne przejrzenie folderu znów je pokazuje.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Zdjęcia pojawiające się w tym folderze (z aparatu podłączonego do komputera, skanera lub aplikacji synchronizującej) są dodawane od razu po ukończeniu zapisu.", @@ -2359,6 +2358,10 @@ "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", "Bottom bar": "Dolny pasek", + "User Templates": "Szablony użytkownika", + "Delete Folder": "Usuń folder", + "Folder name": "Nazwa folderu", + "Its templates move to User Templates.": "Jego szablony zostaną przeniesione do folderu Szablony użytkownika.", "Welcome to LightCraft": "Witamy w LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Szybka biblioteka zdjęć i nieniszczący program do obróbki RAW: oryginały pozostają nietknięte, a każdą edycję można później obejrzeć lub cofnąć.", "Bring photos in with File › Import Photos…": "Zdjęcia importujesz przez Plik › Importuj zdjęcia…", @@ -2387,6 +2390,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Wyłącza animacje powiększania i wskaźników pracy. Zanikanie i przenikanie zostają. Dopóki nie zmienisz tego tutaj, program stosuje systemowe ustawienie Ogranicz ruch.", "Use the system setting": "Użyj ustawienia systemu", "Turns off zoom and spinner animations. Fades stay.": "Wyłącza animacje powiększania i wskaźników pracy. Zanikanie i przenikanie zostają.", + "Drag to move, or use the arrow keys": "Przeciągnij, aby przenieść, lub użyj strzałek", + "A group can't go inside itself": "Grupa nie może znaleźć się wewnątrz samej siebie", + "Groups can't nest any deeper": "Grup nie można zagnieżdżać głębiej", "Stack — click to expand (S)": "Stos — kliknij, aby rozwinąć (S)", "Stack — click to collapse (S)": "Stos — kliknij, aby zwinąć (S)", "Virtual copy": "Kopia wirtualna", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 89df13687d..4c9450a3d2 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -15,7 +15,7 @@ "Added {n} photo{} to “{}”": "{n} foto{0} adicionada{0} a “{1}”", "Adding photos… {} of {}": "Adicionando fotos… {} de {}", "All {n} selected photos move by the same amount.": "Todas as {n} fotos selecionadas se movem pela mesma quantidade.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Já na biblioteca, em Excluídos recentemente: {0} foto{1} selecionada{1} · clique com o botão direito → Restaurar, ou Excluir permanentemente para importar de novo", "Already in the library: {} photo{} selected in All Photos": "Já na biblioteca: {0} foto{1} selecionada{1} em Todas as fotos", "Already in “{}”": "Já está em “{}”", "Auto ({})": "Automático ({})", @@ -176,7 +176,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright guiado não é compatível.", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "A geometria do Lightroom não foi preservada para {path}; a transformação salva do Upright não é compatível.", "XMP adjustments were not imported for {path}: {fields}.": "Os ajustes XMP não foram importados para {path}: {fields}.", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", + "Imported {profiles} profile{} (Profile browser → their groups)": "{profiles} perfil(is) importado(s){:.0} (Navegador de perfis → seus grupos)", "Insert at the cursor (also written {})": "Inserir no cursor (também escrito {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0. Fontes: {} (OFL). Ícones: originais.", "Painting “{k}”: click photos to add or remove it · Esc stops": "Aplicando “{k}”: clique nas fotos para adicionar ou remover · Esc para", @@ -206,7 +206,7 @@ "{} — show their photos": "{} — mostrar as fotos desta pessoa", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "O LightCraft ainda não consegue decodificar esta variante RAW ({}). Você está editando a prévia JPEG incorporada da câmera, que já inclui o estilo de imagem da câmera (p. ex. Monocromático) e o balanço de branco.", "Filtered: {label}": "Filtrado: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", + "{n} similar photo{} · View → Clear Filters to see all": "{n} foto{0} semelhante{0} · Exibir → Limpar filtros para ver todas", "Moved; {} photo(s) relinked": "Movida; {} foto(s) vinculada(s) novamente", "{} label (click more labels to show any of them)": "Rótulo {} (clique em mais rótulos para mostrar qualquer um deles)", ", {} label": ", rótulo {}", @@ -254,7 +254,7 @@ "Create the keyword “{name}”": "Criar a palavra-chave “{name}”", "new, inside {parent}": "nova, dentro de {parent}", "Keywords of {n} selected photos": "Palavras-chave de {n} fotos selecionadas", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "“{name}” removida de {n} fotos. Editar → Desfazer a traz de volta.", "1 task is still running: {names}. Quitting stops it.": "1 tarefa ainda está em andamento: {names}. Sair a interrompe.", "{n} tasks are still running: {names}. Quitting stops them.": "{n} tarefas ainda estão em andamento: {names}. Sair as interrompe.", "{what} merge cancelled": "{what} mesclagem cancelada", @@ -275,7 +275,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Excluir {n} predefinição(ões) de efeito?{:.0} Não é possível desfazer.", "Effect: {name}": "Efeito: {name}", "Exported {} effect preset{}": "Predefinições de efeito exportadas: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", + "Imported {e} mask effect{} (Masking → Effect)": "{e} efeito(s) de máscara importado(s){:.0} (Máscaras → Efeito)", "Update “{name}” with Current Settings": "Atualizar “{name}” com as configurações atuais", "{n} preset{}": "{n} predefinição(ões){:.0}", "{name} opened in the other editor": "{name} aberto no outro editor", @@ -292,6 +292,7 @@ "Exported to {path}": "Exportado para {path}", "Saved template {name}": "Modelo {name} salvo", "Imported {name}": "{name} importado", + "Moved {name} to {folder}": "{name} movido para {folder}", "Skipped {problem}": "Ignorado: {problem}", "…and {more} more": "…e mais {more}", "Template preview: {name}": "Prévia do modelo: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Regra {n} de {m}: {what}. Mova com as setas", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: igualar {mode}, {count} dentro. Mova com as setas", ", rating {} of 5": ", avaliação: {} de 5" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 1e1dfb1d2d..d2e96211f0 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -1055,7 +1055,6 @@ "Photo Grid": "Grade de fotos", "Photo Grid (G)": "Grade de fotos (G)", "Photo Merge": "Mesclagem de fotos", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Editar no editor externo (⇧⌘E) renderiza uma cópia TIFF de 16 bits, empilha-a com o original e a abre aqui (um nome de aplicativo no macOS, um caminho de programa em outros sistemas).", "Photos": "Fotos", "Photos per bracket (0 = auto)": "Fotos por bracketing (0 = automático)", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Fotos vistas em Local mas nunca adicionadas nem alteradas saem do catálogo quando sua pasta não é navegada por esse período (verificado ao abrir a biblioteca). Os arquivos permanecem no disco; navegar pela pasta as mostra novamente.", @@ -1213,7 +1212,7 @@ "Remove from survey": "Remover da inspeção", "Remove location info": "Remover informações de local", "Remove shortcut": "Remover atalho", - "Remove this face box (undo with Edit ▸ Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", + "Remove this face box (undo with Edit → Undo)": "Remover esta caixa de rosto (desfaça com Editar → Desfazer)", "Remove this filter": "Remover este filtro", "Remove this group": "Remover este grupo", "Remove this rule": "Remover esta regra", @@ -1266,7 +1265,7 @@ "Revert": "Reverter", "Review": "Revisão", "Review Import": "Revisar importação", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Clique com o botão direito em uma foto → Definir como foto de referência, depois Exibir → Exibição de referência (Shift+R)", "Right-click a preset to delete it": "Clique com o botão direito em uma predefinição para excluí-la", "Rights Usage Terms": "Termos de uso dos direitos", "Rotate": "Girar", @@ -2169,7 +2168,7 @@ "Tidying the thumbnail cache": "Organizando o cache de miniaturas", "Checking free disk space": "Verificando o espaço livre em disco", "Reset all edits (Cmd+Shift+R)": "Redefinir todas as edições (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Álbuns inteligentes se atualizam sozinhos: altere as regras ou use Foto → Excluir foto", "LightCraft stopped": "O LightCraft parou", "Focus Point": "Ponto de foco", "Zoom to Focus Point": "Zoom no ponto de foco", @@ -2281,6 +2280,10 @@ "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "User Templates": "Modelos do usuário", + "Delete Folder": "Excluir pasta", + "Folder name": "Nome da pasta", + "Its templates move to User Templates.": "Os modelos dela vão para Modelos do usuário.", "Welcome to LightCraft": "Bem-vindo ao LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Uma biblioteca de fotos rápida e não destrutiva e um revelador RAW: seus originais permanecem intactos, e cada edição pode ser revista ou desfeita.", "Bring photos in with File › Import Photos…": "Traga fotos com Arquivo › Importar fotos…", @@ -2308,6 +2311,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Desativa as animações de zoom e dos indicadores de atividade. As transições de opacidade continuam. Segue o ajuste Reduzir movimento do sistema até você alterá-lo aqui.", "Use the system setting": "Usar o ajuste do sistema", "Turns off zoom and spinner animations. Fades stay.": "Desativa as animações de zoom e dos indicadores de atividade. As transições de opacidade continuam.", + "Drag to move, or use the arrow keys": "Arraste para mover ou use as setas", + "A group can't go inside itself": "Um grupo não pode ficar dentro de si mesmo", + "Groups can't nest any deeper": "Os grupos não podem ser aninhados mais fundo", "Stack — click to expand (S)": "Pilha — clique para expandir (S)", "Stack — click to collapse (S)": "Pilha — clique para recolher (S)", "Virtual copy": "Cópia virtual", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 86671ed752..87ba31bbaa 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -27,7 +27,7 @@ "Adjustments: {n}": "Корректировки: {n}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", "Already in the library: {} photo{} selected in All Photos": "Уже в библиотеке: выбрано фото в разделе «Все фото»: {}{:.0}", "Auto ({})": "Авто ({})", "Auto Import: added {} photo{}": "Автоимпорт: добавлено фото: {}{:.0}", @@ -78,7 +78,7 @@ "Imported {n} point curve preset{}": "Импортировано пресетов точечной кривой: {n}{:.0}", "Imported {n} preset{}": "Импортировано пресетов: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Импортировано пресетов: {n}{:.0}, не читается файлов: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Импортировано профилей: {profiles}{:.0} (Обозреватель профилей → их группы)", "Imported {} photo{}": "Импортировано фото: {}{:.0}", "Insert at the cursor (also written {})": "Вставить в позицию курсора (также пишется как {})", "Label Set: {name}": "Набор меток: {name}", @@ -175,7 +175,7 @@ "{n} photo{} match · updates automatically as photos change": "Подходящих фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} photo{} now · updates automatically as photos change": "Сейчас фото: {n}{:.0} · обновляется автоматически при изменении фото", "{n} selected photo{} · {pages} page{}": "Выбрано фото: {n} · страниц: {pages}{:.0}{:.0}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", + "{n} similar photo{} · View → Clear Filters to see all": "Похожих фото: {n}{:.0} · Вид → Сбросить фильтры, чтобы увидеть все", "{pid} (missing)": "{pid} (отсутствует)", "{sel_n} selected · {counted}": "Выбрано: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", @@ -250,7 +250,7 @@ "Create the keyword “{name}”": "Создать ключевое слово «{name}»", "new, inside {parent}": "новое, внутри {parent}", "Keywords of {n} selected photos": "Ключевые слова выбранных фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» убрано с фото: {n}. Правка → Отменить вернёт его.", "1 task is still running: {names}. Quitting stops it.": "Ещё выполняется задача: {names}. Выход прервёт её.", "{n} tasks are still running: {names}. Quitting stops them.": "Ещё выполняется задач: {n} — {names}. Выход прервёт их.", "{what} merge cancelled": "{what}: слияние отменено", @@ -271,7 +271,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Удалить пресеты эффектов ({n})?{:.0} Это нельзя отменить.", "Effect: {name}": "Эффект: {name}", "Exported {} effect preset{}": "Экспортировано пресетов эффектов: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", + "Imported {e} mask effect{} (Masking → Effect)": "Импортировано эффектов маски: {e}{:.0} (Маски → Эффект)", "Update “{name}” with Current Settings": "Обновить «{name}» текущими настройками", "{n} preset{}": "Пресетов: {n}{:.0}", "{name} opened in the other editor": "{name} открыт в другом редакторе", @@ -288,6 +288,7 @@ "Exported to {path}": "Экспортировано в {path}", "Saved template {name}": "Шаблон {name} сохранён", "Imported {name}": "Импортировано: {name}", + "Moved {name} to {folder}": "{name} перемещено в {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…и ещё {more}", "Template preview: {name}": "Просмотр шаблона: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Условие {n} из {m}: {what}. Перемещение стрелками", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Группа {n} из {m}: совпадение {mode}, внутри {count}. Перемещение стрелками", ", rating {} of 5": ", оценка: {} из 5" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 4d8aab5bdf..3fef8d0757 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -1092,7 +1092,6 @@ "Photo Grid": "Сетка фото", "Photo Grid (G)": "Сетка фото (G)", "Photo Merge": "Слияние фото", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Фото → Править во внешнем редакторе (⇧⌘E) создаёт 16-битную TIFF-копию, помещает её в стопку с оригиналом и открывает здесь (имя приложения в macOS, путь к программе в других системах).", "Photos": "Фото", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Фото, которые видели в «Локальном», но ни разу не добавляли и не меняли, исключаются из каталога, если папку не открывали так долго (проверяется при открытии библиотеки). Файлы остаются на диске; при просмотре папки они появятся снова.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Фото, поступающие в эту папку (тетеринг, сканер, приложение синхронизации), добавляются, как только будут готовы.", @@ -1264,7 +1263,7 @@ "Retouch": "Ретушь", "Revert": "Вернуть", "Review Import": "Проверить импорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Щёлкните фото правой кнопкой → Назначить эталонным фото, затем Вид → Режим эталона (Shift+R)", "Right-click a preset to delete it": "Щёлкните пресет правой кнопкой, чтобы удалить его", "Rights Usage Terms": "Условия использования прав", "Rotate": "Повернуть", @@ -2204,7 +2203,7 @@ "Remove a filter above, or choose Clear all": "Уберите фильтр выше или выберите «Очистить всё»", "Remove from Library…": "Убрать из библиотеки…", "Remove from Target Album": "Убрать из целевого альбома", - "Remove this face box (undo with Edit ▸ Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", + "Remove this face box (undo with Edit → Undo)": "Удалить эту рамку лица (отмена: Правка → Отменить)", "Rename Component": "Переименовать компонент", "Rename Folder… and Move Folder To… (Local) can be undone and redone (issue #97): the folder moves back on disk with": "Переименование папки… и перемещение папки в… («Локальное») можно отменить и повторить (проблема #97): папка возвращается на диске вместе с", "Rename Photos never overwrites another photo when only the letter case changes (issue #95): on case-sensitive": "Переименование фото никогда не перезаписывает другое фото, когда меняется только регистр букв (проблема #95): на томах с учётом регистра", @@ -2537,7 +2536,7 @@ "Tidying the thumbnail cache": "Упорядочивание кэша миниатюр", "Checking free disk space": "Проверка свободного места на диске", "Reset all edits (Cmd+Shift+R)": "Сбросить все правки (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Смарт-альбомы обновляются сами: измените их правила или выберите Фото → Удалить фото", "LightCraft stopped": "LightCraft остановился", "Focus Point": "Точка фокусировки", "Zoom to Focus Point": "Увеличить по точке фокусировки", @@ -2643,6 +2642,10 @@ "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "User Templates": "Пользовательские шаблоны", + "Delete Folder": "Удалить папку", + "Folder name": "Название папки", + "Its templates move to User Templates.": "Её шаблоны будут перемещены в «Пользовательские шаблоны».", "Welcome to LightCraft": "Добро пожаловать в LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Быстрая библиотека фотографий и неразрушающий проявитель RAW: оригиналы остаются нетронутыми, а каждую правку можно просмотреть или сбросить.", "Bring photos in with File › Import Photos…": "Фотографии добавляются через Файл › Импорт фото…", @@ -2670,6 +2673,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Отключает анимацию масштабирования и индикаторов работы. Плавные затухания остаются. Пока вы не измените это здесь, действует системная настройка «Уменьшение движения».", "Use the system setting": "Использовать настройку системы", "Turns off zoom and spinner animations. Fades stay.": "Отключает анимацию масштабирования и индикаторов работы. Плавные затухания остаются.", + "Drag to move, or use the arrow keys": "Перетащите, чтобы переместить, или используйте стрелки", + "A group can't go inside itself": "Группу нельзя поместить внутрь самой себя", + "Groups can't nest any deeper": "Группы нельзя вкладывать глубже", "Stack — click to expand (S)": "Стопка — щёлкните, чтобы развернуть (S)", "Stack — click to collapse (S)": "Стопка — щёлкните, чтобы свернуть (S)", "Virtual copy": "Виртуальная копия", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 08dff39bc7..fcb15a5eda 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -39,7 +39,7 @@ "Add Keyword “{keywords}”": "Lägg till nyckelordet ”{keywords}”", "Adding photos… {} of {}": "Lägger till foton… {} av {}", "All {n} selected photos move by the same amount.": "Alla {n} markerade foton flyttas lika mycket.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Finns redan i biblioteket, i Nyligen raderade: {} foto{} markerade · högerklicka → Återställ, eller Radera permanent för att importera på nytt", "Already in the library: {} photo{} selected in All Photos": "Finns redan i biblioteket: {} foto{} markerade i Alla foton", "Applied {name}": "Tillämpade {name}", "Apply to “{mask}” on Selected Photos": "Använd på ”{mask}” i markerade foton", @@ -94,12 +94,13 @@ "Import failed: {e}": "Importen misslyckades: {e}", "Import photos with File → Import Photos… ({}), or drop them here": "Importera foton med Arkiv → Importera foton… ({}) eller släpp dem här", "Import warnings ({n}):\n{warnings}": "Importvarningar ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", + "Imported {e} mask effect{} (Masking → Effect)": "Importerade {e} maskeffekt{} (Maskering → Effekt)", "Imported {name}": "Importerade {name}", + "Moved {name} to {folder}": "Flyttade {name} till {folder}", "Imported {n} point curve preset{}": "Importerade {n} punktkurvförinställning{}", "Imported {n} preset{}": "Importerade {n} förinställning{}", "Imported {n} preset{}, {f} file{} not readable": "Importerade {n} förinställning{}, {f} fil{} kunde inte läsas", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Importerade {profiles} profil{} (Profilbläddrare → deras grupper)", "Imported {} photo{}": "Importerade {} foto{}", "In line for AI Denoise ({ahead} ahead)…": "I kö för AI-brusreducering ({ahead} före)…", "Insert at the cursor (also written {})": "Infoga vid textmarkören (skrivs även {})", @@ -158,7 +159,7 @@ "Remove “{}” from Favorites": "Ta bort ”{}” från Favoriter", "Removed from {}": "Borttaget från {}", "Removed {what} from {name}": "Tog bort {what} från {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Tog bort ”{name}” från {n} foton. Redigera → Ångra lägger tillbaka det.", "Rename {n} Photos…": "Byt namn på {n} foton…", "Rename “{name}”": "Byt namn på ”{name}”", "Renames {n} face{} across the library. The files are not changed.": "Byter namn på {n} ansikte{} i hela biblioteket. Filerna ändras inte.", @@ -247,7 +248,7 @@ "{n} photo{} now · updates automatically as photos change": "{n} foto{} just nu · uppdateras automatiskt när fotona ändras", "{n} preset{}": "{n} förinställning{}", "{n} raws can now be developed from their raw data": "{n} raw-filer kan nu framkallas från sina rådata", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", + "{n} similar photo{} · View → Clear Filters to see all": "{n} likartade foto{} · Visa → Rensa filter för att se alla", "{n} tasks are still running: {names}. Quitting stops them.": "{n} uppgifter körs fortfarande: {names}. Om du avslutar stoppas de.", "{n} {noun}": "{n} {noun}", "{pct} %": "{pct} %", @@ -326,5 +327,7 @@ "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna", ", rating {} of 5": ", betyg: {} av 5" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 4594522c2b..a5604c37fe 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -1549,7 +1549,7 @@ "Photo Merge": "Fotosammanfogning", "photo waiting": "foto väntar", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Foto → Redigera i externt program (⇧⌘E) renderar en 16-bitars TIFF-kopia, staplar den med originalet och öppnar den här (ett appnamn på macOS, en programsökväg på andra system).", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Redigera i → Redigera i PhotoCraft (⇧⌘E, eller högerklicka på ett foto) renderar en kopia med dina ändringar, staplar den med originalet och öppnar den i PhotoCraft. Spara där så uppdateras kopian här. Som PSD sparar PhotoCraft direkt tillbaka till den. Lämna platsen tom om du inte använder en portabel kopia.", "PhotoCraft": "PhotoCraft", "Photos": "Foton", "Photos are shown through your monitor's ICC profile, so colours are right on wide-gamut and calibrated displays, and the Detail view uses the display's whole gamut. The histogram, the preview caches and exports are not affected.": "Foton visas genom bildskärmens ICC-profil, så att färgerna blir rätt på kalibrerade skärmar och skärmar med brett färgomfång, och vyn Detalj använder skärmens hela färgomfång. Histogrammet, förhandsgranskningscacharna och exporter påverkas inte.", @@ -1766,7 +1766,7 @@ "Remove missing photos from the library": "Ta bort saknade foton från biblioteket", "Remove region": "Ta bort region", "Remove shortcut": "Ta bort kortkommando", - "Remove this face box (undo with Edit ▸ Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", + "Remove this face box (undo with Edit → Undo)": "Ta bort den här ansiktsrutan (ångra med Redigera → Ångra)", "Remove this filter": "Ta bort det här filtret", "Remove this group": "Ta bort den här gruppen", "Remove this rule": "Ta bort den här regeln", @@ -1835,7 +1835,7 @@ "Review": "Granskning", "Review Import": "Granska import", "Right": "Höger", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Högerklicka på ett foto → Ange som referensfoto, sedan Visa → Referensvy (Shift+R)", "Right-click a preset to delete it": "Högerklicka på en förinställning för att radera den", "Rights Usage Terms": "Villkor för användningsrätt", "Rotate": "Rotera", @@ -2052,7 +2052,7 @@ "Smart Album Rule Fields": "Regelfält för smarta album", "smart album value|No": "Nej", "smart album value|Yes": "Ja", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Smarta album uppdateras automatiskt: ändra deras regler eller använd Foto → Radera foto", "Smart albums with a rule editor: match all / any / none, nested groups, 26 fields.": "Smarta album med regelredigerare: matcha alla/någon/ingen, nästlade grupper, 26 fält.", "Smart preview available": "Smart förhandsgranskning tillgänglig", "Smart Preview Status": "Status för smart förhandsgranskning", @@ -2517,12 +2517,19 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", + "User Templates": "Användarmallar", + "Delete Folder": "Radera mapp", + "Folder name": "Mappnamn", + "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar.", "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", "Reduce Motion": "Minska rörelse", "Reduce motion": "Minska rörelse", "Turns off zoom and spinner animations. Fades stay.": "Stänger av zoom- och snurranimationer. Toningar finns kvar.", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Stänger av zoom- och snurranimationer. Toningar finns kvar. Följer systemets Minska rörelse tills du ändrar det här.", "Use the system setting": "Använd systeminställningen", + "Drag to move, or use the arrow keys": "Dra för att flytta, eller använd piltangenterna", + "A group can't go inside itself": "En grupp kan inte läggas inuti sig själv", + "Groups can't nest any deeper": "Grupper kan inte nästlas djupare", "Right-click ▸ Locate Missing File… to find it again.": "Högerklicka → Leta upp saknad fil… för att hitta den igen.", "Right-click ▸ Reload from Disk to try again.": "Högerklicka → Läs in igen från disk för att försöka igen.", "Stack — click to collapse (S)": "Stapel — klicka för att komprimera (S)", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index d9f93772ff..3871bc75af 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -26,7 +26,7 @@ "Adjustments: {n}": "Коригування: {n}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", "Already in the library: {} photo{} selected in All Photos": "Уже в бібліотеці: вибрано фото в усіх фото: {}{:.0}", "Auto ({})": "Автоматично ({})", "Auto Import: added {} photo{}": "Автоімпорт: додано фото: {}{:.0}", @@ -69,7 +69,7 @@ "Imported {n} point curve preset{}": "Імпортовано наборів налаштувань точкової кривої: {n}{:.0}", "Imported {n} preset{}": "Імпортовано наборів налаштувань: {n}{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Імпортовано наборів налаштувань: {n}{:.0}, файлів не читається: {f}{:.0}", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не вдалося записати XMP-файли {n} фото (папка недоступна?). LightCraft продовжує спроби.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профіль XMP «{profile}» не застосовано до {path}; кольори можуть відрізнятися від Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Геометрію Lightroom для {path} не збережено; режим {mode} буде перераховано.", @@ -202,7 +202,7 @@ "… and {more} more": "… і ще {more}", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft ще не може декодувати цей варіант RAW ({}). Ви редагуєте вбудований JPEG-перегляд камери, який уже містить її стиль зображення (наприклад, монохромний) і баланс білого.", "Filtered: {label}": "Відфільтровано: {label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", + "{n} similar photo{} · View → Clear Filters to see all": "Подібних фото: {n}{:.0} · Вигляд → Скинути фільтри, щоб побачити всі", "Moved; {} photo(s) relinked": "Переміщено; повторно пов’язано фото: {}", "{} label (click more labels to show any of them)": "Мітка «{}» (клацніть інші мітки, щоб показати фото з будь-якою з них)", ", {} label": ", мітка: {}", @@ -250,7 +250,7 @@ "Create the keyword “{name}”": "Створити ключове слово «{name}»", "new, inside {parent}": "нове, всередині {parent}", "Keywords of {n} selected photos": "Ключові слова вибраних фото: {n}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "«{name}» вилучено з фото: {n}. Редагування → Скасувати поверне його.", "1 task is still running: {names}. Quitting stops it.": "1 завдання ще виконується: {names}. Вихід зупинить його.", "{n} tasks are still running: {names}. Quitting stops them.": "Ще виконуються завдання ({n}): {names}. Вихід зупинить їх.", "{what} merge cancelled": "Об’єднання {what} скасовано", @@ -271,7 +271,7 @@ "Delete {n} effect preset{}? This can't be undone.": "Видалити пресети ефектів ({n})?{:.0} Це не можна скасувати.", "Effect: {name}": "Ефект: {name}", "Exported {} effect preset{}": "Експортовано пресетів ефектів: {}{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", + "Imported {e} mask effect{} (Masking → Effect)": "Імпортовано ефектів маски: {e}{:.0} (Маски → Ефект)", "Update “{name}” with Current Settings": "Оновити «{name}» поточними налаштуваннями", "{n} preset{}": "Пресетів: {n}{:.0}", "{name} opened in the other editor": "{name} відкрито в іншому редакторі", @@ -288,6 +288,7 @@ "Exported to {path}": "Експортовано до {path}", "Saved template {name}": "Шаблон {name} збережено", "Imported {name}": "Імпортовано: {name}", + "Moved {name} to {folder}": "{name} переміщено до {folder}", "Skipped {problem}": "Пропущено: {problem}", "…and {more} more": "…і ще {more}", "Template preview: {name}": "Перегляд шаблону: {name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Правило {n} з {m}: {what}. Переміщення стрілками", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Група {n} з {m}: збіг {mode}, усередині {count}. Переміщення стрілками", ", rating {} of 5": ", оцінка: {} з 5" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 2ae059e689..2772aeb8e2 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -940,7 +940,7 @@ "Remove a filter above, or choose Clear all": "Видаліть фільтр вище або виберіть «Очистити все»", "Remove from Target Album": "Вилучити з цільового альбому", "Remove shortcut": "Видалити скорочення", - "Remove this face box (undo with Edit ▸ Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", + "Remove this face box (undo with Edit → Undo)": "Видалити цю рамку обличчя (скасувати через Редагування → Скасувати)", "Rename Component": "Перейменувати компонент", "Rename Folder": "Перейменувати теку", "Rename Mask": "Перейменувати маску", @@ -1182,7 +1182,6 @@ "Photo Grid": "Сітка фото", "Photo Grid (G)": "Сітка фото (G)", "Photo Merge": "Об’єднання фото", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Фото → Редагувати в зовнішньому редакторі (⇧⌘E) створює 16-бітну копію TIFF, додає її до стосу з оригіналом і відкриває тут (назва застосунку в macOS, шлях до програми в інших системах).", "Photos": "Фото", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "Фото, переглянуті в локальних, але ніколи не додані й не змінені, вилучаються з каталогу, якщо їхню теку не оглядали протягом цього часу (перевіряється під час відкриття бібліотеки). Файли залишаються на диску; огляд теки знову їх показує.", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Фото, що надходять до цієї теки (камерне підключення, сканер, застосунок синхронізації), додаються одразу після завершення запису.", @@ -1283,7 +1282,7 @@ "Restore them": "Відновити їх", "Retouch": "Ретушування", "Review Import": "Перевірити імпорт", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Клацніть фото правою кнопкою → Задати як еталонне фото, потім Вигляд → Еталонне подання (Shift+R)", "Right-click a preset to delete it": "Клацніть набір налаштувань правою кнопкою, щоб видалити його", "Rights Usage Terms": "Умови використання прав", "Rotate Crop": "Обертати кадрування", @@ -2327,7 +2326,7 @@ "Tidying the thumbnail cache": "Упорядкування кешу мініатюр", "Checking free disk space": "Перевірка вільного місця на диску", "Reset all edits (Cmd+Shift+R)": "Скинути всі зміни (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "Розумні альбоми оновлюються самі: змініть їхні правила або виберіть Фото → Видалити фото", "LightCraft stopped": "LightCraft зупинився", "Focus Point": "Точка фокусування", "Zoom to Focus Point": "Збільшити до точки фокусування", @@ -2433,6 +2432,10 @@ "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "User Templates": "Власні шаблони", + "Delete Folder": "Видалити теку", + "Folder name": "Назва теки", + "Its templates move to User Templates.": "Її шаблони буде переміщено до «Власні шаблони».", "Welcome to LightCraft": "Ласкаво просимо до LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Швидка бібліотека фотографій і неруйнівна обробка RAW: оригінали залишаються недоторканими, а кожну зміну можна переглянути або скасувати.", "Bring photos in with File › Import Photos…": "Фотографії імпортуйте через Файл › Імпортувати фото…", @@ -2460,6 +2463,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Вимикає анімацію масштабування та індикаторів роботи. Плавні згасання залишаються. Доки ви не зміните це тут, діє системне налаштування «Зменшити рух».", "Use the system setting": "Використовувати налаштування системи", "Turns off zoom and spinner animations. Fades stay.": "Вимикає анімацію масштабування та індикаторів роботи. Плавні згасання залишаються.", + "Drag to move, or use the arrow keys": "Перетягніть, щоб перемістити, або скористайтеся стрілками", + "A group can't go inside itself": "Групу не можна помістити саму в себе", + "Groups can't nest any deeper": "Групи не можна вкладати глибше", "Stack — click to expand (S)": "Стос — клацніть, щоб розгорнути (S)", "Stack — click to collapse (S)": "Стос — клацніть, щоб згорнути (S)", "Virtual copy": "Віртуальна копія", diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 2ff7c7824c..883b61f05e 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -39,7 +39,7 @@ "Add Keyword “{keywords}”": "Thêm từ khóa «{keywords}»", "Adding photos… {} of {}": "Đang thêm ảnh… {} / {}", "All {n} selected photos move by the same amount.": "Tất cả {n} ảnh đã chọn dịch chuyển cùng một lượng.", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "Đã có trong thư viện, trong Đã xóa gần đây: đã chọn {} ảnh{:.0} · nhấp chuột phải → Khôi phục, hoặc Xóa vĩnh viễn để nhập lại", "Already in the library: {} photo{} selected in All Photos": "Đã có trong thư viện: đã chọn {} ảnh{:.0} trong Tất cả ảnh", "Already in “{}”": "Already in “{}”", "Applied {name}": "Applied {name}", @@ -96,12 +96,13 @@ "Import failed: {e}": "Nhập thất bại: {e}", "Import photos with File → Import Photos… ({}), or drop them here": "Nhập ảnh bằng Tệp → Nhập ảnh… ({}), hoặc thả vào đây", "Import warnings ({n}):\n{warnings}": "Cảnh báo khi nhập ({n}):\n{warnings}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", + "Imported {e} mask effect{} (Masking → Effect)": "Imported {e} mask effect{} (Masking → Effect)", "Imported {name}": "Imported {name}", + "Moved {name} to {folder}": "Đã chuyển {name} vào {folder}", "Imported {n} point curve preset{}": "Đã nhập {n} thiết lập sẵn đường cong điểm{:.0}", "Imported {n} preset{}": "Đã nhập {n} thiết lập sẵn{:.0}", "Imported {n} preset{}, {f} file{} not readable": "Đã nhập {n} thiết lập sẵn{:.0}, {f} tệp{:.0} không đọc được", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", + "Imported {profiles} profile{} (Profile browser → their groups)": "Đã nhập {profiles} hồ sơ{:.0} (Trình duyệt hồ sơ → nhóm của chúng)", "Imported {} photo{}": "Đã nhập {} ảnh{:.0}", "In line for AI Denoise ({ahead} ahead)…": "Đang xếp hàng Khử nhiễu AI (trước bạn: {ahead})…", "Insert at the cursor (also written {})": "Chèn tại con trỏ (cũng ghi là {})", @@ -162,7 +163,7 @@ "Remove “{}” from Favorites": "Gỡ «{}» khỏi Yêu thích", "Removed from {}": "Đã gỡ khỏi {}", "Removed {what} from {name}": "Đã gỡ {what} khỏi {name}", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "Removed “{name}” from {n} photos. Edit → Undo puts it back.", "Rename {n} Photos…": "Đổi tên {n} ảnh…", "Rename “{name}”": "Đổi tên «{name}»", "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", @@ -255,7 +256,7 @@ "{n} preset{}": "{n} preset{}", "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", "{n} selected photo{} · {pages} page{}": "{n} ảnh đã chọn · {pages} trang{:.0}{:.0}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", + "{n} similar photo{} · View → Clear Filters to see all": "{n} ảnh tương tự{:.0} · Xem → Xóa bộ lọc để thấy tất cả", "{n} tasks are still running: {names}. Quitting stops them.": "Còn {n} tác vụ đang chạy: {names}. Thoát sẽ dừng chúng.", "{n} {noun}": "{noun}: {n}", "{pct} %": "{pct} %", @@ -323,5 +324,7 @@ "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", + "Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên", ", rating {} of 5": ", xếp hạng: {} trên 5" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 104eb0cf7d..bd5c8bc112 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -1297,7 +1297,7 @@ "Photo Grid (G)": "Lưới ảnh (G)", "Photo Merge": "Ghép ảnh", "Photo menu. The filmstrip has the photo context menu too. Adding a file again that is in Recently Deleted no": "Menu Ảnh. Dải phim cũng có menu ngữ cảnh ảnh. Thêm lại tệp đang ở Đã xóa gần đây không", - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Ảnh → Chỉnh trong → Chỉnh trong PhotoCraft (⇧⌘E, hoặc nhấp phải ảnh) kết xuất bản sao kèm chỉnh sửa, xếp chồng với bản gốc và mở trong PhotoCraft. Lưu ở đó thì bản sao cập nhật tại đây. Dạng PSD, PhotoCraft lưu thẳng lại. Để trống vị trí trừ khi dùng bản portable.", "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "Ảnh → Chỉnh trong trình soạn ngoài (⇧⌘E) kết xuất bản sao TIFF 16 bit, xếp chồng với bản gốc và mở tại đây (tên app trên macOS, đường dẫn chương trình ở nơi khác).", "PhotoCraft": "PhotoCraft", "Photos": "Ảnh", @@ -1496,7 +1496,7 @@ "Remove location info": "Xóa thông tin vị trí", "Remove missing photos from the library": "Gỡ ảnh mất khỏi thư viện", "Remove shortcut": "Gỡ lối tắt", - "Remove this face box (undo with Edit ▸ Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", + "Remove this face box (undo with Edit → Undo)": "Gỡ khung khuôn mặt này (hoàn tác bằng Chỉnh sửa → Hoàn tác)", "Remove this filter": "Gỡ bộ lọc này", "Remove this group": "Gỡ nhóm này", "Remove this rule": "Gỡ quy tắc này", @@ -1555,7 +1555,7 @@ "Revert": "Hoàn tác", "Review": "Xem lại", "Review Import": "Xem lại nhập", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "Nhấp phải ảnh → Đặt làm ảnh tham chiếu, rồi Xem → Chế độ tham chiếu (Shift+R)", "Right-click a preset to delete it": "Nhấp phải thiết lập sẵn để xóa", "Rights Usage Terms": "Điều khoản sử dụng quyền", "Rotate": "Xoay", @@ -2741,12 +2741,19 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", + "User Templates": "Mẫu người dùng", + "Delete Folder": "Xóa thư mục", + "Folder name": "Tên thư mục", + "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng.", "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", "Reduce Motion": "Giảm chuyển động", "Reduce motion": "Giảm chuyển động", "Turns off zoom and spinner animations. Fades stay.": "Tắt hiệu ứng phóng to và biểu tượng xoay. Hiệu ứng mờ dần vẫn được giữ nguyên.", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Tắt hiệu ứng phóng to và biểu tượng xoay. Hiệu ứng mờ dần vẫn được giữ nguyên. Theo cài đặt Giảm chuyển động của hệ thống cho đến khi bạn thay đổi tại đây.", "Use the system setting": "Dùng cài đặt của hệ thống", + "Drag to move, or use the arrow keys": "Kéo để di chuyển, hoặc dùng phím mũi tên", + "A group can't go inside itself": "Nhóm không thể nằm trong chính nó", + "Groups can't nest any deeper": "Không thể lồng nhóm sâu hơn", "Right-click ▸ Locate Missing File… to find it again.": "Nhấp chuột phải → Định vị tệp bị thiếu… để tìm lại.", "Right-click ▸ Reload from Disk to try again.": "Nhấp chuột phải → Tải lại từ đĩa để thử lại.", "Stack — click to collapse (S)": "Chồng — nhấp để thu gọn (S)", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 1302c9b2f5..360f2f43f9 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -125,7 +125,7 @@ "Adding photos… {} of {}": "正在添加照片… 第 {0} 张,共 {1} 张", " ({} in Recently Deleted)": "(其中 {0} 张在“最近删除”中)", "Already in the library: {} photo{} selected in All Photos": "已在图库中:已在“所有照片”中选择 {0} 张照片{1:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在图库的“最近删除”中:已选择 {0} 张照片{1:.0} · 右键单击 → 恢复,或永久删除后重新导入", "Auto ({})": "自动({})", "Build 1:1 Previews ({scope})": "生成 1:1 预览({scope})", "Build Smart Previews ({scope})": "生成智能预览({scope})", @@ -176,7 +176,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的引导 Upright 变换。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 几何信息;不支持保存的 Upright 变换。", "XMP adjustments were not imported for {path}: {fields}.": "未导入 {path} 的 XMP 调整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已导入 {profiles} 个配置文件{0:.0}(配置文件浏览器 → 各自的分组)", "Insert at the cursor (also written {})": "在光标处插入(也可写作 {0})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字体:{0}(OFL)。图标:原创。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在应用“{k}”:单击照片以添加或移除 · 按 Esc 停止", @@ -206,7 +206,7 @@ "{} — show their photos": "{0} — 显示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 暂时无法解码这种 RAW 变体({0})。你正在编辑相机内嵌的 JPEG 预览,其中已包含相机的照片风格(如单色)和白平衡。", "Filtered: {label}": "已筛选:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 张相似照片{0:.0} · 选择“视图 → 清除过滤器”可查看全部", "Moved; {} photo(s) relinked": "已移动;已重新链接 {0} 张照片", "{} label (click more labels to show any of them)": "{0}标签(单击更多标签可显示符合其中任一标签的照片)", ", {} label": ",{0}标签", @@ -254,7 +254,7 @@ "Create the keyword “{name}”": "创建关键字“{name}”", "new, inside {parent}": "新关键字,位于 {parent} 内", "Keywords of {n} selected photos": "所选 {n} 张照片的关键字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已从 {n} 张照片中移除“{name}”。编辑 → 撤销可恢复。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 个任务在运行:{names}。退出将停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 个任务在运行:{names}。退出将停止它们。", "{what} merge cancelled": "已取消 {what} 合并", @@ -275,7 +275,7 @@ "Delete {n} effect preset{}? This can't be undone.": "删除 {n} 个效果预设?{:.0}此操作无法撤销。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已导出 {} 个效果预设{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已导入 {e} 个蒙版效果{:.0}(蒙版 → 效果)", "Update “{name}” with Current Settings": "用当前设置更新“{name}”", "{n} preset{}": "{n} 个预设{:.0}", "{name} opened in the other editor": "已在其他编辑器中打开 {name}", @@ -292,6 +292,7 @@ "Exported to {path}": "已导出到 {path}", "Saved template {name}": "已保存模板 {name}", "Imported {name}": "已导入 {name}", + "Moved {name} to {folder}": "已将 {name} 移到 {folder}", "Skipped {problem}": "已跳过:{problem}", "…and {more} more": "…还有 {more} 个", "Template preview: {name}": "模板预览:{name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", + "Rule {n} of {m}: {what}. Move with the arrow keys": "规则 {n}/{m}:{what}。用方向键移动", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "组 {n}/{m}:匹配{mode},内含 {count} 项。用方向键移动", ", rating {} of 5": ",评分:{}/5" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 4589570b7a..9a117ea928 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -669,7 +669,7 @@ "Remove a filter above, or choose Clear all": "请移除上方的某个筛选条件,或选择“全部清除”", "Remove from Target Album": "从目标相册中移除", "Remove shortcut": "移除快捷键", - "Remove this face box (undo with Edit ▸ Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", + "Remove this face box (undo with Edit → Undo)": "移除此人脸框(可通过“编辑 → 撤销”恢复)", "Rename Component": "重命名组件", "Reorder Masks": "重新排序蒙版", "Reset All": "全部重置", @@ -1096,7 +1096,6 @@ "Photo Grid": "照片网格", "Photo Grid (G)": "照片网格(G)", "Photo Merge": "照片合并", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "“照片 » 在外部编辑器中编辑”(⇧⌘E)会渲染一份 16 位 TIFF 副本,与原图堆叠并在此打开(macOS 上填应用名称,其他平台填程序路径)。", "Photos": "照片", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "仅在“本地”中查看过、从未添加或更改的照片,若其文件夹在此时长内未被浏览,将移出目录(打开图库时检查)。文件保留在磁盘上;浏览该文件夹即可再次显示。", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "进入此文件夹的照片(联机拍摄、扫描仪、同步应用)在传输完成后即被添加。", @@ -1251,7 +1250,7 @@ "Revert": "恢复", "Review": "审阅", "Review Import": "查看导入内容", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "右键单击照片 » 设为参考照片,然后选择“视图 → 参考视图”(Shift+R)", "Right-click a preset to delete it": "右键单击预设即可将其删除", "Rights Usage Terms": "使用条款", "Rotate": "旋转", @@ -2162,7 +2161,7 @@ "Tidying the thumbnail cache": "正在整理缩略图缓存", "Checking free disk space": "正在检查可用磁盘空间", "Reset all edits (Cmd+Shift+R)": "重置所有编辑 (Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智能相册会自动更新:请更改其规则,或使用“照片 → 删除照片”", "LightCraft stopped": "LightCraft 已停止", "Zoom to Focus Point": "缩放至对焦点", "Focus": "对焦", @@ -2436,6 +2435,10 @@ "Top bar": "顶部栏", "Tool strip": "工具栏", "Bottom bar": "底部栏", + "User Templates": "用户模板", + "Delete Folder": "删除文件夹", + "Folder name": "文件夹名称", + "Its templates move to User Templates.": "其中的模板将移到“用户模板”。", "Welcome to LightCraft": "欢迎使用 LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "一款快速、非破坏性的照片库和 RAW 显影工具:原片保持不变,每次编辑都可以随时查看或还原。", "Bring photos in with File › Import Photos…": "通过 文件 › 导入照片…导入照片。", @@ -2463,6 +2466,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "关闭缩放和旋转指示器的动画。淡入淡出效果保留。在你于此处更改之前,跟随系统的“减弱动态效果”设置。", "Use the system setting": "使用系统设置", "Turns off zoom and spinner animations. Fades stay.": "关闭缩放和旋转指示器的动画。淡入淡出效果保留。", + "Drag to move, or use the arrow keys": "拖动以移动,或使用方向键", + "A group can't go inside itself": "组不能放入它自己里面", + "Groups can't nest any deeper": "组不能再嵌套得更深", "Stack — click to expand (S)": "堆叠 — 单击展开 (S)", "Stack — click to collapse (S)": "堆叠 — 单击折叠 (S)", "Virtual copy": "虚拟副本", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 59b6e3bfe6..1b550e4c07 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -147,7 +147,7 @@ "… and {more} more": "…以及另外 {more} 個", " ({} in Recently Deleted)": "(其中 {} 張在「最近刪除」中)", "Already in the library: {} photo{} selected in All Photos": "已在照片庫中:已在「所有照片」中選取 {} 張照片{:.0}", - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh": "已在照片庫的「最近刪除」中:已選取 {} 張照片{:.0} · 按右鍵 → 還原,或永久刪除後重新匯入", "Remove “{name}” and its {count} photo{} from the library?": "要將「{name}」及其 {count} 張照片從照片庫移除嗎?{:.0}", " ({unsure} with several look-alike files: use Locate)": "(其中 {unsure} 張有多個相似檔案:請使用「尋找」)", " · {:.0}% clipped": " · {:.0}% 剪裁", @@ -176,7 +176,7 @@ "Lightroom geometry for {path} was not preserved; Guided Upright saved transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的引導 Upright 轉換。", "Lightroom geometry for {path} was not preserved; saved Upright transform is unsupported.": "未保留 {path} 的 Lightroom 幾何資料;不支援儲存的 Upright 轉換。", "XMP adjustments were not imported for {path}: {fields}.": "未匯入 {path} 的 XMP 調整:{fields}。", - "Imported {profiles} profile{} (Profile browser ▸ their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", + "Imported {profiles} profile{} (Profile browser → their groups)": "已匯入 {profiles} 個描述檔{:.0}(描述檔瀏覽器 → 各自的群組)", "Insert at the cursor (also written {})": "在游標處插入(也可寫成 {})", "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.": "MIT OR Apache-2.0。字型:{}(OFL)。圖示:原創。", "Painting “{k}”: click photos to add or remove it · Esc stops": "正在套用「{k}」:點擊照片即可加入或移除 · 按 Esc 停止", @@ -206,7 +206,7 @@ "{} — show their photos": "{} — 顯示其照片", "LightCraft can't decode this raw variant yet ({}). You're editing the camera's embedded JPEG preview, which already includes the camera's picture style (e.g. Monochrome) and white balance.": "LightCraft 目前還無法解碼這種 RAW 變體({})。你正在編輯相機內嵌的 JPEG 預覽,其中已包含相機的相片風格(例如單色)與白平衡。", "Filtered: {label}": "已篩選:{label}", - "{n} similar photo{} · View ▸ Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", + "{n} similar photo{} · View → Clear Filters to see all": "{n} 張相似照片{:.0} · 選擇「檢視 → 清除篩選條件」可查看全部", "Moved; {} photo(s) relinked": "已移動;已重新連結 {} 張照片", "{} label (click more labels to show any of them)": "{}標籤(點擊更多標籤可顯示符合其中任一標籤的照片)", ", {} label": ",{}標籤", @@ -254,7 +254,7 @@ "Create the keyword “{name}”": "建立關鍵字「{name}」", "new, inside {parent}": "新關鍵字,位於 {parent} 內", "Keywords of {n} selected photos": "選取的 {n} 張照片的關鍵字", - "Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", + "Removed “{name}” from {n} photos. Edit → Undo puts it back.": "已從 {n} 張照片移除「{name}」。編輯 → 復原可恢復。", "1 task is still running: {names}. Quitting stops it.": "仍有 1 個工作在執行:{names}。結束將停止它。", "{n} tasks are still running: {names}. Quitting stops them.": "仍有 {n} 個工作在執行:{names}。結束將停止它們。", "{what} merge cancelled": "已取消{what}合併", @@ -275,7 +275,7 @@ "Delete {n} effect preset{}? This can't be undone.": "刪除 {n} 個效果預設集?{:.0}此動作無法復原。", "Effect: {name}": "效果:{name}", "Exported {} effect preset{}": "已匯出 {} 個效果預設集{:.0}", - "Imported {e} mask effect{} (Masking ▸ Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", + "Imported {e} mask effect{} (Masking → Effect)": "已匯入 {e} 個遮色片效果{:.0}(遮色片 → 效果)", "Update “{name}” with Current Settings": "以目前設定更新「{name}」", "{n} preset{}": "{n} 個預設集{:.0}", "{name} opened in the other editor": "已在其他編輯器中開啟 {name}", @@ -292,6 +292,7 @@ "Exported to {path}": "已匯出到 {path}", "Saved template {name}": "已儲存範本 {name}", "Imported {name}": "已匯入 {name}", + "Moved {name} to {folder}": "已將 {name} 移至 {folder}", "Skipped {problem}": "已略過:{problem}", "…and {more} more": "…還有 {more} 個", "Template preview: {name}": "範本預覽:{name}", @@ -327,5 +328,7 @@ "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", + "Rule {n} of {m}: {what}. Move with the arrow keys": "規則 {n}/{m}:{what}。用方向鍵移動", + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "群組 {n}/{m}:符合{mode},內含 {count} 項。用方向鍵移動", ", rating {} of 5": ",評分:{}/5" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 88ba1a0756..3a6a783e9b 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -670,7 +670,7 @@ "Remove a filter above, or choose Clear all": "請移除上方的某個篩選條件,或選擇「全部清除」", "Remove from Target Album": "從目標相簿移除", "Remove shortcut": "移除快速鍵", - "Remove this face box (undo with Edit ▸ Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", + "Remove this face box (undo with Edit → Undo)": "移除此臉部框(可用「編輯 → 復原」還原)", "Rename Component": "重新命名元件", "Reorder Masks": "重新排序遮色片", "Reset All": "全部重設", @@ -1097,7 +1097,6 @@ "Photo Grid": "照片格狀檢視", "Photo Grid (G)": "照片格狀檢視(G)", "Photo Merge": "照片合併", - "Photo ▸ Edit in External Editor (⇧⌘E) renders a 16-bit TIFF copy, stacks it with the original and opens it here (an app name on macOS, a program path elsewhere).": "「照片 → 在外部編輯器中編輯」(⇧⌘E)會算繪 16 位元 TIFF 副本,與原始照片堆疊後在此開啟(macOS 填應用程式名稱,其他平台填程式路徑)。", "Photos": "照片", "Photos seen in Local but never added or changed leave the catalog when their folder hasn't been browsed for this long (checked when the library opens). Files stay on disk; browsing the folder shows them again.": "曾在本機瀏覽、但未加入或變更的照片,在其資料夾超過此期間未瀏覽時會移出目錄(開啟照片庫時檢驗)。檔案仍保留在磁碟上,再次瀏覽資料夾即可重新顯示。", "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "此資料夾中新出現的照片(連線拍攝、掃描器或同步程式)會在檔案完整後立即加入。", @@ -1252,7 +1251,7 @@ "Revert": "回復至上次儲存", "Review": "審閱", "Review Import": "檢視匯入", - "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", + "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)": "在照片上按右鍵 → 設為參考照片,再選擇「檢視 → 參考檢視」(Shift+R)", "Right-click a preset to delete it": "在預設集上按右鍵即可刪除", "Rights Usage Terms": "使用權利條款", "Rotate": "旋轉", @@ -2131,7 +2130,7 @@ "Tidying the thumbnail cache": "正在整理縮圖快取", "Checking free disk space": "正在檢查可用磁碟空間", "Reset all edits (Cmd+Shift+R)": "重設所有編輯(Cmd+Shift+R)", - "Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", + "Smart albums update automatically: change their rules, or use Photo → Delete Photo": "智慧型相簿會自動更新:請變更其規則,或使用「照片 → 刪除照片」", "LightCraft stopped": "LightCraft 已停止", "Focus Point": "對焦點", "Zoom to Focus Point": "縮放至對焦點", @@ -2437,6 +2436,10 @@ "Tool strip": "工具列", "Bottom bar": "底部列", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "User Templates": "使用者範本", + "Delete Folder": "刪除資料夾", + "Folder name": "資料夾名稱", + "Its templates move to User Templates.": "其中的範本會移到「使用者範本」。", "Welcome to LightCraft": "歡迎使用 LightCraft", "A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "快速且非破壞性的照片庫與 RAW 顯影工具:原始檔保持不變,每次編輯都能隨時檢視或還原。", "Bring photos in with File › Import Photos…": "透過 檔案 › 匯入照片…匯入照片。", @@ -2464,6 +2467,9 @@ "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "關閉縮放與旋轉指示器的動畫。淡入淡出效果保留。在你於此處更改之前,跟隨系統的「減少動態效果」設定。", "Use the system setting": "使用系統設定", "Turns off zoom and spinner animations. Fades stay.": "關閉縮放與旋轉指示器的動畫。淡入淡出效果保留。", + "Drag to move, or use the arrow keys": "拖曳以移動,或使用方向鍵", + "A group can't go inside itself": "群組不能放進它自己裡面", + "Groups can't nest any deeper": "群組不能再巢狀得更深", "Stack — click to expand (S)": "堆疊 — 按一下以展開 (S)", "Stack — click to collapse (S)": "堆疊 — 按一下以收合 (S)", "Virtual copy": "虛擬副本", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 884311948c..5845b2a0be 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -115,6 +115,7 @@ impl LightcraftApp { scan: None, scans_stopping: Default::default(), waiting_import: Default::default(), + review_listed: None, sync: None, sync_owns_changes: false, sync_run: None, @@ -122,6 +123,7 @@ impl LightcraftApp { lightroom_last: None, lightroom_result: None, review_pending: None, + review_pending_listed: None, shown_library: None, export: None, tasks: Default::default(), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b2..6d67ceb1e7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -466,6 +466,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest "ui.dialog.cancel" => { if matches!(app.ui.dialog, Some(crate::state::Dialog::Import { .. })) { app.renderer.forget_imports(); + app.review_listed = None; } app.ui.dialog = None; ok(Value::Null) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 49a73997f7..e762ba7371 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -52,6 +52,14 @@ pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", " /// Help ▸ What's New (docs/whats-new.md). pub const WHATS_NEW: &str = include_str!("../../../docs/whats-new.md"); +/// A line of What's New as the dialog shows it, in the UI language. The notes are written like the +/// docs, with symbols Inter lacks (issue #1950): ▸ between menu items shows as → (as in the +/// translations), the activity stack's ✕ as ×, and the sidebar's full-width +, which only the CJK +/// faces have, as +. +pub(crate) fn whats_new_line(source: &str) -> String { + crate::i18n::tr(source).replace('`', "").replace('▸', "→").replace('✕', "×").replace('+', "+") +} + /// The tour's window title and the labels of its next and last-page buttons: translated in every /// catalog, with the pages' text (the test that pins it reads these). pub(crate) const WELCOME_TITLE: &str = "Welcome"; @@ -389,8 +397,10 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { let frame = ctx.cumulative_frame_nr(); ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame)); } + // a review closed without importing (Cancel, Esc) leaves no listing behind (OK took it already) if close && matches!(dlg, Dialog::Import { .. }) { app.renderer.forget_imports(); + app.review_listed = None; } app.ui.dialog = if close { None } else { Some(dlg) }; } @@ -842,7 +852,7 @@ fn auto_stack_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: /// The body of the Cull dialog. fn cull_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { - let Dialog::Cull { reject_below, pick_best, burst_gap, similarity } = dlg else { return }; + let Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } = dlg else { return }; let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) @@ -869,6 +879,8 @@ fn cull_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut D ); let r = ui.checkbox(pick_best, crate::i18n::tr("Pick the sharpest photo of each burst")); crate::widgets::register(ui, "check:cullPick", r.rect); + let r = ui.checkbox(stack_groups, crate::i18n::tr("Stack each burst, best photo on top")); + crate::widgets::register(ui, "check:cullStack", r.rect); ui.add_space(6.0); // the sliders drag over the usual range; their value fields take whatever // `photo.analyze` accepts (a gap of 0 s to a day, a similarity of 0 to 1) @@ -908,15 +920,15 @@ fn whats_new_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { let l = line.trim_end(); if let Some(h) = l.strip_prefix("### ") { ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(whats_new_line(h)).font(t.semibold(12.5)).color(t.text)); } else if let Some(h) = l.strip_prefix("## ") { ui.add_space(8.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); + ui.label(egui::RichText::new(whats_new_line(h)).font(t.semibold(14.0)).color(t.text)); } else if l.starts_with("# ") || l.is_empty() { } else if let Some(b) = l.strip_prefix("- ") { - ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label)); + ui.label(egui::RichText::new(format!("• {}", whats_new_line(b))).color(t.text_label)); } else { - ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label)); + ui.label(egui::RichText::new(whats_new_line(l.trim())).color(t.text_label)); } } }); @@ -1007,7 +1019,7 @@ fn all_metadata_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { /// The body of the SmartRules dialog. fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { - let Dialog::SmartRules { id, name, rules, .. } = dlg else { return }; + let Dialog::SmartRules { id, name, rules, instance, .. } = dlg else { return }; let r = crate::widgets::named( ui.add(egui::TextEdit::singleline(name).hint_text(crate::i18n::tr("Name")).desired_width(f32::INFINITY)), crate::i18n::tr("Name"), @@ -1022,6 +1034,8 @@ fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: let now = (app.session.clock)(); let view = app.caches.rules_view(&app.session.catalog, rules, *id, folder, &now); let env = crate::panels::rules_editor::Env { problems: view.problems.clone(), today: now, albums: view.albums.clone() }; + // a drag that began in another dialog is not this one's, whatever its rules say + crate::panels::rules_reorder::bind(ui.ctx(), *instance); egui::ScrollArea::vertical().max_height(list_height(ui, 360.0)).auto_shrink([false, true]).show(ui, |ui| { crate::panels::rules_editor::edit(ui, rules, "rules", 0, &[], &env); }); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index b0d816d25c..20adb92620 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -178,11 +178,14 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew | Dialog::Welcome { .. } => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); - app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity)) + app.ui.cull_stack = *stack_groups; + let mut p = cull_params(*reject_below, *pick_best, *burst_gap, *similarity); + p["stackGroups"] = json!(stack_groups); + app.run("photo.analyze", p) } - Dialog::SmartRules { id, name, rules, parent } => { + Dialog::SmartRules { id, name, rules, parent, .. } => { // refused before anything changes (not even the name) if let Some(problem) = rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).first() { return Err(problem.to_string()); diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index f4d22079a4..9902262856 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -239,12 +239,15 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option) -> let candidates = queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect(); // the probes of earlier scans go back to the session with the result, for the import that follows + // (a browse imports nothing from a review, so no folder listing goes with it) + let listed = lightcraft_engine::import::ListedFolders::default(); let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput { candidates, probes: input.take_probes(), truncated: false, unreadable: 0, unsupported: 0, + listed, })); }; #[cfg(not(target_arch = "wasm32"))] @@ -393,6 +396,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; d.library = Some(app.session.library_generation()); + app.review_pending_listed = Some(out.listed); app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) }); show_pending_review(app, ctx); } @@ -408,10 +412,12 @@ fn show_pending_review(app: &mut LightcraftApp, ctx: &egui::Context) { && !opts.in_library(app) { app.review_pending = None; + app.review_pending_listed = None; return; } if app.ui.dialog.is_none() { app.ui.dialog = app.review_pending.take(); + app.review_listed = app.review_pending_listed.take(); } else { ctx.request_repaint_after(std::time::Duration::from_millis(100)); } diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index b2a8af6652..18179685f3 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -17,6 +17,8 @@ pub struct ImportTask { pub total: usize, pub done: usize, pub(super) params: Value, + /// What the review that started this import listed, for its job. + listed: Option, pub imported: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, @@ -261,7 +263,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result } } let total = queue.len(); - app.import = Some(ImportTask::new(queue, params, undo0, false)); + let mut task = ImportTask::new(queue, params, undo0, false); + task.listed = app.review_listed.take(); + app.import = Some(task); app.renderer.forget_imports(); Ok(json!({"importing": total})) } @@ -287,6 +291,16 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { p["paths"] = json!(task.queue); let started = lightcraft_engine::cmd::library::import_params(&app.session, &p) .and_then(|req| Ok((lightcraft_engine::import::ImportJob::new(&mut app.session, req.opts)?, req.album, req.album_name))) + .map(|(job, album, name)| { + ( + match task.listed.take() { + Some(l) => job.with_listed(l), + None => job, + }, + album, + name, + ) + }) .map_err(|e| e.to_string()) .and_then(|(job, album, name)| ImportRun::start(job, std::mem::take(&mut task.queue), album, name, ctx)); if task.auto { @@ -554,7 +568,7 @@ fn show_existing(app: &mut LightcraftApp, ctx: &egui::Context, existing: &[u64]) crate::i18n::tr_format!("Already in the library: {} photo{} selected in All Photos", n, plural) } else { crate::i18n::tr_format!( - "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh", + "Already in the library, in Recently Deleted: {} photo{} selected · right-click → Restore, or Delete Permanently to import afresh", n, plural ) diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index fda115e6c1..2675964032 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -10,7 +10,7 @@ use lightcraft_catalog::PhotoId; use lightcraft_engine::export::ExportOptions; use lightcraft_engine::print::compose::{self, place}; use lightcraft_engine::print::layout::{self, Snap, Style, Unit}; -use lightcraft_engine::print::template::PrintSettings; +use lightcraft_engine::print::template::{DEFAULT_FOLDER, PrintSettings}; use lightcraft_engine::print_color::{ManagedSpace, PrintColorSettings, PrintIntent, PrintMedia, PrintProfile, PrintSharpen}; use serde_json::{Value, json}; @@ -49,10 +49,30 @@ pub struct PrintUi { drag: Option, /// The name typed for Save Template. pub template_name: String, + /// The folder Save and Import… put a template in; `None`: User Templates. + pub save_folder: Option, + /// Whether a folder was picked in the Folder selector or made with New Folder…. Until then Save + /// over an existing name leaves that template in its folder. + pub save_folder_chosen: bool, + /// A folder name being typed in the Template Browser. + pub folder_edit: Option, + /// The folder whose Delete Folder waits for a confirmation. + pub delete_folder: Option, + /// Template Browser folders shown closed, by [`folder_key`]. + pub closed_folders: Vec, + /// The template being dragged onto a folder. + pub dragging_template: Option, /// Size of the next cell added, inches. pub new_cell: Option<(f64, f64)>, } +/// New Folder… (`from: None`) or Rename Folder… of the folder `from`, with the name typed so far. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FolderEdit { + pub from: Option, + pub name: String, +} + fn run(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Option { match app.run(id, params) { Ok(v) => Some(v), @@ -196,31 +216,264 @@ pub fn body(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens) { app.ui.print = pu; } -/// The print templates: save the settings as one, import, and the saved ones to apply, export and delete. +/// The folder a command names for `folder` (`None`: User Templates). +fn folder_param(folder: Option<&str>) -> &str { + folder.unwrap_or(DEFAULT_FOLDER) +} + +/// The key a folder's open or closed state is kept under: its name in ASCII lowercase, the case the +/// engine ignores when it keeps folder names unique. +fn folder_key(folder: &str) -> String { + folder.to_ascii_lowercase() +} + +/// How the Template Browser names `folder`: User Templates in the interface's language, a folder +/// of the user's as it was typed. +fn folder_label(folder: Option<&str>) -> String { + folder.map_or_else(|| crate::i18n::tr("User Templates").to_string(), str::to_string) +} + +/// The folder the Folder selector shows, where Save puts the template: the one picked, or until a +/// folder is picked, the folder of the saved template with the typed name (any ASCII case). +fn shown_save_folder(app: &LightcraftApp, pu: &PrintUi) -> Option { + if pu.save_folder_chosen { + return pu.save_folder.clone(); + } + let name = pu.template_name.trim(); + app.session.print_templates.iter().find(|x| x.name.eq_ignore_ascii_case(name)).map_or_else(|| pu.save_folder.clone(), |x| x.folder.clone()) +} + +/// The print templates: save the settings as one into a folder, import, and the Template Browser: +/// its folders (New Folder…, Rename Folder…, Delete Folder) and in each the saved templates to +/// apply, export, delete, and drag onto another folder or move there from their menu. fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi) { let ctx = ui.ctx().clone(); heading(ui, t, "Templates"); + // a folder deleted or renamed by a command is no longer the one Save uses + if pu.save_folder.as_ref().is_some_and(|f| !app.session.print_template_folders.contains(f)) { + pu.save_folder = None; + pu.save_folder_chosen = false; + } ui.horizontal(|ui| { crate::text_field::TextField::singleline("field:printTemplateName", &mut pu.template_name) .hint(crate::i18n::tr("Template name")) .width(140.0) .show(ui); + let folder = folder_param(shown_save_folder(app, pu).as_deref()).to_string(); if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() { - run(app, &ctx, "print.template.save", json!({"name": pu.template_name})); + let mut params = json!({"name": pu.template_name}); + if pu.save_folder_chosen { + params["folder"] = json!(folder); + } + run(app, &ctx, "print.template.save", params); } if app.services.pick_print_templates.is_some() && text_button(ui, "printTemplateImport", "Import…", false).clicked() { let paths = app.services.pick_print_templates.as_mut().map(|pick| pick()).unwrap_or_default(); for path in paths { - if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path})) { + if let Some(r) = run(app, &ctx, "print.template.import", json!({"path": path, "folder": folder})) { app.toast(&ctx, crate::i18n::tr_format!("Imported {name}", name = r["name"].as_str().unwrap_or_default())); } } } }); - let names: Vec = app.session.print_templates.iter().map(|t| t.name.clone()).collect(); - for (i, name) in names.iter().enumerate() { + let folders: Vec> = std::iter::once(None).chain(app.session.print_template_folders.iter().cloned().map(Some)).collect(); + let shown = shown_save_folder(app, pu); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(crate::i18n::tr("Folder")).color(t.text_label)); + let c = craft_ui::ComboBox::from_id_salt("printSaveFolder").width(120.0).selected_text(folder_label(shown.as_deref())).show_ui(ui, |ui| { + for (j, f) in folders.iter().enumerate() { + let r = ui.selectable_label(shown == *f, folder_label(f.as_deref())); + register(ui, format!("item:printSaveFolder-{j}"), r.rect); + if r.clicked() { + pu.save_folder.clone_from(f); + pu.save_folder_chosen = true; + } + } + }); + crate::widgets::name_combo(&c.response, crate::i18n::tr("Folder")); + register(ui, "combo:printSaveFolder", c.response.rect); + if text_button(ui, "printTemplateNewFolder", "New Folder…", false).clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + }); + folder_editor(app, ui, &ctx, pu); + folder_delete_confirmation(app, ui, t, &ctx, pu); + for (j, folder) in folders.iter().enumerate() { + folder_rows(app, ui, t, pu, j, folder.as_deref(), &folders); + } + template_drag_feedback(&ctx, t, pu); +} + +/// The New Folder… / Rename Folder… field under the Save row, while one is open: Return or its +/// button runs the command, Esc or Cancel closes it. A refused name keeps it open, with the reason +/// in a toast. +fn folder_editor(app: &mut LightcraftApp, ui: &mut Ui, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(mut edit) = pu.folder_edit.take() else { return }; + let (mut confirm, mut cancel) = (false, false); + ui.horizontal(|ui| { + let r = crate::text_field::TextField::singleline("field:printFolderName", &mut edit.name) + .hint(crate::i18n::tr("Folder name")) + .width(140.0) + .select_on_focus(true) + .show(ui); + if super::frame::just_opened(ui, "printFolderName") { + r.response.request_focus(); + } + match r.ending { + Some(crate::text_field::Ending::Return) => confirm = true, + Some(crate::text_field::Ending::Escape) => cancel = true, + _ => {} + } + confirm |= text_button(ui, "printFolderOk", if edit.from.is_some() { "Rename" } else { "Create" }, false).clicked(); + cancel |= text_button(ui, "printFolderCancel", "Cancel", false).clicked(); + }); + if cancel { + return; + } + if confirm { + let (id, params) = match &edit.from { + None => ("print.template.folder.create", json!({"name": edit.name})), + Some(from) => ("print.template.folder.rename", json!({"name": from, "to": edit.name})), + }; + if let Some(r) = run(app, ctx, id, params) { + let made = r["name"].as_str().map(str::to_string); + // a new folder is where the next Save goes; a renamed one keeps its place there and its closed state + if edit.from.is_none() || pu.save_folder == edit.from { + pu.save_folder.clone_from(&made); + } + if edit.from.is_none() { + pu.save_folder_chosen = true; + } + if let (Some(from), Some(to)) = (&edit.from, &made) { + for c in &mut pu.closed_folders { + if *c == folder_key(from) { + *c = folder_key(to); + } + } + } + return; + } + } + pu.folder_edit = Some(edit); +} + +/// Delete Folder's question, while it is asked: the folder's templates move to User Templates. +fn folder_delete_confirmation(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context, pu: &mut PrintUi) { + let Some(name) = pu.delete_folder.clone() else { return }; + let question = + format!("{} {}", crate::i18n::tr_format!("Delete “{name}”?", name = name), crate::i18n::tr("Its templates move to User Templates.")); + ui.label(egui::RichText::new(question).color(t.text_label)); + ui.horizontal(|ui| { + if text_button(ui, "printFolderDeleteConfirm", "Delete Folder", false).clicked() + && run(app, ctx, "print.template.folder.delete", json!({"name": name})).is_some() + { + pu.delete_folder = None; + pu.closed_folders.retain(|c| *c != folder_key(&name)); + } + if text_button(ui, "printFolderDeleteCancel", "Cancel", false).clicked() { + pu.delete_folder = None; + } + }); +} + +/// Moves the template `name` to `folder` and says so; nothing when it is there already. +fn move_template(app: &mut LightcraftApp, ctx: &egui::Context, name: &str, folder: Option<&str>) { + if let Some(r) = run(app, ctx, "print.template.move", json!({"name": name, "folder": folder_param(folder)})) + && r["moved"] == true + { + app.toast(ctx, crate::i18n::tr_format!("Moved {name} to {folder}", name = name, folder = folder_label(folder))); + } +} + +/// One Template Browser folder: its row (a click opens or closes it, a template dropped on it moves +/// there, its menu has New Folder… and, for the user's folders, Rename Folder… and Delete Folder), +/// then, while it is open, its templates. +fn folder_rows(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, j: usize, folder: Option<&str>, folders: &[Option]) { + let ctx = ui.ctx().clone(); + let label = folder_label(folder); + let key = folder_key(folder_param(folder)); + let open = !pu.closed_folders.contains(&key); + let count = app.session.print_templates.iter().filter(|x| x.folder.as_deref() == folder).count(); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); + crate::widgets::announce_disclosure(&resp, true, open, &label); + register(ui, format!("printTemplateFolder-{j}"), r); + let pointer = ui.input(|i| i.pointer.latest_pos()); + let under_drag = pu.dragging_template.is_some() && crate::docking::drop_target(ui, r, pointer); + if under_drag { + ui.painter().rect_stroke(r.shrink(1.0), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, 4.0, t.hover.gamma_multiply(0.6)); + } + crate::icons::paint( + ui.painter(), + Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(14.0, 14.0)), + if open { crate::icons::Icon::ChevronDown } else { crate::icons::Icon::ChevronRight }, + t.text_label, + ); + ui.painter().text(pos2(r.left() + 20.0, r.center().y), Align2::LEFT_CENTER, &label, t.semibold(12.0), t.text); + ui.painter().text(pos2(r.right() - 4.0, r.center().y), Align2::RIGHT_CENTER, count.to_string(), t.font(11.0), t.text_dim); + if resp.clicked() { + if open { + pu.closed_folders.push(key); + } else { + pu.closed_folders.retain(|c| *c != key); + } + } + if under_drag + && ui.input(|i| i.pointer.primary_released()) + && let Some(name) = pu.dragging_template.take() + { + move_template(app, &ctx, &name, folder); + } + crate::widgets::context_menu(&resp, |ui| { + let new = ui.button(crate::i18n::tr("New Folder…")); + register(ui, format!("item:printFolderNew-{j}"), new.rect); + if new.clicked() { + pu.folder_edit = Some(FolderEdit::default()); + pu.delete_folder = None; + } + if let Some(f) = folder { + let rename = ui.button(crate::i18n::tr("Rename Folder…")); + register(ui, format!("item:printFolderRename-{j}"), rename.rect); + if rename.clicked() { + pu.folder_edit = Some(FolderEdit { from: Some(f.to_string()), name: f.to_string() }); + pu.delete_folder = None; + } + let delete = ui.button(crate::i18n::tr("Delete Folder")); + register(ui, format!("item:printFolderDelete-{j}"), delete.rect); + if delete.clicked() { + pu.delete_folder = Some(f.to_string()); + pu.folder_edit = None; + } + } + }); + if !open { + return; + } + let rows: Vec<(usize, String)> = + app.session.print_templates.iter().enumerate().filter(|(_, x)| x.folder.as_deref() == folder).map(|(i, x)| (i, x.name.clone())).collect(); + for (i, name) in &rows { + let (i, name) = (*i, name.as_str()); ui.horizontal(|ui| { - ui.label(egui::RichText::new(name).color(t.text_label)); + ui.add_space(20.0); + let resp = ui.add(egui::Label::new(egui::RichText::new(name).color(t.text_label)).sense(Sense::click_and_drag())); + register(ui, format!("printTemplate-{i}"), resp.rect); + if resp.drag_started() { + pu.dragging_template = Some(name.to_string()); + } + crate::widgets::context_menu(&resp, |ui| { + let sub = crate::widgets::menu_button(ui, crate::i18n::tr("Move to Folder"), |ui| { + for (k, f) in folders.iter().enumerate().filter(|(_, f)| f.as_deref() != folder) { + let item = ui.button(folder_label(f.as_deref())); + register(ui, format!("item:printTemplateMove-{i}-{k}"), item.rect); + if item.clicked() { + move_template(app, &ctx, name, f.as_deref()); + } + } + }); + register(ui, format!("item:printTemplateMoveMenu-{i}"), sub.response.rect); + }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, &format!("printTemplateDelete-{i}"), "Delete", false).clicked() { run(app, &ctx, "print.template.delete", json!({"name": name})); @@ -244,6 +497,28 @@ fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut } } +/// A template being dragged: its name follows the pointer, and the drag ends with the button's +/// release (after the folder rows, which take the drop) or with Esc. +fn template_drag_feedback(ctx: &egui::Context, t: &Tokens, pu: &mut PrintUi) { + let Some(name) = pu.dragging_template.clone() else { return }; + let (released, down, at, esc) = + ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); + if released || !down || esc { + pu.dragging_template = None; + return; + } + let Some(at) = at else { return }; + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + egui::Area::new(egui::Id::unique("drag-print-template")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( + ctx, + |ui| { + egui::Frame::NONE.fill(t.accent).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.label(egui::RichText::new(name).color(Color32::WHITE).font(t.semibold(12.0))); + }); + }, + ); +} + /// The image settings: zoom, rotation, border and stroke. fn image_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSettings) { let ctx = ui.ctx().clone(); @@ -1033,4 +1308,11 @@ mod tests { assert_eq!(paper_label(current_paper("はがき")), "はがき (100 × 148 mm)"); assert_eq!(paper_label(current_paper("a4")), "A4"); } + + #[test] + fn folders_that_differ_only_in_non_ascii_case_keep_their_own_open_state() { + assert_eq!(folder_key("Work"), folder_key("work")); + assert_eq!(folder_key(folder_param(None)), folder_key("user templates")); + assert_ne!(folder_key("Été"), folder_key("été")); + } } diff --git a/crates/ui-egui/src/dialogs/rules_editor.rs b/crates/ui-egui/src/dialogs/rules_editor.rs index 23677cfd70..402bd84b07 100644 --- a/crates/ui-egui/src/dialogs/rules_editor.rs +++ b/crates/ui-egui/src/dialogs/rules_editor.rs @@ -6,12 +6,15 @@ use lightcraft_catalog::rules::{FIELD_GROUPS, Kind, Problem, TOP_LEVEL_FIELDS, b use lightcraft_catalog::{Match, Rule, RuleSet}; use serde_json::{Value, json}; +use self::rules_move::MAX_GROUP_DEPTH; +use self::rules_reorder as reorder; use crate::album_picker::{AlbumEntry, AlbumPicker}; use crate::date_picker::{DatePicker, PickedDate}; use crate::theme::Tokens; use crate::widgets::register; pub mod rules_move; +pub mod rules_reorder; /// A sensible starting value for `field` / `op`. pub fn default_value(field: &str, op: &str) -> Value { @@ -305,6 +308,9 @@ fn problem_note(ui: &mut egui::Ui, problem: Option<&Problem>, salt: &str) { /// (empty at the top) so each row finds its own problem in `env`. pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: &[usize], env: &Env) { let t = Tokens::get(ui.ctx()); + if depth == 0 { + reorder::begin(ui.ctx()); + } ui.horizontal(|ui| { ui.label(RichText::new(crate::i18n::tr("Match")).color(t.text_label)); match_combo(ui, salt, &mut rs.mode); @@ -312,14 +318,26 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: }); let mut remove = None; let mut insert: Option<(usize, Rule)> = None; + let count = rs.rules.len(); for (i, rule) in rs.rules.iter_mut().enumerate() { let rsalt = format!("{salt}-{i}"); let here: Vec = path.iter().copied().chain([i]).collect(); let problem = env.problems.iter().find(|p| p.path == here); match rule { Rule::Group { group } => { - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.horizontal(|ui| { + let frame = egui::Frame::group(ui.style()).show(ui, |ui| { + ui.horizontal_top(|ui| { + let mode = group.mode; + reorder::grip( + ui, + &reorder::Row { + salt: &rsalt, + path: &here, + count, + group: Some((mode, group.rules.len())), + label: &|| reorder::group_heading(mode), + }, + ); if ui.small_button("−").on_hover_text(crate::i18n::tr("Remove this group")).clicked() { remove = Some(i); } @@ -327,9 +345,13 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: }); problem_note(ui, problem, &rsalt); }); + reorder::record(ui.ctx(), &here, frame.response.rect, true); } Rule::Field { field, op, value } => { + let (row_left, row_top) = (ui.available_rect_before_wrap(), ui.cursor().top()); ui.horizontal(|ui| { + let label = || reorder::rule_text(field, op, value, &env.albums); + reorder::grip(ui, &reorder::Row { salt: &rsalt, path: &here, count, group: None, label: &label }); field_menu(ui, &rsalt, field, op, value); let kind = field_kind(field).unwrap_or(Kind::Text); let op_label = ops_for(kind).iter().find(|o| o.0 == op.as_str()).map_or(op.as_str(), |o| o.1).to_string(); @@ -368,6 +390,8 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: } }); problem_note(ui, problem, &rsalt); + let row = egui::Rect::from_min_max(egui::pos2(row_left.left(), row_top), egui::pos2(row_left.right(), ui.min_rect().bottom())); + reorder::record(ui.ctx(), &here, row, false); } } } @@ -384,11 +408,14 @@ pub fn edit(ui: &mut egui::Ui, rs: &mut RuleSet, salt: &str, depth: usize, path: if add.clicked() { rs.rules.push(new_rule()); } - if depth < 3 && ui.small_button(crate::i18n::tr("+ Group")).clicked() { + if depth < MAX_GROUP_DEPTH && ui.small_button(crate::i18n::tr("+ Group")).clicked() { rs.rules.push(Rule::Group { group: RuleSet { mode: Match::Any, rules: vec![new_rule()] } }); } }); } + if depth == 0 { + reorder::finish(ui, rs, salt); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/rules_editor/rules_reorder.rs b/crates/ui-egui/src/dialogs/rules_editor/rules_reorder.rs new file mode 100644 index 0000000000..ef2f06343d --- /dev/null +++ b/crates/ui-egui/src/dialogs/rules_editor/rules_reorder.rs @@ -0,0 +1,560 @@ +//! Reordering in the smart-album rule editor ([`super::rules_editor`]): every rule and every group +//! has a grip at the start of its row. Dragging the grip moves the row, with a line showing where it +//! would land; Esc gives the drag up. With the keyboard, Tab reaches the grip and ↑ ↓ move the row +//! one place (out of its group at the group's ends), → moves it into the group next to it and ← +//! out of its group. Where a row sits is a path of positions from the top list (`[1, 0]`: the first +//! rule of the second rule's group); a drop is a path too: the group's path and the position among +//! its rules, counted before the row leaves its old place. +//! +//! The moves themselves are [`super::rules_move`]'s; this module draws and reads the editor's side of +//! them. + +use egui::{Color32, CursorIcon, Id, Key, Modifiers, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use lightcraft_catalog::rules::{Kind, album_rule_id, bool_label, bool_value, choice_label, field_kind, field_label, ops_for}; +use lightcraft_catalog::{Match, Rule, RuleSet}; +use serde_json::Value; + +use crate::album_picker::AlbumEntry; +use crate::icons::{Icon, paint}; +use crate::theme::Tokens; +use crate::widgets::register; + +use super::rules_move::{Dir, Refusal, Verdict, judge, key_dest, move_node}; + +/// How wide a grip is; its height is a row's. +const GRIP_W: f32 = 16.0; +/// A group frame's top and bottom strip (its padding and a little more): a pointer there is beside +/// the group, between its siblings, not inside it. +const EDGE: f32 = 8.0; +/// How far past the list's visible part a drag still counts as over it. +const REACH: f32 = 24.0; + +// ------------------------------------------------------------------ where a drag would drop + +/// Where one row of the editor was drawn this frame. +#[derive(Clone, Debug)] +pub struct RowRec { + pub path: Vec, + pub rect: Rect, + pub group: bool, +} + +/// The rows of the list at `list`, in order. +fn children<'a>(rows: &'a [RowRec], list: &[usize]) -> Vec<&'a RowRec> { + let mut kids: Vec<&RowRec> = rows.iter().filter(|r| r.path.len() == list.len() + 1 && r.path.starts_with(list)).collect(); + kids.sort_by_key(|r| r.path.last().copied().unwrap_or(0)); + kids +} + +/// The place a row dragged to height `y` would drop: in the innermost group the pointer is inside +/// of (not on its top or bottom strip: those are beside it), before the first row whose middle is +/// below the pointer, else after the last. +pub fn slot_at(rows: &[RowRec], y: f32) -> Vec { + let mut list: Vec = Vec::new(); + loop { + let kids = children(rows, &list); + if let Some(group) = kids.iter().find(|r| r.group && y > r.rect.top() + EDGE && y < r.rect.bottom() - EDGE) { + list = group.path.clone(); + continue; + } + let at = kids.iter().find(|r| y < r.rect.center().y).and_then(|r| r.path.last().copied()).unwrap_or(kids.len()); + list.push(at); + return list; + } +} + +/// The line showing a drop at `dest`: where it starts and ends along x, and its height. +fn gap_line(rows: &[RowRec], dest: &[usize]) -> Option<(f32, f32, f32)> { + let (&at, list) = dest.split_last()?; + let kids = children(rows, list); + let first = kids.first()?; + let before = kids.iter().rev().find(|r| r.path.last().is_some_and(|&i| i < at)); + let after = kids.iter().find(|r| r.path.last().is_some_and(|&i| i >= at)); + let y = match (before, after) { + (Some(b), Some(a)) => (b.rect.bottom() + a.rect.top()) / 2.0, + (None, Some(a)) => a.rect.top() - 2.0, + (Some(b), None) => b.rect.bottom() + 2.0, + (None, None) => return None, + }; + Some((first.rect.left(), first.rect.right(), y)) +} + +// ------------------------------------------------------------------ the editor's side + +#[derive(Clone, Default)] +struct Drag { + from: Vec, + /// What the dragged row says in the pill that follows the pointer. + label: String, + /// The rules when the drag was first seen: a drag whose rules were replaced (another dialog with other + /// rules; one with the same rules is told by [`bind`]) or edited meanwhile (typing in a field that kept + /// focus) is given up, its path would point into other rules; the edit stays. + base: Option, + /// No more rounding is to be expected (no other widget had the focus when the drag started, or + /// the one frame after the start has passed): the rules must be the ones the drag started with. + /// Until then `base` may take a field's rounded number. + settled: bool, +} + +/// Whether `a` and `b` are the same rules but for the numbers in their values (what a number field +/// rewrites when it gives its focus up): the same groups and match modes, the same fields and +/// operators, every other value equal. +fn same_but_numbers(a: &RuleSet, b: &RuleSet) -> bool { + a.mode == b.mode + && a.rules.len() == b.rules.len() + && a.rules.iter().zip(&b.rules).all(|pair| match pair { + (Rule::Group { group: x }, Rule::Group { group: y }) => same_but_numbers(x, y), + (Rule::Field { field: f, op: o, value: v }, Rule::Field { field: g, op: p, value: w }) => { + f == g && o == p && (matches!((last_unit(v), last_unit(w)), (Some(x), Some(y)) if x == y) || alike(v, w)) + } + _ => false, + }) +} + +/// The unit of an "in the last" value as its field reads it (`{"n": 7, "unit": "Weeks"}`, or a plain +/// number of days): the field writes `{"n", "unit"}` back in lower case whatever shape it was stored in. +fn last_unit(v: &Value) -> Option { + match v { + Value::Object(o) if o.get("n").is_some_and(|n| n.is_number() || n.is_string()) => { + Some(o.get("unit").and_then(Value::as_str).unwrap_or("days").to_lowercase()) + } + Value::Number(_) => Some("days".to_string()), + _ => None, + } +} + +/// Whether two values are equal but for numbers: a number (or a text that reads as one) stands for +/// any number, in a pair (Between) or an object (`{"n": 20, "unit": "days"}`) too. +fn alike(a: &Value, b: &Value) -> bool { + let number = |v: &Value| v.is_number() || v.as_str().is_some_and(|s| s.trim().parse::().is_ok()); + match (a, b) { + _ if number(a) && number(b) => true, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| alike(x, y)), + (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, x)| y.get(k).is_some_and(|y| alike(x, y))), + _ => a == b, + } +} + +/// What the rows record while they are drawn, for the end of the frame to act on (kept in the +/// context: the rows are drawn by nested calls). +#[derive(Clone, Default)] +struct State { + rows: Vec, + drag: Option, + /// An arrow key pressed on the grip of this row. + key_move: Option<(Vec, Dir)>, + /// The grip to bring into view (it took the focus after a move). + refocus: Option, + /// The smart album dialog ([`crate::state::Dialog::SmartRules`]'s `instance`) the state above belongs to. + instance: Option, +} + +fn with_state(ctx: &egui::Context, f: impl FnOnce(&mut State) -> R) -> R { + ctx.data_mut(|d| f(d.get_temp_mut_or_default::(Id::unique("lc-rule-reorder")))) +} + +/// The salt of the row at `path` under the editor whose top list has salt `root` (what `edit` makes +/// for each row). +fn row_salt(root: &str, path: &[usize]) -> String { + path.iter().fold(root.to_string(), |salt, i| format!("{salt}-{i}")) +} + +pub(crate) fn grip_id(salt: &str) -> Id { + Id::unique(("ruleGrip", salt)) +} + +/// Says which dialog the editor about to be drawn is in (its `instance`): a drag that began in another one, and +/// the grip a move there left to be brought into view, are given up, however alike the rules of the two are. +pub fn bind(ctx: &egui::Context, instance: u64) { + with_state(ctx, |s| { + if s.instance != Some(instance) { + s.drag = None; + s.refocus = None; + s.instance = Some(instance); + } + }); +} + +/// Starts a frame of the editor (its top list): forgets last frame's rows. +pub fn begin(ctx: &egui::Context) { + with_state(ctx, |s| { + s.rows.clear(); + s.key_move = None; + }); +} + +/// Says where the row at `path` was drawn. +pub fn record(ctx: &egui::Context, path: &[usize], rect: Rect, group: bool) { + with_state(ctx, |s| s.rows.push(RowRec { path: path.to_vec(), rect, group })); +} + +/// A rule's or group's row, as its grip needs to know it. +pub struct Row<'a> { + /// The row's salt (its widget ids; `ruleGrip:` for tests and agents). + pub salt: &'a str, + pub path: &'a [usize], + /// How many rows are in its list. + pub count: usize, + /// For a group: how it matches and how many rows it holds. + pub group: Option<(Match, usize)>, + /// What the row says (a rule in words, a group's heading), for the pill and the screen reader; + /// worked out only when needed. + pub label: &'a dyn Fn() -> String, +} + +fn match_word(m: Match) -> &'static str { + match m { + Match::All => "all", + Match::Any => "any", + Match::None => "none", + } +} + +/// A group's heading in words, as the editor shows it above the group's rules. +pub fn group_heading(m: Match) -> String { + use crate::i18n::tr; + format!("{} {} {}", tr("Match"), tr(match_word(m)), tr("of the following rules:")) +} + +/// What a screen reader says for the grip of `row`. +pub(crate) fn spoken(row: &Row) -> String { + let n = row.path.last().map_or(1, |i| i.saturating_add(1)); + match row.group { + Some((mode, inside)) => { + crate::i18n::tr_format!( + "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys", + n = n, + m = row.count, + mode = crate::i18n::tr(match_word(mode)), + count = inside + ) + } + None => crate::i18n::tr_format!("Rule {n} of {m}: {what}. Move with the arrow keys", n = n, m = row.count, what = (row.label)()), + } +} + +/// The grip at the start of a row: drag it, or Tab to it and use the arrow keys. While its row is +/// dragged the rest of the row fades (call it first in the row). +pub fn grip(ui: &mut Ui, row: &Row) { + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + let (rect, _) = ui.allocate_exact_size(vec2(GRIP_W, ui.spacing().interact_size.y), Sense::hover()); + let id = grip_id(row.salt); + let resp = ui.interact(rect, id, Sense::click_and_drag()); + register(ui, format!("ruleGrip:{}", row.salt), rect); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, spoken(row))); + let (dragging_this, dragging) = with_state(&ctx, |s| (s.drag.as_ref().is_some_and(|d| d.from == row.path), s.drag.is_some())); + if resp.drag_started_by(egui::PointerButton::Primary) { + let label = (row.label)(); + // only a widget that has the focus before the grip takes it can hand back a rounded number + let other_focus = ctx.memory(|m| m.focused()).is_some_and(|f| f != id); + with_state(&ctx, |s| s.drag = Some(Drag { from: row.path.to_vec(), label, base: None, settled: !other_focus })); + // the dragged row's grip takes the focus, so after the drop it follows the row (a focus left + // on another row's grip or field would stay at its old place, on whichever row lands there) + resp.request_focus(); + } + if with_state(&ctx, |s| s.refocus.take_if(|f| *f == id)).is_some() { + resp.scroll_to_me(None); + } + let focused = resp.has_focus(); + if focused && !dragging { + // the arrow keys are this widget's: not the focus moving to the next one + ui.memory_mut(|m| { + m.set_focus_lock_filter(id, egui::EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: true, escape: false }) + }); + let pressed = ui.input_mut(|i| { + [(Key::ArrowUp, Dir::Up), (Key::ArrowDown, Dir::Down), (Key::ArrowLeft, Dir::Out), (Key::ArrowRight, Dir::In)] + .into_iter() + .find(|(key, _)| i.consume_key(Modifiers::NONE, *key)) + .map(|(_, dir)| dir) + }); + if let Some(dir) = pressed { + // egui picked a neighbor to focus from this same key (the first one after the focus moved + // here, or a repeat in the frame after a move, before the lock above applies): cancel that + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + with_state(&ctx, |s| s.key_move = Some((row.path.to_vec(), dir))); + } + } + let color = if dragging_this { + t.accent + } else if resp.hovered() || focused { + t.text + } else { + t.text_dim + }; + paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(14.0, 14.0)), Icon::Grip, color); + if focused { + ui.painter().rect_stroke(rect, 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + } + if resp.hovered() && !dragging { + ctx.set_cursor_icon(CursorIcon::Grab); + resp.on_hover_text(crate::i18n::tr("Drag to move, or use the arrow keys")); + } + if dragging_this { + ui.multiply_opacity(0.45); + } +} + +/// The end of the editor's frame (its top list, `salt`, being `rs`): does what the grips asked for. +/// A key press moves its row; a drag shows where it would land and moves it on release. +pub fn finish(ui: &mut Ui, rs: &mut RuleSet, salt: &str) { + let ctx = ui.ctx().clone(); + let (rows, key_move, drag) = with_state(&ctx, |s| (std::mem::take(&mut s.rows), s.key_move.take(), s.drag.clone())); + if let Some((from, dir)) = key_move { + if let Some(dest) = key_dest(rs, &from, dir) + && let Some(at) = move_node(rs, &from, &dest) + { + // the row's grip is where the focus follows it; it is drawn at its new place next frame + let id = grip_id(&row_salt(salt, &at)); + ctx.memory_mut(|m| m.request_focus(id)); + with_state(&ctx, |s| s.refocus = Some(id)); + ctx.request_repaint(); + } + return; + } + let Some(mut drag) = drag else { return }; + match &drag.base { + None => { + drag.base = Some(rs.clone()); + with_state(&ctx, |s| s.drag = Some(drag.clone())); + } + // the frame after the drag starts, a number field the grip took the focus from hands back its + // clamped or rounded text: only that may differ from the rules the drag started with + Some(base) if !drag.settled && same_but_numbers(base, rs) => { + drag.base = Some(rs.clone()); + drag.settled = true; + with_state(&ctx, |s| s.drag = Some(drag.clone())); + } + Some(base) if base != rs => { + with_state(&ctx, |s| s.drag = None); + return; + } + Some(_) => {} + } + let end = |ctx: &egui::Context| with_state(ctx, |s| s.drag = None); + let (released, down, pos, esc) = + ui.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos(), i.key_pressed(Key::Escape))); + if esc { + // this Esc is the drag's, not the dialog's + crate::widgets::take_escape(&ctx); + end(&ctx); + return; + } + if !down && !released { + end(&ctx); + return; + } + let view = ui.clip_rect(); + let Some(pos) = pos else { return }; + // near the top or bottom edge the list scrolls, so rows beyond the visible part can be reached + if pos.x >= view.left() && pos.x <= view.right() { + let speed = crate::panels::left::auto_scroll_speed(pos.y, view.top(), view.bottom()); + if speed != 0.0 { + ui.scroll_with_delta_animation(vec2(0.0, -speed * ui.input(|i| i.stable_dt).min(0.1)), egui::style::ScrollAnimation::none()); + ctx.request_repaint(); + } + } + let over = view.expand(REACH).contains(pos).then(|| slot_at(&rows, pos.y)); + let verdict = over.as_ref().map(|dest| judge(rs, &drag.from, dest)); + if released { + if let (Some(dest), Some(Verdict::Moves)) = (&over, verdict) + && let Some(at) = move_node(rs, &drag.from, dest) + && ctx.memory(|m| m.has_focus(grip_id(&row_salt(salt, &drag.from)))) + { + // the grip that had the focus is drawn at the row's new place next frame: the focus follows it + let id = grip_id(&row_salt(salt, &at)); + ctx.memory_mut(|m| m.request_focus(id)); + with_state(&ctx, |s| s.refocus = Some(id)); + ctx.request_repaint(); + } + end(&ctx); + return; + } + let t = Tokens::get(&ctx); + let refused = match verdict { + Some(Verdict::Refused(why)) => Some(why), + _ => None, + }; + ctx.set_cursor_icon(if refused.is_some() { CursorIcon::NotAllowed } else { CursorIcon::Grabbing }); + if let (Some(dest), Some(Verdict::Moves | Verdict::Refused(_))) = (&over, verdict) + && let Some((x0, x1, y)) = gap_line(&rows, dest) + { + let color = if refused.is_some() { t.caution } else { t.accent }; + ui.painter().circle_stroke(pos2(x0, y), 3.0, Stroke::new(1.5, color)); + ui.painter().line_segment([pos2(x0 + 3.0, y), pos2(x1.max(x0 + 3.0), y)], Stroke::new(2.0, color)); + } + let (text, fill, ink, edge) = match refused { + Some(Refusal::IntoItself) => (crate::i18n::tr("A group can't go inside itself").to_string(), t.chrome, t.caution, t.caution), + Some(Refusal::TooDeep) => (crate::i18n::tr("Groups can't nest any deeper").to_string(), t.chrome, t.caution, t.caution), + None => (drag.label.clone(), t.accent, Color32::WHITE, t.accent), + }; + egui::Area::new(Id::unique("drag-rule")).order(egui::Order::Tooltip).interactable(false).fixed_pos(pos + vec2(14.0, 10.0)).show(&ctx, |ui| { + egui::Frame::NONE.fill(fill).stroke(Stroke::new(1.0, edge)).corner_radius(10.0).inner_margin(egui::Margin::symmetric(9, 3)).show(ui, |ui| { + ui.add(egui::Label::new(RichText::new(text).color(ink).font(t.semibold(12.0))).wrap_mode(egui::TextWrapMode::Extend)); + }); + }); +} + +// ------------------------------------------------------------------ a rule in words + +/// A number as the editor shows it: `3`, not `3.0`; a fraction as it is (`2.8`). +fn number_text(n: f64) -> String { + if n.is_finite() && n.fract() == 0.0 { format!("{n:.0}") } else { n.to_string() } +} + +/// A rule value as a person would read it. +fn value_text(field: &str, value: &Value) -> String { + use crate::i18n::tr; + match value { + Value::String(s) => choice_label(field, s).map_or_else(|| s.clone(), |l| tr(l).to_string()), + Value::Null => String::new(), + Value::Number(n) => n.as_f64().map_or_else(|| n.to_string(), number_text), + Value::Bool(b) => tr(bool_label(*b)).to_string(), + Value::Array(a) => a.iter().map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_string)).collect::>().join(" – "), + // as the editor's "in the last" row shows it: n as the catalog reads it (a number, or text), the unit + // lowercased and in the editor's words + Value::Object(o) => { + let n = o.get("n").and_then(|n| n.as_f64().or_else(|| n.as_str().and_then(|t| t.trim().parse().ok()))).unwrap_or(30.0); + let unit = o.get("unit").and_then(Value::as_str).unwrap_or("days").to_lowercase(); + format!("{} {}", number_text(n.round()), tr(&unit)) + } + } +} + +/// A field rule in words, in the language of the editor: `Rating ≥ 3`. `albums` names an Album +/// rule's album. +pub fn rule_text(field: &str, op: &str, value: &Value, albums: &[AlbumEntry]) -> String { + use crate::i18n::tr; + let kind = field_kind(field); + let name = field_label(field).map_or_else(|| field.to_string(), |l| tr(l).to_string()); + let op = kind.and_then(|k| ops_for(k).iter().find(|o| o.0 == op)).map_or_else(|| op.to_string(), |o| tr(o.1).to_string()); + let value = match kind { + Some(Kind::Album) => album_rule_id(value) + .map(|id| albums.iter().find(|a| a.id == id.0).map_or_else(|| format!("#{}", id.0), |a| a.name.clone())) + .unwrap_or_default(), + Some(Kind::Bool) => bool_value(value).map_or_else(|| value.to_string(), |b| tr(bool_label(b)).to_string()), + _ => value_text(field, value), + }; + [name, op, value].into_iter().filter(|s| !s.is_empty()).collect::>().join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// What a move leaves for the next frame (the grip to bring into view) belongs to the dialog it was made in: another + /// dialog drawn next doesn't scroll to it, while the same one still does. + #[test] + fn a_pending_refocus_is_given_up_for_another_dialog() { + let ctx = egui::Context::default(); + let grip = grip_id("rules-1"); + bind(&ctx, 1); + with_state(&ctx, |s| s.refocus = Some(grip)); + bind(&ctx, 1); + assert_eq!(with_state(&ctx, |s| s.refocus), Some(grip), "the same dialog keeps it"); + bind(&ctx, 2); + assert_eq!(with_state(&ctx, |s| s.refocus), None, "another dialog doesn't"); + } + + fn row(path: &[usize], top: f32, bottom: f32, group: bool) -> RowRec { + RowRec { path: path.to_vec(), rect: Rect::from_min_max(pos2(0.0, top), pos2(100.0, bottom)), group } + } + + /// 0: rule (0–20), 1: group (24–100) holding two rules (40–60, 64–90), 2: rule (104–124) + fn rows() -> Vec { + vec![ + row(&[0], 0.0, 20.0, false), + row(&[1, 0], 40.0, 60.0, false), + row(&[1, 1], 64.0, 90.0, false), + row(&[1], 24.0, 100.0, true), + row(&[2], 104.0, 124.0, false), + ] + } + + #[test] + fn a_drag_drops_in_the_list_under_the_pointer() { + let rows = rows(); + assert_eq!(slot_at(&rows, 5.0), [0], "above the middle of the first rule"); + assert_eq!(slot_at(&rows, 15.0), [1], "below it"); + assert_eq!(slot_at(&rows, 26.0), [1], "the group's top strip is beside the group: before it"); + assert_eq!(slot_at(&rows, 34.0), [1, 0], "its header line is inside it, before its first rule"); + assert_eq!(slot_at(&rows, 55.0), [1, 1], "in its first rule's lower half"); + assert_eq!(slot_at(&rows, 85.0), [1, 2], "in its last rule's lower half"); + assert_eq!(slot_at(&rows, 98.0), [2], "the bottom strip is beside the group: after it"); + assert_eq!(slot_at(&rows, 500.0), [3], "below everything"); + assert_eq!(slot_at(&rows, -50.0), [0], "above everything"); + } + + /// What a number field hands back when it gives up its focus (a clamped or rounded number, in + /// whatever shape the rule keeps it) is the same rule; anything else is another one. + #[test] + fn rules_differing_only_in_numbers_are_alike() { + let set = |rules: serde_json::Value| -> RuleSet { serde_json::from_value(json!({"rules": rules})).unwrap() }; + let a = set(json!([{"field": "rating", "op": "is", "value": 9}, {"field": "rating", "op": "between", "value": [2, 9]}])); + let b = set(json!([{"field": "rating", "op": "is", "value": 5}, {"field": "rating", "op": "between", "value": [2.0, 5]}])); + assert!(same_but_numbers(&a, &b), "numbers, and numbers in a pair"); + let c = set(json!([{"field": "rating", "op": "is", "value": "9"}])); + assert!(same_but_numbers(&c, &set(json!([{"field": "rating", "op": "is", "value": 5}]))), "a text that reads as a number"); + let last = |n: u64| set(json!([{"field": "captureDate", "op": "inLast", "value": {"n": n, "unit": "days"}}])); + assert!(same_but_numbers(&last(20_000), &last(10_000)), "a number in an object"); + let unit = set(json!([{"field": "captureDate", "op": "inLast", "value": {"n": 3, "unit": "weeks"}}])); + assert!(!same_but_numbers(&last(3), &unit), "another unit is another rule"); + let stored = |v: serde_json::Value| set(json!([{"field": "captureDate", "op": "inLast", "value": v}])); + let written = stored(json!({"n": 10_000.0, "unit": "days"})); + assert!(same_but_numbers(&stored(json!(20_000)), &written), "a plain number of days is written as {{n, unit}}"); + assert!(same_but_numbers(&stored(json!({"n": 20_000})), &written), "a missing unit is days"); + assert!(same_but_numbers(&stored(json!({"n": "7.4", "unit": "Days"})), &written), "the unit in lower case"); + assert!(!same_but_numbers(&stored(json!(7)), &stored(json!({"n": 7, "unit": "weeks"}))), "days are not weeks"); + let text = |s: &str| set(json!([{"field": "keyword", "op": "is", "value": s}])); + assert!(!same_but_numbers(&text("a"), &text("b")) && same_but_numbers(&text("a"), &text("a"))); + assert!(!same_but_numbers(&a, &set(json!([{"field": "rating", "op": "is", "value": 9}]))), "another count of rules"); + let op = set(json!([{"field": "rating", "op": "gte", "value": 5}])); + assert!(!same_but_numbers(&op, &set(json!([{"field": "rating", "op": "lte", "value": 5}]))), "another operator"); + } + + #[test] + fn the_drop_line_sits_in_the_gap() { + let rows = rows(); + assert_eq!(gap_line(&rows, &[0]), Some((0.0, 100.0, -2.0))); + assert_eq!(gap_line(&rows, &[1]), Some((0.0, 100.0, 22.0)), "between the rule and the group"); + assert_eq!(gap_line(&rows, &[1, 1]), Some((0.0, 100.0, 62.0)), "inside the group"); + assert_eq!(gap_line(&rows, &[3]), Some((0.0, 100.0, 126.0))); + assert_eq!(gap_line(&rows, &[7, 0]), None); + } + + #[test] + fn rules_read_in_words() { + let none: [AlbumEntry; 0] = []; + assert_eq!(rule_text("rating", "gte", &json!(3), &none), "Rating is ≥ 3"); + assert_eq!(rule_text("edited", "is", &json!(true), &none), "Has Edits is Yes"); + let album = AlbumEntry { id: 7, name: "Trip".into(), parent: None, depth: 0, folder: false, smart: false, blocked: None }; + assert!(rule_text("album", "is", &json!(7), std::slice::from_ref(&album)).ends_with("Trip")); + assert!(rule_text("album", "is", &json!(9), &[album]).ends_with("#9")); + assert_eq!(rule_text("nonsense", "x", &Value::Null, &none), "nonsense x"); + } + + #[test] + fn numbers_and_units_read_as_the_editor_shows_them() { + let none: [AlbumEntry; 0] = []; + let text = |f: &str, op: &str, v: Value| rule_text(f, op, &v, &none); + crate::i18n::set_language(crate::i18n::Locale::En); + assert_eq!(text("rating", "gte", json!(3.0)), "Rating is ≥ 3"); + assert_eq!(text("aperture", "lte", json!(2.8)), "Aperture is ≤ 2.8"); + for n in [json!(30.0), json!("30"), json!(30)] { + assert_eq!(text("captureDate", "inLast", json!({"n": n, "unit": "days"})), "Capture Date is in the last 30 days"); + } + crate::i18n::set_language(crate::i18n::Locale::De); + let de = text("captureDate", "inLast", json!({"n": 7.0, "unit": "Weeks"})); + let de_str = text("captureDate", "inLast", json!({"n": "7", "unit": "weeks"})); + crate::i18n::set_language(crate::i18n::Locale::En); + assert_eq!(de, de_str); + assert!(de.ends_with(" 7 Wochen") && !de.contains("7.0") && !de.contains('"'), "{de}"); + } + + #[test] + fn row_salts_follow_the_editors() { + assert_eq!(row_salt("rules", &[]), "rules"); + assert_eq!(row_salt("rules", &[2, 1]), "rules-2-1"); + } +} diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index 1231e9d3b7..5495ac56e7 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -89,7 +89,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens ui, t, crate::i18n::tr( - "Photo ▸ Edit In ▸ Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", + "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.", ), ); row(ui, t, crate::i18n::tr("Other editor"), |ui| { diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 4e8d2a10d1..57cd17f92c 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -175,7 +175,7 @@ pub fn new_library(app: &mut LightcraftApp, p: &Value) -> Result None => location, }; if lightcraft_engine::library::is_library(&dir) { - return Err(format!("{}: there is a library here already; open it with File ▸ Open Library…", dir.display())); + return Err(format!("{}: there is a library here already; open it with File → Open Library…", dir.display())); } if dir.is_file() { return Err(format!("{}: is a file; a library is a folder", dir.display())); diff --git a/crates/ui-egui/src/dialogs/settings/slideshow.rs b/crates/ui-egui/src/dialogs/settings/slideshow.rs index a11bbfff60..49eebed646 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow.rs @@ -93,6 +93,33 @@ fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); + let mut v = s.pan_and_zoom; + if check(ui, "settings.slideshowPanAndZoom", &mut v, "Pan and zoom") { + let _ = app.run("slideshow.playback", json!({"panAndZoom": v})); + } + row(ui, t, crate::i18n::tr("Amount"), |ui| { + ui.add_enabled_ui(s.pan_and_zoom, |ui| { + ui.label(crate::i18n::tr("Low")); + let mut a = s.pan_and_zoom_amount; + let r = ui.add(egui::Slider::new(&mut a, 0.0..=1.0).show_value(false)); + register(ui, "slider:slideshowPanAndZoom", r.rect); + ui.label(crate::i18n::tr("High")); + if r.changed() + && let Ok(next) = app.session.slideshow.merged(&json!({"panAndZoomAmount": a})) + { + app.session.slideshow = next; + } + if r.drag_stopped() || (r.changed() && !r.dragged()) { + let _ = app.run("slideshow.playback", json!({"panAndZoomAmount": a})); + // the live value above already holds the amount, so the command finds no change + // to save: save it here + if let Err(e) = app.session.save_prefs() { + log::warn!("slideshow: {e}"); + } + } + }); + }); + hint(ui, t, crate::i18n::tr("Each photo moves and zooms slowly while it is up, on a path of its own. Exports show the photos still.")); let mut v = s.random_order; if check(ui, "settings.slideshowRandom", &mut v, "Random order") { let _ = app.run("slideshow.playback", json!({"randomOrder": v})); diff --git a/crates/ui-egui/src/find_similar.rs b/crates/ui-egui/src/find_similar.rs index d96424317c..07a306600f 100644 --- a/crates/ui-egui/src/find_similar.rs +++ b/crates/ui-egui/src/find_similar.rs @@ -73,7 +73,7 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Result { End::Found(answer) => { let n = answer["photos"].as_array().map_or(0, Vec::len); app.ui.view = crate::state::ViewMode::PhotoGrid; - app.toast(ctx, crate::i18n::tr_format!("{n} similar photo{} · View ▸ Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n)); + app.toast(ctx, crate::i18n::tr_format!("{n} similar photo{} · View → Clear Filters to see all", if n == 1 { "" } else { "s" }, n = n)); } // (whoever stopped it knows; a search of another library has nothing to say about this one) End::Dropped(_) => {} diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 157f389334..fb50726047 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3695,6 +3695,98 @@ fn import_review_dialog() { let _ = std::fs::remove_dir_all(&dir); } +/// Set a folder's modification time (Windows opens a folder for attributes, with backup semantics). +fn set_folder_time(dir: &std::path::Path, at: std::time::SystemTime) { + #[cfg(windows)] + let handle = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir) + }; + #[cfg(not(windows))] + let handle = std::fs::File::open(dir); + handle.unwrap().set_modified(at).unwrap(); +} + +/// A review's listing belongs to the import that review starts. Given a review that was +/// cancelled, when a sidecar appears in its folder (the folder's time put back as it was, as a +/// volume with coarse folder times would show it) and its file is imported another way (a folder +/// given by name is walked afresh, so only a named file could meet the old listing), +/// then the sidecar is read. +#[test] +fn a_cancelled_reviews_listing_is_not_used_by_another_import() { + let dir = std::env::temp_dir().join(format!("lc-ui-import-cancelled-review-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("a.png"), png).unwrap(); + // (old enough for the scan to vouch for the folder's time) + set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600)); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.settle(SETTLE); + h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the review is open"); + assert!(h.app.review_listed.is_some(), "the review holds its listing"); + h.request("ui.dialog.cancel", json!({}), t); + assert!(h.app.review_listed.is_none(), "cancelling the review drops the listing"); + let was = std::fs::metadata(&dir).unwrap().modified().unwrap(); + std::fs::write( + dir.join("a.xmp"), + r#""#, + ) + .unwrap(); + set_folder_time(&dir, was); + let r = h.request("engine.execute", json!({"command": "library.import", "params": {"paths": [dir.join("a.png").to_string_lossy()]}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let p = h.app.session.catalog.photos().find(|p| p.file_name == "a.png").expect("imported"); + assert_eq!(p.rating, 4, "the sidecar that appeared after the review is read"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A review waiting behind the open one keeps its own listing. Given a review that is open, when +/// another scan finishes (it waits for the dialog to close), then the open review still holds the +/// folders its own scan listed, and the waiting one's are kept for when it opens. +#[test] +fn a_waiting_reviews_listing_does_not_replace_the_open_ones() { + let make = |tag: &str| { + let dir = std::env::temp_dir().join(format!("lc-ui-import-waiting-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("a.png"), png).unwrap(); + set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600)); + dir + }; + let (first, second) = (make("first"), make("second")); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0); + let t = Duration::from_secs(10); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [first.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. }))); + let listed = |h: &Headless| format!("{:?}", h.app.review_listed); + assert!(listed(&h).contains("-first-"), "the open review holds its own listing: {}", listed(&h)); + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [second.to_string_lossy()]}}), t); + assert_eq!(r["result"]["scanning"], true, "{r}"); + h.step_until(SETTLE, |h| h.app.scan.is_none()); + h.settle(SETTLE); + assert!(h.app.review_pending.is_some(), "the second review waits behind the open one"); + assert!(listed(&h).contains("-first-") && !listed(&h).contains("-second-"), "the open review keeps its listing: {}", listed(&h)); + // cancelled, the first review makes room for the waiting one, which brings its own listing + h.request("ui.dialog.cancel", json!({}), t); + h.step_until(SETTLE, |h| h.app.review_pending.is_none()); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the waiting review opens"); + assert!(listed(&h).contains("-second-") && !listed(&h).contains("-first-"), "it holds its own listing: {}", listed(&h)); + let _ = std::fs::remove_dir_all(&first); + let _ = std::fs::remove_dir_all(&second); +} + /// The import review offers what to do with files that are in Recently Deleted (issues #298, /// #706): they are checked, to be restored, by default; Leave them unchecks them; confirming /// restores the photo (with its edits) or, with Import as new, imports the file afresh. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 8540f7b741..139ee53583 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -368,6 +368,307 @@ fn translated_catalogs_do_not_use_missing_menu_triangles() { } } +/// The string literals of non-test code in `src`, with the line each starts on. Code under +/// `#[cfg(test)]` and comments are left out; escapes are decoded where they matter here (`\u{…}`, +/// line continuations). +fn string_literals(src: &str) -> Vec<(usize, String)> { + let chars: Vec = src.chars().collect(); + let at = |i: usize| chars.get(i).copied().unwrap_or('\0'); + let ident = |c: char| c.is_alphanumeric() || c == '_'; + // where the inside of a `#[cfg(…)]` or `#![cfg(…)]` attribute starts; other attributes are read + // as code, so the strings in `#[error("…")]` and `#[cfg_attr(…, error("…"))]` are checked + let cfg_start = |i: usize| { + let open = if at(i) == '#' && at(i + 1) == '[' { + i + 2 + } else if at(i) == '#' && at(i + 1) == '!' && at(i + 2) == '[' { + i + 3 + } else { + return None; + }; + let name = (open..chars.len()).find(|&j| !chars[j].is_whitespace())?; + let paren = (name + 3..chars.len()).find(|&j| !chars[j].is_whitespace())?; + (chars[name..].starts_with(&['c', 'f', 'g']) && chars[paren] == '(').then_some(open) + }; + // whether `test` is one of the top-level conditions of an `all(…)`: `all(unix, any(test, …))` + // can ship without it + let all_has_test = |args: &str| { + let (mut level, mut from) = (0, 0); + for (k, ch) in args.char_indices().chain([(args.len(), ',')]) { + match ch { + '(' => level += 1, + ')' => level -= 1, + ',' if level == 0 => { + if &args[from..k] == "test" { + return true; + } + from = k + 1; + } + _ => {} + } + } + false + }; + let (mut out, mut i, mut line) = (Vec::new(), 0, 1); + let (mut depth, mut test_depth, mut pending_test) = (0usize, None, false); + while i < chars.len() { + let c = chars[i]; + let raw_start = if c == 'r' { + Some(i + 1) + } else if c == 'b' && at(i + 1) == 'r' { + Some(i + 2) + } else { + None + }; + let raw_hashes = raw_start.filter(|_| i == 0 || !ident(at(i - 1))).and_then(|start| { + let hashes = chars[start..].iter().take_while(|&&h| h == '#').count(); + (at(start + hashes) == '"').then_some((start, hashes)) + }); + if c == '\n' { + line += 1; + i += 1; + } else if c == '/' && at(i + 1) == '/' { + while i < chars.len() && chars[i] != '\n' { + i += 1; + } + } else if c == '/' && at(i + 1) == '*' { + skip_block_comment(&chars, &mut i, &mut line); + } else if let Some(start) = cfg_start(i) { + // `#[cfg(test)]` (spaces allowed) and `#[cfg(all(test, …))]` mark the next item as test + // code up to its `;` or through its body, `#![cfg(test)]` the rest of the file; + // `cfg(any(test, …))` code can ship, so it stays + let mut end = start; + let mut nested = 1; + while end < chars.len() && nested > 0 { + nested = match chars[end] { + '[' => nested + 1, + ']' => nested - 1, + _ => nested, + }; + line += usize::from(chars[end] == '\n'); + end += 1; + } + let attr: String = chars[start..end.saturating_sub(1)].iter().filter(|ch| !ch.is_whitespace()).collect(); + let all_test = attr.strip_prefix("cfg(all(").and_then(|rest| rest.strip_suffix("))")).is_some_and(all_has_test); + if attr == "cfg(test)" || all_test { + if c == '#' && at(i + 1) == '!' { + break; + } + pending_test = true; + } + i = end; + } else if let Some((start, hashes)) = raw_hashes { + let (first, mut text) = (line, String::new()); + i = start + hashes + 1; + while i < chars.len() && !(chars[i] == '"' && chars[i + 1..].iter().take(hashes).filter(|&&h| h == '#').count() == hashes) { + line += usize::from(chars[i] == '\n'); + text.push(chars[i]); + i += 1; + } + i += 1 + hashes; + if test_depth.is_none() && !pending_test { + out.push((first, text)); + } + } else if c == '"' { + let first = line; + let text = quoted_literal(&chars, &mut i, &mut line); + if test_depth.is_none() && !pending_test { + out.push((first, text)); + } + } else if c == '\'' { + // a char literal ('"', '\'', '{') or a lifetime ('a) + i += if at(i + 1) == '\\' { + chars[i + 3..].iter().position(|&q| q == '\'').map_or(1, |end| end + 4) + } else if at(i + 2) == '\'' { + 3 + } else { + 1 + }; + } else { + match c { + '{' => { + depth += 1; + if pending_test && test_depth.is_none() { + test_depth = Some(depth); + } + pending_test = false; + } + '}' => { + if test_depth == Some(depth) { + test_depth = None; + } + depth = depth.saturating_sub(1); + } + ';' => pending_test = false, + _ => {} + } + i += 1; + } + } + out +} + +/// Skips the block comment (nested ones too) that starts at `chars[*i]`, counting its lines. +fn skip_block_comment(chars: &[char], i: &mut usize, line: &mut usize) { + let at = |k: usize| chars.get(k).copied().unwrap_or('\0'); + let mut nested = 0; + while *i < chars.len() { + if chars[*i] == '/' && at(*i + 1) == '*' { + nested += 1; + *i += 2; + } else if chars[*i] == '*' && at(*i + 1) == '/' { + nested -= 1; + *i += 2; + if nested == 0 { + break; + } + } else { + *line += usize::from(chars[*i] == '\n'); + *i += 1; + } + } +} + +/// The text of the `"…"` literal that starts at `chars[*i]`, with `\u{…}`, line continuations and +/// other escapes decoded; `*i` ends past its closing quote. +fn quoted_literal(chars: &[char], i: &mut usize, line: &mut usize) -> String { + let at = |k: usize| chars.get(k).copied().unwrap_or('\0'); + let mut text = String::new(); + *i += 1; + while *i < chars.len() && chars[*i] != '"' { + if chars[*i] != '\\' { + *line += usize::from(chars[*i] == '\n'); + text.push(chars[*i]); + *i += 1; + continue; + } + match at(*i + 1) { + '\n' => { + *line += 1; + *i += 2; + while at(*i).is_whitespace() { + *line += usize::from(at(*i) == '\n'); + *i += 1; + } + } + 'u' => { + let hex: String = chars[*i + 3..].iter().take_while(|&&h| h != '}').collect(); + text.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)); + *i += 4 + hex.len(); + } + escaped => { + text.push(escaped); + *i += 2; + } + } + } + *i += 1; + text +} + +#[test] +fn string_literals_skip_comments_tests_and_char_literals() { + let src = r##"// "a" +fn f() { let q = '"'; let e = '\''; let s = "one ▸ \"two\""; } +/* "b" */ const R: &str = r#"raw "x""#; +fn g<'a>(x: &'a str) -> &'a str { "long \ + line \u{2192}" } +#[cfg(test)] +mod tests { fn t() { "test"; } } +const Z: &str = "after"; +#[ cfg( test ) ] fn spaced() { "test"; } +#[cfg(all(unix, test))] fn both() { "test"; } +#[cfg(any(test, feature = "x"))] fn either() { "either"; } +#[error("shown")] struct E; +#[cfg(all(unix, any(test, feature = "y")))] fn nested() { "nested"; } +#[cfg(all(test, not(feature = "y")))] fn negated() { "test"; } +#[cfg(test)] const SYMBOL: &str = "test"; +const KEPT: &str = "kept"; +#[cfg_attr(feature = "y", error("conditional"))] struct C; +#![cfg(test)] +fn rest() { "test"; }"##; + let found = string_literals(src); + let found: Vec<(usize, &str)> = found.iter().map(|(line, text)| (*line, text.as_str())).collect(); + let expected = [ + (2, "one ▸ \"two\""), + (3, "raw \"x\""), + (4, "long line →"), + (8, "after"), + (11, "either"), + (12, "shown"), + (13, "nested"), + (16, "kept"), + (17, "y"), + (17, "conditional"), + ]; + assert_eq!(found, expected); +} + +/// Every symbol in the interface's own text has a glyph (issue #1950: ▸ showed as a box in the +/// English strings, which untranslated messages fall back to). Checked on the string literals of +/// the code, not just the catalogs, with the fonts the build installs: a build without craft-fonts +/// checks Inter and egui's own fonts alone, so a symbol can't lean on a CJK face. Letters and the +/// full-width forms only CJK text uses are `catalog_characters_are_paintable`'s business. +/// Test code is left out: `tests/` directories, files named `tests.rs`, `tests_*.rs` or +/// `*_tests.rs`, and items under `#[cfg(test)]` or `#[cfg(all(test, …))]`. A string only a test +/// uses belongs in one of those, or it is checked like interface text. +#[test] +fn source_strings_use_paintable_symbols() { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::font_definitions(lightcraft_engine::CRAFT_FONTS)); + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + let cjk_only = |ch: char| matches!(ch, '\u{3000}'..='\u{303f}' | '\u{ff00}'..='\u{ffef}'); + // noncharacters are sentinels (an IndexedDB key range's end), never shown + let text = |ch: char| u32::from(ch) & 0xfffe != 0xfffe && !matches!(ch, '\u{fdd0}'..='\u{fdef}') && !ch.is_control(); + let checked = |ch: &char| !ch.is_ascii() && !ch.is_whitespace() && !ch.is_alphanumeric() && !cjk_only(*ch) && text(*ch); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + for group in ["crates", "apps"] { + for krate in std::fs::read_dir(root.join(group)).unwrap() { + let mut dirs = vec![krate.unwrap().path().join("src")]; + while let Some(dir) = dirs.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries { + let path = entry.unwrap().path(); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("").to_string(); + if path.is_dir() { + if name != "tests" { + dirs.push(path); + } + } else if name.ends_with(".rs") && !name.starts_with("tests_") && !name.ends_with("_tests.rs") && name != "tests.rs" { + files.push(path); + } + } + } + } + } + assert!(files.len() > 100, "found the workspace's sources ({} files)", files.len()); + let mut texts: Vec<(String, String)> = Vec::new(); + for path in &files { + let src = std::fs::read_to_string(path).unwrap(); + let shown = path.strip_prefix(&root).unwrap_or(path).display().to_string(); + texts.extend(string_literals(&src).into_iter().map(|(line, text)| (format!("{shown}:{line}"), text))); + } + // What's New as the dialog shows it + for line in crate::panels::dialogs::WHATS_NEW.lines().map(str::trim) { + let line = line.strip_prefix("### ").or_else(|| line.strip_prefix("## ")).or_else(|| line.strip_prefix("- ")).unwrap_or(line); + texts.push(("docs/whats-new.md".into(), crate::panels::dialogs::whats_new_line(line))); + } + let font = egui::FontId::new(13.0, egui::FontFamily::Proportional); + let mut missing: Vec = Vec::new(); + ctx.fonts_mut(|fonts| { + for (place, text) in &texts { + for ch in text.chars().filter(checked) { + if !fonts.has_glyph(&font, ch) { + missing.push(format!("{place}: {ch:?} (U+{:04X})", u32::from(ch))); + } + } + } + }); + missing.dedup(); + assert!(missing.is_empty(), "symbols no UI font has (they paint as boxes):\n{}", missing.join("\n")); +} + /// Every language has a command, and a language's own command selects it. #[test] fn language_commands_cover_every_language() { diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a06184f2af..23c0f501fd 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -56,6 +56,8 @@ pub enum Icon { SmartAlbum, Stack, Folder, + /// A drag handle: two columns of three dots. + Grip, /// Edit (a pencil). Pencil, Photos, @@ -342,6 +344,13 @@ fn paint_with(p: &Painter, rect: Rect, icon: Icon, color: Color32, turn: Option< pen.dot(x, 10.0, 1.3); } } + Grip => { + for x in [7.0, 13.0] { + for y in [4.5, 10.0, 15.5] { + pen.dot(x, y, 1.3); + } + } + } Tag => { pen.closed(&[(3.0, 3.5), (10.0, 3.5), (17.0, 10.5), (10.5, 17.0), (3.0, 10.0)]); pen.dot(7.0, 7.5, 1.2); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b6ded83704..554ad93405 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -340,6 +340,8 @@ pub struct LightcraftApp { pub(crate) scans_stopping: import::StoppingScans, /// Files that waited for a library and wait for the running import or Synchronize Folder too. pub waiting_import: panels::library_problem::WaitingImport, + /// The folders the scan of the review on screen listed, for the import that review starts (and no other). + pub review_listed: Option, /// A Synchronize Folder scan in progress (feeds its dialog). pub sync: Option, /// `session.folder_changes` came from the Synchronize Folder dialog (and goes with it). @@ -354,6 +356,8 @@ pub struct LightcraftApp { pub(crate) lightroom_result: Option, /// The import review of a finished scan, waiting for another dialog to close. pub(crate) review_pending: Option, + /// The folders that review's scan listed; they become [`Self::review_listed`] when the review opens. + pub(crate) review_pending_listed: Option, /// The library generation the window title and the recent list were last updated for. pub shown_library: Option, /// A background export in progress. diff --git a/crates/ui-egui/src/menus/files.rs b/crates/ui-egui/src/menus/files.rs index d75282e577..42abcddb74 100644 --- a/crates/ui-egui/src/menus/files.rs +++ b/crates/ui-egui/src/menus/files.rs @@ -8,7 +8,7 @@ pub fn delete_in_album(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { let lightcraft_engine::LibrarySource::Album(aid) = app.session.source else { return false }; let Some(album) = app.session.catalog.album(aid) else { return false }; if album.is_smart() { - app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo ▸ Delete Photo")); + app.toast(ctx, crate::i18n::tr("Smart albums update automatically: change their rules, or use Photo → Delete Photo")); return true; } if app.session.selected().is_empty() { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 2fde272c31..a4462659e5 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1326,7 +1326,7 @@ fn ui_commands_10(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Va "photo.openOriginalInExternal" => open_original_in(app, ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); Ok(Value::Null) } "app.whatsNew" => { @@ -1678,12 +1678,11 @@ fn dialog_smart_album_command(app: &mut LightcraftApp, _id: &str, p: &Value) -> .and_then(Value::as_u64) .and_then(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(id)).filter(|a| a.is_smart()).cloned()); app.ui.dialog = Some(match album { - Some(a) => Dialog::SmartRules { - id: Some(a.id.0), - name: a.name.clone(), + Some(a) => Dialog::smart_rules( + Some(a.id.0), + a.name.clone(), // older rules read as they always matched (RuleSet::upgrade) - rules: a - .smart + a.smart .as_ref() .and_then(|f| f.rule_set.clone()) .map(|mut r| { @@ -1691,14 +1690,14 @@ fn dialog_smart_album_command(app: &mut LightcraftApp, _id: &str, p: &Value) -> r }) .unwrap_or_default(), - parent: None, - }, - None => Dialog::SmartRules { - id: None, - name: p.get("name").and_then(Value::as_str).unwrap_or("").into(), - rules: lightcraft_catalog::RuleSet { rules: vec![crate::panels::rules_editor::new_rule()], ..Default::default() }, - parent: parent_param(p), - }, + None, + ), + None => Dialog::smart_rules( + None, + p.get("name").and_then(Value::as_str).unwrap_or("").into(), + lightcraft_catalog::RuleSet { rules: vec![crate::panels::rules_editor::new_rule()], ..Default::default() }, + parent_param(p), + ), }); Ok(Value::Null) } @@ -1973,7 +1972,7 @@ fn import_luts(app: &mut LightcraftApp, lut_paths: &[&String], news: &mut Import let profiles = v["imported"].as_array().map_or(0, Vec::len); if profiles > 0 { news.parts.push(crate::i18n::tr_format!( - "Imported {profiles} profile{} (Profile browser ▸ their groups)", + "Imported {profiles} profile{} (Profile browser → their groups)", crate::i18n::plural_s(profiles), profiles = profiles )); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ed9c45fb5d..c4c8a03ece 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -39,6 +39,7 @@ pub use crate::dialogs::faces; pub use crate::dialogs::keymap; pub use crate::dialogs::rules_editor; pub use crate::dialogs::rules_editor::rules_move; +pub use crate::dialogs::rules_editor::rules_reorder; pub use crate::dialogs::settings; pub use crate::dialogs::settings::slide_layout; pub use crate::dialogs::settings::slide_overlays; diff --git a/crates/ui-egui/src/panels/chips.rs b/crates/ui-egui/src/panels/chips.rs index 19626bbfd3..736731b53d 100644 --- a/crates/ui-egui/src/panels/chips.rs +++ b/crates/ui-egui/src/panels/chips.rs @@ -155,7 +155,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, chips: &[FilterChip]) { egui::Popup::menu(&more).show(|ui| { for c in hidden { if ui - .button(format!("{} ✕", display_label(c, &app.session.filter, &app.session.catalog))) + .button(format!("{} ×", display_label(c, &app.session.filter, &app.session.catalog))) .on_hover_text(crate::i18n::tr("Remove this filter")) .clicked() { diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 4fc9e49554..f3cd9821b3 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -633,7 +633,7 @@ pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) { let canvas = area_and_filmstrip(app, ui); let reference = app.ui.reference.map(PhotoId).filter(|r| live(app, *r)); let (Some(r), Some(active)) = (reference, app.session.active()) else { - super::empty_message(ui, canvas, "No reference photo", "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)"); + super::empty_message(ui, canvas, "No reference photo", "Right-click a photo → Set as Reference Photo, then View → Reference View (Shift+R)"); return; }; let area = canvas.shrink(18.0); diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index 1148d9527b..766d0d75d2 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -174,7 +174,7 @@ pub(super) fn region_overlay( let cross = Stroke::new(1.4, if resp.hovered() { Color32::WHITE } else { Color32::from_gray(210) }); p.line_segment([c - vec2(m, m), c + vec2(m, m)], cross); p.line_segment([c - vec2(m, -m), c + vec2(m, -m)], cross); - if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit ▸ Undo)")).clicked() { + if resp.on_hover_text(crate::i18n::tr("Remove this face box (undo with Edit → Undo)")).clicked() { edit = Some(RegionEdit::Remove(index)); } } diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index b231084541..d24371d163 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -137,7 +137,7 @@ fn remove(app: &mut LightcraftApp, ctx: &egui::Context, chip: &Chip) { let name = chip.path.replace('|', " › "); app.toast_for( ctx, - crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit ▸ Undo puts it back.", name = name, n = chip.have), + crate::i18n::tr_format!("Removed “{name}” from {n} photos. Edit → Undo puts it back.", name = name, n = chip.have), 6.0, ); } diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index b7a3ad3902..dd0d46f973 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -356,12 +356,12 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.dialog = Some(crate::state::Dialog::NewAlbum { name: String::new(), folder: false, parent: None, include_selected: true }); } if ui.button(crate::i18n::tr("Create Smart Album…")).clicked() { - app.ui.dialog = Some(crate::state::Dialog::SmartRules { - id: None, - name: String::new(), - rules: lightcraft_catalog::RuleSet { rules: vec![crate::panels::rules_editor::new_rule()], ..Default::default() }, - parent: None, - }); + app.ui.dialog = Some(crate::state::Dialog::smart_rules( + None, + String::new(), + lightcraft_catalog::RuleSet { rules: vec![crate::panels::rules_editor::new_rule()], ..Default::default() }, + None, + )); } if ui.button(crate::i18n::tr("Create Smart Album from Filter…")).clicked() { app.ui.dialog = Some(crate::state::Dialog::NewSmartAlbum { name: String::new(), parent: None }); diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index d1c4fe1f49..0300425467 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -708,7 +708,7 @@ pub fn import_toast(v: &Value) -> String { } fn imported_effects_message(n: usize) -> String { - crate::i18n::tr_format!("Imported {e} mask effect{} (Masking ▸ Effect)", crate::i18n::plural_s(n), e = n) + crate::i18n::tr_format!("Imported {e} mask effect{} (Masking → Effect)", crate::i18n::plural_s(n), e = n) } fn in_groups_message(groups: usize) -> String { diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index d833fbeb11..5e88bc1379 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -319,7 +319,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let op = match c.op { lightcraft_develop::MaskOp::Add => "", lightcraft_develop::MaskOp::Subtract => "− ", - lightcraft_develop::MaskOp::Intersect => "∩ ", + lightcraft_develop::MaskOp::Intersect => { + // drawn: Inter has no ∩, only the CJK faces do (issue #1950) + let (r, _) = ui.allocate_exact_size(vec2(8.0, 16.0), Sense::hover()); + intersect_mark(ui.painter(), r, ui.visuals().text_color()); + "" + } }; if let Some((_, _, name)) = app.ui.renaming_component.as_mut().filter(|(mid, k, _)| *mid == m.id && *k == i) { // inline rename: Enter (or leaving the field) commits, Escape cancels @@ -344,9 +349,14 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let room = (ui.available_width() - 30.0).max(0.0); let resp = ui.scope(|ui| { ui.set_max_width(room); - ui.add(egui::Label::new(text).truncate().sense(Sense::click())) + ui.add(egui::Label::new(text.clone()).truncate().sense(Sense::click())) }); let resp = resp.inner; + if matches!(c.op, lightcraft_develop::MaskOp::Intersect) { + // the drawn ∩ has no text: the row still names its mode to screen readers + let spoken = format!("{}: {text}", crate::i18n::tr("Intersect")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, spoken.clone())); + } register(ui, format!("component:{i}"), resp.rect); if resp.double_clicked() { app.ui.renaming_component = Some((m.id, i, label.clone())); @@ -974,6 +984,19 @@ fn brush_settings(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } +/// The ∩ in front of an intersecting mask component: two legs joined by a half circle, as tall as +/// a lowercase letter. +fn intersect_mark(painter: &egui::Painter, rect: Rect, color: egui::Color32) { + let (c, r) = (rect.center(), 3.0); + let mut points = vec![pos2(c.x - r, c.y + 4.0)]; + points.extend((0..=8).map(|i| { + let a = std::f32::consts::PI * (1.0 + i as f32 / 8.0); + pos2(c.x + r * a.cos(), c.y - 0.5 + r * a.sin()) + })); + points.push(pos2(c.x + r, c.y + 4.0)); + painter.add(egui::Shape::line(points, Stroke::new(1.2, color))); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index 8b0ade6cf3..351b8d531c 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -1,6 +1,6 @@ //! The slideshow (View ▸ Slideshow, ⌥⌘↩): the photos in view, full screen, played with the //! library's Playback settings (`slideshow.playback`: slide and fade durations, fade colour, -//! random order, repeat, preparing previews in advance, manual slideshow). +//! random order, repeat, preparing previews in advance, manual slideshow, pan and zoom). //! //! The timeline is [`lightcraft_engine::slideshow::Playback`] (no egui, tested on its own); this //! module renders the slides, draws the frame it asks for and the playback controls. @@ -22,11 +22,17 @@ //! render worker ([`crate::render::Renderer::request_title`]), prepared ahead, waited for and //! faded like photo slides. They never move the selection, and the controls show "Intro" / "End" //! in place of "n / N" while one is up (titles aren't photos, so N stays the number of photos). +//! +//! Pan and zoom ([`Playback::pan_zoom`]) moves the photo's part of each slide's texture: the photo +//! inside its image cell for a composed slide, while the backdrop, margins, stroke and shadow stay +//! where they are. A photo drawn on its own, and a slide with overlays (drawn into its texture, +//! where they can cross the cell's edge), move as a whole. A title screen does not move. use egui::{Align2, Color32, Pos2, Rect, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_engine::slideshow::{Item, Playback, Tick, Title}; use lightcraft_pipeline::geometry::Frame; +use lightcraft_slideshow::View; use serde_json::{Value, json}; use crate::LightcraftApp; @@ -53,9 +59,10 @@ pub struct Run { } /// `view.slideshow {interval?, seed?, slideDuration?, fadeDuration?, fadeColor?, randomOrder?, -/// repeat?, preparePreviews?, manual?}`: play the photos in view from the selected one with the library's -/// playback settings; the keys given change them for this run only (`interval` = slideDuration, -/// `seed` fixes the random order). The intro and ending screens that are on (`slideshow.titles`) +/// repeat?, preparePreviews?, manual?, panAndZoom?, panAndZoomAmount?}`: play the photos in view +/// from the selected one with the library's playback settings; the keys given change them for +/// this run only (`interval` = slideDuration, `seed` fixes the random order and the pan and zoom +/// paths). The intro and ending screens that are on (`slideshow.titles`) /// play before the first photo and after the last one. With no photos in view there is nothing /// to show (titles alone don't make a slideshow). pub fn start(app: &mut LightcraftApp, p: &Value, now: f64) -> Result { @@ -130,6 +137,12 @@ pub fn state(play: &Playback, now: f64) -> Value { // (null in a manual slideshow: no slide is ever due) "remaining": play.remaining(now), "manual": play.settings().manual, + "panAndZoom": play.settings().pan_and_zoom, + // (the current photo's window, 0–1 across and down; null when it shows whole) + "view": play.pan_zoom(now).current.map(|v| { + let (x0, y0, x1, y1) = v.window(); + json!([x0, y0, x1, y1]) + }), }) } @@ -173,8 +186,14 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { after(app, t); let Some(run) = app.ui.slideshow.as_ref() else { return }; let f = run.play.frame(now); - if f.from.is_some() { - ctx.request_repaint(); // a fade draws every frame + // A slide's time, and so its pan and zoom, starts only once it is ready: until then the + // next frame comes soon, for the render queue to take the slide and show it. + let shown = ready(app, run.play.current()); + let moving = run.play.pan_zoom_moving(now) && shown; + if f.from.is_some() || moving { + ctx.request_repaint(); // a fade, and pan and zoom, draw every frame + } else if !shown { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); } else if !run.play.is_paused() && !run.play.settings().manual { ctx.request_repaint_after(std::time::Duration::from_secs_f64(run.play.remaining(now).clamp(0.016, 120.0))); } @@ -253,12 +272,52 @@ fn wanted(play: &Playback, now: f64) -> Vec<(Item, u32)> { /// screen has nothing to stand in for it: the black canvas shows until it lands. fn texture(app: &LightcraftApp, item: Item) -> Option<&crate::render::Tex> { let Item::Photo(id) = item else { return app.renderer.textures.get(&Slot::Slide(item)) }; - app.renderer - .textures - .get(&Slot::Slide(item)) - .filter(|t| t.photo == id) - .or_else(|| app.renderer.textures.get(&Slot::Main).filter(|t| t.photo == id)) - .or_else(|| app.renderer.thumb(id)) + slide_texture(app, id).or_else(|| app.renderer.textures.get(&Slot::Main).filter(|t| t.photo == id)).or_else(|| app.renderer.thumb(id)) +} + +/// Photo `id`'s own slide render. +fn slide_texture(app: &LightcraftApp, id: PhotoId) -> Option<&crate::render::Tex> { + app.renderer.textures.get(&Slot::Slide(Item::Photo(id))).filter(|t| t.photo == id) +} + +/// The part of `item`'s texture `t` that pan and zoom moves, in texture coordinates (0–1): the +/// photo's visible part of a composed slide without overlays (its image cell), else all of it (a +/// photo drawn on its own, a plain slide or a stand-in, and a slide with overlays, which are +/// drawn into its texture and can cross the cell's edge: they move with the slide). The cell +/// comes from the current settings and the size of the photo's render the slide was composed +/// from, so a texture rendered with older settings (its new render still on the way) also moves +/// whole. +pub(crate) fn moving_part(app: &LightcraftApp, item: Item, t: &crate::render::Tex) -> Rect { + let Item::Photo(id) = item else { return full_uv() }; + let composed = !app.session.slides_plain() + && !app.session.slide_overlays.any() + && slide_texture(app, id).is_some_and(|s| std::ptr::eq(s, t)) + && app.renderer.is_current(Slot::Slide(item), t.key); + let [w, h] = t.size; + let photo = t.slide_photo.filter(|[pw, ph]| composed && w > 0 && h > 0 && *pw > 0 && *ph > 0); + let Some([pw, ph]) = photo else { return full_uv() }; + let aspect = pw as f64 / ph as f64; + let v = lightcraft_slideshow::layout(&app.session.slide_layout, aspect, w, h).visible; + let (w, h) = (w as f64, h as f64); + let uv = Rect::from_min_max(pos2((v.x0 / w) as f32, (v.y0 / h) as f32), pos2((v.x1 / w) as f32, (v.y1 / h) as f32)); + if uv.is_positive() { uv.intersect(full_uv()) } else { full_uv() } +} + +/// Draw texture `t` into `r` with `tint`. With a pan and zoom `view`, the `part` of it (texture +/// coordinates) shows that view's window of itself in the same place; the rest is drawn as is. +fn paint(p: &egui::Painter, t: &crate::render::Tex, r: Rect, part: Rect, view: Option, tint: Color32) { + let Some(v) = view else { + p.image(t.id(), r, full_uv(), tint); + return; + }; + let at = |u: Pos2| pos2(r.min.x + u.x * r.width(), r.min.y + u.y * r.height()); + let place = Rect::from_min_max(at(part.min), at(part.max)); + for band in outside(r, place) { + p.with_clip_rect(band).image(t.id(), r, full_uv(), tint); + } + let (x0, y0, x1, y1) = v.window(); + let sub = |x: f64, y: f64| pos2(part.min.x + x as f32 * part.width(), part.min.y + y as f32 * part.height()); + p.image(t.id(), place, Rect::from_min_max(sub(x0, y0), sub(x1, y1)), tint); } fn full_uv() -> Rect { @@ -299,6 +358,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let side = super::detail::texture_side(ui.ctx()); let want = wanted(&run.play, now); let frame = run.play.frame(now); + let pz = run.play.pan_zoom(now); let mut unrenderable = Vec::new(); for (item, priority) in &want { match *item { @@ -325,12 +385,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let p = ui.painter_at(canvas); p.rect_filled(canvas, 0.0, Color32::BLACK); let rect_of = |t: &crate::render::Tex| super::detail::fit_texture_rect(canvas, t.size); - let draw = |id: Item, alpha: f32| -> Option { + let view_of = |id: Item| { + if id == frame.current { + pz.current + } else if Some(id) == frame.from { + pz.from + } else { + None + } + }; + let draw_on = |p: &egui::Painter, id: Item, alpha: f32| -> Option { let t = texture(app, id)?; let r = rect_of(t); - p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); + paint(p, t, r, moving_part(app, id, t), view_of(id), Color32::WHITE.gamma_multiply(alpha.clamp(0.0, 1.0))); Some(r) }; + let draw = |id: Item, alpha: f32| draw_on(&p, id, alpha); let k = frame.progress.clamp(0.0, 1.0); match (frame.from, frame.fade_color) { // fade through a colour: out to it, then in from it @@ -348,17 +418,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the old one is, it fades to the backdrop (Some(from), None) => { let new_rect = texture(app, frame.current).map(rect_of); - if let Some(t) = texture(app, from) { - let r = rect_of(t); + if let Some(r) = texture(app, from).map(rect_of) { match new_rect { Some(n) => { - p.with_clip_rect(n.intersect(canvas)).image(t.id(), r, full_uv(), Color32::WHITE); + draw_on(&p.with_clip_rect(n.intersect(canvas)), from, 1.0); for band in outside(r, n) { - p.with_clip_rect(band).image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + draw_on(&p.with_clip_rect(band), from, 1.0 - k); } } None => { - p.image(t.id(), r, full_uv(), Color32::WHITE.gamma_multiply(1.0 - k)); + draw(from, 1.0 - k); } } } diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index a2eb3bf342..6b09bc89d3 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -102,6 +102,9 @@ pub struct Tex { pub pixels: Option>, /// Showing a render that stayed on the GPU ([`ScreenTextures`]): drawn by this id instead of `tex`. pub native: Option, + /// A composed slide's photo: the size of the render the slide was laid out with + /// ([`RenderResult::slide_photo`]). + pub slide_photo: Option<[usize; 2]>, } impl Tex { @@ -1333,13 +1336,25 @@ impl Renderer { t.histogram = Some(histogram); t.ms = ms; t.quick = None; + t.slide_photo = r.slide_photo; } None => { // (`tex` is never drawn while `native` is set) let blank = egui::ColorImage::filled([1, 1], egui::Color32::BLACK); let tex = ctx.load_texture(format!("{slot:?}"), blank, egui::TextureOptions::LINEAR); - let t = - Tex { look, key: r.key, photo: r.photo, tex, size, histogram: Some(histogram), ms, quick: None, pixels: None, native: Some(id) }; + let t = Tex { + look, + key: r.key, + photo: r.photo, + tex, + size, + histogram: Some(histogram), + ms, + quick: None, + pixels: None, + native: Some(id), + slide_photo: r.slide_photo, + }; self.textures.insert(slot, t); } } @@ -1479,6 +1494,7 @@ impl Renderer { t.histogram = Some(rendered.histogram); t.ms = ms; t.quick = r.quick; + t.slide_photo = r.slide_photo; } None => { let tex = ctx.load_texture(name, color, egui::TextureOptions::LINEAR); @@ -1495,6 +1511,7 @@ impl Renderer { quick: r.quick, pixels, native: None, + slide_photo: r.slide_photo, }, ); } @@ -1767,7 +1784,19 @@ mod stage_budget_tests { let tex = ctx.load_texture("window", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); r.textures.insert( Slot::Region, - Tex { look: None, key: 1, photo: PhotoId(1), tex, native: None, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: None, + key: 1, + photo: PhotoId(1), + tex, + native: None, + size: [1, 1], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + slide_photo: None, + }, ); let long_ago = std::time::Instant::now().checked_sub(IDLE_TRIM * 2).unwrap(); r.idle = Some((long_ago, false)); @@ -1797,6 +1826,7 @@ mod stage_budget_tests { ms: 0.0, quick: None, pixels: None, + slide_photo: None, }; r.textures.insert(Slot::Before, view(tex("before"), Some(egui::TextureId::User(7)))); r.textures.insert(Slot::Compare(0), view(tex("compare"), Some(egui::TextureId::User(8)))); @@ -1824,6 +1854,7 @@ mod stage_budget_tests { ms: 0.0, quick: None, pixels: Some(std::sync::Arc::new(egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]))), + slide_photo: None, }; t.show_native(egui::TextureId::User(7)); assert_eq!(t.tex.size(), [1, 1], "the pixel image is released"); @@ -1953,6 +1984,7 @@ mod color_image_tests { quick: None, display: None, frame: None, + slide_photo: None, }; let histogram = Histogram::of_srgb8(&image); let ok = Renderer::run_for(|| result(Ok(lightcraft_pipeline::Rendered { image: image.clone(), histogram, deep: None })), &None); diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index b2a87e6522..db99ed5b22 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -330,6 +330,7 @@ fn larger_texture_for_another_key_does_not_count_as_current() { quick: None, pixels: None, native: None, + slide_photo: None, }; let mut r = Renderer::default(); // A completed larger bucket: the remembered request is bucket 512, key 77. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 203ede571e..3c45ab474f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -143,6 +143,9 @@ pub struct UiState { /// session; `None` until the dialog is first confirmed (then 10 s, 0.93). #[serde(skip)] pub cull_burst: Option<(f32, f32)>, + /// Whether Assisted Culling stacked its bursts the last time it was confirmed (this session). + #[serde(skip)] + pub cull_stack: bool, /// "More" faces the user hid with ×, for this session: (photo, region index). #[serde(skip)] pub dismissed_faces: std::collections::HashSet<(u64, usize)>, @@ -446,6 +449,7 @@ impl Default for UiState { person_from: None, last_person: None, cull_burst: None, + cull_stack: false, dismissed_faces: Default::default(), unnamed_selected: Default::default(), unnamed_name: String::new(), diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 77f80a280c..553277ec7e 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -6,11 +6,22 @@ pub fn default_preset_groups() -> Vec { lightcraft_develop::SettingsGroup::default_copy().iter().filter_map(|g| serde_json::to_value(g).ok()?.as_str().map(str::to_string)).collect() } +/// A number no other smart album dialog has had in this run ([`Dialog::SmartRules`]'s `instance`). +fn new_smart_rules_instance() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + impl Dialog { /// A fresh Create Preset dialog. pub fn create_preset() -> Dialog { Dialog::CreatePreset { name: String::new(), group: "User Presets".into(), groups: default_preset_groups() } } + + /// A new smart album rules dialog: a fresh one, whatever rules it holds. + pub fn smart_rules(id: Option, name: String, rules: lightcraft_catalog::RuleSet, parent: Option) -> Dialog { + Dialog::SmartRules { id, name, rules, parent, instance: new_smart_rules_instance() } + } } /// A face's name being typed in the loupe: which face, and what has been typed so far. @@ -172,11 +183,13 @@ pub enum Dialog { page: usize, }, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best - /// of each burst; shots at most `burst_gap` seconds apart and at least `similarity` alike are - /// a burst. + /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Cull { reject_below: f32, pick_best: bool, + #[serde(default)] + stack_groups: bool, burst_gap: f32, similarity: f32, }, @@ -209,6 +222,11 @@ pub enum Dialog { /// The folder a new smart album is created in (ignored when editing). #[serde(default)] parent: Option, + /// Which dialog this is: two dialogs holding the same rules can't be told apart by them, and a drag + /// in the editor belongs to the dialog it began in. Made with the dialog ([`Dialog::smart_rules`]), + /// never saved. + #[serde(skip, default = "new_smart_rules_instance")] + instance: u64, }, /// `groups`: the settings groups the preset includes (`SettingsGroup` ids). CreatePreset { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 825a84d017..b3927c54c1 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -98,6 +98,7 @@ mod recheck; mod reduce_motion; mod rename_person; mod rules_editor; +mod rules_reorder; mod sam_setup; mod scan_probes; mod scroll; diff --git a/crates/ui-egui/src/tests/dialog_copy.rs b/crates/ui-egui/src/tests/dialog_copy.rs index 7983c3052d..48087f3e1d 100644 --- a/crates/ui-egui/src/tests/dialog_copy.rs +++ b/crates/ui-egui/src/tests/dialog_copy.rs @@ -80,7 +80,7 @@ fn confirm_buttons_name_their_action() { } // a new smart album's rules are created; an existing one's are saved for (id, want) in [(None, "Create"), (Some(1), "Save")] { - let d = Dialog::SmartRules { id, name: "A".into(), rules: Default::default(), parent: None }; + let d = Dialog::smart_rules(id, "A".into(), Default::default(), None); show(&mut h, d); assert_eq!(confirm_label(&h), want, "smart album rules {id:?}"); } diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index ae043cb5f1..7dffeb491c 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -1230,6 +1230,7 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() { truncated: false, unreadable: 0, unsupported: 0, + listed: Default::default(), })) .unwrap(); drop(tx); diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index e29946baa2..052f410169 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -609,7 +609,19 @@ fn hidden_slideshow_pauses_and_keeps_its_remaining_time() { let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default()); app.renderer.textures.insert( Slot::Slide(Item::Photo(id)), - Tex { look: None, key: 0, photo: id, tex, native: None, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + look: None, + key: 0, + photo: id, + tex, + native: None, + size: [2, 2], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + slide_photo: None, + }, ); } let first = app.ui.slideshow.as_ref().unwrap().play.current(); diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 54575499e2..c8cb5b9efe 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -1126,7 +1126,7 @@ fn album_dialogs_without_a_parent_still_deserialize() { assert!(matches!(d, Dialog::NewAlbum { parent: None, .. })); let d: Dialog = serde_json::from_value(json!({"kind": "newSmartAlbum", "name": "x"})).unwrap(); assert!(matches!(d, Dialog::NewSmartAlbum { parent: None, .. })); - let mut v = serde_json::to_value(Dialog::SmartRules { id: None, name: "x".into(), rules: Default::default(), parent: Some(3) }).unwrap(); + let mut v = serde_json::to_value(Dialog::smart_rules(None, "x".into(), Default::default(), Some(3))).unwrap(); assert_eq!(v["parent"], 3); v.as_object_mut().unwrap().remove("parent"); let d: Dialog = serde_json::from_value(v).unwrap(); diff --git a/crates/ui-egui/src/tests/print.rs b/crates/ui-egui/src/tests/print.rs index 7a6c380e4f..44b06f80b3 100644 --- a/crates/ui-egui/src/tests/print.rs +++ b/crates/ui-egui/src/tests/print.rs @@ -90,6 +90,11 @@ fn style_buttons_and_checkboxes_run_print_set() { click(&mut h, "check:printZoomFill"); click(&mut h, "check:printStroke"); assert!(h.app.session.print.image.zoom_to_fill && h.app.session.print.image.stroke_enabled); + // (the page settings are below the Template Browser: the settings column is scrolled to them) + let column = rect(&h, "check:printStroke").center(); + h.request("ui.move", json!({"x": column.x, "y": column.y}), T); + h.request("ui.scroll", json!({"dy": -200.0}), T); + h.settle(T); click(&mut h, "button:printOrientation-1"); assert_eq!(h.app.session.print.layout.page.orientation, lightcraft_engine::print::layout::Orientation::Landscape); let p = rect(&h, "print:page"); @@ -248,6 +253,152 @@ fn templates_export_and_import_from_the_dialog() { let _ = std::fs::remove_dir_all(dir); } +/// Each template's name and folder (`None`: User Templates). +fn template_folders(h: &Headless) -> Vec<(String, Option)> { + h.app.session.print_templates.iter().map(|t| (t.name.clone(), t.folder.clone())).collect() +} + +/// The text the last frame painted inside the widget `id`. +fn text_in(h: &Headless, id: &str) -> Vec { + let r = rect(h, id); + h.view + .painted_shapes() + .into_iter() + .filter_map(|s| match s { + egui::epaint::Shape::Text(t) if r.contains(t.visual_bounding_rect().center()) => Some(t.galley.job.text.clone()), + _ => None, + }) + .collect() +} + +/// Drags the widget `from` onto the center of the widget `to`. +fn drag_onto(h: &mut Headless, from: &str, to: &str) { + let (a, b) = (rect(h, from).center(), rect(h, to).center()); + drag(h, from, b.x - a.x, b.y - a.y); +} + +#[test] +fn the_template_browser_makes_folders_and_saves_into_one() { + let mut h = demo(Services::default()); + open_print(&mut h); + assert!(has(&h, "printTemplateFolder-0"), "User Templates is listed"); + assert!(!has(&h, "printTemplateFolder-1")); + click(&mut h, "button:printTemplateNewFolder"); + assert!(has(&h, "field:printFolderName")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Weddings".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Weddings"]); + assert!(h.app.ui.print.folder_edit.is_none()); + assert!(has(&h, "printTemplateFolder-1")); + assert_eq!(h.app.ui.print.save_folder.as_deref(), Some("Weddings"), "a new folder is where Save goes"); + // a name taken is refused, and the field stays open + click(&mut h, "button:printTemplateNewFolder"); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "weddings".into(); + click(&mut h, "button:printFolderOk"); + assert!(h.app.ui.print.folder_edit.is_some()); + click(&mut h, "button:printFolderCancel"); + assert!(h.app.ui.print.folder_edit.is_none()); + assert_eq!(h.app.session.print_template_folders.len(), 1); + + h.app.ui.print.template_name = "Sheet".into(); + click(&mut h, "button:printSaveTemplate"); + h.app.ui.print.save_folder = None; + h.app.ui.print.template_name = "Plain".into(); + click(&mut h, "button:printSaveTemplate"); + assert_eq!(template_folders(&h), [("Sheet".into(), Some("Weddings".into())), ("Plain".into(), None)]); + // a folder's row opens and closes its list + assert!(has(&h, "printTemplate-0")); + click(&mut h, "printTemplateFolder-1"); + assert!(!has(&h, "printTemplate-0"), "a closed folder hides its templates"); + assert!(has(&h, "printTemplate-1")); + click(&mut h, "printTemplateFolder-1"); + assert!(has(&h, "printTemplate-0")); +} + +#[test] +fn saving_over_a_template_keeps_its_folder_until_one_is_picked() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Sheet", "folder": "Weddings"})); + h.app.ui.print.template_name = "Sheet".into(); + click(&mut h, "button:printSaveTemplate"); + assert_eq!(template_folders(&h), [("Sheet".into(), Some("Weddings".into()))], "the Folder selector was not touched"); + assert_eq!(text_in(&h, "combo:printSaveFolder"), ["Weddings"], "the Folder selector shows the template's folder"); + click(&mut h, "combo:printSaveFolder"); + click(&mut h, "item:printSaveFolder-0"); + assert_eq!(text_in(&h, "combo:printSaveFolder"), ["User Templates"], "the Folder selector shows the folder picked"); + click(&mut h, "button:printSaveTemplate"); + assert_eq!(template_folders(&h), [("Sheet".into(), None)], "User Templates was picked"); +} + +#[test] +fn a_template_dragged_onto_a_folder_moves_there() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let settings = h.app.session.print_templates[0].settings.clone(); + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + assert_eq!(h.app.session.print_templates[0].settings, settings, "only the folder changes"); + assert!(h.app.ui.print.dragging_template.is_none()); + // and back onto User Templates + drag_onto(&mut h, "printTemplate-0", "printTemplateFolder-0"); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + // a drop anywhere else leaves it where it is + drag(&mut h, "printTemplate-0", 0.0, 300.0); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.dragging_template.is_none()); +} + +#[test] +fn a_templates_menu_moves_it_and_a_folders_menu_renames_and_deletes() { + let mut h = demo(Services::default()); + open_print(&mut h); + cmd(&mut h, "print.template.folder.create", json!({"name": "Weddings"})); + cmd(&mut h, "print.template.save", json!({"name": "Plain"})); + let r = h.request("ui.clickWidget", json!({"id": "printTemplate-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert_eq!(h.request("ui.hoverWidget", json!({"id": "item:printTemplateMoveMenu-0"}), T)["ok"], true); + h.settle(T); + click(&mut h, "item:printTemplateMove-0-1"); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Weddings".into()))]); + + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderRename-1"); + assert_eq!(h.app.ui.print.folder_edit.as_ref().and_then(|e| e.from.as_deref()), Some("Weddings")); + h.app.ui.print.folder_edit.as_mut().unwrap().name = "Family".into(); + click(&mut h, "button:printFolderOk"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + assert_eq!(template_folders(&h), [("Plain".into(), Some("Family".into()))]); + + // Delete Folder asks first; its templates then go to User Templates + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-1", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + click(&mut h, "item:printFolderDelete-1"); + assert_eq!(h.app.session.print_template_folders, ["Family"], "nothing is deleted before the confirmation"); + click(&mut h, "button:printFolderDeleteCancel"); + assert_eq!(h.app.session.print_template_folders, ["Family"]); + h.app.ui.print.delete_folder = Some("Family".into()); + h.settle(T); + click(&mut h, "button:printFolderDeleteConfirm"); + assert!(h.app.session.print_template_folders.is_empty()); + assert_eq!(template_folders(&h), [("Plain".into(), None)]); + assert!(h.app.ui.print.delete_folder.is_none()); + + // User Templates has New Folder… but no Rename or Delete + let r = h.request("ui.clickWidget", json!({"id": "printTemplateFolder-0", "button": "right"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert!(has(&h, "item:printFolderNew-0")); + assert!(!has(&h, "item:printFolderRename-0") && !has(&h, "item:printFolderDelete-0")); +} + #[test] fn template_files_need_the_hosts_file_dialogs() { let mut h = demo(Services::default()); diff --git a/crates/ui-egui/src/tests/rules_reorder.rs b/crates/ui-egui/src/tests/rules_reorder.rs new file mode 100644 index 0000000000..3e30fe5a4a --- /dev/null +++ b/crates/ui-egui/src/tests/rules_reorder.rs @@ -0,0 +1,602 @@ +//! Reordering rules and groups in the smart-album rule editor: the grip at the start of each row, +//! dragged with the pointer or moved with the arrow keys. Every move here is made with real pointer +//! and key events, and each test says what the person sees. + +use std::time::Duration; + +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2}; +use lightcraft_catalog::{Rule, RuleSet}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::panels::rules_reorder::grip_id; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn rule(n: u32) -> Value { + json!({"field": "rating", "op": "is", "value": n}) +} + +fn group(rules: Vec) -> Value { + json!({"group": {"match": "any", "rules": rules}}) +} + +/// The rule editor of a new smart album holding `rules`, in a window with room for them. +fn editor(rules: Vec) -> Headless { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 1000.0], 1.0); + let r = h.request("engine.execute", json!({"command": "dialog.smartAlbum", "params": {"name": "Order"}}), T); + assert_eq!(r["ok"], true, "{r}"); + set_rules(&mut h, rules); + h +} + +fn set_rules(h: &mut Headless, rules: Vec) { + let Some(crate::state::Dialog::SmartRules { rules: r, .. }) = &mut h.app.ui.dialog else { panic!("no rule editor") }; + *r = serde_json::from_value(json!({"rules": rules})).unwrap(); + h.settle(SETTLE); +} + +fn rules(h: &Headless) -> RuleSet { + let Some(crate::state::Dialog::SmartRules { rules, .. }) = &h.app.ui.dialog else { panic!("no rule editor") }; + rules.clone() +} + +/// The rules as the editor shows them, each by its rating, each group in parentheses: `1 (2 3) 4`. +fn shape(h: &Headless) -> String { + fn of(rs: &RuleSet) -> String { + let parts: Vec = rs + .rules + .iter() + .map(|r| match r { + Rule::Field { value, .. } => value.to_string(), + Rule::Group { group } => format!("({})", of(group)), + }) + .collect(); + parts.join(" ") + } + of(&rules(h)) +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().rev().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +/// The grip of the row with salt `salt` (`rules-1-0`: the first rule of the second row's group). +fn grip(h: &Headless, salt: &str) -> Rect { + widget(h, &format!("ruleGrip:{salt}")) +} + +/// A point on the upper half of a row, where a drop goes before it. +fn above(r: Rect) -> Pos2 { + r.center() + vec2(40.0, -6.0) +} + +/// A point on the lower half of a row, where a drop goes after it. +fn below(r: Rect) -> Pos2 { + r.center() + vec2(40.0, 6.0) +} + +fn pointer(h: &mut Headless, pos: Pos2, pressed: Option) { + h.app.synthetic.push(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + h.app.synthetic.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } +} + +/// Press on `from` and move to `to` over a few frames, holding the button down. +fn hold(h: &mut Headless, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + h.step(); + for i in 1..=8 { + pointer(h, from + (to - from) * (i as f32 / 8.0), None); + h.step(); + } + h.step(); +} + +fn release(h: &mut Headless, at: Pos2) { + pointer(h, at, Some(false)); + h.step(); + h.settle(SETTLE); +} + +/// A whole drag: press the grip of `from`, move to the lower (`after`) or upper half of the row +/// of `to`, release. +fn drag(h: &mut Headless, from: &str, to: &str, after: bool) { + let from = grip(h, from).center(); + let to = if after { below(grip(h, to)) } else { above(grip(h, to)) }; + hold(h, from, to); + release(h, to); +} + +fn key(h: &mut Headless, key: &str) { + let r = h.request("ui.key", json!({"key": key}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +fn focus(h: &mut Headless, salt: &str) { + h.view.ctx.memory_mut(|m| m.request_focus(grip_id(salt))); + h.settle(SETTLE); +} + +fn focused_is(h: &Headless, salt: &str) -> bool { + h.view.ctx.memory(|m| m.focused()) == Some(grip_id(salt)) +} + +/// The line the editor draws where a dragged row would land (accent, 2 pt wide), if it is drawn. +fn drop_line(h: &Headless) -> Option<(Pos2, Pos2)> { + let accent = crate::theme::Tokens::get(&h.view.ctx).accent; + h.view.painted_shapes().into_iter().find_map(|s| match s { + egui::epaint::Shape::LineSegment { points, stroke } if stroke.width == 2.0 && stroke.color == accent => Some((points[0], points[1])), + _ => None, + }) +} + +fn pill(h: &Headless, text: &str) -> bool { + h.painted_text().iter().any(|t| t == text) +} + +/// Given three rules, when the first rule's grip is dragged below the third, a line shows the drop +/// between the third and the fourth, the dragged rule's name follows the pointer, and releasing +/// moves it there; and dragging a rule up works the same. +#[test] +fn dragging_a_grip_moves_the_rule() { + let mut h = editor(vec![rule(1), rule(2), rule(3), rule(4)]); + for i in 0..4 { + assert!(has(&h, &format!("ruleGrip:rules-{i}")), "row {i} has a grip"); + } + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-2")); + hold(&mut h, from, to); + let (a, b) = drop_line(&h).expect("a line shows where the rule would land"); + assert!(a.y > grip(&h, "rules-2").center().y && a.y < grip(&h, "rules-3").center().y, "between the third and fourth rule: {a:?}"); + assert_eq!(a.y, b.y, "a level line"); + assert!(pill(&h, "Rating is 1"), "the rule's name follows the pointer: {:?}", h.painted_text()); + assert_eq!(h.last_cursor, egui::CursorIcon::Grabbing); + assert_eq!(shape(&h), "1 2 3 4", "nothing moves before the release"); + release(&mut h, to); + assert_eq!(shape(&h), "2 3 1 4"); + assert!(drop_line(&h).is_none() && !pill(&h, "Rating is 1"), "the line and the name are gone"); + // up: the last rule above the first + drag(&mut h, "rules-3", "rules-0", false); + assert_eq!(shape(&h), "4 2 3 1"); +} + +/// Given a grip has the keyboard focus, when the mouse drags a rule's grip below the third, the +/// focus ends on the dragged rule's grip at its new place, whether the focus was on that grip, on +/// another row's grip (which would otherwise keep its place and find another rule there) or +/// nowhere; so the next arrow key moves the same rule. +#[test] +fn a_drop_keeps_the_focus_on_the_moved_rule() { + for start in [Some("rules-0"), Some("rules-1"), None] { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + if let Some(salt) = start { + focus(&mut h, salt); + } + drag(&mut h, "rules-0", "rules-2", true); + assert_eq!(shape(&h), "2 3 1"); + assert!(focused_is(&h, "rules-2"), "the focus went with the rule (started on {start:?})"); + key(&mut h, "ArrowUp"); + assert_eq!(shape(&h), "2 1 3", "the next key moves the same rule (started on {start:?})"); + } +} + +/// Given a grip has the focus and ↓ moves its row, when the key repeats in the very next frame +/// (before the focus lock of the new place applies), the same row moves again: egui doesn't take +/// the repeat for the focus moving to a neighbor. +#[test] +fn a_repeated_arrow_key_right_after_a_move_moves_the_same_row() { + let mut h = editor(vec![rule(1), rule(2), rule(3), rule(4)]); + focus(&mut h, "rules-0"); + let press = |h: &mut Headless, repeat: bool| { + h.events.push(Event::Key { key: egui::Key::ArrowDown, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE }); + h.step(); + }; + press(&mut h, false); + press(&mut h, true); + press(&mut h, true); + h.settle(SETTLE); + assert_eq!(shape(&h), "2 3 4 1", "three presses, three places, all the same row"); + assert!(focused_is(&h, "rules-3")); +} + +/// Given a rule whose number is outside what its field allows (a rating of 9 written by an agent) +/// and the person has clicked into that field, when they drag another row's grip, the drag goes on: +/// the field handing back its focus doesn't make the rules look edited, and the drop moves the row. +#[test] +fn a_drag_survives_a_number_field_that_loses_focus() { + let mut h = editor(vec![json!({"field": "rating", "op": "is", "value": 9}), rule(2), rule(3)]); + let field = widget(&h, "ruleField:rules-0"); + let value = pos2(field.right() + 142.0, field.center().y); + pointer(&mut h, value, Some(true)); + h.step(); + pointer(&mut h, value, Some(false)); + h.step(); + h.settle(SETTLE); + let on = h.view.ctx.memory(|m| m.focused()); + assert!(on.is_some() && on != Some(grip_id("rules-0")), "the number field has the focus: {on:?}"); + let from = grip(&h, "rules-2").center(); + // the dialog changes height when the field hands its text back: aim at the top of the list + let to = above(grip(&h, "rules-0")); + hold(&mut h, from, to); + assert!(drop_line(&h).is_some(), "the drop line shows where the rule would land"); + release(&mut h, to); + let order = shape(&h); + assert!(order.starts_with("3 ") && order.ends_with(" 2"), "the dragged rule went first: {order}"); +} + +/// Dropping a rule where it already is changes nothing and shows no line. +#[test] +fn dropping_a_rule_where_it_is_does_nothing() { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + let from = grip(&h, "rules-1").center(); + let to = below(grip(&h, "rules-1")); + hold(&mut h, from, to); + assert!(drop_line(&h).is_none(), "no line for a drop that changes nothing"); + release(&mut h, to); + assert_eq!(shape(&h), "1 2 3"); +} + +/// Given a group among rules, a rule dropped on a rule inside the group joins it there, and one +/// dropped beside the group leaves it. +#[test] +fn a_rule_is_dragged_into_and_out_of_a_group() { + let mut h = editor(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + drag(&mut h, "rules-0", "rules-1-0", true); + assert_eq!(shape(&h), "(2 1 3) 4", "into the group, after its first rule"); + drag(&mut h, "rules-0-2", "rules-1", false); + assert_eq!(shape(&h), "(2 1) 3 4", "out of it, before the next rule"); + drag(&mut h, "rules-1", "rules-0-1", true); + assert_eq!(shape(&h), "(2 1 3) 4", "and in again, after its last rule"); +} + +/// A group dropped on the rules of another group nests inside it, with its own rules. +#[test] +fn a_group_is_dragged_into_another_group() { + let mut h = editor(vec![group(vec![rule(1)]), group(vec![rule(2)]), rule(3)]); + drag(&mut h, "rules-0", "rules-1-0", true); + assert_eq!(shape(&h), "(2 (1)) 3", "the first group sits in the second, after its rule"); + assert!(has(&h, "ruleGrip:rules-0-1") && has(&h, "ruleGrip:rules-0-1-0"), "drawn nested"); +} + +/// A group left empty by dragging its only rule out goes away, as the rule's own group would. +#[test] +fn a_group_whose_last_rule_is_dragged_out_goes_away() { + let mut h = editor(vec![rule(1), group(vec![rule(2)]), rule(3)]); + drag(&mut h, "rules-1-0", "rules-0", false); + assert_eq!(shape(&h), "2 1 3"); + assert!(!has(&h, "ruleGrip:rules-3"), "and no empty group is left"); +} + +/// A group can't be dropped inside itself: the pointer says so (a not-allowed cursor, a line and a +/// note in the caution colour), the release changes nothing and the dialog stays. +#[test] +fn a_group_cant_be_dropped_inside_itself() { + let mut h = editor(vec![group(vec![rule(1), rule(2)]), rule(3)]); + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-0-0")); + hold(&mut h, from, to); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed); + assert!(pill(&h, "A group can't go inside itself"), "{:?}", h.painted_text()); + assert!(drop_line(&h).is_none(), "the line is not the accent one"); + release(&mut h, to); + assert_eq!(shape(&h), "(1 2) 3"); + assert!(h.app.ui.dialog.is_some()); +} + +/// Groups nest three deep at most (as the + Group button allows): a group whose rules would end up +/// deeper is refused with the reason, and one that fits is not. +#[test] +fn a_drop_that_would_nest_groups_too_deep_is_refused() { + let tall = group(vec![group(vec![group(vec![rule(1)])])]); + let mut h = editor(vec![group(vec![rule(2)]), tall]); + let from = grip(&h, "rules-1").center(); + let to = below(grip(&h, "rules-0-0")); + hold(&mut h, from, to); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed); + assert!(pill(&h, "Groups can't nest any deeper"), "{:?}", h.painted_text()); + release(&mut h, to); + assert_eq!(shape(&h), "(2) (((1)))", "nothing moved"); + // beside the other group, the same drag is fine + let from = grip(&h, "rules-1").center(); + // (above the group's frame, not on its first line) + let to = above(grip(&h, "rules-0")) - vec2(0.0, 7.0); + hold(&mut h, from, to); + assert_ne!(h.last_cursor, egui::CursorIcon::NotAllowed); + release(&mut h, to); + assert_eq!(shape(&h), "(((1))) (2)"); +} + +/// Esc gives a drag up: nothing moves on the release, the dialog stays open, and the Esc after +/// that closes it as usual. +#[test] +fn escape_cancels_a_drag() { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-2")); + hold(&mut h, from, to); + assert!(drop_line(&h).is_some(), "dragging"); + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_some(), "the Esc was the drag's"); + assert!(drop_line(&h).is_none() && !pill(&h, "Rating is 1"), "the drag is over"); + release(&mut h, to); + assert_eq!(shape(&h), "1 2 3", "the release dropped nothing"); + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none(), "the next Esc closes the dialog"); +} + +/// A drag released away from the list drops nothing. +#[test] +fn a_drag_released_outside_the_list_drops_nothing() { + let mut h = editor(vec![rule(1), rule(2)]); + let from = grip(&h, "rules-0").center(); + let to = pos2(40.0, 980.0); + hold(&mut h, from, to); + assert!(drop_line(&h).is_none()); + release(&mut h, to); + assert_eq!(shape(&h), "1 2"); +} + +/// Tab reaches a grip, ↓ and ↑ move its row one place, the focus stays on that row's grip, and at +/// the ends of the list nothing happens. +#[test] +fn arrow_keys_move_the_focused_row_and_the_focus_follows() { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + let mut reached = false; + for _ in 0..4 { + key(&mut h, "Tab"); + if focused_is(&h, "rules-0") { + reached = true; + break; + } + } + assert!(reached, "Tab gets to the first row's grip"); + key(&mut h, "ArrowUp"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-0")), ("1 2 3", true), "the top stays"); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1")), ("2 1 3", true), "moved down, focus with it"); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-2")), ("2 3 1", true)); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-2")), ("2 3 1", true), "the end stays"); + key(&mut h, "ArrowUp"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1")), ("2 1 3", true)); + // the keys didn't also move the focus on to another widget, and don't leak to the photo grid + assert!(h.app.ui.dialog.is_some()); +} + +/// At the ends of a group ↑ and ↓ carry the row out of it, one place at a time otherwise. +#[test] +fn arrow_keys_carry_a_row_out_at_the_ends_of_a_group() { + let mut h = editor(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + focus(&mut h, "rules-1-0"); + key(&mut h, "ArrowUp"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1")), ("1 2 (3) 4", true), "out, before the group"); + focus(&mut h, "rules-2-0"); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-2")), ("1 2 3 4", true), "its last rule: out, after the group, which is gone"); + let mut h = editor(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + focus(&mut h, "rules-1-0"); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1-1")), ("1 (3 2) 4", true), "inside, one place"); + key(&mut h, "ArrowDown"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-2")), ("1 (3) 2 4", true), "then out, after the group"); +} + +/// → moves a row into the group above it (at its end) or below it (at its start); ← moves it out +/// of its group, to just after it. +#[test] +fn right_and_left_arrows_move_a_row_into_and_out_of_a_group() { + let mut h = editor(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + focus(&mut h, "rules-2"); + key(&mut h, "ArrowRight"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1-2")), ("1 (2 3 4)", true), "into the group above, at its end"); + key(&mut h, "ArrowLeft"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-2")), ("1 (2 3) 4", true), "out, after the group"); + focus(&mut h, "rules-0"); + key(&mut h, "ArrowRight"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-0-0")), ("(1 2 3) 4", true), "into the group below, at its start"); + key(&mut h, "ArrowLeft"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1")), ("(2 3) 1 4", true)); + key(&mut h, "ArrowLeft"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-1")), ("(2 3) 1 4", true), "at the top level ← does nothing"); + // a group moves the same way + let mut h = editor(vec![group(vec![rule(1)]), group(vec![rule(2)])]); + focus(&mut h, "rules-1"); + key(&mut h, "ArrowRight"); + assert_eq!((shape(&h).as_str(), focused_is(&h, "rules-0-1")), ("(1 (2))", true), "a group into the group above"); +} + +/// → doesn't push a group deeper than groups go; nothing moves. +#[test] +fn right_arrow_respects_the_depth_limit() { + let tall = group(vec![group(vec![group(vec![rule(1)])])]); + let mut h = editor(vec![tall, group(vec![rule(2)])]); + focus(&mut h, "rules-0"); + key(&mut h, "ArrowRight"); + assert_eq!(shape(&h), "(((1))) (2)"); + assert!(focused_is(&h, "rules-0")); +} + +/// A group's rows keep their problems wherever they go: the mark under a rule that can't mean +/// anything follows the rule, and OK stays refused until it is fixed. +#[test] +fn a_rules_problem_follows_it() { + let bad = json!({"field": "captureDate", "op": "is", "value": "banana"}); + let mut h = editor(vec![rule(1), bad, rule(3)]); + assert!(has(&h, "ruleProblem:rules-1") && !has(&h, "ruleProblem:rules-0")); + drag(&mut h, "rules-1", "rules-0", false); + assert_eq!(rules(&h).rules.len(), 3); + h.settle(SETTLE); + assert!(has(&h, "ruleProblem:rules-0") && !has(&h, "ruleProblem:rules-1"), "the mark moved with the rule"); + focus(&mut h, "rules-0"); + key(&mut h, "ArrowDown"); + h.settle(SETTLE); + assert!(has(&h, "ruleProblem:rules-1") && !has(&h, "ruleProblem:rules-0"), "and with the arrow keys"); +} + +/// The rows that read as buttons to a screen reader, by name. +fn spoken(rules: Vec) -> Vec { + let view = crate::headless::HeadlessView::new(); + view.ctx.enable_accesskit(); + let mut rs: RuleSet = serde_json::from_value(json!({"rules": rules})).unwrap(); + let env = crate::panels::rules_editor::Env::default(); + let mut found = Vec::new(); + for _ in 0..3 { + let raw = crate::headless::HeadlessView::raw_input(vec2(900.0, 700.0), 1.0, 0.0, vec![]); + let mut out = view.ctx.run_ui(raw, |ui| crate::panels::rules_editor::edit(ui, &mut rs, "rules", 0, &[], &env)); + out.textures_delta.clear(); + if let Some(update) = out.platform_output.accesskit_update.take() { + found = update + .nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Button) + .filter_map(|(_, n)| n.label().map(str::to_string)) + .filter(|l| l.ends_with("Move with the arrow keys")) + .collect(); + } + } + found +} + +/// A grip is a focusable button named with the row's place and what it says. +#[test] +fn a_grip_is_named_for_its_row() { + let names = spoken(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + for n in [ + "Rule 1 of 3: Rating is 1. Move with the arrow keys", + "Group 2 of 3: match any, 2 inside. Move with the arrow keys", + "Rule 1 of 2: Rating is 2. Move with the arrow keys", + "Rule 2 of 2: Rating is 3. Move with the arrow keys", + "Rule 3 of 3: Rating is 4. Move with the arrow keys", + ] { + assert!(names.iter().any(|x| x == n), "no grip named {n:?} in {names:?}"); + } +} + +/// OK saves the rules in the order the editor shows, as one undo step like any edit of the rules. +#[test] +fn ok_saves_the_new_order_in_one_undo_step() { + let mut h = editor(vec![rule(1), group(vec![rule(2), rule(3)]), rule(4)]); + drag(&mut h, "rules-0", "rules-2", true); + assert_eq!(shape(&h), "(2 3) 4 1"); + focus(&mut h, "rules-0"); + key(&mut h, "ArrowDown"); + assert_eq!(shape(&h), "4 (2 3) 1"); + let undo = h.app.session.undo.len(); + let r = h.request("ui.clickWidget", json!({"id": "button:dialogOk"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none(), "saved"); + assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step for the whole reorder"); + let album = h.app.session.catalog.albums().find(|a| a.name == "Order").expect("the album").clone(); + let saved = album.smart.as_ref().and_then(|f| f.rule_set.clone()).expect("rules"); + let order: Vec = saved + .rules + .iter() + .map(|r| match r { + Rule::Field { value, .. } => value.to_string(), + Rule::Group { group } => format!("g{}", group.rules.len()), + }) + .collect(); + assert_eq!(order, ["4", "g2", "1"].map(String::from), "{order:?}"); +} + +/// A row moved out of nested groups may leave the group it goes into empty for a moment: ← on the +/// only rule of a group in a group moves it into the outer one. +#[test] +fn a_rule_alone_in_a_nested_group_can_leave_it() { + let mut h = editor(vec![group(vec![group(vec![rule(1)])])]); + focus(&mut h, "rules-0-0-0"); + key(&mut h, "ArrowLeft"); + assert_eq!(shape(&h), "(1)"); + assert!(focused_is(&h, "rules-0-0")); +} + +/// A drag whose rules are replaced under it (another dialog opened by an agent) drops nothing. +#[test] +fn a_drag_whose_dialog_was_replaced_drops_nothing() { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-2")); + hold(&mut h, from, to); + let r = h.request("engine.execute", json!({"command": "dialog.smartAlbum", "params": {"name": "Other"}}), T); + assert_eq!(r["ok"], true, "{r}"); + set_rules(&mut h, vec![rule(7), rule(8), rule(9)]); + pointer(&mut h, to, None); + h.step(); + release(&mut h, to); + assert_eq!(shape(&h), "7 8 9"); +} + +/// A drag whose dialog is replaced by another one that holds the very same rules (an agent opens the +/// smart album being edited again) drops nothing: the rules can't tell the two dialogs apart, so the +/// drag belongs to the dialog it started in. +#[test] +fn a_drag_whose_dialog_was_replaced_by_one_with_the_same_rules_drops_nothing() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 1000.0], 1.0); + let rules = json!({"ruleSet": {"rules": [rule(1), rule(2), rule(3)]}}); + let r = h.request("engine.execute", json!({"command": "album.createSmart", "params": {"name": "Same", "rules": rules}}), T); + assert_eq!(r["ok"], true, "{r}"); + let id = r["result"]["id"].as_u64().expect("an album id"); + let open = |h: &mut Headless| { + let r = h.request("engine.execute", json!({"command": "dialog.smartAlbum", "params": {"id": id}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + }; + open(&mut h); + assert_eq!(shape(&h), "1 2 3"); + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-2")); + hold(&mut h, from, to); + open(&mut h); + pointer(&mut h, to, None); + h.step(); + release(&mut h, to); + assert_eq!(shape(&h), "1 2 3", "nothing moved in the dialog that replaced it"); +} + +/// A drag whose dialog is replaced in the very frame after the drag starts (before its rules are +/// compared with the ones it started with) drops nothing in the other dialog either, whether the +/// other dialog has other rules or the same kind of rules with other numbers. +#[test] +fn a_drag_whose_dialog_was_replaced_in_its_first_frames_drops_nothing() { + for (replacement, shown) in [(vec![rule(7), rule(8)], "7 8"), (vec![rule(7), rule(8), rule(9)], "7 8 9")] { + let mut h = editor(vec![rule(1), rule(2), rule(3)]); + let from = grip(&h, "rules-0").center(); + let to = below(grip(&h, "rules-2")); + pointer(&mut h, from, Some(true)); + h.step(); + let mut started = false; + for i in 1..=16 { + pointer(&mut h, from + (to - from) * (i as f32 / 16.0), None); + h.step(); + // the grip takes the focus in the frame the drag starts (the name follows a frame later) + if focused_is(&h, "rules-0") { + started = true; + break; + } + } + assert!(started, "the drag started"); + // the other dialog opens before the next frame is drawn + let other: RuleSet = serde_json::from_value(json!({"rules": replacement})).unwrap(); + h.app.ui.dialog = Some(crate::state::Dialog::smart_rules(None, "Other".into(), other, None)); + h.step(); + // over a place that is valid in the new dialog + let to = below(grip(&h, "rules-1")); + pointer(&mut h, to, None); + h.step(); + h.step(); + release(&mut h, to); + assert_eq!(shape(&h), shown, "nothing moved in the dialog that replaced it"); + } +} diff --git a/crates/ui-egui/src/tests/scan_probes.rs b/crates/ui-egui/src/tests/scan_probes.rs index a8a5bf116f..7496ad85fb 100644 --- a/crates/ui-egui/src/tests/scan_probes.rs +++ b/crates/ui-egui/src/tests/scan_probes.rs @@ -74,6 +74,7 @@ fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() { truncated: false, unreadable: 0, unsupported: 0, + listed: Default::default(), })) .unwrap(); assert!(h.step_until(T, kept), "the probes came back"); diff --git a/crates/ui-egui/src/tests/slideshow.rs b/crates/ui-egui/src/tests/slideshow.rs index 1659005ab7..6d90cf6848 100644 --- a/crates/ui-egui/src/tests/slideshow.rs +++ b/crates/ui-egui/src/tests/slideshow.rs @@ -301,6 +301,315 @@ fn a_manual_slideshow_waits_for_the_arrow_keys() { h.settle(SETTLE); } +#[test] +fn pan_and_zoom_moves_the_photo_inside_its_cell() { + let mut h = grid(); + run(&mut h, "slideshow.layout", json!({"margins": 0.1, "backdropColor": "#ff0000"})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + let r = run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "seed": 3})); + assert_eq!((r["settings"]["panAndZoom"].clone(), r["settings"]["panAndZoomAmount"].clone()), (json!(true), json!(1.0)), "{r}"); + let current = photo_up(&h); + assert!(h.step_until(SETTLE, |h| has_slide(h, current)), "the slide is composed and ready"); + h.step(); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_eq!(s["panAndZoom"], true, "{s}"); + let start = s["view"].clone(); + let w = start.as_array().map(|v| v.iter().filter_map(|x| x.as_f64()).collect::>()).unwrap_or_default(); + assert_eq!(w.len(), 4, "{s}"); + assert!(w[0] >= 0.0 && w[1] >= 0.0 && w[2] <= 1.0 && w[3] <= 1.0 && w[2] - w[0] < 1.0, "a window inside the photo: {s}"); + let moving = h.paint(); + // the backdrop stays where it is + for (x, y) in [(5, 5), (995, 5), (500, 30), (30, 350), (985, 350)] { + assert_eq!(painted(&moving, x, y), [255, 0, 0], "margin at ({x}, {y})"); + } + // playing on, it moves + run(&mut h, "slideshow.togglePause", json!({})); + for _ in 0..240 { + h.step(); + } + assert_eq!(photo_up(&h), current, "the same slide is up"); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_ne!(s["view"], start, "{s}"); + // the photo's cell moves; with an overlay drawn into the slide, the whole slide moves, so an + // overlay crossing the cell's edge stays in one piece + let part = |h: &Headless| { + let tex = h.app.renderer.textures.get(&Slot::Slide(current.into())).unwrap(); + crate::panels::slideshow::moving_part(&h.app, current.into(), tex) + }; + let cell = part(&h); + assert!(cell.min.x > 0.05 && cell.max.x < 0.95 && cell.min.y > 0.05 && cell.max.y < 0.95, "{cell:?}"); + run(&mut h, "slideshow.overlays", json!({"ratingStars": {"enabled": true}})); + assert_eq!(part(&h), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0))); + run(&mut h, "slideshow.overlays", json!({"ratingStars": {"enabled": false}})); + run(&mut h, "slideshow.end", json!({})); + // off: the photo shows whole, so the same slide paints other pixels in its cell + run(&mut h, "slideshow.playback", json!({"panAndZoom": false})); + run(&mut h, "library.select", json!({"ids": [current.0]})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true})); + assert_eq!(photo_up(&h), current); + assert!(h.step_until(SETTLE, |h| has_slide(h, current))); + h.step(); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert_eq!((s["panAndZoom"].clone(), s["view"].clone()), (json!(false), json!(null)), "{s}"); + let still = h.paint(); + let mut changed = 0; + for y in (100..600).step_by(4) { + for x in (100..900).step_by(4) { + if painted(&moving, x, y) != painted(&still, x, y) { + changed += 1; + } + } + } + assert!(changed > 500, "the zoomed photo differs from the whole one ({changed} samples)"); + assert_eq!(painted(&still, 5, 5), [255, 0, 0]); + run(&mut h, "slideshow.end", json!({})); + // the Settings controls + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + reveal(&mut h, "check:settings.slideshowPanAndZoom"); + assert!(latest_widget_rect(&h, "slider:slideshowPanAndZoom").is_some(), "the Low to High slider"); + let r = h.request("ui.clickWidget", json!({"id": "check:settings.slideshowPanAndZoom"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.session.slideshow.pan_and_zoom, "the checkbox goes through slideshow.playback"); + h.settle(SETTLE); +} + +/// While a slide's new render (after a layout change) is on the way, the old texture moves +/// whole: its cell is where the old settings put it, not where the new ones do. +#[test] +fn pan_and_zoom_moves_an_old_render_whole_until_the_new_one_lands() { + let mut h = grid(); + let open = Rc::new(Cell::new(true)); + h.app.renderer.set_offload(Box::new(RenderGate::new(open.clone()))); + run(&mut h, "slideshow.layout", json!({"margins": 0.1})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true, "seed": 3})); + let current = photo_up(&h); + let slot = Slot::Slide(current.into()); + assert!(h.step_until(SETTLE, |h| has_slide(h, current) && h.app.renderer.wanted(slot) == h.app.renderer.textures.get(&slot).map(|t| t.key))); + let part = |h: &Headless| { + let tex = h.app.renderer.textures.get(&slot).unwrap(); + crate::panels::slideshow::moving_part(&h.app, current.into(), tex) + }; + let cell = part(&h); + assert!(cell.min.x > 0.05 && cell.max.x < 0.95, "the photo's cell: {cell:?}"); + // the margins change while the next render is held back + open.set(false); + let old = h.app.renderer.textures.get(&slot).map(|t| t.key); + run(&mut h, "slideshow.layout", json!({"margins": 0.3})); + h.step(); + assert_eq!(h.app.renderer.textures.get(&slot).map(|t| t.key), old, "the old render is still drawn"); + assert_ne!(h.app.renderer.wanted(slot), old, "a new render is on the way"); + assert_eq!(part(&h), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), "the old texture moves whole"); + // the new render lands: its own cell moves again + open.set(true); + assert!(h.step_until(SETTLE, |h| h.app.renderer.textures.get(&slot).map(|t| t.key) != old)); + let cell = part(&h); + assert!(cell.min.x > 0.2 && cell.max.x < 0.8, "the new, smaller cell: {cell:?}"); + run(&mut h, "slideshow.end", json!({})); + h.settle(SETTLE); +} + +/// A slide's time starts only once its render is in, so while it is held back pan and zoom does +/// not ask for every frame, only for one 16 ms later so the render is taken and shown; once the +/// render lands, every frame is drawn. +#[test] +fn pan_and_zoom_draws_every_frame_only_once_its_slide_is_ready() { + let mut h = grid(); + let open = Rc::new(Cell::new(false)); + h.app.renderer.set_offload(Box::new(RenderGate::new(open.clone()))); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "seed": 3})); + let current = photo_up(&h); + let ctx = egui::Context::default(); + let delays = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let seen = delays.clone(); + ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay)); + let raw = egui::RawInput::default(); + let tick = |h: &mut Headless| { + let now = h.time(); + // (the first passes of a context ask for frames at once, which would hide the slideshow's) + for _ in 0..3 { + let _ = ctx.run_logic(&raw, |ctx| crate::panels::slideshow::tick(&mut h.app, ctx, now)); + } + delays.lock().unwrap().clear(); + let _ = ctx.run_logic(&raw, |ctx| crate::panels::slideshow::tick(&mut h.app, ctx, now)); + delays.lock().unwrap().clone() + }; + assert!(!has_slide(&h, current), "the slide's render is held back"); + assert!(play(&h).pan_zoom_moving(h.time()), "the playback counts the slide as moving"); + let got = tick(&mut h); + assert!(!got.contains(&Duration::ZERO), "no frame at once while the slide is not ready: {got:?}"); + // a 60 second slide still asks for a frame soon, for its render to be taken and shown + assert!(got.iter().any(|d| *d <= Duration::from_millis(16)), "a frame soon while the slide is not ready: {got:?}"); + open.set(true); + assert!(h.step_until(SETTLE, |h| has_slide(h, current)), "the render lands"); + let got = tick(&mut h); + assert!(got.contains(&Duration::ZERO), "every frame once it is ready: {got:?}"); + run(&mut h, "slideshow.end", json!({})); + h.settle(SETTLE); +} + +/// A photo cropped to its cell's shape, a very narrow one (aspect 0.01) and a very wide one +/// (aspect 50): the part that moves is the photo's visible part of the slide, so the backdrop +/// beside it stays where it is and the photo still shows inside it. +#[test] +fn pan_and_zoom_moves_only_the_visible_photo_at_any_aspect() { + let mut h = grid(); + run(&mut h, "slideshow.layout", json!({"margins": 0.1, "backdropColor": "#ff0000"})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + let id = h.app.session.visible_cloned()[0]; + let own = h.app.session.slide_photo_aspect(id).unwrap(); + // 70 px margins around a 860 × 560 cell + for aspect in [860.0 / 560.0, 0.01, 50.0] { + let mut d = (*h.app.session.develop_of(id).expect("settings")).clone(); + d.crop.geometry.rect = if aspect < own { + let f = aspect / own; + lightcraft_geom::Rect::new(0.5 - f / 2.0, 0.0, 0.5 + f / 2.0, 1.0) + } else { + let f = own / aspect; + lightcraft_geom::Rect::new(0.0, 0.5 - f / 2.0, 1.0, 0.5 + f / 2.0) + }; + h.app.session.set_develop(id, d, "Test").expect("edit"); + let shown = h.app.session.slide_photo_aspect(id).unwrap(); + assert!((shown / aspect - 1.0).abs() < 0.01, "{aspect}: the crop shows at {shown}"); + run(&mut h, "library.select", json!({"ids": [id.0]})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true, "seed": 3})); + assert_eq!(photo_up(&h), id); + let slot = Slot::Slide(id.into()); + assert!(h.step_until(SETTLE, |h| has_slide(h, id) && h.app.renderer.wanted(slot) == h.app.renderer.textures.get(&slot).map(|t| t.key))); + h.step(); + let s = run(&mut h, "slideshow.togglePause", json!({})); + assert!(s["view"].is_array(), "{aspect}: a manual slideshow holds the photo at its start view: {s}"); + let tex = h.app.renderer.textures.get(&slot).unwrap(); + assert_eq!(tex.size, [1000, 700]); + let v = lightcraft_slideshow::layout(&h.app.session.slide_layout, shown, 1000, 700).visible; + let part = crate::panels::slideshow::moving_part(&h.app, id.into(), tex); + let px = |r: egui::Rect| [r.min.x * 1000.0, r.min.y * 700.0, r.max.x * 1000.0, r.max.y * 700.0]; + for (got, want) in px(part).into_iter().zip([v.x0, v.y0, v.x1, v.y1]) { + assert!((f64::from(got) - want).abs() < 0.01, "{aspect}: moves {part:?}, the photo shows at {v:?}"); + } + if aspect < 1.0 { + assert!(v.width() < 8.0, "{aspect}: a strip of {v:?}"); + } else if aspect > 10.0 { + assert!(v.height() < 20.0, "{aspect}: a strip of {v:?}"); + } else { + assert!((v.width() - 860.0).abs() <= 1.0 && (v.height() - 560.0).abs() <= 1.0, "{aspect}: fills its cell: {v:?}"); + } + let img = h.paint(); + let (cx, cy) = (((v.x0 + v.x1) / 2.0) as usize, ((v.y0 + v.y1) / 2.0) as usize); + assert_ne!(painted(&img, cx, cy), [255, 0, 0], "{aspect}: the photo shows in its part"); + let (x0, y0, x1, y1) = (v.x0 as usize, v.y0 as usize, v.x1 as usize, v.y1 as usize); + // the backdrop just beside the photo stays (away from the top center, where the + // slideshow's controls draw over it) + let (sx, sy) = (if v.width() > 200.0 { x0 + 100 } else { cx }, if v.height() > 200.0 { y0 + 100 } else { cy }); + let mut beside = vec![(x0 - 3, sy), (x1 + 2, sy)]; + if v.width() > 200.0 { + beside.extend([(sx, y0 - 3), (sx, y1 + 2)]); + } + for (x, y) in beside { + assert_eq!(painted(&img, x, y), [255, 0, 0], "{aspect}: backdrop at ({x}, {y})"); + } + // and no backdrop shows inside the photo's edges + if aspect > 1.0 && aspect < 10.0 { + for (x, y) in [(x0 + 3, sy), (x1 - 4, sy), (sx, y0 + 3), (sx, y1 - 4)] { + assert_ne!(painted(&img, x, y), [255, 0, 0], "{aspect}: photo at ({x}, {y})"); + } + } + run(&mut h, "slideshow.end", json!({})); + } + h.settle(SETTLE); +} + +/// A crop so narrow (aspect 0.001) or so wide (aspect 1000) that the photo's render is 1 px +/// across: the slide is laid out with that render's size, not the crop's aspect, so the part that +/// moves is the strip of the slide the photo was composed into, not the whole cell around it. +#[test] +fn pan_and_zoom_moves_the_composed_strip_of_an_extreme_crop() { + let mut h = grid(); + h.app.renderer.keep_pixels = true; + run(&mut h, "slideshow.layout", json!({"margins": 0.1, "backdropColor": "#ff0000"})); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true, "panAndZoomAmount": 1.0})); + let id = h.app.session.visible_cloned()[0]; + let own = h.app.session.slide_photo_aspect(id).unwrap(); + for aspect in [0.001, 1000.0] { + let mut d = (*h.app.session.develop_of(id).expect("settings")).clone(); + d.crop.geometry.rect = if aspect < own { + let f = aspect / own; + lightcraft_geom::Rect::new(0.5 - f / 2.0, 0.0, 0.5 + f / 2.0, 1.0) + } else { + let f = own / aspect; + lightcraft_geom::Rect::new(0.0, 0.5 - f / 2.0, 1.0, 0.5 + f / 2.0) + }; + h.app.session.set_develop(id, d, "Test").expect("edit"); + run(&mut h, "library.select", json!({"ids": [id.0]})); + run(&mut h, "view.slideshow", json!({"interval": 60, "fadeDuration": 0, "manual": true, "seed": 3})); + assert_eq!(photo_up(&h), id); + let slot = Slot::Slide(id.into()); + assert!(h.step_until(SETTLE, |h| has_slide(h, id) && h.app.renderer.wanted(slot) == h.app.renderer.textures.get(&slot).map(|t| t.key))); + h.step(); + let tex = h.app.renderer.textures.get(&slot).unwrap(); + assert_eq!(tex.size, [1000, 700]); + // where the photo is in the composed slide: every pixel that is not the red backdrop + let px = tex.pixels.as_ref().expect("the slide's pixels"); + let [w, rows] = px.size; + let (mut x0, mut y0, mut x1, mut y1) = (w, rows, 0, 0); + for y in 0..rows { + for x in 0..w { + let c = px.pixels[y * w + x]; + if !(c.r() > 240 && c.g() < 15 && c.b() < 15) { + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + } + } + } + assert!(x1 > x0 && y1 > y0, "{aspect}: the photo shows in the slide"); + assert!((x1 - x0).min(y1 - y0) <= 2, "{aspect}: a strip of {x0}..{x1} × {y0}..{y1}"); + let part = crate::panels::slideshow::moving_part(&h.app, id.into(), tex); + let got = [part.min.x * 1000.0, part.min.y * 700.0, part.max.x * 1000.0, part.max.y * 700.0]; + for (g, want) in got.into_iter().zip([x0, y0, x1, y1]) { + assert!((g - want as f32).abs() <= 1.0, "{aspect}: moves {got:?}, the photo is at {:?}", [x0, y0, x1, y1]); + } + run(&mut h, "slideshow.end", json!({})); + } + h.settle(SETTLE); +} + +/// The amount set on the Low to High slider is saved with the library: the slider writes the +/// live value as it moves, which leaves `slideshow.playback` nothing to change when it ends. +#[test] +fn the_pan_and_zoom_amount_from_the_slider_is_there_when_the_library_reopens() { + struct Folder(std::path::PathBuf); + impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = Folder(std::env::temp_dir().join(format!("lc-ui-pan-zoom-amount-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + let mut session = lightcraft_engine::Session::new().with_fs(); + session.open_library(&dir.0, false).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1000.0, 700.0], 1.0); + h.step(); + run(&mut h, "slideshow.playback", json!({"panAndZoom": true})); + let before = h.app.session.slideshow.pan_and_zoom_amount; + run(&mut h, "view.slideshowOptions", json!({})); + h.step(); + let slider = reveal(&mut h, "slider:slideshowPanAndZoom"); + let r = h.request("ui.dragWidget", json!({"id": "slider:slideshowPanAndZoom", "toX": slider.left(), "toY": slider.center().y}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let amount = h.app.session.slideshow.pan_and_zoom_amount; + assert!(amount < before - 0.1, "the slider moved the amount from {before} to {amount}"); + h.settle(SETTLE); + drop(h); + let mut again = lightcraft_engine::Session::new().with_fs(); + again.open_library(&dir.0, false).unwrap(); + assert!(again.slideshow.pan_and_zoom, "the checkbox's setting is saved"); + assert_eq!(again.slideshow.pan_and_zoom_amount, amount, "the slider's amount is saved"); +} + #[test] fn random_order_starts_at_the_selection_and_is_fixed_by_the_seed() { let order = |seed: u64| { diff --git a/crates/ui-egui/src/tests/zoom.rs b/crates/ui-egui/src/tests/zoom.rs index 518bd477af..5253d40a3e 100644 --- a/crates/ui-egui/src/tests/zoom.rs +++ b/crates/ui-egui/src/tests/zoom.rs @@ -81,6 +81,7 @@ fn a_pending_crop_or_rotation_does_not_reuse_the_old_textures_aspect() { ms: 0.0, quick: None, pixels: None, + slide_photo: None, }, ); edit(&mut h, |d| d.crop.geometry.rect = lightcraft_geom::Rect::new(0.25, 0.2, 0.75, 0.2 + 1.0 / 3.0)); diff --git a/docs/ai-masks.md b/docs/ai-masks.md index 8c2034ab59..a10933a3f9 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -48,13 +48,13 @@ In the Masking panel (M): so small objects get 5–10× finer edges than one pass over the whole photo gives. The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and -look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the -model after launch). That starts in the background as soon as you pick Object; after it, each -click takes ~35 ms and each description ~0.6 s. Everything the model does runs on its own worker -thread: the window stays responsive, a click shows its dot at once and the selection follows -when it's computed ("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is -unloaded after 10 minutes without use (it takes several GB of memory) and loaded again when -needed. +look: ~3 s on an Apple M4 Pro, ~11 s on the CPU of a 12-core Ryzen 9 3900X, plus a one-time ~6 s +for compiling GPU kernels and loading the model after launch). That starts in the background as +soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s +and ~2 s on that CPU). Everything the model does runs on its own worker thread: the window stays +responsive, a click shows its dot at once and the selection follows when it's computed +("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is unloaded after 10 +minutes without use (it takes several GB of memory) and loaded again when needed. The result is stored with the mask: the model's 288 × 288 mask logits over the uncropped photo (quantized, compressed, ~10–30 KB). Renders and exports sample them at any resolution and never @@ -261,6 +261,18 @@ wait and return the result (when built with the `sam` feature; the default CLI h - Accuracy: `crates/segment/tests/it/reference.rs` compares every stage against the Python reference (`tools/sam3_reference.py`); on Metal the backbone matches to 7e-5 relative error and masks to ~5e-5. f16 was tried and rejected (overflow, ~7 % faster). +- Speed on the CPU: candle runs elementwise operations and layout copies on one thread, batched + matrix products one pair after another and transposed convolutions one output channel at a + time. `cpu.rs` fuses the bias adds, activations, rotary encoding, window partitioning, head + split/merge, the detector's box bias and the pixel decoder's GroupNorm into parallel kernels + (the same operations in the same order: bit-identical), runs attention as one task per batch, + head and block of query rows (256 KB of scores, so they stay in the core's cache), and the + necks' 2 × 2 transposed convolutions as one matrix product each. Those two change how gemm + blocks its sums, so results move by float rounding only, as they do between two CPUs (gemm + picks its blocking from the cache sizes): against the tensor operations the backbone differs + by 1e-5 relative and the masks by at most 7e-4, and fewer than 4e-7 of the mask pixels change + side. On a 12-core Ryzen 9 3900X: encode ~37 → ~11 s, a description ~6 → ~2 s, getting ready + for clicks ~2.3 → ~0.8 s. - The engine feature `sam` (on in the desktop app, off for web and CLI) gates the model; without it the commands report that the build has no AI masks. diff --git a/docs/localization.md b/docs/localization.md index 446d914892..ce0e739d0e 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -50,7 +50,9 @@ are in [`localization-zh-hans.md`](localization-zh-hans.md), [`localization-zh-h Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never here; a missing face is added there, not worked around in this repository. Sentence-cased messages go through `i18n::upper_first`, which leaves Georgian lowercase (upper-casing Mkhedruli would make - Mtavruli). + Mtavruli). Menu paths in messages use → ("View → Clear Filters"), in English and in + translations: Inter has no ▸ or ▾, so those paint as boxes (issue #1950). + `source_strings_use_paintable_symbols` checks every symbol in the code's string literals. 4. Run `cargo xtask ci` (it includes `fmt`, `clippy`, the tests, `parity` and the wasm check). ## How a message is found @@ -123,4 +125,5 @@ Help ▸ What's New shows `docs/whats-new.md`, and each of its lines (a heading, bullet, without the `- ` or `### `) is looked up like any message, so a catalog can translate the notes line by line (German does). A line that is re-wrapped or edited no longer matches its translation and shows in English until the catalog is updated; the translation gaps report counts the untranslated -lines. +lines. The notes may write menu paths with ▸ like the other docs: the dialog shows it as → (and the +activity stack's ✕ as ×, the sidebar's + as +), since Inter has none of them. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 031b419d16..574aef2ff0 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -120,7 +120,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. A capture time that doesn't fully read (cut short, or text after it) is left as it is and counted (`unreadable`); it can't anchor a set that moves other photos, and set alone repairs it. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked; reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -712,7 +712,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`), `crates/ui-egui/src/tests/move_folder.rs` | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken); Move Folder To… (here and in Folders) asks for the destination in a folder dialog that doesn't hold up the window (issue #3140); the rows of the standard places themselves (Pictures, Desktop, Downloads, Home) offer neither Rename Folder… nor Move Folder To…, while the folders inside them and the ones kept with Browse Folder… do, starting from their real name; `folder.rename` and `folder.move` refuse the home folder and its Pictures, Desktop and Downloads for every caller | | LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge, except on a row indented so far that its count (or colour dot) would cover its name: that count follows the name, wholly past the edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, which is kept only once the move has started, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-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-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; rules and groups are reordered from a grip at the start of each row (`crates/ui-egui/src/dialogs/rules_editor/rules_move.rs`, `crates/ui-egui/src/dialogs/rules_editor/rules_reorder.rs`, `crates/ui-egui/src/tests/rules_reorder.rs`): dragging it shows a line where the row would land and Esc gives the drag up, a group can't be dropped inside itself or where groups would nest deeper than three levels (a not-allowed cursor and the reason), a group a move leaves empty goes away; from the keyboard, Tab to the grip, then ↑ / ↓ move the row one place (out of a group at its ends), → into the group next to it and ← out of its group, the focus staying on the moved row; the grip is named for its place (“Rule 2 of 4: Rating is ≥ 3. Move with the arrow keys”), and OK saves the order shown, as the same one undo step | | LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | | | LRC-LIB-FILTERBAR | Library filter bar | P1 | ✅ | `cmd:view.filterBar`, `cmd:filter.applyPreset`, `cmd:library.filter` (`flags`, `labels`, `ruleSet`), `crates/ui-egui/src/panels/filterbar.rs` | rating/flag (several flags at once = any of them)/label (several labels at once = any of them)/kind/edited/camera/lens/keyword, clear, save as smart album, filter presets; the filter stays as you change albums (an album the filter held is replaced by the album you show; always locked, as in the desktop app); arbitrary conditions via the smart-album rule editor | | LRC-LIB-STACKS | Stacks (full) | P1 | ✅ | `crates/catalog/src/stacks.rs`, `cmd:stack.group`, `cmd:stack.split`, `cmd:stack.moveUp`, `cmd:stack.moveDown` | group / ungroup / toggle / set top / remove / auto by time / split / move up and down | @@ -765,7 +765,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-SS-BACKDROP | Slideshow backdrop | P2 | ✅ | `cmd:slideshow.layout`, `path:crates/slideshow/src/compose.rs` | Background colour, Color Wash (a gradient from a second colour, full at the side its angle points to, at an opacity), Background Image (a library photo filling the slide at an opacity: "Use selected photo" in Settings ▸ Slideshow, `backgroundImage` in `slideshow.layout`; rendered once and shared by the slides). In the web build the composition runs on the main thread when a worker's render comes back | | LRC-SS-TITLES | Slideshow titles | P2 | 🟡 | `cmd:slideshow.titles`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_title.rs`, `path:crates/ui-egui/src/dialogs/settings/slide_titles.rs` | Intro screen and ending screen, each on or off (library preference, `slideshow.titles`; Settings ▸ Slideshow ▸ Titles): a background colour and, centred on it, the identity plate of the Overlays section (its text or image; Add Identity Plate) or the screen's own line of text, in the plate's colour or an override colour, at a scale (height as a share of the slide's shorter side; text wider than the slide shrinks to fit), for its own duration (default: the slide duration). Titles are items of the playback timeline: composed off the UI thread by the same composer at the screen's size, prepared ahead, waited for and faded like slides; the intro plays once before the first photo, the ending after the last photo when repeat is off; random order never moves them; ←/→ step across them; they never change the selection and the control bar shows Intro / End instead of n / N. `slideshow.preview {title}` renders a screen; the Settings preview shows Photo / Intro / Ending. An empty view still refuses to play ("no photos to show"). Missing: Classic's exact behaviour with Repeat on is not verified (we never show the ending, and show the intro only at the start, while repeating), the Identity Plate Editor's styled text (Inter SemiBold only), override colour leaves an image plate's colours alone, the Slideshow module's Titles panel (settings live in Settings ▸ Slideshow). Slideshow export (LRC-SS-EXPORT) includes them: a PDF page / JPEG each, and in video they hold and fade like slides | | LRC-SS-MUSIC | Slideshow music | P2 | ⬜ | | | -| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan & zoom, choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | +| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end`, `path:crates/slideshow/src/motion.rs` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration), pan and zoom (`panAndZoom`, off by default, with a Low–High amount `panAndZoomAmount` 0–1, default 0.5: each photo moves at constant speed from one window of itself to another over its slide's time, its fade in included, zooming in or out between about 1.0025× and 1.01× at Low and 1.03× and 1.12× at High, on a path from the playback seed, the pass and the photo, so every photo and every pass has its own path and a seed replays it; the photo moves inside its image cell and the backdrop stays still, except that with overlays on the whole slide moves with them; title screens don't move; pause freezes it, a photo fading out stays at its end view, a manual slideshow holds each photo at its start view, a single repeating photo starts each new path where the last one ended; these motion rules are LightCraft's own). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan and zoom in exports (LRC-SS-EXPORT), choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) | | LRC-SS-EXPORT | Slideshow export | P2 | 🟡 | `cmd:slideshow.export`, `cmd:slideshow.exportStatus`, `cmd:dialog.slideshowExport`, `cmd:app.slideshowExport`, `path:crates/engine/src/slideshow_export.rs`, `path:crates/codecs/src/video.rs`, `path:crates/ui-egui/src/dialogs/slideshow_export.rs` | View ▸ Export Slideshow… (and Export PDF / JPEG / Video in Settings ▸ Slideshow): the photos in view as their composed slides (layout, overlays) between the intro and ending screens that are on, in view order. **PDF**: one page per slide at 1024 / 1920 / 3840 px (any 64–8192 by command; page = slide pixels in points, aspect from the aspect preview, "screen" = 16:9), JPEG quality, each page carrying the slide duration and a fade transition for presentation mode, "Automatically show full screen" (`/PageMode /FullScreen`). **JPEG**: `-001.jpg`… in a new folder. **Video**: AV1 (rav1e, fast preset) in MP4 or WebM written by our own muxers, 720p / 1080p (64–2160 by command), 24 / 30 fps (25 / 60 by command); each slide held for its duration (one long sample: variable frame rate) and fades rendered as blended frames (crossfade or through the fade colour); at most 2 hours. Runs in the background with a row in the activity stack (frames or slides done, ✕ cancels); files are written as `.part` and renamed when complete, so a cancelled or failed export leaves nothing; a photo that can't be rendered is skipped with a warning. Missing: H.264 (Classic's codec; patents, no pure-Rust encoder), audio / music in the video (LRC-SS-MUSIC), random order and pan & zoom in exports, the PDF's per-page fades follow the viewer (Acrobat), export presets, Classic's export dialog sizes beyond these, the web build (no export) | | LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | ✅ | `cmd:dialog.print`, `cmd:print.set`, `cmd:print.get`, `cmd:print.exportPdf`, `cmd:export.contactSheet`, `crates/ui-egui/src/dialogs/print_view.rs` | File → Print… (⌘P): Single Image, Contact Sheet, Picture Package and Custom Package, one page preview each; also `print.*` commands for the CLI, control channel and MCP; the older File → Contact Sheet PDF stays | | LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | ✅ | `cmd:print.set`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | Zoom to Fill Frame, Rotate to Fit, Photo Border (width, colour; package styles) and Inner Stroke (width in points, colour) in the dialog, drawn in the preview and in the PDF; pixel-tested | @@ -774,7 +774,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-PRINT-CELLS | Picture-package cells | P2 | ✅ | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout`, `crates/ui-egui/src/dialogs/print_view.rs` | add cells at standard or custom sizes, drag and resize them on the page preview (snap to cells, grid or off), Send to Back / Backward / Forward / Bring to Front, a photo per cell (Custom Package), Auto Layout packing, New Page, Clear Layout; no Auto Layout for Custom Package | | LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | page background colour and margins in the Print dialog; Page Options for Single Image and Contact Sheet (`print.set {page: {pageNumbers, pageInfo, cropMarks}}`, checkboxes in the Page section, kept in templates): the page number at the bottom right, the print settings line (sharpening, profile, resolution) at the bottom left, crop marks at each photo's corners, drawn in the preview and in the PDF (`print::compose::tests::crop_marks_sit_outside_each_photo_corner`); filename captions in the contact-sheet PDF; no identity plate, watermark, photo info or package Cut Guides | | LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:print.set`, `cmd:print.exportPdf`, `crates/ui-egui/src/dialogs/print_view.rs`, `crates/engine/src/print_color.rs`, `crates/codecs/src/print.rs`, `crates/engine/src/pdf.rs`, `cmd:export.contactSheet` | the Print dialog's Print Job panel and `print.set {job}`: print resolution 72–720 ppi; colour management: Managed by Printer (sRGB / Adobe RGB, profile embedded) or a printer / paper ICC profile (RGB, CMYK or grey) converted here and named as the PDF's output intent; perceptual / relative colorimetric with black point compensation; Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte / Glossy; 16-bit (or 8-bit) ICC-tagged lossless page images; a bad profile fails before rendering (`tests_print::export_pdf_with_a_printer_profile`). The contact sheet keeps its fixed 150 dpi sRGB JPEG PDF. Missing: printing to a printer (OS print dialog), JPEG file output, Draft Mode | -| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); no built-in templates, no folders | +| LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `cmd:print.template.export`, `cmd:print.template.import`, `cmd:print.template.move`, `cmd:print.template.folder.create`, `cmd:print.template.folder.rename`, `cmd:print.template.folder.delete`, `crates/ui-egui/src/dialogs/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; Export… writes a template to a `.lcprint` file and Import… adds one from such a file (checked like a saved template; a name already in use gets " (2)"); the Template Browser lists the templates in folders: User Templates and folders made with New Folder… (its button, or a folder's context menu), which open and close; Save and Import… put a template in the folder chosen beside them; a template dragged onto a folder, or moved with its context menu's Move to Folder, moves there; Rename Folder… and Delete Folder (asks first, and moves the folder's templates to User Templates, LightCraft's own rule) for every folder but User Templates; no built-in templates | | LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | | | LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | | | LRC-WEB-COLOR | Web gallery colours | OOS | 🚫 | | | @@ -894,6 +894,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LR-BEHAV-BG-TASKS: Reload from Disk reads its files on a worker thread with a cancellable activity row instead of freezing the window on a selection of raws; its result is committed through the command wrapper (XMP sidecars auto-written as before) and an older reload finishing late no longer overwrites a newer one; status unchanged (✅) | | 2026-10-19 | patch | LR-LIB-STACK: the filmstrip's stack badge expands / collapses the stack like the grid's, and a badge click works on a stack that isn't selected (it is selected first). Statuses and feature counts unchanged. | | 2026-10-14 | minor | LR-VIEW-ZOOM: Visualize Spots, Point Color range and Visualize HDR render zoom windows; LRC-DEV-SOFTPROOF: output-space proofs on the GPU | +| 2026-10-19 | patch | LR-LIB-CULL: Assisted Culling can stack each burst collapsed with its best photo on top (dialog checkbox, `photo.analyze` `stackGroups`; #2277). Statuses and feature counts unchanged. | | 2026-10-14 | patch | LR-EXP-TYPE: opaque 8-bit PNG/TIFF/WebP use RGB; transparent exports retain alpha (#1670). Statuses and feature counts unchanged. | | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | @@ -1067,6 +1068,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-EXP-DIALOG: built-in export presets for the issue #2104 delivery targets — Instagram Feed (1080 px, screen sharpening), Instagram Story / Reel (1920 px), Web / Portfolio (2048 px, copyright and creator metadata), Full Resolution Master (full size, Display P3, quality 95); LR-EXP-PREVIOUS drops its stale "no named export presets yet" note; status unchanged (✅) | | 2026-10-20 | patch | LR-EXP-DIALOG: the four built-in export presets are translated in all 17 catalogs (translations pending native-speaker review); Instagram Story / Reel states that it applies no crop to 9:16; status unchanged (✅) | | 2026-10-31 | patch | LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread under an activity row with ✕ instead of on the UI thread, where a large library left the window not responding (#3468). A stopped search leaves the view as it was and keeps what it read; a control request gets the same `{photos}` when the search ends. | +| 2026-10-31 | minor | LRC-PRINT-TEMPLATES: the Print dialog's Template Browser has folders (`print.template.folder.create` / `rename` / `delete`), Save and Import… put a template in a chosen folder, and a template dragged onto a folder moves there (`print.template.move`); deleting a folder moves its templates to User Templates; status unchanged (🟡: no built-in templates) | | 2026-10-27 | patch | LR-BEHAV-LOCALE: the Edit menu loses its Language submenu (18 rows); Settings ▸ General ▸ Language, which already lists every language, is the one place to choose; the `app.language.*` commands stay for agents; status counts unchanged | +| 2026-10-24 | minor | LRC-LIB-SMARTCOLL: the rule editor reorders rules and groups (a grip on each row: drag, or Tab and the arrow keys), in every locale. Status and summary counts unchanged. | | 2026-10-17 | minor | LR-VIEW-FILMSTRIP, LR-LIB-VIRTUALCOPY, LR-LIB-STACK, LR-LIB-LABEL, LRC-LIB-MISSING: one thumbnail overlay for the justified grid, the square grid and the filmstrip (`thumb.rs`): the filmstrip gains the copy tag, a clickable stack badge, the placeholder, the failure mark and the label dot; the failure mark explains itself on hover; the justified grid's tinted label footer is gone; marks degrade on narrow thumbnails; the rating is read out without an English plural; statuses unchanged (✅) | | 2026-10-17 | minor | LR-PREF-INTERFACE: grid badges set to Stars on hover (the default, formerly "When rated or hovered") keep flags and colour labels on every tile but show the stars and the edited mark only on the hovered or selected photo (before, any rated photo wore the whole badge bar); Always / Never unchanged; status unchanged (✅) | diff --git a/docs/slideshow.md b/docs/slideshow.md index e0c89b0311..fc2084e2c7 100644 --- a/docs/slideshow.md +++ b/docs/slideshow.md @@ -7,7 +7,7 @@ next to a live preview of the selected photo's slide, and View ▸ Slideshow ( | Part | Commands | Code | |---|---|---| -| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead, manual slideshow | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/ui-egui/src/panels/slideshow.rs` | +| Playback: slide and fade durations, fade colour, random order, repeat, preparing slides ahead, manual slideshow, pan and zoom | `slideshow.playback`, `view.slideshow` | `crates/engine/src/slideshow.rs` (the timeline), `crates/slideshow/src/motion.rs` (the pan and zoom path), `crates/ui-egui/src/panels/slideshow.rs` | | Layout, options, backdrop: margins, aspect preview, zoom to fill, stroke, shadow, colour, colour wash, background photo | `slideshow.layout` | `crates/slideshow` (the composer, no UI), `crates/engine/src/slide.rs` | | Overlays: identity plate, rating stars, text with tokens, watermark | `slideshow.overlays` | `crates/engine/src/slide_overlay.rs` | | Intro and ending screens | `slideshow.titles` | `crates/engine/src/slide_title.rs` | @@ -23,7 +23,7 @@ the same pixels through the same composer. View ▸ Export Slideshow… (or Export PDF / JPEG / Video at the end of Settings ▸ Slideshow) chooses a format and size, then asks where to write. The slides are the photos in view, in view order, between the intro and ending screens that -are on; random order, repeat and manual slideshow are playback choices and don't apply. The slide aspect is the Layout's aspect preview +are on; random order, repeat, manual slideshow and pan and zoom are playback choices and don't apply. The slide aspect is the Layout's aspect preview (Screen exports 16:9). - **PDF** — one page per slide, its picture a JPEG at the chosen quality, the page as many points as the slide has @@ -61,4 +61,4 @@ rendering included. The cost is in the fades (one encoded frame per frame of fad ## Not yet The Slideshow module view (left-panel template browser, slide editor with draggable guides and overlays), music and -sync to music, pan & zoom, H.264 video, saving a slideshow with an album, export presets. +sync to music, pan and zoom in exports, H.264 video, saving a slideshow with an album, export presets. diff --git a/docs/whats-new.md b/docs/whats-new.md index 4902eaad1c..2b5f132799 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -482,6 +482,19 @@ Denoise ▸ Run on chooses; Automatic times both). Photos denoised before are denoised again the next time they are needed. See [AI Denoise](denoise.md). +### Imports and moves on a network share ask it less +- Import no longer asks a network share about each photo's `.xmp` sidecar (up to nine names, each a round trip) when + the folder's listing, which the import or the Add Photos review has already read, shows there is none. A sidecar in + any letter case (`.xmp`, `.XMP`, `.Xmp`, or `.xmp`) is still found and read. A folder that changed since + it was listed, or was too recently changed to tell, is asked about photo by photo. For the folders that have not + changed since the review listed them, importing the photos picked in the review also stops asking the share + whether each one is a file or a folder before the first one is handled. +- Renaming photos, moving them to another folder, and undoing either look for their sidecars in one listing of each + folder that eight or more photos leave, instead of asking for four names per photo. Sidecars the listing shows + still move with their photos (`.xmp` or `.XMP`, as before). +- Folders that could not be listed completely or whose time can't be read, and files you add one by one, are checked + as before. + ### A right-click on a text field while you carry photos opens no menu - While you drag photos from the grid, a right-click on a text field, such as the search box, opens no Cut, Copy and Paste menu. Before, the menu opened over the field the photos were on. Right-clicking a field without a drag works @@ -561,6 +574,18 @@ left out of a new album made from the selection, out of Add to Album, and out of the target album (B), which does nothing and says nothing when none of them is left, and counts only the photos it changed. +### Reorder rules and groups in the smart album editor +- Every rule and every group in the New / Edit Smart Album window has a grip (six dots) at the start of its row. Drag it + to move the row: a line shows where it will land, the row's name follows the pointer, and Esc gives the drag up. Drop + on a rule inside a group to put it in that group, beside the group's frame to take it out; drag a whole group to + nest it in another. A group can't go inside itself or deeper than three levels: the pointer shows a not-allowed + cursor and says why, and nothing moves. A group a move leaves empty goes away. +- With the keyboard, Tab to a grip and press ↑ or ↓ to move the row one place (at the end of a group it moves out of + the group), → to move it into the group above it (or below it, if that is the one next to it) and ← to move it out + of its group. The focus stays on the moved row's grip, and a screen reader says where the row is: "Rule 2 of 4: + Rating is ≥ 3. Move with the arrow keys". +- OK saves the rules in the order shown, in one undo step like any other change to the rules. + ## 2026-10-23 ### AI Denoise works out of the box @@ -1064,6 +1089,12 @@ every photo of the view again: at about 180,000 photos a batch cost the window a tenth of a second, over and over for as long as the import ran. Changing one photo's capture time or crop is quicker too. +### Menu paths without boxes +- Messages that name a menu path, such as "View → Clear Filters to see all" or the External Editing help in + Settings, showed a box between the menu names: the interface font has no glyph for the small triangle used + there (issue #1950). They use → now, as the translations already did, and so do these notes. The remove + mark of each filter under "+N more" was a box too; it is an × now. + ## 2026-10-15 ### Photo Merge takes each photo once