From c10673254be785d132ca00eaf3c892da2b4774dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 05:58:12 +0100 Subject: [PATCH 01/12] WIP: Artboards to Files: reference file type list (#13635) From ff60e13c5038fb7a68af6b2314fbbeca5d0dca3d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 06:19:27 +0100 Subject: [PATCH 02/12] Artboards to Files: the File Type list matches the reference application (#13635) The dialog's list is now File Type: BMP, JPEG, PDF, PSD, Targa, TIFF, PNG-8, PNG-24, with PSD chosen on open. The command learns png8 (indexed PNG), png24 (truecolour PNG), targa and pdf (one multi-page .pdf, bottom artboard first, pages at 72 ppi, through Artboards to PDF's writer). Scripts still default to png; Layer Comps to Files keeps its list. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 106 ++++++++++--- .../src/cmd/artboard_cmds/file_types_tests.rs | 145 ++++++++++++++++++ .../src/artboards_to_files_types_tests.rs | 98 ++++++++++++ crates/ui-egui/src/export_quality_tests.rs | 2 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds/dialogs.rs | 20 ++- 6 files changed, 346 insertions(+), 27 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/file_types_tests.rs create mode 100644 crates/ui-egui/src/artboards_to_files_types_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..810a102488 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -675,7 +675,30 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec { } } -/// File › Export › Artboards to Files: `__.` per board. +/// What an Artboards to Files `format` writes (the dialog's File Type list). +enum FileType { + /// One file per board through the format's encoder, with this extension. + Save(String), + /// One indexed (palette) PNG per board, as PNG-8. + Png8, + /// One multi-page PDF, a page per board, bottom artboard first. + Pdf, +} + +impl FileType { + fn of(format: &str) -> Self { + match format { + "png8" | "png-8" => FileType::Png8, + "png24" | "png-24" => FileType::Save("png".into()), + "targa" => FileType::Save("tga".into()), + "pdf" => FileType::Pdf, + ext => FileType::Save(ext.into()), + } + } +} + +/// File › Export › Artboards to Files: `__.` per board, +/// or for PDF one `.pdf`. fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); @@ -684,20 +707,69 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); - let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { - // Names may be identical, or collide after sanitizing or filesystem case folding. - let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; - let path = join(&dir, &format!("{name}.{format}")); - save_doc(&one, &path, save)?; - files.push(path); - } - if files.is_empty() { + let boards = chosen_documents(&doc, p)?; + if boards.is_empty() { return Err(bad(cmd, "no matching artboards")); } + let ext = match FileType::of(&format) { + FileType::Pdf => { + // The reference application's Multi-Page Document: the bottom artboard is page 1, and + // each page is the board's pixel size at 72 ppi. + let mut pages = Vec::new(); + for one in boards.iter().rev() { + pages.push((one.size.width, one.size.height, 72.0, jpeg_page(one, save.quality.or(Some(10.0)))?)); + } + let name = if prefix.is_empty() { stem(&doc.name) } else { prefix }; + let path = join(&dir, &format!("{}.pdf", sanitize(&name))); + write_file(&path, &raster_pdf(&pages))?; + return Ok(json!({"files": [path]})); + } + FileType::Png8 => None, + FileType::Save(ext) => Some(ext), + }; + let mut files = Vec::new(); + for (i, one) in boards.into_iter().enumerate() { + // Names may be identical, or collide after sanitizing or filesystem case folding. + let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; + let path = join(&dir, &format!("{name}.{}", ext.as_deref().unwrap_or("png"))); + match &ext { + Some(_) => { + save_doc(&one, &path, save)?; + } + None => write_file(&path, &png8(&one)?)?, + } + files.push(path); + } Ok(json!({"files": files})) } +/// `one` as an indexed PNG: Generate Assets' PNG-8 (selective palette, no dither, transparency kept). +fn png8(one: &Document) -> Result> { + use crate::web_cmds::{WebFormat, WebMetadata, WebSettings, optimize, web_document}; + let st = WebSettings { + format: WebFormat::Png8, + dither: photocraft_algo::quantize::Dither::None, + matte: None, + metadata: WebMetadata::None, + ..WebSettings::default() + }; + let (wdoc, _, _) = web_document(one, &json!({}), &st)?; + let buf = photocraft_compose::flatten(&wdoc); + Ok(optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?.bytes) +} + +/// `one` flattened over white as a JPEG, for a PDF page. +fn jpeg_page(one: &Document, quality: Option) -> Result> { + let buf = photocraft_compose::flatten(one).over_background([1.0, 1.0, 1.0]); + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); + let mut surf = Surface::new(fmt); + let vals: Vec = buf.px.iter().flat_map(|px| photocraft_raster::from_rgba(&fmt, *px)).collect(); + surf.write_region(one.bounds(), &vals); + flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); + Ok(encode(&flat, "page.jpg", quality)?.0) +} + /// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). /// Pages are sized so the image prints at its resolution. pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { @@ -753,14 +825,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let quality = f64_param(p, "quality").or(Some(10.0)); let mut pages = Vec::new(); for one in chosen_documents(&doc, p)? { - let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); - let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); - let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); - let mut surf = Surface::new(fmt); - let vals: Vec = buf.px.iter().flat_map(|px| photocraft_raster::from_rgba(&fmt, *px)).collect(); - surf.write_region(one.bounds(), &vals); - flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); - let (jpeg, _) = encode(&flat, "page.jpg", quality)?; + let jpeg = jpeg_page(&one, quality)?; pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg)); } if pages.is_empty() { @@ -829,7 +894,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, + r##"{"dir":folder,"format":"png|png24|png8|jpg|bmp|tga|tiff|psd|pdf|…"="png" (png24 = truecolour .png, png8 = indexed .png, tga = Targa; pdf = one multi-page .pdf, bottom artboard first, pages at 72 ppi),"prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, export_artboards, artboards_to_files ), @@ -844,6 +909,9 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +#[path = "artboard_cmds/file_types_tests.rs"] +mod file_types_tests; #[cfg(test)] #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; diff --git a/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs new file mode 100644 index 0000000000..9788e98d33 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs @@ -0,0 +1,145 @@ +//! Artboards to Files writes each of the File Type list's types (#13635): PNG-8 an indexed +//! PNG, PNG-24 a truecolour one, Targa a `.tga`, PDF one multi-page file with the bottom +//! artboard first and each page the board's pixel size at 72 ppi. +use super::*; + +/// The issue's test document: 800 x 400, transparent, Red Board 200 x 150 at the bottom of the +/// Layers panel, then Blue Board 200 x 200, then an empty transparent board on top. 300 ppi, so +/// a page sized from the document resolution would not be 72 ppi. +fn boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "name": "abfiles-test", "background": "transparent"})).unwrap(); + for (name, rect, bg) in [ + ("Red Board", [0, 0, 200, 150], json!({"background": "custom", "color": "#ff0000"})), + ("Blue Board", [300, 0, 200, 200], json!({"background": "custom", "color": "#0000ff"})), + ("Empty Board", [600, 0, 100, 100], json!({"background": "transparent"})), + ] { + let mut p = json!({"rect": rect, "name": name}); + p.as_object_mut().unwrap().extend(bg.as_object().unwrap().clone()); + s.execute("layer.new.artboard", p).unwrap(); + } + s.edit("ppi", |doc, _| { + doc.resolution_dpi = 300.0; + Ok(()) + }) + .unwrap(); + s +} + +fn out_dir(tag: &str) -> String { + let dir = std::env::temp_dir().join(format!("photocraft-13635-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.to_string_lossy().into_owned() +} + +fn export(s: &mut Session, dir: &str, format: &str) -> Vec { + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})).unwrap(); + r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() +} + +/// The PNG IHDR colour type: 2 truecolour, 3 indexed, 6 truecolour with alpha. +fn png_color_type(path: &str) -> u8 { + let bytes = std::fs::read(path).unwrap(); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "{path} is not a PNG"); + assert_eq!(&bytes[12..16], b"IHDR"); + bytes[25] +} + +fn size_of(path: &str, ext: &str) -> (u32, u32) { + let d = photocraft_io::import(&format!("x.{ext}"), &std::fs::read(path).unwrap()).unwrap().document; + (d.size.width, d.size.height) +} + +#[test] +fn png8_writes_indexed_pngs() { + let mut s = boards(); + let dir = out_dir("png8"); + let files = export(&mut s, &dir, "png8"); + assert_eq!(files.len(), 3); + for f in &files { + assert!(f.ends_with(".png"), "{f}"); + assert_eq!(png_color_type(f), 3, "{f} is not indexed"); + } + assert!(files[2].ends_with("abfiles-test_0002_Red Board.png"), "{files:?}"); + assert_eq!(size_of(&files[2], "png"), (200, 150)); + // Red stays red through the palette. + let red = photocraft_io::import("x.png", &std::fs::read(&files[2]).unwrap()).unwrap().document; + let px = photocraft_compose::flatten(&red).px.clone(); + assert!(px[0][0] > 0.99 && px[0][1] < 0.01 && px[0][2] < 0.01, "{:?}", px[0]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn png24_writes_truecolour_pngs_with_alpha_where_transparent() { + let mut s = boards(); + let dir = out_dir("png24"); + let files = export(&mut s, &dir, "png24"); + assert_eq!(files.len(), 3); + for f in &files { + assert!(f.ends_with(".png"), "{f}"); + assert!(matches!(png_color_type(f), 2 | 6), "{f} is not truecolour"); + } + // The empty board is transparent: the file keeps its alpha. + assert!(files[0].ends_with("abfiles-test_0000_Empty Board.png"), "{files:?}"); + assert_eq!(png_color_type(&files[0]), 6); + assert_eq!(size_of(&files[1], "png"), (200, 200)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn targa_writes_tga_files() { + let mut s = boards(); + let dir = out_dir("tga"); + for format in ["tga", "targa"] { + let files = export(&mut s, &dir, format); + assert_eq!(files.len(), 3); + assert!(files.iter().all(|f| f.ends_with(".tga")), "{files:?}"); + assert_eq!(size_of(&files[2], "tga"), (200, 150)); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn pdf_writes_one_multi_page_file_bottom_artboard_first_at_72_ppi() { + let mut s = boards(); + let dir = out_dir("pdf"); + let files = export(&mut s, &dir, "pdf"); + assert_eq!(files, vec![join(&dir, "abfiles-test.pdf")]); + let entries: Vec<_> = std::fs::read_dir(&dir).unwrap().collect(); + assert_eq!(entries.len(), 1, "one file, not one per board"); + let bytes = std::fs::read(&files[0]).unwrap(); + assert!(bytes.starts_with(b"%PDF-")); + let text = String::from_utf8_lossy(&bytes); + assert_eq!(text.matches("/Type /Page ").count(), 3); + assert_eq!(text.matches("/DCTDecode").count(), 3); + // Page order: Red Board (bottom of the Layers panel), Blue Board, the empty board. + let boxes: Vec<&str> = text.match_indices("/MediaBox [").map(|(i, _)| &text[i + 11..i + 11 + text[i + 11..].find(']').unwrap()]).collect(); + assert_eq!(boxes, vec!["0 0 200.000 150.000", "0 0 200.000 200.000", "0 0 100.000 100.000"]); + // A prefix names the file. + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": "pdf", "prefix": "pre_"})).unwrap(); + assert_eq!(r["files"], json!([join(&dir, "pre_.pdf")])); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn scripts_still_default_to_png() { + let mut s = boards(); + let dir = out_dir("default"); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir})).unwrap(); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(files.len(), 3); + assert!(files.iter().all(|f| f.ends_with(".png")), "{files:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unknown_format_is_an_error_and_writes_nothing() { + let mut s = boards(); + let dir = out_dir("unknown"); + for format in ["xyz", "png9", ""] { + assert!(s.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})).is_err(), "{format}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/artboards_to_files_types_tests.rs b/crates/ui-egui/src/artboards_to_files_types_tests.rs new file mode 100644 index 0000000000..7b411641db --- /dev/null +++ b/crates/ui-egui/src/artboards_to_files_types_tests.rs @@ -0,0 +1,98 @@ +//! #13635: File › Export › Artboards to Files has the reference application's File Type list: +//! BMP, JPEG, PDF, PSD, Targa, TIFF, PNG-8, PNG-24 in that order, PSD chosen when it opens. +//! Layer Comps to Files keeps its own list. +use crate::PhotocraftApp; +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const NAMES: [&str; 8] = ["BMP", "JPEG", "PDF", "PSD", "Targa", "TIFF", "PNG-8", "PNG-24"]; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 200, "background": "transparent"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 100, 50], "name": "Red Board", "background": "custom", "color": "#ff0000"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [200, 0, 80, 80], "name": "Blue Board", "background": "custom", "color": "#0000ff"})).unwrap(); + app.run("layerComp.new", json!({"name": "Comp"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, id: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, id, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + dialog +} + +#[test] +fn file_type_list_is_the_reference_list_with_psd_chosen() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let fields = h.state_mut().ui.dialog_mut(dialog).unwrap().fields.clone(); + assert_eq!(fields["format"], json!("psd"), "PSD on first open"); + assert_eq!(fields["__choices"]["format"], json!(["bmp", "jpg", "pdf", "psd", "tga", "tiff", "png8", "png24"])); + // The row reads "File Type:" and the closed dropdown shows PSD. + let combo = h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("File Type:")).expect("a File Type: dropdown"); + assert_eq!(combo.accesskit_node().value().as_deref(), Some("PSD")); + let at = combo.rect().center(); + h.hover_at(at); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(2); + } + h.run_steps(2); + // Opened, the list shows the eight names top to bottom in the reference order. + let ys: Vec = NAMES + .iter() + .map(|name| { + let tops: Vec = h.query_all_by_label(name).map(|n| n.rect().min.y).collect(); + assert!(!tops.is_empty(), "the list shows {name}"); + tops.into_iter().fold(f32::MIN, f32::max) + }) + .collect(); + assert!(ys.windows(2).all(|w| w[0] < w[1]), "{NAMES:?} at {ys:?}"); +} + +#[test] +fn ok_with_png8_writes_indexed_pngs_and_pdf_one_file() { + let mut h = harness(); + let t = tempfile::tempdir().unwrap(); + let dir = t.path().to_string_lossy().into_owned(); + for (format, files) in [("png8", 2), ("pdf", 1), ("psd", 2)] { + let dialog = open(&mut h, ARTBOARDS); + let fields = &mut h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + fields.insert("dir".into(), json!(dir)); + fields.insert("prefix".into(), json!(format)); + fields.insert("format".into(), json!(format)); + h.run_steps(2); + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + let written: Vec = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + assert_eq!(written.len(), files, "{format}: {written:?}"); + for f in &written { + let bytes = std::fs::read(f).unwrap(); + match format { + "png8" => assert_eq!(bytes[25], 3, "{f} is an indexed PNG"), + "pdf" => assert!(f.ends_with("pdf.pdf") && bytes.starts_with(b"%PDF-"), "{f}"), + _ => assert!(f.ends_with(".psd") && bytes.starts_with(b"8BPS"), "{f}"), + } + } + } +} + +#[test] +fn layer_comps_to_files_keeps_its_list() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + let fields = h.state_mut().ui.dialog_mut(dialog).unwrap().fields.clone(); + assert_eq!(fields["format"], json!("png")); + assert_eq!(fields["__choices"]["format"], json!(["png", "jpg", "psd", "tiff", "webp", "bmp"])); +} diff --git a/crates/ui-egui/src/export_quality_tests.rs b/crates/ui-egui/src/export_quality_tests.rs index 1f1bfd88ae..4cb4227604 100644 --- a/crates/ui-egui/src/export_quality_tests.rs +++ b/crates/ui-egui/src/export_quality_tests.rs @@ -219,7 +219,7 @@ fn alt_reset_restores_the_custom_quality() { alt_reset(&mut h); assert!(h.state().ui.dialogs.iter().any(|d| d.id == dialog), "Reset keeps the dialog open"); let p = params(&mut h, dialog); - assert_eq!((&p["format"], &p["quality"]), (&json!("png"), &Value::Null), "the opening format, no quality"); + assert_eq!((&p["format"], &p["quality"]), (&json!("psd"), &Value::Null), "the opening format, no quality"); assert!(!custom_ticked(&h) && !quality_enabled(&h), "Custom is off again"); assert_eq!(shown_quality(&h), Some(10.0), "the field shows the opening quality"); // Choosing JPEG again still sends no quality until Custom is ticked. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..4e0905e91d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1056,6 +1056,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_to_files_types_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..f1e23b6063 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -500,17 +500,23 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}), ) } - "file.export.layerCompsToFiles" | "file.export.artboardsToFiles" => { + "file.export.layerCompsToFiles" => { let (_, _, name) = doc?; let prefix = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - let fields = if id == "file.export.layerCompsToFiles" { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, - "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}) - } else { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "__order": ["dir", "prefix", "format", "quality"]}) - }; + let fields = json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, + "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}); dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) } + // The reference application's File Type list, in its order, PSD first chosen (#13635). + "file.export.artboardsToFiles" => { + let (_, _, name) = doc?; + let prefix = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); + let fields = json!({"dir": dir, "prefix": prefix, "format": "psd", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, + "__order": ["dir", "prefix", "format", "quality"], + "__labels": {"format": tl!("File Type:"), "bmp": "BMP", "jpg": "JPEG", "pdf": "PDF", "psd": "PSD", "tga": "Targa", "tiff": "TIFF", + "png8": "PNG-8", "png24": "PNG-24"}}); + dialog(app, fields, json!({"format": ["bmp", "jpg", "pdf", "psd", "tga", "tiff", "png8", "png24"]})) + } "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); From c57c51efca5dcf36ffcc67c91c3a7c95543d4be8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 06:33:12 +0100 Subject: [PATCH 03/12] WIP: Artboards to Files: Export Options per file type (#13636) From 71d11f4e447bf1cefb07ea057875e1d1b6a94626 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 07:05:08 +0100 Subject: [PATCH 04/12] Artboards to Files: Export Options per file type (#13636) The dialog gets an Export Options checkbox below File Type (unticked by default) that shows the chosen type's options with the reference application's defaults: PSD Maximize Compatibility / Preserve Artboard, BMP and Targa Depth, JPEG Quality, TIFF Image Compression with Quality (greyed unless JPEG), PNG Transparency / Interlaced, and Include ICC Profile for each. They are sent only while the checkbox is on and are remembered per type after a successful run, not after a failed one. file.export.artboardsToFiles takes iccProfile, bmpBits, pngInterlaced, transparency and preserveArtboard next to the existing save options, and refuses bad values. 16-bit BMP and JPEG-compressed TIFF are refused as unsupported: the shared encoders write neither yet. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 15 +- .../src/cmd/artboard_cmds/export_options.rs | 99 ++++++++ .../cmd/artboard_cmds/export_options_tests.rs | 212 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/save.rs | 22 ++ crates/io/src/flat.rs | 31 ++- crates/io/src/lib.rs | 37 +++ .../artboards_export_options_dialog_tests.rs | 212 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/export_quality_tests.rs | 21 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds.rs | 2 +- .../view_cmds/artboard_export_options.rs | 191 ++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 24 +- 13 files changed, 851 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/export_options.rs create mode 100644 crates/engine/src/cmd/artboard_cmds/export_options_tests.rs create mode 100644 crates/ui-egui/src/artboards_export_options_dialog_tests.rs create mode 100644 crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..009865fd39 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -14,7 +14,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::{CommandSpec, color_param, int, int_i32}; -use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; +use crate::file_cmds::{encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; use crate::{EngineError, Result, Session}; /// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages. @@ -680,12 +680,13 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); - let save = SaveOpts::from_params(s, p, cmd)?; + let (save, board) = export_options::parse(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + for (i, mut one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + board.apply(&mut one, &format); // Names may be identical, or collide after sanitizing or filesystem case folding. let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{format}")); @@ -829,7 +830,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files}"##, export_artboards, artboards_to_files ), @@ -844,6 +845,12 @@ pub fn specs() -> Vec { ] } +#[path = "artboard_cmds/export_options.rs"] +mod export_options; + +#[cfg(test)] +#[path = "artboard_cmds/export_options_tests.rs"] +mod export_options_tests; #[cfg(test)] #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; diff --git a/crates/engine/src/cmd/artboard_cmds/export_options.rs b/crates/engine/src/cmd/artboard_cmds/export_options.rs new file mode 100644 index 0000000000..9be7249c32 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/export_options.rs @@ -0,0 +1,99 @@ +//! Artboards to Files' Export Options (#13636): the per-file-type settings beyond the format. +//! Each one is optional; without any, an export writes what it wrote before. +//! +//! - `"iccProfile": bool`: embed the document's ICC profile (PSD: its ICC resource). Unset, as +//! before: flat files embed it, a PSD only when the document has a profile of its own. +//! - `"bmpBits": 16 | 24 | 32`: BMP depth. 16 is refused: the encoder writes 24 and 32 only. +//! - `"pngInterlaced": bool`: an Adam7-interlaced PNG. +//! - `"transparency": bool`: PNG; `false` composites each board over white, so the file has no alpha. +//! - `"preserveArtboard": bool`: PSD; `false` writes the board as a plain group. +//! - `"tiffCompression": "none" | "lzw" | "zip"`: as Save As; `"jpeg"` is refused, the TIFF +//! encoder has no JPEG compression yet. +//! - `"quality": 0..12` (JPEG), `"maximizeCompatibility": bool` (PSD) and `"tgaBits": 24 | 32` +//! (Targa) as for every save ([`SaveOpts::from_params`]). + +use photocraft_color::Color; +use photocraft_doc::{Document, LayerContent}; +use serde_json::Value; + +use crate::file_cmds::SaveOpts; +use crate::{EngineError, Result, Session}; + +/// What the options change in each board's document before it is written. +#[derive(Debug, Clone, Copy, Default)] +pub(super) struct BoardOptions { + /// PNG Transparency; `Some(false)` puts a white Background under the board. + transparency: Option, + /// PSD Preserve Artboard; `Some(false)` turns the board into a plain group. + preserve_artboard: Option, + /// Include ICC Profile; `Some(false)` leaves a PSD's ICC resource out, `Some(true)` writes + /// one even for a document without a profile of its own. + icc_profile: Option, +} + +fn bad(cmd: &str, msg: String) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg } +} + +/// `key` in `p` as a bool; absent or null: `None`. Anything else is a bad parameter of `cmd`. +fn bool_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(v) => Err(bad(cmd, format!("`{key}` must be true or false, got {v}"))), + } +} + +/// The save options and the per-board changes `p` asks for. +pub(super) fn parse(s: &Session, p: &Value, cmd: &str) -> Result<(SaveOpts, BoardOptions)> { + if p.get("tiffCompression").and_then(Value::as_str) == Some("jpeg") { + return Err(bad(cmd, "JPEG compression in a TIFF is not supported yet; use \"none\", \"lzw\" or \"zip\"".into())); + } + match p.get("quality") { + None | Some(Value::Null) => {} + Some(v) if v.as_f64().is_some() => {} + Some(v) => return Err(bad(cmd, format!("`quality` must be a number from 0 to 12, got {v}"))), + } + let mut save = SaveOpts::from_params(s, p, cmd)?; + save.bmp_bits = match p.get("bmpBits") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(photocraft_io::BmpBits::from_bits) { + Some(photocraft_io::BmpBits::Bits16) => return Err(bad(cmd, "16-bit BMP is not supported yet; use 24 or 32 bits".into())), + Some(bits) => Some(bits), + None => return Err(bad(cmd, format!("`bmpBits` must be 16, 24 or 32, got {v}"))), + }, + }; + let icc_profile = bool_param(p, "iccProfile", cmd)?; + save.embed_icc = icc_profile; + save.png_interlaced = bool_param(p, "pngInterlaced", cmd)?; + let board = BoardOptions { transparency: bool_param(p, "transparency", cmd)?, preserve_artboard: bool_param(p, "preserveArtboard", cmd)?, icc_profile }; + Ok((save, board)) +} + +impl BoardOptions { + /// Applies the options of `format` (lower case, no dot) to one board's document. + pub(super) fn apply(&self, one: &mut Document, format: &str) { + if format == "png" && self.transparency == Some(false) { + // A white Background in the document's own mode and depth: the composite is opaque, + // so the file is written without alpha. + let bg = Document::with_background("Background", one.size, one.mode, one.depth, Color::WHITE); + one.layers.splice(0..0, bg.layers); + } + if matches!(format, "psd" | "psb") { + if self.preserve_artboard == Some(false) { + for layer in &mut one.layers { + if let LayerContent::Group(g) = &mut layer.content { + g.artboard = None; + } + } + } + match self.icc_profile { + Some(false) => one.icc_profile = None, + // A document without a profile of its own gets the one its colours are taken to + // be in, as a flat file embeds it. + Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), + _ => {} + } + } + } +} diff --git a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs new file mode 100644 index 0000000000..f4eec3589f --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs @@ -0,0 +1,212 @@ +//! Artboards to Files' Export Options (#13636): each per-file-type option reaches the written +//! file, no option leaves the output as it was, and bad values are refused before anything is +//! written. + +use super::*; +use photocraft_geom::Rect; + +/// 64 x 48, transparent, with two boards: "Clear" (transparent, a red square inside, half the +/// board left empty) and "White" (white background, empty). +fn session() -> (Session, u64, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "transparent"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 16, 24), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + let clear = s.execute("layer.new.artboardFromLayers", json!({"name": "Clear", "background": "transparent", "width": 32, "height": 24})).unwrap(); + let white = s.execute("layer.new.artboard", json!({"rect": [40, 0, 16, 16], "name": "White", "background": "white"})).unwrap(); + (s, clear["layer"].as_u64().unwrap(), white["layer"].as_u64().unwrap()) +} + +/// Exports `board` with `extra` params as `format` and returns the file's bytes. +fn export(s: &mut Session, dir: &str, board: u64, format: &str, extra: Value) -> Vec { + let mut p = json!({"dir": dir, "prefix": "", "format": format, "artboards": [board]}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + std::fs::read(r["files"][0].as_str().unwrap()).unwrap() +} + +/// A fresh, empty folder for one test's files. +fn tmp(name: &str) -> String { + let dir = std::env::temp_dir().join(format!("photocraft-13636-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.to_string_lossy().into_owned() +} + +/// PNG IHDR: (colour type, interlace method). +fn png_header(b: &[u8]) -> (u8, u8) { + assert_eq!(&b[12..16], b"IHDR"); + (b[25], b[28]) +} + +fn has(b: &[u8], needle: &[u8]) -> bool { + b.windows(needle.len()).any(|w| w == needle) +} + +/// A little- or big-endian TIFF's first-IFD value of `tag` (SHORT or LONG), if present. +fn tiff_tag(b: &[u8], tag: u16) -> Option { + let le = &b[0..2] == b"II"; + let u16_at = |o: usize| if le { u16::from_le_bytes([b[o], b[o + 1]]) } else { u16::from_be_bytes([b[o], b[o + 1]]) }; + let u32_at = + |o: usize| if le { u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) } else { u32::from_be_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) }; + let ifd = u32_at(4) as usize; + (0..usize::from(u16_at(ifd))) + .map(|i| ifd + 2 + i * 12) + .find(|&e| u16_at(e) == tag) + .map(|e| if u16_at(e + 2) == 3 { u32::from(u16_at(e + 8)) } else { u32_at(e + 8) }) +} + +#[test] +fn without_options_the_files_are_as_before() { + let (mut s, clear, white) = session(); + let dir = &tmp("plain"); + let png = export(&mut s, dir, clear, "png", json!({})); + assert_eq!(png_header(&png), (6, 0), "RGBA, not interlaced"); + assert!(has(&png, b"iCCP"), "the profile is embedded"); + let bmp = export(&mut s, dir, white, "bmp", json!({})); + assert_eq!(u16::from_le_bytes([bmp[28], bmp[29]]), 24, "an opaque board is a 24-bit BMP"); + let tif = export(&mut s, dir, white, "tiff", json!({})); + assert_eq!(tiff_tag(&tif, 259), Some(1), "uncompressed"); + let psd = export(&mut s, dir, clear, "psd", json!({})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert_eq!(doc.artboards().len(), 1, "the board is kept"); + assert!(doc.icc_profile.is_none(), "a document without a profile of its own writes a PSD without one, as before"); + // Explicit nulls are the same as no option. + let nulls = json!({"iccProfile": null, "bmpBits": null, "pngInterlaced": null, "transparency": null, "preserveArtboard": null, "tiffCompression": null}); + assert_eq!(export(&mut s, dir, clear, "png", nulls.clone()), png); + assert_eq!(export(&mut s, dir, white, "bmp", nulls), bmp); +} + +#[test] +fn bmp_depth_reaches_the_file() { + let (mut s, clear, white) = session(); + let dir = &tmp("bmp"); + let bits = |b: &[u8]| u16::from_le_bytes([b[28], b[29]]); + // 32 bits on an opaque board adds an opaque alpha; 24 on a transparent one drops it. + let b32 = export(&mut s, dir, white, "bmp", json!({"bmpBits": 32})); + assert_eq!(bits(&b32), 32); + let b24 = export(&mut s, dir, clear, "bmp", json!({"bmpBits": 24})); + assert_eq!(bits(&b24), 24); + let img = photocraft_io::import("x.bmp", &b24).unwrap().document; + let px = photocraft_compose::flatten(&img).px.clone(); + // The empty right half of the board is white, the square red. + assert_eq!(px[(10 * 32 + 28) as usize], [1.0, 1.0, 1.0, 1.0]); + assert_eq!(px[(10 * 32 + 4) as usize], [1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn tiff_compression_reaches_the_file() { + let (mut s, _, white) = session(); + let dir = &tmp("tiff"); + for (name, tag) in [("none", 1), ("lzw", 5), ("zip", 8)] { + let tif = export(&mut s, dir, white, "tiff", json!({"tiffCompression": name})); + assert_eq!(tiff_tag(&tif, 259), Some(tag), "{name}"); + } +} + +#[test] +fn png_interlace_and_transparency_reach_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("png"); + let png = export(&mut s, dir, clear, "png", json!({"pngInterlaced": true})); + assert_eq!(png_header(&png), (6, 1), "Adam7"); + let png = export(&mut s, dir, clear, "png", json!({"transparency": true, "pngInterlaced": false})); + assert_eq!(png_header(&png), (6, 0)); + let png = export(&mut s, dir, clear, "png", json!({"transparency": false})); + assert_eq!(png_header(&png).0, 2, "Transparency off writes RGB without alpha"); + let img = photocraft_io::import("x.png", &png).unwrap().document; + let px = photocraft_compose::flatten(&img).px.clone(); + assert_eq!(px[(10 * 32 + 28) as usize], [1.0, 1.0, 1.0, 1.0], "the empty part is white"); + assert_eq!(px[(10 * 32 + 4) as usize], [1.0, 0.0, 0.0, 1.0]); + // Transparency is a PNG option: a PSD keeps its transparent board. + let psd = export(&mut s, dir, clear, "psd", json!({"transparency": false})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert_eq!(doc.layers.len(), 1, "no Background added"); +} + +#[test] +fn include_icc_profile_reaches_the_file() { + let (mut s, clear, white) = session(); + let dir = &tmp("icc"); + for on in [true, false] { + let p = json!({"iccProfile": on}); + assert_eq!(has(&export(&mut s, dir, clear, "png", p.clone()), b"iCCP"), on, "png {on}"); + assert_eq!(has(&export(&mut s, dir, white, "jpg", p.clone()), b"ICC_PROFILE\0"), on, "jpg {on}"); + assert_eq!(tiff_tag(&export(&mut s, dir, white, "tiff", p.clone()), 34675).is_some(), on, "tiff {on}"); + let psd = export(&mut s, dir, clear, "psd", p); + assert_eq!(photocraft_io::import("x.psd", &psd).unwrap().document.icc_profile.is_some(), on, "psd {on}"); + } + // The source document is not given one. + assert!(s.active().unwrap().doc.icc_profile.is_none()); +} + +#[test] +fn psd_options_reach_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("psd"); + let merged = |b: &[u8]| craft_psd::PsdFile::from_bytes(b).unwrap().has_real_merged_data(); + for on in [true, false] { + assert_eq!(merged(&export(&mut s, dir, clear, "psd", json!({"maximizeCompatibility": on}))), Some(on), "{on}"); + } + let psd = export(&mut s, dir, clear, "psd", json!({"preserveArtboard": false})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert!(doc.artboards().is_empty(), "written as a plain group"); + let group = doc.layers.first().unwrap(); + assert_eq!(group.name, "Clear"); + assert_eq!(group.children().unwrap().first().unwrap().name, "Red"); + let psd = export(&mut s, dir, clear, "psd", json!({"preserveArtboard": true})); + assert_eq!(photocraft_io::import("x.psd", &psd).unwrap().document.artboards().len(), 1); + // The source document keeps its board. + assert_eq!(s.active().unwrap().doc.artboards().len(), 2); +} + +#[test] +fn jpeg_quality_reaches_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("jpeg"); + s.execute("filter.noise.addNoise", json!({"amount": 60})).ok(); + let low = export(&mut s, dir, clear, "jpg", json!({"quality": 0})); + let frac = export(&mut s, dir, clear, "jpg", json!({"quality": 7.6})); + let high = export(&mut s, dir, clear, "jpg", json!({"quality": 12})); + assert!(low.len() < frac.len() && frac.len() < high.len(), "{} {} {}", low.len(), frac.len(), high.len()); +} + +#[test] +fn bad_option_values_are_errors_and_write_nothing() { + let (mut s, clear, _) = session(); + let dir = &tmp("bad"); + for bad in [ + json!({"tiffCompression": "jpeg"}), + json!({"tiffCompression": "rle"}), + json!({"tiffCompression": 5}), + json!({"bmpBits": 16}), + json!({"bmpBits": 17}), + json!({"bmpBits": "24"}), + json!({"bmpBits": -1}), + json!({"quality": "high"}), + json!({"quality": [8]}), + json!({"iccProfile": "yes"}), + json!({"pngInterlaced": 1}), + json!({"transparency": {}}), + json!({"preserveArtboard": "false"}), + json!({"maximizeCompatibility": 0}), + json!({"tgaBits": 16}), + ] { + let mut p = json!({"dir": dir, "format": "png", "artboards": [clear]}); + if let (Some(p), Some(bad)) = (p.as_object_mut(), bad.as_object()) { + p.extend(bad.clone()); + } + let r = s.execute("file.export.artboardsToFiles", p); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{bad}: nothing written"); + } +} diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index eba2b9502d..25f436b3ec 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -22,6 +22,15 @@ pub(crate) struct SaveOpts { /// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or /// transparency, else 24. pub tga_bits: Option, + /// BMP: 16, 24 or 32 bits per pixel; unset, 32 with transparency, else 24. Set by Artboards to + /// Files' BMP options (`"bmpBits"`). + pub bmp_bits: Option, + /// Embed the ICC profile in a flat file; unset, embed it. Artboards to Files' Include ICC + /// Profile (`"iccProfile"`). + pub embed_icc: Option, + /// PNG: write it interlaced (Adam7); unset, not. Artboards to Files' PNG Interlaced + /// (`"pngInterlaced"`). + pub png_interlaced: Option, /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. pub dpx_bits: Option, /// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none. @@ -57,6 +66,9 @@ impl Default for SaveOpts { jpeg_format: None, tiff_layers: false, tga_bits: None, + bmp_bits: None, + embed_icc: None, + png_interlaced: None, dpx_bits: None, tiff_compression: None, tiff_transparency: None, @@ -86,6 +98,9 @@ impl SaveOpts { jpeg_format: jpeg_format_param(p, cmd)?, tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits: tga_bits_param(p, cmd)?, + bmp_bits: None, + embed_icc: None, + png_interlaced: None, dpx_bits: dpx_bits_param(p, cmd)?, tiff_compression: tiff_compression_param(p, cmd)?, tiff_transparency: tiff_bool_param(p, "tiffTransparency", cmd)?, @@ -250,6 +265,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R tiff_transparency: save.tiff_transparency, preserve_alpha: save.preserve_alpha, tga_bits: save.tga_bits, + bmp_bits: save.bmp_bits, pdf_spot_plates: save.pdf_spot_plates, image_previews: save.image_previews, psd_maximize_compatibility: save.psd_maximize_compatibility, @@ -268,6 +284,12 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R opts.encode.tiff_compression = c; } opts.encode.tiff_pyramid = save.tiff_pyramid; + if let Some(embed) = save.embed_icc { + opts.encode.embed_icc = embed; + } + if let Some(interlaced) = save.png_interlaced { + opts.encode.png_interlaced = interlaced; + } opts.encode.dds = save.dds; if let Some(q) = save.quality { let q = jpeg_quality(q); diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 53611d5007..3961494410 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -9,7 +9,7 @@ use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_raster::{AllocationError, Interrupt, PruneCursor, RowWriteError, Surface}; use crate::renderer::{BandRenderer, RenderError}; -use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; +use crate::{BmpBits, ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; /// Bytes per band when converting or exporting a band of rows at a time. const BAND_BYTES: usize = 32 << 20; @@ -1769,6 +1769,9 @@ pub fn export_flat_with_renderer( if format == Format::Tga { img = tga_image(doc, img, opts.tga_bits, opts.preserve_alpha, &mut warnings)?; } + if format == Format::Bmp { + img = bmp_image(img, opts.bmp_bits, &mut warnings)?; + } if format == Format::Dds { img = dds_image(doc, img, &mut warnings)?; } @@ -1819,6 +1822,9 @@ pub fn export_flat_with_renderer( if format == Format::Tga { img = tga_image(doc, img, opts.tga_bits, opts.preserve_alpha, &mut warnings)?; } + if format == Format::Bmp { + img = bmp_image(img, opts.bmp_bits, &mut warnings)?; + } if format == Format::Dds { img = dds_image(doc, img, &mut warnings)?; } @@ -2123,6 +2129,29 @@ fn tga_image(doc: &Document, img: Image, bits: Option, preserve_alpha: } } +/// The image an RGB BMP of `bits` per pixel holds: 24 composites a transparent image over white, +/// 32 gives an opaque image an opaque alpha; `None` keeps the image (32 with transparency, else +/// 24). Grayscale images are written as they are. 16 bits is refused: the encoder has no 16-bit +/// BMP. +fn bmp_image(img: Image, bits: Option, warnings: &mut Vec) -> Result { + let Some(bits) = bits else { return Ok(img) }; + if !img.layout().is_rgb() { + warnings.push(format!("{}-bit BMP applies to RGB images; the grayscale image is written as it is", bits.bits())); + return Ok(img); + } + match bits { + BmpBits::Bits16 => Err(IoError::Unsupported("16-bit BMP is not supported yet; use 24 or 32 bits".into())), + BmpBits::Bits24 if img.layout().has_alpha() => { + warnings.push("transparency composited over white; a 24-bit BMP has no alpha".into()); + matte_over_white(&img) + } + BmpBits::Bits32 if !img.layout().has_alpha() => { + map_bands(&img, ChannelLayout::Rgba, img.sample_type(), |vals| vals.as_chunks::<3>().0.iter().flat_map(|&[r, g, b]| [r, g, b, 1.0]).collect()) + } + _ => Ok(img), + } +} + /// The image a DDS texture holds (#8563): as with a 32-bit Targa, the document's alpha channel /// becomes the texture's alpha when it has exactly one (spot channels don't count), the colours /// composited over white where the layers are transparent; BC1 keeps it as on/off, BC2 and BC3 diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index f537ac2b41..526f3f2cab 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -417,6 +417,10 @@ pub struct ExportOptions { /// Targa: bits per pixel of an RGB file. `None` writes 32 when the document has an alpha /// channel or transparency, else 24; Save As asks, starting at [`tga_default_bits`]. pub tga_bits: Option, + /// BMP: bits per pixel of an RGB file. `None` writes 32 when the composite has transparency, + /// else 24; `Some(24)` composites over white, `Some(32)` adds an opaque alpha to an opaque + /// image. 16 bits is refused as unsupported: the encoder writes 24 and 32 only. + pub bmp_bits: Option, /// PSD/PSB: embed the thumbnail image resource (1036), Preferences › File Handling › Image /// Previews. On by default, as Photoshop's Always Save. pub image_previews: bool, @@ -455,6 +459,7 @@ impl Default for ExportOptions { preserve_alpha: false, xmp: XmpEmbed::All, tga_bits: None, + bmp_bits: None, image_previews: true, psd_maximize_compatibility: true, document_path: None, @@ -494,6 +499,38 @@ impl TgaBits { } } +/// Bits per pixel of an RGB BMP (the Depth of Artboards to Files' BMP options). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BmpBits { + /// 5 bits per colour. + Bits16, + /// The colours alone, no alpha. + Bits24, + /// The colours and an 8-bit alpha. + Bits32, +} + +impl BmpBits { + /// `16`, `24` or `32` as [`BmpBits`]; any other number is `None`. + pub fn from_bits(bits: u64) -> Option { + match bits { + 16 => Some(BmpBits::Bits16), + 24 => Some(BmpBits::Bits24), + 32 => Some(BmpBits::Bits32), + _ => None, + } + } + + /// The bits per pixel. + pub fn bits(self) -> u8 { + match self { + BmpBits::Bits16 => 16, + BmpBits::Bits24 => 24, + BmpBits::Bits32 => 32, + } + } +} + /// `true` if `bytes` start with the PSD/PSB signature. pub fn is_psd(bytes: &[u8]) -> bool { bytes.starts_with(b"8BPS") diff --git a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs new file mode 100644 index 0000000000..0995e1be9b --- /dev/null +++ b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs @@ -0,0 +1,212 @@ +//! #13636: Artboards to Files' Export Options checkbox (unticked by default, below File Type) +//! shows the chosen file type's options with the reference application's defaults, sends them +//! to the command only while ticked, and remembers them after a successful run only. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const OPTION_PARAMS: [&str; 9] = + ["iccProfile", "bmpBits", "tgaBits", "pngInterlaced", "transparency", "tiffCompression", "maximizeCompatibility", "preserveArtboard", "quality"]; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#8A42B3"})).unwrap(); + app.run("layer.new.artboardFromLayers", json!({"name": "Board", "background": "transparent"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, dir: &str, format: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS, json!({})).unwrap()["dialog"].as_u64().unwrap(); + set(h, dialog, &[("dir", json!(dir)), ("prefix", json!("out")), ("format", json!(format))]); + dialog +} + +fn set(h: &mut Harness<'_, PhotocraftApp>, dialog: u64, kv: &[(&str, Value)]) { + let fields = &mut h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + for (k, v) in kv { + fields.insert((*k).into(), v.clone()); + } + h.run_steps(4); +} + +fn params(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(dialog).unwrap().fields) +} + +/// The option params the dialog sends (the null ones left out). +fn sent(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + let p = params(h, dialog); + Value::Object(OPTION_PARAMS.iter().filter_map(|k| p.get(*k).filter(|v| !v.is_null()).map(|v| ((*k).to_string(), v.clone()))).collect()) +} + +fn ticked(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn shown(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +fn tick_export_options(h: &mut Harness<'_, PhotocraftApp>) { + h.get_by_role_and_label(Role::CheckBox, "Export Options").click(); + h.run_steps(3); +} + +fn quality_field_enabled(h: &Harness<'_, PhotocraftApp>) -> bool { + !h.get_by_role_and_label(Role::SpinButton, "Quality").accesskit_node().is_disabled() +} + +fn type_quality(h: &mut Harness<'_, PhotocraftApp>, text: &str) { + h.get_by_role_and_label(Role::SpinButton, "Quality").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in text.chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn tmp() -> (tempfile::TempDir, String) { + let t = tempfile::tempdir().unwrap(); + let s = t.path().to_string_lossy().into_owned(); + (t, s) +} + +#[test] +fn export_options_is_unticked_below_file_type_and_sends_nothing() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + assert!(!ticked(&h, "Export Options")); + assert!(!shown(&h, "Include ICC Profile"), "the Options group is hidden"); + assert_eq!(sent(&mut h, dialog), json!({}), "no option reaches the command"); + assert!(!shown(&h, "Custom"), "no Custom quality row"); + let order = h.state_mut().ui.dialog_mut(dialog).unwrap().fields["__order"].clone(); + assert_eq!(order, json!(["dir", "prefix", "format", "exportOptions"]), "below File Type"); + let below = h.get_by_role_and_label(Role::CheckBox, "Export Options").rect().top(); + let format = h.get_by_role_and_label(Role::ComboBox, "Format").rect().top(); + assert!(below > format, "{below} > {format}"); +} + +#[test] +fn each_file_type_shows_its_options_with_the_reference_defaults() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + assert!(shown(&h, "Options:")); + let cases = [ + ("psd", vec!["Maximize Compatibility", "Preserve Artboard"], json!({"maximizeCompatibility": true, "preserveArtboard": true, "iccProfile": true})), + ("bmp", vec!["16bit", "24bit", "32bit"], json!({"bmpBits": 24, "iccProfile": true})), + ("jpg", vec!["Quality"], json!({"quality": 8.0, "iccProfile": true})), + ("tiff", vec!["Image Compression", "Quality"], json!({"tiffCompression": "none", "iccProfile": true})), + ("png", vec!["Transparency", "Interlaced"], json!({"transparency": true, "pngInterlaced": false, "iccProfile": true})), + ]; + for (format, labels, defaults) in cases { + set(&mut h, dialog, &[("format", json!(format))]); + for l in labels { + assert!(shown(&h, l), "{format}: {l}"); + } + assert!(ticked(&h, "Include ICC Profile"), "{format}"); + assert_eq!(sent(&mut h, dialog), defaults, "{format}"); + } + assert!(ticked(&h, "Transparency") && !ticked(&h, "Interlaced")); + set(&mut h, dialog, &[("format", json!("bmp"))]); + let radio = |h: &Harness<'_, PhotocraftApp>, l: &str| h.get_by_role_and_label(Role::RadioButton, l).accesskit_node().toggled() == Some(Toggled::True); + assert!(radio(&h, "24bit") && !radio(&h, "16bit") && !radio(&h, "32bit")); + h.get_by_role_and_label(Role::RadioButton, "32bit").click(); + h.run_steps(3); + assert_eq!(sent(&mut h, dialog)["bmpBits"], json!(32)); + // Each type keeps its own settings. + set(&mut h, dialog, &[("format", json!("png"))]); + assert_eq!(sent(&mut h, dialog), json!({"transparency": true, "pngInterlaced": false, "iccProfile": true})); + set(&mut h, dialog, &[("format", json!("bmp"))]); + assert_eq!(sent(&mut h, dialog)["bmpBits"], json!(32)); + // Unticked again: the group is hidden and nothing is sent. + tick_export_options(&mut h); + assert!(!shown(&h, "Include ICC Profile") && !shown(&h, "32bit")); + assert_eq!(sent(&mut h, dialog), json!({})); +} + +#[test] +fn tiff_quality_is_greyed_unless_the_compression_is_jpeg() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "tiff"); + tick_export_options(&mut h); + assert!(!quality_field_enabled(&h)); + assert!(sent(&mut h, dialog).get("quality").is_none()); + let mut opts = h.state_mut().ui.dialog_mut(dialog).unwrap().fields["__exportOpts"].clone(); + opts["tiff"]["tiffCompression"] = json!("jpeg"); + set(&mut h, dialog, &[("__exportOpts", opts)]); + assert!(quality_field_enabled(&h)); + assert_eq!(sent(&mut h, dialog), json!({"tiffCompression": "jpeg", "quality": 8.0, "iccProfile": true})); +} + +#[test] +fn the_quality_field_clamps_keeps_fractions_and_ignores_text() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "jpg"); + tick_export_options(&mut h); + for (typed, expect) in [("99", 12.0), ("-5", 0.0), ("7.6", 7.6), ("abc", 7.6)] { + type_quality(&mut h, typed); + let q = sent(&mut h, dialog)["quality"].as_f64().unwrap(); + assert!((q - expect).abs() < 1e-4, "{typed}: {q}"); + } +} + +#[test] +fn the_options_reach_the_written_file() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Interlaced").click(); + h.get_by_role_and_label(Role::CheckBox, "Transparency").click(); + h.run_steps(3); + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + let png = std::fs::read(r["files"][0].as_str().unwrap()).unwrap(); + assert_eq!((png[25], png[28]), (2, 1), "RGB without alpha, interlaced"); +} + +#[test] +fn options_are_remembered_after_a_successful_run_only() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Interlaced").click(); + h.run_steps(3); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(3); + let dialog = open(&mut h, &dir, "png"); + assert!(ticked(&h, "Export Options") && ticked(&h, "Interlaced"), "remembered after the run"); + // A run that fails (16-bit BMP is refused) is not remembered. + set(&mut h, dialog, &[("format", json!("bmp"))]); + h.get_by_role_and_label(Role::RadioButton, "16bit").click(); + h.get_by_role_and_label(Role::CheckBox, "Include ICC Profile").click(); + h.run_steps(3); + assert!(crate::dialogs::confirm(h.state_mut(), dialog).is_err()); + h.state_mut().ui.dialogs.clear(); + h.run_steps(3); + let dialog = open(&mut h, &dir, "bmp"); + assert_eq!(sent(&mut h, dialog), json!({"bmpBits": 24, "iccProfile": true}), "the last successful run's settings"); + set(&mut h, dialog, &[("format", json!("png"))]); + assert!(ticked(&h, "Interlaced")); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba..22c15511c7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1066,6 +1066,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, mut d: Dialog) -> Result Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { @@ -56,7 +57,7 @@ fn direct(h: &mut Harness<'_, PhotocraftApp>, dir: &str, format: &str, quality: if let Some(q) = quality { p["quality"] = json!(q); } - let r = h.state_mut().run(ARTBOARDS, p).unwrap(); + let r = h.state_mut().run(COMPS, p).unwrap(); std::fs::read(r["files"][0].as_str().unwrap()).unwrap() } @@ -121,13 +122,13 @@ fn tmp() -> (tempfile::TempDir, String) { } #[test] -fn artboards_to_files_sends_a_custom_jpeg_quality() { +fn layer_comps_to_files_sends_a_custom_jpeg_quality() { let mut h = harness(); let (_a, via_dialog) = tmp(); let (_b, via_command) = tmp(); let mut sizes = Vec::new(); for quality in [0, 3, 12] { - let dialog = open(&mut h, ARTBOARDS, &via_dialog, "jpg"); + let dialog = open(&mut h, COMPS, &via_dialog, "jpg"); assert!(!custom_ticked(&h) && !quality_enabled(&h), "JPEG with Custom off: the field is greyed out"); tick_custom(&mut h); assert!(custom_ticked(&h) && quality_enabled(&h), "JPEG with Custom on: the field takes input"); @@ -147,7 +148,7 @@ fn an_untouched_jpeg_export_writes_what_the_command_writes_with_no_quality() { let mut h = harness(); let (_a, via_dialog) = tmp(); let (_b, via_command) = tmp(); - let dialog = open(&mut h, ARTBOARDS, &via_dialog, "jpg"); + let dialog = open(&mut h, COMPS, &via_dialog, "jpg"); assert!(params(&mut h, dialog).get("quality").is_none_or(Value::is_null), "no quality is sent"); let bytes = exported(&mut h, dialog); assert!(bytes == direct(&mut h, &via_command, "jpg", None), "the untouched dialog keeps the command's own JPEG quality"); @@ -186,7 +187,7 @@ fn export_to_files_quality_leaves_png_and_webp_as_they_were() { fn the_custom_quality_survives_a_format_round_trip() { let mut h = harness(); let (_a, dir) = tmp(); - let dialog = open(&mut h, ARTBOARDS, &dir, "jpg"); + let dialog = open(&mut h, COMPS, &dir, "jpg"); tick_custom(&mut h); type_quality(&mut h, "4"); assert_eq!(params(&mut h, dialog)["quality"], json!(4)); @@ -209,7 +210,7 @@ fn the_custom_quality_survives_a_format_round_trip() { fn alt_reset_restores_the_custom_quality() { let mut h = harness(); let ctx = h.ctx.clone(); - let dialog = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS, json!({})).unwrap()["dialog"].as_u64().unwrap(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, COMPS, json!({})).unwrap()["dialog"].as_u64().unwrap(); // JPEG chosen in the dialog, after it opened: Reset puts the format back too. h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("format".into(), json!("jpg")); h.run_steps(4); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..b5198b51ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1056,6 +1056,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_export_options_dialog_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 6194417a22..5ff7c7ab7b 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -20,10 +20,10 @@ mod options; pub use arrange::{Border, borders, cells, drag_border}; pub(crate) use arrange::{document_is_floating, float_window}; -pub(crate) use dialogs::write_copy; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; +pub(crate) use dialogs::{remember_artboard_export_options, write_copy}; #[cfg(test)] use dispatch::is_enabled_with_engine; pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_without_document}; diff --git a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs new file mode 100644 index 0000000000..77856b9357 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs @@ -0,0 +1,191 @@ +//! Artboards to Files' Export Options (#13636): a checkbox below File Type, unticked by default, +//! that shows an Options group with the chosen file type's settings. Each type keeps its own +//! settings (shell state in [`OPTS`]); the command gets the flat params of the shown type only +//! while the checkbox is on, so an export without it writes what it wrote before. Both are +//! remembered after a successful run, never after a failed one. + +use super::{Map, PhotocraftApp, Value, json}; + +pub(super) const COMMAND: &str = "file.export.artboardsToFiles"; +/// The checkbox (a field, so it shows in `__order`; the command ignores it). +pub(super) const CHECKBOX: &str = "exportOptions"; +/// Every type's settings, `{type: {param: value}}`: shell state, never a command parameter. +pub(super) const OPTS: &str = "__exportOpts"; +/// The params the group sends; the form renders none of them itself. +pub(super) const PARAMS: [&str; 9] = + ["iccProfile", "bmpBits", "tgaBits", "pngInterlaced", "transparency", "tiffCompression", "maximizeCompatibility", "preserveArtboard", "quality"]; + +/// The settings key of a File Type value (`jpg` and `jpeg` share one, as `tif` and `tiff` do). +fn kind(format: &str) -> Option<&'static str> { + Some(match format.to_ascii_lowercase().as_str() { + "psd" | "psb" => "psd", + "bmp" => "bmp", + "jpg" | "jpeg" => "jpg", + "tif" | "tiff" => "tiff", + "tga" => "tga", + "png" => "png", + _ => return None, + }) +} + +/// The reference application's defaults for each type. +fn defaults() -> Value { + json!({ + "psd": {"maximizeCompatibility": true, "preserveArtboard": true, "iccProfile": true}, + "bmp": {"bmpBits": 24, "iccProfile": true}, + "tga": {"tgaBits": 24, "iccProfile": true}, + "jpg": {"quality": 8.0, "iccProfile": true}, + "tiff": {"tiffCompression": "none", "quality": 8.0, "iccProfile": true}, + "png": {"transparency": true, "pngInterlaced": false, "iccProfile": true}, + }) +} + +/// Whether `v` is a valid value for `key` (a hand-edited preferences file may hold anything). +fn valid(key: &str, v: &Value) -> bool { + match key { + "bmpBits" | "tgaBits" => v.as_u64().is_some_and(|b| [16, 24, 32].contains(&b)), + "tiffCompression" => v.as_str().is_some_and(|c| ["none", "lzw", "zip", "jpeg"].contains(&c)), + "quality" => v.as_f64().is_some_and(|q| (0.0..=12.0).contains(&q)), + _ => v.is_boolean(), + } +} + +/// The open dialog's fields: the checkbox and every type's settings, the defaults overlaid with +/// what the last successful run remembered. +pub(super) fn open_fields(app: &PhotocraftApp) -> (Value, Value) { + let mut opts = defaults(); + let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap_or(Value::Null); + if let (Some(all), Some(remembered)) = (opts.as_object_mut(), saved.get("options").and_then(Value::as_object)) { + for (kind, settings) in all.iter_mut() { + let (Some(settings), Some(from)) = (settings.as_object_mut(), remembered.get(kind).and_then(Value::as_object)) else { continue }; + for (key, v) in settings.iter_mut() { + if let Some(r) = from.get(key).filter(|r| valid(key, r)) { + *v = r.clone(); + } + } + } + } + (json!(saved.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false)), opts) +} + +/// Inserts the group's fields into a new dialog's `fields`. +pub(super) fn insert_fields(app: &PhotocraftApp, fields: &mut Value) { + let (on, opts) = open_fields(app); + if let Some(f) = fields.as_object_mut() { + f.insert(CHECKBOX.into(), on); + f.insert(OPTS.into(), opts); + for p in PARAMS { + f.insert(p.into(), Value::Null); + } + } + sync_params(fields.as_object_mut()); +} + +/// Remembers the checkbox and every type's settings after a successful run of the dialog. +pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map) { + if command != COMMAND || !fields.contains_key(OPTS) { + return; + } + let saved = json!({CHECKBOX: fields.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false), "options": fields.get(OPTS).cloned().unwrap_or(Value::Null)}); + app.session.prefs.edit(|prefs| prefs.dialogs.insert(COMMAND.into(), saved)); +} + +/// Writes the flat params for the command: the shown type's settings while the checkbox is on, +/// else none. TIFF sends its quality only with JPEG compression. +fn sync_params(f: Option<&mut Map>) { + let Some(f) = f else { return }; + for p in PARAMS { + f.insert(p.into(), Value::Null); + } + if f.get(CHECKBOX).and_then(Value::as_bool) != Some(true) { + return; + } + let Some(kind) = f.get("format").and_then(Value::as_str).and_then(kind) else { return }; + let Some(settings) = f.get(OPTS).and_then(|o| o.get(kind)).and_then(Value::as_object).cloned() else { return }; + let jpeg_tiff = settings.get("tiffCompression").and_then(Value::as_str) == Some("jpeg"); + for (key, v) in settings { + if kind == "tiff" && key == "quality" && !jpeg_tiff { + continue; + } + f.insert(key, v); + } +} + +fn get_bool(s: &Map, key: &str) -> bool { + s.get(key).and_then(Value::as_bool).unwrap_or(false) +} + +fn checkbox(ui: &mut egui::Ui, s: &mut Map, key: &str, label: &str) { + let mut on = get_bool(s, key); + crate::widgets::checkbox(ui, &mut on, label); + s.insert(key.into(), json!(on)); +} + +/// The Quality slider and field, 0-12: a typed value past either end is clamped, fractions are +/// kept, and text that is no number leaves the value as it was. +fn quality(ui: &mut egui::Ui, s: &mut Map) { + let mut q = s.get("quality").and_then(Value::as_f64).unwrap_or(8.0).clamp(0.0, 12.0) as f32; + crate::widgets::slider_line(ui, tl!("Quality"), 70.0, &mut q, 0.0..=12.0, ""); + s.insert("quality".into(), json!(f64::from(q.clamp(0.0, 12.0)))); +} + +/// Depth radios for BMP and Targa. +fn depth(ui: &mut egui::Ui, s: &mut Map, key: &str) { + let mut bits = s.get(key).and_then(Value::as_u64).unwrap_or(24); + ui.horizontal(|ui| { + ui.label(tl!("Depth:")); + for (b, label) in [(16, tl!("16bit")), (24, tl!("24bit")), (32, tl!("32bit"))] { + ui.radio_value(&mut bits, b, label); + } + }); + s.insert(key.into(), json!(bits)); +} + +/// The Export Options checkbox and, while it is ticked, the Options group of the chosen type. +pub(super) fn group(ui: &mut egui::Ui, f: &mut Map) { + let mut on = f.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false); + let kind = f.get("format").and_then(Value::as_str).and_then(kind); + ui.vertical(|ui| { + crate::widgets::checkbox(ui, &mut on, tl!("Export Options")); + let Some(kind) = kind.filter(|_| on) else { return }; + let Some(Value::Object(all)) = f.get_mut(OPTS) else { return }; + let Some(Value::Object(s)) = all.get_mut(kind) else { return }; + ui.label(tl!("Options:")); + ui.group(|ui| { + ui.set_min_width(300.0); + match kind { + "psd" => { + checkbox(ui, s, "maximizeCompatibility", tl!("Maximize Compatibility")); + checkbox(ui, s, "preserveArtboard", tl!("Preserve Artboard")); + } + "bmp" => depth(ui, s, "bmpBits"), + "tga" => depth(ui, s, "tgaBits"), + "jpg" => quality(ui, s), + "tiff" => { + let mut c = s.get("tiffCompression").and_then(Value::as_str).unwrap_or("none").to_string(); + let opts = [ + ("none".to_string(), tl!("None")), + ("lzw".to_string(), tl!("LZW")), + ("zip".to_string(), tl!("ZIP")), + ("jpeg".to_string(), tl!("JPEG")), + ]; + ui.horizontal(|ui| { + ui.label(tl!("Image Compression:")); + crate::widgets::dropdown(ui, "artboards-tiff-compression", tl!("Image Compression"), &mut c, &opts, 120.0); + }); + let jpeg = c == "jpeg"; + s.insert("tiffCompression".into(), json!(c)); + ui.add_enabled_ui(jpeg, |ui| quality(ui, s)); + } + "png" => { + checkbox(ui, s, "transparency", tl!("Transparency")); + checkbox(ui, s, "pngInterlaced", tl!("Interlaced")); + } + _ => {} + } + checkbox(ui, s, "iccProfile", tl!("Include ICC Profile")); + }); + }); + f.insert(CHECKBOX.into(), json!(on)); + sync_params(Some(f)); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..b8182d72e0 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1,6 +1,10 @@ use super::dispatch::no_params; use super::{DialogKind, Map, PhotocraftApp, Value, json}; +#[path = "artboard_export_options.rs"] +mod artboard_export_options; +pub(crate) use artboard_export_options::remember as remember_artboard_export_options; + // ---------- dialogs and pickers in front of engine commands ---------- /// A generic form dialog that runs `command` with its fields on OK (rendered by [`form_body`]). @@ -141,6 +145,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { let command = f.get("__command").and_then(Value::as_str); let file_info = command == Some("file.fileInfo"); let image_processor = command == Some("file.scripts.imageProcessor"); + let artboards = command == Some(artboard_export_options::COMMAND); let label = |k: &str| { if file_info { match k { @@ -162,6 +167,17 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { { continue; } + if artboards { + if artboard_export_options::PARAMS.contains(&k.as_str()) { + continue; + } + if k == artboard_export_options::CHECKBOX { + ui.label(""); + artboard_export_options::group(ui, f); + ui.end_row(); + continue; + } + } let v = f.get(&k).cloned().unwrap_or(Value::Null); if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { let label = ui.label(tl!("File Naming")); @@ -278,7 +294,7 @@ const BATCH_QUALITY: &str = "__batchQuality"; const JPEG_CUSTOM: &str = "__jpegCustom"; const JPEG_QUALITY: &str = "__jpegQuality"; /// The shell keys Alt+Reset restores along with a form's params. -const RESET_SHELL_KEYS: [&str; 3] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY]; +const RESET_SHELL_KEYS: [&str; 4] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, artboard_export_options::OPTS]; /// A Custom checkbox and the 0..12 Quality field it enables (Batch, the exports to files). Off, /// the command gets no quality and keeps its own defaults; `usable` false greys out both. @@ -507,7 +523,11 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}) } else { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "__order": ["dir", "prefix", "format", "quality"]}) + // The JPEG quality is one of the Export Options here (#13636). + let mut fields = + json!({"dir": dir, "prefix": prefix, "format": "png", "__order": ["dir", "prefix", "format", artboard_export_options::CHECKBOX]}); + artboard_export_options::insert_fields(app, &mut fields); + fields }; dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) } From 806b851e547f71c13610b38d51ba9532b28500b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:19:13 +0100 Subject: [PATCH 05/12] Artboards to Files: PNG-24 writes truecolour for non-RGB documents A Grayscale (or other non-RGB) board is converted to RGB for PNG-24, keeping its depth, layers and transparency; plain png keeps writing it as before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 15 +++++++++++++- .../src/cmd/artboard_cmds/file_types_tests.rs | 20 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 810a102488..381369a702 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -681,6 +681,8 @@ enum FileType { Save(String), /// One indexed (palette) PNG per board, as PNG-8. Png8, + /// One truecolour PNG per board, as PNG-24: a Grayscale or other non-RGB board becomes RGB. + Png24, /// One multi-page PDF, a page per board, bottom artboard first. Pdf, } @@ -689,7 +691,7 @@ impl FileType { fn of(format: &str) -> Self { match format { "png8" | "png-8" => FileType::Png8, - "png24" | "png-24" => FileType::Save("png".into()), + "png24" | "png-24" => FileType::Png24, "targa" => FileType::Save("tga".into()), "pdf" => FileType::Pdf, ext => FileType::Save(ext.into()), @@ -725,14 +727,19 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { return Ok(json!({"files": [path]})); } FileType::Png8 => None, + FileType::Png24 => Some("png".to_string()), FileType::Save(ext) => Some(ext), }; + let truecolour = matches!(FileType::of(&format), FileType::Png24); let mut files = Vec::new(); for (i, one) in boards.into_iter().enumerate() { // Names may be identical, or collide after sanitizing or filesystem case folding. let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{}", ext.as_deref().unwrap_or("png"))); match &ext { + Some(_) if truecolour && one.mode != ColorMode::Rgb => { + save_doc(&rgb_copy(&one)?, &path, save)?; + } Some(_) => { save_doc(&one, &path, save)?; } @@ -758,6 +765,12 @@ fn png8(one: &Document) -> Result> { Ok(optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?.bytes) } +/// `one` converted to RGB (its depth, layers and transparency kept), for a truecolour file. +fn rgb_copy(one: &Document) -> Result { + use crate::web_cmds::{WebSettings, web_document}; + Ok(web_document(one, &json!({}), &WebSettings { convert_to_srgb: false, ..WebSettings::default() })?.0) +} + /// `one` flattened over white as a JPEG, for a PDF page. fn jpeg_page(one: &Document, quality: Option) -> Result> { let buf = photocraft_compose::flatten(one).over_background([1.0, 1.0, 1.0]); diff --git a/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs index 9788e98d33..3e30ef0620 100644 --- a/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs @@ -87,6 +87,26 @@ fn png24_writes_truecolour_pngs_with_alpha_where_transparent() { let _ = std::fs::remove_dir_all(&dir); } +/// A Grayscale document's boards are still truecolour as PNG-24 (and keep their alpha), while +/// plain `png` keeps writing Grayscale as before. +#[test] +fn png24_is_truecolour_for_a_grayscale_document() { + let mut s = boards(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let dir = out_dir("png24-gray"); + let files = export(&mut s, &dir, "png24"); + assert_eq!(files.len(), 3); + for f in &files { + assert!(matches!(png_color_type(f), 2 | 6), "{f} is not truecolour"); + } + assert_eq!(png_color_type(&files[0]), 6, "the transparent board keeps its alpha"); + assert_eq!(size_of(&files[2], "png"), (200, 150)); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Grayscale, "the document itself is unchanged"); + let files = export(&mut s, &dir, "png"); + assert!(files.iter().all(|f| matches!(png_color_type(f), 0 | 4)), "plain png stays Grayscale"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn targa_writes_tga_files() { let mut s = boards(); From 05092c4fa8e0f2b8e66f3320d8dbe97a36f8cc86 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 22:30:19 +0100 Subject: [PATCH 06/12] cargo fmt after merging main Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 248eabc7da..61740c4214 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -977,13 +977,13 @@ pub fn specs() -> Vec { ] } -#[cfg(test)] -#[path = "artboard_cmds/file_types_tests.rs"] -mod file_types_tests; #[cfg(test)] #[path = "artboard_cmds/file_names_tests.rs"] mod file_names_tests; #[cfg(test)] +#[path = "artboard_cmds/file_types_tests.rs"] +mod file_types_tests; +#[cfg(test)] #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] From 2f0ac3215f75af77dbdb4d08052c26f4aeefaf99 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:22:45 +0100 Subject: [PATCH 07/12] Address CodeRabbit review: refuse compound file types, unreadable scratch tiles and oversized boards in artboard exports - A format token must be one plain extension: `unknown.png` named `.unknown.png` and wrote PNGs, and a `/` could leave the folder. - Artboards to Files and Artboards to PDF capture the scratch read generation before the boards are built and check it, and the document's own scratch health, before each file is written: building the boards copies their pixels (and the PNG-8 and PDF paths flatten them) before the encoder's own check sees them, so placeholder pixels from a failed read reached files. - The PNG-8 and PDF page paths refuse a board past the compositor's render limit as a bad parameter instead of panicking on the empty flatten. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 74 +++++++++++++----- .../src/cmd/artboard_cmds/file_types_tests.rs | 29 ++++++- .../engine/tests/artboard_export_scratch.rs | 76 +++++++++++++++++++ 3 files changed, 157 insertions(+), 22 deletions(-) create mode 100644 crates/engine/tests/artboard_export_scratch.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 61740c4214..fa6452ee7a 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -16,7 +16,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::{CommandSpec, color_param, int, int_i32}; -use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; +use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, stem, str_param, write_file}; use crate::{EngineError, Result, Session}; /// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages. @@ -690,14 +690,17 @@ enum FileType { } impl FileType { - fn of(format: &str) -> Self { - match format { + /// Any other token is an extension for the encoder to pick by. It must be one plain extension: + /// `unknown.png` would name `.unknown.png` and write a PNG, and a `/` would leave `dir`. + fn of(format: &str, cmd: &str) -> Result { + Ok(match format { "png8" | "png-8" => FileType::Png8, "png24" | "png-24" => FileType::Png24, "targa" => FileType::Save("tga".into()), "pdf" => FileType::Pdf, - ext => FileType::Save(ext.into()), - } + ext if !ext.is_empty() && ext.bytes().all(|b| b.is_ascii_alphanumeric()) => FileType::Save(ext.into()), + other => return Err(bad(cmd, format!("unknown file type `{other}`"))), + }) } } @@ -761,20 +764,24 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); + let guard = ScratchGuard::new(&doc)?; let boards = chosen_documents(&doc, p)?; if boards.is_empty() { return Err(bad(cmd, "no matching artboards")); } - let ext = match FileType::of(&format) { + let file_type = FileType::of(&format, cmd)?; + let truecolour = matches!(file_type, FileType::Png24); + let ext = match file_type { FileType::Pdf => { // The reference application's Multi-Page Document: the bottom artboard is page 1, and // each page is the board's pixel size at 72 ppi. let mut pages = Vec::new(); for one in boards.iter().rev() { - pages.push((one.size.width, one.size.height, 72.0, jpeg_page(one, save.quality.or(Some(10.0)))?)); + pages.push((one.size.width, one.size.height, 72.0, jpeg_page(one, save.quality.or(Some(10.0)), cmd)?)); } let name = if prefix.is_empty() { stem(&doc.name) } else { prefix }; let path = join(&dir, &format!("{}.pdf", sanitize(&name))); + guard.check()?; write_file(&path, &raster_pdf(&pages))?; return Ok(json!({"files": [path]})); } @@ -782,29 +789,49 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { FileType::Png24 => Some("png".to_string()), FileType::Save(ext) => Some(ext), }; - let truecolour = matches!(FileType::of(&format), FileType::Png24); let extension = ext.as_deref().unwrap_or("png"); let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect(); let stems = artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&extension)); let mut files = Vec::new(); for (one, name) in boards.iter().zip(stems) { let path = join(&dir, &format!("{name}.{extension}")); - match &ext { - Some(_) if truecolour && one.mode != ColorMode::Rgb => { - save_doc(&rgb_copy(one)?, &path, save)?; - } - Some(_) => { - save_doc(one, &path, save)?; - } - None => write_file(&path, &png8(one)?)?, - } + let bytes = match &ext { + Some(_) if truecolour && one.mode != ColorMode::Rgb => encode(&rgb_copy(one)?, &path, save)?.0, + Some(_) => encode(one, &path, save)?.0, + None => png8(one, cmd)?, + }; + guard.check()?; + write_file(&path, &bytes)?; files.push(path); } Ok(json!({"files": files})) } +/// The scratch state an artboard export starts from. Building the boards copies their pixels +/// (and the PNG-8 and PDF paths flatten them) before the encoder's own scratch check sees them, +/// and a tile that fails to read gives placeholder pixels: [`ScratchGuard::check`] refuses them +/// before a file is written, as the export pipeline does for a document it reads itself. +struct ScratchGuard<'a> { + doc: &'a Document, + generation: u64, +} + +impl<'a> ScratchGuard<'a> { + fn new(doc: &'a Document) -> Result { + photocraft_compose::discard_unreadable_pixel_caches(); + doc.scratch_health().map_err(EngineError::Other)?; + Ok(Self { doc, generation: photocraft_raster::spill::read_error_generation() }) + } + + /// An error when a scratch read failed since [`ScratchGuard::new`], or the document's own + /// pixels are unreadable. + fn check(&self) -> Result<()> { + photocraft_raster::spill::check_since(self.generation).and_then(|()| self.doc.scratch_health()).map_err(EngineError::Other) + } +} + /// `one` as an indexed PNG: Generate Assets' PNG-8 (selective palette, no dither, transparency kept). -fn png8(one: &Document) -> Result> { +fn png8(one: &Document, cmd: &str) -> Result> { use crate::web_cmds::{WebFormat, WebMetadata, WebSettings, optimize, web_document}; let st = WebSettings { format: WebFormat::Png8, @@ -813,6 +840,7 @@ fn png8(one: &Document) -> Result> { metadata: WebMetadata::None, ..WebSettings::default() }; + crate::file_cmds::check_flattenable(one, cmd)?; let (wdoc, _, _) = web_document(one, &json!({}), &st)?; let buf = photocraft_compose::flatten(&wdoc); Ok(optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?.bytes) @@ -824,8 +852,10 @@ fn rgb_copy(one: &Document) -> Result { Ok(web_document(one, &json!({}), &WebSettings { convert_to_srgb: false, ..WebSettings::default() })?.0) } -/// `one` flattened over white as a JPEG, for a PDF page. -fn jpeg_page(one: &Document, quality: Option) -> Result> { +/// `one` flattened over white as a JPEG, for a PDF page. A board past the compositor's render +/// limit is refused before it is flattened (the flatten would be empty). +fn jpeg_page(one: &Document, quality: Option, cmd: &str) -> Result> { + crate::file_cmds::check_flattenable(one, cmd)?; let buf = photocraft_compose::flatten(one).over_background([1.0, 1.0, 1.0]); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); @@ -889,16 +919,18 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); + let guard = ScratchGuard::new(&doc)?; let mut pages = Vec::new(); // Pages go bottom artboard of the Layers panel first, as in the reference application (#13643); // `chosen_documents` lists them top first, the order Artboards to Files keeps. for one in chosen_documents(&doc, p)?.into_iter().rev() { - let jpeg = jpeg_page(&one, quality)?; + let jpeg = jpeg_page(&one, quality, cmd)?; pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg)); } if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } + guard.check()?; write_file(&path, &raster_pdf(&pages))?; Ok(json!({"path": path, "pages": pages.len()})) } diff --git a/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs index 0ac435e4fc..7ca2b2b4e9 100644 --- a/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/file_types_tests.rs @@ -157,9 +157,36 @@ fn scripts_still_default_to_png() { fn unknown_format_is_an_error_and_writes_nothing() { let mut s = boards(); let dir = out_dir("unknown"); - for format in ["xyz", "png9", ""] { + // A token with a second extension or a path in it is not a file type either: `unknown.png` + // used to name `.unknown.png` and write PNGs. + for format in ["xyz", "png9", "", "unknown.png", "x.jpg", "../png", "png/x", "png "] { assert!(s.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})).is_err(), "{format}"); } assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); let _ = std::fs::remove_dir_all(&dir); } + +/// A board past the compositor's render limit flattens to an empty buffer; the PNG-8 and PDF +/// paths flatten it themselves, so they refuse it as a bad parameter instead of panicking on the +/// empty buffer (`region data length mismatch`). +#[test] +fn oversized_board_is_a_bad_params_error_for_png8_and_pdf() { + let mut s = Session::new(); + let mut doc = Document::new("huge", Size::new(40_000, 40_000), ColorMode::Rgb, SampleType::U8); + let mut board = Layer::group("Huge Board", Vec::new()); + if let LayerContent::Group(g) = &mut board.content { + g.artboard = Some(Artboard { rect: Rect::new(0, 0, 40_000, 40_000), background: ArtboardBackground::Transparent, preset: String::new() }); + } + doc.layers.push(board); + s.add_document(doc, None); + let dir = out_dir("huge"); + for format in ["png8", "pdf"] { + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{format}: {r:?}"); + } + let path = join(&dir, "huge.pdf"); + let r = s.execute("file.export.artboardsToPdf", json!({"path": path})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "artboardsToPdf: {r:?}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/artboard_export_scratch.rs b/crates/engine/tests/artboard_export_scratch.rs new file mode 100644 index 0000000000..da0443310b --- /dev/null +++ b/crates/engine/tests/artboard_export_scratch.rs @@ -0,0 +1,76 @@ +//! Artboards to Files and Artboards to PDF never write a board whose scratch tiles can't be read: +//! the PNG-8 and PDF paths flatten the board themselves, outside the checked export pipeline, so +//! the placeholder pixels a failed read gives would otherwise be encoded as real pixels. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent}; +use photocraft_engine::Session; +use photocraft_geom::{Rect, Size, TileCoord}; +use photocraft_raster::spill; +use serde_json::json; +use std::io::{Read, Seek, SeekFrom, Write}; + +#[test] +fn artboard_exports_refuse_unreadable_scratch_tiles() { + let root = std::env::temp_dir().join(format!("photocraft-artboard-scratch-{}", std::process::id())); + let scratch = root.join("scratch"); + let out = root.join("out"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&out).unwrap(); + let mut session = Session::new(); + session.edit_prefs(|p| { + p.scratch_disks.disks = vec![photocraft_engine::prefs::ScratchDisk { path: scratch.to_string_lossy().into(), enabled: true }]; + p.performance.memory_usage_mb = 1; + }); + assert!(spill::enabled()); + let mut doc = Document::new("Scratch boards", Size::new(2048, 256), ColorMode::Rgb, SampleType::U8); + let mut pixels = Layer::raster("Pixels", PixelFormat::RGBA8); + for i in 0..8 { + let mut bytes = pixels.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut(); + for (j, b) in bytes.iter_mut().enumerate() { + *b = (j as u32).wrapping_mul(17).wrapping_add(i as u32 * 43) as u8; + } + } + let mut board = Layer::group("Board", vec![pixels]); + if let LayerContent::Group(g) = &mut board.content { + g.artboard = Some(Artboard { rect: Rect::new(0, 0, 2048, 256), background: ArtboardBackground::Transparent, preset: String::new() }); + } + doc.layers.push(board); + session.add_document(doc, None); + let dir = out.to_string_lossy().into_owned(); + // Readable: every path writes. + for format in ["png8", "pdf"] { + session.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})).unwrap(); + } + let pdf = out.join("whole.pdf").to_string_lossy().into_owned(); + session.execute("file.export.artboardsToPdf", json!({"path": pdf})).unwrap(); + for entry in std::fs::read_dir(&out).unwrap() { + std::fs::remove_file(entry.unwrap().path()).unwrap(); + } + + // Force every tile to disk, then damage only this test's scratch file. + spill::configure(Some(&scratch), 1).unwrap(); + spill::settle(); + assert_eq!(spill::stats().resident_bytes, 0); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + + for format in ["png8", "pdf", "png24", "png"] { + let r = session.execute("file.export.artboardsToFiles", json!({"dir": dir, "format": format})); + assert!(r.is_err(), "{format} wrote a board with unreadable tiles: {r:?}"); + } + assert!(session.execute("file.export.artboardsToPdf", json!({"path": pdf})).is_err(), "Artboards to PDF wrote unreadable tiles"); + let written: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); + assert!(written.is_empty(), "{written:?}"); + + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + drop((session, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(root); +} From ad131b391ec096563494cab65250182fa91829bf Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:41:29 +0100 Subject: [PATCH 08/12] Address CodeRabbit review: keep the scratch test's one-byte budget through eviction The session's memory worker refreshes the tile budget from the preferences every two seconds; a refresh between configure and settle could leave tiles resident. Set the budget again until a settle has emptied memory (bounded). Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/artboard_export_scratch.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/artboard_export_scratch.rs b/crates/engine/tests/artboard_export_scratch.rs index da0443310b..38f0e71e6c 100644 --- a/crates/engine/tests/artboard_export_scratch.rs +++ b/crates/engine/tests/artboard_export_scratch.rs @@ -47,9 +47,17 @@ fn artboard_exports_refuse_unreadable_scratch_tiles() { std::fs::remove_file(entry.unwrap().path()).unwrap(); } - // Force every tile to disk, then damage only this test's scratch file. - spill::configure(Some(&scratch), 1).unwrap(); - spill::settle(); + // Force every tile to disk, then damage only this test's scratch file. The session's memory + // worker refreshes the budget from the preferences every two seconds; a refresh between + // `configure` and `settle` would leave tiles resident, so set the one-byte budget again until + // a settle has emptied memory (bounded). + for _ in 0..20 { + spill::configure(Some(&scratch), 1).unwrap(); + spill::settle(); + if spill::stats().resident_bytes == 0 { + break; + } + } assert_eq!(spill::stats().resident_bytes, 0); let mut file = spill::scratch_handle_for_tests().unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); From c30a5bfbd7c16665ed229da785b54a6a0dcbe7da Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:36:29 +0100 Subject: [PATCH 09/12] Tests: the artboard export scratch test joins the global_state binary `cargo xtask test-binaries` refuses single-file test binaries under crates/*/tests. The test sets the scratch disk and the memory budget for the whole process, so it moves next to scratch_disk.rs in tests/global_state and takes the same process lock and test volume. Co-Authored-By: Claude Opus 5.5 --- .../engine/tests/{ => global_state}/artboard_export_scratch.rs | 2 ++ crates/engine/tests/global_state/main.rs | 1 + 2 files changed, 3 insertions(+) rename crates/engine/tests/{ => global_state}/artboard_export_scratch.rs (97%) diff --git a/crates/engine/tests/artboard_export_scratch.rs b/crates/engine/tests/global_state/artboard_export_scratch.rs similarity index 97% rename from crates/engine/tests/artboard_export_scratch.rs rename to crates/engine/tests/global_state/artboard_export_scratch.rs index 38f0e71e6c..cb2d21be19 100644 --- a/crates/engine/tests/artboard_export_scratch.rs +++ b/crates/engine/tests/global_state/artboard_export_scratch.rs @@ -11,6 +11,8 @@ use std::io::{Read, Seek, SeekFrom, Write}; #[test] fn artboard_exports_refuse_unreadable_scratch_tiles() { + photocraft_raster::spill::use_test_volume_space(); + let _scratch = crate::lock(&crate::PROCESS); let root = std::env::temp_dir().join(format!("photocraft-artboard-scratch-{}", std::process::id())); let scratch = root.join("scratch"); let out = root.join("out"); diff --git a/crates/engine/tests/global_state/main.rs b/crates/engine/tests/global_state/main.rs index fa3f08a3d1..4d78ec0606 100644 --- a/crates/engine/tests/global_state/main.rs +++ b/crates/engine/tests/global_state/main.rs @@ -2,6 +2,7 @@ //! spill configuration, simulated memory, global caches, compositor settings). They live apart from //! `it` so plain `cargo test` runs them without the rest of the suite. +mod artboard_export_scratch; mod lut_row_cache_purge; mod mask_cache_purge; mod memory_gate; From 2667bd6f15d13b83797e6f500493a8450fa7a99e Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:55:30 +0100 Subject: [PATCH 10/12] Address CodeRabbit review: a reopened recording keeps its JPEG quality The editor of a recorded Artboards to Files step is built from the command's own plain params, so its values carry no Export Options checkbox. `nest` removed the plain `quality` from every form, and a recorded quality never reached the command again. Values without the checkbox now go to the command as they are. Co-Authored-By: Claude Opus 5.5 --- .../artboards_export_options_dialog_tests.rs | 23 +++++++++++++++++++ .../view_cmds/artboard_export_options.rs | 6 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs index c4e183fc4a..fc4070f8ed 100644 --- a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs @@ -204,3 +204,26 @@ fn options_are_remembered_after_a_successful_run_only() { set(&mut h, dialog, "format", json!("png")); assert!(ticked(&h, "Interlaced")); } + +/// Opens the editor of a recorded step with `recorded`, as Record Again and a playback with the step's dialog on do. +fn reopen(h: &mut H, recorded: Value) -> DialogId { + let dialog = crate::panels::actions::open_recorded_editor(h.state_mut(), ARTBOARDS, &recorded).unwrap(); + h.run_steps(4); + dialog +} + +/// The editor of a recorded step has the command's own plain params, the Export Options among them: OK without +/// changes sends what was recorded, the JPEG quality too. +#[test] +fn a_reopened_recording_keeps_its_export_options() { + let (_t, dir) = tmp(); + let mut h = harness(); + let dialog = reopen(&mut h, json!({"dir": dir, "prefix": "out", "format": "jpg", "quality": 3, "iccProfile": false})); + let p = sent(&h, dialog); + assert_eq!(p["quality"].as_f64(), Some(3.0), "{p}"); + assert_eq!(p["iccProfile"], false, "{p}"); + let mut h = harness(); + let dialog = reopen(&mut h, json!({"dir": dir, "format": "tiff", "tiffCompression": "lzw", "pngInterlaced": false})); + let p = sent(&h, dialog); + assert_eq!((&p["tiffCompression"], &p["pngInterlaced"]), (&json!("lzw"), &json!(false)), "{p}"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs index ebf88dd06f..36446c1fbb 100644 --- a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs +++ b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs @@ -76,9 +76,11 @@ pub(super) fn rows() -> Vec { /// The command params of the form's values `map`: the chosen type's settings under their plain names while the /// checkbox is ticked, else none; every type's own row keys and the checkbox go. TIFF sends its quality only with JPEG -/// compression, and the depths are numbers. +/// compression, and the depths are numbers. Values without the checkbox come from the editor of a recorded step, +/// whose rows are the command's own plain params: they go to the command as they are. pub(crate) fn nest(map: &mut Map) { - let on = map.remove(CHECKBOX).and_then(|v| v.as_bool()) == Some(true); + let Some(on) = map.remove(CHECKBOX) else { return }; + let on = on.as_bool() == Some(true); let chosen = map.get("format").and_then(Value::as_str).and_then(kind).filter(|_| on); let own: Vec = map.keys().filter(|k| k.split_once('.').is_some_and(|(kind, _)| KINDS.contains(&kind))).cloned().collect(); let mut settings = Map::new(); From ff4fbc294eff0232603f1b963f35df93f45b01c7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:55:31 +0100 Subject: [PATCH 11/12] Address CodeRabbit review: report Interlaced on palette PNG exports The palette PNG path wrote an Indexed Color document without interlacing and said nothing; the band-wise PNG path warns when it turns interlacing off. The palette path now adds the same kind of warning. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/flat.rs | 3 +++ crates/io/tests/it/modes.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index c299a34908..b12104ab70 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -2396,6 +2396,9 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi)); let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi, opts.encode.png_stereo)?; let mut warnings = vec![format!("written as an 8-bit palette PNG ({} colours)", table.colors.len())]; + if opts.encode.png_interlaced { + warnings.push("written without interlacing: the palette PNG exporter does not interlace".into()); + } if opts.encode.embed_metadata && opts.xmp == XmpEmbed::All && !doc.metadata.text.is_empty() { warnings.push("text metadata is not supported by the palette PNG exporter; it will be dropped".into()); } diff --git a/crates/io/tests/it/modes.rs b/crates/io/tests/it/modes.rs index b1bfff3d30..ad3ac65415 100644 --- a/crates/io/tests/it/modes.rs +++ b/crates/io/tests/it/modes.rs @@ -153,6 +153,20 @@ fn indexed_png_keeps_the_document_resolution() { assert!((back.resolution_dpi - 300.0).abs() < 0.01, "{}", back.resolution_dpi); } +#[test] +fn indexed_png_reports_that_it_is_not_interlaced() { + // Interlaced was dropped without a word for an Indexed Color document; the RGB path warns. + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0]], transparent: None }); + let mut opts = photocraft_io::ExportOptions::default(); + opts.encode.png_interlaced = true; + let r = photocraft_io::export(&d, "x.png", &opts).unwrap(); + assert_eq!((r.bytes[25], r.bytes[28]), (3, 0), "a palette PNG, not interlaced"); + assert!(r.warnings.iter().any(|w| w.contains("without interlacing")), "{:?}", r.warnings); + let plain = photocraft_io::export(&d, "x.png", &Default::default()).unwrap(); + assert!(!plain.warnings.iter().any(|w| w.contains("interlac")), "{:?}", plain.warnings); +} + #[test] fn indexed_bmp_is_palette_bmp() { // The BMP export wrote an Indexed Color document as 24-bit RGB, so reopening it lost the mode (#3869 follow-up). From 0bd8b76c73967b47063cf576b8499fb13dbab150 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 13:12:19 +0100 Subject: [PATCH 12/12] PR #14292: refuse JPEG quality outside 0-12, return export warnings Artboards to Files accepted any number as `quality` and clamped it while writing, though the params string documents 0..12; it now returns BadParams before any file is written. The warnings of each file's save were dropped; they now come back as `warnings`, each prefixed with the file name, as Save a Copy returns them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 7 ++++--- .../src/cmd/artboard_cmds/export_options.rs | 2 +- .../cmd/artboard_cmds/export_options_tests.rs | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 452ff70758..267c17ad48 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -875,16 +875,17 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect(); let stems = artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str())); let mut files = Vec::new(); + let mut warnings = Vec::new(); for (mut one, name) in boards.into_iter().zip(stems) { board.apply(&mut one, &format); let path = join(&dir, &format!("{name}.{format}")); - save_doc(&one, &path, save)?; + warnings.extend(save_doc(&one, &path, save)?.into_iter().map(|w| format!("{name}.{format}: {w}"))); files.push(path); } if files.is_empty() { return Err(bad(cmd, "no matching artboards")); } - Ok(json!({"files": files})) + Ok(json!({"files": files, "warnings": warnings})) } /// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). @@ -1020,7 +1021,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files} (one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files, warnings} (warnings: what a file could not hold, each ": "; one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, export_artboards, artboards_to_files ), diff --git a/crates/engine/src/cmd/artboard_cmds/export_options.rs b/crates/engine/src/cmd/artboard_cmds/export_options.rs index 9be7249c32..354b2cdf5c 100644 --- a/crates/engine/src/cmd/artboard_cmds/export_options.rs +++ b/crates/engine/src/cmd/artboard_cmds/export_options.rs @@ -51,7 +51,7 @@ pub(super) fn parse(s: &Session, p: &Value, cmd: &str) -> Result<(SaveOpts, Boar } match p.get("quality") { None | Some(Value::Null) => {} - Some(v) if v.as_f64().is_some() => {} + Some(v) if v.as_f64().is_some_and(|q| (0.0..=12.0).contains(&q)) => {} Some(v) => return Err(bad(cmd, format!("`quality` must be a number from 0 to 12, got {v}"))), } let mut save = SaveOpts::from_params(s, p, cmd)?; diff --git a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs index f4eec3589f..62345e5668 100644 --- a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs @@ -194,6 +194,9 @@ fn bad_option_values_are_errors_and_write_nothing() { json!({"bmpBits": -1}), json!({"quality": "high"}), json!({"quality": [8]}), + json!({"quality": -1}), + json!({"quality": 12.5}), + json!({"quality": 13}), json!({"iccProfile": "yes"}), json!({"pngInterlaced": 1}), json!({"transparency": {}}), @@ -210,3 +213,17 @@ fn bad_option_values_are_errors_and_write_nothing() { assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{bad}: nothing written"); } } + +/// What a file could not hold comes back as a warning naming the file, as Save a Copy reports it: +/// a 24-bit BMP of the transparent board is composited over white. +#[test] +fn export_warnings_reach_the_result() { + let (mut s, clear, white) = session(); + let dir = &tmp("warnings"); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "prefix": "", "format": "bmp", "artboards": [clear], "bmpBits": 24})).unwrap(); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("Clear.bmp: ") && w.contains("over white"))), "{r}"); + let opaque = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "prefix": "", "format": "png", "artboards": [white]})).unwrap(); + let warnings = opaque["warnings"].as_array().unwrap(); + assert!(warnings.iter().all(|w| w.as_str().is_some_and(|w| w.starts_with("White.png: ") && !w.contains("over white"))), "{opaque}"); +}