Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Merge PR #2964: LR-IMP-ADD-DIALOG: handle rename sequence exhaustion

aiongg5a7a1b2ad9d3
diff --cc crates/engine/src/cmd/library/import.rs
index 8437bf165,000000000..2a663b79d
mode 100644,000000..100644
--- a/crates/engine/src/cmd/library/import.rs
+++ b/crates/engine/src/cmd/library/import.rs
@@@ -1,110 -1,0 +1,114 @@@
+use super::selection::strs;
+use super::{AlbumId, PhotoId, Result, Selection, Session, Value, bad, bool_or, json, str_param};
+
+/// The auto-import folder's visible files with their sizes (the file-system half of
+/// `library.autoImportScan`; the app lists on a worker thread and passes `listing`).
+pub fn list_auto_import_folder(folder: &str) -> std::result::Result<Vec<(String, u64)>, String> {
+ let rd = std::fs::read_dir(folder).map_err(|e| format!("{folder}: {e}"))?;
+ Ok(rd
+ .flatten()
+ .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
+ .filter_map(|e| {
+ let m = std::fs::metadata(e.path()).ok()?;
+ m.is_file().then(|| (e.path().to_string_lossy().to_string(), m.len()))
+ })
+ .collect())
+}
+
+/// `library.import`'s params, checked (no file-system calls).
+pub struct ImportRequest {
+ pub paths: Vec<String>,
+ pub opts: crate::import::ImportOptions,
+ pub album: Option<u64>,
+ pub album_name: Option<String>,
+}
+
+/// Parse and check `library.import`'s params (the app's import task runs the import itself, on a
+/// worker thread, with the same options).
+pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
+ let paths = strs(p, "paths");
+ let mode = match str_param(p, "mode").unwrap_or("add") {
+ "add" => crate::import::ImportMode::Add,
+ "copy" => crate::import::ImportMode::Copy,
+ "move" => crate::import::ImportMode::Move,
+ other => return Err(bad("library.import", format!("unknown mode `{other}` (add|copy|move)"))),
+ };
+ let preset = match str_param(p, "preset").filter(|x| !x.is_empty()) {
+ Some(id) => Some(s.presets.iter().find(|x| x.id == id).cloned().ok_or_else(|| bad("library.import", format!("unknown preset `{id}`")))?),
+ None => None,
+ };
+ let album = p.get("album").and_then(Value::as_u64);
+ if let Some(a) = album
+ && s.catalog.album(AlbumId(a)).is_none_or(|al| al.folder || al.is_smart())
+ {
+ return Err(bad("library.import", "album must be a regular album"));
+ }
+ let organize = match str_param(p, "organize") {
+ Some(o) => crate::import::Organize::parse(o).ok_or_else(|| {
+ bad("library.import", format!("unknown organize `{o}` (date|month|flat, or a folder template like {{date:%Y}}/{{date:%Y%m%d}})"))
+ })?,
+ None => Default::default(),
+ };
+ if let crate::import::Organize::Template(t) = &organize
+ && let Some(e) = crate::rename::folder_template_error(t)
+ {
+ return Err(bad("library.import", e));
+ }
+ let metadata_preset = str_param(p, "metadataPreset").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
+ if let Some(n) = &metadata_preset
+ && !s.metadata_presets.iter().any(|m| m.name.eq_ignore_ascii_case(n))
+ {
+ return Err(bad("library.import", format!("unknown metadata preset `{n}`")));
+ }
+ let on_deleted = match str_param(p, "onDeleted") {
+ Some(v) => {
+ crate::import::OnDeleted::parse(v).ok_or_else(|| bad("library.import", format!("unknown onDeleted `{v}` (restore|skip|fresh)")))?
+ }
+ None => Default::default(),
+ };
++ let rename_start = match p.get("renameStart").and_then(Value::as_u64) {
++ Some(n) => usize::try_from(n).map_err(|_| bad("library.import", "renameStart is too large for this platform"))?,
++ None => 1,
++ };
+ let opts = crate::import::ImportOptions {
+ on_deleted,
+ mode,
+ preset,
+ keywords: strs(p, "keywords"),
+ destination: str_param(p, "destination").map(str::to_string),
+ organize,
+ rename: str_param(p, "rename").map(str::to_string),
- rename_start: p.get("renameStart").and_then(Value::as_u64).unwrap_or(1) as usize,
++ rename_start,
+ metadata_preset,
+ convert_dng: bool_or(p, "dng", false),
+ local: bool_or(p, "local", false),
+ };
+ let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
+ Ok(ImportRequest { paths, opts, album, album_name })
+}
+
+/// After a batch of an import was committed: the album (a new one named `album_name` when there
+/// is no `album` and something was imported) gets the photos. Returns the report as JSON (with
+/// `album`).
+pub fn import_batch_done(s: &mut Session, report: crate::import::ImportReport, mut album: Option<u64>, album_name: Option<&str>) -> Result<Value> {
+ let mut report = serde_json::to_value(report).unwrap_or_default();
+ // photos an import restored from Recently Deleted take part like new ones (album, selection)
+ let imported: Vec<u64> =
+ ["imported", "restored"].iter().flat_map(|k| report[*k].as_array().into_iter().flatten().filter_map(Value::as_u64)).collect();
+ if album.is_none()
+ && let Some(name) = album_name
+ && !imported.is_empty()
+ {
+ let r = s.execute("album.create", &json!({"name": name}))?;
+ album = r["id"].as_u64();
+ }
+ if let Some(a) = album
+ && !imported.is_empty()
+ {
+ // (album.addPhotos wants a selection: the new photos are about to be it)
+ s.selection = Selection::single(PhotoId(imported[0]));
+ s.execute("album.addPhotos", &json!({"id": a, "ids": imported}))?;
+ report["album"] = json!(a);
+ }
+ Ok(report)
+}
diff --cc crates/engine/src/cmd/library/specs.rs
index 2e7c1311d,000000000..bbb153321
mode 100644,000000..100644
--- a/crates/engine/src/cmd/library/specs.rs
+++ b/crates/engine/src/cmd/library/specs.rs
@@@ -1,1377 -1,0 +1,1377 @@@
+use super::filters::{covers_other_disks, merge_rules, view_rules};
+use super::gps::parse_gps;
+use super::import::{import_batch_done, import_params, list_auto_import_folder};
+use super::selection::{
+ album_param, album_targets, album_targets_or_err, change_flag, change_rating, cull, flip, for_targets, has_library, mark_deleted,
+ opt_album_param, rotate, row_step, select_after_deletion, select_by, step, strs,
+};
+use super::{
+ Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey,
+ Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param,
+};
+
+/// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote.
+const MAX_SEED: u64 = 1 << 53;
+
+/// `seed` as an integer in `0..2^53`, or `default` when absent or null; anything else is an error.
+fn seed_param(p: &Value, cmd: &str, default: u64) -> Result<u64> {
+ match p.get("seed") {
+ None | Some(Value::Null) => Ok(default),
+ Some(v) => v.as_u64().filter(|n| *n < MAX_SEED).ok_or_else(|| bad(cmd, "seed must be an integer from 0 to 2^53 - 1")),
+ }
+}
+
+/// The seed after `prev` at time `now`: a mix of `prev` and the clock text, so repeated reshuffles
+/// within one clock tick still differ (barring a 2^-53 collision). Kept below 2^53 so JSON
+/// clients that read numbers as doubles (web, MCP agents) get the same seed back.
+fn next_seed(prev: u64, now: &str) -> u64 {
+ let t = now.bytes().fold(0u64, |h, b| lightcraft_catalog::mix64(h ^ u64::from(b)));
+ (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ // ---- view source / filter / sort
+ cmd!(
+ "library.source",
+ "Show Source",
+ [],
+ None,
+ "{kind: all|recentlyAdded|album|recentlyDeleted|picks|missing|libraryFolder, id?: albumId, path?: a path from library.folders (for libraryFolder)}",
+ always,
+ |s, p| {
+ let kind = str_param(p, "kind").unwrap_or("all");
+ s.source = match kind {
+ "all" => LibrarySource::All,
+ "recentlyAdded" => LibrarySource::RecentlyAdded,
+ "recentlyDeleted" => LibrarySource::RecentlyDeleted,
+ "picks" => LibrarySource::Picks,
+ "missing" => LibrarySource::Missing,
+ "album" => {
+ let a = album_param(p, "id", "library.source")?;
+ if s.catalog.album(a).is_none_or(|a| a.folder) {
+ return Err(bad("library.source", "no such album"));
+ }
+ // one album at a time: `to_filter` makes the album shown replace the filter's, and the
+ // filter bar has no album chip, so a left-over one would narrow the next source unseen
+ s.filter.album = None;
+ LibrarySource::Album(a)
+ }
+ "libraryFolder" => {
+ let path = str_param(p, "path").filter(|d| !d.trim().is_empty() && !lightcraft_catalog::query::folder_key(d).is_empty());
+ let path = path.ok_or_else(|| bad("library.source", "libraryFolder needs the `path` of a folder from library.folders"))?;
+ if lightcraft_catalog::folders::is_startup_disk(path) {
+ return Err(bad("library.source", "the startup disk's path covers every disk: choose a folder in it"));
+ }
+ let f = Filter { library_folder: Some(path.to_string()), ..Default::default() };
+ let ids = s.catalog.query(&f, &Sort::default());
+ if ids.is_empty() {
+ return Err(bad("library.source", format!("{path}: no photo in the library was imported from it")));
+ }
+ if covers_other_disks(s, path, &ids) {
+ return Err(bad("library.source", format!("{path} holds other disks as well: choose a disk or a folder on one")));
+ }
+ s.library_folder = Some(path.to_string());
+ // one folder at a time: a folder filter left over would be ignored
+ s.filter.library_folder = None;
+ LibrarySource::LibraryFolder
+ }
+ other => return Err(bad("library.source", format!("unknown source `{other}`"))),
+ };
+ s.keep_active_in_view();
+ Ok(json!({"count": s.visible().len()}))
+ }
+ ),
+ cmd!(
+ "library.filter",
+ "Filter",
+ [],
+ None,
+ "partial Filter: {text?, rating?, ratingOp?: atLeast|exactly|atMost, flag?: pick|reject|none|null, label?, kind?, merged?: hdr|panorama|hdrPanorama|any, edited?, date?, libraryFolder?: a path from library.folders, keyword?, person?, camera?}",
+ always,
+ |s, p| {
+ let mut v = serde_json::to_value(&s.filter).unwrap_or_default();
+ lightcraft_develop::presets::deep_merge(&mut v, p);
+ let f: Filter = serde_json::from_value(v).map_err(|e| bad("library.filter", e.to_string()))?;
+ let mut f = f;
+ // a blank folder is no folder: no hidden "filters active" state
+ f.library_folder = f.library_folder.filter(|d| !d.trim().is_empty());
+ if f.library_folder.is_some() && s.source == LibrarySource::LibraryFolder {
+ return Err(bad("library.filter", "a folder is already shown (library.source): show another source first"));
+ }
+ // checked like a smart album's rules when this call sets them: an unknown field or a value
+ // that can't match is an error, not an empty grid. Rules that stopped checking since
+ // (their album was deleted) don't block other filter changes.
+ if let Some(rules) = f.rule_set.as_mut() {
+ rules.upgrade();
+ }
+ let sets_rules = p.get("ruleSet").is_some_and(|r| !r.is_null());
+ if let Some(problems) = f.rule_set.as_ref().filter(|_| sets_rules).map(|rs| rs.check(&s.catalog)).filter(|p| !p.is_empty()) {
+ return Err(bad("library.filter", problems.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")));
+ }
+ s.filter = f;
+ s.shelved_filter = None;
+ Ok(json!({"count": s.visible().len()}))
+ }
+ ),
+ cmd!(
+ query "library.folders",
+ "Library Folders",
+ [],
+ None,
+ "{} → [{name, path, count, own, volume, selectable, label?, children}] the disks and the folders the library's photos were imported from, with photo counts (subfolders included in `count`); show one with library.source {kind: libraryFolder, path} (rows with selectable false only open)",
+ always,
+ |s, _| Ok(serde_json::to_value(s.catalog.folder_tree()).unwrap_or_default())
+ ),
+ cmd!(
+ "library.removeFolder",
+ "Remove Folder from Library",
+ [],
+ None,
+ "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}",
+ always,
+ |s, p| {
+ const C: &str = "library.removeFolder";
+ let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?;
+ if lightcraft_catalog::query::folder_key(path).is_empty() {
+ return Err(bad(C, format!("{path}: not a folder")));
+ }
+ if lightcraft_catalog::folders::is_startup_disk(path) {
+ return Err(bad(C, "choose a folder, not the whole startup disk"));
+ }
+ if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) {
+ return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it")));
+ }
+ let f = Filter { library_folder: Some(path.to_string()), ..Default::default() };
+ let ids = s.catalog.query(&f, &Sort::default());
+ if ids.is_empty() {
+ return Err(bad(C, format!("{path}: no photo in the library was imported from it")));
+ }
+ if covers_other_disks(s, path, &ids) && !bool_or(p, "disk", false) {
+ return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them")));
+ }
+ mark_deleted(s, &ids, "Remove Folder from Library")?;
+ if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) {
+ s.filter.library_folder = None;
+ }
+ // a filter put aside by Enable Filters must not bring the removed folder back
+ if let Some(f) = s.shelved_filter.as_mut()
+ && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path))
+ {
+ f.library_folder = None;
+ }
+ if s.shelved_filter.as_ref() == Some(&Filter::default()) {
+ s.shelved_filter = None;
+ }
+ // the folder being shown is gone: back to everything, as for a deleted album
+ if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) {
+ s.library_folder = None;
+ if s.source == LibrarySource::LibraryFolder {
+ s.source = LibrarySource::All;
+ }
+ }
+ let vis = s.visible_cloned();
+ s.selection = vis.first().map(|f| Selection::single(*f)).unwrap_or_default();
+ Ok(json!({"removed": ids.len()}))
+ }
+ ),
+ cmd!(
+ "folder.label",
+ "Set Folder Color Label",
+ [],
+ None,
+ "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}",
+ always,
+ |s, p| {
+ const C: &str = "folder.label";
+ let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?;
+ let label = match str_param(p, "label").ok_or_else(|| bad(C, "missing `label` (red|yellow|green|blue|purple|none)"))? {
+ "none" => None,
+ x => Some(ColorLabel::parse(x).ok_or_else(|| bad(C, format!("unknown label {x:?}")))?),
+ };
+ // taking a label off always works, also once the folder's photos are gone
+ let f = Filter { library_folder: Some(path.to_string()), ..Default::default() };
+ if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() {
+ return Err(bad(C, format!("{path}: no photo in the library was imported from it")));
+ }
+ if label.is_none() && s.catalog.folder_record(path).is_none() {
+ return Ok(json!({"path": path, "label": label}));
+ }
+ let op = s.catalog.folder_label_op(path, label);
+ s.commit(if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }, op)?;
+ Ok(json!({"path": path, "label": label}))
+ }
+ ),
+ cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| {
+ s.filter = Default::default();
+ s.shelved_filter = None;
+ Ok(json!({"count": s.visible().len()}))
+ }),
+ // Classic: Library > Enable Filters (Cmd+L) switches the filter off and on again as it was
+ cmd!(
+ "library.toggleFilters",
+ "Enable Filters",
+ ["View"],
+ Some("Cmd+L"),
+ "{} — with a filter set, puts it aside and shows everything; with one put aside, brings it back as it was (stars, flag, text… together). Setting or clearing a filter while it is off forgets the one put aside → {enabled, count}",
+ always,
+ |s, _| {
+ if s.filter != Filter::default() {
+ s.shelved_filter = Some(std::mem::take(&mut s.filter));
+ } else if let Some(mut f) = s.shelved_filter.take() {
+ // one folder at a time: the folder shown now wins over the one the filter had
+ if s.source == LibrarySource::LibraryFolder {
+ f.library_folder = None;
+ }
+ s.filter = f;
+ }
+ Ok(json!({"enabled": s.shelved_filter.is_none(), "count": s.visible().len()}))
+ }
+ ),
+ cmd!(
+ "library.sort",
+ "Sort",
+ ["View", "Sort"],
+ None,
+ "{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random, ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)}",
+ always,
+ |s, p| {
+ let key: SortKey = match p.get("key") {
+ Some(k) => serde_json::from_value(k.clone()).map_err(|e| bad("library.sort", e.to_string()))?,
+ None => s.sort.key,
+ };
+ let group = match str_param(p, "group") {
+ Some(g) => GroupBy::parse(g).ok_or_else(|| bad("library.sort", "group must be auto|none|day|month|year"))?,
+ None => s.sort.group,
+ };
+ let mut seed = seed_param(p, "library.sort", s.sort.seed)?;
+ let explicit = p.get("seed").is_some_and(|v| !v.is_null());
+ if key == SortKey::Random && s.sort.key != SortKey::Random && !explicit {
+ // switching to Random is a fresh shuffle, not whatever seed was left behind
+ seed = next_seed(seed, &(s.clock)());
+ }
+ s.sort = Sort { key, ascending: bool_or(p, "ascending", s.sort.ascending), group, seed };
+ ok()
+ }
+ ),
+ cmd!(
+ "library.refresh",
+ "Refresh View",
+ ["View"],
+ None,
+ "{} — show what matches now: a view that holds its photos (`library.holdView`) lets go of the ones that stopped matching a smart album's rules, Picks or the filter bar since it was opened, sorted or last refreshed",
+ always,
+ |s, _| {
+ s.refresh_view();
+ ok()
+ }
+ ),
+ cmd!(
+ "library.holdView",
+ "Hold View Until Refreshed",
+ ["View"],
+ None,
+ "{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing",
+ always,
+ |s, p| {
+ let on = match p.get("on") {
+ None | Some(Value::Null) => !s.hold_view,
+ Some(Value::Bool(on)) => *on,
+ Some(_) => return Err(bad("library.holdView", "on must be true or false")),
+ };
+ if on != s.hold_view {
+ let was = s.hold_view;
+ s.hold_view = on;
+ if let Err(e) = s.save_prefs() {
+ // not kept: not changed either, so asking again does what was asked
+ s.hold_view = was;
+ return Err(e);
+ }
+ s.refresh_view();
+ }
+ Ok(json!({"hold": s.hold_view}))
+ }
+ ),
+ cmd!(
+ "library.shuffle",
+ "Reshuffle",
+ ["View", "Sort"],
+ None,
+ "{seed?: 0..2^53-1} — sort at random; without `seed` a new shuffle each time",
+ always,
+ |s, p| {
+ let seed = match seed_param(p, "library.shuffle", s.sort.seed)? {
+ given if p.get("seed").is_some_and(|v| !v.is_null()) => given,
+ // derived from the previous seed and the session clock: reproducible under a test
+ // clock, and no RNG needed
+ prev => next_seed(prev, &(s.clock)()),
+ };
+ s.sort = Sort { key: SortKey::Random, seed, ..s.sort };
+ ok()
+ }
+ ),
+ cmd!(
+ query "library.groups",
+ "Date Groups",
+ [],
+ None,
+ "{by?: day|month|year (default: the sort's grouping; auto = day)} → [{key, label, start, count}] date headers of the grid",
+ always,
+ |s, p| {
+ let by = match str_param(p, "by") {
+ Some(g) => GroupBy::parse(g).ok_or_else(|| bad("library.groups", "by must be auto|none|day|month|year"))?,
+ None => s.sort.group,
+ };
+ let vis = s.visible_cloned();
+ Ok(serde_json::to_value(s.catalog.date_runs(&vis, s.sort.key, by)).unwrap_or_default())
+ }
+ ),
+ // ---- selection
+ cmd!(
+ "library.select",
+ "Select Photos",
+ [],
+ None,
+ "{ids: [id], active?: id, mode?: replace|add|toggle|range} — every id must be a photo of the library",
+ always,
+ |s, p| {
+ let ids = crate::cmd::photo_ids(p, "library.select")?.unwrap_or_default();
+ let active = p.get("active").and_then(Value::as_u64).map(PhotoId);
+ let mode = str_param(p, "mode").unwrap_or("replace");
+ // An id that is not in the library is an error, and the selection stays as it was:
+ // selecting it would otherwise report success and leave the session with no usable
+ // active photo (#182).
+ if let Some(id) = ids.iter().chain(active.as_ref()).find(|id| s.catalog.photo(**id).is_none()) {
+ return Err(bad("library.select", format!("no such photo {}", id.0)));
+ }
+ s.end_interaction()?;
+ match mode {
+ "replace" => {
+ s.selection = Selection { ids: ids.clone(), active: active.or(ids.first().copied()) };
+ }
+ "add" => {
+ for id in ids {
+ if !s.selection.contains(id) {
+ s.selection.ids.push(id);
+ }
+ s.selection.active = Some(id);
+ }
+ }
+ "toggle" => ids.into_iter().for_each(|id| s.selection.toggle(id)),
+ "range" => {
+ let vis = s.visible_cloned();
+ if let Some(id) = ids.first() {
+ s.selection.extend_to(*id, &vis);
+ }
+ }
+ other => return Err(bad("library.select", format!("unknown mode `{other}`"))),
+ }
+ s.active_mask = None;
+ s.active_spot = None;
+ Ok(json!({"selected": s.selection.ids.len()}))
+ }
+ ),
+ cmd!("library.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", always, |s, _| {
+ let vis = s.visible_cloned();
+ s.selection = Selection { active: s.selection.active.filter(|a| vis.contains(a)).or(vis.first().copied()), ids: vis };
+ Ok(json!({"selected": s.selection.ids.len()}))
+ }),
+ cmd!(query "library.devices", "Cameras and Cards", [], None, "{} → [{name, path (its DCIM folder), root}] — mounted volumes with a DCIM folder", always, |_, _| {
+ Ok(serde_json::to_value(crate::devices::devices_now()).unwrap_or_default())
+ }),
+ cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| {
+ let id = s.active().ok_or_else(|| bad("photo.copyMetadata", "no active photo"))?;
+ let m = &s.catalog.photo(id).ok_or_else(|| bad("photo.copyMetadata", "no photo"))?.meta;
+ let v = json!({"title": m.title, "caption": m.caption, "altText": m.alt_text, "extendedDescription": m.extended_description,
+ "copyright": m.copyright, "copyrightStatus": m.copyright_status.id(), "usageTerms": m.usage_terms, "copyrightUrl": m.copyright_url,
+ "creator": m.creator, "location": m.location, "city": m.city, "state": m.state, "country": m.country,
+ "keywords": m.keywords});
+ s.meta_clipboard = Some(v.clone());
+ Ok(v)
+ }),
+ cmd!(
+ "photo.pasteMetadata",
+ "Paste Metadata",
+ ["Photo"],
+ Some("Cmd+Alt+Shift+V"),
+ "{ids?, fields?: [title|caption|copyright|copyrightStatus|usageTerms|copyrightUrl|creator|location|keywords] (default: all copied)}",
+ has_selection,
+ |s, p| {
+ let c = "photo.pasteMetadata";
+ let clip = s.meta_clipboard.clone().ok_or_else(|| bad(c, "nothing copied (photo.copyMetadata)"))?;
+ let fields: Option<Vec<String>> =
+ p.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
+ let mut params = serde_json::Map::new();
+ for (k, v) in clip.as_object().into_iter().flatten() {
+ if fields.as_ref().is_none_or(|f| f.iter().any(|x| x == k)) {
+ params.insert(k.clone(), v.clone());
+ }
+ }
+ if let Some(ids) = p.get("ids") {
+ params.insert("ids".into(), ids.clone());
+ }
+ s.execute("photo.setMeta", &Value::Object(params))
+ }
+ ),
+ cmd!(
+ "library.selectBy",
+ "Select by Flag, Rating or Label",
+ [],
+ None,
+ "{flag?: pick|reject|none, rating?: 0..5, ratingOp?: gte|eq|lte (default gte), label?: red|…|none, add?: bool (extend the selection)} — among the photos in view",
+ always,
+ select_by
+ ),
+ cmd!("library.selectNone", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always, |s, _| {
+ let a = s.selection.active;
+ s.selection = Selection { ids: a.into_iter().collect(), active: a };
+ ok()
+ }),
+ cmd!("library.next", "Next Photo", [], Some("Right"), "{}", always, |s, _| step(s, 1)),
+ cmd!("library.previous", "Previous Photo", [], Some("Left"), "{}", always, |s, _| step(s, -1)),
+ cmd!(
+ "library.down",
+ "Photo Below",
+ [],
+ Some("Down"),
+ "{rows?: n (photos to move forward; default 1, the grid passes the distance to the cell below)}",
+ always,
+ |s, p| { step(s, row_step(p)) }
+ ),
+ cmd!(
+ "library.up",
+ "Photo Above",
+ [],
+ Some("Up"),
+ "{rows?: n (photos to move back; default 1, the grid passes the distance to the cell above)}",
+ always,
+ |s, p| { step(s, -row_step(p)) }
+ ),
+ // ---- rating / flags / labels
+ cmd!(
+ "photo.rate",
+ "Set Rating",
+ ["Photo", "Set Rating"],
+ None,
+ "{rating: 0..5, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| {
+ let r = crate::cmd::index_req(p, "rating", "photo.rate")
+ .ok()
+ .filter(|r| *r <= 5)
+ .ok_or_else(|| bad("photo.rate", "rating must be a whole number 0..5"))?;
+ cull(s, p, |s| for_targets(s, p, "Set Rating", |id| Some(Op::SetRating { id, rating: r as u8 })))
+ }
+ ),
+ cmd!(
+ "photo.decreaseRating",
+ "Decrease Rating",
+ [],
+ None,
+ "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| change_rating(s, p, -1, "Decrease Rating")) }
+ ),
+ cmd!(
+ "photo.increaseRating",
+ "Increase Rating",
+ [],
+ None,
+ "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| change_rating(s, p, 1, "Increase Rating")) }
+ ),
+ cmd!(
+ "photo.flag",
+ "Set Flag",
+ ["Photo", "Set Flag"],
+ None,
+ "{flag: pick|reject|none, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| {
+ let f = str_param(p, "flag").and_then(Flag::parse).ok_or_else(|| bad("photo.flag", "flag must be pick|reject|none"))?;
+ cull(s, p, |s| for_targets(s, p, "Set Flag", |id| Some(Op::SetFlag { id, flag: f })))
+ }
+ ),
+ // Classic: ` cycles the flag; Cmd+Up / Cmd+Down raise / lower it (Ctrl on Windows and Linux)
+ cmd!(
+ "photo.cycleFlag",
+ "Cycle Flag",
+ ["Photo", "Set Flag"],
+ Some("`"),
+ "{ids?, advance?: bool} — each photo's own flag: unflagged -> pick -> reject -> unflagged; without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| {
+ cull(s, p, |s| {
+ change_flag(s, p, "Cycle Flag", |f| match f {
+ Flag::None => Flag::Pick,
+ Flag::Pick => Flag::Reject,
+ Flag::Reject => Flag::None,
+ })
+ })
+ }
+ ),
+ cmd!(
+ "photo.increaseFlag",
+ "Increase Flag Status",
+ ["Photo", "Set Flag"],
+ Some("Cmd+Up"),
+ "{ids?, advance?: bool} — reject -> unflagged -> pick (stops at pick); without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| change_flag(s, p, "Increase Flag Status", |f| if f == Flag::Reject { Flag::None } else { Flag::Pick })) }
+ ),
+ cmd!(
+ "photo.decreaseFlag",
+ "Decrease Flag Status",
+ ["Photo", "Set Flag"],
+ Some("Cmd+Down"),
+ "{ids?, advance?: bool} — pick -> unflagged -> reject (stops at reject); without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| change_flag(s, p, "Decrease Flag Status", |f| if f == Flag::Pick { Flag::None } else { Flag::Reject })) }
+ ),
+ cmd!(
+ "photo.pick",
+ "Flag as Pick",
+ ["Photo", "Set Flag"],
+ Some("P"),
+ "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| for_targets(s, p, "Flag as Pick", |id| Some(Op::SetFlag { id, flag: Flag::Pick }))) }
+ ),
+ cmd!(
+ "photo.reject",
+ "Flag as Reject",
+ ["Photo", "Set Flag"],
+ Some("X"),
+ "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| for_targets(s, p, "Flag as Reject", |id| Some(Op::SetFlag { id, flag: Flag::Reject }))) }
+ ),
+ cmd!(
+ "photo.unflag",
+ "Unflag",
+ ["Photo", "Set Flag"],
+ Some("U"),
+ "{ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| { cull(s, p, |s| for_targets(s, p, "Unflag", |id| Some(Op::SetFlag { id, flag: Flag::None }))) }
+ ),
+ cmd!(
+ "photo.label",
+ "Set Color Label",
+ ["Photo", "Set Color Label"],
+ None,
+ "{label: red|yellow|green|blue|purple|none, ids?, advance?: bool} — without `ids`, the selection moves on when this takes the active photo out of the view",
+ has_selection,
+ |s, p| {
+ // `none` (or null) clears; a missing label or one that isn't text is an error, not a clear
+ let l = match p.get("label") {
+ Some(Value::Null) => None,
+ Some(Value::String(x)) if x == "none" => None,
+ Some(Value::String(x)) => Some(ColorLabel::parse(x).ok_or_else(|| bad("photo.label", "unknown label"))?),
+ None => return Err(bad("photo.label", "missing `label` (red|yellow|green|blue|purple|none)")),
+ Some(_) => return Err(bad("photo.label", "label must be red|yellow|green|blue|purple|none")),
+ };
+ cull(s, p, |s| for_targets(s, p, "Set Color Label", |id| Some(Op::SetLabel { id, label: l })))
+ }
+ ),
+ // ---- orientation
+ cmd!("photo.rotateLeft", "Rotate Left", ["Photo"], Some("Cmd+["), "{ids?}", has_selection, |s, p| rotate(s, p, false)),
+ cmd!("photo.rotateRight", "Rotate Right", ["Photo"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| rotate(s, p, true)),
+ cmd!("photo.flipHorizontal", "Flip Horizontal", ["Photo"], None, "{ids?}", has_selection, |s, p| flip(s, p, true)),
+ cmd!("photo.flipVertical", "Flip Vertical", ["Photo"], None, "{ids?}", has_selection, |s, p| flip(s, p, false)),
+ // ---- face / pet regions
+ cmd!(
+ "photo.removeRegion",
+ "Remove Face Box",
+ [],
+ None,
+ "{id?, index} — remove one face / pet region (by its position in the photo's regions) from the photo in the catalog; undoable. The XMP sidecar is never rewritten for this, even with auto-write on, so reading the metadata from the file brings the region back",
+ always,
+ |s, p| {
+ let id =
+ crate::cmd::photo_id(p, "photo.removeRegion")?.or_else(|| s.active()).ok_or_else(|| bad("photo.removeRegion", "no photo"))?;
+ let index = p
+ .get("index")
+ .and_then(Value::as_u64)
+ .and_then(|i| usize::try_from(i).ok())
+ .ok_or_else(|| bad("photo.removeRegion", "missing or invalid `index`"))?;
+ let mut meta = s.catalog.photo(id).ok_or_else(|| bad("photo.removeRegion", "no such photo"))?.meta.clone();
+ if index >= meta.regions.len() {
+ return Err(bad("photo.removeRegion", "no such region"));
+ }
+ let gone = meta.regions.remove(index);
+ s.commit("Remove Face Box", Op::SetMeta { id, meta: Box::new(meta) })?;
+ s.skip_auto_write = true;
+ Ok(json!({"removed": gone.name}))
+ }
+ ),
+ cmd!(
+ "photo.setRegion",
+ "Resize Face Box",
+ [],
+ None,
+ "{id?, index, rect: {x0, y0, x1, y1}} — set one face / pet region's box (normalized, in the photo's upright frame; clamped to the photo, at least 0.5 % each way) in the catalog; undoable. Like photo.removeRegion it never rewrites the XMP sidecar",
+ always,
+ |s, p| {
+ const C: &str = "photo.setRegion";
+ // a drag is one undo step however many frames it took: the caller commits once, on release
+ let id = crate::cmd::photo_id(p, C)?.or_else(|| s.active()).ok_or_else(|| bad(C, "no photo"))?;
+ let index = p
+ .get("index")
+ .and_then(Value::as_u64)
+ .and_then(|i| usize::try_from(i).ok())
+ .ok_or_else(|| bad(C, "missing or invalid `index`"))?;
+ let r = p.get("rect").ok_or_else(|| bad(C, "missing `rect`"))?;
+ let num = |k: &str| {
+ r.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(C, format!("`rect.{k}` must be a finite number")))
+ };
+ let (a, b, c, d) = (num("x0")?, num("y0")?, num("x1")?, num("y1")?);
+ let (x0, x1) = (a.min(c).clamp(0.0, 1.0), a.max(c).clamp(0.0, 1.0));
+ let (y0, y1) = (b.min(d).clamp(0.0, 1.0), b.max(d).clamp(0.0, 1.0));
+ if x1 - x0 < 0.005 || y1 - y0 < 0.005 {
+ return Err(bad(C, "the box would be too small"));
+ }
+ let mut meta = s.catalog.photo(id).ok_or_else(|| bad(C, "no such photo"))?.meta.clone();
+ let region = meta.regions.get_mut(index).ok_or_else(|| bad(C, "no such region"))?;
+ region.rect = lightcraft_geom::Rect { x0, y0, x1, y1 };
+ s.commit("Resize Face Box", Op::SetMeta { id, meta: Box::new(meta) })?;
+ s.skip_auto_write = true;
+ Ok(json!({"rect": {"x0": x0, "y0": y0, "x1": x1, "y1": y1}}))
+ }
+ ),
+ // ---- delete / restore
+ cmd!("photo.delete", "Delete Photo", ["Photo"], Some("Delete"), "{ids?} — moves to Recently Deleted", has_selection, |s, p| {
+ let before = s.visible_cloned();
+ let targets = s.targets(p)?;
+ // an open drag ends first, as its own undo step (the selection moves on)
+ s.end_interaction()?;
+ let n = mark_deleted(s, &targets, "Delete")?;
+ select_after_deletion(s, &before);
+ Ok(json!({"changed": n}))
+ }),
+ cmd!("photo.restore", "Restore", ["Photo"], None, "{ids?}", has_selection, |s, p| for_targets(s, p, "Restore", |id| Some(Op::SetDeleted {
+ id,
+ deleted: false
+ }))),
+ cmd!(
+ "library.emptyRecentlyDeleted",
+ "Empty Recently Deleted",
+ ["Photo"],
+ None,
+ "{} → {deleted} — removes every photo in Recently Deleted from the library (files on disk stay)",
+ always,
+ |s, _| {
+ let ids: Vec<PhotoId> = s.catalog.photos().filter(|p| p.deleted).map(|p| p.id).collect();
+ if ids.is_empty() {
+ return Ok(json!({"deleted": 0}));
+ }
+ let op = s.catalog.delete_photos_permanently_ops(&ids);
+ s.commit("Empty Recently Deleted", op)?;
+ s.selection = Selection::default();
+ Ok(json!({"deleted": ids.len()}))
+ }
+ ),
+ cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| {
+ let before = s.visible_cloned();
+ let t = s.targets(p)?;
+ // before the inverse ops are taken, so undo brings the photo back with its edit
+ s.end_interaction()?;
+ let op = s.catalog.delete_photos_permanently_ops(&t);
+ s.commit("Delete Permanently", op)?;
+ select_after_deletion(s, &before);
+ Ok(json!({"deleted": t.len()}))
+ }),
+ // ---- metadata
+ cmd!(
+ "photo.setMeta",
+ "Edit Info",
+ [],
+ None,
+ "{ids?, title?, caption?, altText?, extendedDescription?, copyright?, copyrightStatus?: unknown|copyrighted|publicDomain, usageTerms?, copyrightUrl?, creator?, location?, city?, state?, country?, gps?: \"lat, lon\" | [lat, lon] | null, keywords?: [..], addKeywords?: [..], removeKeywords?: [..]}",
+ has_selection,
+ |s, p| {
+ let strs =
+ |k: &str| p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect::<Vec<_>>());
+ let targets = s.targets(p)?;
+ // GPS: "lat, lon" (decimal or 51°30'26"N 0°7'39"W), [lat, lon], or null / "" to clear
+ let gps: Option<Option<(f64, f64)>> = match p.get("gps") {
+ None => None,
+ Some(Value::Null) => Some(None),
+ Some(Value::String(t)) if t.trim().is_empty() => Some(None),
+ Some(Value::String(t)) => Some(Some(
+ parse_gps(t).ok_or_else(|| bad("photo.setMeta", format!("can't read `{t}` as coordinates (e.g. 51.5072, -0.1276)")))?,
+ )),
+ Some(Value::Array(a)) if a.len() == 2 => match (a[0].as_f64(), a[1].as_f64()) {
+ (Some(la), Some(lo)) if la.abs() <= 90.0 && lo.abs() <= 180.0 => Some(Some((la, lo))),
+ _ => return Err(bad("photo.setMeta", "gps is [latitude, longitude] in degrees")),
+ },
+ Some(_) => return Err(bad("photo.setMeta", "gps is \"lat, lon\", [lat, lon] or null")),
+ };
+ let status = match str_param(p, "copyrightStatus") {
+ Some(t) => Some(
+ CopyrightStatus::parse(t)
+ .ok_or_else(|| bad("photo.setMeta", format!("copyrightStatus `{t}`: unknown, copyrighted or publicDomain")))?,
+ ),
+ None => None,
+ };
+ let mut ops = Vec::new();
+ for id in targets {
+ let Some(ph) = s.catalog.photo(id) else { continue };
+ let mut m = ph.meta.clone();
+ if let Some(g) = gps {
+ m.gps = g;
+ }
+ if let Some(st) = status {
+ m.copyright_status = st;
+ }
+ for (k, field) in [
+ ("title", &mut m.title),
+ ("caption", &mut m.caption),
+ ("copyright", &mut m.copyright),
+ ("usageTerms", &mut m.usage_terms),
+ ("copyrightUrl", &mut m.copyright_url),
+ ("creator", &mut m.creator),
+ ("location", &mut m.location),
+ ("city", &mut m.city),
+ ("state", &mut m.state),
+ ("country", &mut m.country),
+ ("altText", &mut m.alt_text),
+ ("extendedDescription", &mut m.extended_description),
+ ] {
+ if let Some(v) = str_param(p, k) {
+ *field = v.to_string();
+ }
+ }
+ // keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case
+ use lightcraft_catalog::keywords::{clean, same};
+ let add = |m: &mut lightcraft_catalog::Meta, k: &str| {
+ let k = clean(k);
+ if !k.is_empty() && !m.keywords.iter().any(|x| same(x, &k)) {
+ m.keywords.push(k);
+ }
+ };
+ if let Some(k) = strs("keywords") {
+ m.keywords.clear();
+ for k in k {
+ add(&mut m, &k);
+ }
+ }
+ for k in strs("addKeywords").unwrap_or_default() {
+ add(&mut m, &k);
+ }
+ for k in strs("removeKeywords").unwrap_or_default() {
+ let k = clean(&k);
+ m.keywords.retain(|x| !same(&clean(x), &k));
+ }
+ ops.push(Op::SetMeta { id, meta: Box::new(m) });
+ }
+ let n = ops.len();
+ s.commit("Edit Info", Op::Batch { ops })?;
+ // keywords just added become the Recent Keywords set
+ let added: Vec<String> = strs("addKeywords").unwrap_or_default().into_iter().chain(strs("keywords").unwrap_or_default()).collect();
+ if n > 0 && !added.is_empty() {
+ crate::cmd::keywords::note_recent(s, &added);
+ }
+ Ok(json!({"changed": n}))
+ }
+ ),
+ // ---- albums
+ cmd!(
+ "album.create",
+ "New Album",
+ ["File"],
+ None,
+ "{name, parent?: folderId, folder?: bool, addSelected?: bool} → {id, skipped} (skipped: Local photos of the selection, which albums can't hold)",
+ always,
+ |s, p| {
+ let name = str_param(p, "name").unwrap_or("Untitled Album").trim().to_string();
+ if name.is_empty() {
+ return Err(bad("album.create", "empty name"));
+ }
+ let folder = bool_or(p, "folder", false);
+ let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId);
+ let (photos, skipped) = if !folder && bool_or(p, "addSelected", false) { album_targets(s, s.selected()) } else { (vec![], 0) };
+ let id = s.catalog.alloc_album_id();
+ let cover = photos.first().copied();
+ s.commit(
+ if folder { "New Folder" } else { "New Album" },
+ Op::AddAlbum { album: Album { id, name, parent, folder, photos, cover, smart: None, quick: false, order: None } },
+ )?;
+ Ok(json!({"id": id.0, "skipped": skipped}))
+ }
+ ),
+ cmd!(
+ "album.createSmart",
+ "New Smart Album…",
+ [],
+ None,
+ "{name, rules?: partial Filter (rating, ratingOp, flag, label, kind, edited, keyword, camera, lens, dateFrom, dateTo, date, text, album, ruleSet: {match: all|any|none, rules: [{field, op, value} | {group: ruleSet}]} — see album.ruleFields), parent?: folderId} — without `rules`, saves the current view (source + filter)",
+ always,
+ |s, p| {
+ let name = str_param(p, "name").unwrap_or("Smart Album").trim().to_string();
+ if name.is_empty() {
+ return Err(bad("album.createSmart", "empty name"));
+ }
+ let rules = match p.get("rules") {
+ Some(r) => merge_rules(&lightcraft_catalog::Filter::default(), r, "album.createSmart", &s.catalog, None)?,
+ None => view_rules(s),
+ };
+ let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId);
+ let id = s.catalog.alloc_album_id();
+ let album = Album { parent, smart: Some(Box::new(rules)), ..Album::new(id, name) };
+ s.commit("New Smart Album", Op::AddAlbum { album })?;
+ Ok(json!({"id": id.0, "count": s.catalog.album_count(id)}))
+ }
+ ),
+ cmd!(query "album.ruleFields", "Smart Album Rule Fields", [], None, "{} → [{field, label, kind (text|keywords|number|date|choice|bool|album: an album id), group (field-menu submenu, null at the top level), ops: [{op, label}], choices? (ids), choiceLabels? ({id: label})}] for ruleSet rules, in menu order", always, |_, _| {
+ use lightcraft_catalog::rules::{FIELDS, Kind, field_group, ops_for};
+ Ok(json!(FIELDS
+ .iter()
+ .map(|(id, label, kind)| {
+ let k = match kind {
+ Kind::Text => "text",
+ Kind::Keywords => "keywords",
+ Kind::Number => "number",
+ Kind::Album => "album",
+ Kind::Date => "date",
+ Kind::Choice(_) => "choice",
+ Kind::Bool => "bool",
+ };
+ let mut v = json!({"field": id, "label": label, "kind": k, "group": field_group(id), "ops": ops_for(*kind).iter().map(|(o, l)| json!({"op": o, "label": l})).collect::<Vec<_>>()});
+ if let Kind::Choice(c) = kind {
+ v["choices"] = json!(c.iter().map(|c| c.0).collect::<Vec<_>>());
+ v["choiceLabels"] = c.iter().map(|(id, label)| (id.to_string(), json!(label))).collect::<serde_json::Map<_, _>>().into();
+ }
+ v
+ })
+ .collect::<Vec<_>>()))
+ }),
+ cmd!(
+ "album.setRules",
+ "Edit Smart Album",
+ [],
+ None,
+ "{id, rules?: partial Filter merged onto the current rules (null clears a field), replace?: bool, fromView?: bool (use the current view), name?: also rename it (blank keeps the name) — one undo step, both or neither}",
+ always,
+ |s, p| {
+ let id = album_param(p, "id", "album.setRules")?;
+ let cur = s.catalog.album(id).and_then(|a| a.smart.as_deref().cloned()).ok_or_else(|| bad("album.setRules", "not a smart album"))?;
+ let rules = if bool_or(p, "fromView", false) {
+ // the view is saved as it is, but never as a loop (showing A, which tests this
+ // album, and saving that view here would make it test itself)
+ let view = view_rules(s);
+ let loops: Vec<String> = view
+ .rule_set
+ .as_ref()
+ .map(|r| r.check_for(&s.catalog, Some(id)))
+ .unwrap_or_default()
+ .into_iter()
+ .chain(s.catalog.album_filter_problem(&view, Some(id)))
+ .filter(|p| p.issue == lightcraft_catalog::rules::Issue::AlbumLoop)
+ .map(|p| p.to_string())
+ .collect();
+ if !loops.is_empty() {
+ return Err(bad("album.setRules", loops.join("; ")));
+ }
+ view
+ } else {
+ let replace = bool_or(p, "replace", false);
+ let folder = cur.library_folder.clone();
+ let base = if replace { Default::default() } else { cur };
+ let mut r = merge_rules(&base, p.get("rules").unwrap_or(&Value::Null), "album.setRules", &s.catalog, Some(id))?;
+ // the rules dialog has no folder field: replacing its rules keeps the folder
+ // unless the call says (`libraryFolder: null`) to drop it
+ if replace && p.get("rules").and_then(|r| r.get("libraryFolder")).is_none() {
+ r.library_folder = folder;
+ }
+ r
+ };
+ let set = Op::SetAlbumRules { id, rules: Box::new(rules) };
+ // a new name goes with the rules: one step, applied (and undone) together
+ let rename = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty() && s.catalog.album(id).is_some_and(|a| a.name != *n));
+ match rename {
+ Some(name) => s.commit("Edit Smart Album", Op::Batch { ops: vec![Op::RenameAlbum { id, name: name.to_string() }, set] })?,
+ None => s.commit("Edit Smart Album", set)?,
+ };
+ Ok(json!({"count": s.catalog.album_count(id)}))
+ }
+ ),
+ cmd!("album.rename", "Rename Album", [], None, "{id, name}", always, |s, p| {
+ let id = album_param(p, "id", "album.rename")?;
+ let name = str_param(p, "name").ok_or_else(|| bad("album.rename", "missing name"))?.to_string();
+ s.commit("Rename Album", Op::RenameAlbum { id, name })?;
+ ok()
+ }),
+ cmd!(
+ "album.delete",
+ "Delete Album",
+ [],
+ None,
+ "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step",
+ always,
+ |s, p| {
+ let id = album_param(p, "id", "album.delete")?;
+ let folder = s.catalog.album(id).ok_or_else(|| bad("album.delete", "no such album"))?.folder;
+ let mut children = std::collections::BTreeMap::<AlbumId, Vec<AlbumId>>::new();
+ for album in s.catalog.albums() {
+ if let Some(parent) = album.parent {
+ children.entry(parent).or_default().push(album.id);
+ }
+ }
+ // Iterative traversal: even a malformed cycle is rejected before any change.
+ // Reverse parent-first order removes children first; the batch inverse restores
+ // parents first, including memberships, smart rules, covers and manual ordering.
+ let mut pending = vec![id];
+ let mut order = Vec::new();
+ let mut removed = std::collections::BTreeSet::new();
+ while let Some(next) = pending.pop() {
+ if !removed.insert(next) {
+ return Err(bad("album.delete", "cycle in album folders"));
+ }
+ order.push(next);
+ if let Some(nested) = children.remove(&next) {
+ pending.extend(nested);
+ }
+ }
+ let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect();
+ s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?;
+ if matches!(s.source, LibrarySource::Album(current) if removed.contains(&current)) {
+ s.source = LibrarySource::All;
+ }
+ ok()
+ }
+ ),
+ cmd!("album.move", "Move Album", [], None, "{id, parent?: folderId|null}", always, |s, p| {
+ let id = album_param(p, "id", "album.move")?;
+ let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId);
+ s.commit("Move Album", Op::MoveAlbum { id, parent })?;
+ ok()
+ }),
+ cmd!(
+ "album.reorder",
+ "Reorder Album",
+ [],
+ None,
+ "{id, parent?: folderId|null, before?: albumId|null} — places the album (or folder) in `parent` (default: where it is; null: the top level) before the sibling `before` of the same kind, or last of its kind; the folder is then ordered by hand. One undo step. → {changed}: how many edits it took (0: already there)",
+ always,
+ |s, p| {
+ let id = album_param(p, "id", "album.reorder")?;
+ let me = s.catalog.album(id).ok_or_else(|| bad("album.reorder", "no such album"))?;
+ let parent = if p.get("parent").is_some() { opt_album_param(p, "parent", "album.reorder")? } else { me.parent };
+ let before = opt_album_param(p, "before", "album.reorder")?;
+ if before == Some(id) {
+ // before itself: where it is
+ return Ok(json!({"changed": 0}));
+ }
+ let mut order: Vec<AlbumId> = s.catalog.album_children(parent).into_iter().filter(|a| a.id != id).map(|a| a.id).collect();
+ let at = match before {
+ Some(b) => {
+ let at = order.iter().position(|x| *x == b).ok_or_else(|| bad("album.reorder", "`before` is not inside that folder"))?;
+ if s.catalog.album(b).is_none_or(|x| x.folder != me.folder) {
+ return Err(bad("album.reorder", "folders are placed among folders and albums among albums"));
+ }
+ at
+ }
+ None if me.folder => order.iter().take_while(|x| s.catalog.album(**x).is_some_and(|a| a.folder)).count(),
+ None => order.len(),
+ };
+ order.insert(at.min(order.len()), id);
+ let moved = me.parent != parent;
+ let mut ops = Vec::new();
+ if moved {
+ ops.push(Op::MoveAlbum { id, parent });
+ }
+ for (i, aid) in order.iter().enumerate() {
+ let want = u32::try_from(i).ok();
+ // a moved album starts without a place in its new folder
+ let have = if moved && *aid == id { None } else { s.catalog.album(*aid).and_then(|a| a.order) };
+ if have != want {
+ ops.push(Op::SetAlbumOrder { id: *aid, order: want });
+ }
+ }
+ if ops.is_empty() {
+ return Ok(json!({"changed": 0}));
+ }
+ let changed = ops.len();
+ s.commit("Reorder Album", Op::Batch { ops })?;
+ Ok(json!({"changed": changed}))
+ }
+ ),
+ cmd!(
+ "album.sort",
+ "Sort Albums by Name",
+ [],
+ None,
+ "{parent?: folderId|null} — drops the hand order of the albums inside the folder (default: the top level), so they are listed by name → {changed}: how many albums lost their place",
+ always,
+ |s, p| {
+ let parent = opt_album_param(p, "parent", "album.sort")?;
+ let ops: Vec<Op> = s
+ .catalog
+ .album_children(parent)
+ .into_iter()
+ .filter(|a| a.order.is_some())
+ .map(|a| Op::SetAlbumOrder { id: a.id, order: None })
+ .collect();
+ if ops.is_empty() {
+ return Ok(json!({"changed": 0}));
+ }
+ let changed = ops.len();
+ s.commit("Sort Albums by Name", Op::Batch { ops })?;
+ Ok(json!({"changed": changed}))
+ }
+ ),
+ cmd!(
+ "album.addPhotos",
+ "Add to Album",
+ ["Photo"],
+ None,
+ "{id: albumId, ids?: [photoIds]} (default: selection) → {added, skipped}; Local photos are skipped (albums hold library photos), only Local ones is an error",
+ has_library_selection,
+ |s, p| {
+ let id = album_param(p, "id", "album.addPhotos")?;
+ let targets = crate::cmd::photo_ids(p, "album.addPhotos")?.unwrap_or_else(|| s.selected());
+ let al = s.catalog.album(id).ok_or_else(|| bad("album.addPhotos", "no such album"))?;
+ if al.is_smart() || al.folder {
+ return Err(bad("album.addPhotos", "smart albums and folders can't hold photos"));
+ }
+ let (targets, skipped) = album_targets_or_err(s, "album.addPhotos", targets)?;
+ let mut photos = al.photos.clone();
+ let before = photos.len();
+ // looked up, not searched for: adding thousands to a big album stays linear
+ let mut held: std::collections::HashSet<PhotoId> = photos.iter().copied().collect();
+ for t in targets {
+ if held.insert(t) {
+ photos.push(t);
+ }
+ }
+ let added = photos.len() - before;
+ let cover = al.cover.or(photos.first().copied());
+ s.commit("Add to Album", Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] })?;
+ Ok(json!({"added": added, "skipped": skipped}))
+ }
+ ),
+ cmd!(
+ "album.toggleTarget",
+ "Add to Target Album",
+ [],
+ None,
+ "{ids?} — B: adds the photos to the target album (the Quick Collection unless one is set), or removes them when they're all in it → {album, added, skipped}; Local photos are skipped",
+ has_library_selection,
+ |s, p| {
+ let targets =
+ album_targets_or_err(s, "album.toggleTarget", crate::cmd::photo_ids(p, "album.toggleTarget")?.unwrap_or_else(|| s.selected()))?;
+ let (targets, skipped) = targets;
+ let target = s.target_album.filter(|a| s.catalog.album(*a).is_some_and(|al| !al.is_smart() && !al.folder));
+ let id = match target.or_else(|| s.catalog.quick_collection()) {
+ Some(id) => id,
+ None => {
+ let id = s.catalog.alloc_album_id();
+ let album = Album { quick: true, ..Album::new(id, "Quick Collection") };
+ s.commit("New Quick Collection", Op::AddAlbum { album })?;
+ id
+ }
+ };
+ let al = s.catalog.album(id).ok_or_else(|| bad("album.toggleTarget", "no target album"))?;
+ // looked up, not searched for: thousands toggled in a big album stay linear
+ let mut held: std::collections::HashSet<PhotoId> = al.photos.iter().copied().collect();
+ let all_in = !targets.is_empty() && targets.iter().all(|t| held.contains(t));
+ let photos: Vec<PhotoId> = if all_in {
+ let targets: std::collections::HashSet<PhotoId> = targets.iter().copied().collect();
+ al.photos.iter().copied().filter(|x| !targets.contains(x)).collect()
+ } else {
+ al.photos.iter().copied().chain(targets.iter().copied().filter(|t| held.insert(*t))).collect()
+ };
+ let name = al.name.clone();
+ let cover = al.cover.filter(|c| photos.contains(c)).or(photos.first().copied());
+ s.commit(
+ if all_in { "Remove from Target Album" } else { "Add to Target Album" },
+ Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos }, Op::SetAlbumCover { id, cover }] },
+ )?;
+ Ok(json!({"album": id.0, "name": name, "added": !all_in, "count": s.catalog.album_count(id), "skipped": skipped}))
+ }
+ ),
+ cmd!("album.setTarget", "Set as Target Album", [], None, "{id: albumId | null} (null = the Quick Collection)", always, |s, p| {
+ s.target_album = match p.get("id").and_then(Value::as_u64) {
+ Some(a) => {
+ let id = AlbumId(a);
+ let al = s.catalog.album(id).ok_or_else(|| bad("album.setTarget", "no such album"))?;
+ if al.is_smart() || al.folder {
+ return Err(bad("album.setTarget", "smart albums and folders can't hold photos"));
+ }
+ Some(id)
+ }
+ None => None,
+ };
+ Ok(json!({"target": s.target_album.map(|a| a.0)}))
+ }),
+ cmd!("album.clearQuick", "Clear Quick Collection", [], None, "{}", always, |s, _| {
+ let Some(id) = s.catalog.quick_collection() else { return ok() };
+ s.commit(
+ "Clear Quick Collection",
+ Op::Batch { ops: vec![Op::SetAlbumPhotos { id, photos: vec![] }, Op::SetAlbumCover { id, cover: None }] },
+ )?;
+ ok()
+ }),
+ cmd!(
+ "library.autoImport",
+ "Auto Import Settings",
+ [],
+ None,
+ "{folder?: path | null (off), copy?: bool (copy into the library's Originals, else add in place), album?: name | null} — a watched folder whose new photos are added as they arrive (library.autoImportScan; the app scans every few seconds) → the settings",
+ always,
+ |s, p| {
+ if let Some(f) = p.get("folder") {
+ s.import_defaults.auto_folder = match f.as_str().map(str::trim).filter(|f| !f.is_empty()) {
+ Some(f) if std::path::Path::new(f).is_dir() || cfg!(target_arch = "wasm32") => Some(f.to_string()),
+ Some(f) => return Err(bad("library.autoImport", format!("`{f}` is not a folder"))),
+ None => None,
+ };
+ }
+ if let Some(c) = p.get("copy").and_then(Value::as_bool) {
+ s.import_defaults.auto_copy = c;
+ }
+ if let Some(a) = p.get("album") {
+ s.import_defaults.auto_album = a.as_str().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
+ }
+ s.save_prefs()?;
+ let d = &s.import_defaults;
+ Ok(json!({"folder": d.auto_folder, "copy": d.auto_copy, "album": d.auto_album}))
+ }
+ ),
+ cmd!(
+ "library.autoImportScan",
+ "Auto Import Now",
+ [],
+ None,
+ "{listing?: [[path, size]] (the folder as listed by the caller, e.g. on a worker thread), start?: bool (false: return the `library.import` params as `import` instead of importing)} — add the watched folder's new photos (files the library doesn't have yet; partial / still-copying files wait for the next scan) → {imported, folder, warnings?: [{path, code, profile?, mode?, fields?}], import?}",
+ always,
+ |s, p| {
+ let Some(folder) = s.import_defaults.auto_folder.clone() else { return Ok(json!({"imported": [], "folder": null})) };
+ // only files that stopped growing: a file still being written is left for later
+ let known: std::collections::HashSet<String> = s
+ .catalog
+ .photos()
+ .filter_map(|p| match &p.source {
+ lightcraft_catalog::Source::File { path } => Some(path.clone()),
+ _ => None,
+ })
+ .collect();
+ // the folder's files and sizes: listed here, or already listed on a worker thread (the app)
+ let listing: Vec<(String, u64)> = match p.get("listing").and_then(Value::as_array) {
+ Some(l) => l.iter().filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_u64()?))).collect(),
+ None => list_auto_import_folder(&folder).map_err(|e| bad("library.autoImportScan", e))?,
+ };
+ let mut fresh = Vec::new();
+ for (ps, size) in listing {
+ if known.contains(&ps) {
+ continue;
+ }
+ // each file is tried once (a non-photo isn't retried every scan)
+ if s.auto_import_seen.get(&ps) == Some(&u64::MAX) {
+ continue;
+ }
+ let seen = s.auto_import_seen.insert(ps.clone(), size);
+ if size > 0 && seen == Some(size) {
+ fresh.push(ps);
+ }
+ }
+ if fresh.is_empty() {
+ return Ok(json!({"imported": [], "folder": folder}));
+ }
+ let mode = if s.import_defaults.auto_copy { "copy" } else { "add" };
+ // a photo deleted from the library doesn't come back on its own because its file
+ // is still in the watched folder (a copy's source is not a known path)
+ let mut params = json!({"paths": fresh, "mode": mode, "onDeleted": "skip"});
+ if let Some(a) = s.import_defaults.auto_album.clone() {
+ match s.catalog.albums().find(|al| al.name.eq_ignore_ascii_case(&a) && !al.folder && !al.is_smart()) {
+ Some(al) => params["album"] = json!(al.id.0),
+ None => params["albumName"] = json!(a),
+ }
+ }
+ for f in &fresh {
+ s.auto_import_seen.insert(f.clone(), u64::MAX);
+ }
+ if p.get("start").and_then(Value::as_bool) == Some(false) {
+ // the caller imports them (the app: on a worker thread)
+ return Ok(json!({"imported": [], "folder": folder, "import": params}));
+ }
+ let sel = s.selection.clone();
+ let r = s.execute("library.import", &params)?;
+ // arriving photos don't take over the selection
+ s.selection = sel;
+ let mut result = json!({"imported": r["imported"], "folder": folder});
+ if let Some(warnings) = r.get("warnings") {
+ result["warnings"] = warnings.clone();
+ }
+ Ok(result)
+ }
+ ),
+ cmd!(
+ "album.removePhotos",
+ "Remove from Album",
+ ["Photo"],
+ None,
+ "{id?: albumId (default: the album on screen), ids?} — takes the photos out of the album only: they stay in the library and in their folders (issue #1805; photo.delete removes them from the library) → {removed, album: name}",
+ has_selection,
+ |s, p| {
+ let id = match p.get("id") {
+ Some(_) => album_param(p, "id", "album.removePhotos")?,
+ None => match s.source {
+ LibrarySource::Album(a) => a,
+ _ => return Err(bad("album.removePhotos", "no album: pass `id` or show an album")),
+ },
+ };
+ let targets = crate::cmd::photo_ids(p, "album.removePhotos")?.unwrap_or_else(|| s.selected());
+ let al = s.catalog.album(id).ok_or_else(|| bad("album.removePhotos", "no such album"))?;
+ if al.is_smart() {
+ return Err(bad("album.removePhotos", "smart albums update automatically: change their rules"));
+ }
+ if al.folder {
+ return Err(bad("album.removePhotos", "album folders don't hold photos"));
+ }
+ let name = al.name.clone();
+ let targets: std::collections::HashSet<PhotoId> = targets.into_iter().collect();
+ let photos: Vec<PhotoId> = al.photos.iter().copied().filter(|x| !targets.contains(x)).collect();
+ let removed = al.photos.len().saturating_sub(photos.len());
+ if removed > 0 {
+ s.commit("Remove from Album", Op::SetAlbumPhotos { id, photos })?;
+ }
+ Ok(json!({"removed": removed, "album": name}))
+ }
+ ),
+ cmd!("album.setCover", "Set as Album Cover", [], None, "{id: albumId, photo?: photoId}", has_active, |s, p| {
+ let id = album_param(p, "id", "album.setCover")?;
+ let photo = p.get("photo").and_then(Value::as_u64).map(PhotoId).or(s.active());
+ s.commit("Set Album Cover", Op::SetAlbumCover { id, cover: photo })?;
+ ok()
+ }),
+ // ---- import
+ cmd!(query "library.inspectLightroom", "Inspect Lightroom Catalog", [], None,
+ "{path: .lrcat} → {photos, collections, missing, warnings}; read-only, no Lightroom required",
+ always, |_, p| {
+ let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?;
+ let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?;
+ Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings,"skipped":data.skipped}))
+ }),
+ cmd!(
+ "library.importLightroom",
+ "Import Lightroom Catalog",
+ [],
+ None,
+ "{path: .lrcat, updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.",
+ always,
+ |s, p| {
+ let path = str_param(p, "path").ok_or_else(|| bad("library.importLightroom", "missing path"))?;
+ crate::lightroom_catalog::import(s, std::path::Path::new(path), bool_or(p, "updateExisting", false))
+ }
+ ),
+ cmd!(
+ query "library.importPreview",
+ "Review Import",
+ [],
+ None,
+ "{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned} — nothing is added",
+ always,
+ |s, p| {
+ let paths = strs(p, "paths");
+ if paths.is_empty() {
+ return Err(bad("library.importPreview", "no paths"));
+ }
+ let c = crate::import::scan(s, &paths);
+ let dups = c.iter().filter(|c| c.duplicate.is_some()).count();
+ Ok(json!({"scanned": c.len(), "duplicates": dups, "candidates": c}))
+ }
+ ),
+ cmd!(
+ "library.import",
+ "Import Photos",
+ ["File"],
+ Some("Cmd+Shift+I"),
- "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1, metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
++ "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
+ always,
+ |s, p| {
+ let req = import_params(s, p)?;
+ if req.paths.is_empty() {
+ return Err(bad("library.import", "no paths"));
+ }
+ let undo0 = s.undo.len();
+ let report = crate::import::import_with(s, &req.paths, &req.opts)?;
+ let report = import_batch_done(s, report, req.album, req.album_name.as_deref())?;
+ // one undo step for the whole import
+ let ids_of = |k: &str| -> Vec<u64> { report[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default() };
+ let (imported, restored) = (ids_of("imported"), ids_of("restored"));
+ let n = s.undo.len().saturating_sub(undo0);
+ let (verb, count) = if imported.is_empty() && !restored.is_empty() { ("Restore", restored.len()) } else { ("Add", imported.len()) };
+ s.merge_undo(n, &format!("{verb} {count} Photo{}", if count == 1 { "" } else { "s" }));
+ let imported = if imported.is_empty() { restored } else { imported };
+ if let Some(f) = imported.first() {
+ s.selection = Selection::single(PhotoId(*f));
+ }
+ Ok(report)
+ }
+ ),
+ // ---- persistence
+ cmd!(query "library.info", "Library Info", [], None, "{}", always, |s, _| {
+ let photos = s.catalog.len();
+ let albums = s.catalog.albums().count();
+ let (rendered_n, rendered_bytes) = s.media.rendered.mem_usage();
+ let (sources_n, sources_bytes) = s.media.source_usage();
+ let disk = s.media.rendered.disk().map(|d| {
+ use std::sync::atomic::Ordering::Relaxed;
+ json!({
+ "path": d.dir().display().to_string(),
+ "bytes": d.size(),
+ "hits": d.hits.load(Relaxed),
+ "misses": d.misses.load(Relaxed),
+ "writes": d.writes.load(Relaxed),
+ })
+ });
+ let cache = json!({
+ "renderedInMemory": rendered_n, "renderedBytes": rendered_bytes,
+ "sourcesInMemory": sources_n, "sourceBytes": sources_bytes,
+ "disk": disk,
+ });
+ let Some(lib) = &s.library else {
+ return Ok(json!({"persistent": false, "photos": photos, "albums": albums, "cache": cache}));
+ };
+ let j = lib.journal();
+ Ok(json!({
+ "persistent": true,
+ "path": lib.dir.display().to_string(),
+ "photos": photos,
+ "albums": albums,
+ "seq": j.seq(),
+ "snapshotSeq": j.snapshot_seq(),
+ "logRecords": j.log_records(),
+ "logBytes": j.log_bytes(),
+ "lastError": lib.last_error,
+ // settings files that were unreadable or damaged at open (kept, defaults used)
+ "settingsWarnings": lib.settings_warnings,
+ // changes applied in memory whose write failed (retried by every save)
+ "unsavedOps": s.unsaved().map_or(0, |u| u.0),
+ "unsavedError": s.unsaved().map(|u| u.1),
+ // untouched Local records forgotten when the library opened
+ "forgotLocal": lib.forgot_local.as_ref().map(|p| json!({"forgotten": p.evict.len(), "local": p.local, "keptRecent": p.kept_recent, "keptTouched": p.kept_touched, "keptInUse": p.kept_in_use})),
+ "persistence": j.stats(),
+ "cache": cache,
+ "load": {
+ "created": lib.report.created,
+ "replayed": lib.report.replayed,
+ "tornBytes": lib.report.torn_bytes,
+ "damaged": lib.report.damaged,
+ },
+ }))
+ }),
+ cmd!("library.compact", "Optimize Library", ["File"], None, "{}", has_library, |s, _| {
+ s.compact_library()?;
+ ok()
+ }),
+ cmd!("library.clearPreviews", "Discard Preview Cache", ["File"], None, "{}", always, |s, _| {
+ s.media.rendered.clear();
+ s.media.clear_sources();
+ ok()
+ }),
+ ]
+}
diff --cc crates/engine/src/import/job.rs
index 903308b03,000000000..ac94f4030
mode 100644,000000..100644
--- a/crates/engine/src/import/job.rs
+++ b/crates/engine/src/import/job.rs
@@@ -1,515 -1,0 +1,525 @@@
+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::types::{ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted};
+use super::{HashMap, 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<ImportReport> {
+ import_with(s, paths, &ImportOptions { mode, ..Default::default() })
+}
+
+/// Import files/folders with options (preset, keywords). See the module docs.
+///
+/// The file-system half ([`ImportJob::prepare`]: expanding folders, probing, reading sidecars,
+/// copying / placing files) and the catalog half ([`commit_prepared`]) are separate so the app can
+/// run the first on a worker thread; here both run in turn.
+pub fn import_with(s: &mut Session, paths: &[String], opts: &ImportOptions) -> crate::Result<ImportReport> {
+ let mut job = ImportJob::new(s, opts.clone())?;
+ let prepared = job.prepare(paths, &std::sync::atomic::AtomicBool::new(false));
+ // probes a scan left for files not imported now stay for a later import
+ s.import_probes.extend(std::mem::take(&mut job.cache));
+ commit_prepared(s, &job.opts, &job.now, prepared)
+}
+
+/// Everything the file-system half of an import needs, detached from the session so it can run
+/// on another thread (a network share or a card can take minutes). Built by [`ImportJob::new`];
+/// [`ImportJob::prepare`] may be called for several batches in turn (renamed copies keep counting,
+/// duplicates are found across batches); each batch is then [`commit_prepared`] on the session.
+pub struct ImportJob {
+ pub opts: ImportOptions,
+ /// The mode in effect (Copy / Move become Add in a library without its own folder).
+ mode: ImportMode,
+ lib_dir: Option<PathBuf>,
+ copy_root: Option<PathBuf>,
+ /// The library as it was when the import was set up, until it is looked up
+ /// ([`ImportJob::look_up_library`], with the first files): setting an import up is the
+ /// session's thread, and a table of a library of millions of photos takes seconds. With it,
+ /// whether a photo in Recently Deleted is passed over (an import that replaces such photos,
+ /// as the options said when the import was set up).
+ pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>,
+ /// path → (photo, a Local browse record?)
+ pub(super) by_path: HashMap<String, (PhotoId, bool)>,
+ /// content hash → the photo that has it (`None`: a file earlier in this import)
+ pub(super) by_hash: HashMap<String, Option<PhotoId>>,
+ pub(super) probe: Option<crate::media::FileProbe>,
+ file_bytes: Option<crate::merge::ByteReader>,
+ /// Probes from a preceding scan (not read again).
+ pub(super) cache: HashMap<String, ProbeInfo>,
+ naming: crate::sidecar::SidecarNaming,
+ now: String,
- seq: usize,
++ /// Next rename number; `None` once the final representable value has been reserved.
++ seq: Option<usize>,
+ /// Files found so far (folders expanded) and handled so far, for progress.
+ pub total: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub done: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ /// Of those, the files that have to be read first (not probed by a preceding scan) and the
+ /// ones read so far: the step before they are handled.
+ pub read_total: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+ pub read_done: std::sync::Arc<std::sync::atomic::AtomicUsize>,
+}
+
+/// The outcome of [`ImportJob::prepare`] for one batch, in file order.
+#[derive(Debug, Default)]
+pub struct Prepared {
+ pub scanned: usize,
+ pub(super) items: Vec<PreparedItem>,
+}
+
+#[derive(Debug)]
+pub(super) enum PreparedItem {
+ /// A Local (browsed) record imported for real.
+ Promote(PhotoId),
+ Duplicate {
+ path: String,
+ existing: Option<PhotoId>,
+ reason: &'static str,
+ hash: Option<String>,
+ },
+ Failed(String, String),
+ Kept(Kept),
+ Ready(Box<ReadyFile>),
+}
+
+#[derive(Debug)]
+pub(super) struct ReadyFile {
+ pub(super) path: String,
+ pub(super) stored: String,
+ pub(super) info: ProbeInfo,
+ pub(super) sidecar: Option<crate::sidecar::SidecarData>,
+ pub(super) placed: Option<crate::import_move::Placed>,
+}
+
+impl Prepared {
+ /// Undo what the batch did on disk that only a commit would make permanent: files placed by a
+ /// Move (their sources were never touched). Copies stay, like copies of a failed commit.
+ pub fn rollback(&self) {
+ for it in &self.items {
+ if let PreparedItem::Ready(r) = it
+ && let Some(pl) = &r.placed
+ {
+ crate::import_move::rollback(pl);
+ }
+ }
+ }
+
+ /// Entries in the batch (after expanding folders).
+ pub fn len(&self) -> usize {
+ self.items.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.items.is_empty()
+ }
+
+ /// Recheck Add-only entries against the owner catalog immediately before commit.
+ /// Preparation may have run while another import added the same path or content.
+ pub fn revalidate_add(&mut self, s: &Session) {
+ let mut paths = HashMap::new();
+ let mut hashes = HashMap::new();
+ for photo in s.catalog.photos() {
+ if let Source::File { path } = &photo.source {
+ paths.insert(normalize_import_path(path), photo.id);
+ }
+ if let Some(hash) = &photo.content_hash {
+ hashes.insert(hash.clone(), photo.id);
+ }
+ }
+ let mut items = Vec::with_capacity(self.items.len());
+ for item in std::mem::take(&mut self.items) {
+ let PreparedItem::Ready(ready) = item else {
+ items.push(item);
+ continue;
+ };
+ let ReadyFile { path, stored, info, sidecar, placed } = *ready;
+ let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied());
+ let existing_hash = info.content_hash.as_ref().and_then(|hash| hashes.get(hash).copied());
+ if let Some(existing) = existing_path.or(existing_hash) {
+ if let Some(placed) = &placed {
+ crate::import_move::rollback(placed);
+ }
+ items.push(PreparedItem::Duplicate {
+ path,
+ existing: Some(existing),
+ reason: if existing_path.is_some() { "path" } else { "content" },
+ hash: info.content_hash,
+ });
+ } else {
+ items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed })));
+ }
+ }
+ self.items = items;
+ }
+}
+
+fn normalize_import_path(path: &str) -> String {
+ let path = path.replace('\\', "/");
+ if cfg!(windows) { path.to_lowercase() } else { path }
+}
+
+impl ImportJob {
+ /// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes
+ /// the probes a preceding scan left ([`Session::import_probes`]).
+ pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result<Self> {
+ let mode = opts.mode;
+ // Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of
+ // every added file in its own storage already, so "copy" there means "add".
+ let transfer = matches!(mode, ImportMode::Copy | ImportMode::Move);
+ let mode = if transfer && s.library.as_ref().is_some_and(|l| !l.on_disk) { ImportMode::Add } else { mode };
+ if mode == ImportMode::Move && opts.local {
+ return Err(crate::EngineError::Other("browsing a folder never moves its files".into()));
+ }
+ let lib_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone());
+ // where copies go: the chosen folder, else the library's Originals/
+ let copy_root = opts
+ .destination
+ .as_deref()
+ .filter(|d| !d.trim().is_empty())
+ .map(std::path::PathBuf::from)
+ .or_else(|| lib_dir.as_ref().map(|l| l.join("Originals")));
+ if matches!(mode, ImportMode::Copy | ImportMode::Move) && copy_root.is_none() {
+ return Err(crate::EngineError::Other("copying or moving needs a destination folder or an open library".into()));
+ }
+ let fresh = opts.on_deleted == OnDeleted::Fresh;
+ Ok(ImportJob {
- seq: opts.rename_start.max(1),
++ seq: Some(opts.rename_start.max(1)),
+ opts,
+ mode,
+ lib_dir,
+ copy_root,
+ library: Some((s.catalog.clone(), fresh)),
+ by_path: HashMap::new(),
+ by_hash: HashMap::new(),
+ probe: s.media.file_probe.clone(),
+ file_bytes: s.media.file_bytes.clone(),
+ cache: std::mem::take(&mut s.import_probes),
+ naming: s.xmp.naming,
+ now: (s.clock)(),
+ total: Default::default(),
+ done: Default::default(),
+ read_total: Default::default(),
+ read_done: Default::default(),
+ })
+ }
+
+ /// The file-system half of importing `paths`: expand folders, skip known paths, probe, skip
+ /// duplicates by content, read sidecars, copy or place (Move) the files — several at once,
+ /// with the names and outcomes of one after another. Nothing in the catalog changes. Stops
+ /// before the next file once `cancel` is set.
+ pub fn prepare(&mut self, paths: &[String], cancel: &std::sync::atomic::AtomicBool) -> Prepared {
+ let files = self.expand(paths);
+ self.prepare_files(files, cancel)
+ }
+
+ /// 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<String> {
+ let files = expand(paths, self.lib_dir.as_deref());
+ self.total.fetch_add(files.len(), std::sync::atomic::Ordering::Relaxed);
+ files
+ }
+
+ /// When the import started ([`Session::clock`]), for [`commit_prepared`].
+ pub fn now(&self) -> &str {
+ &self.now
+ }
+
+ /// What the library held when the import was set up, by path and by content: made once, with
+ /// the first files (on the thread that prepares them), from the library as it was then. The
+ /// snapshot comes back: the files the import is adding are ranked against it for the ownership
+ /// of the shared stem sidecars they read ([`crate::sidecar::ImportStems`]).
+ fn look_up_library(&mut self) -> Option<lightcraft_catalog::Catalog> {
+ let (library, fresh) = self.library.take()?;
+ for p in library.photos() {
+ // a trashed photo is replaced by a fresh import, so it doesn't count as a duplicate
+ if p.deleted && fresh {
+ continue;
+ }
+ if let Source::File { path } = &p.source {
+ self.by_path.insert(path.clone(), (p.id, p.local));
+ }
+ if let Some(h) = &p.content_hash {
+ self.by_hash.insert(h.clone(), Some(p.id));
+ }
+ }
+ Some(library)
+ }
+
+ /// [`ImportJob::prepare`] for files [`ImportJob::expand`] returned.
+ pub fn prepare_files(&mut self, files: Vec<String>, cancel: &std::sync::atomic::AtomicBool) -> Prepared {
+ 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();
+ let opts = self.opts.clone();
+ let mode = self.mode;
+ let mut out = Prepared { scanned: files.len(), items: Vec::new() };
+ let mut todo = Vec::new();
+ for f in files {
+ match self.by_path.get(f.as_str()).copied() {
+ Some((id, true)) if !opts.local => {
+ // a file that was only browsed (Local) joins the library when it is imported for real
+ self.by_path.insert(f, (id, false));
+ out.items.push(PreparedItem::Promote(id));
+ self.done.fetch_add(1, Relaxed);
+ }
+ Some((id, _)) => {
+ out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None });
+ self.done.fetch_add(1, Relaxed);
+ }
+ None => todo.push(f),
+ }
+ }
+
+ // files a preceding scan already probed are not read again (a network share is slow to read),
+ // as long as they are still there, as they were: a file gone or changed since is probed again
+ let cached = reusable_probes(&todo, &mut self.cache, cancel, |seen, info| {
+ // (the web's files are not std::fs files: kept as probed)
+ cfg!(target_arch = "wasm32") || matches!(seen, Seen::At { is_file: true, len } if len == info.file_size)
+ });
+ let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();
+ // Reading the files is the slow part of adding them where they are: it is counted on its
+ // own, and `cancel` stops it too (a large library takes long enough to want both).
+ self.read_total.fetch_add(missing.len(), Relaxed);
+ let mut fresh = probe_all(self.probe.as_ref(), &missing, &self.read_done, cancel).into_iter();
+ let probed: Vec<Result<ProbeInfo, String>> =
+ cached.into_iter().map(|c| c.map(Ok).unwrap_or_else(|| fresh.next().unwrap_or_else(|| Err("not probed".into())))).collect();
+ crate::memory::release();
+ // Who owns the shared stem sidecar (`IMG_0001.xmp`) among the library's files and the ones
+ // arriving with this import: a JPEG or a TIFF arriving beside its raw reads its own sidecar
+ // and never the raw's packet (issue #1905).
+ let stems = crate::sidecar::ImportStems::for_import(
+ library.as_ref(),
+ todo.iter().zip(&probed).filter_map(|(path, info)| info.as_ref().ok().map(|i| (path.as_str(), i.kind))),
+ );
+ // The sidecar of every file that was probed, looked up for the batch at once: each is a few
+ // 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)
+ 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))))
+ .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();
+ // 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.
+ let mut plan = Plan::default();
+ for (path, info) in todo.into_iter().zip(probed) {
+ if cancel.load(Relaxed) {
+ break;
+ }
+ let mut info = match info {
+ Ok(i) => i,
+ Err(e) => {
+ log::warn!("import {path}: {e}");
+ self.done.fetch_add(1, Relaxed);
+ plan.slots.push(Slot::Item(PreparedItem::Failed(path, e)));
+ continue;
+ }
+ };
+ // (this file's place in the lookups above: files that failed to probe have none)
+ let found_sidecar = found.next().flatten();
+ // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds
+ if !opts.local
+ && let Some(h) = &info.content_hash
+ && plan.transfers.iter().any(|t| t.info.content_hash.as_ref() == Some(h))
+ {
+ self.run_plan(&mut plan, &mut out, cancel);
+ if cancel.load(Relaxed) {
+ break;
+ }
+ }
+ if let Some(h) = &info.content_hash
+ && !opts.local
+ && let Some(existing) = self.by_hash.get(h)
+ {
+ self.done.fetch_add(1, Relaxed);
+ plan.slots.push(Slot::Item(PreparedItem::Duplicate { path, existing: *existing, reason: "content", hash: Some(h.clone()) }));
+ continue;
+ }
+ // 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
+ let raw = info.kind == MediaKind::Raw;
+ let packet = found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw));
+ let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
+ let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
+ Ok(sc) => Some(sc),
+ Err(e) => {
+ log::warn!("import {path}: XMP: {e}");
+ None
+ }
+ });
+ if info.captured.is_none() {
+ info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone());
+ }
+ // no date in the file or its sidecar: the file's own date, as Lightroom does
+ if info.captured.is_none() {
+ info.captured = info.file_modified.clone();
+ }
+ let stored = match (mode, &self.copy_root) {
+ (ImportMode::Copy | ImportMode::Move, Some(root))
+ if !crate::import_move::inside(Path::new(&path), root)
+ && !self.lib_dir.as_ref().is_some_and(|l| crate::import_move::inside(Path::new(&path), l)) =>
+ {
+ // the templates see the photo as it will be catalogued (undated: the import time)
+ let own = Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
+ let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now);
+ q.captured = info.captured.clone();
+ q.meta = info.meta.clone();
- let name = opts.rename.as_deref().filter(|t| !t.trim().is_empty()).map(|t| {
- let n = crate::rename::expand(t, &q, self.seq);
- self.seq += 1;
- n
- });
++ let name = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) {
++ let Some(seq) = self.seq else {
++ self.done.fetch_add(1, Relaxed);
++ plan.slots.push(Slot::Item(PreparedItem::Failed(
++ path,
++ "rename sequence exhausted; choose a lower renameStart or leave rename blank".into(),
++ )));
++ continue;
++ };
++ self.seq = seq.checked_add(1);
++ Some(crate::rename::expand(template, &q, seq))
++ } else {
++ None
++ };
+ let folders = opts.organize.folders(&q);
+ let dir = folders.iter().fold(root.to_path_buf(), |d, f| d.join(f));
+ // the name this file gets depends on what a pending transfer of a like-named file
+ // into the same folder ends up with: that one goes first
+ let as_named = name.as_deref().unwrap_or(if own.is_empty() { "photo" } else { own.as_str() });
+ let family = (dir.to_string_lossy().to_lowercase(), name_family(as_named));
+ if plan.transfers.iter().any(|t| t.family == family) {
+ self.run_plan(&mut plan, &mut out, cancel);
+ if cancel.load(Relaxed) {
+ break;
+ }
+ }
+ let how = if mode == ImportMode::Move && !crate::import_move::is_symlink(Path::new(&path)) {
+ How::Place { name: name.unwrap_or(own) }
+ } else {
+ if mode == ImportMode::Move {
+ let reason = "a symbolic link: the file it points to was copied, the link and its target stay";
+ plan.slots.push(Slot::Item(PreparedItem::Kept(Kept { path: path.clone(), reason: reason.into() })));
+ }
+ How::Copy { name }
+ };
+ // Copy as DNG: the copied raw becomes a DNG (the copy is ours to replace)
+ let dng = opts.convert_dng && mode == ImportMode::Copy && raw && !info.format.eq_ignore_ascii_case("DNG");
+ plan.slots.push(Slot::Transfer);
+ plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng, family });
+ continue;
+ }
+ (ImportMode::Move, _) => {
+ let reason = "already inside the destination or the library: added where it is";
+ plan.slots.push(Slot::Item(PreparedItem::Kept(Kept { path: path.clone(), reason: reason.into() })));
+ path.clone()
+ }
+ _ => path.clone(),
+ };
+ if let Some(h) = &info.content_hash {
+ self.by_hash.insert(h.clone(), None);
+ }
+ self.done.fetch_add(1, Relaxed);
+ plan.slots.push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed: None }))));
+ }
+ self.run_plan(&mut plan, &mut out, cancel);
+ out
+ }
+
+ /// Run the transfers `plan` collected (on several threads) and append its items to `out` in
+ /// file order. Transfers not started because `cancel` was set leave no item.
+ fn run_plan(&mut self, plan: &mut Plan, out: &mut Prepared, cancel: &std::sync::atomic::AtomicBool) {
+ let mut done = run_transfers(std::mem::take(&mut plan.transfers), self.file_bytes.as_ref(), cancel, &self.done).into_iter();
+ for slot in std::mem::take(&mut plan.slots) {
+ let item = match slot {
+ Slot::Item(it) => it,
+ Slot::Transfer => match done.next().flatten() {
+ Some(it) => it,
+ None => continue,
+ },
+ };
+ if let PreparedItem::Ready(r) = &item
+ && let Some(h) = &r.info.content_hash
+ {
+ self.by_hash.insert(h.clone(), None);
+ }
+ out.items.push(item);
+ }
+ }
+}
+
+/// Identity of a candidate preview at the bounded requested edge, without constructing a job.
+pub fn candidate_thumb_key(c: &ImportCandidate, edge: usize) -> u64 {
+ lightcraft_preview::Hasher128::new().str(&c.path).u64(c.file_size).u64(edge.clamp(64, 1024) as u64).finish().0 as u64
+}
+
+impl Session {
+ /// A thumbnail for an import candidate (not in the catalog): a raw's embedded preview, else a
+ /// small render of the file. `slot` makes the job's photo id unique (`u64::MAX - slot`).
+ pub fn candidate_thumb_job(&mut self, c: &ImportCandidate, edge: usize, slot: u64) -> Option<crate::media::QuickJob> {
+ if c.error.is_some() {
+ return None;
+ }
+ let id = PhotoId(u64::MAX - slot);
+ let mut p = Photo::new(id, Source::File { path: c.path.clone() }, &c.name, &c.format, c.width.max(1), c.height.max(1), "");
+ p.kind = c.kind;
+ if let Some(info) = self.import_probes.get(&c.path) {
+ p.as_shot_wb = info.as_shot_wb;
+ p.embedded_lens = info.embedded_lens;
+ p.preview_only = info.preview_only.clone();
+ }
+ p.develop = std::sync::Arc::new(p.import_defaults());
+ let edge = edge.clamp(64, 1024);
+ let level = crate::media::SourceLevel::for_size(edge);
+ let source = self.media.origin_ref(&p.source, level.max_edge());
+ let key = candidate_thumb_key(c, edge);
+ // A small original already supplies all its detail; do not enlarge it to the bucket.
+ let native_edge = c.width.max(c.height) as usize;
+ let render_edge = if native_edge > 0 { edge.min(native_edge) } else { edge };
+ let small = crate::media::RenderJob {
+ request_id: 0,
+ cache_generation: self.media.rendered.generation(),
+ source_key: None,
+ photo: id,
+ level,
+ source,
+ origin: p.source.clone(),
+ info: crate::media::source_info(&p),
+ settings: p.develop.clone(),
+ request: lightcraft_pipeline::RenderRequest::fit(render_edge, render_edge),
+ key,
+ cache: None,
+ stages: None,
+ view_cache: None,
+ display: None,
+ slide: None,
+ preview_cut: None,
+ display_fit: None,
+ };
+ let embedded = match (&self.media.preview_loader, c.kind) {
+ (Some(l), MediaKind::Raw) => Some((c.path.clone(), l.clone(), edge)),
+ _ => None,
+ };
+ let minimum_embedded_edge = (c.preview_only.is_none() && p.preview_only.is_none()).then_some(render_edge);
+ Some(crate::media::QuickJob {
+ request_id: 0,
+ photo: id,
+ key,
+ cached: Vec::new(),
+ embedded,
+ minimum_embedded_edge,
+ small: Some(Box::new(small)),
+ })
+ }
+
+ /// Use the system clock for import/edit times (native hosts).
+ pub fn with_system_clock(mut self) -> Self {
+ self.clock = Box::new(system_clock);
+ self
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --cc docs/gaps.md
index e912040e1,9a67f7344..ead7fc091
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -1,6 -1,6 +1,6 @@@
# Gaps: where LightCraft falls short of Lightroom
- > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-29 · **Change:** minor (import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF)
-> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (import: checked rename-sequence exhaustion; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF)
++> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-29 · **Change:** minor (import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 551 models verified; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF)
Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and
how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is
@@@ -86,8 -84,7 +86,9 @@@ Beta-blocking gaps (B) total **~230–4
| Date | Change | Summary |
|---|---|---|
+| 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes |
+| 2026-10-24 | minor | Gap 8: lens profile work is tracked in #329; hours unchanged |
+ | 2026-10-25 | patch | Import Copy and Move report rename-sequence exhaustion per file without losing earlier transfers; no ranked gap or readiness changes |
| 2026-10-24 | minor | Gap 28: ⌘⌥⇧C / ⌘⌥⇧V (Ctrl+Alt+Shift+C / V on Windows and Linux) copy and paste metadata; no key leaves the entry; hours unchanged |
| 2026-10-24 | minor | Gap 30 shrinks: the Info panel's Show Metadata For (Target Photo / Selected Photos, `view.infoSelectedPhotos`) shows the selected photos' shared values and marks fields that differ as Mixed; the All Metadata dialog remains; 1–3 h (was 4–8) |
| 2026-10-23 | minor | Gap 13: before a Lightroom catalog import the app asks whether it merges into the open library or goes into a new one (opt-out in Settings, #2672); hours unchanged |
diff --cc docs/parity-checklist.md
index f7b9e74d6,2f4b9f54c..73f7f8836
--- a/docs/parity-checklist.md
+++ b/docs/parity-checklist.md
@@@ -1,6 -1,6 +1,6 @@@
# Lightroom parity checklist
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we
have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good
@@@ -69,13 -69,13 +69,13 @@@ differences and missing bindings are i
| Id | Feature | Tier | Status | Evidence | Missing / notes |
|---|---|---|---|---|---|
- | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip |
-| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/album_picker.rs`, `crates/ui-egui/src/tests_album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests_import.rs`) |
-| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests_drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported |
-| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests_import.rs` | |
-| LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/import.rs`) |
-| LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/panels/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s |
++| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip |
+| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported |
+| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | |
+| LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) |
+| LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s |
| LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry |
-| LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/panels/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it |
+| LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/dialogs/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it |
| LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | |
| LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) |
| LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) |
@@@ -84,8 -84,8 +84,8 @@@
| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. |
| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), and mid-sized NEF / RW2 JPEGs; a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) |
| LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic |
- | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving |
-| LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving |
-| LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) |
++| LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving |
+| LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/dialogs/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) |
## B. Library management (LIB)
@@@ -799,8 -799,7 +799,9 @@@ Latin stays upright. Advanced Japanese
| Date | Change | Summary |
|---|---|---|
+| 2026-10-29 | minor | LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket, with sharper raw fallback and the available camera JPEG retained when rendering cannot help (#2237, part of #2056); import loupe remains open; counts unchanged |
+| 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged |
+ | 2026-10-25 | patch | LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence reservation; exhausted later files are reported failed while earlier transfers remain accounted for; status counts unchanged |
| 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) |
| 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) |
| 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged |
diff --cc docs/whats-new.md
index 04bf78035,ed890b838..1aaf93b0e
--- a/docs/whats-new.md
+++ b/docs/whats-new.md
@@@ -1,29 -1,14 +1,34 @@@
# What's new in LightCraft
+## 2026-10-27
+
+### The Edit menu groups Select Only Active Photo and Paste Settings from Previous with their kin
+- Select Only Active Photo now sits under Deselect All, and Paste Settings from Previous under Paste Selected Settings…, instead of both after Settings…, near the end of the Edit menu. On macOS, where Settings… lives in the application menu, the Edit menu no longer shows two separator lines in a row.
+
## 2026-10-25
+### `>=` and `<=` work in the search box
+- Fielded search tokens now take inclusive comparisons: `rating:>=3`, `iso:<=400`, `f:>=2.8`, `focal:<=50`. Before,
+ the `=` was read as part of the number, so such a search quietly showed no photos at all.
+
+ ### Import rename numbering stops safely at its limit
+ - Copy and Move imports can use the last representable rename number once. If more renamed files remain, each is
+ reported as failed with guidance to lower `renameStart` or leave `rename` blank; completed transfers stay
+ accounted for and catalogued. A `renameStart` value outside this platform's range is rejected before setup.
+
## 2026-10-24
+### A refused move no longer switches the Move Photos question off
+- Ticking Don't ask again in the question that appears when you drop photos on a Folders row used to be remembered even when the move was then refused (for example because a file of the same name is already in that folder). The choice is now kept only once the move has started, so a refused move leaves the question on.
+
+### Importing a folder from a network share waits less
+- After the import review, the import used to check that each photo was still as the review had seen it by asking the
+ disk about one photo after another, so on a network share every photo waited for a round trip to the server. It now
+ asks about up to 16 photos at a time, the same wait for every 16 instead of for each one. Reading the photos in the review
+ is unchanged.
+- Looking for each photo's `.xmp` sidecar, which asks the disk several names for every photo, also goes up to 16
+ photos at a time.
+
### Relative-date filters and smart albums follow the clock
- A current view or source count using “in the last” rules now refreshes when the session clock moves into a new
minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for