Skip to content

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

M10.2: MCP/CLI export shares the engine encoder (all formats, batch, size limit, sharpening)

Brandon Thomas908713c39b66
diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs
index b36930bce..0ad3f7f78 100644
--- a/crates/mcp/src/headless.rs
+++ b/crates/mcp/src/headless.rs
@@ -46,21 +46,43 @@ impl Headless {
Ok(self.session.render_now(id, size, size)?.image)
}
- /// The UI command `app.export`, emulated: render and write PNG/JPEG/TIFF/WebP by extension.
+ /// The UI command `app.export`, emulated with the same parameters as the desktop app
+ /// (see `lightcraft_engine::export::ExportOptions::from_json`, plus `ids`, `dir`, `path`).
+ /// With `path` and no `format`, the format follows the path's extension.
fn export(&mut self, p: &Value) -> Result<Value, String> {
- let id = self.photo_or_active(p)?;
- let img = self.render(&json!({"id": id.0, "size": p.get("longEdge").and_then(Value::as_u64).unwrap_or(3000)}), 3000)?;
- let path = match p.get("path").and_then(Value::as_str) {
- Some(path) => path.to_string(),
- None => {
- let name = self.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_else(|| "export".into());
- let stem = name.rsplit_once('.').map(|(a, _)| a.to_string()).unwrap_or(name);
- format!("{stem}-lightcraft.png")
- }
+ use lightcraft_engine::export::{ExportFormat, ExportOptions, export_photo};
+ let mut opts = ExportOptions::from_json(p);
+ if p.get("longEdge").is_none() {
+ opts.long_edge = Some(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(),
+ None => vec![self.photo_or_active(p)?],
};
- let quality = p.get("quality").and_then(Value::as_u64).unwrap_or(90).clamp(1, 100) as u8;
- write_image(Path::new(&path), &img, quality)?;
- Ok(json!({"path": path, "width": img.width, "height": img.height}))
+ let dir = p.get("dir").and_then(Value::as_str).unwrap_or("");
+ let mut files = Vec::new();
+ for (i, id) in ids.iter().enumerate() {
+ let e = export_photo(&mut self.session, *id, &opts, i + 1)?;
+ let path = match exact.filter(|_| ids.len() == 1) {
+ Some(path) => path.to_string(),
+ None if dir.is_empty() => e.file_name.clone(),
+ None => format!("{dir}/{}", e.file_name),
+ };
+ if let Some(parent) = Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) {
+ std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
+ }
+ std::fs::write(&path, &e.bytes).map_err(|err| format!("{path}: {err}"))?;
+ files.push(json!({"path": path, "width": e.width, "height": e.height, "bytes": e.bytes.len()}));
+ }
+ // Single-photo exports also report path/width/height at the top level (back-compat).
+ let mut out = files.first().cloned().unwrap_or_else(|| json!({}));
+ out["files"] = json!(files);
+ Ok(out)
}
}
@@ -140,18 +162,12 @@ pub fn expand_paths(paths: &[String]) -> Vec<String> {
out
}
-/// Encode by extension: `.png` (default), `.jpg`/`.jpeg` (quality), `.tif`/`.tiff`, `.webp` (lossless).
+/// Encode by extension: `.png` (default), `.jpg`/`.jpeg` (quality), `.tif`/`.tiff`, `.webp` (lossless),
+/// `.avif` — via the shared export encoder (embeds an sRGB profile).
pub fn encode_image(ext: &str, img: &Rgba8, quality: u8) -> Result<Vec<u8>, String> {
- use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, TiffCompression};
- let e = EncodeImage::rgba8(img);
- let m = EncodeMeta::default();
- match ext.to_ascii_lowercase().as_str() {
- "jpg" | "jpeg" => lightcraft_codecs::encode_jpeg(&e, quality, ChromaSubsampling::S444, &m),
- "tif" | "tiff" => lightcraft_codecs::encode_tiff(&e, TiffCompression::Deflate, &m),
- "webp" => lightcraft_codecs::encode_webp_lossless(&e, &m),
- _ => lightcraft_codecs::encode_png(&e, &m),
- }
- .map_err(|e| e.to_string())
+ use lightcraft_engine::export::{ExportFormat, ExportOptions};
+ let format = ExportFormat::parse(ext).unwrap_or(ExportFormat::Png);
+ lightcraft_engine::export::encode_image(img, &ExportOptions { format, quality: quality.clamp(1, 100), ..Default::default() })
}
/// Encode by the path's extension and write the file.
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index e1e54874e..050ced35d 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -173,9 +173,21 @@ pub fn helper_tools(has_ui: bool) -> Vec<Value> {
tool(
"export",
"Export photo",
- "Render a photo at full quality and write it to `path` (.png, .jpg, .tif or .webp; the desktop app writes PNG).",
- json!({"id": photo_id, "path": {"type": "string"}, "longEdge": {"type": "integer", "description": "Default 3000"}, "quality": {"type": "integer", "description": "JPEG quality 1..100"}}),
- &["path"],
+ "Render and write photos. Give `path` (one photo; format from the extension unless `format` is set) or `dir` (batch, file names from `naming`).",
+ json!({
+ "id": photo_id,
+ "ids": {"type": "array", "items": {"type": "integer"}, "description": "Photos to export (default: the given/active photo)"},
+ "path": {"type": "string"},
+ "dir": {"type": "string"},
+ "format": {"type": "string", "enum": ["jpeg", "png", "tiff", "webp", "avif"]},
+ "longEdge": {"type": "integer", "description": "Default 3000; 0 = full size"},
+ "quality": {"type": "integer", "description": "JPEG/AVIF quality 1..100"},
+ "limitKb": {"type": "integer", "description": "JPEG: largest quality that fits this many KB"},
+ "sharpen": {"type": "string", "enum": ["none", "screen", "matte", "glossy"]},
+ "sharpenAmount": {"type": "string", "enum": ["low", "standard", "high"]},
+ "naming": {"type": "string", "description": "e.g. {name}-{seq}"}
+ }),
+ &[],
),
];
if has_ui {
@@ -499,7 +511,13 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
}
})),
"render_photo" => render_photo(b, args),
- "export" => ToolResult::from(activate(b, args).and_then(|_| exec(b, "app.export", obj(args, &["path", "longEdge", "quality"])))),
+ "export" => ToolResult::from(activate(b, args).and_then(|_| {
+ exec(
+ b,
+ "app.export",
+ obj(args, &["ids", "path", "dir", "format", "longEdge", "quality", "limitKb", "sharpen", "sharpenAmount", "naming"]),
+ )
+ })),
"screenshot" => screenshot(b, args),
"inspect_ui" => ToolResult::from(b.call("ui.inspect", json!({}))),
"set_ui" => ToolResult::from(b.call("ui.set", args.get("state").cloned().unwrap_or(json!({})))),
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 6e10b8a04..4a7fad6a2 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -299,7 +299,11 @@ pub fn default_export_dir() -> String {
/// (exact output file, single photo), `ids` (default: the selection, else the active photo).
pub fn export_active(app: &mut LightcraftApp, p: &Value) -> Result<Value, String> {
use lightcraft_engine::export::{ExportOptions, export_photo};
- let opts = ExportOptions::from_json(p);
+ let mut opts = ExportOptions::from_json(p);
+ 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);
+ }
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() => {