LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-EXP-BITDEPTH: check bitDepth against the format a path without a known extension gets
Marco Arnulfo302faf547b53
diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rsindex f0c8f0033..ce8a34f0c 100644--- a/crates/engine/src/export.rs+++ b/crates/engine/src/export.rs@@ -840,8 +840,27 @@ impl ExportOptions {/// silent default. `app.export` targets (`id`, `ids`, `path`, `dir`, `preset`, `background`)/// are accepted and left to the caller.pub fn from_params(p: &serde_json::Value) -> crate::Result<Self> {- Self::validate("app.export", p)?;- Ok(Self::from_json(p))+ Self::from_params_or(p, ExportFormat::default())+ }++ /// [`ExportOptions::from_params`] for a caller that writes `fallback` to a `path` naming no+ /// format; the format returned is [`ExportOptions::export_format`], the one written.+ pub fn from_params_or(p: &serde_json::Value, fallback: ExportFormat) -> crate::Result<Self> {+ let format = Self::export_format(p, fallback);+ Self::validate_as("app.export", p, format)?;+ Ok(Self { format, ..Self::from_json(p) })+ }++ /// The format `app.export` writes: `format` (`null`: the default), else the one the extension of+ /// `path` names, else `fallback` for a path that names none (the desktop app writes JPEG there,+ /// the headless backend PNG), else the default.+ pub fn export_format(p: &serde_json::Value, fallback: ExportFormat) -> ExportFormat {+ use serde_json::Value;+ match (p.get("format"), p.get("path").and_then(Value::as_str)) {+ (Some(f), _) => f.as_str().and_then(ExportFormat::parse).unwrap_or_default(),+ (None, Some(path)) => std::path::Path::new(path).extension().and_then(|e| e.to_str()).and_then(ExportFormat::parse).unwrap_or(fallback),+ (None, None) => ExportFormat::default(),+ }}/// Check `app.export` params for `cmd` (the command named in the error): every key must be an@@ -849,6 +868,11 @@ impl ExportOptions {/// kind of thing its key takes, and a `watermark` object must hold only [`WATERMARK_PARAMS`]/// with its sizes in range (issue #183). `null` means "not given", as a dropped key does.pub fn validate(cmd: &str, p: &serde_json::Value) -> crate::Result<()> {+ Self::validate_as(cmd, p, Self::export_format(p, ExportFormat::default()))+ }++ /// [`ExportOptions::validate`] with `bitDepth` checked against `format`, the one exported.+ fn validate_as(cmd: &str, p: &serde_json::Value, format: ExportFormat) -> crate::Result<()> {use serde_json::Value;let bad = |msg: String| crate::cmd::bad(cmd, msg);let Some(obj) = p.as_object() else { return Err(bad("params must be an object".into())) };@@ -956,24 +980,16 @@ impl ExportOptions {_ => return Err(bad(unknown_key("parameter", k, &known))),}}- // issue #1952: a depth the format doesn't have would be written at the format's own depth;- // the format is the one exported: `format`, else the one `path` names, else the default+ // issue #1952: a depth the format doesn't have would be written at the format's own depthif let Some(depth) = obj.get("bitDepth").and_then(whole) {- let format = match (obj.get("format").and_then(Value::as_str), obj.get("path").and_then(Value::as_str)) {- (Some(f), _) => ExportFormat::parse(f),- (None, Some(path)) => std::path::Path::new(path).extension().and_then(|e| e.to_str()).and_then(ExportFormat::parse),- (None, None) => Some(ExportFormat::default()),- };- if let Some(format) = format {- let mut depths: Vec<u8> = Self::bit_depths(format).iter().map(|d| d.0).collect();- if !depths.iter().any(|d| i64::from(*d) == depth) {- depths.sort_unstable();- let mut list: Vec<String> = depths.iter().map(u8::to_string).collect();- let last = list.pop().unwrap_or_default();- let list = if list.is_empty() { last } else { format!("{} or {last}", list.join(", ")) };- let name = serde_json::to_value(format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();- return Err(bad(format!("`bitDepth` must be {list} for {name}")));- }+ let mut depths: Vec<u8> = Self::bit_depths(format).iter().map(|d| d.0).collect();+ if !depths.iter().any(|d| i64::from(*d) == depth) {+ depths.sort_unstable();+ let mut list: Vec<String> = depths.iter().map(u8::to_string).collect();+ let last = list.pop().unwrap_or_default();+ let list = if list.is_empty() { last } else { format!("{} or {last}", list.join(", ")) };+ let name = serde_json::to_value(format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();+ return Err(bad(format!("`bitDepth` must be {list} for {name}")));}}Ok(())@@ -3244,6 +3260,15 @@ mod tests {assert!(err(json!({"path": "/out/a.png", "bitDepth": 32})).contains("for png"));assert!(err(json!({"bitDepth": 16})).contains("for jpeg"));assert!(ExportOptions::from_params(&json!({"path": "/out/a.tif", "bitDepth": 32})).is_ok());+ // a path naming no format, or a `null` format, exports the default too+ assert!(err(json!({"path": "/out/output", "bitDepth": 10})).contains("for jpeg"));+ assert!(err(json!({"path": "/out/output.xyz", "bitDepth": 10})).contains("for jpeg"));+ assert!(err(json!({"format": null, "path": "/out/a.png", "bitDepth": 16})).contains("for jpeg"));+ // or the caller's own format for such a path, which is the one returned+ let png = |p: serde_json::Value| ExportOptions::from_params_or(&p, ExportFormat::Png);+ assert!(png(json!({"path": "/out/output", "bitDepth": 10})).unwrap_err().to_string().contains("for png"));+ assert_eq!(png(json!({"path": "/out/output.xyz", "bitDepth": 16})).unwrap().format, ExportFormat::Png);+ assert_eq!(png(json!({"path": "/out/a.tif", "bitDepth": 32})).unwrap().format, ExportFormat::Tiff);// stored settings (a preset, Export with Previous) lose such a depth instead of failinglet stored = ExportOptions::known_keys_only(&json!({"format": "jpeg", "bitDepth": 16}));assert_eq!(stored.get("bitDepth"), None);diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rsindex 7c9af704d..6b3606ba6 100644--- a/crates/mcp/src/headless.rs+++ b/crates/mcp/src/headless.rs@@ -62,15 +62,12 @@ impl Headless {fn export(&mut self, p: &Value) -> Result<Value, String> {use lightcraft_engine::export::{Destination, ExportFormat, ExportOptions, Resize, prepare_batch, run_batch};let p = &self.session.export_params(p)?;- let mut opts = ExportOptions::from_params(p).map_err(|e| e.to_string())?;+ // PNG for a `path` that names no format; `bitDepth` is checked against the format written+ let mut opts = ExportOptions::from_params_or(p, ExportFormat::Png).map_err(|e| e.to_string())?;if !ExportOptions::has_size_param(p) {opts.resize = Some(Resize::long_edge(3000));}let exact = p.get("path").and_then(Value::as_str);- if let (Some(path), None) = (exact, p.get("format")) {- let ext = Path::new(path).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();- opts.format = ExportFormat::parse(&ext).unwrap_or(ExportFormat::Png);- }let ids: Vec<_> = match p.get("ids").and_then(Value::as_array) {Some(a) => a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect(),// like the desktop app: the selection (in grid order), else the given / active photodiff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rsindex 99193b480..e2e8596f5 100644--- a/crates/mcp/src/tests.rs+++ b/crates/mcp/src/tests.rs@@ -147,6 +147,28 @@ fn export_refuses_unknown_params_and_bad_values() {assert!(e.contains("did you mean `quality`"), "{e}");}+/// Review of #1966: a `path` whose extension names no format exports PNG through the headless+/// backend, so its `bitDepth` is checked against PNG's, not let through to an 8-bit file.+#[test]+fn export_checks_the_depth_of_the_format_a_bare_path_gets() {+ let mut b = Headless::demo();+ let base = std::env::temp_dir().join(format!("lc-mcp-bare-path-depth-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ std::fs::create_dir_all(&base).unwrap();+ for name in ["output", "output.xyz"] {+ let e = b.call("app.export", json!({"path": base.join(name).to_string_lossy(), "longEdge": 32, "bitDepth": 10})).unwrap_err();+ assert!(e.contains("`bitDepth` must be 8 or 16 for png"), "{name}: {e}");+ }+ assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "nothing written");+ // the format such a path gets is still PNG, and 16 bits is one of its depths+ b.call("app.export", json!({"path": base.join("output").to_string_lossy(), "longEdge": 32, "bitDepth": 16})).unwrap();+ let written = std::fs::read_dir(&base).unwrap().next().unwrap().unwrap().path();+ let bytes = std::fs::read(&written).unwrap();+ assert!(bytes.starts_with(b"\x89PNG"), "{written:?} is a PNG");+ assert_eq!(bytes[24], 16, "{written:?} is 16-bit");+ let _ = std::fs::remove_dir_all(&base);+}+/// Every option the `export` tool advertises reaches `app.export` (they were accepted, then dropped).#[test]fn export_tool_forwards_its_advertised_options() {diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 097b13c4d..953874f6a 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -484,11 +484,8 @@ pub fn default_export_dir() -> String {pub fn export_active(app: &mut LightcraftApp, p: &Value) -> Result<Value, String> {use lightcraft_engine::export::{Destination, ExportOptions, export_batch};let p = &app.session.export_params(p)?;- let mut opts = ExportOptions::from_params(p).map_err(|e| e.to_string())?;- if let (Some(path), None) = (p.get("path").and_then(Value::as_str), p.get("format")) {- let ext = path.rsplit_once('.').map_or("", |(_, e)| e);- opts.format = lightcraft_engine::export::ExportFormat::parse(ext).unwrap_or(opts.format);- }+ // the format follows `path` (JPEG when it names none), and `bitDepth` is checked against it+ let opts = ExportOptions::from_params(p).map_err(|e| e.to_string())?;let ids: Vec<_> = match p.get("ids").and_then(Value::as_array) {Some(a) => a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect(),None if !app.session.selection.ids.is_empty() => {diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rsindex 70f128f22..aa387ef2d 100644--- a/crates/ui-egui/src/headless.rs+++ b/crates/ui-egui/src/headless.rs@@ -2196,6 +2196,32 @@ mod tests {assert_eq!(opened(&mut h, json!({"format": "tiff", "bitDepth": 32})).bit_depth, Some(32));}+ /// Review of #1966: a `path` whose extension names no format exports JPEG here, so its+ /// `bitDepth` is checked against JPEG's, not let through to an 8-bit file.+ #[test]+ fn export_checks_the_depth_of_the_format_a_bare_path_gets() {+ let mut h = demo([1200.0, 900.0]);+ let t = Duration::from_secs(10);+ let out = std::env::temp_dir().join(format!("lc-bare-path-depth-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&out);+ std::fs::create_dir_all(&out).unwrap();+ h.app.services.write = Some(Box::new(|p: &str, bytes: &[u8]| lightcraft_engine::export::write_file(p, bytes)));+ for name in ["output", "output.xyz"] {+ let p = json!({"path": out.join(name).to_string_lossy(), "longEdge": 32, "bitDepth": 10});+ let r = h.request("engine.execute", json!({"command": "app.export", "params": p}), t);+ assert_eq!(r["ok"], false, "{name}: {r}");+ assert!(r["error"].as_str().unwrap().contains("`bitDepth` must be 8 for jpeg"), "{name}: {r}");+ }+ assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written");+ // the format such a path gets is still JPEG+ let p = json!({"path": out.join("output").to_string_lossy(), "longEdge": 32, "bitDepth": 8});+ let r = h.request("engine.execute", json!({"command": "app.export", "params": p}), t);+ assert_eq!(r["ok"], true, "{r}");+ let written = std::fs::read_dir(&out).unwrap().next().unwrap().unwrap().path();+ assert!(std::fs::read(&written).unwrap().starts_with(&[0xFF, 0xD8]), "{written:?} is a JPEG");+ let _ = std::fs::remove_dir_all(&out);+ }+#[test]fn export_dialog_runs_in_the_background() {let mut h = demo([1200.0, 900.0]);