Skip to content

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

LR-IMP-AUTO: watched-folder auto import

Brandon Thomas608fb6dc1335
diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs
index c301b850f..3e47d5868 100644
--- a/crates/engine/src/cmd/library.rs
+++ b/crates/engine/src/cmd/library.rs
@@ -596,6 +596,88 @@ pub fn specs() -> Vec<CommandSpec> {
)?;
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,
+ "{} — 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}",
+ always,
+ |s, _| {
+ 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();
+ let mut fresh = Vec::new();
+ for e in std::fs::read_dir(&folder).map_err(|e| bad("library.autoImportScan", format!("{folder}: {e}")))?.flatten() {
+ let path = e.path();
+ let ps = path.to_string_lossy().to_string();
+ if !path.is_file() || known.contains(&ps) || path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')) {
+ 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 size = e.metadata().map(|m| m.len()).unwrap_or(0);
+ 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" };
+ let mut params = json!({"paths": fresh, "mode": mode});
+ 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);
+ }
+ let sel = s.selection.clone();
+ let r = s.execute("library.import", &params)?;
+ // arriving photos don't take over the selection
+ s.selection = sel;
+ Ok(json!({"imported": r["imported"], "folder": folder}))
+ }
+ ),
cmd!("album.removePhotos", "Remove from Album", [], None, "{id: albumId, ids?}", has_selection, |s, p| {
let id = album_param(p, "id", "album.removePhotos")?;
let targets = ids_param(p).unwrap_or_else(|| s.targets(&Value::Null));
@@ -697,6 +779,8 @@ pub fn specs() -> Vec<CommandSpec> {
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);
}
diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs
index a41422e08..37b5bac4d 100644
--- a/crates/engine/src/import.rs
+++ b/crates/engine/src/import.rs
@@ -164,6 +164,12 @@ pub struct ImportDefaults {
pub creator: String,
/// Metadata preset applied to every imported photo (`metadata.*`; `None` = none).
pub metadata_preset: Option<String>,
+ /// Auto import: a watched folder whose new photos are added as they arrive (`None` = off),
+ /// copied into the library's Originals instead of added in place when `auto_copy`, and an
+ /// album they go to.
+ pub auto_folder: Option<String>,
+ pub auto_copy: bool,
+ pub auto_album: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e392b0804..3093148f6 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -127,6 +127,9 @@ pub struct Session {
pub label_sets: Vec<cmd::manage::LabelSet>,
/// The target album B adds to (`None` = the Quick Collection).
pub target_album: Option<lightcraft_catalog::AlbumId>,
+ /// Auto import: files seen in the watched folder and their size then (a file is imported once
+ /// its size held between two scans).
+ pub auto_import_seen: std::collections::HashMap<String, u64>,
/// Keyword sets (⌥1–⌥9 apply the current set's keywords), the one in use (`None` = Recent
/// Keywords) and the recently added keywords, newest first.
pub keyword_sets: Vec<cmd::keywords::KeywordSet>,
@@ -188,6 +191,7 @@ impl Session {
filter_presets: Vec::new(),
label_sets: Vec::new(),
target_album: None,
+ auto_import_seen: Default::default(),
keyword_sets: Vec::new(),
keyword_set: None,
recent_keywords: Vec::new(),
diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs
index b318106c2..c4a03c2bb 100644
--- a/crates/engine/src/tests_import.rs
+++ b/crates/engine/src/tests_import.rs
@@ -256,3 +256,34 @@ fn copy_with_destination_organize_rename_and_metadata_preset() {
let _ = std::fs::remove_dir_all(d);
}
}
+
+/// Auto import: files in the watched folder are added once their size held between two scans,
+/// into the named album; non-photos are tried once; the selection stays put.
+#[test]
+fn auto_import_watched_folder() {
+ let dir = temp_dir("watch");
+ let mut s = Session::new().with_fs();
+ assert!(s.execute("library.autoImport", &json!({"folder": dir.join("nope").to_string_lossy()})).is_err());
+ s.execute("library.autoImport", &json!({"folder": dir.to_string_lossy(), "album": "Tethered"})).unwrap();
+ assert_eq!(s.execute("library.autoImportScan", &json!({})).unwrap()["imported"], json!([]));
+ write_png(&dir.join("one.png"), 1);
+ std::fs::write(dir.join("notes.txt"), "not a photo").unwrap();
+ // first sight: wait (it may still be copying)
+ assert_eq!(s.execute("library.autoImportScan", &json!({})).unwrap()["imported"], json!([]));
+ let r = s.execute("library.autoImportScan", &json!({})).unwrap();
+ assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}");
+ let album = s.catalog.albums().find(|a| a.name == "Tethered").expect("album").id;
+ assert_eq!(s.catalog.album_count(album), 1);
+ assert!(s.selection.ids.is_empty(), "arrivals don't take the selection");
+ // nothing new: nothing happens, and the text file isn't retried
+ for _ in 0..2 {
+ assert_eq!(s.execute("library.autoImportScan", &json!({})).unwrap()["imported"], json!([]));
+ }
+ write_png(&dir.join("two.png"), 2);
+ s.execute("library.autoImportScan", &json!({})).unwrap();
+ s.execute("library.autoImportScan", &json!({})).unwrap();
+ assert_eq!(s.catalog.album_count(album), 2);
+ s.execute("library.autoImport", &json!({"folder": null})).unwrap();
+ assert_eq!(s.execute("library.autoImportScan", &json!({})).unwrap()["folder"], json!(null));
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index ecafde7a8..adc98bdf9 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -414,6 +414,21 @@ impl LightcraftApp {
}
}
self.ui.was_focused = focused;
+ // auto import: scan the watched folder every few seconds
+ #[cfg(not(target_arch = "wasm32"))]
+ if self.session.import_defaults.auto_folder.is_some() {
+ let now = ctx.input(|i| i.time);
+ if now - self.ui.auto_import_at >= 3.0 {
+ self.ui.auto_import_at = now;
+ if let Ok(r) = self.session.execute("library.autoImportScan", &serde_json::json!({})) {
+ let n = r["imported"].as_array().map_or(0, Vec::len);
+ if n > 0 {
+ self.toast(ctx, format!("Auto Import: added {n} photo{}", if n == 1 { "" } else { "s" }));
+ }
+ }
+ }
+ ctx.request_repaint_after(std::time::Duration::from_secs(3));
+ }
self.session.persist_if_dirty();
self.collect_screenshots(ctx);
self.issue_screenshots(ctx);
diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs
index 5990c522c..c6961e54f 100644
--- a/crates/ui-egui/src/panels/settings.rs
+++ b/crates/ui-egui/src/panels/settings.rs
@@ -294,6 +294,42 @@ fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
let _ = app.run("library.xmpPreferences", json!({"naming": naming}));
}
});
+ if !cfg!(target_arch = "wasm32") {
+ heading(ui, t, "Auto Import");
+ hint(ui, t, "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.");
+ row(ui, t, "Watched folder", |ui| {
+ ui.label(RichText::new(d.auto_folder.clone().unwrap_or_else(|| "Off".into())).color(t.text));
+ let can = app.services.pick_folder.is_some();
+ let r = ui.add_enabled(can, egui::Button::new("Choose…"));
+ register(ui.ctx(), "button:settingsAutoFolder", r.rect);
+ if r.clicked()
+ && let Some(f) = app.services.pick_folder.as_mut().and_then(|f| f())
+ && let Err(e) = app.run("library.autoImport", json!({"folder": f}))
+ {
+ app.toast(ui.ctx(), e);
+ }
+ if d.auto_folder.is_some() && ui.button("Turn Off").clicked() {
+ let _ = app.run("library.autoImport", json!({"folder": null}));
+ }
+ });
+ if d.auto_folder.is_some() {
+ row(ui, t, "", |ui| {
+ let mut copy = d.auto_copy;
+ if ui.checkbox(&mut copy, "Copy into the library (else use the files where they are)").changed() {
+ let _ = app.run("library.autoImport", json!({"copy": copy}));
+ }
+ });
+ row(ui, t, "Album", |ui| {
+ let id = egui::Id::new("auto-album");
+ let mut name = ui.data(|m| m.get_temp::<String>(id)).unwrap_or_else(|| d.auto_album.clone().unwrap_or_default());
+ let r = ui.add(egui::TextEdit::singleline(&mut name).hint_text("None").desired_width(180.0));
+ if r.lost_focus() {
+ let _ = app.run("library.autoImport", json!({"album": name.trim()}));
+ }
+ ui.data_mut(|m| m.insert_temp(id, name));
+ });
+ }
+ }
if app.session.library.is_none() {
hint(ui, t, "In-memory session: these settings last until LightCraft quits.");
}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 397eca711..a6031716d 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -219,6 +219,9 @@ pub struct UiState {
pub external_edits: Vec<u64>,
#[serde(skip)]
pub was_focused: bool,
+ /// When the watched folder was last scanned (egui time).
+ #[serde(skip)]
+ pub auto_import_at: f64,
/// The develop control whose slider is being dragged (geometry sliders show a grid).
#[serde(skip)]
pub dragging_control: Option<String>,
@@ -460,6 +463,7 @@ impl Default for UiState {
dragging_control: None,
external_edits: Vec::new(),
was_focused: true,
+ auto_import_at: 0.0,
search: String::new(),
focus_search: false,
renaming_mask: None,
diff --git a/docs/parity.md b/docs/parity.md
index 994b6687d..2c4889ebd 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -21,7 +21,7 @@ and prints the summary; `cargo xtask parity --write` refreshes the summary table
<!-- parity:summary -->
| Section | ✅ | 🟡 | ⬜ | 🚫 | P0 done | P1 done |
|---|---:|---:|---:|---:|---:|---:|
-| A. Import (IMP) | 8 | 2 | 3 | 1 | 3/4 (75%) | 3/4 (75%) |
+| A. Import (IMP) | 9 | 2 | 2 | 1 | 3/4 (75%) | 3/4 (75%) |
| B. Library management (LIB) | 21 | 0 | 4 | 2 | 9/9 (100%) | 9/9 (100%) |
| C. Views & navigation (VIEW) | 15 | 0 | 2 | 0 | 9/9 (100%) | 4/4 (100%) |
| D. Search & filter (FILT) | 10 | 0 | 3 | 0 | 4/4 (100%) | 4/4 (100%) |
@@ -47,10 +47,10 @@ and prints the summary; `cargo xtask parity --write` refreshes the summary table
| X. Cross-cutting behaviours (BEHAV) | 13 | 0 | 4 | 1 | 8/8 (100%) | 5/5 (100%) |
| Y. Menus | 77 | 2 | 6 | 8 | 46/47 (98%) | 22/23 (96%) |
| Z. Keyboard shortcuts (desktop) | 74 | 3 | 3 | 1 | 49/52 (94%) | 22/23 (96%) |
-| Lightroom Classic extras | 21 | 10 | 48 | 9 | — | 18/21 (86%) |
-| **Total** | 362 | 25 | 113 | 37 | 193/198 (97%) | 132/144 (92%) |
+| Lightroom Classic extras | 22 | 10 | 47 | 9 | — | 18/21 (86%) |
+| **Total** | 364 | 25 | 111 | 37 | 193/198 (97%) | 132/144 (92%) |
-Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **74.9%** of 500 in-scope rows — P0 98.7% of 198 · P1 94.4% of 144 · P2 27.2% of 158.
+Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **75.3%** of 500 in-scope rows — P0 98.7% of 198 · P1 94.4% of 144 · P2 28.5% of 158.
<!-- /parity:summary -->
## Top gaps
@@ -102,7 +102,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins.
| LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → `cmd:library.import`) | 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 → Add from Device → the import review, copying into the library by default; no PTP/MTP (cameras that don't mount as a disk) |
-| LR-IMP-AUTO | Watched-folder auto import | P2 | ⬜ | | |
+| 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-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-MIGRATE | Migrate other catalogs | OOS | 🚫 | | |
@@ -686,7 +686,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| Id | Feature | Tier | Status | Evidence | Missing / notes |
|---|---|---|---|---|---|
| LRC-LIB-IMPORT | Full import dialog | P1 | ✅ | `cmd:library.import` (`mode`, `destination`, `organize`, `rename`, `metadataPreset`, `preset`, `keywords`, `album`), `crates/ui-egui/src/import.rs` | review grid with duplicates skipped; add in place or copy (library Originals or any folder; by day / by month / one folder; rename template with live example, numbered across the import); develop preset, metadata preset, keywords, album on import |
-| LRC-LIB-AUTOIMPORT | Watched-folder import | P2 | ⬜ | | |
+| LRC-LIB-AUTOIMPORT | Watched-folder import | P2 | ✅ | `cmd:library.autoImport` | see LR-IMP-AUTO |
| LRC-LIB-TETHER | Tethered capture | P2 | ⬜ | | |
| LRC-LIB-VIEWS | Grid / loupe / compare / survey / people | P1 | 🟡 | `cmd:view.photoGrid`, `cmd:view.squareGrid`, `cmd:view.detail`, `cmd:view.compare`, `cmd:view.survey` | grid, square grid, loupe, compare, survey; no people view; grid cell styles: filenames only |
| LRC-LIB-COMPARE | Compare view | P1 | ✅ | `cmd:view.compare` | ⇧C (C is Crop here); swap, make select; zoom always linked |