From c10673254be785d132ca00eaf3c892da2b4774dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 05:58:12 +0100 Subject: [PATCH 01/21] 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/21] 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 00b0f7e37fc..810a1024880 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 00000000000..9788e98d33e --- /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 00000000000..7b411641db2 --- /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 1f1bfd88ae2..4cb42276048 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 7928bf442c0..4e0905e91de 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 51c67b83e5c..f1e23b60632 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/21] 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/21] 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 00b0f7e37fc..009865fd392 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 00000000000..9be7249c32c --- /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 00000000000..f4eec3589f2 --- /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 eba2b9502d6..25f436b3ecd 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 53611d5007a..39614944106 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 f537ac2b418..526f3f2cab4 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 00000000000..0995e1be9b9 --- /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 cd5de48bba1..22c15511c72 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 7928bf442c0..b5198b51ee8 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 6194417a224..5ff7c7ab7ba 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 00000000000..77856b93576 --- /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 51c67b83e5c..b8182d72e0d 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 fc8c6f366431ce961ef59b23d91f51fbf185a917 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 07:55:02 +0100 Subject: [PATCH 05/21] Artboards to Files: Include Artboard Name with its Name Options (#13637) file.export.artboardsToFiles takes includeName, font, fontStyle, fontSize, extension (white, black, other with extensionColor, or a colour) and textColor. With the option on, flat file types get a border of (w + h) / 20 px on each side in the Canvas Extension colour and the board's name in the top border, left-aligned with the board; a size that is not a positive number fails before any file is written. PSD and PDF stay as today. The dialog has the Include Artboard Name checkbox, kept per file type, and the Name Options shown while it is ticked. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 121 ++++++++++- .../cmd/artboard_cmds/include_name_tests.rs | 203 ++++++++++++++++++ .../artboards_include_name_dialog_tests.rs | 129 +++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds/dialogs.rs | 114 +++++++++- 5 files changed, 559 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/include_name_tests.rs create mode 100644 crates/ui-egui/src/artboards_include_name_dialog_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37fc..fbbae0668b9 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -13,7 +13,7 @@ use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, color_param, int, int_i32}; +use crate::commands::{CommandSpec, color_param, int, int_i32, parse_hex}; use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; use crate::{EngineError, Result, Session}; @@ -675,17 +675,129 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec { } } +/// Artboards to Files' Include Artboard Name and its Name Options (#13637). +struct NameBorder { + /// `{"font", "fontStyle", "size", "color"}` for [`crate::type_cmds::apply_char_props`]. + style: Value, + /// The Canvas Extension colour, sRGB with alpha. + extension: [f32; 4], +} + +/// Photoshop's largest type size, in points. +const NAME_SIZE_MAX_PT: f64 = 1296.0; + +/// The Name Options of `file.export.artboardsToFiles`, or `None` with `includeName` off. A size +/// that is not a positive number fails the export, as in Photoshop ("the initial bounding +/// rectangle is empty"), before any file is written. +fn name_border_param(p: &Value, cmd: &str) -> Result> { + if !p.get("includeName").and_then(Value::as_bool).unwrap_or(false) { + return Ok(None); + } + // The dialog's Size field takes any text, so a numeric string counts as its number. + let size = match p.get("fontSize") { + None | Some(Value::Null) => Some(12.0), + Some(Value::String(t)) => t.trim().parse::().ok(), + Some(v) => v.as_f64(), + }; + let Some(size) = size.filter(|v| v.is_finite() && *v > 0.0) else { + return Err(bad(cmd, "the artboard name size must be a positive number of points")); + }; + let font = p.get("font").and_then(Value::as_str).filter(|f| !f.trim().is_empty()).unwrap_or("Arial"); + let font_style = p.get("fontStyle").and_then(Value::as_str).filter(|f| !f.trim().is_empty()).unwrap_or("Regular"); + let white = [1.0, 1.0, 1.0, 1.0]; + let extension = match p.get("extension") { + None | Some(Value::Null) => white, + Some(Value::String(c)) if c.eq_ignore_ascii_case("white") => white, + Some(Value::String(c)) if c.eq_ignore_ascii_case("black") => [0.0, 0.0, 0.0, 1.0], + // The dialog's Other...: the colour picked in its swatch. + Some(Value::String(c)) if c.eq_ignore_ascii_case("other") => color_param(cmd, p, "extensionColor", white)?, + Some(Value::String(c)) => parse_hex(c).ok_or_else(|| bad(cmd, "`extension` must be \"white\", \"black\", \"#rrggbb\" or [r, g, b]"))?, + Some(_) => color_param(cmd, p, "extension", white)?, + }; + let text = color_param(cmd, p, "textColor", [0.0, 0.0, 0.0, 1.0])?.map(|c| c.clamp(0.0, 1.0)); + let style = json!({"font": font, "fontStyle": font_style, "size": size.min(NAME_SIZE_MAX_PT), "color": text}); + Ok(Some(NameBorder { style, extension: extension.map(|c| c.clamp(0.0, 1.0)) })) +} + +/// The width of the name border on each side: a twentieth of width plus height, rounded. This +/// gives exactly Photoshop's measured borders: 18 px for 200 x 150, 20 for 200 x 200 and 60 for +/// 800 x 400. +fn name_border_width(w: u32, h: u32) -> u32 { + ((f64::from(w) + f64::from(h)) / 20.0).round() as u32 +} + +/// Include Artboard Name: extends `one` on all four sides by [`name_border_width`], fills the new +/// border with the Canvas Extension colour (a bottom layer, so the board keeps its own pixels) +/// and draws the board's name in the top border, its ink left-aligned with the board's left edge +/// and centred in the border's height. +fn add_name_border(one: &mut Document, o: &NameBorder, cmd: &str) -> Result<()> { + let (w, h) = (one.size.width, one.size.height); + let b = name_border_width(w, h); + let grown = |len: u32| b.checked_mul(2).and_then(|d| len.checked_add(d)).and_then(|n| i32::try_from(n).ok().map(|i| (n, i))); + let (Some((nw, nwi)), Some((nh, nhi)), Ok(bi)) = (grown(w), grown(h), i32::try_from(b)) else { + return Err(bad(cmd, format!("artboard `{}` is too large to add a name border", one.name))); + }; + let before = one.clone(); + for l in &mut one.layers { + crate::commands::translate_layer(&before, l, bi, bi); + crate::vector_cmds::translate_vectors(&before, l, f64::from(bi), f64::from(bi)); + } + crate::canvas_geom::transform_doc_marks(one, &Affine::translate(f64::from(bi), f64::from(bi))); + one.size = Size::new(nw, nh); + let fmt = one.pixel_format(); + let mut ring = Layer::raster("Canvas Extension", fmt); + if let Some(surf) = ring.surface_mut() { + let px = photocraft_raster::from_rgba(&fmt, o.extension); + let (x1, y1) = (nwi - bi, nhi - bi); + for r in [Rect::new(0, 0, nwi, bi), Rect::new(0, y1, nwi, nhi), Rect::new(0, bi, bi, y1), Rect::new(x1, bi, nwi, y1)] { + if !r.is_empty() { + surf.fill_rect(r, &px); + } + } + } + one.layers.insert(0, ring); + let mut style = photocraft_doc::text::CharStyle::default(); + crate::type_cmds::apply_char_props(&mut style, &o.style); + let mut t = photocraft_doc::TextLayer { text: one.name.clone(), ..Default::default() }; + t.runs = vec![photocraft_doc::text::TextRun { len: t.text.len(), style }]; + t.sync_summary(); + let dpi = one.resolution_dpi; + let layout = photocraft_text::shared().lock().unwrap_or_else(std::sync::PoisonError::into_inner).layout(&t, dpi); + if let Some([x0, y0, _, y1]) = photocraft_text::render::ink_bounds(&layout) { + let (dx, dy) = ((f64::from(bi) - x0).round(), (f64::from(bi) / 2.0 - (y0 + y1) / 2.0).round()); + if dx.is_finite() && dy.is_finite() { + t.transform = Affine::translate(dx, dy); + crate::type_cmds::refresh_at(dpi, fmt, &mut t); + let name = t.text.clone(); + one.layers.push(Layer::new(name, LayerContent::Text(t))); + } + } + Ok(()) +} + +/// File types Include Artboard Name leaves as they are: what it does there is not measured. +fn keeps_layers(format: &str) -> bool { + matches!(format, "psd" | "psb" | "pdf" | "pcraft") +} + /// File › Export › Artboards to Files: `__.` per board. 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 border = name_border_param(p, cmd)?.filter(|_| !keeps_layers(&format)); 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 boards = chosen_documents(&doc, p)?; + if let Some(o) = &border { + for one in &mut boards { + add_name_border(one, o, cmd)?; + } + } let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + 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}.{format}")); @@ -829,7 +941,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?,"includeName":bool=false (Include Artboard Name: a border of (w + h) / 20 px on each side, the name in the top one; psd and pdf keep their layers),"font":family="Arial","fontStyle":"Regular|Italic|Bold|Bold Italic|Black"="Regular","fontSize":pt|numeric str=12 (else an error),"extension":"white|black|other"|"#rrggbb"|[r,g,b]="white" (Canvas Extension; "other" takes "extensionColor":[r,g,b]),"textColor":"#rrggbb"|[r,g,b]=black} → {files}"##, export_artboards, artboards_to_files ), @@ -848,5 +960,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/include_name_tests.rs"] +mod include_name_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs new file mode 100644 index 00000000000..35734e32c3e --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -0,0 +1,203 @@ +//! Artboards to Files › Include Artboard Name (#13637): a border of the Canvas Extension colour +//! on all four sides, the board's name in the top one, at 8 and 16 bit; bad Name Options fail the +//! export before any file is written; without the option the output is today's. + +use super::*; + +const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; +const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; +const RED: [f32; 4] = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + +/// The spec's test document: 800 x 400, transparent, `Red Board` 0,0-200,150 (white, a red +/// layer at 20,20-120,100) and `Blue Board` 120,30-320,230 (white, a blue layer at 130,40-230,140). +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + board(&mut s, "Red Board", [0, 0, 200, 150], Rect::new(20, 20, 120, 100), RED); + board(&mut s, "Blue Board", [120, 30, 200, 200], Rect::new(130, 40, 230, 140), [30.0 / 255.0, 30.0 / 255.0, 220.0 / 255.0, 1.0]); + s +} + +fn board(s: &mut Session, name: &str, rect: [i32; 4], px: Rect, rgba: [f32; 4]) { + let r = s.execute("layer.new.artboard", json!({"rect": rect, "name": name, "background": "white"})).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + s.edit("px", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name.replace(" Board", ""), fmt); + l.surface_mut().unwrap().fill_rect(px, &photocraft_raster::from_rgba(&fmt, rgba)); + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); +} + +fn tmp(tag: &str) -> String { + let dir = std::env::temp_dir().join(format!("photocraft-abname-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.to_string_lossy().into_owned() +} + +/// Runs the export and reads every written PNG back, keyed by the board name in its file name. +fn export(s: &mut Session, dir: &str, extra: Value) -> Vec<(String, Document)> { + let mut p = json!({"dir": dir, "prefix": "t", "format": "png"}); + if let (Some(p), Value::Object(extra)) = (p.as_object_mut(), extra) { + p.extend(extra); + } + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let f = f.as_str().unwrap(); + let name = if f.contains("Red Board") { "Red" } else { "Blue" }; + (name.to_string(), photocraft_io::import("x.png", &std::fs::read(f).unwrap()).unwrap().document) + }) + .collect() +} + +fn find<'a>(files: &'a [(String, Document)], name: &str) -> &'a Document { + &files.iter().find(|(n, _)| n == name).unwrap().1 +} + +fn px(d: &Document, x: i32, y: i32) -> [f32; 4] { + photocraft_compose::flatten(d).get(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) +} + +fn on() -> Value { + json!({"includeName": true}) +} + +#[test] +fn the_border_width_is_a_twentieth_of_width_plus_height() { + // The three borders measured in the reference application. + assert_eq!(name_border_width(200, 150), 18); + assert_eq!(name_border_width(200, 200), 20); + assert_eq!(name_border_width(800, 400), 60); +} + +#[test] +fn the_boards_get_the_measured_sizes_with_their_content_unchanged_inside() { + for depth in [8, 16] { + let mut s = session(depth); + let plain = export(&mut s, &tmp(&format!("plain{depth}")), json!({})); + let named = export(&mut s, &tmp(&format!("named{depth}")), on()); + let (red, blue) = (find(&named, "Red"), find(&named, "Blue")); + assert_eq!((red.size.width, red.size.height), (236, 186), "{depth} bit"); + assert_eq!((blue.size.width, blue.size.height), (240, 240), "{depth} bit"); + // Content at 18..218 x 18..168, pixel for pixel the file without the option. + let (before, after) = (photocraft_compose::flatten(find(&plain, "Red")), photocraft_compose::flatten(red)); + for y in (0..150).step_by(7) { + for x in (0..200).step_by(7) { + assert!(close(before.get(x, y), after.get(x + 18, y + 18)), "{depth} bit at {x},{y}"); + } + } + assert!(close(px(red, 18 + 50, 18 + 50), RED), "{depth} bit"); + assert!(close(px(red, 18, 18), WHITE), "{depth} bit: the board's own white"); + // The border is opaque white on every side. + for (x, y) in [(0, 0), (235, 185), (5, 100), (230, 100), (100, 180), (17, 17)] { + assert!(close(px(red, x, y), WHITE), "{depth} bit at {x},{y}"); + } + } +} + +#[test] +fn the_name_sits_in_the_top_border_from_the_boards_left_edge() { + let mut s = session(8); + let files = export(&mut s, &tmp("text"), on()); + for (name, border) in [("Red", 18), ("Blue", 20)] { + let img = photocraft_compose::flatten(find(&files, name)); + let w = find(&files, name).size.width as i32; + let dark: Vec<(i32, i32)> = (0..border).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] < 0.5).collect(); + assert!(!dark.is_empty(), "{name}: the name is drawn in the top border"); + let x0 = dark.iter().map(|p| p.0).min().unwrap(); + assert!((x0 - border).abs() <= 1, "{name}: ink starts at the board's left edge, got {x0}"); + let (y0, y1) = (dark.iter().map(|p| p.1).min().unwrap(), dark.iter().map(|p| p.1).max().unwrap()); + assert!(y0 > 0 && y1 < border - 1, "{name}: ink inside the border, rows {y0}..{y1}"); + // Black text by default. + assert!(dark.iter().any(|&(x, y)| close(img.get(x, y), BLACK)), "{name}"); + } +} + +#[test] +fn canvas_extension_black_fills_the_border_black() { + let mut s = session(8); + let files = export(&mut s, &tmp("black"), json!({"includeName": true, "extension": "black", "textColor": [1.0, 1.0, 1.0]})); + let red = find(&files, "Red"); + for (x, y) in [(0, 0), (235, 185), (5, 100), (230, 100), (100, 180)] { + assert!(close(px(red, x, y), BLACK), "at {x},{y}"); + } + assert!(close(px(red, 18, 18), WHITE), "the board keeps its own white"); + // An "#rrggbb" extension colour too. + let files = export(&mut s, &tmp("hex"), json!({"includeName": true, "extension": "#00ff00"})); + assert!(close(px(find(&files, "Red"), 2, 100), [0.0, 1.0, 0.0, 1.0])); + // The dialog's Other... sends the swatch colour along. + let files = export(&mut s, &tmp("other"), json!({"includeName": true, "extension": "other", "extensionColor": [0.0, 0.0, 1.0]})); + assert!(close(px(find(&files, "Red"), 2, 100), [0.0, 0.0, 1.0, 1.0])); +} + +#[test] +fn without_the_option_the_output_is_todays() { + let mut s = session(8); + for extra in [json!({}), json!({"includeName": false, "fontSize": "abc"})] { + let files = export(&mut s, &tmp("off"), extra); + let red = find(&files, "Red"); + assert_eq!((red.size.width, red.size.height), (200, 150)); + assert!(close(px(red, 50, 50), RED)); + } + // PSD keeps its layers: the option leaves it as it is today. + let d = tmp("psd"); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "format": "psd", "includeName": true})).unwrap(); + for f in r["files"].as_array().unwrap() { + let psd = photocraft_io::import("x.psd", &std::fs::read(f.as_str().unwrap()).unwrap()).unwrap().document; + assert!(matches!((psd.size.width, psd.size.height), (200, 150) | (200, 200)), "{:?}", psd.size); + } +} + +#[test] +fn a_size_that_is_not_a_positive_number_fails_and_writes_nothing() { + let mut s = session(8); + for size in [json!("abc"), json!(""), json!("0"), json!(0), json!(-3), json!("-1"), json!("inf"), json!({"x": 1}), json!([12])] { + let d = tmp("bad"); + let before = s.active().unwrap().doc.clone(); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); + assert!(err.contains("size"), "{size}: {err}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "{size}: no file written"); + assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len(), "{size}: source unchanged"); + } + // A numeric string is its number, as the dialog's free text field sends it. + let files = export(&mut s, &tmp("str"), json!({"includeName": true, "fontSize": " 9 "})); + assert_eq!(find(&files, "Red").size.width, 236); +} + +#[test] +fn bad_name_options_never_panic() { + let mut s = session(8); + let d = tmp("junk"); + for p in [ + json!({"extension": "purple"}), + json!({"extension": [f64::MAX, -1.0, 2.0]}), + json!({"extension": {"r": 1}}), + json!({"extension": "#12"}), + json!({"textColor": "zz"}), + json!({"textColor": [1, 2]}), + json!({"font": 7, "fontStyle": null}), + json!({"font": "", "fontStyle": "No Such Style"}), + json!({"font": "No Such Font Family", "fontSize": 1e300}), + json!({"fontSize": 1e-30}), + json!({"includeName": "yes"}), + ] { + let mut p = p; + p["dir"] = json!(d); + if p.get("includeName").is_none() { + p["includeName"] = json!(true); + } + let _ = s.execute("file.export.artboardsToFiles", p); + } + assert!(s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "extension": "purple"})).is_err()); +} diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs new file mode 100644 index 00000000000..ef4938e680e --- /dev/null +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -0,0 +1,129 @@ +//! #13637: the Artboards to Files dialog has Include Artboard Name (unticked), kept per file type; +//! ticking it shows the Name Options (Font Arial, Style Regular, Size 12 pt, Canvas Extension +//! White / Black / Other..., Text black), and OK passes them to `file.export.artboardsToFiles`. +//! Layer Comps to Files has none of it. +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 INCLUDE: &str = "Include Artboard Name"; + +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})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).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 +} + +fn ticked(h: &Harness<'_, PhotocraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, INCLUDE).accesskit_node().toggled() == Some(Toggled::True) +} + +fn params(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(dialog).unwrap().fields) +} + +fn set(h: &mut Harness<'_, PhotocraftApp>, dialog: u64, key: &str, v: Value) { + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert(key.into(), v); + h.run_steps(4); +} + +/// Labels of the rows the dialog shows now. +fn has_label(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.query_all_by_label(label).next().is_some() +} + +#[test] +fn the_checkbox_starts_unticked_and_ticking_it_shows_the_name_options_with_their_defaults() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + assert!(!ticked(&h)); + assert!(!has_label(&h, "Name Options") && !has_label(&h, "Font:") && !has_label(&h, "Canvas Extension:")); + assert_eq!(params(&mut h, dialog)["includeName"], false); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h)); + for label in ["Name Options", "Font:", "Style", "Size (pt)", "Canvas Extension:", "Text:"] { + assert!(has_label(&h, label), "{label} is shown"); + } + // The Other... colour swatch only with Other... chosen. + assert!(!has_label(&h, "Canvas Extension Color")); + let p = params(&mut h, dialog); + assert_eq!(p["includeName"], true); + assert_eq!((&p["font"], &p["fontStyle"], &p["fontSize"], &p["extension"]), (&json!("Arial"), &json!("Regular"), &json!("12"), &json!("white"))); + assert_eq!(p["textColor"], json!([0.0, 0.0, 0.0])); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + let choices = &fields["__choices"]; + assert_eq!(choices["fontStyle"], json!(["Regular", "Italic", "Bold", "Bold Italic", "Black"])); + assert_eq!(choices["extension"], json!(["white", "black", "other"])); + assert!(choices["font"].as_array().unwrap().iter().any(|f| f == "Arial")); + assert_eq!(fields["__labels"]["other"], "Other..."); + set(&mut h, dialog, "extension", json!("other")); + assert!(has_label(&h, "Canvas Extension Color")); +} + +#[test] +fn the_checkbox_is_kept_per_file_type() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h)); + set(&mut h, dialog, "format", json!("psd")); + assert!(!ticked(&h), "PSD keeps its own, unticked"); + assert!(!has_label(&h, "Font:")); + set(&mut h, dialog, "format", json!("tiff")); + assert!(!ticked(&h)); + set(&mut h, dialog, "format", json!("png")); + assert!(ticked(&h), "PNG's tick comes back"); + assert_eq!(params(&mut h, dialog)["includeName"], true); +} + +#[test] +fn ok_runs_the_export_with_the_name_options() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let dir = std::env::temp_dir().join(format!("photocraft-abname-ui-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + set(&mut h, dialog, "dir", json!(dir.to_string_lossy())); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + set(&mut h, dialog, "extension", json!("black")); + let p = params(&mut h, dialog); + let r = h.state_mut().run(ARTBOARDS, p).unwrap(); + let file = r["files"][0].as_str().unwrap().to_string(); + let img = photocraft_io::import("x.png", &std::fs::read(&file).unwrap()).unwrap().document; + // A 64 x 64 board gets a border of (64 + 64) / 20 = 6 px on each side. + assert_eq!((img.size.width, img.size.height), (76, 76)); + // A size that is not a number fails the run. + set(&mut h, dialog, "fontSize", json!("abc")); + let p = params(&mut h, dialog); + assert!(h.state_mut().run(ARTBOARDS, p).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn layer_comps_to_files_has_no_artboard_name() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + assert_eq!(h.query_all_by_role_and_label(Role::CheckBox, INCLUDE).count(), 0); + assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("includeName").is_none()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c0..44af308cdf9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1076,6 +1076,8 @@ mod pen_path_ownership_tests; #[cfg(test)] mod artboard_options_bar_tests; #[cfg(test)] +mod artboards_include_name_dialog_tests; +#[cfg(test)] mod background_eraser_bar_angle_tests; #[cfg(test)] mod brush_alt_digit_smoothing_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5c..0ccd7f084ef 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -152,6 +152,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { } labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string) }; + per_format_state(f); let keys = form_keys(f); let mut browse: Option = None; egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { @@ -162,7 +163,25 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { { continue; } + if !shown(f, &k) { + continue; + } + if let Some(title) = f.get("__sections").and_then(|m| m.get(&k)).and_then(Value::as_str) { + ui.label(egui::RichText::new(title).font(crate::theme::semibold(13.0))); + ui.end_row(); + } let v = f.get(&k).cloned().unwrap_or(Value::Null); + // A key named in `__swatches` is an sRGB `[r, g, b]` (0..1) edited with a colour swatch. + let swatch = f.get("__swatches").and_then(Value::as_array).is_some_and(|s| s.iter().any(|n| n.as_str() == Some(k.as_str()))); + if swatch && let Some(rgb) = v.as_array() { + ui.label(label(&k)); + let byte = |i: usize| (rgb.get(i).and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as u8; + let mut c = [byte(0), byte(1), byte(2)]; + crate::widgets::color_edit_button_srgb(ui, &mut c, &crate::color_picker_ui::title_for(&label(&k))).on_hover_text(label(&k)); + f.insert(k, json!(c.map(|b| f64::from(b) / 255.0))); + ui.end_row(); + continue; + } if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { let label = ui.label(tl!("File Naming")); let mut naming = v.as_str().unwrap_or_default().to_owned(); @@ -206,13 +225,18 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { json!(b) } Value::String(s) => { - ui.label(label(&k)); + let name = ui.label(label(&k)); + if let Some(tip) = f.get("__tooltips").and_then(|m| m.get(&k)).and_then(Value::as_str) { + name.on_hover_text(tip); + } let mut s = s.clone(); match choices.get(&k).and_then(Value::as_array) { Some(opts) => { - // Action and set names are the user's own text, never catalogue entries. - let action_names = matches!(k.as_str(), "action" | "set") - && matches!(f.get("__command").and_then(Value::as_str), Some("file.automate.batch" | "file.automate.createDroplet")); + // Action and set names are the user's own text, never catalogue entries; + // nor are the choices of a key in `__literal` (font names). + let action_names = (matches!(k.as_str(), "action" | "set") + && matches!(f.get("__command").and_then(Value::as_str), Some("file.automate.batch" | "file.automate.createDroplet"))) + || f.get("__literal").and_then(Value::as_array).is_some_and(|l| l.iter().any(|n| n.as_str() == Some(k.as_str()))); let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), if action_names { o.to_string() } else { label(o) })).collect(); let refs: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); @@ -277,8 +301,59 @@ const BATCH_QUALITY: &str = "__batchQuality"; /// is not JPEG or Custom is off: shell state, never command parameters. const JPEG_CUSTOM: &str = "__jpegCustom"; const JPEG_QUALITY: &str = "__jpegQuality"; +/// The checkboxes a form keeps per file type (`__perFormat`, keys of the `format` field), the +/// values kept for the other types, and the type they belong to now (#13637): shell state. +const PER_FORMAT_STATE: &str = "__perFormatState"; +const FORMAT_SEEN: &str = "__formatSeen"; /// 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; 5] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, PER_FORMAT_STATE, FORMAT_SEEN]; + +/// When the `format` field has changed, keeps the `__perFormat` keys' values under the type they +/// were set for and brings back the new type's (their value at open for a type not seen yet), as +/// Artboards to Files keeps Include Artboard Name per file type. +fn per_format_state(f: &mut Map) { + let Some(keys) = f.get("__perFormat").and_then(Value::as_array).cloned() else { return }; + let format = f.get("format").and_then(Value::as_str).unwrap_or_default().to_string(); + let seen = f.get(FORMAT_SEEN).and_then(Value::as_str).unwrap_or_default().to_string(); + if format == seen { + return; + } + let orig = f.get("__formOrig").cloned().unwrap_or(Value::Null); + let mut state = f.get(PER_FORMAT_STATE).and_then(Value::as_object).cloned().unwrap_or_default(); + let mut old = Map::new(); + for k in keys.iter().filter_map(Value::as_str) { + old.insert(k.to_string(), f.get(k).cloned().unwrap_or(Value::Null)); + let kept = state.get(&format).and_then(|m| m.get(k)).or_else(|| orig.get(k)).cloned(); + if let Some(v) = kept { + f.insert(k.to_string(), v); + } + } + state.insert(seen, Value::Object(old)); + f.insert(PER_FORMAT_STATE.into(), Value::Object(state)); + f.insert(FORMAT_SEEN.into(), json!(format)); +} + +/// A key named in `__shownBy` is shown only while the checkbox it names is on, or, for a +/// `[key, value]` pair, while that choice is `value`; and only while the key it names is shown. +fn shown(f: &Map, k: &str) -> bool { + shown_at(f, k, 0) +} + +fn shown_at(f: &Map, k: &str, depth: u8) -> bool { + // A chain longer than this (or a cycle) shows the field rather than recursing on. + if depth > 8 { + return true; + } + let (by, on) = match f.get("__shownBy").and_then(|m| m.get(k)) { + Some(Value::String(by)) => (by.as_str(), f.get(by.as_str()).and_then(Value::as_bool) == Some(true)), + Some(Value::Array(pair)) => match (pair.first().and_then(Value::as_str), pair.get(1)) { + (Some(by), Some(want)) => (by, f.get(by) == Some(want)), + _ => return true, + }, + _ => return true, + }; + on && shown_at(f, by, depth + 1) +} /// 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,9 +582,34 @@ 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"]}) + // Include Artboard Name, kept per file type, and its Name Options (#13637). + json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, + "includeName": false, "font": "Arial", "fontStyle": "Regular", "fontSize": "12", "extension": "white", "extensionColor": [0.5, 0.5, 0.5], + "textColor": [0.0, 0.0, 0.0], + "__order": ["dir", "prefix", "format", "quality", "includeName", "font", "fontStyle", "fontSize", "extension", "extensionColor", "textColor"], + "__perFormat": ["includeName"], PER_FORMAT_STATE: {}, FORMAT_SEEN: "png", + "__shownBy": {"font": "includeName", "fontStyle": "includeName", "fontSize": "includeName", "extension": "includeName", + "extensionColor": ["extension", "other"], "textColor": "includeName"}, + "__sections": {"font": tl!("Name Options")}, + "__swatches": ["extensionColor", "textColor"], + "__literal": ["font"], + "__tooltips": {"fontStyle": tl!("Select the font style")}, + "__labels": {"includeName": tl!("Include Artboard Name"), "font": tl!("Font:"), "fontStyle": tl!("Style"), "fontSize": tl!("Size (pt)"), + "extension": tl!("Canvas Extension:"), "white": tl!("White"), "black": tl!("Black"), "other": tl!("Other..."), + "extensionColor": tl!("Canvas Extension Color"), "textColor": tl!("Text:"), + "Regular": tl!("Regular"), "Italic": tl!("Italic"), "Bold": tl!("Bold"), "Bold Italic": tl!("Bold Italic"), "Black": tl!("Black")}}) }; - dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) + let mut choices = json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}); + if id == "file.export.artboardsToFiles" { + let mut fonts: Vec = crate::type_tool::families().to_vec(); + if !fonts.iter().any(|f| f == "Arial") { + fonts.insert(0, "Arial".into()); + } + choices["font"] = json!(fonts); + choices["fontStyle"] = json!(["Regular", "Italic", "Bold", "Bold Italic", "Black"]); + choices["extension"] = json!(["white", "black", "other"]); + } + dialog(app, fields, choices) } "file.export.artboardsToPdf" => { let (_, _, name) = doc?; From 806b851e547f71c13610b38d51ba9532b28500b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:19:13 +0100 Subject: [PATCH 06/21] 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 810a1024880..381369a7026 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 9788e98d33e..3e30ef06200 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 3764fa82ed56f90e876588b1d095c24f2fb94376 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:35:58 +0100 Subject: [PATCH 07/21] Artboards to Files: keep the artboard name inside the top border A name size taller than the border is cut at the border instead of drawing over the board. The tests clean up their export folders with tempfile guards, and the default text colour check allows anti-aliased ink. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 14 ++++- .../cmd/artboard_cmds/include_name_tests.rs | 55 +++++++++++++++---- .../artboards_include_name_dialog_tests.rs | 8 +-- 3 files changed, 58 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index fbbae0668b9..2e9ef649e34 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -768,8 +768,18 @@ fn add_name_border(one: &mut Document, o: &NameBorder, cmd: &str) -> Result<()> if dx.is_finite() && dy.is_finite() { t.transform = Affine::translate(dx, dy); crate::type_cmds::refresh_at(dpi, fmt, &mut t); - let name = t.text.clone(); - one.layers.push(Layer::new(name, LayerContent::Text(t))); + // Only the top border takes the name: ink of a size taller than the border is cut + // there, never drawn over the board (the file is flat, so the type need not stay + // editable). + if let Some(cache) = &t.cache { + let r = cache.content_bounds().intersect(&Rect::new(0, 0, nwi, bi)); + if !r.is_empty() { + let px = cache.try_read_region(r).map_err(|e| bad(cmd, e.to_string()))?; + let mut clipped = Surface::new(cache.format()); + clipped.write_region(r, &px); + one.layers.push(Layer::new(t.text.clone(), LayerContent::Raster(clipped))); + } + } } } Ok(()) diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs index 35734e32c3e..0846e49bb15 100644 --- a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -31,11 +31,23 @@ fn board(s: &mut Session, name: &str, rect: [i32; 4], px: Rect, rgba: [f32; 4]) .unwrap(); } -fn tmp(tag: &str) -> String { - let dir = std::env::temp_dir().join(format!("photocraft-abname-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir.to_string_lossy().into_owned() +/// An empty export folder, removed when dropped (also when an assertion fails). +struct Tmp { + _dir: tempfile::TempDir, + path: String, +} + +impl std::ops::Deref for Tmp { + type Target = str; + fn deref(&self) -> &str { + &self.path + } +} + +fn tmp(tag: &str) -> Tmp { + let dir = tempfile::Builder::new().prefix(&format!("photocraft-abname-{tag}-")).tempdir().unwrap(); + let path = dir.path().to_string_lossy().into_owned(); + Tmp { _dir: dir, path } } /// Runs the export and reads every written PNG back, keyed by the board name in its file name. @@ -119,8 +131,27 @@ fn the_name_sits_in_the_top_border_from_the_boards_left_edge() { assert!((x0 - border).abs() <= 1, "{name}: ink starts at the board's left edge, got {x0}"); let (y0, y1) = (dark.iter().map(|p| p.1).min().unwrap(), dark.iter().map(|p| p.1).max().unwrap()); assert!(y0 > 0 && y1 < border - 1, "{name}: ink inside the border, rows {y0}..{y1}"); - // Black text by default. - assert!(dark.iter().any(|&(x, y)| close(img.get(x, y), BLACK)), "{name}"); + // Black text by default: the darkest ink is near black and neutral (small anti-aliased + // glyphs may not reach pure black with every font). + let ink = dark.iter().map(|&(x, y)| img.get(x, y)).min_by(|a, b| a[0].total_cmp(&b[0])).unwrap(); + assert!(ink[0] < 0.3 && (ink[0] - ink[1]).abs() < 0.02 && (ink[0] - ink[2]).abs() < 0.02, "{name}: {ink:?}"); + } +} + +#[test] +fn a_name_taller_than_the_border_never_draws_over_the_board() { + let mut s = session(8); + let plain = export(&mut s, &tmp("plain-big"), json!({})); + for size in [72, 400, 1296] { + let named = export(&mut s, &tmp("big"), json!({"includeName": true, "fontSize": size})); + let (before, after) = (photocraft_compose::flatten(find(&plain, "Red")), photocraft_compose::flatten(find(&named, "Red"))); + for y in 0..150 { + for x in (0..200).step_by(3) { + assert!(close(before.get(x, y), after.get(x + 18, y + 18)), "{size} pt at {x},{y}"); + } + } + // The cut name still shows in the border. + assert!((0..18).any(|y| (18..236).any(|x| after.get(x, y)[0] < 0.5)), "{size} pt"); } } @@ -152,7 +183,7 @@ fn without_the_option_the_output_is_todays() { } // PSD keeps its layers: the option leaves it as it is today. let d = tmp("psd"); - let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "format": "psd", "includeName": true})).unwrap(); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "format": "psd", "includeName": true})).unwrap(); for f in r["files"].as_array().unwrap() { let psd = photocraft_io::import("x.psd", &std::fs::read(f.as_str().unwrap()).unwrap()).unwrap().document; assert!(matches!((psd.size.width, psd.size.height), (200, 150) | (200, 200)), "{:?}", psd.size); @@ -165,9 +196,9 @@ fn a_size_that_is_not_a_positive_number_fails_and_writes_nothing() { for size in [json!("abc"), json!(""), json!("0"), json!(0), json!(-3), json!("-1"), json!("inf"), json!({"x": 1}), json!([12])] { let d = tmp("bad"); let before = s.active().unwrap().doc.clone(); - let err = s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); assert!(err.contains("size"), "{size}: {err}"); - assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "{size}: no file written"); + assert_eq!(std::fs::read_dir(&*d).unwrap().count(), 0, "{size}: no file written"); assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len(), "{size}: source unchanged"); } // A numeric string is its number, as the dialog's free text field sends it. @@ -193,11 +224,11 @@ fn bad_name_options_never_panic() { json!({"includeName": "yes"}), ] { let mut p = p; - p["dir"] = json!(d); + p["dir"] = json!(&*d); if p.get("includeName").is_none() { p["includeName"] = json!(true); } let _ = s.execute("file.export.artboardsToFiles", p); } - assert!(s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "extension": "purple"})).is_err()); + assert!(s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "includeName": true, "extension": "purple"})).is_err()); } diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs index ef4938e680e..0532489b412 100644 --- a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -100,10 +100,9 @@ fn the_checkbox_is_kept_per_file_type() { fn ok_runs_the_export_with_the_name_options() { let mut h = harness(); let dialog = open(&mut h, ARTBOARDS); - let dir = std::env::temp_dir().join(format!("photocraft-abname-ui-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - set(&mut h, dialog, "dir", json!(dir.to_string_lossy())); + // Removed when dropped, also when an assertion fails. + let dir = tempfile::tempdir().unwrap(); + set(&mut h, dialog, "dir", json!(dir.path().to_string_lossy())); h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); h.run_steps(4); set(&mut h, dialog, "extension", json!("black")); @@ -117,7 +116,6 @@ fn ok_runs_the_export_with_the_name_options() { set(&mut h, dialog, "fontSize", json!("abc")); let p = params(&mut h, dialog); assert!(h.state_mut().run(ARTBOARDS, p).is_err()); - let _ = std::fs::remove_dir_all(&dir); } #[test] From abdcbbd7917dbda419ad6b44e03adaa4e5ae4526 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:53:18 +0100 Subject: [PATCH 08/21] WIP: Artboards to PDF: Reverse Page Order option (#13644) From dd5acdc6e19ac9d5da865d1a345469db56a74099 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 09:04:03 +0100 Subject: [PATCH 09/21] Artboards to PDF: Reverse Page Order option (#13644) The dialog gets a Reverse Page Order checkbox, unticked on first open and remembered after a successful run; file.export.artboardsToPdf takes reversePageOrder (default false), which writes the default page order the other way round. A non-boolean value is an error. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 13 ++- .../pdf_reverse_page_order_tests.rs | 96 +++++++++++++++++++ .../src/artboards_to_pdf_reverse_tests.rs | 92 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds.rs | 2 +- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 15 ++- 7 files changed, 220 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs create mode 100644 crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37fc..e2cebb3f13f 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -751,6 +751,11 @@ 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)); + // Reverse Page Order (#13644): the default page order the other way round. + let reverse = match p.get("reversePageOrder") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`reversePageOrder` must be true or false"))?, + }; 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]); @@ -766,6 +771,9 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } + if reverse { + pages.reverse(); + } write_file(&path, &raster_pdf(&pages))?; Ok(json!({"path": path, "pages": pages.len()})) } @@ -837,7 +845,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, + r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board)"##, export_artboards, artboards_to_pdf ), @@ -848,5 +856,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] +mod pdf_reverse_page_order_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs new file mode 100644 index 00000000000..dc23d5858b0 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs @@ -0,0 +1,96 @@ +//! Artboards to PDF's Reverse Page Order (#13644), on the measured document: 800 x 400 with Red, +//! Blue and Empty Board, bottom to top. The boards have three different sizes, so each page's +//! MediaBox says which board it is. + +use super::*; + +/// The measured document, and the ids of Red, Blue and Empty Board (bottom to top). +fn session() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": 8, "resolution": 72})).unwrap(); + let mut board = |rect: [i64; 4], name: &str| { + let r = s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap(); + r["layer"].as_u64().unwrap() + }; + let ids = [board([0, 0, 200, 150], "Red Board"), board([120, 30, 200, 200], "Blue Board"), board([600, 0, 100, 100], "Empty Board")]; + (s, ids) +} + +/// Runs the export with `params` (plus a fresh path) and returns its result. +fn export(s: &mut Session, params: Value, tag: &str) -> (Result, Vec) { + let dir = std::env::temp_dir().join(format!("photocraft-pdf-reverse-{}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = join(&dir.to_string_lossy(), "boards.pdf"); + let mut params = params; + params["path"] = json!(path); + let r = s.execute("file.export.artboardsToPdf", params); + let bytes = std::fs::read(&path).unwrap_or_default(); + let _ = std::fs::remove_dir_all(&dir); + (r, bytes) +} + +/// Each page's size in points, in page order. +fn page_sizes(s: &mut Session, params: Value, tag: &str) -> Vec<(u32, u32)> { + let (r, bytes) = export(s, params, tag); + r.unwrap(); + let text = String::from_utf8_lossy(&bytes).into_owned(); + text.split("/MediaBox [0 0 ") + .skip(1) + .map(|rest| { + let mut n = rest.split([' ', ']']).map(|v| v.parse::().unwrap().round() as u32); + (n.next().unwrap(), n.next().unwrap()) + }) + .collect() +} + +fn reversed(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> { + v.reverse(); + v +} + +#[test] +fn reverse_page_order_turns_the_default_order_round() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({}), "default"); + assert_eq!(default.len(), 3); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(100, 100), (200, 150), (200, 200)], "one page per board"); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true}), "reverse"), reversed(default)); +} + +#[test] +fn false_or_no_param_keeps_the_default_order() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({}), "none"); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false}), "false"), default); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null}), "null"), default); +} + +#[test] +fn chosen_artboards_come_in_the_reversed_order_too() { + let (mut s, [red, blue, _]) = session(); + let chosen = json!([red, blue]); + let default = page_sizes(&mut s, json!({"artboards": chosen}), "chosen"); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(200, 150), (200, 200)], "only Red and Blue Board"); + assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true}), "chosen-reverse"), reversed(default)); +} + +#[test] +fn a_non_boolean_value_is_an_error_not_a_panic() { + let (mut s, _) = session(); + for (i, v) in [json!("yes"), json!(1), json!([true]), json!({"on": true})].into_iter().enumerate() { + let (r, bytes) = export(&mut s, json!({"reversePageOrder": v}), &format!("bad-{i}")); + let e = r.unwrap_err().to_string(); + assert!(e.contains("reversePageOrder"), "{e}"); + assert!(bytes.is_empty(), "nothing is written for {v}"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToPdf").unwrap(); + assert!(spec.params.contains(r#""reversePageOrder":bool=false"#), "{}", spec.params); +} diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs new file mode 100644 index 00000000000..b4b0129d08b --- /dev/null +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -0,0 +1,92 @@ +//! #13644: the Artboards to PDF dialog has a Reverse Page Order checkbox. It is unticked on first +//! open, reaches the command, and reopens as the last successful run left it. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const COMMAND: &str = "file.export.artboardsToPdf"; + +/// A document with two artboards of different sizes, so a page's MediaBox says which board it is. +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})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 200, 150], "name": "Low"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [250, 0, 100, 100], "name": "High"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, path: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("path".into(), json!(path)); + h.run_steps(4); + dialog +} + +fn ticked(h: &Harness<'_, PhotocraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").accesskit_node().toggled() == Some(Toggled::True) +} + +fn tick(h: &mut Harness<'_, PhotocraftApp>) { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").click(); + h.run_steps(2); +} + +/// Each page's width in points, in page order. +fn page_widths(path: &str) -> Vec { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); + text.split("/MediaBox [0 0 ").skip(1).map(|rest| rest.split(' ').next().unwrap().parse::().unwrap().round() as u32).collect() +} + +#[test] +fn the_checkbox_starts_unticked_and_reverses_the_pages() { + let t = tempfile::tempdir().unwrap(); + let path = t.path().join("plain.pdf").to_string_lossy().into_owned(); + let mut h = harness(); + let d = open(&mut h, &path); + assert!(!ticked(&h), "unticked on first open"); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + let plain = page_widths(&path); + assert_eq!(plain.len(), 2); + + let path = t.path().join("reversed.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + assert!(ticked(&h)); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + let mut want = plain; + want.reverse(); + assert_eq!(page_widths(&path), want); +} + +#[test] +fn a_successful_run_is_remembered_a_failed_one_is_not() { + let t = tempfile::tempdir().unwrap(); + let mut h = harness(); + let path = t.path().join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + + // Reopens ticked; untick it and fail the run (the destination is a file, not a folder). + let blocked = t.path().join("file"); + std::fs::write(&blocked, b"x").unwrap(); + let bad = blocked.join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &bad); + assert!(ticked(&h), "remembered after a successful run"); + tick(&mut h); + assert!(!ticked(&h)); + assert!(crate::dialogs::confirm(h.state_mut(), d).is_err()); + + let d = open(&mut h, &path); + assert!(ticked(&h), "a failed run leaves the remembered value alone"); + h.state_mut().ui.close_dialog(d); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba1..49939bb18d4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1057,6 +1057,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, mut d: Dialog) -> Result String { } /// Handle menu commands that need a shell action or a parameter dialog before execution. +/// Artboards to PDF remembers Reverse Page Order after a successful run (#13644). +pub(crate) fn remember_artboards_to_pdf(app: &mut PhotocraftApp, params: &Value) { + let Some(reverse) = params.get("reversePageOrder").and_then(Value::as_bool) else { return }; + app.session.prefs.edit(|prefs| prefs.dialogs.insert("file.export.artboardsToPdf".into(), json!({"reversePageOrder": reverse}))); +} + pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if id == "file.closeAll" || id == "file.closeOthers" { // Keep the remaining document's view (views are index-aligned with documents). @@ -514,7 +520,14 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + // Reverse Page Order starts unticked and reopens as the last successful run left it (#13644). + let reverse = app.session.prefs().dialogs.get(id).and_then(|v| v.get("reversePageOrder")).and_then(Value::as_bool).unwrap_or(false); + dialog( + app, + json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10, "reversePageOrder": reverse, "__order": ["path", "quality", "reversePageOrder"], + "__labels": {"reversePageOrder": tl!("Reverse Page Order")}}), + json!({}), + ) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] From e72dc193ae9534d64946a293107067e211b3e5a8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 10:15:05 +0100 Subject: [PATCH 10/21] Artboards to PDF reverse tests: export into a fresh temporary folder Co-Authored-By: Claude Opus 5.5 --- .../pdf_reverse_page_order_tests.rs | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs index dc23d5858b0..b3009e12511 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs @@ -16,22 +16,21 @@ fn session() -> (Session, [u64; 3]) { (s, ids) } -/// Runs the export with `params` (plus a fresh path) and returns its result. -fn export(s: &mut Session, params: Value, tag: &str) -> (Result, Vec) { - let dir = std::env::temp_dir().join(format!("photocraft-pdf-reverse-{}-{tag}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = join(&dir.to_string_lossy(), "boards.pdf"); +/// Runs the export with `params` (plus a path in a fresh temporary folder) and returns its result +/// and the bytes written (empty when nothing was). +fn export(s: &mut Session, params: Value) -> (Result, Vec) { + let dir = tempfile::tempdir().unwrap(); + let path = join(&dir.path().to_string_lossy(), "boards.pdf"); let mut params = params; params["path"] = json!(path); let r = s.execute("file.export.artboardsToPdf", params); let bytes = std::fs::read(&path).unwrap_or_default(); - let _ = std::fs::remove_dir_all(&dir); (r, bytes) } /// Each page's size in points, in page order. -fn page_sizes(s: &mut Session, params: Value, tag: &str) -> Vec<(u32, u32)> { - let (r, bytes) = export(s, params, tag); +fn page_sizes(s: &mut Session, params: Value) -> Vec<(u32, u32)> { + let (r, bytes) = export(s, params); r.unwrap(); let text = String::from_utf8_lossy(&bytes).into_owned(); text.split("/MediaBox [0 0 ") @@ -51,38 +50,38 @@ fn reversed(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> { #[test] fn reverse_page_order_turns_the_default_order_round() { let (mut s, _) = session(); - let default = page_sizes(&mut s, json!({}), "default"); + let default = page_sizes(&mut s, json!({})); assert_eq!(default.len(), 3); let mut sorted = default.clone(); sorted.sort_unstable(); assert_eq!(sorted, [(100, 100), (200, 150), (200, 200)], "one page per board"); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true}), "reverse"), reversed(default)); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true})), reversed(default)); } #[test] fn false_or_no_param_keeps_the_default_order() { let (mut s, _) = session(); - let default = page_sizes(&mut s, json!({}), "none"); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false}), "false"), default); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null}), "null"), default); + let default = page_sizes(&mut s, json!({})); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false})), default); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null})), default); } #[test] fn chosen_artboards_come_in_the_reversed_order_too() { let (mut s, [red, blue, _]) = session(); let chosen = json!([red, blue]); - let default = page_sizes(&mut s, json!({"artboards": chosen}), "chosen"); + let default = page_sizes(&mut s, json!({"artboards": chosen})); let mut sorted = default.clone(); sorted.sort_unstable(); assert_eq!(sorted, [(200, 150), (200, 200)], "only Red and Blue Board"); - assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true}), "chosen-reverse"), reversed(default)); + assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true})), reversed(default)); } #[test] fn a_non_boolean_value_is_an_error_not_a_panic() { let (mut s, _) = session(); - for (i, v) in [json!("yes"), json!(1), json!([true]), json!({"on": true})].into_iter().enumerate() { - let (r, bytes) = export(&mut s, json!({"reversePageOrder": v}), &format!("bad-{i}")); + for v in [json!("yes"), json!(1), json!([true]), json!({"on": true})] { + let (r, bytes) = export(&mut s, json!({"reversePageOrder": v})); let e = r.unwrap_err().to_string(); assert!(e.contains("reversePageOrder"), "{e}"); assert!(bytes.is_empty(), "nothing is written for {v}"); From 05092c4fa8e0f2b8e66f3320d8dbe97a36f8cc86 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 22:30:19 +0100 Subject: [PATCH 11/21] 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 248eabc7da6..61740c4214a 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 3b6b44d1c89a818f8458f5c081b9363e7b04b395 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:02:50 +0100 Subject: [PATCH 12/21] 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 8db9463d159..f6b09d0ddda 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -913,11 +913,11 @@ mod file_names_tests; #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] -#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] -mod pdf_reverse_page_order_tests; -#[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] +mod pdf_reverse_page_order_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; From a8975b1505f5df0874ce72e9a757723c0f1a69b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:57:29 +0100 Subject: [PATCH 13/21] Artboards to Files include-name tests: match main's file names Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds/include_name_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs index 0846e49bb15..228cbf022e0 100644 --- a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -63,7 +63,8 @@ fn export(s: &mut Session, dir: &str, extra: Value) -> Vec<(String, Document)> { .iter() .map(|f| { let f = f.as_str().unwrap(); - let name = if f.contains("Red Board") { "Red" } else { "Blue" }; + // Files are named , spaces as hyphens (#13633). + let name = if f.contains("Red-Board") { "Red" } else { "Blue" }; (name.to_string(), photocraft_io::import("x.png", &std::fs::read(f).unwrap()).unwrap().document) }) .collect() From 2f0ac3215f75af77dbdb4d08052c26f4aeefaf99 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:22:45 +0100 Subject: [PATCH 14/21] 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 61740c4214a..fa6452ee7ab 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 0ac435e4fca..7ca2b2b4e94 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 00000000000..da0443310bd --- /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 0848d7c51b852e4475b34183dae8b52f4ae24a3f Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:05:38 +0100 Subject: [PATCH 15/21] Address CodeRabbit review: per-type tick when a control client sets the file type ui.dialog.set of `format` changed the field without bringing back the new type's Include Artboard Name, so an OK before the next frame sent the tick of the type it left. dialog_set now runs per_format_state right after a `format` change. Co-Authored-By: Claude Opus 5.5 --- .../artboards_include_name_dialog_tests.rs | 22 +++++++++++++++++++ crates/ui-egui/src/control/dispatch.rs | 5 +++++ crates/ui-egui/src/menus/view_cmds.rs | 2 +- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 5 +++-- 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs index 0532489b412..33c8aa14cd4 100644 --- a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -125,3 +125,25 @@ fn layer_comps_to_files_has_no_artboard_name() { assert_eq!(h.query_all_by_role_and_label(Role::CheckBox, INCLUDE).count(), 0); assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("includeName").is_none()); } + +/// A control client that picks another file type and confirms before the dialog is drawn again +/// exports with that type's own Include Artboard Name, not the tick of the type it left. +#[test] +fn a_file_type_set_by_a_control_client_brings_its_own_tick_at_once() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let dir = tempfile::tempdir().unwrap(); + set(&mut h, dialog, "dir", json!(dir.path().to_string_lossy())); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h), "PNG ticked"); + let ctx = h.ctx.clone(); + let (req, _rx) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": dialog, "field": "format", "value": "jpg"})); + assert!(matches!(crate::control::handle(h.state_mut(), &ctx, &req), crate::control::Outcome::Done(_))); + assert_eq!(params(&mut h, dialog)["includeName"], false, "JPEG keeps its own, unticked"); + // OK in the same frame: no border around the board. + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + let file = r["files"][0].as_str().unwrap().to_string(); + let img = photocraft_io::import("x.jpg", &std::fs::read(&file).unwrap()).unwrap().document; + assert_eq!((img.size.width, img.size.height), (64, 64)); +} diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 86a036a66b5..af7a7a5d60d 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1146,6 +1146,11 @@ fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { d.fields.remove("sourceLayer"); } d.fields.insert(field.to_string(), value); + // A new file type brings back its own per-type checkboxes now, not on the next frame: + // an OK before then would send the previous type's (#13637). + if field == "format" { + crate::view_cmds::per_format_state(&mut d.fields); + } // A Color Picker's colour shows in its target dialog at once, as a drag would. crate::color_picker_ui::live_preview::sync(app); ok(Value::Null) diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 60d2fadd775..89ef64d7ce8 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::{per_format_state, 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/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 4f9d4098284..39150c7c91b 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -339,8 +339,9 @@ const RESET_SHELL_KEYS: [&str; 5] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, P /// When the `format` field has changed, keeps the `__perFormat` keys' values under the type they /// were set for and brings back the new type's (their value at open for a type not seen yet), as -/// Artboards to Files keeps Include Artboard Name per file type. -fn per_format_state(f: &mut Map) { +/// Artboards to Files keeps Include Artboard Name per file type. Also run when a control client +/// sets `format`, so an OK before the next frame sends the new type's values. +pub(crate) fn per_format_state(f: &mut Map) { let Some(keys) = f.get("__perFormat").and_then(Value::as_array).cloned() else { return }; let format = f.get("format").and_then(Value::as_str).unwrap_or_default().to_string(); let seen = f.get(FORMAT_SEEN).and_then(Value::as_str).unwrap_or_default().to_string(); From ad131b391ec096563494cab65250182fa91829bf Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:41:29 +0100 Subject: [PATCH 16/21] 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 da0443310bd..38f0e71e6c3 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 20b36b91ae4b9c8843abec29a3ecdf29713b753a Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:34:27 +0100 Subject: [PATCH 17/21] Address CodeRabbit review: check that the blocked Artboards to PDF run fails The reverse-order memory test now asserts that the run into a blocked folder really fails (an error or the status bar's error) and writes nothing, before it checks that the dialog reopens with the last successful value. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs index abef5f2f691..ebc7371bb75 100644 --- a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -99,7 +99,11 @@ fn a_successful_run_is_remembered_a_failed_one_is_not() { assert!(ticked(&h), "remembered after a successful run"); tick(&mut h); assert!(!ticked(&h)); - let _ = confirm(&mut h, d); + assert!(!h.state().ui.status_error, "the first run succeeded: {}", h.state().ui.status); + let r = confirm(&mut h, d); + // The run fails, so it must not be what the next open remembers. + assert!(r.is_err() || h.state().ui.status_error, "the blocked run fails: {r:?}, status {}", h.state().ui.status); + assert!(!std::path::Path::new(&bad).exists(), "the blocked run writes nothing"); if h.state().framework.dialogs.get_dyn(d).is_some() { let ctx = h.ctx.clone(); crate::dialogs::cancel(h.state_mut(), &ctx, d).unwrap(); From c30a5bfbd7c16665ed229da785b54a6a0dcbe7da Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:36:29 +0100 Subject: [PATCH 18/21] 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 38f0e71e6c3..cb2d21be19f 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 fa3f08a3d10..4d78ec06063 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 19/21] 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 c4e183fc4a4..fc4070f8ed5 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 ebf88dd06f3..36446c1fbb5 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 20/21] 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 c299a349087..b12104ab70e 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 b1bfff3d30f..ad3ac65415a 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 21/21] 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 452ff707587..267c17ad481 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 9be7249c32c..354b2cdf5c7 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 f4eec3589f2..62345e5668c 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}"); +}