Merge PR #14321 (with #14361, #14292 and #14272) into #14381

Artboards to PDF keeps Include Overlapping Areas / Artboard Content
Only next to Reverse Page Order, and builds its pages through the shared
JPEG page helper with the scratch checks. The params doc lists both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-11-21 17:35:03 +01:00
commit 33d7f9d527
23 files changed
+2216 -41

No files matched your search

+285 -24
View File
@@ -15,8 +15,8 @@ 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::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file};
use crate::commands::{CommandSpec, color_param, int, int_i32, parse_hex};
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.
@@ -824,6 +824,148 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec<LayerId> {
}
}
/// 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<Option<NameBorder>> {
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::<f64>().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);
// 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(())
}
/// 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")
}
/// 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 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,
}
impl FileType {
/// Any other token is an extension for the encoder to pick by. It must be one plain extension:
/// `unknown.png` would name `<board>.unknown.png` and write a PNG, and a `/` would leave `dir`.
fn of(format: &str, cmd: &str) -> Result<Self> {
Ok(match format {
"png8" | "png-8" => FileType::Png8,
"png24" | "png-24" => FileType::Png24,
"targa" => FileType::Save("tga".into()),
"pdf" => FileType::Pdf,
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}`"))),
})
}
}
/// Formats whose file names Artboards to Files writes with a `-` for each space, as the reference
/// application does for PNG (and, per #13633, JPEG, BMP, Targa and TIFF). PSD keeps its spaces,
/// as do the formats the reference application was not measured with.
@@ -874,28 +1016,129 @@ fn collision_key(stem: &str) -> String {
}
/// File › Export › Artboards to Files: one `<prefix><artboard name>.<format>` per board, named by
/// [`artboard_file_stems`] (`abfiles-testRed-Board.png`, `abfiles-testRed Board.psd`).
/// [`artboard_file_stems`] (`abfiles-testRed-Board.png`, `abfiles-testRed Board.psd`), or for PDF one
/// `<prefix>.pdf`.
fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
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 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 overlapping = overlapping_param(p, cmd)?;
let doc = d.doc.clone();
let boards = chosen_documents(&doc, p, overlapping)?;
let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect();
let mut files = Vec::new();
for (one, name) in boards.iter().zip(artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str()))) {
let path = join(&dir, &format!("{name}.{format}"));
save_doc(one, &path, save)?;
files.push(path);
}
if files.is_empty() {
let guard = ScratchGuard::new(&doc)?;
let mut boards = chosen_documents(&doc, p, overlapping)?;
if boards.is_empty() {
return Err(bad(cmd, "no matching artboards"));
}
Ok(json!({"files": files}))
if let Some(o) = &border {
for one in &mut boards {
add_name_border(one, o, cmd)?;
}
}
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)), 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], "warnings": []}));
}
FileType::Png8 => None,
FileType::Png24 => Some("png".to_string()),
FileType::Save(ext) => Some(ext),
};
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();
let mut warnings = Vec::new();
for (mut one, name) in boards.into_iter().zip(stems) {
// Export Options of the file type (#13636): PNG-8 and PNG-24 take PNG's.
board.apply(&mut one, extension);
let path = join(&dir, &format!("{name}.{extension}"));
let (bytes, warned) = match &ext {
Some(_) if truecolour && one.mode != ColorMode::Rgb => encode(&rgb_copy(&one)?, &path, save)?,
Some(_) => encode(&one, &path, save)?,
// The PNG-8 writer does not interlace; say so, as the palette PNG path of a save does.
None if save.png_interlaced == Some(true) => (png8(&one, cmd)?, vec!["written without interlacing: the PNG-8 exporter does not interlace".to_owned()]),
None => (png8(&one, cmd)?, Vec::new()),
};
guard.check()?;
write_file(&path, &bytes)?;
warnings.extend(warned.into_iter().map(|w| format!("{name}.{extension}: {w}")));
files.push(path);
}
Ok(json!({"files": files, "warnings": warnings}))
}
/// 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<Self> {
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, cmd: &str) -> Result<Vec<u8>> {
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()
};
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)
}
/// `one` converted to RGB (its depth, layers and transparency kept), for a truecolour file.
fn rgb_copy(one: &Document) -> Result<Document> {
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. 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<f64>, cmd: &str) -> Result<Vec<u8>> {
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);
let mut surf = Surface::new(fmt);
let vals: Vec<f32> = 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).
@@ -951,24 +1194,27 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {
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 overlapping = overlapping_param(p, cmd)?;
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, overlapping)?.into_iter().rev() {
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<f32> = 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, cmd)?;
pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg));
}
if pages.is_empty() {
return Err(bad(cmd, "no matching artboards"));
}
if reverse {
pages.reverse();
}
guard.check()?;
write_file(&path, &raster_pdf(&pages))?;
Ok(json!({"path": path, "pages": pages.len()}))
}
@@ -1032,7 +1278,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "<prefix><artboard name>.<format>" 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|png24|png8|jpg|bmp|tga|tiff|psd|pdf|…"="png" (png24 = truecolour .png, png8 = indexed .png, tga = Targa; pdf = one multi-page <prefix>.pdf, bottom artboard first, pages at 72 ppi),"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 <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG, and the PDF pages),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false (PNG, PNG-24),"transparency":bool=true (PNG, PNG-8, PNG-24; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group),"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, warnings} (warnings: what a file could not hold, each "<file name>: <warning>"; one "<prefix><artboard name>.<extension>" 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
),
@@ -1040,20 +1286,32 @@ pub fn specs() -> Vec<CommandSpec> {
"file.export.artboardsToPdf",
"Artboards to PDF…",
&["File", "Export"],
r##"{"path":str (.pdf),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##,
r##"{"path":str (.pdf),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's page also shows the visible boards above it where they overlap it; artboard: Artboard Content Only),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##,
export_artboards,
artboards_to_pdf
),
]
}
#[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/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)]
#[path = "artboard_cmds/include_name_tests.rs"]
mod include_name_tests;
#[cfg(test)]
#[path = "artboard_cmds/from_group_reset_props_tests.rs"]
mod from_group_reset_props_tests;
@@ -1075,5 +1333,8 @@ mod pdf_overlapping_areas_tests;
#[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;
@@ -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<bool>,
/// PSD Preserve Artboard; `Some(false)` turns the board into a plain group.
preserve_artboard: Option<bool>,
/// 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<bool>,
}
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<Option<bool>> {
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_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)?;
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()),
_ => {}
}
}
}
}
@@ -0,0 +1,229 @@
//! 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<u8> {
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<u32> {
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!({"quality": -1}),
json!({"quality": 12.5}),
json!({"quality": 13}),
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");
}
}
/// 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}");
}
@@ -0,0 +1,192 @@
//! 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<String> {
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-testRed-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-testEmpty-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);
}
/// 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();
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");
// A token with a second extension or a path in it is not a file type either: `unknown.png`
// used to name `<board>.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);
}
@@ -0,0 +1,235 @@
//! 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();
}
/// 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.
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();
// Files are named <prefix><artboard name>, 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()
}
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: 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");
}
}
#[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());
}
@@ -0,0 +1,95 @@
//! 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 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<Value>, Vec<u8>) {
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();
(r, bytes)
}
/// Each page's size in points, in page order.
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 ")
.skip(1)
.map(|rest| {
let mut n = rest.split([' ', ']']).map(|v| v.parse::<f64>().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!({}));
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})), reversed(default));
}
#[test]
fn false_or_no_param_keeps_the_default_order() {
let (mut s, _) = session();
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}));
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})), reversed(default));
}
#[test]
fn a_non_boolean_value_is_an_error_not_a_panic() {
let (mut s, _) = session();
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}");
}
}
#[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);
}
+22
View File
@@ -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<photocraft_io::TgaBits>,
/// 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<photocraft_io::BmpBits>,
/// Embed the ICC profile in a flat file; unset, embed it. Artboards to Files' Include ICC
/// Profile (`"iccProfile"`).
pub embed_icc: Option<bool>,
/// PNG: write it interlaced (Adam7); unset, not. Artboards to Files' PNG Interlaced
/// (`"pngInterlaced"`).
pub png_interlaced: Option<bool>,
/// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16.
pub dpx_bits: Option<photocraft_io::DpxBits>,
/// 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<SaveOpts>) -> 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<SaveOpts>) -> 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);
@@ -0,0 +1,86 @@
//! 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() {
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");
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. 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();
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);
}
+1
View File
@@ -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;
+33 -1
View File
@@ -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;
@@ -1899,6 +1899,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)?;
}
@@ -1949,6 +1952,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)?;
}
@@ -2253,6 +2259,29 @@ fn tga_image(doc: &Document, img: Image, bits: Option<TgaBits>, 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<BmpBits>, warnings: &mut Vec<String>) -> Result<Image, IoError> {
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
@@ -2545,6 +2574,9 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions, ct
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());
}
+37
View File
@@ -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<TgaBits>,
/// 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<BmpBits>,
/// 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<Self> {
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")
+14
View File
@@ -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).
@@ -0,0 +1,231 @@
//! #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 craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::{Role, Toggled};
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"];
type H = Harness<'static, Box<PhotocraftApp>>;
fn harness() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
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();
let h = Harness::builder()
.with_size(egui::vec2(1440.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
fn open(h: &mut H, dir: &str, format: &str) -> DialogId {
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
set(h, dialog, "dir", json!(dir));
set(h, dialog, "prefix", json!("out"));
set(h, dialog, "format", json!(format));
dialog
}
/// Sets a field as automation (`ui.dialog.set`) does, then draws.
fn set(h: &mut H, dialog: DialogId, key: &str, v: Value) {
let ctx = h.ctx.clone();
h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, key, v).unwrap_or_else(|e| panic!("{key}: {e}"));
h.run_steps(4);
}
/// The option params OK sends to the command.
fn sent(h: &H, dialog: DialogId) -> Value {
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(dialog).unwrap();
let p = crate::filter_dialog::command_params(ARTBOARDS, form.fields());
assert!(p.as_object().unwrap().keys().all(|k| !k.contains('.') && k != "exportOptions"), "only plain params are sent: {p}");
Value::Object(OPTION_PARAMS.iter().filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect())
}
fn ticked(h: &H, label: &str) -> bool {
h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled() == Some(Toggled::True)
}
fn shown(h: &H, label: &str) -> bool {
h.query_all_by_label(label).next().is_some()
}
fn click(h: &mut H, role: Role, label: &str) {
h.get_by_role_and_label(role, label).click();
h.run_steps(4);
}
fn tick_export_options(h: &mut H) {
click(h, Role::CheckBox, "Export Options");
}
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, "png24");
assert!(!ticked(&h, "Export Options"));
assert!(!shown(&h, "Include ICC Profile") && !shown(&h, "Options"), "the Options section is hidden");
assert_eq!(sent(&h, dialog), json!({}), "no option reaches the command");
let below = h.get_by_role_and_label(Role::CheckBox, "Export Options").rect().top();
let format = h.query_all_by_label("File Type").next().unwrap().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, "png24");
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})),
// Targa is on the File Type list (#13635).
("tga", vec!["16bit", "24bit", "32bit"], json!({"tgaBits": 24, "iccProfile": true})),
("tiff", vec!["Image Compression", "Quality"], json!({"tiffCompression": "none", "iccProfile": true})),
("png24", 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_eq!(h.query_all_by_label("Include ICC Profile").count(), 1, "{format}: only the chosen type's rows show");
assert!(ticked(&h, "Include ICC Profile"), "{format}");
assert_eq!(sent(&h, dialog), defaults, "{format}");
}
assert!(ticked(&h, "Transparency") && !ticked(&h, "Interlaced"));
set(&mut h, dialog, "format", json!("bmp"));
let radio = |h: &H, 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"));
click(&mut h, Role::RadioButton, "32bit");
assert_eq!(sent(&h, dialog)["bmpBits"], json!(32));
// Each type keeps its own settings.
set(&mut h, dialog, "format", json!("png24"));
assert_eq!(sent(&h, dialog), json!({"transparency": true, "pngInterlaced": false, "iccProfile": true}));
set(&mut h, dialog, "format", json!("bmp"));
assert_eq!(sent(&h, dialog)["bmpBits"], json!(32));
// Unticked again: the section is hidden and nothing is sent.
tick_export_options(&mut h);
assert!(!shown(&h, "Include ICC Profile") && !shown(&h, "32bit") && !shown(&h, "Options"));
assert_eq!(sent(&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);
let ctx = h.ctx.clone();
assert!(h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "tiff.quality", json!(5)).is_err(), "the greyed Quality takes no input");
assert!(sent(&h, dialog).get("quality").is_none());
set(&mut h, dialog, "tiff.tiffCompression", json!("jpeg"));
assert_eq!(sent(&h, dialog), json!({"tiffCompression": "jpeg", "quality": 8.0, "iccProfile": true}));
set(&mut h, dialog, "tiff.quality", json!(5));
assert_eq!(sent(&h, dialog)["quality"], json!(5.0));
}
#[test]
fn the_quality_keeps_fractions_and_refuses_values_past_its_range() {
let mut h = harness();
let (_t, dir) = tmp();
let dialog = open(&mut h, &dir, "jpg");
tick_export_options(&mut h);
set(&mut h, dialog, "jpg.quality", json!(7.6));
let q = sent(&h, dialog)["quality"].as_f64().unwrap();
assert!((q - 7.6).abs() < 1e-4, "{q}");
let ctx = h.ctx.clone();
for bad in [json!(99), json!(-5), json!("abc")] {
assert!(h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "jpg.quality", bad.clone()).is_err(), "{bad}");
}
let q = sent(&h, dialog)["quality"].as_f64().unwrap();
assert!((q - 7.6).abs() < 1e-4, "a refused value leaves {q}");
}
#[test]
fn the_options_reach_the_written_file() {
let mut h = harness();
let (t, dir) = tmp();
let dialog = open(&mut h, &dir, "png24");
tick_export_options(&mut h);
click(&mut h, Role::CheckBox, "Interlaced");
click(&mut h, Role::CheckBox, "Transparency");
crate::dialogs::testing::confirm(h.state_mut(), dialog).unwrap();
let file = std::fs::read_dir(t.path()).unwrap().next().expect("a file was written").unwrap().path();
let png = std::fs::read(file).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, "png24");
tick_export_options(&mut h);
click(&mut h, Role::CheckBox, "Interlaced");
crate::dialogs::testing::confirm(h.state_mut(), dialog).unwrap();
h.run_steps(3);
let dialog = open(&mut h, &dir, "png24");
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"));
click(&mut h, Role::RadioButton, "16bit");
click(&mut h, Role::CheckBox, "Include ICC Profile");
assert_eq!(sent(&h, dialog), json!({"bmpBits": 16, "iccProfile": false}));
crate::dialogs::testing::confirm(h.state_mut(), dialog).unwrap();
h.run_steps(3);
assert!(h.state().framework.dialogs.open_dialogs().iter().all(|d| d.id != dialog), "OK closed the form");
let dialog = open(&mut h, &dir, "bmp");
assert_eq!(sent(&h, dialog), json!({"bmpBits": 24, "iccProfile": true}), "the last successful run's settings");
set(&mut h, dialog, "format", json!("png24"));
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}");
}
@@ -0,0 +1,174 @@
//! #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 craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::{Role, Toggled};
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";
type H = Harness<'static, Box<PhotocraftApp>>;
fn harness() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
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();
let h = Harness::builder()
.with_size(egui::vec2(1440.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
fn open(h: &mut H, command: &str) -> DialogId {
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, command, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
dialog
}
fn ticked(h: &H) -> bool {
h.get_by_role_and_label(Role::CheckBox, INCLUDE).accesskit_node().toggled() == Some(Toggled::True)
}
fn click(h: &mut H) {
h.get_by_role_and_label(Role::CheckBox, INCLUDE).click();
h.run_steps(4);
}
/// What OK sends to the command.
fn params(h: &H, dialog: DialogId) -> Value {
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(dialog).unwrap();
crate::filter_dialog::command_params(ARTBOARDS, form.fields())
}
/// Sets a field as automation (`ui.dialog.set`) does, then draws.
fn set(h: &mut H, dialog: DialogId, key: &str, v: Value) {
let ctx = h.ctx.clone();
h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, key, v).unwrap_or_else(|e| panic!("{key}: {e}"));
h.run_steps(4);
}
fn has_label(h: &H, label: &str) -> bool {
h.query_all_by_label(label).next().is_some()
}
/// The size of the first file the export wrote into `dir`.
fn written_size(dir: &std::path::Path) -> (u32, u32) {
let file = std::fs::read_dir(dir).unwrap().next().expect("a file was written").unwrap().path();
let name = file.to_string_lossy().into_owned();
let img = photocraft_io::import(&name, &std::fs::read(&file).unwrap()).unwrap().document;
(img.size.width, img.size.height)
}
#[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"));
let p = params(&h, dialog);
assert_eq!(p["includeName"], false);
assert!(p.get("font").is_none() && p.get("fontSize").is_none(), "no Name Options are sent while unticked: {p}");
click(&mut h);
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(&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!("#000000"));
assert!(p.get("extensionColor").is_none());
// The choices the rows offer: automation takes each, and refuses what is not offered.
for style in ["Regular", "Italic", "Bold", "Bold Italic", "Black"] {
set(&mut h, dialog, "fontStyle", json!(style));
}
let ctx = h.ctx.clone();
assert!(h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "fontStyle", json!("Light")).is_err());
set(&mut h, dialog, "font", json!("Arial"));
set(&mut h, dialog, "extension", json!("other"));
assert!(has_label(&h, "Canvas Extension Color"));
assert!(params(&h, dialog).get("extensionColor").is_some());
// Unticked again, the swatch goes with the rest.
click(&mut h);
assert!(!has_label(&h, "Canvas Extension Color") && !has_label(&h, "Font"));
}
#[test]
fn the_checkbox_is_kept_per_file_type() {
let mut h = harness();
let dialog = open(&mut h, ARTBOARDS);
set(&mut h, dialog, "format", json!("png24"));
click(&mut h);
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!("png24"));
assert!(ticked(&h), "PNG-24's tick comes back");
assert_eq!(params(&h, dialog)["includeName"], true);
}
#[test]
fn ok_runs_the_export_with_the_name_options() {
let mut h = harness();
let dialog = open(&mut h, ARTBOARDS);
// Removed when dropped, also when an assertion fails.
let dir = tempfile::tempdir().unwrap();
set(&mut h, dialog, "dir", json!(dir.path().to_string_lossy()));
set(&mut h, dialog, "format", json!("png24"));
click(&mut h);
set(&mut h, dialog, "extension", json!("black"));
crate::dialogs::testing::confirm(h.state_mut(), dialog).unwrap();
h.run_steps(2);
// A 64 x 64 board gets a border of (64 + 64) / 20 = 6 px on each side.
assert_eq!(written_size(dir.path()), (76, 76));
// A size that is not a number fails the run.
let failed = tempfile::tempdir().unwrap();
let p = json!({"dir": failed.path(), "format": "png", "includeName": true, "fontSize": "abc"});
assert!(h.state_mut().run(ARTBOARDS, p).is_err());
}
#[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);
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(dialog).unwrap();
assert!(form.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()));
set(&mut h, dialog, "format", json!("png24"));
click(&mut h);
assert!(ticked(&h), "PNG-24 ticked");
let ctx = h.ctx.clone();
h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "format", json!("jpg")).unwrap();
// OK in the same frame: no border around the board.
crate::dialogs::testing::confirm(h.state_mut(), dialog).unwrap();
assert_eq!(written_size(dir.path()), (64, 64));
}
@@ -0,0 +1,120 @@
//! #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 craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
const ARTBOARDS: &str = "file.export.artboardsToFiles";
const NAMES: [&str; 8] = ["BMP", "JPEG", "PDF", "PSD", "Targa", "TIFF", "PNG-8", "PNG-24"];
type H = Harness<'static, Box<PhotocraftApp>>;
fn harness() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
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();
let h = Harness::builder()
.with_size(egui::vec2(1440.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
fn open(h: &mut H, command: &str) -> DialogId {
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, command, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
dialog
}
fn field(h: &H, dialog: DialogId, key: &str) -> Option<Value> {
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(dialog)?;
serde_json::to_value(form.fields()).ok()?.get(key).cloned()
}
fn set(h: &mut H, dialog: DialogId, key: &str, value: Value) {
let ctx = h.ctx.clone();
h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, key, value).unwrap_or_else(|e| panic!("{key}: {e}"));
h.run_steps(2);
}
#[test]
fn file_type_list_is_the_reference_list_with_psd_chosen() {
let mut h = harness();
let dialog = open(&mut h, ARTBOARDS);
assert_eq!(field(&h, dialog, "format"), Some(json!("psd")), "PSD on first open");
for id in ["bmp", "jpg", "pdf", "psd", "tga", "tiff", "png8", "png24"] {
set(&mut h, dialog, "format", json!(id));
}
let ctx = h.ctx.clone();
for gone in ["png", "webp"] {
assert!(h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "format", json!(gone)).is_err(), "{gone} is not in the list");
}
set(&mut h, dialog, "format", json!("psd"));
// 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().is_some_and(|l| l.trim_end_matches(':') == "File Type"))
.expect("a File Type dropdown");
assert_eq!(combo.value().as_deref(), Some("PSD"));
combo.click();
h.run_steps(3);
// Opened, the list shows the eight names top to bottom in the reference order.
let ys: Vec<f32> = NAMES
.iter()
.map(|name| {
let tops: Vec<f32> = 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();
for (format, files) in [("png8", 2), ("pdf", 1), ("psd", 2)] {
let t = tempfile::tempdir().unwrap();
let dialog = open(&mut h, ARTBOARDS);
set(&mut h, dialog, "dir", json!(t.path()));
set(&mut h, dialog, "prefix", json!(format));
set(&mut h, dialog, "format", json!(format));
let ctx = h.ctx.clone();
crate::dialogs::confirm(h.state_mut(), &ctx, dialog).unwrap();
let mut written: Vec<std::path::PathBuf> = std::fs::read_dir(t.path()).unwrap().map(|e| e.unwrap().path()).collect();
written.sort();
assert_eq!(written.len(), files, "{format}: {written:?}");
for f in &written {
let bytes = std::fs::read(f).unwrap();
let name = f.to_string_lossy();
match format {
"png8" => assert_eq!(bytes[25], 3, "{name} is an indexed PNG"),
"pdf" => assert!(name.ends_with("pdf.pdf") && bytes.starts_with(b"%PDF-"), "{name}"),
_ => assert!(name.ends_with(".psd") && bytes.starts_with(b"8BPS"), "{name}"),
}
}
}
}
#[test]
fn layer_comps_to_files_keeps_its_list() {
let mut h = harness();
let dialog = open(&mut h, "file.export.layerCompsToFiles");
assert_eq!(field(&h, dialog, "format"), Some(json!("png")));
for id in ["png", "jpg", "psd", "tiff", "webp", "bmp"] {
set(&mut h, dialog, "format", json!(id));
}
}
@@ -0,0 +1,117 @@
//! #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 craft::ui::dialog::DialogId;
use egui::accesskit::{Role, Toggled};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
const COMMAND: &str = "file.export.artboardsToPdf";
type H = Harness<'static, Box<PhotocraftApp>>;
/// A document with two artboards of different sizes, so a page's MediaBox says which board it is.
fn harness() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
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();
let h = Harness::builder()
.with_size(egui::vec2(1440.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
/// Opens the dialog from its menu entry with File set to `path`.
fn open(h: &mut H, path: &str) -> DialogId {
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "path", json!(path)).unwrap();
h.run_steps(4);
dialog
}
fn confirm(h: &mut H, dialog: DialogId) -> Result<(), String> {
let ctx = h.ctx.clone();
let r = crate::dialogs::confirm(h.state_mut(), &ctx, dialog);
h.run_steps(4);
r
}
fn ticked(h: &H) -> bool {
h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").accesskit_node().toggled() == Some(Toggled::True)
}
fn tick(h: &mut H) {
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<u32> {
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::<f64>().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");
confirm(&mut h, 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));
confirm(&mut h, 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);
confirm(&mut h, 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!(!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();
h.run_steps(4);
}
let d = open(&mut h, &path);
assert!(ticked(&h), "a failed run leaves the remembered value alone");
let ctx = h.ctx.clone();
crate::dialogs::cancel(h.state_mut(), &ctx, d).unwrap();
}
+7 -3
View File
@@ -650,11 +650,15 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value {
}
}
// The exports to files take the JPEG quality only for a JPEG (a quality would make a WebP lossy).
if matches!(command, "file.export.artboardsToFiles" | "file.export.layersToFiles" | "file.export.layerCompsToFiles")
&& map.get("format").and_then(Value::as_str) != Some("jpg")
{
if matches!(command, "file.export.layersToFiles" | "file.export.layerCompsToFiles") && map.get("format").and_then(Value::as_str) != Some("jpg") {
map.remove("quality");
}
// Artboards to Files sends its Name Options only while Include Artboard Name is ticked (#13637), and the chosen
// file type's Export Options only while that box is ticked (#13636).
if command == "file.export.artboardsToFiles" {
crate::menus::view_cmds::strip_artboard_name_options(&mut map);
crate::menus::view_cmds::nest_artboard_export_options(&mut map);
}
// An emptied embedded LUT is no data: a stored empty `data` would be read over the chosen `lut`.
if command == "image.adjustments.colorLookup" && map.get("data").and_then(Value::as_str).is_some_and(str::is_empty) {
map.remove("data");
+9 -8
View File
@@ -1,5 +1,6 @@
//! #11481: File › Export › Artboards to Files (and Layers / Layer Comps to Files) has a JPEG
//! Quality row behind a Custom check box, as Batch has (#3956). The quality reaches the command
//! #11481: File › Export › Layers / Layer Comps to Files have a JPEG Quality row behind a Custom
//! check box, as Batch has (#3956). Artboards to Files has its quality in its Export Options
//! instead (#13636, `artboards_export_options_dialog_tests`). The quality reaches the command
//! only for a JPEG with Custom on: left alone, an export writes what the command writes with no
//! quality (the source JPEG's own quality, else the encoder default), a WebP stays lossless and
//! PNG has none. The forms are the hosted command forms; the tests drive them as automation does.
@@ -9,8 +10,8 @@ use craft::ui::patterns::form_dialogs::HostedParamDialog;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
const ARTBOARDS: &str = "file.export.artboardsToFiles";
const EXPORTS: [&str; 3] = [ARTBOARDS, "file.export.layersToFiles", "file.export.layerCompsToFiles"];
const COMPS: &str = "file.export.layerCompsToFiles";
const EXPORTS: [&str; 2] = [COMPS, "file.export.layersToFiles"];
fn app() -> (Box<PhotocraftApp>, egui::Context) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
@@ -74,7 +75,7 @@ fn direct(app: &mut PhotocraftApp, dir: &Path, format: &str, quality: Option<i64
if let Some(q) = quality {
p["quality"] = json!(q);
}
app.run(ARTBOARDS, p).unwrap();
app.run(COMPS, p).unwrap();
written(dir)
}
@@ -83,13 +84,13 @@ fn tmp() -> tempfile::TempDir {
}
#[test]
fn artboards_to_files_sends_a_custom_jpeg_quality() {
fn layer_comps_to_files_sends_a_custom_jpeg_quality() {
let (mut app, ctx) = app();
let via_dialog = tmp();
let via_command = tmp();
// Custom off: the quality row is greyed out for any format but JPEG, and an untouched JPEG export writes what
// the command writes with no quality.
let dialog = open(&mut app, &ctx, ARTBOARDS, via_dialog.path(), "png");
let dialog = open(&mut app, &ctx, COMPS, via_dialog.path(), "png");
assert!(app.framework.dialogs.set_json_field(&ctx, dialog, "quality", json!(5)).is_err(), "PNG: the quality row takes no input");
set(&mut app, &ctx, dialog, "format", json!("jpg"));
assert!(fields(&app, dialog).get("quality").is_none_or(Value::is_null), "no quality is sent while Custom is off");
@@ -100,7 +101,7 @@ fn artboards_to_files_sends_a_custom_jpeg_quality() {
let mut sizes = Vec::new();
for quality in [0, 3, 12] {
let (a, b) = (tmp(), tmp());
let dialog = open(&mut app, &ctx, ARTBOARDS, a.path(), "jpg");
let dialog = open(&mut app, &ctx, COMPS, a.path(), "jpg");
set(&mut app, &ctx, dialog, "quality", json!(quality));
assert_eq!(fields(&app, dialog)["quality"].as_f64(), Some(quality as f64), "the typed quality is the field's value");
let bytes = exported(&mut app, &ctx, dialog, a.path());
+8
View File
@@ -1021,9 +1021,15 @@ mod polygon_lasso_tests;
#[cfg(test)]
mod window_frame_tests;
#[cfg(test)]
mod artboards_export_options_dialog_tests;
#[cfg(test)]
mod artboards_overlap_dialog_tests;
#[cfg(test)]
mod artboards_to_files_types_tests;
#[cfg(test)]
mod artboards_to_pdf_reverse_tests;
#[cfg(test)]
mod browse_field_tests;
#[cfg(test)]
mod export_quality_tests;
@@ -1040,6 +1046,8 @@ mod pen_path_ownership_tests;
#[cfg(test)]
mod artboard_options_bar_tests;
#[cfg(test)]
mod artboards_include_name_dialog_tests;
#[cfg(test)]
mod doc_tab_menu_tests;
+1 -1
View File
@@ -19,7 +19,7 @@ mod dispatch;
mod options;
pub(crate) use arrange::document_is_floating;
pub(crate) use dialogs::write_copy;
pub(crate) use dialogs::{nest_artboard_export_options, strip_artboard_name_options, write_copy};
#[cfg(test)]
use dispatch::is_enabled_with_engine;
pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_without_document};
@@ -0,0 +1,106 @@
//! Artboards to Files' Export Options (#13636): a checkbox below File Type, unticked by default,
//! that shows an Options section with the chosen file type's settings. Each type keeps its own
//! settings (its own rows, keyed `<type>.<param>`); the command gets the plain params of the shown
//! type only while the checkbox is ticked, so an export without it writes what it wrote before.
//! The checkbox and every type's settings are rows of the form, so they are remembered after a
//! successful run only, as every remembered row is.
use super::{Label, Param, ParamKind, Value, opts};
use craft::ui::patterns::form_dialogs::DialogFields;
use craft::ui::value_drag::SliderScale;
use serde_json::Map;
pub(super) const COMMAND: &str = "file.export.artboardsToFiles";
/// The checkbox. The command never gets it.
const CHECKBOX: &str = "exportOptions";
/// The settings key of the type whose rows show now, `""` while none does: shell state the rows are shown by, kept
/// by [`derive`] before each pass, OK and automation write (one `visible_when` condition per row).
const SHOWN_TYPE: &str = "__exportOptionsType";
/// Whether the Options section shows (the checkbox is ticked and the type has options).
const SHOWN: &str = "__exportOptionsShown";
/// The settings keys of the types with options.
const KINDS: [&str; 6] = ["psd", "bmp", "tga", "jpg", "tiff", "png"];
/// 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" | "png24" => "png",
_ => return None,
})
}
/// Sets the shell keys the option rows are shown by from the checkbox and the File Type.
pub(super) fn derive(fields: &mut DialogFields) {
let shown = if fields.bool(CHECKBOX) == Some(true) { fields.text("format").and_then(kind) } else { None };
fields.set(SHOWN_TYPE, shown.unwrap_or(""));
fields.set(SHOWN, shown.is_some());
}
/// The rows below File Type: the checkbox, then each type's settings with the reference application's defaults, shown
/// only for the chosen type while the checkbox is ticked.
pub(super) fn rows() -> Vec<Param> {
let of = |kind: &str, param: &str, label: &'static str, row: ParamKind| Param::new(format!("{kind}.{param}"), label, row).visible_when(SHOWN_TYPE, kind);
let icc = |kind: &str| of(kind, "iccProfile", tl!("Include ICC Profile"), ParamKind::bool(true));
let quality = |kind: &str| of(kind, "quality", tl!("Quality"), ParamKind::range(0.0, 12.0, 8.0, SliderScale::Linear)).decimals(1);
let depth = |kind: &str, param: &str| {
of(kind, param, tl!("Depth"), ParamKind::radio(opts(&[("16", tl!("16bit")), ("24", tl!("24bit")), ("32", tl!("32bit"))]), Some("24".to_owned())))
};
let compression = opts(&[("none", tl!("None")), ("lzw", tl!("LZW")), ("zip", tl!("ZIP")), ("jpeg", tl!("JPEG"))]);
vec![
Param::new(CHECKBOX, tl!("Export Options"), ParamKind::bool(false)),
Param::section(Label::from(tl!("Options"))).visible_when(SHOWN, true),
of("psd", "maximizeCompatibility", tl!("Maximize Compatibility"), ParamKind::bool(true)),
of("psd", "preserveArtboard", tl!("Preserve Artboard"), ParamKind::bool(true)),
icc("psd"),
depth("bmp", "bmpBits"),
icc("bmp"),
// Targa, for when the File Type list offers it (#13635).
depth("tga", "tgaBits"),
icc("tga"),
quality("jpg"),
icc("jpg"),
of("tiff", "tiffCompression", tl!("Image Compression"), ParamKind::choice(compression, Some("none".to_owned()))),
// The TIFF quality applies to JPEG compression only.
quality("tiff").enabled_when("tiff.tiffCompression", "jpeg"),
icc("tiff"),
of("png", "transparency", tl!("Transparency"), ParamKind::bool(true)),
of("png", "pngInterlaced", tl!("Interlaced"), ParamKind::bool(false)),
icc("png"),
]
}
/// 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. 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<String, Value>) {
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<String> = map.keys().filter(|k| k.split_once('.').is_some_and(|(kind, _)| KINDS.contains(&kind))).cloned().collect();
let mut settings = Map::new();
for key in own {
let value = map.remove(&key);
if let (Some((kind, param)), Some(value)) = (key.split_once('.'), value)
&& Some(kind) == chosen
{
settings.insert(param.to_owned(), value);
}
}
// The quality comes from the options only.
map.remove("quality");
let jpeg_tiff = settings.get("tiffCompression").and_then(Value::as_str) == Some("jpeg");
for (param, value) in settings {
let value = match param.as_str() {
"bmpBits" | "tgaBits" => value.as_str().and_then(|bits| bits.parse::<u64>().ok()).map_or(value, Value::from),
"quality" if chosen == Some("tiff") && !jpeg_tiff => continue,
_ => value,
};
map.insert(param, value);
}
}
@@ -0,0 +1,78 @@
//! Artboards to Files' Include Artboard Name (#13637): a checkbox, unticked, kept per file type,
//! and while it is ticked the Name Options section (Font, Style, Size, Canvas Extension, Text).
//! The Canvas Extension Color swatch shows only with Other... chosen.
use super::{Param, ParamKind, Value, choice, json, named, opts};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
use serde_json::Map;
pub(super) const COMMAND: &str = "file.export.artboardsToFiles";
/// The checkbox, kept per file type.
const INCLUDE: &str = "includeName";
/// The tick of each file type the dialog has shown, `{format: bool}`: shell state, never a command parameter.
const BY_FORMAT: &str = "__includeNameByFormat";
/// The file type the checkbox's value belongs to now.
const FORMAT_SEEN: &str = "__includeNameFormat";
/// Whether the Canvas Extension Color row shows (the checkbox ticked and Other... chosen): shell state the row is
/// shown by, as a row takes one `visible_when` condition.
const OTHER_SHOWN: &str = "__extensionColorShown";
/// Before each pass, OK and automation write: a File Type changed since the last one puts the checkbox's value under
/// the type it was set for and brings back the new type's (unticked for a type not shown yet), so an OK right after a
/// control client picked another type sends that type's own tick. Then sets the colour row's shell key.
pub(super) fn derive(fields: &mut DialogFields) {
// The first build runs before the defaults are in: nothing to keep yet.
let Some(format) = fields.text("format").map(str::to_owned) else { return };
let seen = fields.text(FORMAT_SEEN).map(str::to_owned);
if seen.as_deref() != Some(format.as_str()) {
let mut kept = match fields.get(BY_FORMAT) {
Some(FieldValue::Json(Value::Object(kept))) => kept.clone(),
_ => Map::new(),
};
if let Some(seen) = seen {
kept.insert(seen, json!(fields.bool(INCLUDE).unwrap_or(false)));
}
let on = kept.get(&format).and_then(Value::as_bool).unwrap_or(false);
fields.set(INCLUDE, on);
fields.set(BY_FORMAT, FieldValue::Json(Value::Object(kept)));
fields.set(FORMAT_SEEN, format);
}
let other = fields.bool(INCLUDE) == Some(true) && fields.text("extension") == Some("other");
fields.set(OTHER_SHOWN, other);
}
/// The checkbox and the Name Options rows, which show only while it is ticked. `fonts` are the installed families.
pub(super) fn rows(fonts: &[String]) -> Vec<Param> {
let mut fonts = fonts.to_vec();
if !fonts.iter().any(|f| f == "Arial") {
fonts.insert(0, "Arial".into());
}
let shown = |row: Param| row.visible_when(INCLUDE, true);
let styles =
opts(&[("Regular", tl!("Regular")), ("Italic", tl!("Italic")), ("Bold", tl!("Bold")), ("Bold Italic", tl!("Bold Italic")), ("Black", tl!("Black"))]);
let extensions = opts(&[("white", tl!("White")), ("black", tl!("Black")), ("other", tl!("Other..."))]);
vec![
// Opens unticked, as the per-type ticks start over at every open.
Param::new(INCLUDE, tl!("Include Artboard Name"), ParamKind::bool(false)).not_remembered(),
shown(Param::section(tl!("Name Options"))),
// Font names are the fonts' own, never catalogue entries.
shown(choice("font", tl!("Font"), named(&fonts), "Arial").searchable()),
shown(choice("fontStyle", tl!("Style"), styles, "Regular").tooltip(tl!("Select the font style"))),
shown(Param::new("fontSize", tl!("Size (pt)"), ParamKind::text("12"))),
shown(choice("extension", tl!("Canvas Extension"), extensions, "white")),
Param::new("extensionColor", tl!("Canvas Extension Color"), ParamKind::color(Some([0.5, 0.5, 0.5]))).visible_when(OTHER_SHOWN, true),
shown(Param::new("textColor", tl!("Text"), ParamKind::color(Some([0.0, 0.0, 0.0])))),
]
}
/// The command params of the form's values `map`: the Name Options only while the checkbox is ticked (hidden rows keep
/// their values), the extension colour only with Other... chosen.
pub(crate) fn strip(map: &mut Map<String, Value>) {
if map.get(INCLUDE).and_then(Value::as_bool) != Some(true) {
for key in ["font", "fontStyle", "fontSize", "extension", "extensionColor", "textColor"] {
map.remove(key);
}
} else if map.get("extension").and_then(Value::as_str) != Some("other") {
map.remove("extensionColor");
}
}
+37 -4
View File
@@ -7,6 +7,13 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDi
use craft::ui::runtime::env::Label;
use craft::ui::runtime::requests::PathKind;
#[path = "artboard_export_options.rs"]
mod artboard_export_options;
pub(crate) use artboard_export_options::nest as nest_artboard_export_options;
#[path = "artboard_name_options.rs"]
mod artboard_name_options;
pub(crate) use artboard_name_options::strip as strip_artboard_name_options;
// ---------- dialogs and pickers in front of engine commands ----------
/// The command ids whose dialog is a hosted parameter form built by [`params_for`] (Open EXR Parts included).
@@ -50,10 +57,23 @@ fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec<Param>,
let title = crate::dialogs::filter_dialog::title_of(title);
let key = id.to_owned();
crate::dialogs::params::open_param(app, id, fields, fixed, move |fields: &mut DialogFields| {
derive(&key, fields);
ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields))
})
}
/// Brings a form's shell keys up to date with the values they follow, before each pass, OK and automation write (the
/// form's builder runs at each): a row takes one `visible_when` condition, so a row shown by two values is shown by a
/// shell key that combines them.
fn derive(id: &str, fields: &mut DialogFields) {
if id == artboard_export_options::COMMAND {
artboard_export_options::derive(fields);
}
if id == artboard_name_options::COMMAND {
artboard_name_options::derive(fields);
}
}
/// Choice options from `(id, label)` pairs whose labels are `tl!` literals at the call site.
fn opts(list: &[(&'static str, &'static str)]) -> Vec<(String, Label)> {
list.iter().map(|(id, label)| ((*id).to_owned(), Label::from(*label))).collect()
@@ -90,6 +110,12 @@ fn export_formats() -> Vec<(String, Label)> {
opts(&[("png", tl!("PNG")), ("jpg", tl!("JPEG")), ("psd", tl!("PSD")), ("tiff", tl!("TIFF")), ("webp", tl!("WebP")), ("bmp", tl!("BMP"))])
}
/// The reference application's File Type list of Artboards to Files, in its order (#13635). Format names, not
/// translated.
fn artboard_formats() -> Vec<(String, Label)> {
opts(&[("bmp", "BMP"), ("jpg", "JPEG"), ("pdf", "PDF"), ("psd", "PSD"), ("tga", "Targa"), ("tiff", "TIFF"), ("png8", "PNG-8"), ("png24", "PNG-24")])
}
/// The blending modes of the channel dialogs.
fn blend_modes() -> Vec<(String, Label)> {
opts(&[
@@ -281,7 +307,7 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
}
"file.export.artboardsToFiles" => {
let (_, _, name) = doc?;
plain(vec![
let mut rows = vec![
folder("dir", tl!("Destination"), dir),
Param::new("prefix", tl!("File Name Prefix"), ParamKind::text(stem(&name))),
// Include Overlapping Areas / Artboard Content Only, right below the prefix, with no caption (#13629).
@@ -293,9 +319,14 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
Some("overlapping".to_owned()),
),
),
choice("format", tl!("File Type"), export_formats(), "png"),
export_quality(),
])
// The reference application's list, PSD chosen when the dialog opens (#13635).
choice("format", tl!("File Type"), artboard_formats(), "psd"),
];
// Export Options and each file type's settings (#13636); the JPEG quality is one of them.
rows.extend(artboard_export_options::rows());
// Include Artboard Name and its Name Options (#13637).
rows.extend(artboard_name_options::rows(&crate::type_tool::families()));
plain(rows)
}
"file.export.artboardsToPdf" => {
let (_, _, name) = doc?;
@@ -312,6 +343,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
),
),
Param::new("quality", tl!("Quality"), ParamKind::int(Some(0), Some(12), 10)),
// Unticked on first open; the form remembers it as the last run left it (#13644).
Param::new("reversePageOrder", tl!("Reverse Page Order"), ParamKind::bool(false)),
])
}
"file.export.dataSetsAsFiles" => {