LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-IMP-ADD-DIALOG + LR-IMP-LOCAL: import review dialog with candidates, destination, album, preset, keywords
Brandon Thomas93a1fd3bce6f
diff --git a/Cargo.lock b/Cargo.lockindex 40697205b..151b4c586 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2329,6 +2329,7 @@ version = "0.1.0"dependencies = ["egui","lightcraft-catalog",+ "lightcraft-codecs","lightcraft-color","lightcraft-develop","lightcraft-engine",diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex bbc843c1b..e6790b849 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -11,6 +11,10 @@ fn album_param(p: &Value, key: &str, c: &str) -> Result<AlbumId> {p.get(key).and_then(Value::as_u64).map(AlbumId).ok_or_else(|| bad(c, format!("missing album `{key}`")))}+fn strs(p: &Value, key: &str) -> Vec<String> {+ p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default()+}+fn ids_param(p: &Value) -> Option<Vec<PhotoId>> {p.get("ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(PhotoId).collect())}@@ -428,19 +432,32 @@ pub fn specs() -> Vec<CommandSpec> {ok()}),// ---- import+ 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?}], 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","Add Photos…",["File"],Some("Cmd+Shift+I"),- "{paths: [file or folder (recursive)], mode?: add|copy (copy into the library's Originals/), album?: albumId} → {imported, duplicates, failed}",+ "{paths: [file or folder (recursive)], mode?: add|copy (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..]} → {imported, duplicates, failed, album?}",always,|s, p| {- let paths: Vec<String> = p- .get("paths")- .and_then(Value::as_array)- .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())- .unwrap_or_default();+ let paths = strs(p, "paths");if paths.is_empty() {return Err(bad("library.import", "no paths"));}@@ -449,16 +466,42 @@ pub fn specs() -> Vec<CommandSpec> {"copy" => crate::import::ImportMode::Copy,other => return Err(bad("library.import", format!("unknown mode `{other}` (add|copy)"))),};- let report = crate::import::import(s, &paths, mode)?;- if let Some(a) = p.get("album").and_then(Value::as_u64)- && !report.imported.is_empty()+ 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 mut 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 opts = crate::import::ImportOptions { mode, preset, keywords: strs(p, "keywords") };+ let undo0 = s.undo.len();+ let mut report = serde_json::to_value(crate::import::import_with(s, &paths, &opts)?).unwrap_or_default();+ let imported: Vec<u64> = report["imported"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();+ if album.is_none()+ && let Some(name) = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty())+ && !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(){- s.execute("album.addPhotos", &json!({"id": a, "ids": report.imported}))?;+ s.execute("album.addPhotos", &json!({"id": a, "ids": imported}))?;+ report["album"] = json!(a);}- if let Some(f) = report.imported.first() {+ // one undo step for the whole import+ let n = s.undo.len().saturating_sub(undo0);+ s.merge_undo(n, &format!("Add {} Photo{}", imported.len(), if imported.len() == 1 { "" } else { "s" }));+ if let Some(f) = imported.first() {s.selection = Selection::single(PhotoId(*f));}- Ok(serde_json::to_value(&report).unwrap_or_default())+ Ok(report)}),// ---- persistencediff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rsindex aecb11959..98bf125b6 100644--- a/crates/engine/src/import.rs+++ b/crates/engine/src/import.rs@@ -10,13 +10,18 @@//! `Originals/YYYY/YYYY-MM-DD/` folder (names made unique) and point at the copy.//! 6. Read each photo's XMP sidecar (or a raw/DNG file's embedded XMP): the sidecar wins for//! metadata and develop settings are restored (see [`crate::sidecar`]).-//! 7. Commit all new photos as one undoable op.+//! 7. Optionally apply a preset and add keywords (the import dialog's options).+//! 8. Commit all new photos as one undoable op.+//!+//! The import dialog first calls [`scan`] (`library.importPreview`): the same expansion, probing+//! and duplicate detection without adding anything, so the user can review the candidates. The+//! probes are kept and reused by the import that follows.use std::collections::HashMap;use std::path::{Path, PathBuf};-use lightcraft_catalog::{Op, Photo, PhotoId, Source};-use serde::Serialize;+use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source};+use serde::{Deserialize, Serialize};use crate::Session;use crate::media::ProbeInfo;@@ -36,6 +41,37 @@ pub enum ImportMode {Copy,}+/// What an import does besides adding the photos.+#[derive(Clone, Debug, Default)]+pub struct ImportOptions {+ pub mode: ImportMode,+ /// Applied to every imported photo (one History entry).+ pub preset: Option<lightcraft_develop::Preset>,+ /// Added to every imported photo.+ pub keywords: Vec<String>,+}++/// A file found by [`scan`], for the import review.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct ImportCandidate {+ pub path: String,+ pub name: String,+ pub format: String,+ pub kind: MediaKind,+ pub width: u32,+ pub height: u32,+ pub file_size: u64,+ pub captured: Option<String>,+ /// `"path"` (already in the library), `"content"` (same bytes in the library or earlier in this+ /// list): skipped by the import.+ pub duplicate: Option<String>,+ /// The photo that already has it.+ pub existing: Option<u64>,+ /// Not readable.+ pub error: Option<String>,+}+#[derive(Clone, Debug, Default, Serialize)]pub struct Duplicate {pub path: String,@@ -162,8 +198,86 @@ fn copy_into_library(lib: &Path, src: &str, date: &str) -> Result<String, StringOk(dst.to_string_lossy().to_string())}+/// Find and probe what importing `paths` would add, marking duplicates (by path, or by content+/// against the library and earlier candidates). Nothing is added; the probes are kept for the+/// import that follows.+pub fn scan(s: &mut Session, paths: &[String]) -> Vec<ImportCandidate> {+ let lib_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone());+ let files = expand(paths, lib_dir.as_deref());+ let mut by_path: HashMap<String, PhotoId> = HashMap::new();+ let mut by_hash: HashMap<String, PhotoId> = HashMap::new();+ for p in s.catalog.photos() {+ if let Source::File { path } = &p.source {+ by_path.insert(path.clone(), p.id);+ }+ if let Some(h) = &p.content_hash {+ by_hash.insert(h.clone(), p.id);+ }+ }+ let todo: Vec<String> = files.iter().filter(|f| !by_path.contains_key(f.as_str())).cloned().collect();+ // probes from a preceding `scan` are reused when the file is unchanged (same size)+ let cached: Vec<Option<ProbeInfo>> = todo+ .iter()+ .map(|f| {+ let info = s.import_probes.remove(f)?;+ let size = std::fs::metadata(f).map(|m| m.len()).ok();+ (size.is_none() || size == Some(info.file_size)).then_some(info)+ })+ .collect();+ let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();+ let mut fresh = probe_all(s, &missing).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();+ let mut probes: HashMap<String, Result<ProbeInfo, String>> = todo.into_iter().zip(probed).collect();+ let mut seen_hash: HashMap<String, Option<u64>> = by_hash.into_iter().map(|(h, id)| (h, Some(id.0))).collect();+ let mut out = Vec::with_capacity(files.len());+ for f in files {+ let name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone());+ let mut c = ImportCandidate { path: f.clone(), name, ..Default::default() };+ if let Some(id) = by_path.get(&f) {+ c.duplicate = Some("path".into());+ c.existing = Some(id.0);+ if let Some(p) = s.catalog.photo(*id) {+ (c.format, c.kind, c.width, c.height, c.file_size, c.captured) =+ (p.format.clone(), p.kind, p.width, p.height, p.file_size, p.captured.clone());+ }+ out.push(c);+ continue;+ }+ match probes.remove(&f) {+ Some(Ok(info)) => {+ (c.format, c.kind, c.width, c.height, c.file_size, c.captured) =+ (info.format.clone(), info.kind, info.width, info.height, info.file_size, info.captured.clone());+ if let Some(h) = &info.content_hash {+ match seen_hash.get(h) {+ Some(existing) => {+ c.duplicate = Some("content".into());+ c.existing = *existing;+ }+ None => {+ seen_hash.insert(h.clone(), None);+ }+ }+ }+ s.import_probes.insert(f, info);+ }+ Some(Err(e)) => c.error = Some(e),+ None => c.error = Some("not probed".into()),+ }+ out.push(c);+ }+ out+}+/// 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.+pub fn import_with(s: &mut Session, paths: &[String], opts: &ImportOptions) -> crate::Result<ImportReport> {+ 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 mode = if mode == ImportMode::Copy && s.library.as_ref().is_some_and(|l| !l.on_disk) { ImportMode::Add } else { mode };@@ -252,6 +366,19 @@ pub fn import(s: &mut Session, paths: &[String], mode: ImportMode) -> crate::ResErr(e) => log::warn!("import {path}: XMP: {e}"),}}+ for k in &opts.keywords {+ let k = lightcraft_catalog::keywords::clean(k);+ if !k.is_empty() && !p.meta.keywords.iter().any(|x| x.eq_ignore_ascii_case(&k)) {+ p.meta.keywords.push(k);+ }+ }+ if let Some(preset) = &opts.preset {+ let d = std::sync::Arc::new(preset.apply(&p.develop, 1.0));+ let label = format!("Preset: {}", preset.name);+ p.develop = d.clone();+ p.edited = Some(now.clone());+ p.history.push(lightcraft_catalog::HistoryStep { label, settings: d });+ }report.imported.push(id.0);ops.push(Op::AddPhoto { photo: Box::new(p) });}@@ -281,6 +408,44 @@ pub fn civil(secs: i64) -> String {}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.develop = std::sync::Arc::new(p.import_defaults());+ let edge = edge.clamp(64, crate::media::SourceLevel::Thumb.max_edge());+ let level = crate::media::SourceLevel::Thumb;+ let source = self.media.origin_ref(&p.source, level.max_edge());+ let key = lightcraft_preview::Hasher128::new().str(&c.path).u64(c.file_size).u64(edge as u64).finish().0 as u64;+ let small = crate::media::RenderJob {+ photo: id,+ level,+ source,+ origin: p.source.clone(),+ info: crate::media::source_info(&p),+ settings: p.develop.clone(),+ request: lightcraft_pipeline::RenderRequest::fit(edge, edge),+ key,+ cache: None,+ stages: None,+ view_cache: None,+ };+ let embedded = match (&self.media.preview_loader, c.kind) {+ (Some(l), MediaKind::Raw) => Some((c.path.clone(), l.clone(), edge)),+ _ => None,+ };+ Some(crate::media::QuickJob { photo: id, key, cached: Vec::new(), embedded, 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);diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e368b5968..bd9e38522 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -103,6 +103,8 @@ pub struct Session {pub xmp: sidecar::XmpPrefs,/// Parameters of the last export (`app.export` params, minus targets), persisted in prefs.json.pub last_export: Option<serde_json::Value>,+ /// File probes from the last import review (`library.importPreview`), reused by the import.+ pub import_probes: std::collections::HashMap<String, media::ProbeInfo>,}impl Default for Session {@@ -138,6 +140,7 @@ impl Session {library: None,xmp: sidecar::XmpPrefs::default(),last_export: None,+ import_probes: Default::default(),}}diff --git a/crates/engine/src/tests_libops.rs b/crates/engine/src/tests_libops.rsindex 4578038aa..5f36a2559 100644--- a/crates/engine/src/tests_libops.rs+++ b/crates/engine/src/tests_libops.rs@@ -258,3 +258,60 @@ fn label_names_set_undo_and_replay() {assert_eq!(s.catalog.label_name(lightcraft_catalog::ColorLabel::Green), "Approved");let _ = std::fs::remove_dir_all(&dir);}++/// Import review: `library.importPreview` lists candidates with duplicates marked (nothing is+/// added); `library.import` takes the checked files with preset, keywords and a new album as one+/// undo step, and copies into the dated library folders.+#[test]+fn import_review_preview_and_options() {+ let src = temp_dir("imp-src");+ let lib = temp_dir("imp-lib");+ write_png(&src.join("a.png"), 1);+ write_png(&src.join("sub/b.png"), 2);+ write_png(&src.join("sub/c.png"), 3);+ std::fs::copy(src.join("a.png"), src.join("sub/a-again.png")).unwrap();+ let mut s = Session::new().with_fs();+ s.open_library(&lib, false).unwrap();+ // c.png is already in the library+ s.execute("library.import", &json!({"paths": [src.join("sub/c.png").to_string_lossy()]})).unwrap();+ let n0 = s.catalog.len();+ let undo0 = s.undo.len();+ let pv = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap();+ assert_eq!(pv["scanned"], 4, "{pv}");+ assert_eq!(pv["duplicates"], 2, "{pv}");+ assert_eq!(s.catalog.len(), n0, "a preview adds nothing");+ assert_eq!(s.undo.len(), undo0);+ let cands = pv["candidates"].as_array().unwrap();+ let dup = |name: &str| cands.iter().find(|c| c["name"] == name).unwrap()["duplicate"].clone();+ assert_eq!(dup("c.png"), "path");+ assert_eq!(dup("a-again.png"), "content");+ assert_eq!(dup("a.png"), json!(null));+ assert_eq!(cands[0]["width"], 24);+ // the dialog imports the checked (non-duplicate) files with its options+ let preset = s.presets.iter().find(|p| p.builtin).unwrap().id.clone();+ let checked: Vec<String> = cands.iter().filter(|c| c["duplicate"].is_null()).map(|c| c["path"].as_str().unwrap().to_string()).collect();+ let r = s+ .execute(+ "library.import",+ &json!({"paths": checked, "mode": "copy", "preset": preset, "keywords": ["trip", "family|kids"], "albumName": "Imported Trip"}),+ )+ .unwrap();+ assert_eq!(r["imported"].as_array().unwrap().len(), 2, "{r}");+ let album = lightcraft_catalog::AlbumId(r["album"].as_u64().unwrap());+ assert_eq!(s.catalog.album(album).unwrap().name, "Imported Trip");+ assert_eq!(s.catalog.album_count(album), 2);+ for id in r["imported"].as_array().unwrap() {+ let p = s.catalog.photo(lightcraft_catalog::PhotoId(id.as_u64().unwrap())).unwrap();+ assert_eq!(p.meta.keywords, ["trip", "family|kids"]);+ assert!(p.history.last().unwrap().label.starts_with("Preset: "), "preset applied with a History entry");+ let lightcraft_catalog::Source::File { path } = &p.source else { panic!() };+ assert!(std::path::Path::new(path).starts_with(lib.join("Originals")), "{path}");+ }+ assert_eq!(s.undo.len(), undo0 + 1, "import + album = one undo step");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.catalog.len(), n0);+ assert!(s.catalog.album(album).is_none());+ assert!(s.execute("library.import", &json!({"paths": ["/nope"], "preset": "no-such"})).is_err());+ let _ = std::fs::remove_dir_all(&src);+ let _ = std::fs::remove_dir_all(&lib);+}diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex 499dbfdd1..d52e1725d 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -22,3 +22,6 @@ egui = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }log = { workspace = true }++[dev-dependencies]+lightcraft-codecs = { workspace = true }diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rsindex 1f2ce4a7a..67269ef5d 100644--- a/crates/ui-egui/src/headless.rs+++ b/crates/ui-egui/src/headless.rs@@ -171,7 +171,11 @@ impl Headless {/// Is anything still in progress (renders, queued input)?pub fn busy(&self) -> bool {- self.app.renderer.in_flight() > 0 || self.app.merge.busy() || !self.app.synthetic.is_empty() || !self.events.is_empty()+ self.app.renderer.in_flight() > 0+ || self.app.merge.busy()+ || self.app.import.is_some()+ || !self.app.synthetic.is_empty()+ || !self.events.is_empty()}/// Run frames until nothing is pending (renders finished, input consumed) for a few frames in@@ -600,6 +604,59 @@ mod tests {h.settle(SETTLE);}+ /// File → Add Photos… opens the import review: candidates with thumbnails, the duplicate is+ /// unchecked; unchecking a cell and confirming imports the rest in batches, into a new album+ /// with keywords, as one undo step.+ #[test]+ fn import_review_dialog() {+ let dir = std::env::temp_dir().join(format!("lc-ui-import-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ for i in 0..5u8 {+ let (w, h) = (40usize, 30usize);+ let data: Vec<[u8; 4]> = (0..w * h).map(|k| [(k % w * 6) as u8, i * 40, (k / w * 8) as u8, 255]).collect();+ let img = lightcraft_raster::Rgba8 { width: w, height: h, data };+ let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ std::fs::write(dir.join(format!("img{i}.png")), png).unwrap();+ }+ std::fs::copy(dir.join("img0.png"), dir.join("img0-copy.png")).unwrap();+ let services = crate::Services { png: None, ..Default::default() };+ let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services);+ app.ui.view = crate::state::ViewMode::PhotoGrid;+ let mut h = Headless::new(app, [1300.0, 900.0], 1.0);+ let t = Duration::from_secs(10);+ let n0 = h.app.session.catalog.len();+ let undo0 = h.app.session.undo.len();+ let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), t);+ assert_eq!(r["result"]["candidates"], 6, "{r}");+ assert_eq!(r["result"]["duplicates"], 1, "{r}");+ h.settle(SETTLE);+ assert!(h.app.renderer.textures.keys().filter(|s| matches!(s, crate::render::Slot::Import(_))).count() >= 5, "thumbnails");+ // uncheck the first photo; name a new album and keywords+ let r = h.request("ui.clickWidget", json!({"id": "import:0"}), t);+ assert_eq!(r["ok"], true, "{r}");+ if let Some(crate::state::Dialog::Import { opts }) = &mut h.app.ui.dialog {+ assert_eq!(opts.selected_paths().len(), 4, "duplicate and unchecked photo left out");+ opts.new_album = "Card 1".into();+ opts.keywords = "cardone, 2026".into();+ } else {+ panic!("no import dialog");+ }+ let r = h.request("ui.dialog.confirm", json!({}), t);+ assert_eq!(r["ok"], true, "{r}");+ h.settle(SETTLE);+ assert!(h.app.import.is_none(), "finished");+ assert_eq!(h.app.session.catalog.len(), n0 + 4);+ let album = h.app.session.catalog.albums().find(|a| a.name == "Card 1").expect("album").id;+ assert_eq!(h.app.session.catalog.album_count(album), 4);+ assert!(h.app.session.catalog.photos().filter(|p| p.meta.keywords.contains(&"cardone".to_string())).count() == 4);+ assert_eq!(h.app.session.undo.len(), undo0 + 1, "one undo step");+ h.request("engine.execute", json!({"command": "edit.undo"}), t);+ assert_eq!(h.app.session.catalog.len(), n0);+ h.settle(SETTLE);+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn screenshot_request_is_answered_without_a_window() {let mut h = demo([800.0, 500.0]);diff --git a/crates/ui-egui/src/import.rs b/crates/ui-egui/src/import.rsnew file mode 100644index 000000000..da9f2019f--- /dev/null+++ b/crates/ui-egui/src/import.rs@@ -0,0 +1,353 @@+//! The import review dialog (File → Add Photos…): the files found under the chosen files and+//! folders as a grid of thumbnails with checkboxes (duplicates marked and unchecked), the+//! destination (add in place / copy into the library's dated `Originals/` folders), an album+//! (existing or new), a preset and keywords to apply. Importing runs in small batches, one per+//! frame, with a progress window; the whole import is one undo step.++use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};+use lightcraft_engine::import::ImportCandidate;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use crate::LightcraftApp;+use crate::render::Slot;+use crate::theme::Tokens;+use crate::widgets::register;++/// Files per batch (one batch per frame, so the progress window updates).+const BATCH: usize = 8;++#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct ImportDialog {+ pub candidates: Vec<ImportCandidate>,+ pub checked: Vec<bool>,+ /// Copy into the library (else add in place).+ pub copy: bool,+ /// Existing album to add to.+ pub album: Option<u64>,+ /// …or a new album with this name.+ pub new_album: String,+ /// Preset id ("" = none).+ pub preset: String,+ /// Comma-separated keywords.+ pub keywords: String,+}++impl ImportDialog {+ pub fn new(candidates: Vec<ImportCandidate>) -> Self {+ let checked = candidates.iter().map(|c| c.duplicate.is_none() && c.error.is_none()).collect();+ ImportDialog { candidates, checked, ..Default::default() }+ }+ pub fn importable(&self, i: usize) -> bool {+ self.candidates.get(i).is_some_and(|c| c.duplicate.is_none() && c.error.is_none())+ }+ pub fn selected_paths(&self) -> Vec<String> {+ self.candidates+ .iter()+ .zip(&self.checked)+ .filter(|(c, on)| **on && c.duplicate.is_none() && c.error.is_none())+ .map(|(c, _)| c.path.clone())+ .collect()+ }+ fn keywords(&self) -> Vec<String> {+ self.keywords.split(',').map(str::trim).filter(|k| !k.is_empty()).map(str::to_string).collect()+ }+}++/// A running import (see the module docs).+#[derive(Debug, Default)]+pub struct ImportTask {+ queue: Vec<String>,+ pub total: usize,+ pub done: usize,+ params: Value,+ pub imported: usize,+ pub duplicates: usize,+ pub failed: usize,+ undo0: usize,+ first: Option<u64>,+}++/// Scan `paths` and open the review dialog. Returns the candidate counts.+pub fn open(app: &mut LightcraftApp, paths: Vec<String>) -> Result<Value, String> {+ let r = app.session.execute("library.importPreview", &json!({"paths": paths})).map_err(|e| e.to_string())?;+ let candidates: Vec<ImportCandidate> = serde_json::from_value(r["candidates"].clone()).unwrap_or_default();+ if candidates.is_empty() {+ app.toast(&egui::Context::default(), "No photos found");+ return Ok(json!({"candidates": 0}));+ }+ app.renderer.forget_imports();+ let d = ImportDialog::new(candidates);+ let out = json!({"candidates": d.candidates.len(), "duplicates": r["duplicates"]});+ app.ui.dialog = Some(crate::state::Dialog::Import { opts: Box::new(d) });+ Ok(out)+}++/// Start importing the dialog's checked files (the dialog's OK / `ui.dialog.confirm`).+pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String> {+ let queue = d.selected_paths();+ if queue.is_empty() {+ return Err("no photos selected".into());+ }+ let undo0 = app.session.undo.len();+ let mut album = d.album;+ if album.is_none() && !d.new_album.trim().is_empty() {+ let r = app.session.execute("album.create", &json!({"name": d.new_album.trim()})).map_err(|e| e.to_string())?;+ album = r["id"].as_u64();+ }+ let mut params = json!({"mode": if d.copy { "copy" } else { "add" }, "keywords": d.keywords()});+ if let Some(a) = album {+ params["album"] = json!(a);+ }+ if !d.preset.is_empty() {+ params["preset"] = json!(d.preset);+ }+ let total = queue.len();+ app.import = Some(ImportTask { queue, total, params, undo0, ..Default::default() });+ app.renderer.forget_imports();+ Ok(json!({"importing": total}))+}++/// Run one batch of the import in progress (called every frame).+pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) {+ let Some(task) = app.import.as_mut() else { return };+ let n = task.queue.len().min(BATCH);+ let batch: Vec<String> = task.queue.drain(..n).collect();+ let mut p = task.params.clone();+ p["paths"] = json!(batch);+ let r = app.session.execute("library.import", &p);+ let task = app.import.as_mut().expect("import task");+ task.done += n;+ match r {+ Ok(v) => {+ let len = |k: &str| v[k].as_array().map_or(0, Vec::len);+ task.imported += len("imported");+ task.duplicates += len("duplicates");+ task.failed += len("failed");+ if task.first.is_none() {+ task.first = v["imported"].as_array().and_then(|a| a.first()).and_then(Value::as_u64);+ }+ }+ Err(e) => {+ log::warn!("import: {e}");+ task.failed += n;+ }+ }+ ctx.request_repaint();+ if !task.queue.is_empty() {+ return;+ }+ let task = app.import.take().expect("import task");+ let steps = app.session.undo.len().saturating_sub(task.undo0);+ let label = format!("Add {} Photo{}", task.imported, if task.imported == 1 { "" } else { "s" });+ app.session.merge_undo(steps, &label);+ if let Some(f) = task.first {+ let _ = app.run("library.select", json!({"ids": [f]}));+ }+ let mut msg = format!("Added {} photo{}", task.imported, if task.imported == 1 { "" } else { "s" });+ if task.duplicates > 0 {+ msg.push_str(&format!(" · {} duplicate{} skipped", task.duplicates, if task.duplicates == 1 { "" } else { "s" }));+ }+ if task.failed > 0 {+ msg.push_str(&format!(" · {} not readable", task.failed));+ }+ app.toast(ctx, msg);+}++/// The progress window while an import runs.+pub fn progress(app: &mut LightcraftApp, ctx: &egui::Context) {+ let Some(task) = &app.import else { return };+ let t = Tokens::get(ctx);+ let frac = task.done as f32 / task.total.max(1) as f32;+ let text = format!("Adding photos… {} of {}", task.done, task.total);+ egui::Window::new("Importing").title_bar(false).resizable(false).anchor(Align2::CENTER_BOTTOM, [0.0, -80.0]).fixed_size([340.0, 60.0]).show(+ ctx,+ |ui| {+ ui.label(egui::RichText::new(text).color(t.text));+ ui.add(egui::ProgressBar::new(frac).desired_width(320.0));+ },+ );+}++/// The dialog body: options, then the candidate grid.+pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) {+ let t = Tokens::get(ui.ctx());+ let n = d.candidates.len();+ let dups = d.candidates.iter().filter(|c| c.duplicate.is_some()).count();+ let sel = d.selected_paths().len();+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(format!("{n} found · {sel} selected")).color(t.text));+ if dups > 0 {+ ui.label(egui::RichText::new(format!("· {dups} already in the library")).color(t.text_dim));+ }+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if crate::widgets::text_button(ui, "importNone", "Uncheck All", false).clicked() {+ d.checked.iter_mut().for_each(|c| *c = false);+ }+ if crate::widgets::text_button(ui, "importAll", "Check All", false).clicked() {+ for i in 0..n {+ d.checked[i] = d.importable(i);+ }+ }+ });+ });+ // candidate grid+ let cell = 116.0;+ let avail = ui.available_width();+ let cols = ((avail + 6.0) / (cell + 6.0)).floor().max(1.0) as usize;+ let rows = n.div_ceil(cols);+ egui::ScrollArea::vertical().id_salt("import-grid").max_height(330.0).auto_shrink([false, true]).show_viewport(ui, |ui, viewport| {+ let (area, _) = ui.allocate_exact_size(vec2(avail, rows as f32 * (cell + 26.0)), Sense::hover());+ for i in 0..n {+ let (c, r) = (i % cols, i / cols);+ let local = Rect::from_min_size(pos2(c as f32 * (cell + 6.0), r as f32 * (cell + 26.0)), vec2(cell, cell + 20.0));+ if !local.intersects(viewport.expand(cell)) {+ continue;+ }+ let rect = local.translate(area.min.to_vec2());+ candidate_cell(app, ui, d, i, rect);+ }+ });+ ui.add_space(4.0);+ // options+ field(ui, "Destination", |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if crate::widgets::text_button(ui, "importAdd", "Add in place", !d.copy).on_hover_text("Reference the files where they are").clicked() {+ d.copy = false;+ }+ let can_copy = app.session.library.as_ref().is_some_and(|l| l.on_disk);+ let r = ui.add_enabled_ui(can_copy, |ui| crate::widgets::text_button(ui, "importCopy", "Copy into library", d.copy)).inner;+ if r.on_hover_text("Copy into the library's Originals/YYYY/YYYY-MM-DD/ folders").clicked() {+ d.copy = true;+ }+ });+ let albums: Vec<(u64, String)> = {+ let mut v: Vec<(u64, String)> =+ app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.id.0, a.name.clone())).collect();+ v.sort_by_key(|(_, n)| n.to_lowercase());+ v+ };+ field(ui, "Album", |ui| {+ let cur = match d.album {+ Some(a) => albums.iter().find(|x| x.0 == a).map(|x| x.1.clone()).unwrap_or_default(),+ None if !d.new_album.is_empty() => "New album".into(),+ None => "None".into(),+ };+ egui::ComboBox::from_id_salt("import-album").selected_text(cur).show_ui(ui, |ui| {+ if ui.selectable_label(d.album.is_none() && d.new_album.is_empty(), "None").clicked() {+ d.album = None;+ d.new_album.clear();+ }+ if ui.selectable_label(d.album.is_none() && !d.new_album.is_empty(), "New album…").clicked() {+ d.album = None;+ if d.new_album.is_empty() {+ d.new_album = "Imported Photos".into();+ }+ }+ for (id, name) in &albums {+ if ui.selectable_label(d.album == Some(*id), name).clicked() {+ d.album = Some(*id);+ d.new_album.clear();+ }+ }+ });+ if d.album.is_none() && !d.new_album.is_empty() {+ let r = ui.add(egui::TextEdit::singleline(&mut d.new_album).desired_width(f32::INFINITY));+ register(ui.ctx(), "field:importAlbumName", r.rect);+ }+ });+ field(ui, "Preset", |ui| {+ let cur = app.session.presets.iter().find(|p| p.id == d.preset).map(|p| p.name.clone()).unwrap_or_else(|| "None".into());+ egui::ComboBox::from_id_salt("import-preset").selected_text(cur).height(300.0).show_ui(ui, |ui| {+ if ui.selectable_label(d.preset.is_empty(), "None").clicked() {+ d.preset.clear();+ }+ for p in &app.session.presets {+ if ui.selectable_label(d.preset == p.id, format!("{} — {}", p.group, p.name)).clicked() {+ d.preset = p.id.clone();+ }+ }+ });+ });+ field(ui, "Keywords", |ui| {+ let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text("comma, separated").desired_width(f32::INFINITY));+ register(ui.ctx(), "field:importKeywords", r.rect);+ });+}++fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog, i: usize, rect: Rect) {+ let t = Tokens::get(ui.ctx());+ let c = d.candidates[i].clone();+ let ok = d.importable(i);+ let img = Rect::from_min_size(rect.min, vec2(rect.width(), rect.width()));+ let resp = ui.interact(img, egui::Id::new(("import-cell", i)), Sense::click());+ register(ui.ctx(), format!("import:{i}"), img);+ let p = ui.painter();+ p.rect_filled(img, 3.0, Color32::from_gray(30));+ // thumbnail (background job; the grid only asks for the cells in view)+ let slot = Slot::Import(i as u32);+ if !app.renderer.textures.contains_key(&slot)+ && let Some(job) = app.session.candidate_thumb_job(&c, 192, i as u64)+ {+ app.renderer.request_quick(slot, job, 4);+ }+ if let Some(tex) = app.renderer.textures.get(&slot) {+ let [tw, th] = tex.size;+ let s = ((img.width() - 8.0) / tw as f32).min((img.height() - 8.0) / th as f32);+ let fit = Rect::from_center_size(img.center(), vec2(tw as f32 * s, th as f32 * s));+ let tint = if ok { Color32::WHITE } else { Color32::from_gray(110) };+ p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint);+ }+ let on = d.checked[i] && ok;+ if on {+ p.rect_stroke(img, 3.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);+ }+ // checkbox+ let cb = Rect::from_min_size(img.min + vec2(6.0, 6.0), vec2(16.0, 16.0));+ p.rect(cb, 3.0, if on { t.accent } else { Color32::from_black_alpha(150) }, Stroke::new(1.0, Color32::from_gray(200)), StrokeKind::Inside);+ if on {+ p.line_segment([cb.left_center() + vec2(3.5, 0.5), cb.center_bottom() + vec2(-1.0, -4.0)], Stroke::new(2.0, Color32::WHITE));+ p.line_segment([cb.center_bottom() + vec2(-1.0, -4.0), cb.right_top() + vec2(-3.5, 4.0)], Stroke::new(2.0, Color32::WHITE));+ }+ let badge = match (&c.duplicate, &c.error) {+ (Some(r), _) if r == "path" => Some("In library"),+ (Some(_), _) => Some("Duplicate"),+ (None, Some(_)) => Some("Unreadable"),+ _ => None,+ };+ if let Some(b) = badge {+ let g = p.layout_no_wrap(b.to_string(), t.semibold(10.0), Color32::WHITE);+ let br = Rect::from_min_size(pos2(img.right() - g.size().x - 12.0, img.top() + 6.0), g.size() + vec2(8.0, 4.0));+ p.rect_filled(br, 3.0, Color32::from_rgba_unmultiplied(170, 60, 50, 220));+ p.galley(br.min + vec2(4.0, 2.0), g, Color32::WHITE);+ }+ let name = if c.name.chars().count() > 18 { format!("{}…", c.name.chars().take(17).collect::<String>()) } else { c.name.clone() };+ p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.font(10.5), if ok { t.text_label } else { t.text_dim });+ let tip = format!(+ "{}\n{} × {} · {} · {:.1} MB{}",+ c.path,+ c.width,+ c.height,+ c.format,+ c.file_size as f64 / 1e6,+ c.captured.as_deref().map(|d| format!("\n{}", d.replace('T', " "))).unwrap_or_default()+ );+ let resp = resp.on_hover_text(tip);+ if resp.clicked() && ok {+ d.checked[i] = !d.checked[i];+ }+}++/// A labelled row (fixed label column).+fn field<R>(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R {+ let t = Tokens::get(ui.ctx());+ ui.horizontal(|ui| {+ ui.allocate_ui_with_layout(vec2(78.0, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {+ ui.set_min_width(78.0);+ ui.label(egui::RichText::new(label).color(t.text_label));+ });+ add(ui)+ })+ .inner+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c0ba22ecc..25ea8e5ac 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -8,6 +8,7 @@pub mod control;pub mod headless;pub mod icons;+pub mod import;pub mod menubar;pub mod menus;pub mod merge;@@ -94,6 +95,8 @@ pub struct LightcraftApp {pub loupe_shown: Option<(lightcraft_catalog::PhotoId, &'static str)>,/// Photo Merge dialog previews and background merges.pub merge: merge::MergeState,+ /// An import in progress (the import review dialog's batches).+ pub import: Option<import::ImportTask>,/// The look the loupe shows while the pointer rests on a preset or profile (set by the/// panels each frame; nothing is committed, no history entry).pub hover_preview: Option<HoverPreview>,@@ -127,6 +130,7 @@ impl LightcraftApp {gesture: None,loupe_shown: None,merge: merge::MergeState::default(),+ import: None,hover_preview: None,}}@@ -305,6 +309,7 @@ impl LightcraftApp {}self.renderer.poll(ctx, &mut self.session);merge::poll(self, ctx);+ import::tick(self, ctx);self.session.persist_if_dirty();self.collect_screenshots(ctx);self.issue_screenshots(ctx);@@ -370,6 +375,7 @@ impl LightcraftApp {state::ViewMode::Survey => panels::compare::show_survey(self, ui),});panels::dialogs::show(self, &ctx);+ import::progress(self, &ctx);panels::toast(self, &ctx);self.widgets = widgets::take_registry(&ctx);self.perf.frame_ms = now_ms() - t0;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 919b7f59e..0aa012adb 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -400,7 +400,8 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Reif paths.is_empty() {return Some(Ok(Value::Null));}- return Some(app.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string()));+ // review first: the import dialog lists what was found+ crate::import::open(app, paths)}"file.importPresets" => {let paths = match p.get("paths").and_then(Value::as_array) {diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rsindex 99d41aa07..d36f85274 100644--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@ -23,6 +23,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {Dialog::NewAlbum { .. } => "Create Album",Dialog::RenameAlbum { .. } => "Rename Album",Dialog::Rename { .. } => "Rename Photos",+ Dialog::Import { .. } => "Add Photos",Dialog::LabelNames { .. } => "Edit Color Label Names",Dialog::CaptureTime { .. } => "Edit Capture Time",Dialog::RenameKeyword { .. } => "Rename Keyword",@@ -42,7 +43,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {.resizable(false).frame(frame).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])- .default_width(380.0)+ .default_width(if matches!(dlg, Dialog::Import { .. }) { 760.0 } else { 380.0 }).show(ctx, |ui| {ui.spacing_mut().item_spacing.y = 8.0;match &mut dlg {@@ -322,6 +323,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {field(ui, "Folder", |ui| ui.add(egui::TextEdit::singleline(dir).desired_width(f32::INFINITY)));}Dialog::Merge { opts } => crate::merge::body(app, ui, opts),+ Dialog::Import { opts } => crate::import::body(app, ui, opts),Dialog::About => {ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text));ui.label(format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION")));@@ -368,7 +370,13 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) {if !informational && ui.button("Cancel").clicked() {close = true;}- let ok = match dlg {+ let add_label;+ let ok = match &dlg {+ Dialog::Import { opts } => {+ let n = opts.selected_paths().len();+ add_label = format!("Add {n} Photo{}", if n == 1 { "" } else { "s" });+ add_label.as_str()+ }Dialog::Merge { .. } => "Merge",_ if informational => "Close",_ => "OK",@@ -451,6 +459,7 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_jso}),),Dialog::Merge { opts } => crate::merge::start_final(app, opts),+ Dialog::Import { opts } => crate::import::start(app, opts),Dialog::About | Dialog::Shortcuts => Ok(serde_json::Value::Null),}}diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rsindex 5aceea139..db8f95e8a 100644--- a/crates/ui-egui/src/render.rs+++ b/crates/ui-egui/src/render.rs@@ -43,6 +43,8 @@ pub enum Slot {/// The loupe while hovering a preset or profile: the photo with the hovered look (nothing is/// committed).Hover,+ /// An import candidate's thumbnail in the import review dialog (by index).+ Import(u32),}pub struct Tex {@@ -435,6 +437,12 @@ impl Renderer {self.textures.values().filter_map(|t| Some((t.tex.id(), crate::softpaint::CpuTexture::linear(t.pixels.clone()?)))).collect()}+ /// Drop the import review thumbnails (a new review, or the dialog closed).+ pub fn forget_imports(&mut self) {+ self.textures.retain(|s, _| !matches!(s, Slot::Import(_)));+ self.quick_tried.retain(|s, _| !matches!(s, Slot::Import(_)));+ }+/// Drop thumbnails that aren't in `keep` (bounded memory for huge libraries), and queued/// thumbnail jobs for photos that scrolled out of `keep`.pub fn evict_thumbs(&mut self, keep: &std::collections::HashSet<PhotoId>, max: usize) {diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 9a973e1bb..f8b0241eb 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -178,6 +178,10 @@ pub enum Dialog {minutes: i32,zone: f32,},+ /// The import review (File → Add Photos…).+ Import {+ opts: Box<crate::import::ImportDialog>,+ },/// Edit the colour label names (red, yellow, green, blue, purple; empty = the colour's name).LabelNames {names: Vec<String>,diff --git a/docs/parity.md b/docs/parity.mdindex 60706f7df..5556570d8 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -65,8 +65,6 @@ Ordered by tier, then user value, then (low) effort. Take the first one nobody ifeather/opacity sliders, `[`/`]` size keys. Medium effort.7. **LR-PREF-GENERAL + LR-IMP-RAWDEFAULT** (P0/P1) — a Settings dialog: raw defaults (preset or camera-specific),XMP prefs, cache, GPU. Medium effort.-8. **LR-IMP-ADD-DIALOG + LR-IMP-LOCAL** (P0) — an import review grid with per-photo checkboxes and destination- album; browse folders before adding. Medium effort.9. **LR-EXP-TYPE + LR-EXP-DIM** (P0) — Original (+XMP) and DNG export (writer exists in`crates/raw/src/dngwrite.rs`), short edge / width / height / megapixels, "don't enlarge", ppi.10. **LR-IMP-FORMATS** (P0) — CR3, compressed NEF/RAF/ORF, RW2 v4 (preview only today); HEIC/AVIF decode (no@@ -114,16 +112,16 @@ under the UI command that wraps it (a no-op error); the UI command now wins.| Id | Feature | Tier | Status | Evidence | Missing / notes ||---|---|---|---|---|---|-| LR-IMP-ADD-DIALOG | Add photos/folders | P0 | 🟡 | `cmd:file.addPhotos`, `cmd:library.import` (`mode`, `album`) | file picker + import report; no review grid with per-photo checkboxes / destination album UI |+| 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: candidate grid with thumbnails and checkboxes (duplicates by path/content marked and unchecked), destination, album (existing/new), preset, keywords; batched import with a progress window; one undo step. Drag-and-drop still imports directly || 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 | ⬜ | | no device detection || LR-IMP-AUTO | Watched-folder auto import | P2 | ⬜ | | |-| LR-IMP-PRESET | Preset on import | P2 | ⬜ | | |+| 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 | ⬜ | `crates/engine/src/import.rs` | raws get embedded lens corrections on import; no user raw-default setting || LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | || LR-IMP-PROFILES | Import profiles & presets | P1 | 🟡 | `cmd:file.importPresets`, `cmd:preset.import` | presets (.lcpreset, XMP `crs:`) only; no profile import; Adobe profile formats are deliberately unsupported |-| LR-IMP-LOCAL | Work on files in place | P0 | 🟡 | `cmd:library.import` (mode add), `crates/engine/src/sidecar.rs`, `cmd:library.toggleAutoWriteXmp` | files referenced in place with XMP sidecars; no browse-a-folder-without-adding view |+| LR-IMP-LOCAL | Work on files in place | P0 | 🟡 | `cmd:library.import` (mode add), `cmd:library.importPreview`, `crates/engine/src/sidecar.rs`, `cmd:library.toggleAutoWriteXmp` | files referenced in place with XMP sidecars; the import review shows a folder's photos before adding (“Add in place” or “Copy into library”); no browse-a-folder-without-adding view in the main grid || LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars || LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs` | JPEG, PNG, TIFF, WebP, JXL, PSD, GIF, BMP; DNG, CR2, ARW, NEF, RAF, RW2, PEF, ORF. Missing: CR3, compressed NEF/RAF/ORF, RW2 v4 (preview only), HEIC/AVIF decode || LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | ⬜ | | |