diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0c93a56a65..d9e3466611 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -271,6 +271,66 @@ pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool { pub(crate) fn ok() -> Result { Ok(Value::Null) } + +/// A batch-edit recipe from a command's params: `[{id, value}, …]`, each `id` a develop control a +/// recipe may name ([`check_recipe`]). Empty when absent or null. A malformed item, a control a +/// recipe may not name, or more entries than there are controls is an error, so a typo is refused +/// rather than silently ignored. An id named twice counts once, the last value winning; the list +/// comes back in id order. +pub(crate) fn recipe_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("recipe").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let Some(items) = v.as_array() else { + return Err(bad(cmd, "`recipe` must be a list of {id, value}")); + }; + let most = lightcraft_develop::controls::CONTROLS.len(); + if items.len() > most { + return Err(bad(cmd, format!("a recipe has one entry per control, at most {most} (it has {})", items.len()))); + } + let mut by_id = std::collections::BTreeMap::new(); + for it in items { + let id = it.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "each recipe item needs an `id`"))?; + let value = it.get("value").and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("recipe `{id}` needs a numeric `value`")))?; + by_id.insert(id.to_string(), value); + } + let recipe: Vec<(String, f64)> = by_id.into_iter().collect(); + check_recipe(&recipe).map_err(|e| bad(cmd, e))?; + Ok(recipe) +} + +/// Whether every control of `recipe` is one a batch-edit recipe may name, else why not. The rule is +/// on the control's spec: a plain control of the shared list, writable on any photo's settings +/// (`set` takes it), outside the Geometry section and not white balance. +/// +/// - Per-photo instances (`pointColor.0.hueShift`, `redEye.0.pupilSize`) are not in the list; on a +/// photo without that instance a write is dropped. +/// - Geometry controls (`crop.angle`, `geometry.*`) need the photo's own size: the slider refits the +/// crop around a new angle, which a batch write cannot do. +/// - White balance means something else on each kind of file (Kelvin on a raw with matrices, +/// relative to the as-shot white on a rendered photo or a raw without them), so one temperature +/// cannot name the same look for every photo of a batch. +pub(crate) fn check_recipe(recipe: &[(String, f64)]) -> std::result::Result<(), String> { + use lightcraft_develop::{Section, controls}; + let mut scratch = lightcraft_develop::DevelopSettings::default(); + for (id, value) in recipe { + let Some(spec) = controls::CONTROLS.iter().find(|c| c.id == id.as_str()) else { + return Err(format!( + "unknown recipe control `{id}` (see develop.controls; a control that belongs to one photo, such as pointColor.0.hueShift, is not one)" + )); + }; + if spec.section == Section::Geometry { + return Err(format!("`{id}` is a geometry control: a recipe does not crop, straighten or transform photos")); + } + if id.starts_with("wb.") { + return Err(format!( + "`{id}` is white balance: a recipe does not set it, because a temperature means something else on a raw than on a rendered photo" + )); + } + if !controls::set(&mut scratch, id, *value) { + return Err(format!("recipe control `{id}` cannot be set")); + } + } + Ok(()) +} pub(crate) fn point(p: &Value, key: &str) -> Option { let a = p.get(key)?.as_array()?; Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?)) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 5399aee9b8..5403ad6eb2 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -33,6 +33,58 @@ fn groups_param(p: &Value, c: &str) -> Result>> { } } +/// The leaves of `a` that differ from `b` (same shape), as a partial JSON object: `None` when they +/// are equal. Used to store only what a batch-edit recipe names, so applying the saved preset +/// later never overrides the settings the recipe doesn't name. +fn partial_diff(a: &Value, b: &Value) -> Option { + match (a, b) { + (Value::Object(x), Value::Object(y)) => { + let mut out = serde_json::Map::new(); + for (k, v) in x { + if let Some(d) = partial_diff(v, y.get(k).unwrap_or(&Value::Null)) { + out.insert(k.clone(), d); + } + } + (!out.is_empty()).then_some(Value::Object(out)) + } + (x, y) => (x != y).then(|| x.clone()), + } +} + +/// The settings as JSON with the HDR subtree always present: [`Hdr`] is left out while it is the default +/// (its JSON stays as it was), so a reset to a default HDR value would have nothing to compare with and +/// would be dropped from a saved preset. +fn full_json(s: &DevelopSettings) -> Value { + let mut v = s.to_json(); + if let Some(obj) = v.as_object_mut() { + obj.entry("hdr").or_insert_with(|| serde_json::to_value(s.hdr).unwrap_or(Value::Null)); + } + v +} + +/// The partial settings a batch-edit recipe names, with the values the import would give (clamped +/// by the control specs). Each named control is compared with the same control at a value it is not +/// set to, so a control the recipe sets to its default (a reset) is stored too, and nothing else is. +/// `None` when the recipe names nothing that is stored, or a control that cannot be written. +fn recipe_partial(recipe: &[(String, f64)]) -> Option { + let (mut named, mut other) = (DevelopSettings::default(), DevelopSettings::default()); + for (id, v) in recipe { + if !controls::set(&mut named, id, *v) { + return None; + } + } + for (id, _) in recipe { + let (spec, now) = (controls::find(id)?, controls::get(&named, id)?); + if !controls::set(&mut other, id, if now > spec.min { spec.min } else { spec.max }) { + return None; + } + } + partial_diff(&full_json(&named), &full_json(&other)) +} + +/// The longest name or group a saved recipe preset may have (characters). +const MAX_PRESET_TEXT: usize = 100; + fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { let p = s.catalog.photo(id); let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0)); @@ -1162,6 +1214,41 @@ pub fn specs() -> Vec { s.presets.push(Preset::from_settings(&pid, name, group, &d, &groups)); Ok(json!({"id": pid})) }), + cmd!( + "preset.saveRecipe", + "Save Import Recipe as Preset", + [], + None, + "{name (up to 100 characters), group?: default Import Recipes, recipe: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}]} → {id, name} — save a batch-edit recipe (as library.import takes it) as a user preset, so it can be reused from the Preset list; only the settings the recipe names are stored, so applying it later never overrides the rest. The preset gets an id no other preset has; saving the same recipe under the same name and group again returns the preset that already is", + always, + |s, p| { + const C: &str = "preset.saveRecipe"; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing name"))?.to_string(); + let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).unwrap_or("Import Recipes").to_string(); + if name.chars().count() > MAX_PRESET_TEXT || group.chars().count() > MAX_PRESET_TEXT { + return Err(bad(C, format!("a name or group is at most {MAX_PRESET_TEXT} characters"))); + } + let recipe = super::recipe_param(p, C)?; + if recipe.is_empty() { + return Err(bad(C, "the recipe is empty")); + } + let settings = recipe_partial(&recipe).ok_or_else(|| bad(C, "the recipe sets nothing a preset can store"))?; + // presets get their ids as imported ones do (`user.-`, then -2, -3…): an id from the list's + // length repeats once a preset is deleted, and the first preset with an id is the one that gets applied + let preset = Preset { id: String::new(), name, group, settings, favorite: false, builtin: false }; + let id = match s.add_presets(vec![preset.clone()]).into_iter().next() { + Some(id) => id, + // the same recipe under the same name and group is already a preset + None => s + .presets + .iter() + .find(|q| !q.builtin && q.name == preset.name && q.group == preset.group && q.settings == preset.settings) + .map(|q| q.id.clone()) + .ok_or_else(|| bad(C, "the preset could not be saved"))?, + }; + Ok(json!({"id": id, "name": preset.name})) + } + ), cmd!("preset.delete", "Delete Preset", [], None, "{id}", always, |s, p| { let pid = str_param(p, "id").ok_or_else(|| bad("preset.delete", "missing id"))?; let i = s.presets.iter().position(|x| x.id == pid).ok_or_else(|| bad("preset.delete", "unknown preset"))?; @@ -1336,3 +1423,46 @@ fn has_history_after(s: &Session) -> std::result::Result<(), String> { Err("at the latest History step".into()) } } + +#[cfg(test)] +mod recipe_tests { + use super::*; + + /// Equal settings differ nowhere, so there is nothing to store; a difference comes back with + /// its path only. + #[test] + fn partial_diff_is_the_changed_leaves_only() { + let a = json!({"light": {"exposure": 1.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &a), None); + let b = json!({"light": {"exposure": 0.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &b), Some(json!({"light": {"exposure": 1.0}}))); + assert_eq!(partial_diff(&a, &json!({})), Some(a.clone()), "a leaf the other side lacks is a difference"); + } + + fn recipe(items: &[(&str, f64)]) -> Vec<(String, f64)> { + items.iter().map(|(id, v)| (id.to_string(), *v)).collect() + } + + /// A recipe that names nothing, or a control `set` would drop (a per-photo instance on fresh + /// settings), stores nothing: the command answers with an error, not an empty preset. + #[test] + fn a_recipe_that_stores_nothing_is_none() { + assert_eq!(recipe_partial(&[]), None); + assert_eq!(recipe_partial(&recipe(&[("pointColor.0.hueShift", 5.0)])), None, "set returns false for it"); + assert_eq!(recipe_partial(&recipe(&[("nope.nope", 5.0)])), None); + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.5)])), Some(json!({"light": {"exposure": 0.5}}))); + // a reset to the control's default is stored + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.0)])), Some(json!({"light": {"exposure": 0.0}}))); + } + + /// The HDR subtree is left out of the JSON while it is the default, so a reset of a headroom to its + /// default is stored in the preset by itself and next to another adjustment. + #[test] + fn an_hdr_reset_is_stored_alone_and_next_to_another_adjustment() { + let reset = recipe_partial(&recipe(&[("hdr.maxEv", 3.0)])).expect("a reset is stored"); + assert_eq!(reset.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{reset}"); + let both = recipe_partial(&recipe(&[("hdr.maxEv", 3.0), ("light.exposure", 0.5)])).expect("both are stored"); + assert_eq!(both.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{both}"); + assert_eq!(both.pointer("/light/exposure"), Some(&json!(0.5)), "{both}"); + } +} diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 2a663b79de..188dc6ae99 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -82,6 +82,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result { metadata_preset, convert_dng: bool_or(p, "dng", false), local: bool_or(p, "local", false), + recipe: crate::cmd::recipe_param(p, "library.import")?, }; let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); Ok(ImportRequest { paths, opts, album, album_name }) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 7732b855ba..c725ac216b 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1348,7 +1348,7 @@ pub fn specs() -> Vec { "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 (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?}", + "{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, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), 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)?; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index cd3123e522..96ce93d0c1 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -15,7 +15,8 @@ //! 6. Apply 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`]). Its capture time fills //! in when the file has none (read before step 5, so it also files and names the copy). -//! 7. Optionally apply a preset and add keywords (the import dialog's options). +//! 7. Optionally apply a preset, then a batch-edit recipe (one more History step), and add +//! keywords (the import dialog's options). //! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records; //! the files stay at the destination — undo never moves files back over a card.) //! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index d283bb0ac4..104d1f63b9 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -291,6 +291,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.edited = Some(now.clone()); p.history.push(lightcraft_catalog::HistoryStep { label, settings: d }); } + // the batch-edit recipe goes on top of everything above (sidecar, camera default, + // preset): only the controls it names change, through the same specs the sliders use + if !opts.recipe.is_empty() { + let mut d = (*p.develop).clone(); + for (id, v) in &opts.recipe { + // (`ImportJob::new` refused any id `set` would not write, and `set` clamps to the range) + lightcraft_develop::controls::set(&mut d, id, *v); + } + let d = std::sync::Arc::new(d); + p.develop = d.clone(); + p.edited = Some(now.clone()); + p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d }); + } report.imported.push(id.0); p.local = opts.local; if opts.local { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index e8ed759dd2..ca906c6192 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -163,6 +163,8 @@ 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 { + // a recipe is checked before any file is read or placed, not when the photos are committed + crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?; 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". diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index f342bf4c92..aab839931b 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -67,6 +67,16 @@ pub struct ImportOptions { pub metadata_preset: Option, /// Copy: raws are copied as DNG (Copy as DNG). pub convert_dng: bool, + /// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5), + /// applied to every imported photo *after* its XMP sidecar, camera default and import preset, + /// as one more History step (`Import adjustments`). Only the named controls change; the recipe + /// is a snapshot taken when the import starts, so editing a preset afterwards cannot change it. + /// It names plain adjustments only (no white balance, geometry or crop: `cmd::check_recipe`), + /// and [`ImportJob::new`] refuses anything else. + /// Empty (the default) = no recipe. A photo the library already has keeps its own settings: + /// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed + /// folder (Local) is never touched, as the preset and keywords never are. + pub recipe: Vec<(String, f64)>, } /// How copies are filed in the destination. The date is the capture time, else the time of the diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 5df2ac680d..34e301a6fd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3139,6 +3139,319 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() { let _ = std::fs::remove_dir_all(&src); } +/// A batch-edit recipe changes the imported photos' actual develop settings (not just an option +/// label), renders, is one undo step, and can be saved as a preset that stores only what it names. +#[test] +fn a_batch_edit_recipe_changes_imported_photos() { + let src = temp_dir("recipe"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = Session::new().with_fs(); + let r = s + .execute( + "library.import", + &json!({ + "paths": [src.to_string_lossy()], + "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}], + }), + ) + .unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); + for p in s.catalog.photos() { + assert_eq!(p.develop.light.exposure, 0.5, "{}", p.file_name); + assert_eq!(p.develop.color.vibrance, 20.0, "{}", p.file_name); + assert!(p.history.iter().any(|h| h.label == "Import adjustments"), "{}", p.file_name); + } + // the edit really renders (the recipe is applied to the settings, not only recorded) + let id = s.catalog.photos().next().unwrap().id; + assert!(s.render_now(id, 32, 32).is_ok()); + // saving the recipe as a preset keeps only the settings it names + let p = s.execute("preset.saveRecipe", &json!({"name": "Warm Trip", "recipe": [{"id": "light.exposure", "value": 0.5}]})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(0.5)), "{}", saved.settings); + assert!(saved.settings.get("color").is_none(), "an unnamed group is not stored: {}", saved.settings); + // one undo step for the whole import + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 0); + let _ = std::fs::remove_dir_all(&src); +} + +/// A malformed recipe, or one naming a control a recipe may not name, is refused before anything +/// is imported, and by the command that saves one: unknown ids, controls that belong to one photo, +/// geometry and crop controls (the slider refits the crop around them), white balance (a +/// temperature means something else on each kind of file), and lists longer than the control list. +#[test] +fn a_bad_recipe_is_refused() { + let mut s = Session::new().with_fs(); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": [{"id": "nope.nope", "value": 1}]})).unwrap_err(); + assert!(format!("{err}").contains("unknown recipe control"), "{err}"); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": "x"})).unwrap_err(); + assert!(format!("{err}").contains("recipe"), "{err}"); + assert_eq!(s.catalog.len(), 0); + let too_many: Vec = (0..lightcraft_develop::controls::CONTROLS.len() + 1).map(|_| json!({"id": "light.exposure", "value": 1})).collect(); + for (bad, why) in [ + (json!([{"value": 1}]), "needs an `id`"), + (json!([{"id": "light.exposure"}]), "numeric"), + (json!([{"id": "light.exposure", "value": "high"}]), "numeric"), + (json!([7]), "needs an `id`"), + (json!([{"id": "pointColor.0.hueShift", "value": 5}]), "unknown recipe control"), + (json!([{"id": "redEye.0.pupilSize", "value": 5}]), "unknown recipe control"), + (json!([{"id": "crop.angle", "value": 5}]), "geometry"), + (json!([{"id": "geometry.rotate", "value": 5}]), "geometry"), + (json!([{"id": "wb.temp", "value": 5200}]), "white balance"), + (json!([{"id": "wb.tint", "value": 5}]), "white balance"), + (json!([{"id": "light.exposure", "value": 1}, {"id": "crop.angle", "value": 5}]), "geometry"), + (json!(too_many), "at most"), + ] { + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + let before = s.presets.len(); + let err = s.execute("preset.saveRecipe", &json!({"name": "Bad", "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + assert_eq!(s.presets.len(), before, "nothing saved for {why}"); + } + // the job itself refuses what the command would (a recipe built in code, not from JSON) + let opts = crate::import::ImportOptions { recipe: vec![("crop.angle".into(), 5.0)], ..Default::default() }; + assert!(crate::import::ImportJob::new(&mut s, opts).is_err()); + // no name, a name that is too long, or nothing in the recipe: no preset + let one = json!([{"id": "light.exposure", "value": 1}]); + for params in [json!({"recipe": one}), json!({"name": " ", "recipe": one}), json!({"name": "x".repeat(101), "recipe": one})] { + assert!(s.execute("preset.saveRecipe", ¶ms).is_err(), "{params}"); + } + assert!(s.execute("preset.saveRecipe", &json!({"name": "x".repeat(100), "recipe": one})).is_ok(), "a name of 100 characters is fine"); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty", "recipe": []})).is_err()); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty"})).is_err()); + assert!(!s.presets.iter().any(|p| p.name == "Empty")); +} + +/// The recipe's values go through the control specs like a slider's: past the range they stop at +/// it, for the photo and for the preset. A control named twice counts once, the last value wins. +#[test] +fn recipe_values_are_clamped_like_a_slider() { + let src = temp_dir("recipe-clamp"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + let recipe = json!([{"id": "light.exposure", "value": 1}, {"id": "light.exposure", "value": 99}, {"id": "light.contrast", "value": -1000}]); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + let p = s.catalog.photos().next().unwrap(); + assert_eq!((p.develop.light.exposure, p.develop.light.contrast), (5.0, -100.0)); + let saved = s.execute("preset.saveRecipe", &json!({"name": "Clamped", "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == saved["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(5.0)), "{}", saved.settings); + assert_eq!(saved.settings.pointer("/light/contrast"), Some(&json!(-100.0)), "{}", saved.settings); + let _ = std::fs::remove_dir_all(&src); +} + +/// A session whose files probe as DNG raws shot at 4800 K, tint +12 (the pixels stay the PNG's; +/// nothing here renders them), to see what an import does to a raw's as-shot white balance. +fn session_with_raw_probe() -> Session { + let mut s = Session::new().with_fs(); + let real = s.media.file_probe.clone().unwrap(); + s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| { + let mut info = real(path)?; + info.kind = lightcraft_catalog::MediaKind::Raw; + info.format = "DNG".into(); + info.as_shot_wb = Some((4800.0, 12.0)); + Ok(info) + })); + s +} + +fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId { + let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap(); + lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}"))) +} + +fn white_balance(s: &Session, id: lightcraft_catalog::PhotoId) -> lightcraft_develop::WhiteBalance { + s.catalog.photo(id).unwrap().develop.wb +} + +/// A recipe never touches white balance: a raw keeps the as-shot temperature, tint and scale it was +/// imported with, whatever else the recipe sets, and a recipe cannot name a temperature or tint. +#[test] +fn a_recipe_leaves_a_raws_as_shot_white_balance_alone() { + use lightcraft_develop::{WbMode, WbScale}; + let src = temp_dir("recipe-wb"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = session_with_raw_probe(); + let plain = import_one(&mut s, &src.join("a.png"), json!([])); + let w = white_balance(&s, plain); + assert_eq!((w.mode, w.temp, w.tint, w.scale), (WbMode::AsShot, 4800.0, 12.0, WbScale::Kelvin), "{w:?}"); + let with = import_one(&mut s, &src.join("b.png"), json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 30}])); + assert_eq!(white_balance(&s, with), w, "the as-shot white balance is as the import left it"); + assert_eq!(s.catalog.photo(with).unwrap().develop.light.exposure, 0.5); + for id in ["wb.temp", "wb.tint"] { + let err = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": [{"id": id, "value": 5200}]})).unwrap_err(); + assert!(err.to_string().contains("white balance"), "{err}"); + } + let _ = std::fs::remove_dir_all(&src); +} + +/// Saved as a preset and applied to a photo as it was imported, a recipe gives the settings +/// importing with it gives (for a raw too), and the preset holds a control the recipe sets to its +/// default: that is a reset, not "nothing named". +#[test] +fn a_recipe_saved_as_a_preset_gives_what_the_recipe_gives() { + let src = temp_dir("recipe-preset"); + let recipes = [ + json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]), + json!([{"id": "light.exposure", "value": 99}]), + json!([{"id": "detail.sharpenAmount", "value": 0}, {"id": "grain.amount", "value": 30}]), + json!([{"id": "vignette.amount", "value": -25}, {"id": "effects.clarity", "value": 15}, {"id": "mixer.red.hue", "value": 10}]), + ]; + let mut s = session_with_raw_probe(); + for (i, recipe) in recipes.iter().enumerate() { + write_png(&src.join(format!("with{i}.png")), 2 * i as u8); + write_png(&src.join(format!("plain{i}.png")), 2 * i as u8 + 1); + let with = import_one(&mut s, &src.join(format!("with{i}.png")), recipe.clone()); + let plain = import_one(&mut s, &src.join(format!("plain{i}.png")), json!([])); + let saved = s.execute("preset.saveRecipe", &json!({"name": format!("Recipe {i}"), "recipe": recipe})).unwrap(); + s.selection = crate::Selection::single(plain); + s.execute("preset.apply", &json!({"id": saved["id"], "ids": [plain.0]})).unwrap(); + let (with, plain) = (s.catalog.photo(with).unwrap(), s.catalog.photo(plain).unwrap()); + assert_eq!(with.develop, plain.develop, "recipe {recipe}"); + } + // the sharpening reset (a raw's default is 40) is in the preset although 0 is the control's default + let reset = s.presets.iter().find(|p| p.name == "Recipe 2").unwrap(); + assert_eq!(reset.settings.pointer("/detail/sharpen_amount"), Some(&json!(0.0)), "{}", reset.settings); + assert_eq!(s.catalog.photos().find(|p| p.file_name == "with2.png").unwrap().develop.detail.sharpen_amount, 0.0); + let _ = std::fs::remove_dir_all(&src); +} + +/// The recipe applies to the photos an import adds. A file the library has (by path or by +/// content), a trashed one that comes back, and a browsed one that joins keep their own +/// settings; a trashed one imported afresh is a new photo and gets the recipe. +#[test] +fn a_recipe_only_touches_the_photos_an_import_adds() { + let src = temp_dir("recipe-skipped"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + write_png(&src.join("c.png"), 3); + std::fs::copy(src.join("a.png"), src.join("a-copy.png")).unwrap(); // same bytes as a + let recipe = json!([{"id": "color.vibrance", "value": 20}]); + let adjusted = |s: &Session, name: &str| { + let p = s.catalog.photos().find(|p| p.file_name == name && !p.deleted).unwrap_or_else(|| panic!("no {name}")); + (p.develop.color.vibrance, p.history.iter().any(|h| h.label == "Import adjustments")) + }; + + let mut s = Session::new().with_fs(); + let first = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(first); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap(); + let a_before = s.catalog.photo(first).unwrap().develop.clone(); + + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); // b and c + assert_eq!(ids(&r, "duplicates"), 2, "{r}"); // a (same path) and a-copy (same content) + assert_eq!(adjusted(&s, "b.png"), (20.0, true)); + assert_eq!(adjusted(&s, "c.png"), (20.0, true)); + assert_eq!(adjusted(&s, "a.png"), (0.0, false), "a duplicate is not edited"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "nor is the photo it duplicates"); + assert_eq!(s.catalog.len(), 3); + + // in Recently Deleted: restored with its own settings, no recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "restored")), (0, 1), "{r}"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "a restored photo keeps its edits"); + assert!(!s.catalog.photo(first).unwrap().history.iter().any(|h| h.label == "Import adjustments")); + + // …imported afresh, it is a new photo and gets the recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe, "onDeleted": "fresh"})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "a.png"), (20.0, true)); + + // browsed first (Local), then imported: the record joins the library as it is, as it does for + // a preset or keywords + let other = temp_dir("recipe-browsed"); + write_png(&other.join("d.png"), 4); + s.execute("library.browse", &json!({"path": other.to_string_lossy()})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [other.join("d.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "d.png"), (0.0, false), "a browsed photo that joins keeps its own settings"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&other); +} + +/// A saved recipe never takes another preset's id: with presets A and B, A deleted, a recipe saved +/// as "B" is its own preset and applying it applies the recipe, not the older B. Saving the same +/// recipe under the same name again is that preset, and the presets are in presets.json. +#[test] +fn saved_recipe_presets_get_distinct_ids_and_survive_reopening() { + let lib = temp_dir("recipe-presets-lib"); + let src = temp_dir("recipe-presets-src"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let photo = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(photo); + let create = |s: &mut Session, name: &str| s.execute("preset.create", &json!({"name": name})).unwrap()["id"].as_str().unwrap().to_string(); + let (a, old_b) = (create(&mut s, "A"), create(&mut s, "B")); + s.execute("preset.delete", &json!({"id": a})).unwrap(); + let recipe = json!([{"id": "light.exposure", "value": 0.7}]); + let saved = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + let new_b = saved["id"].as_str().unwrap().to_string(); + assert_ne!(new_b, old_b); + let mut all: Vec<&str> = s.presets.iter().map(|p| p.id.as_str()).collect(); + let n = all.len(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), n, "every preset has its own id"); + s.execute("preset.apply", &json!({"id": new_b})).unwrap(); + assert_eq!(s.catalog.photo(photo).unwrap().develop.light.exposure, 0.7, "the saved recipe is what gets applied"); + // the same recipe, name and group: the preset it already is + let again = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + assert_eq!(again["id"], saved["id"]); + assert_eq!(s.presets.iter().filter(|p| p.name == "B").count(), 2); + drop(s); + + let mut t = Session::new().with_fs(); + t.open_library(&lib, false).unwrap(); + let mut bs: Vec<&str> = t.presets.iter().filter(|p| p.name == "B").map(|p| p.id.as_str()).collect(); + bs.sort(); + let mut expected = [old_b.as_str(), new_b.as_str()]; + expected.sort(); + assert_eq!(bs, expected, "both are still there after reopening"); + assert!(!t.presets.iter().any(|p| p.name == "A"), "the deleted one stays deleted"); + drop(t); + let _ = std::fs::remove_dir_all(&lib); + let _ = std::fs::remove_dir_all(&src); +} + +/// Both commands are in the command list with their parameters documented, which is where the +/// control channel, the CLI and MCP's `list_commands` read them. +#[test] +fn the_recipe_commands_are_listed_with_their_parameters() { + let s = Session::new(); + let commands = s.commands(); + let import = commands.iter().find(|c| c.id == "library.import").unwrap(); + assert!(import.params.contains("recipe?: [{id:") && import.params.contains("Import adjustments"), "{}", import.params); + assert!(import.params.contains("no white balance, geometry or crop") && import.params.contains("is not changed"), "{}", import.params); + let save = commands.iter().find(|c| c.id == "preset.saveRecipe").expect("preset.saveRecipe is a command"); + assert!(save.enabled && save.params.contains("recipe: [{id:") && save.params.contains("name"), "{}", save.params); +} + +/// A saved recipe that resets an HDR control to its default is applied as the recipe would apply it: +/// alone, and next to another adjustment, on a photo whose HDR settings are not the default. +#[test] +fn a_saved_hdr_reset_applies_to_existing_hdr_settings() { + let mut s = Session::new(); + for recipe in [json!([{"id": "hdr.maxEv", "value": 3}]), json!([{"id": "hdr.maxEv", "value": 3}, {"id": "light.exposure", "value": 0.5}])] { + let p = s.execute("preset.saveRecipe", &json!({"name": format!("Reset {recipe}"), "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap().settings.clone(); + let mut base = lightcraft_develop::DevelopSettings::default(); + base.hdr.enabled = true; + base.hdr.max_ev = 1.5; + let out = lightcraft_develop::apply_partial(&base, &saved, 1.0); + assert_eq!(out.hdr.max_ev, 3.0, "{saved}"); + assert!(out.hdr.enabled, "the reset leaves the other HDR settings alone: {saved}"); + let want_exposure = if recipe.as_array().unwrap().len() > 1 { 0.5 } else { base.light.exposure }; + assert_eq!(out.light.exposure, want_exposure, "{saved}"); + } +} + /// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the /// root (CodeRabbit on #3055 / #3080). #[test] diff --git a/crates/mcp/tests/it/e2e.rs b/crates/mcp/tests/it/e2e.rs index 2a8db44c7d..0e0bd98e5e 100644 --- a/crates/mcp/tests/it/e2e.rs +++ b/crates/mcp/tests/it/e2e.rs @@ -412,3 +412,48 @@ fn export_without_token_finishes_after_eof() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2); std::fs::remove_dir_all(dir).unwrap(); } + +/// A batch-edit recipe is reachable over MCP without a tool of its own: `run_command` takes +/// `library.import` with a `recipe`, the generated `cmd_preset_saveRecipe` tool saves one as a +/// preset, `list_commands` documents both, and a recipe naming white balance is a tool error that +/// imports nothing. +#[test] +fn a_batch_edit_recipe_is_reachable_over_mcp() { + let dir = std::env::temp_dir().join(format!("lightcraft-mcp-recipe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [(x * 2) as u8, (y * 3) as u8, 128, 255]); + lightcraft_mcp::write_image(&dir.join("gradient.png"), &img, 90).unwrap(); + let paths = json!([dir.to_string_lossy()]); + let mut server = Server::new(Box::new(Headless::default())); + let replies = session( + &mut server, + &[ + call(1, "list_commands", json!({"filter": "recipe"})), + call(2, "run_command", json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "wb.temp", "value": 5000}]}})), + call(3, "query_photos", json!({"limit": 5})), + call( + 4, + "run_command", + json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]}}), + ), + call(5, "get_develop", json!({})), + call(6, "cmd_preset_saveRecipe", json!({"name": "Warm", "recipe": [{"id": "light.exposure", "value": 0.5}]})), + call(7, "list_commands", json!({"filter": "library.import"})), + ], + ); + let listed = |r: &Value| -> Vec { serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap() }; + let save = listed(&replies[0]).into_iter().find(|c| c["id"] == "preset.saveRecipe").expect("preset.saveRecipe is listed"); + assert!(save["params"].as_str().unwrap().contains("recipe: [{id:"), "{save}"); + assert_eq!(replies[1]["result"]["isError"], true, "{}", replies[1]); + assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("white balance"), "{}", replies[1]); + assert!(replies[2]["result"]["structuredContent"]["photos"].as_array().unwrap().is_empty(), "the refused import added nothing"); + assert_eq!(replies[3]["result"]["isError"], false, "{}", replies[3]); + assert_eq!(replies[3]["result"]["structuredContent"]["imported"].as_array().unwrap().len(), 1); + assert_eq!(replies[4]["result"]["structuredContent"]["light"]["exposure"], 0.5, "{}", replies[4]); + assert_eq!(replies[4]["result"]["structuredContent"]["color"]["vibrance"], 20.0, "{}", replies[4]); + assert_eq!(replies[5]["result"]["isError"], false, "{}", replies[5]); + assert_eq!(replies[5]["result"]["structuredContent"]["name"], "Warm"); + let import = listed(&replies[6]).into_iter().find(|c| c["id"] == "library.import").expect("library.import is listed"); + assert!(import["params"].as_str().unwrap().contains("recipe?: [{id:"), "{import}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 43d8da59b4..7e78396a1c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} Foto{} zu „Meine Fotos“ hinzugefügt", "Added {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzugefügt", "Added {what} to {name}": "{what} zu {name} hinzugefügt", + "Adjustments: {n}": "Anpassungen: {n}", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index bdfd440f1f..77d40f0ec0 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} foto{0} añadida{0} a Mis fotos", "Added {n} photo{} to “{}”": "{n} foto{0} añadida{0} a “{1}”", "Added {what} to {name}": "{what} añadido a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 16782e3499..ba6bcc7b0f 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} photo{} ajoutée(s) à Mes photos", "Added {n} photo{} to “{}”": "{n} photo{} ajoutée(s) à « {} »", "Added {what} to {name}": "{what} ajouté à {name}", + "Adjustments: {n}": "Réglages : {n}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index bc6ce0e60a..9f7dd3fe7c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "。{outside}枚は記録時間の範囲外", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:PR {}件、コミット {}件、+{} / −{} 行(Δ {})、バイナリアセット +{} / −{}、{} – {}", "Added {what} to {name}": "{what}を{name}に追加しました", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動読み込み:{}枚の写真を追加しました{:.0}", "Building previews for {} photos…": "{}枚のプレビューを作成中…", "Couldn't open the editor: {e}": "エディターを開けませんでした:{e}", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index cecd8149c0..4227fe328a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "; {outside} fora do intervalo de tempo", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: {} PRs, {} commits, +{} / −{} linhas (Δ {}), +{} / −{} arquivos binários, {} – {}", "Added {what} to {name}": "{what} adicionado a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Auto Import: added {} photo{}": "Importação automática: {} foto{1} adicionada{1}", "Building previews for {} photos…": "Gerando prévias de {} fotos…", "Couldn't open the editor: {e}": "Não foi possível abrir o editor: {e}", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index d6156cc1fa..24134de944 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -25,6 +25,7 @@ "Added {n} photo{} to My Photos": "В «Мои фото» добавлено фото: {n}{:.0}", "Added {n} photo{} to “{}”": "В «{1}» добавлено фото: {n}{0:.0}", "Added {what} to {name}": "{what}: добавлено в {name}", + "Adjustments: {n}": "Корректировки: {n}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index ed5e041f82..d30091f2d2 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "До моїх фото додано: {n}{:.0}", "Added {n} photo{} to “{}”": "До «{1}» додано фото: {n}{0:.0}", "Added {what} to {name}": "{what}: додано до {name}", + "Adjustments: {n}": "Коригування: {n}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 2996e1a217..1d5f27c576 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 张不在其时间范围内", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 个 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 个二进制资源,{} – {}", "Added {what} to {name}": "已将{what}添加到 {name}", + "Adjustments: {n}": "调整:{n}", "Auto Import: added {} photo{}": "自动导入:已添加 {0} 张照片{1:.0}", "Building previews for {} photos…": "正在为 {0} 张照片生成预览…", "Couldn't open the editor: {e}": "无法打开编辑器:{e}", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 93f6d6fa00..51fb1109ae 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 張不在其時間範圍內", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 個 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 個二進位資產,{} – {}", "Added {what} to {name}": "已將{what}加入 {name}", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動匯入:已新增 {} 張照片{:.0}", "Building previews for {} photos…": "正在為 {} 張照片建立預覽…", "Couldn't open the editor: {e}": "無法開啟編輯器:{e}", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 4336e5e82f..5ce31dacce 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -3,7 +3,8 @@ //! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a //! range), the destination (add in place / copy or move into the library's `Originals/` or a //! chosen folder, filed by day, by month, into one folder or by a custom folder template, -//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan +//! optionally renamed), an album (existing or new), a preset, an optional batch-edit recipe +//! ("Batch edits": develop controls set on every new photo) and keywords to apply. When the scan //! left something out (a walk cut at its limit, folders it couldn't read, files that are not //! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread //! (files are probed, copied or moved there) and its batches join the catalog between frames, with @@ -29,6 +30,7 @@ mod task; #[cfg(test)] pub(crate) use body::grid_height; +use body::recipe_items; pub(crate) use body::scan_note; #[cfg(test)] pub(crate) use body::thumb_edge; @@ -36,6 +38,8 @@ pub(crate) use body::thumb_edge; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; +#[cfg(test)] +use body::{RECIPE_CONTROLS, note_recipe_value}; pub(crate) use scan::StoppingScans; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; @@ -63,6 +67,12 @@ pub struct ImportDialog { pub new_album: String, /// Preset id ("" = none). pub preset: String, + /// An optional batch-edit recipe: develop control id → value (only controls moved off their + /// default are kept), set on every photo this import adds, on top of its sidecar, camera + /// default and preset (the `recipe` param of `library.import`). + pub recipe: std::collections::BTreeMap, + /// Name typed for "Save as Preset" (the recipe saved for reuse). + pub recipe_name: String, /// Comma-separated keywords. pub keywords: String, /// Copy: destination folder ("" = the library's Originals/). @@ -384,4 +394,50 @@ mod tests { d.click(2, true); assert_eq!(d.checked, [true, true, false, false, true, true]); } + + /// The dialog offers only controls a recipe may name: `library.import` refuses the others + /// (white balance, geometry and crop, per-photo controls), so one offered here would make every + /// import with it fail. Each is moved off its default, as a slider drag does. + #[test] + fn every_offered_recipe_control_is_accepted_by_the_import() { + let session = lightcraft_engine::Session::new(); + let mut d = dialog(); + for id in RECIPE_CONTROLS { + let spec = lightcraft_develop::controls::find(id).unwrap_or_else(|| panic!("{id} is not a develop control")); + let moved = if spec.default < spec.max { spec.max } else { spec.min }; + note_recipe_value(&mut d.recipe, spec, moved); + } + assert_eq!(d.recipe.len(), RECIPE_CONTROLS.len(), "all named, none repeated"); + let params = json!({"paths": ["img0.jpg"], "recipe": recipe_items(&d.recipe)}); + let request = lightcraft_engine::cmd::library::import_params(&session, ¶ms).unwrap_or_else(|e| panic!("refused: {e}")); + assert_eq!(request.opts.recipe.len(), RECIPE_CONTROLS.len()); + } + + /// A slider moved off its default names its control in the recipe; moved back, it no longer does. + #[test] + fn a_slider_back_at_its_default_leaves_the_recipe() { + let spec = lightcraft_develop::controls::find("light.exposure").unwrap(); + let mut recipe = std::collections::BTreeMap::new(); + note_recipe_value(&mut recipe, spec, 0.5); + assert_eq!(recipe.get("light.exposure"), Some(&0.5)); + note_recipe_value(&mut recipe, spec, 1.25); + assert_eq!(recipe.get("light.exposure"), Some(&1.25), "a new value replaces the old"); + note_recipe_value(&mut recipe, spec, spec.default); + assert!(recipe.is_empty(), "{recipe:?}"); + } + + /// `start` hands `library.import` a `recipe` only when the dialog has one. + #[test] + fn start_passes_the_recipe_only_when_the_dialog_has_one() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services { png: None, ..Default::default() }); + let mut d = dialog(); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert!(params.get("recipe").is_none(), "{params}"); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), -20.0); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert_eq!(params["recipe"], json!([{"id": "color.vibrance", "value": -20.0}, {"id": "light.exposure", "value": 0.5}]), "{params}"); + } } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index d461d690ab..5228f7b95b 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -1,7 +1,7 @@ use serde_json::json; use super::tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; -use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Vec2, pos2, register, vec2}; +use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Value, Vec2, pos2, register, vec2}; /// The review dialog's first size (points). It can be resized; the photo grid takes the height. pub(crate) const DIALOG_SIZE: [f32; 2] = [960.0, 720.0]; @@ -447,6 +447,96 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text(crate::i18n::tr("comma, separated")).desired_width(f32::INFINITY)); register(ui, "field:importKeywords", r.rect); }); + recipe_section(app, ui, d); +} + +/// The develop controls offered in the import review's optional batch-edit recipe: the everyday +/// adjustments, not a second editor. Each must be one a recipe may name (`library.import` refuses +/// the others: no white balance, geometry or crop); a test holds the list to that. Anything else is +/// reached by choosing or saving a preset. +pub(super) const RECIPE_CONTROLS: &[&str] = &[ + "light.exposure", + "light.contrast", + "light.highlights", + "light.shadows", + "light.whites", + "light.blacks", + "color.vibrance", + "color.saturation", + "effects.clarity", + "effects.texture", + "effects.dehaze", + "detail.sharpenAmount", + "grain.amount", + "vignette.amount", +]; + +/// A recipe as the `recipe` param of `library.import` and `preset.saveRecipe`. +pub(super) fn recipe_items(recipe: &std::collections::BTreeMap) -> Value { + Value::Array(recipe.iter().map(|(id, v)| json!({"id": id, "value": v})).collect()) +} + +/// Record a slider's new value in the recipe: a control back at its default is no longer named. +pub(super) fn note_recipe_value(recipe: &mut std::collections::BTreeMap, spec: &lightcraft_develop::controls::ControlSpec, value: f64) { + if (value - spec.default).abs() < 1e-9 { + recipe.remove(spec.id); + } else { + recipe.insert(spec.id.to_string(), value); + } +} + +/// The optional "Batch edits" section of the import review: a small recipe of develop controls set +/// on every photo this import adds, on top of its XMP sidecar, camera default and the chosen preset. +/// The recipe lives only in the dialog until the import runs, so cancelling changes neither the +/// catalog nor the preset collections; "Save as Preset" is the explicit way to keep one for reuse. +fn recipe_section(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { + let t = Tokens::get(ui.ctx()); + let open_id = egui::Id::unique("import-recipe-open"); + let mut open = ui.ctx().data(|m| m.get_temp::(open_id)).unwrap_or(false); + field(ui, "Batch edits", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if crate::widgets::text_button(ui, "importRecipeToggle", if open { "Hide adjustments" } else { "Adjust…" }, open).clicked() { + open = !open; + } + let n = d.recipe.len(); + let summary = if n == 0 { crate::i18n::tr("None").to_string() } else { crate::i18n::tr_format!("Adjustments: {n}", n = n) }; + ui.label(egui::RichText::new(summary).color(if n == 0 { t.text_dim } else { t.text_label })); + }); + ui.ctx().data_mut(|m| m.insert_temp(open_id, open)); + if !open { + return; + } + ui.label( + egui::RichText::new(crate::i18n::tr( + "Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.", + )) + .color(t.text_dim) + .small(), + ); + for &id in RECIPE_CONTROLS { + let Some(spec) = lightcraft_develop::controls::find(id) else { continue }; + let v = d.recipe.get(id).copied().unwrap_or(spec.default); + if let Some(nv) = crate::widgets::slider(ui, spec, v, true, None).value { + note_recipe_value(&mut d.recipe, spec, nv); + } + } + field(ui, "Recipe", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + crate::text_field::TextField::singleline("field:importRecipeName", &mut d.recipe_name) + .hint(crate::i18n::tr("name for a saved preset")) + .width(160.0) + .show(ui); + let can = !d.recipe.is_empty() && !d.recipe_name.trim().is_empty(); + let b = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Save as Preset"))); + register(ui, "button:importRecipeSave", b.rect); + if b.clicked() { + let params = json!({"name": d.recipe_name.trim(), "recipe": recipe_items(&d.recipe)}); + match app.run("preset.saveRecipe", params) { + Ok(_) => app.toast(ui.ctx(), crate::i18n::tr("Saved as a preset")), + Err(e) => app.toast_error(ui.ctx(), e), + } + } + }); } /// Draw one import-dialog candidate cell: register `import:{i}`, request the cell's thumbnail, diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 5c27983400..71ac358f9a 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -1,5 +1,5 @@ use super::scan::{busy_synchronizing, running}; -use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json}; +use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json, recipe_items}; /// Files per batch in the browser build (each batch joins the catalog as it is ready, so the /// progress window updates); the desktop's worker uses [`lightcraft_engine::import::batch_size`]. @@ -16,7 +16,7 @@ pub struct ImportTask { queue: Vec, pub total: usize, pub done: usize, - params: Value, + pub(super) params: Value, pub imported: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, @@ -225,6 +225,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result (true, true) => "move", }; let mut params = json!({"mode": mode, "keywords": d.keywords()}); + if !d.recipe.is_empty() { + params["recipe"] = recipe_items(&d.recipe); + } if !d.on_deleted.is_empty() { params["onDeleted"] = json!(d.on_deleted); } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e71ef8164a..f801ee843f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod grid; mod grid_drag; mod guided_guides; mod histogram_drag; +mod import_recipe; mod import_scan_note; mod import_thumbnails; mod info_dialogs; diff --git a/crates/ui-egui/src/tests/import_recipe.rs b/crates/ui-egui/src/tests/import_recipe.rs new file mode 100644 index 0000000000..7a46603dfe --- /dev/null +++ b/crates/ui-egui/src/tests/import_recipe.rs @@ -0,0 +1,182 @@ +//! The import review's "Batch edits" section: the recipe in the dialog is what the import sets on +//! the photos it adds, "Save as Preset" needs a name and a recipe, and cancelling the review +//! changes neither the catalog nor the presets. + +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use crate::dialogs::import::ImportDialog; +use crate::headless::Headless; +use crate::state::{Dialog, ViewMode}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// A folder of two small PNGs. +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-ui-import-recipe-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..2u8 { + let data: Vec<[u8; 4]> = (0..40 * 30).map(|k| [(k % 40 * 6) as u8, i * 90, 7, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: 40, height: 30, 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(); + } + dir +} + +/// The app with an empty library and the import review open on a folder of two photos. +fn review(tag: &str) -> (Headless, PathBuf) { + let dir = folder(tag); + let app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 1400.0], 1.0); + h.app.ui.view = ViewMode::PhotoGrid; + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), T); + assert_eq!(r["result"]["scanning"], true, "{r}"); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + h.settle(SETTLE); + (h, dir) +} + +fn dialog(h: &mut Headless) -> &mut ImportDialog { + match &mut h.app.ui.dialog { + Some(Dialog::Import { opts }) => opts, + other => panic!("no import review: {other:?}"), + } +} + +/// Where a widget is and where the review's window is: `[x, y, w, h]` each. +fn rects(h: &mut Headless, id: &str) -> ([f64; 4], [f64; 4]) { + let r = h.request("ui.widgets", json!({}), T); + let all = r["result"].as_array().expect("widgets"); + let find = |name: &str| -> [f64; 4] { + let w = all.iter().find(|w| w["id"] == name).unwrap_or_else(|| panic!("no widget {name}")); + [0usize, 1, 2, 3].map(|i| w["rect"][i].as_f64().unwrap()) + }; + (find(id), find("dialog:window")) +} + +/// Click a widget of the review, scrolling the review first when the widget is below its window +/// (the review's content scrolls; the Batch edits section is at the bottom of it). +fn click(h: &mut Headless, id: &str) { + for _ in 0..40 { + let (w, win) = rects(h, id); + if w[1] + w[3] <= win[1] + win[3] - 30.0 { + break; + } + h.request("ui.move", json!({"x": win[0] + win[2] / 2.0, "y": win[1] + win[3] / 2.0}), T); + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.settle(SETTLE); + } + let (w, win) = rects(h, id); + assert!(w[1] >= win[1] && w[1] + w[3] <= win[1] + win[3], "{id} {w:?} is inside the window {win:?}"); + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.settle(SETTLE); +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default() +} + +/// Wait for the import the review started to finish. +fn finish_import(h: &mut Headless) { + let t0 = std::time::Instant::now(); + while h.app.import.is_some() && t0.elapsed() < Duration::from_secs(60) { + h.step(); + } + assert!(h.app.import.is_none(), "the import finished"); + h.settle(SETTLE); +} + +/// "Save as Preset" saves nothing without a name or without a recipe, and with both saves exactly +/// the recipe as a preset, leaving the review's own choices (its preset, the photos) as they were. +#[test] +fn save_as_preset_needs_a_name_and_a_recipe() { + let (mut h, dir) = review("save"); + let presets0 = h.app.session.presets.len(); + click(&mut h, "button:importRecipeToggle"); + assert!( + h.request("ui.widgets", json!({"filter": "importRecipeSave"}), T)["result"].as_array().is_some_and(|w| !w.is_empty()), + "the section is open" + ); + + dialog(&mut h).recipe_name = "Warm trip".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a name alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off: pressing it does not even ask the engine (which would refuse with a message)"); + + let d = dialog(&mut h); + d.recipe_name = " ".into(); + d.recipe.insert("light.exposure".into(), 0.5); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a recipe alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off without a name too"); + + dialog(&mut h).recipe_name = " Warm trip ".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0 + 1, "{}", toast(&h)); + let saved = h.app.session.presets.iter().find(|p| p.name == "Warm trip").expect("the preset is named as typed, trimmed"); + assert_eq!(saved.settings, json!({"light": {"exposure": 0.5}}), "only what the recipe names"); + assert_eq!(toast(&h), "Saved as a preset"); + assert_eq!(dialog(&mut h).preset, "", "the review's own preset choice is not replaced"); + assert_eq!(h.app.session.catalog.len(), 0, "nothing was imported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Cancelling the review with a recipe in it adds no photo and saves no preset. +#[test] +fn cancelling_the_review_discards_the_recipe() { + let (mut h, dir) = review("cancel"); + let presets0 = h.app.session.presets.len(); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe_name = "Never saved".into(); + h.settle(SETTLE); + let r = h.request("ui.dialog.cancel", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none()); + assert_eq!((h.app.session.catalog.len(), h.app.session.presets.len(), h.app.session.undo.len()), (0, presets0, undo0)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming the review with a recipe imports the photos with it: each has the values and the +/// Import adjustments step, and the import is still one undo step. +#[test] +fn confirming_with_a_recipe_sets_it_on_the_new_photos() { + let (mut h, dir) = review("confirm"); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), 20.0); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + for p in h.app.session.catalog.photos() { + assert_eq!((p.develop.light.exposure, p.develop.color.vibrance), (0.5, 20.0), "{}", p.file_name); + assert!(p.history.iter().any(|s| s.label == "Import adjustments"), "{}", p.file_name); + } + 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(), 0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming without a recipe adds no Import adjustments step. +#[test] +fn confirming_without_a_recipe_adds_no_adjustment_step() { + let (mut h, dir) = review("plain"); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + assert!(h.app.session.catalog.photos().all(|p| !p.history.iter().any(|s| s.label == "Import adjustments"))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/gaps.md b/docs/gaps.md index 5d01ebf9a2..08cebce09d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -153,6 +153,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-12 | minor | Gap 20 shrinks: Mamiya MEF decodes (`vendor/mef.rs`) and is imported; gap 10 count 240 → 241 | | 2026-10-12 | minor | Gap 20 shrinks: Epson ERF decodes (`vendor/erf.rs`), 3 bodies verified; gap 10 count 237 → 240 | | 2026-10-13 | minor | Gap 28: F6 (filmstrip) and F7 (left panel) are bound, so the entry no longer lists them as missing; hours unchanged | +| 2026-10-13 | minor | Import gains an optional batch-edit recipe (LR-IMP-RECIPE); it is additive and no ranked gap lists it, so no gap closes and the numbers do not move | | 2026-10-20 | patch | Gap 24: extreme brush segments skip the intermediate dabs; the gap stays open | | 2026-10-11 | minor | Gap 10 shrinks: Leica Q3 verified by a recorded check of 38 private DNGs (236 models verified; Leica 14); gap not closed | | 2026-10-12 | minor | Camera-look deep shadows follow the JPEG toe (#1307); camera calibration remains partial | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index bcdaada1cf..99381ec5f5 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -26,7 +26,7 @@ cited here still exists. Formerly docs/parity.md. | Section | ✅ | 🟡 | ⬜ | 🚫 | P0 done | P1 done | |---|---:|---:|---:|---:|---:|---:| -| A. Import (IMP) | 12 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | +| A. Import (IMP) | 13 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | | B. Library management (LIB) | 22 | 2 | 1 | 2 | 9/9 (100%) | 9/9 (100%) | | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | @@ -75,6 +75,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | 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-RECIPE | Batch edits during import | P2 | ✅ | `cmd:library.import` (`recipe`), `cmd:preset.saveRecipe` (registered; `crates/engine/src/tests/import.rs` asserts it), `crates/ui-egui/src/dialogs/import.rs` | an optional Batch edits section in the import review: sliders for everyday adjustments (Light, Vibrance and Saturation, Clarity, Texture and Dehaze, Sharpening, Grain, Vignette) whose values are set on every photo the import adds, after its XMP sidecar, camera default and the chosen preset, as one extra History step (`Import adjustments`) after the preset's own; a photo the library already has (a duplicate, one restored from Recently Deleted, one joined from a browsed folder) is not changed; a summary beside the section counts the adjustments, it does not list them; Save as Preset stores only the settings the recipe names (`cmd:preset.saveRecipe`) so it can be reused from the Preset list; the recipe lives only in the dialog until the import runs, so Cancel changes neither the catalog nor the preset collections. The command takes any plain develop control, not only the ones the dialog offers, and refuses white balance, geometry and crop controls, per-photo controls and unknown ids before anything is imported. Not a second editor: white balance is not offered (a temperature means something else on a raw than on a rendered photo, so the command refuses it too), and neither are crop, masks, curve or point colour; a slider left at its default names nothing, so setting a control to its default for the whole batch is only possible through the command | | 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) | @@ -924,6 +925,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (✅) | | 2026-10-20 | patch | LR-MASK-BRUSH: extreme segments skip intermediate dabs; ordinary spacing and endpoints preserved; status unchanged (🟡) | | 2026-10-12 | minor | LR-META-XMP: bounded complete-APP1 manual JPEG reread, fail-closed sidecar precedence and scoped regression coverage; LR-META-EXIF-FULL: reuse loaded bytes; statuses unchanged | +| 2026-10-13 | minor | LR-IMP-RECIPE added (✅): an optional batch-edit recipe for newly imported photos (`library.import` `recipe`, `preset.saveRecipe`, the Batch edits section of the import review); no existing row changes | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type; no walk behaviour changes; status unchanged (✅) | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type (XMP sidecars are not counted); no walk behaviour changes; status unchanged (✅) | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged |