Merge PR #14292 (Artboards to Files Export Options and File Type list) into #14361

Artboards to PDF keeps its Reverse Page Order and gains the scratch checks before the write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-11-21 17:32:48 +01:00
commit 3955245a67
18 files changed
+1363 -38

No files matched your search

+147 -21
View File
@@ -16,7 +16,7 @@ use photocraft_raster::Surface;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, color_param, int, int_i32};
use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file};
use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, stem, str_param, write_file};
use crate::{EngineError, Result, Session};
/// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages.
@@ -807,6 +807,33 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec<LayerId> {
}
}
/// 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.
@@ -857,12 +884,13 @@ 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 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 = match p.get("content") {
@@ -874,18 +902,112 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
},
};
let doc = d.doc.clone();
let guard = ScratchGuard::new(&doc)?;
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() {
if boards.is_empty() {
return Err(bad(cmd, "no matching artboards"));
}
Ok(json!({"files": files}))
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).
@@ -946,18 +1068,12 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`reversePageOrder` must be true or false"))?,
};
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, false)?.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() {
@@ -966,6 +1082,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {
if reverse {
pages.reverse();
}
guard.check()?;
write_file(&path, &raster_pdf(&pages))?;
Ok(json!({"path": path, "pages": pages.len()}))
}
@@ -1029,7 +1146,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)} → {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
),
@@ -1044,10 +1161,19 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[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)]
@@ -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);
}
+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,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));
}
}
+5 -3
View File
@@ -650,11 +650,13 @@ 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 the chosen file type's Export Options, and only while the box is ticked (#13636).
if command == "file.export.artboardsToFiles" {
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());
+4
View File
@@ -1021,9 +1021,13 @@ 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;
+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, 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);
}
}
+27 -4
View File
@@ -7,6 +7,10 @@ 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;
// ---------- 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 +54,20 @@ 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);
}
}
/// 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 +104,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 +301,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 +313,12 @@ 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());
plain(rows)
}
"file.export.artboardsToPdf" => {
let (_, _, name) = doc?;