Files
lightcraft/crates/engine/src/cmd.rs
T
68b464011f Import review: an optional batch-edit recipe for newly imported photos (#2940)
* Import: an optional batch-edit recipe for newly imported photos

library.import takes a recipe, a list of develop control ids and values.
Each control is set, clamped to its range like a slider's, on every photo
the import actually adds, after the XMP sidecar, the camera default and
the chosen preset, as one more History step named Import adjustments.
Photos that are skipped as duplicates, restored from Recently Deleted or
joined from a browsed folder are not touched, as the preset and keywords
never touch them.

A recipe names plain adjustments only. White balance is refused, because
a temperature means Kelvin on a raw with colour matrices and a shift from
the as-shot white on a rendered photo, so one number cannot name the same
look for a whole batch, and the as-shot white balance of a raw is never
touched. Geometry and crop controls are refused, because the slider
refits the crop around a new angle and a batch write cannot. Per-photo
controls such as pointColor.0.hueShift are refused, because a write to a
photo without that instance is dropped. The rule is on the control's
spec (a control of the shared list, outside the Geometry section, not
white balance, and one that set accepts), so new controls follow it. An
id named twice counts once, the last value winning, and a list longer
than the control list is refused. ImportJob::new checks a recipe built in
code the same way, before any file is read or placed.

preset.saveRecipe saves a recipe as a user preset that stores only the
settings the recipe names, including a control the recipe sets to its
default, and refuses a recipe that stores nothing. The preset gets its id
the way imported presets do (user.<group>-<name>, then -2, -3 ...), so no
two presets share one: an id from the list length repeats once a preset
is deleted, and the first preset with an id is the one that gets applied.
A name or group over 100 characters is refused, and saving the same
recipe under the same name and group again returns the preset that
exists.

* Import recipe: tests

Cover a recipe on import (the values, the Import adjustments step, a
render, one undo step), the refusals (unknown ids, malformed items,
per-photo controls, geometry and crop, white balance, too many entries,
by the command and by ImportJob::new), clamping and a repeated id, a
raw's as-shot white balance staying as imported, a saved recipe preset
giving the same settings as the recipe (including a reset to a default),
the photos the recipe leaves alone (duplicates by path and by content, a
restored photo, a browsed photo that joins; a photo imported afresh gets
it), preset ids staying distinct after a delete and surviving a reopened
library, and both commands being listed with their parameters.

* Import review: a Batch edits section

The import review gets a collapsible Batch edits section: sliders for
the everyday adjustments (exposure, contrast, highlights, shadows,
whites, blacks, vibrance, saturation, clarity, texture, dehaze,
sharpening, grain, vignette). The controls moved off their default go to
library.import as its recipe, only when there are any, and a summary
beside the section counts them. The recipe stays in the dialog until the
import runs, so cancelling changes neither the catalog nor the presets.

Save as Preset, which needs a name and a recipe, saves the recipe with
preset.saveRecipe. It leaves the review's own preset choice as it is, so
a preset picked for the import is never replaced by the saved one. The
name goes in a TextField, as new text boxes do.

The summary line is a new tr_format message, added with a translation to
every formats catalog; the other new messages are plain and show in
English until a catalog translates them.

* Import review recipe: tests

Unit tests hold the dialog to the engine: every control it offers is one
a recipe may name, a slider moved back to its default leaves the recipe,
and start passes a recipe to library.import only when the dialog has one.
Driving the real review, Save as Preset saves nothing without a name or
without a recipe and with both saves exactly the recipe (leaving the
review's preset choice and the catalog alone), cancelling the review
discards the recipe, and confirming imports the photos with it as one
undo step, or without an Import adjustments step when there is none.

* Import recipe: tests for the disabled Save button and MCP reachability

The disabled state of Save as Preset was not pinned: the engine refuses
a nameless or empty recipe anyway, so the preset count stayed the same
even with the button always on. The test now also expects no error
toast, which only an enabled button that asked the engine would raise.

A new MCP end-to-end test drives both commands through the public
tools: list_commands documents them, run_command takes library.import
with a recipe (a recipe naming white balance is a tool error that
imports nothing), get_develop shows the values on the imported photo,
and the generated cmd_preset_saveRecipe tool saves a recipe.

* Import recipe: follow main's register(ui) and Id::unique after the rebase

Upstream main changed widgets::register to take &egui::Ui (every other
call site passes ui) and deprecated egui::Id::new in favour of Id::unique
(same hash, so the stored open/closed state is unchanged). Adapt the
batch-edit recipe section so lightcraft-ui-egui compiles again.

* docs: parity row LR-IMP-RECIPE for batch edits during import

* Keep HDR resets when a recipe is saved as a preset

A recipe that resets an HDR control to its default was dropped when it was saved as a preset, because the HDR subtree is left out of the settings JSON while it is the default. The recipe's settings are now compared with the HDR subtree always present, so the reset is stored alone and next to other adjustments. Round-trip tests apply the saved preset to settings with a non-default headroom.

* Address review findings

* Address review findings

* Import review: the imports the merge left in body.rs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 01:23:04 +01:00

364 lines
15 KiB
Rust

//! The command registry.
//!
//! Command ids group by area: `library.*` (view/selection), `photo.*` (rating, flags, rotate,
//! delete), `album.*`, `develop.*` (settings), `crop.*`, `mask.*`, `preset.*`, `version.*`,
//! `edit.*` (undo/redo), and queries (`catalog.query`, `photo.inspect`, `develop.get`…).
mod activity;
mod before;
pub(crate) mod browse;
mod color;
pub(crate) mod convert;
mod cull;
pub mod curves;
pub mod dcp_profiles;
pub(crate) mod denoise;
mod develop;
mod edit;
mod export;
pub(crate) mod face_detect;
mod face_models;
mod face_recognize;
pub mod filters;
mod focus;
pub mod geocode;
pub mod keywords;
pub mod lens_refresh;
pub mod library;
pub mod lut_profiles;
pub mod manage;
pub mod mask_effect_files;
pub mod mask_effects;
mod masks;
mod merge;
pub mod metadata;
pub mod missing;
mod organize;
mod prefs;
mod preset_files;
pub mod previews;
mod print;
mod query;
pub mod recheck;
pub mod reload;
pub mod similar;
mod slideshow;
mod sync;
mod xmp;
use serde::Serialize;
use serde_json::Value;
use crate::{EngineError, Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement (`["Photo", "Rotate"]`); empty = not in menus.
pub menu: &'static [&'static str],
/// Default shortcut (`Cmd+Shift+C`), mapped per platform by the UI.
pub shortcut: Option<&'static str>,
/// Human/agent-readable parameter description.
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
/// Record in the journal (false for queries).
pub journal: bool,
/// `enabled` judges the selection (menus, shortcuts); a call that names its photos (`ids` /
/// `id`, see [`names_photos`]) skips it, and the command validates those photos itself.
/// Off unless a command opts in (`CommandSpec { explicit_targets: true, ..cmd!(…) }`).
pub explicit_targets: bool,
}
#[derive(Clone, Debug, Serialize)]
pub struct CommandInfo {
pub id: &'static str,
pub label: &'static str,
pub menu: Vec<&'static str>,
pub shortcut: Option<&'static str>,
pub params: &'static str,
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_reason: Option<String>,
}
impl CommandSpec {
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
CommandInfo {
id: self.id,
label: self.label,
menu: self.menu.to_vec(),
shortcut: self.shortcut,
params: self.params,
enabled: e.is_ok(),
disabled_reason: e.err(),
}
}
}
// ---------- enablement predicates
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub fn has_active(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no photo selected".into())
}
pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
if s.selection.ids.is_empty() && s.selection.active.is_none() { Err("no photos selected".into()) } else { Ok(()) }
}
/// Albums hold library photos: a selection of only browsed (Local) photos has nothing an album
/// can take (issue #684; Add to My Photos first).
pub fn has_library_selection(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
if s.selected().iter().any(|id| s.catalog.photo(*id).is_none_or(|p| !p.local)) { Ok(()) } else { Err(LOCAL_ONLY.into()) }
}
/// Why an album command refused a Local-only selection.
pub const LOCAL_ONLY: &str = "only Local photos: albums hold library photos (Add to My Photos first)";
pub fn can_undo(s: &Session) -> std::result::Result<(), String> {
if s.undo.is_empty() { Err("nothing to undo".into()) } else { Ok(()) }
}
pub fn can_redo(s: &Session) -> std::result::Result<(), String> {
if s.redo.is_empty() { Err("nothing to redo".into()) } else { Ok(()) }
}
pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
if s.clipboard.is_none() { Err("no settings copied".into()) } else { Ok(()) }
}
macro_rules! cmd {
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, explicit_targets: false }
};
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, explicit_targets: false }
};
}
pub(crate) use cmd;
pub fn command_specs() -> &'static [CommandSpec] {
static SPECS: std::sync::OnceLock<Vec<CommandSpec>> = std::sync::OnceLock::new();
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(edit::specs());
v.extend(library::specs());
v.extend(develop::specs());
v.extend(color::specs());
v.extend(curves::specs());
v.extend(masks::specs());
v.extend(organize::specs());
v.extend(keywords::specs());
v.extend(manage::specs());
v.extend(previews::specs());
v.extend(lut_profiles::specs());
v.extend(dcp_profiles::specs());
v.extend(mask_effects::specs());
v.extend(cull::specs());
v.extend(convert::specs());
v.extend(convert::edit_specs());
v.extend(merge::specs());
v.extend(query::specs());
v.extend(xmp::specs());
v.extend(preset_files::specs());
v.extend(prefs::specs());
v.extend(slideshow::specs());
v.extend(export::specs());
v.extend(print::specs());
v.extend(before::specs());
v.extend(browse::specs());
v.extend(missing::specs());
v.extend(recheck::specs());
v.extend(lens_refresh::specs());
v.extend(sync::specs());
v.extend(metadata::specs());
v.extend(geocode::specs());
v.extend(filters::specs());
v.extend(denoise::specs());
v.extend(face_models::specs());
v.extend(face_detect::specs());
v.extend(face_recognize::specs());
v.extend(focus::specs());
v.extend(activity::specs());
v
})
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
// ---------- param helpers
/// The call names its target photos (`ids` or `id`, not null) instead of using the selection.
pub(crate) fn names_photos(p: &Value) -> bool {
["ids", "id"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null()))
}
/// The call names its target photos in `ids`, whatever else it carries in `id` (`album.addPhotos`'s `id` is the album).
pub(crate) fn names_photo_ids(p: &Value) -> bool {
p.get("ids").is_some_and(|v| !v.is_null())
}
/// For a command that opts into `explicit_targets` but whose `id` isn't a photo: [`Session::execute`] skipped the
/// selection check because the call carries an `id`, so the command makes it itself unless `ids` names the photos.
pub(crate) fn enabled_unless_ids(s: &Session, p: &Value, id: &str, enabled: Enabled) -> Result<()> {
if names_photo_ids(p) {
return Ok(());
}
enabled(s).map_err(|why| EngineError::Disabled(id.to_string(), why))
}
/// The photos `ids` names: `None` when it is missing or null (the command then falls back to the
/// selection, or its own default), else every entry as a photo id. An `ids` that isn't a list of
/// whole numbers is an error, never `None`: falling back would act on the selection instead of
/// the photos the call meant (`{"ids": 3}`, `{"ids": ["3"]}`).
pub(crate) fn photo_ids(p: &Value, cmd: &str) -> Result<Option<Vec<lightcraft_catalog::PhotoId>>> {
match p.get("ids") {
None | Some(Value::Null) => Ok(None),
Some(Value::Array(a)) => a
.iter()
.map(|v| v.as_u64().map(lightcraft_catalog::PhotoId).ok_or_else(|| bad(cmd, "`ids` must be photo ids (whole numbers)")))
.collect::<Result<Vec<_>>>()
.map(Some),
Some(_) => Err(bad(cmd, "`ids` must be a list of photo ids")),
}
}
/// The photo `id` names: `None` when it is missing or null (the command then uses the active
/// photo), else that id. An `id` that isn't a whole number is an error, never `None`: falling back
/// would act on the active photo instead of the one the call meant (`{"id": "5"}`).
pub(crate) fn photo_id(p: &Value, cmd: &str) -> Result<Option<lightcraft_catalog::PhotoId>> {
match p.get("id") {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(|n| Some(lightcraft_catalog::PhotoId(n))).ok_or_else(|| bad(cmd, "`id` must be a photo id (a whole number)")),
}
}
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
}
/// A non-negative whole number that fits `usize`. Keep integer JSON exact; accept integral
/// floating-point values for compatibility, without truncating or saturating their conversion.
pub(crate) fn index_req(p: &Value, key: &str, cmd: &str) -> Result<usize> {
let invalid = || bad(cmd, format!("`{key}` must be a non-negative integer"));
if let Some(i) = p.get(key).and_then(Value::as_u64) {
return usize::try_from(i).map_err(|_| invalid());
}
let i = f64_req(p, key, cmd)?;
// The exclusive bound is exactly representable, unlike usize::MAX on 64-bit targets.
let upper_bound = 2.0_f64.powi(usize::BITS as i32);
if !(i.is_finite() && i >= 0.0 && i.fract() == 0.0 && i < upper_bound) {
return Err(invalid());
}
Ok(i as usize)
}
pub(crate) fn f64_or(p: &Value, key: &str, d: f64) -> f64 {
p.get(key).and_then(Value::as_f64).unwrap_or(d)
}
pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
p.get(key).and_then(Value::as_str)
}
pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool {
p.get(key).and_then(Value::as_bool).unwrap_or(d)
}
pub(crate) fn ok() -> Result<Value> {
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<Vec<(String, f64)>> {
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<lightcraft_geom::Point> {
let a = p.get(key)?.as_array()?;
Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::index_req;
#[test]
fn command_indices_preserve_integer_precision_and_check_usize_bounds() {
for i in [0, 1, usize::MAX] {
assert_eq!(index_req(&json!({"index": i}), "index", "test").unwrap(), i);
}
#[cfg(target_pointer_width = "64")]
{
let i = 9_007_199_254_740_993usize;
assert_eq!(index_req(&json!({"index": i}), "index", "test").unwrap(), i, "integer JSON must not round through f64");
}
let upper_bound = 2.0_f64.powi(usize::BITS as i32);
assert!(index_req(&json!({"index": upper_bound}), "index", "test").is_err(), "2^usize::BITS must not saturate");
#[cfg(target_pointer_width = "32")]
{
assert!(index_req(&json!({"index": u64::from(u32::MAX) + 1}), "index", "test").is_err());
assert_eq!(index_req(&json!({"index": f64::from(u32::MAX)}), "index", "test").unwrap(), usize::MAX);
}
}
}