From c57c51efca5dcf36ffcc67c91c3a7c95543d4be8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 06:33:12 +0100 Subject: [PATCH 01/33] WIP: Artboards to Files: Export Options per file type (#13636) From 71d11f4e447bf1cefb07ea057875e1d1b6a94626 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 07:05:08 +0100 Subject: [PATCH 02/33] Artboards to Files: Export Options per file type (#13636) The dialog gets an Export Options checkbox below File Type (unticked by default) that shows the chosen type's options with the reference application's defaults: PSD Maximize Compatibility / Preserve Artboard, BMP and Targa Depth, JPEG Quality, TIFF Image Compression with Quality (greyed unless JPEG), PNG Transparency / Interlaced, and Include ICC Profile for each. They are sent only while the checkbox is on and are remembered per type after a successful run, not after a failed one. file.export.artboardsToFiles takes iccProfile, bmpBits, pngInterlaced, transparency and preserveArtboard next to the existing save options, and refuses bad values. 16-bit BMP and JPEG-compressed TIFF are refused as unsupported: the shared encoders write neither yet. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 15 +- .../src/cmd/artboard_cmds/export_options.rs | 99 ++++++++ .../cmd/artboard_cmds/export_options_tests.rs | 212 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/save.rs | 22 ++ crates/io/src/flat.rs | 31 ++- crates/io/src/lib.rs | 37 +++ .../artboards_export_options_dialog_tests.rs | 212 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/export_quality_tests.rs | 21 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds.rs | 2 +- .../view_cmds/artboard_export_options.rs | 191 ++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 24 +- 13 files changed, 851 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/export_options.rs create mode 100644 crates/engine/src/cmd/artboard_cmds/export_options_tests.rs create mode 100644 crates/ui-egui/src/artboards_export_options_dialog_tests.rs create mode 100644 crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..009865fd39 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -14,7 +14,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::{CommandSpec, color_param, int, int_i32}; -use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; +use crate::file_cmds::{encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; use crate::{EngineError, Result, Session}; /// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages. @@ -680,12 +680,13 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); - let save = SaveOpts::from_params(s, p, cmd)?; + let (save, board) = export_options::parse(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + for (i, mut one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + board.apply(&mut one, &format); // Names may be identical, or collide after sanitizing or filesystem case folding. let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{format}")); @@ -829,7 +830,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files}"##, export_artboards, artboards_to_files ), @@ -844,6 +845,12 @@ pub fn specs() -> Vec { ] } +#[path = "artboard_cmds/export_options.rs"] +mod export_options; + +#[cfg(test)] +#[path = "artboard_cmds/export_options_tests.rs"] +mod export_options_tests; #[cfg(test)] #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; diff --git a/crates/engine/src/cmd/artboard_cmds/export_options.rs b/crates/engine/src/cmd/artboard_cmds/export_options.rs new file mode 100644 index 0000000000..9be7249c32 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/export_options.rs @@ -0,0 +1,99 @@ +//! Artboards to Files' Export Options (#13636): the per-file-type settings beyond the format. +//! Each one is optional; without any, an export writes what it wrote before. +//! +//! - `"iccProfile": bool`: embed the document's ICC profile (PSD: its ICC resource). Unset, as +//! before: flat files embed it, a PSD only when the document has a profile of its own. +//! - `"bmpBits": 16 | 24 | 32`: BMP depth. 16 is refused: the encoder writes 24 and 32 only. +//! - `"pngInterlaced": bool`: an Adam7-interlaced PNG. +//! - `"transparency": bool`: PNG; `false` composites each board over white, so the file has no alpha. +//! - `"preserveArtboard": bool`: PSD; `false` writes the board as a plain group. +//! - `"tiffCompression": "none" | "lzw" | "zip"`: as Save As; `"jpeg"` is refused, the TIFF +//! encoder has no JPEG compression yet. +//! - `"quality": 0..12` (JPEG), `"maximizeCompatibility": bool` (PSD) and `"tgaBits": 24 | 32` +//! (Targa) as for every save ([`SaveOpts::from_params`]). + +use photocraft_color::Color; +use photocraft_doc::{Document, LayerContent}; +use serde_json::Value; + +use crate::file_cmds::SaveOpts; +use crate::{EngineError, Result, Session}; + +/// What the options change in each board's document before it is written. +#[derive(Debug, Clone, Copy, Default)] +pub(super) struct BoardOptions { + /// PNG Transparency; `Some(false)` puts a white Background under the board. + transparency: Option, + /// PSD Preserve Artboard; `Some(false)` turns the board into a plain group. + preserve_artboard: Option, + /// Include ICC Profile; `Some(false)` leaves a PSD's ICC resource out, `Some(true)` writes + /// one even for a document without a profile of its own. + icc_profile: Option, +} + +fn bad(cmd: &str, msg: String) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg } +} + +/// `key` in `p` as a bool; absent or null: `None`. Anything else is a bad parameter of `cmd`. +fn bool_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(v) => Err(bad(cmd, format!("`{key}` must be true or false, got {v}"))), + } +} + +/// The save options and the per-board changes `p` asks for. +pub(super) fn parse(s: &Session, p: &Value, cmd: &str) -> Result<(SaveOpts, BoardOptions)> { + if p.get("tiffCompression").and_then(Value::as_str) == Some("jpeg") { + return Err(bad(cmd, "JPEG compression in a TIFF is not supported yet; use \"none\", \"lzw\" or \"zip\"".into())); + } + match p.get("quality") { + None | Some(Value::Null) => {} + Some(v) if v.as_f64().is_some() => {} + Some(v) => return Err(bad(cmd, format!("`quality` must be a number from 0 to 12, got {v}"))), + } + let mut save = SaveOpts::from_params(s, p, cmd)?; + save.bmp_bits = match p.get("bmpBits") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(photocraft_io::BmpBits::from_bits) { + Some(photocraft_io::BmpBits::Bits16) => return Err(bad(cmd, "16-bit BMP is not supported yet; use 24 or 32 bits".into())), + Some(bits) => Some(bits), + None => return Err(bad(cmd, format!("`bmpBits` must be 16, 24 or 32, got {v}"))), + }, + }; + let icc_profile = bool_param(p, "iccProfile", cmd)?; + save.embed_icc = icc_profile; + save.png_interlaced = bool_param(p, "pngInterlaced", cmd)?; + let board = BoardOptions { transparency: bool_param(p, "transparency", cmd)?, preserve_artboard: bool_param(p, "preserveArtboard", cmd)?, icc_profile }; + Ok((save, board)) +} + +impl BoardOptions { + /// Applies the options of `format` (lower case, no dot) to one board's document. + pub(super) fn apply(&self, one: &mut Document, format: &str) { + if format == "png" && self.transparency == Some(false) { + // A white Background in the document's own mode and depth: the composite is opaque, + // so the file is written without alpha. + let bg = Document::with_background("Background", one.size, one.mode, one.depth, Color::WHITE); + one.layers.splice(0..0, bg.layers); + } + if matches!(format, "psd" | "psb") { + if self.preserve_artboard == Some(false) { + for layer in &mut one.layers { + if let LayerContent::Group(g) = &mut layer.content { + g.artboard = None; + } + } + } + match self.icc_profile { + Some(false) => one.icc_profile = None, + // A document without a profile of its own gets the one its colours are taken to + // be in, as a flat file embeds it. + Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), + _ => {} + } + } + } +} diff --git a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs new file mode 100644 index 0000000000..f4eec3589f --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs @@ -0,0 +1,212 @@ +//! Artboards to Files' Export Options (#13636): each per-file-type option reaches the written +//! file, no option leaves the output as it was, and bad values are refused before anything is +//! written. + +use super::*; +use photocraft_geom::Rect; + +/// 64 x 48, transparent, with two boards: "Clear" (transparent, a red square inside, half the +/// board left empty) and "White" (white background, empty). +fn session() -> (Session, u64, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "transparent"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 16, 24), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + let clear = s.execute("layer.new.artboardFromLayers", json!({"name": "Clear", "background": "transparent", "width": 32, "height": 24})).unwrap(); + let white = s.execute("layer.new.artboard", json!({"rect": [40, 0, 16, 16], "name": "White", "background": "white"})).unwrap(); + (s, clear["layer"].as_u64().unwrap(), white["layer"].as_u64().unwrap()) +} + +/// Exports `board` with `extra` params as `format` and returns the file's bytes. +fn export(s: &mut Session, dir: &str, board: u64, format: &str, extra: Value) -> Vec { + let mut p = json!({"dir": dir, "prefix": "", "format": format, "artboards": [board]}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + std::fs::read(r["files"][0].as_str().unwrap()).unwrap() +} + +/// A fresh, empty folder for one test's files. +fn tmp(name: &str) -> String { + let dir = std::env::temp_dir().join(format!("photocraft-13636-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.to_string_lossy().into_owned() +} + +/// PNG IHDR: (colour type, interlace method). +fn png_header(b: &[u8]) -> (u8, u8) { + assert_eq!(&b[12..16], b"IHDR"); + (b[25], b[28]) +} + +fn has(b: &[u8], needle: &[u8]) -> bool { + b.windows(needle.len()).any(|w| w == needle) +} + +/// A little- or big-endian TIFF's first-IFD value of `tag` (SHORT or LONG), if present. +fn tiff_tag(b: &[u8], tag: u16) -> Option { + let le = &b[0..2] == b"II"; + let u16_at = |o: usize| if le { u16::from_le_bytes([b[o], b[o + 1]]) } else { u16::from_be_bytes([b[o], b[o + 1]]) }; + let u32_at = + |o: usize| if le { u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) } else { u32::from_be_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) }; + let ifd = u32_at(4) as usize; + (0..usize::from(u16_at(ifd))) + .map(|i| ifd + 2 + i * 12) + .find(|&e| u16_at(e) == tag) + .map(|e| if u16_at(e + 2) == 3 { u32::from(u16_at(e + 8)) } else { u32_at(e + 8) }) +} + +#[test] +fn without_options_the_files_are_as_before() { + let (mut s, clear, white) = session(); + let dir = &tmp("plain"); + let png = export(&mut s, dir, clear, "png", json!({})); + assert_eq!(png_header(&png), (6, 0), "RGBA, not interlaced"); + assert!(has(&png, b"iCCP"), "the profile is embedded"); + let bmp = export(&mut s, dir, white, "bmp", json!({})); + assert_eq!(u16::from_le_bytes([bmp[28], bmp[29]]), 24, "an opaque board is a 24-bit BMP"); + let tif = export(&mut s, dir, white, "tiff", json!({})); + assert_eq!(tiff_tag(&tif, 259), Some(1), "uncompressed"); + let psd = export(&mut s, dir, clear, "psd", json!({})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert_eq!(doc.artboards().len(), 1, "the board is kept"); + assert!(doc.icc_profile.is_none(), "a document without a profile of its own writes a PSD without one, as before"); + // Explicit nulls are the same as no option. + let nulls = json!({"iccProfile": null, "bmpBits": null, "pngInterlaced": null, "transparency": null, "preserveArtboard": null, "tiffCompression": null}); + assert_eq!(export(&mut s, dir, clear, "png", nulls.clone()), png); + assert_eq!(export(&mut s, dir, white, "bmp", nulls), bmp); +} + +#[test] +fn bmp_depth_reaches_the_file() { + let (mut s, clear, white) = session(); + let dir = &tmp("bmp"); + let bits = |b: &[u8]| u16::from_le_bytes([b[28], b[29]]); + // 32 bits on an opaque board adds an opaque alpha; 24 on a transparent one drops it. + let b32 = export(&mut s, dir, white, "bmp", json!({"bmpBits": 32})); + assert_eq!(bits(&b32), 32); + let b24 = export(&mut s, dir, clear, "bmp", json!({"bmpBits": 24})); + assert_eq!(bits(&b24), 24); + let img = photocraft_io::import("x.bmp", &b24).unwrap().document; + let px = photocraft_compose::flatten(&img).px.clone(); + // The empty right half of the board is white, the square red. + assert_eq!(px[(10 * 32 + 28) as usize], [1.0, 1.0, 1.0, 1.0]); + assert_eq!(px[(10 * 32 + 4) as usize], [1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn tiff_compression_reaches_the_file() { + let (mut s, _, white) = session(); + let dir = &tmp("tiff"); + for (name, tag) in [("none", 1), ("lzw", 5), ("zip", 8)] { + let tif = export(&mut s, dir, white, "tiff", json!({"tiffCompression": name})); + assert_eq!(tiff_tag(&tif, 259), Some(tag), "{name}"); + } +} + +#[test] +fn png_interlace_and_transparency_reach_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("png"); + let png = export(&mut s, dir, clear, "png", json!({"pngInterlaced": true})); + assert_eq!(png_header(&png), (6, 1), "Adam7"); + let png = export(&mut s, dir, clear, "png", json!({"transparency": true, "pngInterlaced": false})); + assert_eq!(png_header(&png), (6, 0)); + let png = export(&mut s, dir, clear, "png", json!({"transparency": false})); + assert_eq!(png_header(&png).0, 2, "Transparency off writes RGB without alpha"); + let img = photocraft_io::import("x.png", &png).unwrap().document; + let px = photocraft_compose::flatten(&img).px.clone(); + assert_eq!(px[(10 * 32 + 28) as usize], [1.0, 1.0, 1.0, 1.0], "the empty part is white"); + assert_eq!(px[(10 * 32 + 4) as usize], [1.0, 0.0, 0.0, 1.0]); + // Transparency is a PNG option: a PSD keeps its transparent board. + let psd = export(&mut s, dir, clear, "psd", json!({"transparency": false})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert_eq!(doc.layers.len(), 1, "no Background added"); +} + +#[test] +fn include_icc_profile_reaches_the_file() { + let (mut s, clear, white) = session(); + let dir = &tmp("icc"); + for on in [true, false] { + let p = json!({"iccProfile": on}); + assert_eq!(has(&export(&mut s, dir, clear, "png", p.clone()), b"iCCP"), on, "png {on}"); + assert_eq!(has(&export(&mut s, dir, white, "jpg", p.clone()), b"ICC_PROFILE\0"), on, "jpg {on}"); + assert_eq!(tiff_tag(&export(&mut s, dir, white, "tiff", p.clone()), 34675).is_some(), on, "tiff {on}"); + let psd = export(&mut s, dir, clear, "psd", p); + assert_eq!(photocraft_io::import("x.psd", &psd).unwrap().document.icc_profile.is_some(), on, "psd {on}"); + } + // The source document is not given one. + assert!(s.active().unwrap().doc.icc_profile.is_none()); +} + +#[test] +fn psd_options_reach_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("psd"); + let merged = |b: &[u8]| craft_psd::PsdFile::from_bytes(b).unwrap().has_real_merged_data(); + for on in [true, false] { + assert_eq!(merged(&export(&mut s, dir, clear, "psd", json!({"maximizeCompatibility": on}))), Some(on), "{on}"); + } + let psd = export(&mut s, dir, clear, "psd", json!({"preserveArtboard": false})); + let doc = photocraft_io::import("x.psd", &psd).unwrap().document; + assert!(doc.artboards().is_empty(), "written as a plain group"); + let group = doc.layers.first().unwrap(); + assert_eq!(group.name, "Clear"); + assert_eq!(group.children().unwrap().first().unwrap().name, "Red"); + let psd = export(&mut s, dir, clear, "psd", json!({"preserveArtboard": true})); + assert_eq!(photocraft_io::import("x.psd", &psd).unwrap().document.artboards().len(), 1); + // The source document keeps its board. + assert_eq!(s.active().unwrap().doc.artboards().len(), 2); +} + +#[test] +fn jpeg_quality_reaches_the_file() { + let (mut s, clear, _) = session(); + let dir = &tmp("jpeg"); + s.execute("filter.noise.addNoise", json!({"amount": 60})).ok(); + let low = export(&mut s, dir, clear, "jpg", json!({"quality": 0})); + let frac = export(&mut s, dir, clear, "jpg", json!({"quality": 7.6})); + let high = export(&mut s, dir, clear, "jpg", json!({"quality": 12})); + assert!(low.len() < frac.len() && frac.len() < high.len(), "{} {} {}", low.len(), frac.len(), high.len()); +} + +#[test] +fn bad_option_values_are_errors_and_write_nothing() { + let (mut s, clear, _) = session(); + let dir = &tmp("bad"); + for bad in [ + json!({"tiffCompression": "jpeg"}), + json!({"tiffCompression": "rle"}), + json!({"tiffCompression": 5}), + json!({"bmpBits": 16}), + json!({"bmpBits": 17}), + json!({"bmpBits": "24"}), + json!({"bmpBits": -1}), + json!({"quality": "high"}), + json!({"quality": [8]}), + json!({"iccProfile": "yes"}), + json!({"pngInterlaced": 1}), + json!({"transparency": {}}), + json!({"preserveArtboard": "false"}), + json!({"maximizeCompatibility": 0}), + json!({"tgaBits": 16}), + ] { + let mut p = json!({"dir": dir, "format": "png", "artboards": [clear]}); + if let (Some(p), Some(bad)) = (p.as_object_mut(), bad.as_object()) { + p.extend(bad.clone()); + } + let r = s.execute("file.export.artboardsToFiles", p); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{bad}: nothing written"); + } +} diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index eba2b9502d..25f436b3ec 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -22,6 +22,15 @@ pub(crate) struct SaveOpts { /// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or /// transparency, else 24. pub tga_bits: Option, + /// BMP: 16, 24 or 32 bits per pixel; unset, 32 with transparency, else 24. Set by Artboards to + /// Files' BMP options (`"bmpBits"`). + pub bmp_bits: Option, + /// Embed the ICC profile in a flat file; unset, embed it. Artboards to Files' Include ICC + /// Profile (`"iccProfile"`). + pub embed_icc: Option, + /// PNG: write it interlaced (Adam7); unset, not. Artboards to Files' PNG Interlaced + /// (`"pngInterlaced"`). + pub png_interlaced: Option, /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. pub dpx_bits: Option, /// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none. @@ -57,6 +66,9 @@ impl Default for SaveOpts { jpeg_format: None, tiff_layers: false, tga_bits: None, + bmp_bits: None, + embed_icc: None, + png_interlaced: None, dpx_bits: None, tiff_compression: None, tiff_transparency: None, @@ -86,6 +98,9 @@ impl SaveOpts { jpeg_format: jpeg_format_param(p, cmd)?, tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits: tga_bits_param(p, cmd)?, + bmp_bits: None, + embed_icc: None, + png_interlaced: None, dpx_bits: dpx_bits_param(p, cmd)?, tiff_compression: tiff_compression_param(p, cmd)?, tiff_transparency: tiff_bool_param(p, "tiffTransparency", cmd)?, @@ -250,6 +265,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R tiff_transparency: save.tiff_transparency, preserve_alpha: save.preserve_alpha, tga_bits: save.tga_bits, + bmp_bits: save.bmp_bits, pdf_spot_plates: save.pdf_spot_plates, image_previews: save.image_previews, psd_maximize_compatibility: save.psd_maximize_compatibility, @@ -268,6 +284,12 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R opts.encode.tiff_compression = c; } opts.encode.tiff_pyramid = save.tiff_pyramid; + if let Some(embed) = save.embed_icc { + opts.encode.embed_icc = embed; + } + if let Some(interlaced) = save.png_interlaced { + opts.encode.png_interlaced = interlaced; + } opts.encode.dds = save.dds; if let Some(q) = save.quality { let q = jpeg_quality(q); diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 53611d5007..3961494410 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -9,7 +9,7 @@ use photocraft_geom::{Rect, Size, TILE_SIZE}; use photocraft_raster::{AllocationError, Interrupt, PruneCursor, RowWriteError, Surface}; use crate::renderer::{BandRenderer, RenderError}; -use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; +use crate::{BmpBits, ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; /// Bytes per band when converting or exporting a band of rows at a time. const BAND_BYTES: usize = 32 << 20; @@ -1769,6 +1769,9 @@ pub fn export_flat_with_renderer( if format == Format::Tga { img = tga_image(doc, img, opts.tga_bits, opts.preserve_alpha, &mut warnings)?; } + if format == Format::Bmp { + img = bmp_image(img, opts.bmp_bits, &mut warnings)?; + } if format == Format::Dds { img = dds_image(doc, img, &mut warnings)?; } @@ -1819,6 +1822,9 @@ pub fn export_flat_with_renderer( if format == Format::Tga { img = tga_image(doc, img, opts.tga_bits, opts.preserve_alpha, &mut warnings)?; } + if format == Format::Bmp { + img = bmp_image(img, opts.bmp_bits, &mut warnings)?; + } if format == Format::Dds { img = dds_image(doc, img, &mut warnings)?; } @@ -2123,6 +2129,29 @@ fn tga_image(doc: &Document, img: Image, bits: Option, preserve_alpha: } } +/// The image an RGB BMP of `bits` per pixel holds: 24 composites a transparent image over white, +/// 32 gives an opaque image an opaque alpha; `None` keeps the image (32 with transparency, else +/// 24). Grayscale images are written as they are. 16 bits is refused: the encoder has no 16-bit +/// BMP. +fn bmp_image(img: Image, bits: Option, warnings: &mut Vec) -> Result { + let Some(bits) = bits else { return Ok(img) }; + if !img.layout().is_rgb() { + warnings.push(format!("{}-bit BMP applies to RGB images; the grayscale image is written as it is", bits.bits())); + return Ok(img); + } + match bits { + BmpBits::Bits16 => Err(IoError::Unsupported("16-bit BMP is not supported yet; use 24 or 32 bits".into())), + BmpBits::Bits24 if img.layout().has_alpha() => { + warnings.push("transparency composited over white; a 24-bit BMP has no alpha".into()); + matte_over_white(&img) + } + BmpBits::Bits32 if !img.layout().has_alpha() => { + map_bands(&img, ChannelLayout::Rgba, img.sample_type(), |vals| vals.as_chunks::<3>().0.iter().flat_map(|&[r, g, b]| [r, g, b, 1.0]).collect()) + } + _ => Ok(img), + } +} + /// The image a DDS texture holds (#8563): as with a 32-bit Targa, the document's alpha channel /// becomes the texture's alpha when it has exactly one (spot channels don't count), the colours /// composited over white where the layers are transparent; BC1 keeps it as on/off, BC2 and BC3 diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index f537ac2b41..526f3f2cab 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -417,6 +417,10 @@ pub struct ExportOptions { /// Targa: bits per pixel of an RGB file. `None` writes 32 when the document has an alpha /// channel or transparency, else 24; Save As asks, starting at [`tga_default_bits`]. pub tga_bits: Option, + /// BMP: bits per pixel of an RGB file. `None` writes 32 when the composite has transparency, + /// else 24; `Some(24)` composites over white, `Some(32)` adds an opaque alpha to an opaque + /// image. 16 bits is refused as unsupported: the encoder writes 24 and 32 only. + pub bmp_bits: Option, /// PSD/PSB: embed the thumbnail image resource (1036), Preferences › File Handling › Image /// Previews. On by default, as Photoshop's Always Save. pub image_previews: bool, @@ -455,6 +459,7 @@ impl Default for ExportOptions { preserve_alpha: false, xmp: XmpEmbed::All, tga_bits: None, + bmp_bits: None, image_previews: true, psd_maximize_compatibility: true, document_path: None, @@ -494,6 +499,38 @@ impl TgaBits { } } +/// Bits per pixel of an RGB BMP (the Depth of Artboards to Files' BMP options). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BmpBits { + /// 5 bits per colour. + Bits16, + /// The colours alone, no alpha. + Bits24, + /// The colours and an 8-bit alpha. + Bits32, +} + +impl BmpBits { + /// `16`, `24` or `32` as [`BmpBits`]; any other number is `None`. + pub fn from_bits(bits: u64) -> Option { + match bits { + 16 => Some(BmpBits::Bits16), + 24 => Some(BmpBits::Bits24), + 32 => Some(BmpBits::Bits32), + _ => None, + } + } + + /// The bits per pixel. + pub fn bits(self) -> u8 { + match self { + BmpBits::Bits16 => 16, + BmpBits::Bits24 => 24, + BmpBits::Bits32 => 32, + } + } +} + /// `true` if `bytes` start with the PSD/PSB signature. pub fn is_psd(bytes: &[u8]) -> bool { bytes.starts_with(b"8BPS") diff --git a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs new file mode 100644 index 0000000000..0995e1be9b --- /dev/null +++ b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs @@ -0,0 +1,212 @@ +//! #13636: Artboards to Files' Export Options checkbox (unticked by default, below File Type) +//! shows the chosen file type's options with the reference application's defaults, sends them +//! to the command only while ticked, and remembers them after a successful run only. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const OPTION_PARAMS: [&str; 9] = + ["iccProfile", "bmpBits", "tgaBits", "pngInterlaced", "transparency", "tiffCompression", "maximizeCompatibility", "preserveArtboard", "quality"]; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#8A42B3"})).unwrap(); + app.run("layer.new.artboardFromLayers", json!({"name": "Board", "background": "transparent"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, dir: &str, format: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS, json!({})).unwrap()["dialog"].as_u64().unwrap(); + set(h, dialog, &[("dir", json!(dir)), ("prefix", json!("out")), ("format", json!(format))]); + dialog +} + +fn set(h: &mut Harness<'_, PhotocraftApp>, dialog: u64, kv: &[(&str, Value)]) { + let fields = &mut h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + for (k, v) in kv { + fields.insert((*k).into(), v.clone()); + } + h.run_steps(4); +} + +fn params(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(dialog).unwrap().fields) +} + +/// The option params the dialog sends (the null ones left out). +fn sent(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + let p = params(h, dialog); + Value::Object(OPTION_PARAMS.iter().filter_map(|k| p.get(*k).filter(|v| !v.is_null()).map(|v| ((*k).to_string(), v.clone()))).collect()) +} + +fn ticked(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn shown(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +fn tick_export_options(h: &mut Harness<'_, PhotocraftApp>) { + h.get_by_role_and_label(Role::CheckBox, "Export Options").click(); + h.run_steps(3); +} + +fn quality_field_enabled(h: &Harness<'_, PhotocraftApp>) -> bool { + !h.get_by_role_and_label(Role::SpinButton, "Quality").accesskit_node().is_disabled() +} + +fn type_quality(h: &mut Harness<'_, PhotocraftApp>, text: &str) { + h.get_by_role_and_label(Role::SpinButton, "Quality").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in text.chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn tmp() -> (tempfile::TempDir, String) { + let t = tempfile::tempdir().unwrap(); + let s = t.path().to_string_lossy().into_owned(); + (t, s) +} + +#[test] +fn export_options_is_unticked_below_file_type_and_sends_nothing() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + assert!(!ticked(&h, "Export Options")); + assert!(!shown(&h, "Include ICC Profile"), "the Options group is hidden"); + assert_eq!(sent(&mut h, dialog), json!({}), "no option reaches the command"); + assert!(!shown(&h, "Custom"), "no Custom quality row"); + let order = h.state_mut().ui.dialog_mut(dialog).unwrap().fields["__order"].clone(); + assert_eq!(order, json!(["dir", "prefix", "format", "exportOptions"]), "below File Type"); + let below = h.get_by_role_and_label(Role::CheckBox, "Export Options").rect().top(); + let format = h.get_by_role_and_label(Role::ComboBox, "Format").rect().top(); + assert!(below > format, "{below} > {format}"); +} + +#[test] +fn each_file_type_shows_its_options_with_the_reference_defaults() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + assert!(shown(&h, "Options:")); + let cases = [ + ("psd", vec!["Maximize Compatibility", "Preserve Artboard"], json!({"maximizeCompatibility": true, "preserveArtboard": true, "iccProfile": true})), + ("bmp", vec!["16bit", "24bit", "32bit"], json!({"bmpBits": 24, "iccProfile": true})), + ("jpg", vec!["Quality"], json!({"quality": 8.0, "iccProfile": true})), + ("tiff", vec!["Image Compression", "Quality"], json!({"tiffCompression": "none", "iccProfile": true})), + ("png", vec!["Transparency", "Interlaced"], json!({"transparency": true, "pngInterlaced": false, "iccProfile": true})), + ]; + for (format, labels, defaults) in cases { + set(&mut h, dialog, &[("format", json!(format))]); + for l in labels { + assert!(shown(&h, l), "{format}: {l}"); + } + assert!(ticked(&h, "Include ICC Profile"), "{format}"); + assert_eq!(sent(&mut h, dialog), defaults, "{format}"); + } + assert!(ticked(&h, "Transparency") && !ticked(&h, "Interlaced")); + set(&mut h, dialog, &[("format", json!("bmp"))]); + let radio = |h: &Harness<'_, PhotocraftApp>, l: &str| h.get_by_role_and_label(Role::RadioButton, l).accesskit_node().toggled() == Some(Toggled::True); + assert!(radio(&h, "24bit") && !radio(&h, "16bit") && !radio(&h, "32bit")); + h.get_by_role_and_label(Role::RadioButton, "32bit").click(); + h.run_steps(3); + assert_eq!(sent(&mut h, dialog)["bmpBits"], json!(32)); + // Each type keeps its own settings. + set(&mut h, dialog, &[("format", json!("png"))]); + assert_eq!(sent(&mut h, dialog), json!({"transparency": true, "pngInterlaced": false, "iccProfile": true})); + set(&mut h, dialog, &[("format", json!("bmp"))]); + assert_eq!(sent(&mut h, dialog)["bmpBits"], json!(32)); + // Unticked again: the group is hidden and nothing is sent. + tick_export_options(&mut h); + assert!(!shown(&h, "Include ICC Profile") && !shown(&h, "32bit")); + assert_eq!(sent(&mut h, dialog), json!({})); +} + +#[test] +fn tiff_quality_is_greyed_unless_the_compression_is_jpeg() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "tiff"); + tick_export_options(&mut h); + assert!(!quality_field_enabled(&h)); + assert!(sent(&mut h, dialog).get("quality").is_none()); + let mut opts = h.state_mut().ui.dialog_mut(dialog).unwrap().fields["__exportOpts"].clone(); + opts["tiff"]["tiffCompression"] = json!("jpeg"); + set(&mut h, dialog, &[("__exportOpts", opts)]); + assert!(quality_field_enabled(&h)); + assert_eq!(sent(&mut h, dialog), json!({"tiffCompression": "jpeg", "quality": 8.0, "iccProfile": true})); +} + +#[test] +fn the_quality_field_clamps_keeps_fractions_and_ignores_text() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "jpg"); + tick_export_options(&mut h); + for (typed, expect) in [("99", 12.0), ("-5", 0.0), ("7.6", 7.6), ("abc", 7.6)] { + type_quality(&mut h, typed); + let q = sent(&mut h, dialog)["quality"].as_f64().unwrap(); + assert!((q - expect).abs() < 1e-4, "{typed}: {q}"); + } +} + +#[test] +fn the_options_reach_the_written_file() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Interlaced").click(); + h.get_by_role_and_label(Role::CheckBox, "Transparency").click(); + h.run_steps(3); + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + let png = std::fs::read(r["files"][0].as_str().unwrap()).unwrap(); + assert_eq!((png[25], png[28]), (2, 1), "RGB without alpha, interlaced"); +} + +#[test] +fn options_are_remembered_after_a_successful_run_only() { + let mut h = harness(); + let (_t, dir) = tmp(); + let dialog = open(&mut h, &dir, "png"); + tick_export_options(&mut h); + h.get_by_role_and_label(Role::CheckBox, "Interlaced").click(); + h.run_steps(3); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(3); + let dialog = open(&mut h, &dir, "png"); + assert!(ticked(&h, "Export Options") && ticked(&h, "Interlaced"), "remembered after the run"); + // A run that fails (16-bit BMP is refused) is not remembered. + set(&mut h, dialog, &[("format", json!("bmp"))]); + h.get_by_role_and_label(Role::RadioButton, "16bit").click(); + h.get_by_role_and_label(Role::CheckBox, "Include ICC Profile").click(); + h.run_steps(3); + assert!(crate::dialogs::confirm(h.state_mut(), dialog).is_err()); + h.state_mut().ui.dialogs.clear(); + h.run_steps(3); + let dialog = open(&mut h, &dir, "bmp"); + assert_eq!(sent(&mut h, dialog), json!({"bmpBits": 24, "iccProfile": true}), "the last successful run's settings"); + set(&mut h, dialog, &[("format", json!("png"))]); + assert!(ticked(&h, "Interlaced")); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba..22c15511c7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1066,6 +1066,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, mut d: Dialog) -> Result Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { @@ -56,7 +57,7 @@ fn direct(h: &mut Harness<'_, PhotocraftApp>, dir: &str, format: &str, quality: if let Some(q) = quality { p["quality"] = json!(q); } - let r = h.state_mut().run(ARTBOARDS, p).unwrap(); + let r = h.state_mut().run(COMPS, p).unwrap(); std::fs::read(r["files"][0].as_str().unwrap()).unwrap() } @@ -121,13 +122,13 @@ fn tmp() -> (tempfile::TempDir, String) { } #[test] -fn artboards_to_files_sends_a_custom_jpeg_quality() { +fn layer_comps_to_files_sends_a_custom_jpeg_quality() { let mut h = harness(); let (_a, via_dialog) = tmp(); let (_b, via_command) = tmp(); let mut sizes = Vec::new(); for quality in [0, 3, 12] { - let dialog = open(&mut h, ARTBOARDS, &via_dialog, "jpg"); + let dialog = open(&mut h, COMPS, &via_dialog, "jpg"); assert!(!custom_ticked(&h) && !quality_enabled(&h), "JPEG with Custom off: the field is greyed out"); tick_custom(&mut h); assert!(custom_ticked(&h) && quality_enabled(&h), "JPEG with Custom on: the field takes input"); @@ -147,7 +148,7 @@ fn an_untouched_jpeg_export_writes_what_the_command_writes_with_no_quality() { let mut h = harness(); let (_a, via_dialog) = tmp(); let (_b, via_command) = tmp(); - let dialog = open(&mut h, ARTBOARDS, &via_dialog, "jpg"); + let dialog = open(&mut h, COMPS, &via_dialog, "jpg"); assert!(params(&mut h, dialog).get("quality").is_none_or(Value::is_null), "no quality is sent"); let bytes = exported(&mut h, dialog); assert!(bytes == direct(&mut h, &via_command, "jpg", None), "the untouched dialog keeps the command's own JPEG quality"); @@ -186,7 +187,7 @@ fn export_to_files_quality_leaves_png_and_webp_as_they_were() { fn the_custom_quality_survives_a_format_round_trip() { let mut h = harness(); let (_a, dir) = tmp(); - let dialog = open(&mut h, ARTBOARDS, &dir, "jpg"); + let dialog = open(&mut h, COMPS, &dir, "jpg"); tick_custom(&mut h); type_quality(&mut h, "4"); assert_eq!(params(&mut h, dialog)["quality"], json!(4)); @@ -209,7 +210,7 @@ fn the_custom_quality_survives_a_format_round_trip() { fn alt_reset_restores_the_custom_quality() { let mut h = harness(); let ctx = h.ctx.clone(); - let dialog = crate::menus::invoke(h.state_mut(), &ctx, ARTBOARDS, json!({})).unwrap()["dialog"].as_u64().unwrap(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, COMPS, json!({})).unwrap()["dialog"].as_u64().unwrap(); // JPEG chosen in the dialog, after it opened: Reset puts the format back too. h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("format".into(), json!("jpg")); h.run_steps(4); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..b5198b51ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1056,6 +1056,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_export_options_dialog_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 6194417a22..5ff7c7ab7b 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -20,10 +20,10 @@ mod options; pub use arrange::{Border, borders, cells, drag_border}; pub(crate) use arrange::{document_is_floating, float_window}; -pub(crate) use dialogs::write_copy; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; +pub(crate) use dialogs::{remember_artboard_export_options, write_copy}; #[cfg(test)] use dispatch::is_enabled_with_engine; pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_without_document}; diff --git a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs new file mode 100644 index 0000000000..77856b9357 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs @@ -0,0 +1,191 @@ +//! Artboards to Files' Export Options (#13636): a checkbox below File Type, unticked by default, +//! that shows an Options group with the chosen file type's settings. Each type keeps its own +//! settings (shell state in [`OPTS`]); the command gets the flat params of the shown type only +//! while the checkbox is on, so an export without it writes what it wrote before. Both are +//! remembered after a successful run, never after a failed one. + +use super::{Map, PhotocraftApp, Value, json}; + +pub(super) const COMMAND: &str = "file.export.artboardsToFiles"; +/// The checkbox (a field, so it shows in `__order`; the command ignores it). +pub(super) const CHECKBOX: &str = "exportOptions"; +/// Every type's settings, `{type: {param: value}}`: shell state, never a command parameter. +pub(super) const OPTS: &str = "__exportOpts"; +/// The params the group sends; the form renders none of them itself. +pub(super) const PARAMS: [&str; 9] = + ["iccProfile", "bmpBits", "tgaBits", "pngInterlaced", "transparency", "tiffCompression", "maximizeCompatibility", "preserveArtboard", "quality"]; + +/// The settings key of a File Type value (`jpg` and `jpeg` share one, as `tif` and `tiff` do). +fn kind(format: &str) -> Option<&'static str> { + Some(match format.to_ascii_lowercase().as_str() { + "psd" | "psb" => "psd", + "bmp" => "bmp", + "jpg" | "jpeg" => "jpg", + "tif" | "tiff" => "tiff", + "tga" => "tga", + "png" => "png", + _ => return None, + }) +} + +/// The reference application's defaults for each type. +fn defaults() -> Value { + json!({ + "psd": {"maximizeCompatibility": true, "preserveArtboard": true, "iccProfile": true}, + "bmp": {"bmpBits": 24, "iccProfile": true}, + "tga": {"tgaBits": 24, "iccProfile": true}, + "jpg": {"quality": 8.0, "iccProfile": true}, + "tiff": {"tiffCompression": "none", "quality": 8.0, "iccProfile": true}, + "png": {"transparency": true, "pngInterlaced": false, "iccProfile": true}, + }) +} + +/// Whether `v` is a valid value for `key` (a hand-edited preferences file may hold anything). +fn valid(key: &str, v: &Value) -> bool { + match key { + "bmpBits" | "tgaBits" => v.as_u64().is_some_and(|b| [16, 24, 32].contains(&b)), + "tiffCompression" => v.as_str().is_some_and(|c| ["none", "lzw", "zip", "jpeg"].contains(&c)), + "quality" => v.as_f64().is_some_and(|q| (0.0..=12.0).contains(&q)), + _ => v.is_boolean(), + } +} + +/// The open dialog's fields: the checkbox and every type's settings, the defaults overlaid with +/// what the last successful run remembered. +pub(super) fn open_fields(app: &PhotocraftApp) -> (Value, Value) { + let mut opts = defaults(); + let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap_or(Value::Null); + if let (Some(all), Some(remembered)) = (opts.as_object_mut(), saved.get("options").and_then(Value::as_object)) { + for (kind, settings) in all.iter_mut() { + let (Some(settings), Some(from)) = (settings.as_object_mut(), remembered.get(kind).and_then(Value::as_object)) else { continue }; + for (key, v) in settings.iter_mut() { + if let Some(r) = from.get(key).filter(|r| valid(key, r)) { + *v = r.clone(); + } + } + } + } + (json!(saved.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false)), opts) +} + +/// Inserts the group's fields into a new dialog's `fields`. +pub(super) fn insert_fields(app: &PhotocraftApp, fields: &mut Value) { + let (on, opts) = open_fields(app); + if let Some(f) = fields.as_object_mut() { + f.insert(CHECKBOX.into(), on); + f.insert(OPTS.into(), opts); + for p in PARAMS { + f.insert(p.into(), Value::Null); + } + } + sync_params(fields.as_object_mut()); +} + +/// Remembers the checkbox and every type's settings after a successful run of the dialog. +pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map) { + if command != COMMAND || !fields.contains_key(OPTS) { + return; + } + let saved = json!({CHECKBOX: fields.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false), "options": fields.get(OPTS).cloned().unwrap_or(Value::Null)}); + app.session.prefs.edit(|prefs| prefs.dialogs.insert(COMMAND.into(), saved)); +} + +/// Writes the flat params for the command: the shown type's settings while the checkbox is on, +/// else none. TIFF sends its quality only with JPEG compression. +fn sync_params(f: Option<&mut Map>) { + let Some(f) = f else { return }; + for p in PARAMS { + f.insert(p.into(), Value::Null); + } + if f.get(CHECKBOX).and_then(Value::as_bool) != Some(true) { + return; + } + let Some(kind) = f.get("format").and_then(Value::as_str).and_then(kind) else { return }; + let Some(settings) = f.get(OPTS).and_then(|o| o.get(kind)).and_then(Value::as_object).cloned() else { return }; + let jpeg_tiff = settings.get("tiffCompression").and_then(Value::as_str) == Some("jpeg"); + for (key, v) in settings { + if kind == "tiff" && key == "quality" && !jpeg_tiff { + continue; + } + f.insert(key, v); + } +} + +fn get_bool(s: &Map, key: &str) -> bool { + s.get(key).and_then(Value::as_bool).unwrap_or(false) +} + +fn checkbox(ui: &mut egui::Ui, s: &mut Map, key: &str, label: &str) { + let mut on = get_bool(s, key); + crate::widgets::checkbox(ui, &mut on, label); + s.insert(key.into(), json!(on)); +} + +/// The Quality slider and field, 0-12: a typed value past either end is clamped, fractions are +/// kept, and text that is no number leaves the value as it was. +fn quality(ui: &mut egui::Ui, s: &mut Map) { + let mut q = s.get("quality").and_then(Value::as_f64).unwrap_or(8.0).clamp(0.0, 12.0) as f32; + crate::widgets::slider_line(ui, tl!("Quality"), 70.0, &mut q, 0.0..=12.0, ""); + s.insert("quality".into(), json!(f64::from(q.clamp(0.0, 12.0)))); +} + +/// Depth radios for BMP and Targa. +fn depth(ui: &mut egui::Ui, s: &mut Map, key: &str) { + let mut bits = s.get(key).and_then(Value::as_u64).unwrap_or(24); + ui.horizontal(|ui| { + ui.label(tl!("Depth:")); + for (b, label) in [(16, tl!("16bit")), (24, tl!("24bit")), (32, tl!("32bit"))] { + ui.radio_value(&mut bits, b, label); + } + }); + s.insert(key.into(), json!(bits)); +} + +/// The Export Options checkbox and, while it is ticked, the Options group of the chosen type. +pub(super) fn group(ui: &mut egui::Ui, f: &mut Map) { + let mut on = f.get(CHECKBOX).and_then(Value::as_bool).unwrap_or(false); + let kind = f.get("format").and_then(Value::as_str).and_then(kind); + ui.vertical(|ui| { + crate::widgets::checkbox(ui, &mut on, tl!("Export Options")); + let Some(kind) = kind.filter(|_| on) else { return }; + let Some(Value::Object(all)) = f.get_mut(OPTS) else { return }; + let Some(Value::Object(s)) = all.get_mut(kind) else { return }; + ui.label(tl!("Options:")); + ui.group(|ui| { + ui.set_min_width(300.0); + match kind { + "psd" => { + checkbox(ui, s, "maximizeCompatibility", tl!("Maximize Compatibility")); + checkbox(ui, s, "preserveArtboard", tl!("Preserve Artboard")); + } + "bmp" => depth(ui, s, "bmpBits"), + "tga" => depth(ui, s, "tgaBits"), + "jpg" => quality(ui, s), + "tiff" => { + let mut c = s.get("tiffCompression").and_then(Value::as_str).unwrap_or("none").to_string(); + let opts = [ + ("none".to_string(), tl!("None")), + ("lzw".to_string(), tl!("LZW")), + ("zip".to_string(), tl!("ZIP")), + ("jpeg".to_string(), tl!("JPEG")), + ]; + ui.horizontal(|ui| { + ui.label(tl!("Image Compression:")); + crate::widgets::dropdown(ui, "artboards-tiff-compression", tl!("Image Compression"), &mut c, &opts, 120.0); + }); + let jpeg = c == "jpeg"; + s.insert("tiffCompression".into(), json!(c)); + ui.add_enabled_ui(jpeg, |ui| quality(ui, s)); + } + "png" => { + checkbox(ui, s, "transparency", tl!("Transparency")); + checkbox(ui, s, "pngInterlaced", tl!("Interlaced")); + } + _ => {} + } + checkbox(ui, s, "iccProfile", tl!("Include ICC Profile")); + }); + }); + f.insert(CHECKBOX.into(), json!(on)); + sync_params(Some(f)); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..b8182d72e0 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1,6 +1,10 @@ use super::dispatch::no_params; use super::{DialogKind, Map, PhotocraftApp, Value, json}; +#[path = "artboard_export_options.rs"] +mod artboard_export_options; +pub(crate) use artboard_export_options::remember as remember_artboard_export_options; + // ---------- dialogs and pickers in front of engine commands ---------- /// A generic form dialog that runs `command` with its fields on OK (rendered by [`form_body`]). @@ -141,6 +145,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { let command = f.get("__command").and_then(Value::as_str); let file_info = command == Some("file.fileInfo"); let image_processor = command == Some("file.scripts.imageProcessor"); + let artboards = command == Some(artboard_export_options::COMMAND); let label = |k: &str| { if file_info { match k { @@ -162,6 +167,17 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { { continue; } + if artboards { + if artboard_export_options::PARAMS.contains(&k.as_str()) { + continue; + } + if k == artboard_export_options::CHECKBOX { + ui.label(""); + artboard_export_options::group(ui, f); + ui.end_row(); + continue; + } + } let v = f.get(&k).cloned().unwrap_or(Value::Null); if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { let label = ui.label(tl!("File Naming")); @@ -278,7 +294,7 @@ const BATCH_QUALITY: &str = "__batchQuality"; const JPEG_CUSTOM: &str = "__jpegCustom"; const JPEG_QUALITY: &str = "__jpegQuality"; /// The shell keys Alt+Reset restores along with a form's params. -const RESET_SHELL_KEYS: [&str; 3] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY]; +const RESET_SHELL_KEYS: [&str; 4] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, artboard_export_options::OPTS]; /// A Custom checkbox and the 0..12 Quality field it enables (Batch, the exports to files). Off, /// the command gets no quality and keeps its own defaults; `usable` false greys out both. @@ -507,7 +523,11 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}) } else { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "__order": ["dir", "prefix", "format", "quality"]}) + // The JPEG quality is one of the Export Options here (#13636). + let mut fields = + json!({"dir": dir, "prefix": prefix, "format": "png", "__order": ["dir", "prefix", "format", artboard_export_options::CHECKBOX]}); + artboard_export_options::insert_fields(app, &mut fields); + fields }; dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) } From fc8c6f366431ce961ef59b23d91f51fbf185a917 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 07:55:02 +0100 Subject: [PATCH 03/33] Artboards to Files: Include Artboard Name with its Name Options (#13637) file.export.artboardsToFiles takes includeName, font, fontStyle, fontSize, extension (white, black, other with extensionColor, or a colour) and textColor. With the option on, flat file types get a border of (w + h) / 20 px on each side in the Canvas Extension colour and the board's name in the top border, left-aligned with the board; a size that is not a positive number fails before any file is written. PSD and PDF stay as today. The dialog has the Include Artboard Name checkbox, kept per file type, and the Name Options shown while it is ticked. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 121 ++++++++++- .../cmd/artboard_cmds/include_name_tests.rs | 203 ++++++++++++++++++ .../artboards_include_name_dialog_tests.rs | 129 +++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds/dialogs.rs | 114 +++++++++- 5 files changed, 559 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/include_name_tests.rs create mode 100644 crates/ui-egui/src/artboards_include_name_dialog_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..fbbae0668b 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -13,7 +13,7 @@ use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, color_param, int, int_i32}; +use crate::commands::{CommandSpec, color_param, int, int_i32, parse_hex}; use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file}; use crate::{EngineError, Result, Session}; @@ -675,17 +675,129 @@ fn chosen_artboards(doc: &Document, p: &Value) -> Vec { } } +/// Artboards to Files' Include Artboard Name and its Name Options (#13637). +struct NameBorder { + /// `{"font", "fontStyle", "size", "color"}` for [`crate::type_cmds::apply_char_props`]. + style: Value, + /// The Canvas Extension colour, sRGB with alpha. + extension: [f32; 4], +} + +/// Photoshop's largest type size, in points. +const NAME_SIZE_MAX_PT: f64 = 1296.0; + +/// The Name Options of `file.export.artboardsToFiles`, or `None` with `includeName` off. A size +/// that is not a positive number fails the export, as in Photoshop ("the initial bounding +/// rectangle is empty"), before any file is written. +fn name_border_param(p: &Value, cmd: &str) -> Result> { + if !p.get("includeName").and_then(Value::as_bool).unwrap_or(false) { + return Ok(None); + } + // The dialog's Size field takes any text, so a numeric string counts as its number. + let size = match p.get("fontSize") { + None | Some(Value::Null) => Some(12.0), + Some(Value::String(t)) => t.trim().parse::().ok(), + Some(v) => v.as_f64(), + }; + let Some(size) = size.filter(|v| v.is_finite() && *v > 0.0) else { + return Err(bad(cmd, "the artboard name size must be a positive number of points")); + }; + let font = p.get("font").and_then(Value::as_str).filter(|f| !f.trim().is_empty()).unwrap_or("Arial"); + let font_style = p.get("fontStyle").and_then(Value::as_str).filter(|f| !f.trim().is_empty()).unwrap_or("Regular"); + let white = [1.0, 1.0, 1.0, 1.0]; + let extension = match p.get("extension") { + None | Some(Value::Null) => white, + Some(Value::String(c)) if c.eq_ignore_ascii_case("white") => white, + Some(Value::String(c)) if c.eq_ignore_ascii_case("black") => [0.0, 0.0, 0.0, 1.0], + // The dialog's Other...: the colour picked in its swatch. + Some(Value::String(c)) if c.eq_ignore_ascii_case("other") => color_param(cmd, p, "extensionColor", white)?, + Some(Value::String(c)) => parse_hex(c).ok_or_else(|| bad(cmd, "`extension` must be \"white\", \"black\", \"#rrggbb\" or [r, g, b]"))?, + Some(_) => color_param(cmd, p, "extension", white)?, + }; + let text = color_param(cmd, p, "textColor", [0.0, 0.0, 0.0, 1.0])?.map(|c| c.clamp(0.0, 1.0)); + let style = json!({"font": font, "fontStyle": font_style, "size": size.min(NAME_SIZE_MAX_PT), "color": text}); + Ok(Some(NameBorder { style, extension: extension.map(|c| c.clamp(0.0, 1.0)) })) +} + +/// The width of the name border on each side: a twentieth of width plus height, rounded. This +/// gives exactly Photoshop's measured borders: 18 px for 200 x 150, 20 for 200 x 200 and 60 for +/// 800 x 400. +fn name_border_width(w: u32, h: u32) -> u32 { + ((f64::from(w) + f64::from(h)) / 20.0).round() as u32 +} + +/// Include Artboard Name: extends `one` on all four sides by [`name_border_width`], fills the new +/// border with the Canvas Extension colour (a bottom layer, so the board keeps its own pixels) +/// and draws the board's name in the top border, its ink left-aligned with the board's left edge +/// and centred in the border's height. +fn add_name_border(one: &mut Document, o: &NameBorder, cmd: &str) -> Result<()> { + let (w, h) = (one.size.width, one.size.height); + let b = name_border_width(w, h); + let grown = |len: u32| b.checked_mul(2).and_then(|d| len.checked_add(d)).and_then(|n| i32::try_from(n).ok().map(|i| (n, i))); + let (Some((nw, nwi)), Some((nh, nhi)), Ok(bi)) = (grown(w), grown(h), i32::try_from(b)) else { + return Err(bad(cmd, format!("artboard `{}` is too large to add a name border", one.name))); + }; + let before = one.clone(); + for l in &mut one.layers { + crate::commands::translate_layer(&before, l, bi, bi); + crate::vector_cmds::translate_vectors(&before, l, f64::from(bi), f64::from(bi)); + } + crate::canvas_geom::transform_doc_marks(one, &Affine::translate(f64::from(bi), f64::from(bi))); + one.size = Size::new(nw, nh); + let fmt = one.pixel_format(); + let mut ring = Layer::raster("Canvas Extension", fmt); + if let Some(surf) = ring.surface_mut() { + let px = photocraft_raster::from_rgba(&fmt, o.extension); + let (x1, y1) = (nwi - bi, nhi - bi); + for r in [Rect::new(0, 0, nwi, bi), Rect::new(0, y1, nwi, nhi), Rect::new(0, bi, bi, y1), Rect::new(x1, bi, nwi, y1)] { + if !r.is_empty() { + surf.fill_rect(r, &px); + } + } + } + one.layers.insert(0, ring); + let mut style = photocraft_doc::text::CharStyle::default(); + crate::type_cmds::apply_char_props(&mut style, &o.style); + let mut t = photocraft_doc::TextLayer { text: one.name.clone(), ..Default::default() }; + t.runs = vec![photocraft_doc::text::TextRun { len: t.text.len(), style }]; + t.sync_summary(); + let dpi = one.resolution_dpi; + let layout = photocraft_text::shared().lock().unwrap_or_else(std::sync::PoisonError::into_inner).layout(&t, dpi); + if let Some([x0, y0, _, y1]) = photocraft_text::render::ink_bounds(&layout) { + let (dx, dy) = ((f64::from(bi) - x0).round(), (f64::from(bi) / 2.0 - (y0 + y1) / 2.0).round()); + if dx.is_finite() && dy.is_finite() { + t.transform = Affine::translate(dx, dy); + crate::type_cmds::refresh_at(dpi, fmt, &mut t); + let name = t.text.clone(); + one.layers.push(Layer::new(name, LayerContent::Text(t))); + } + } + Ok(()) +} + +/// File types Include Artboard Name leaves as they are: what it does there is not measured. +fn keeps_layers(format: &str) -> bool { + matches!(format, "psd" | "psb" | "pdf" | "pcraft") +} + /// File › Export › Artboards to Files: `__.` per board. fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let save = SaveOpts::from_params(s, p, cmd)?; + let border = name_border_param(p, cmd)?.filter(|_| !keeps_layers(&format)); let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); + let mut boards = chosen_documents(&doc, p)?; + if let Some(o) = &border { + for one in &mut boards { + add_name_border(one, o, cmd)?; + } + } let mut files = Vec::new(); - for (i, one) in chosen_documents(&doc, p)?.into_iter().enumerate() { + for (i, one) in boards.into_iter().enumerate() { // Names may be identical, or collide after sanitizing or filesystem case folding. let name = if prefix.is_empty() { format!("{i:04}_{}", sanitize(&one.name)) } else { format!("{}_{i:04}_{}", sanitize(&prefix), sanitize(&one.name)) }; let path = join(&dir, &format!("{name}.{format}")); @@ -829,7 +941,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?,"includeName":bool=false (Include Artboard Name: a border of (w + h) / 20 px on each side, the name in the top one; psd and pdf keep their layers),"font":family="Arial","fontStyle":"Regular|Italic|Bold|Bold Italic|Black"="Regular","fontSize":pt|numeric str=12 (else an error),"extension":"white|black|other"|"#rrggbb"|[r,g,b]="white" (Canvas Extension; "other" takes "extensionColor":[r,g,b]),"textColor":"#rrggbb"|[r,g,b]=black} → {files}"##, export_artboards, artboards_to_files ), @@ -848,5 +960,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/include_name_tests.rs"] +mod include_name_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs new file mode 100644 index 0000000000..35734e32c3 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -0,0 +1,203 @@ +//! Artboards to Files › Include Artboard Name (#13637): a border of the Canvas Extension colour +//! on all four sides, the board's name in the top one, at 8 and 16 bit; bad Name Options fail the +//! export before any file is written; without the option the output is today's. + +use super::*; + +const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; +const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; +const RED: [f32; 4] = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + +/// The spec's test document: 800 x 400, transparent, `Red Board` 0,0-200,150 (white, a red +/// layer at 20,20-120,100) and `Blue Board` 120,30-320,230 (white, a blue layer at 130,40-230,140). +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + board(&mut s, "Red Board", [0, 0, 200, 150], Rect::new(20, 20, 120, 100), RED); + board(&mut s, "Blue Board", [120, 30, 200, 200], Rect::new(130, 40, 230, 140), [30.0 / 255.0, 30.0 / 255.0, 220.0 / 255.0, 1.0]); + s +} + +fn board(s: &mut Session, name: &str, rect: [i32; 4], px: Rect, rgba: [f32; 4]) { + let r = s.execute("layer.new.artboard", json!({"rect": rect, "name": name, "background": "white"})).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + s.edit("px", |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name.replace(" Board", ""), fmt); + l.surface_mut().unwrap().fill_rect(px, &photocraft_raster::from_rgba(&fmt, rgba)); + doc.layer_mut(id).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); +} + +fn tmp(tag: &str) -> String { + let dir = std::env::temp_dir().join(format!("photocraft-abname-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir.to_string_lossy().into_owned() +} + +/// Runs the export and reads every written PNG back, keyed by the board name in its file name. +fn export(s: &mut Session, dir: &str, extra: Value) -> Vec<(String, Document)> { + let mut p = json!({"dir": dir, "prefix": "t", "format": "png"}); + if let (Some(p), Value::Object(extra)) = (p.as_object_mut(), extra) { + p.extend(extra); + } + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let f = f.as_str().unwrap(); + let name = if f.contains("Red Board") { "Red" } else { "Blue" }; + (name.to_string(), photocraft_io::import("x.png", &std::fs::read(f).unwrap()).unwrap().document) + }) + .collect() +} + +fn find<'a>(files: &'a [(String, Document)], name: &str) -> &'a Document { + &files.iter().find(|(n, _)| n == name).unwrap().1 +} + +fn px(d: &Document, x: i32, y: i32) -> [f32; 4] { + photocraft_compose::flatten(d).get(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) +} + +fn on() -> Value { + json!({"includeName": true}) +} + +#[test] +fn the_border_width_is_a_twentieth_of_width_plus_height() { + // The three borders measured in the reference application. + assert_eq!(name_border_width(200, 150), 18); + assert_eq!(name_border_width(200, 200), 20); + assert_eq!(name_border_width(800, 400), 60); +} + +#[test] +fn the_boards_get_the_measured_sizes_with_their_content_unchanged_inside() { + for depth in [8, 16] { + let mut s = session(depth); + let plain = export(&mut s, &tmp(&format!("plain{depth}")), json!({})); + let named = export(&mut s, &tmp(&format!("named{depth}")), on()); + let (red, blue) = (find(&named, "Red"), find(&named, "Blue")); + assert_eq!((red.size.width, red.size.height), (236, 186), "{depth} bit"); + assert_eq!((blue.size.width, blue.size.height), (240, 240), "{depth} bit"); + // Content at 18..218 x 18..168, pixel for pixel the file without the option. + let (before, after) = (photocraft_compose::flatten(find(&plain, "Red")), photocraft_compose::flatten(red)); + for y in (0..150).step_by(7) { + for x in (0..200).step_by(7) { + assert!(close(before.get(x, y), after.get(x + 18, y + 18)), "{depth} bit at {x},{y}"); + } + } + assert!(close(px(red, 18 + 50, 18 + 50), RED), "{depth} bit"); + assert!(close(px(red, 18, 18), WHITE), "{depth} bit: the board's own white"); + // The border is opaque white on every side. + for (x, y) in [(0, 0), (235, 185), (5, 100), (230, 100), (100, 180), (17, 17)] { + assert!(close(px(red, x, y), WHITE), "{depth} bit at {x},{y}"); + } + } +} + +#[test] +fn the_name_sits_in_the_top_border_from_the_boards_left_edge() { + let mut s = session(8); + let files = export(&mut s, &tmp("text"), on()); + for (name, border) in [("Red", 18), ("Blue", 20)] { + let img = photocraft_compose::flatten(find(&files, name)); + let w = find(&files, name).size.width as i32; + let dark: Vec<(i32, i32)> = (0..border).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| img.get(x, y)[0] < 0.5).collect(); + assert!(!dark.is_empty(), "{name}: the name is drawn in the top border"); + let x0 = dark.iter().map(|p| p.0).min().unwrap(); + assert!((x0 - border).abs() <= 1, "{name}: ink starts at the board's left edge, got {x0}"); + let (y0, y1) = (dark.iter().map(|p| p.1).min().unwrap(), dark.iter().map(|p| p.1).max().unwrap()); + assert!(y0 > 0 && y1 < border - 1, "{name}: ink inside the border, rows {y0}..{y1}"); + // Black text by default. + assert!(dark.iter().any(|&(x, y)| close(img.get(x, y), BLACK)), "{name}"); + } +} + +#[test] +fn canvas_extension_black_fills_the_border_black() { + let mut s = session(8); + let files = export(&mut s, &tmp("black"), json!({"includeName": true, "extension": "black", "textColor": [1.0, 1.0, 1.0]})); + let red = find(&files, "Red"); + for (x, y) in [(0, 0), (235, 185), (5, 100), (230, 100), (100, 180)] { + assert!(close(px(red, x, y), BLACK), "at {x},{y}"); + } + assert!(close(px(red, 18, 18), WHITE), "the board keeps its own white"); + // An "#rrggbb" extension colour too. + let files = export(&mut s, &tmp("hex"), json!({"includeName": true, "extension": "#00ff00"})); + assert!(close(px(find(&files, "Red"), 2, 100), [0.0, 1.0, 0.0, 1.0])); + // The dialog's Other... sends the swatch colour along. + let files = export(&mut s, &tmp("other"), json!({"includeName": true, "extension": "other", "extensionColor": [0.0, 0.0, 1.0]})); + assert!(close(px(find(&files, "Red"), 2, 100), [0.0, 0.0, 1.0, 1.0])); +} + +#[test] +fn without_the_option_the_output_is_todays() { + let mut s = session(8); + for extra in [json!({}), json!({"includeName": false, "fontSize": "abc"})] { + let files = export(&mut s, &tmp("off"), extra); + let red = find(&files, "Red"); + assert_eq!((red.size.width, red.size.height), (200, 150)); + assert!(close(px(red, 50, 50), RED)); + } + // PSD keeps its layers: the option leaves it as it is today. + let d = tmp("psd"); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "format": "psd", "includeName": true})).unwrap(); + for f in r["files"].as_array().unwrap() { + let psd = photocraft_io::import("x.psd", &std::fs::read(f.as_str().unwrap()).unwrap()).unwrap().document; + assert!(matches!((psd.size.width, psd.size.height), (200, 150) | (200, 200)), "{:?}", psd.size); + } +} + +#[test] +fn a_size_that_is_not_a_positive_number_fails_and_writes_nothing() { + let mut s = session(8); + for size in [json!("abc"), json!(""), json!("0"), json!(0), json!(-3), json!("-1"), json!("inf"), json!({"x": 1}), json!([12])] { + let d = tmp("bad"); + let before = s.active().unwrap().doc.clone(); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); + assert!(err.contains("size"), "{size}: {err}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "{size}: no file written"); + assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len(), "{size}: source unchanged"); + } + // A numeric string is its number, as the dialog's free text field sends it. + let files = export(&mut s, &tmp("str"), json!({"includeName": true, "fontSize": " 9 "})); + assert_eq!(find(&files, "Red").size.width, 236); +} + +#[test] +fn bad_name_options_never_panic() { + let mut s = session(8); + let d = tmp("junk"); + for p in [ + json!({"extension": "purple"}), + json!({"extension": [f64::MAX, -1.0, 2.0]}), + json!({"extension": {"r": 1}}), + json!({"extension": "#12"}), + json!({"textColor": "zz"}), + json!({"textColor": [1, 2]}), + json!({"font": 7, "fontStyle": null}), + json!({"font": "", "fontStyle": "No Such Style"}), + json!({"font": "No Such Font Family", "fontSize": 1e300}), + json!({"fontSize": 1e-30}), + json!({"includeName": "yes"}), + ] { + let mut p = p; + p["dir"] = json!(d); + if p.get("includeName").is_none() { + p["includeName"] = json!(true); + } + let _ = s.execute("file.export.artboardsToFiles", p); + } + assert!(s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "extension": "purple"})).is_err()); +} diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs new file mode 100644 index 0000000000..ef4938e680 --- /dev/null +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -0,0 +1,129 @@ +//! #13637: the Artboards to Files dialog has Include Artboard Name (unticked), kept per file type; +//! ticking it shows the Name Options (Font Arial, Style Regular, Size 12 pt, Canvas Extension +//! White / Black / Other..., Text black), and OK passes them to `file.export.artboardsToFiles`. +//! Layer Comps to Files has none of it. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const INCLUDE: &str = "Include Artboard Name"; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).unwrap(); + app.run("layerComp.new", json!({"name": "Comp"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, id: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, id, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + dialog +} + +fn ticked(h: &Harness<'_, PhotocraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, INCLUDE).accesskit_node().toggled() == Some(Toggled::True) +} + +fn params(h: &mut Harness<'_, PhotocraftApp>, dialog: u64) -> Value { + crate::filter_dialog::params_of(&h.state_mut().ui.dialog_mut(dialog).unwrap().fields) +} + +fn set(h: &mut Harness<'_, PhotocraftApp>, dialog: u64, key: &str, v: Value) { + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert(key.into(), v); + h.run_steps(4); +} + +/// Labels of the rows the dialog shows now. +fn has_label(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.query_all_by_label(label).next().is_some() +} + +#[test] +fn the_checkbox_starts_unticked_and_ticking_it_shows_the_name_options_with_their_defaults() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + assert!(!ticked(&h)); + assert!(!has_label(&h, "Name Options") && !has_label(&h, "Font:") && !has_label(&h, "Canvas Extension:")); + assert_eq!(params(&mut h, dialog)["includeName"], false); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h)); + for label in ["Name Options", "Font:", "Style", "Size (pt)", "Canvas Extension:", "Text:"] { + assert!(has_label(&h, label), "{label} is shown"); + } + // The Other... colour swatch only with Other... chosen. + assert!(!has_label(&h, "Canvas Extension Color")); + let p = params(&mut h, dialog); + assert_eq!(p["includeName"], true); + assert_eq!((&p["font"], &p["fontStyle"], &p["fontSize"], &p["extension"]), (&json!("Arial"), &json!("Regular"), &json!("12"), &json!("white"))); + assert_eq!(p["textColor"], json!([0.0, 0.0, 0.0])); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + let choices = &fields["__choices"]; + assert_eq!(choices["fontStyle"], json!(["Regular", "Italic", "Bold", "Bold Italic", "Black"])); + assert_eq!(choices["extension"], json!(["white", "black", "other"])); + assert!(choices["font"].as_array().unwrap().iter().any(|f| f == "Arial")); + assert_eq!(fields["__labels"]["other"], "Other..."); + set(&mut h, dialog, "extension", json!("other")); + assert!(has_label(&h, "Canvas Extension Color")); +} + +#[test] +fn the_checkbox_is_kept_per_file_type() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h)); + set(&mut h, dialog, "format", json!("psd")); + assert!(!ticked(&h), "PSD keeps its own, unticked"); + assert!(!has_label(&h, "Font:")); + set(&mut h, dialog, "format", json!("tiff")); + assert!(!ticked(&h)); + set(&mut h, dialog, "format", json!("png")); + assert!(ticked(&h), "PNG's tick comes back"); + assert_eq!(params(&mut h, dialog)["includeName"], true); +} + +#[test] +fn ok_runs_the_export_with_the_name_options() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let dir = std::env::temp_dir().join(format!("photocraft-abname-ui-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + set(&mut h, dialog, "dir", json!(dir.to_string_lossy())); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + set(&mut h, dialog, "extension", json!("black")); + let p = params(&mut h, dialog); + let r = h.state_mut().run(ARTBOARDS, p).unwrap(); + let file = r["files"][0].as_str().unwrap().to_string(); + let img = photocraft_io::import("x.png", &std::fs::read(&file).unwrap()).unwrap().document; + // A 64 x 64 board gets a border of (64 + 64) / 20 = 6 px on each side. + assert_eq!((img.size.width, img.size.height), (76, 76)); + // A size that is not a number fails the run. + set(&mut h, dialog, "fontSize", json!("abc")); + let p = params(&mut h, dialog); + assert!(h.state_mut().run(ARTBOARDS, p).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn layer_comps_to_files_has_no_artboard_name() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + assert_eq!(h.query_all_by_role_and_label(Role::CheckBox, INCLUDE).count(), 0); + assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("includeName").is_none()); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..44af308cdf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1076,6 +1076,8 @@ mod pen_path_ownership_tests; #[cfg(test)] mod artboard_options_bar_tests; #[cfg(test)] +mod artboards_include_name_dialog_tests; +#[cfg(test)] mod background_eraser_bar_angle_tests; #[cfg(test)] mod brush_alt_digit_smoothing_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..0ccd7f084e 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -152,6 +152,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { } labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string) }; + per_format_state(f); let keys = form_keys(f); let mut browse: Option = None; egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { @@ -162,7 +163,25 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { { continue; } + if !shown(f, &k) { + continue; + } + if let Some(title) = f.get("__sections").and_then(|m| m.get(&k)).and_then(Value::as_str) { + ui.label(egui::RichText::new(title).font(crate::theme::semibold(13.0))); + ui.end_row(); + } let v = f.get(&k).cloned().unwrap_or(Value::Null); + // A key named in `__swatches` is an sRGB `[r, g, b]` (0..1) edited with a colour swatch. + let swatch = f.get("__swatches").and_then(Value::as_array).is_some_and(|s| s.iter().any(|n| n.as_str() == Some(k.as_str()))); + if swatch && let Some(rgb) = v.as_array() { + ui.label(label(&k)); + let byte = |i: usize| (rgb.get(i).and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as u8; + let mut c = [byte(0), byte(1), byte(2)]; + crate::widgets::color_edit_button_srgb(ui, &mut c, &crate::color_picker_ui::title_for(&label(&k))).on_hover_text(label(&k)); + f.insert(k, json!(c.map(|b| f64::from(b) / 255.0))); + ui.end_row(); + continue; + } if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { let label = ui.label(tl!("File Naming")); let mut naming = v.as_str().unwrap_or_default().to_owned(); @@ -206,13 +225,18 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { json!(b) } Value::String(s) => { - ui.label(label(&k)); + let name = ui.label(label(&k)); + if let Some(tip) = f.get("__tooltips").and_then(|m| m.get(&k)).and_then(Value::as_str) { + name.on_hover_text(tip); + } let mut s = s.clone(); match choices.get(&k).and_then(Value::as_array) { Some(opts) => { - // Action and set names are the user's own text, never catalogue entries. - let action_names = matches!(k.as_str(), "action" | "set") - && matches!(f.get("__command").and_then(Value::as_str), Some("file.automate.batch" | "file.automate.createDroplet")); + // Action and set names are the user's own text, never catalogue entries; + // nor are the choices of a key in `__literal` (font names). + let action_names = (matches!(k.as_str(), "action" | "set") + && matches!(f.get("__command").and_then(Value::as_str), Some("file.automate.batch" | "file.automate.createDroplet"))) + || f.get("__literal").and_then(Value::as_array).is_some_and(|l| l.iter().any(|n| n.as_str() == Some(k.as_str()))); let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), if action_names { o.to_string() } else { label(o) })).collect(); let refs: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); @@ -277,8 +301,59 @@ const BATCH_QUALITY: &str = "__batchQuality"; /// is not JPEG or Custom is off: shell state, never command parameters. const JPEG_CUSTOM: &str = "__jpegCustom"; const JPEG_QUALITY: &str = "__jpegQuality"; +/// The checkboxes a form keeps per file type (`__perFormat`, keys of the `format` field), the +/// values kept for the other types, and the type they belong to now (#13637): shell state. +const PER_FORMAT_STATE: &str = "__perFormatState"; +const FORMAT_SEEN: &str = "__formatSeen"; /// The shell keys Alt+Reset restores along with a form's params. -const RESET_SHELL_KEYS: [&str; 3] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY]; +const RESET_SHELL_KEYS: [&str; 5] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, PER_FORMAT_STATE, FORMAT_SEEN]; + +/// When the `format` field has changed, keeps the `__perFormat` keys' values under the type they +/// were set for and brings back the new type's (their value at open for a type not seen yet), as +/// Artboards to Files keeps Include Artboard Name per file type. +fn per_format_state(f: &mut Map) { + let Some(keys) = f.get("__perFormat").and_then(Value::as_array).cloned() else { return }; + let format = f.get("format").and_then(Value::as_str).unwrap_or_default().to_string(); + let seen = f.get(FORMAT_SEEN).and_then(Value::as_str).unwrap_or_default().to_string(); + if format == seen { + return; + } + let orig = f.get("__formOrig").cloned().unwrap_or(Value::Null); + let mut state = f.get(PER_FORMAT_STATE).and_then(Value::as_object).cloned().unwrap_or_default(); + let mut old = Map::new(); + for k in keys.iter().filter_map(Value::as_str) { + old.insert(k.to_string(), f.get(k).cloned().unwrap_or(Value::Null)); + let kept = state.get(&format).and_then(|m| m.get(k)).or_else(|| orig.get(k)).cloned(); + if let Some(v) = kept { + f.insert(k.to_string(), v); + } + } + state.insert(seen, Value::Object(old)); + f.insert(PER_FORMAT_STATE.into(), Value::Object(state)); + f.insert(FORMAT_SEEN.into(), json!(format)); +} + +/// A key named in `__shownBy` is shown only while the checkbox it names is on, or, for a +/// `[key, value]` pair, while that choice is `value`; and only while the key it names is shown. +fn shown(f: &Map, k: &str) -> bool { + shown_at(f, k, 0) +} + +fn shown_at(f: &Map, k: &str, depth: u8) -> bool { + // A chain longer than this (or a cycle) shows the field rather than recursing on. + if depth > 8 { + return true; + } + let (by, on) = match f.get("__shownBy").and_then(|m| m.get(k)) { + Some(Value::String(by)) => (by.as_str(), f.get(by.as_str()).and_then(Value::as_bool) == Some(true)), + Some(Value::Array(pair)) => match (pair.first().and_then(Value::as_str), pair.get(1)) { + (Some(by), Some(want)) => (by, f.get(by) == Some(want)), + _ => return true, + }, + _ => return true, + }; + on && shown_at(f, by, depth + 1) +} /// A Custom checkbox and the 0..12 Quality field it enables (Batch, the exports to files). Off, /// the command gets no quality and keeps its own defaults; `usable` false greys out both. @@ -507,9 +582,34 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "selectedOnly": false, "__order": ["dir", "prefix", "selectedOnly", "format", "quality"]}) } else { - json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, "__order": ["dir", "prefix", "format", "quality"]}) + // Include Artboard Name, kept per file type, and its Name Options (#13637). + json!({"dir": dir, "prefix": prefix, "format": "png", "quality": null, JPEG_CUSTOM: false, JPEG_QUALITY: 10, + "includeName": false, "font": "Arial", "fontStyle": "Regular", "fontSize": "12", "extension": "white", "extensionColor": [0.5, 0.5, 0.5], + "textColor": [0.0, 0.0, 0.0], + "__order": ["dir", "prefix", "format", "quality", "includeName", "font", "fontStyle", "fontSize", "extension", "extensionColor", "textColor"], + "__perFormat": ["includeName"], PER_FORMAT_STATE: {}, FORMAT_SEEN: "png", + "__shownBy": {"font": "includeName", "fontStyle": "includeName", "fontSize": "includeName", "extension": "includeName", + "extensionColor": ["extension", "other"], "textColor": "includeName"}, + "__sections": {"font": tl!("Name Options")}, + "__swatches": ["extensionColor", "textColor"], + "__literal": ["font"], + "__tooltips": {"fontStyle": tl!("Select the font style")}, + "__labels": {"includeName": tl!("Include Artboard Name"), "font": tl!("Font:"), "fontStyle": tl!("Style"), "fontSize": tl!("Size (pt)"), + "extension": tl!("Canvas Extension:"), "white": tl!("White"), "black": tl!("Black"), "other": tl!("Other..."), + "extensionColor": tl!("Canvas Extension Color"), "textColor": tl!("Text:"), + "Regular": tl!("Regular"), "Italic": tl!("Italic"), "Bold": tl!("Bold"), "Bold Italic": tl!("Bold Italic"), "Black": tl!("Black")}}) }; - dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) + let mut choices = json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}); + if id == "file.export.artboardsToFiles" { + let mut fonts: Vec = crate::type_tool::families().to_vec(); + if !fonts.iter().any(|f| f == "Arial") { + fonts.insert(0, "Arial".into()); + } + choices["font"] = json!(fonts); + choices["fontStyle"] = json!(["Regular", "Italic", "Bold", "Bold Italic", "Black"]); + choices["extension"] = json!(["white", "black", "other"]); + } + dialog(app, fields, choices) } "file.export.artboardsToPdf" => { let (_, _, name) = doc?; From 3764fa82ed56f90e876588b1d095c24f2fb94376 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:35:58 +0100 Subject: [PATCH 04/33] Artboards to Files: keep the artboard name inside the top border A name size taller than the border is cut at the border instead of drawing over the board. The tests clean up their export folders with tempfile guards, and the default text colour check allows anti-aliased ink. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 14 ++++- .../cmd/artboard_cmds/include_name_tests.rs | 55 +++++++++++++++---- .../artboards_include_name_dialog_tests.rs | 8 +-- 3 files changed, 58 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index fbbae0668b..2e9ef649e3 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -768,8 +768,18 @@ fn add_name_border(one: &mut Document, o: &NameBorder, cmd: &str) -> Result<()> if dx.is_finite() && dy.is_finite() { t.transform = Affine::translate(dx, dy); crate::type_cmds::refresh_at(dpi, fmt, &mut t); - let name = t.text.clone(); - one.layers.push(Layer::new(name, LayerContent::Text(t))); + // Only the top border takes the name: ink of a size taller than the border is cut + // there, never drawn over the board (the file is flat, so the type need not stay + // editable). + if let Some(cache) = &t.cache { + let r = cache.content_bounds().intersect(&Rect::new(0, 0, nwi, bi)); + if !r.is_empty() { + let px = cache.try_read_region(r).map_err(|e| bad(cmd, e.to_string()))?; + let mut clipped = Surface::new(cache.format()); + clipped.write_region(r, &px); + one.layers.push(Layer::new(t.text.clone(), LayerContent::Raster(clipped))); + } + } } } Ok(()) diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs index 35734e32c3..0846e49bb1 100644 --- a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -31,11 +31,23 @@ fn board(s: &mut Session, name: &str, rect: [i32; 4], px: Rect, rgba: [f32; 4]) .unwrap(); } -fn tmp(tag: &str) -> String { - let dir = std::env::temp_dir().join(format!("photocraft-abname-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir.to_string_lossy().into_owned() +/// An empty export folder, removed when dropped (also when an assertion fails). +struct Tmp { + _dir: tempfile::TempDir, + path: String, +} + +impl std::ops::Deref for Tmp { + type Target = str; + fn deref(&self) -> &str { + &self.path + } +} + +fn tmp(tag: &str) -> Tmp { + let dir = tempfile::Builder::new().prefix(&format!("photocraft-abname-{tag}-")).tempdir().unwrap(); + let path = dir.path().to_string_lossy().into_owned(); + Tmp { _dir: dir, path } } /// Runs the export and reads every written PNG back, keyed by the board name in its file name. @@ -119,8 +131,27 @@ fn the_name_sits_in_the_top_border_from_the_boards_left_edge() { assert!((x0 - border).abs() <= 1, "{name}: ink starts at the board's left edge, got {x0}"); let (y0, y1) = (dark.iter().map(|p| p.1).min().unwrap(), dark.iter().map(|p| p.1).max().unwrap()); assert!(y0 > 0 && y1 < border - 1, "{name}: ink inside the border, rows {y0}..{y1}"); - // Black text by default. - assert!(dark.iter().any(|&(x, y)| close(img.get(x, y), BLACK)), "{name}"); + // Black text by default: the darkest ink is near black and neutral (small anti-aliased + // glyphs may not reach pure black with every font). + let ink = dark.iter().map(|&(x, y)| img.get(x, y)).min_by(|a, b| a[0].total_cmp(&b[0])).unwrap(); + assert!(ink[0] < 0.3 && (ink[0] - ink[1]).abs() < 0.02 && (ink[0] - ink[2]).abs() < 0.02, "{name}: {ink:?}"); + } +} + +#[test] +fn a_name_taller_than_the_border_never_draws_over_the_board() { + let mut s = session(8); + let plain = export(&mut s, &tmp("plain-big"), json!({})); + for size in [72, 400, 1296] { + let named = export(&mut s, &tmp("big"), json!({"includeName": true, "fontSize": size})); + let (before, after) = (photocraft_compose::flatten(find(&plain, "Red")), photocraft_compose::flatten(find(&named, "Red"))); + for y in 0..150 { + for x in (0..200).step_by(3) { + assert!(close(before.get(x, y), after.get(x + 18, y + 18)), "{size} pt at {x},{y}"); + } + } + // The cut name still shows in the border. + assert!((0..18).any(|y| (18..236).any(|x| after.get(x, y)[0] < 0.5)), "{size} pt"); } } @@ -152,7 +183,7 @@ fn without_the_option_the_output_is_todays() { } // PSD keeps its layers: the option leaves it as it is today. let d = tmp("psd"); - let r = s.execute("file.export.artboardsToFiles", json!({"dir": d, "format": "psd", "includeName": true})).unwrap(); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "format": "psd", "includeName": true})).unwrap(); for f in r["files"].as_array().unwrap() { let psd = photocraft_io::import("x.psd", &std::fs::read(f.as_str().unwrap()).unwrap()).unwrap().document; assert!(matches!((psd.size.width, psd.size.height), (200, 150) | (200, 200)), "{:?}", psd.size); @@ -165,9 +196,9 @@ fn a_size_that_is_not_a_positive_number_fails_and_writes_nothing() { for size in [json!("abc"), json!(""), json!("0"), json!(0), json!(-3), json!("-1"), json!("inf"), json!({"x": 1}), json!([12])] { let d = tmp("bad"); let before = s.active().unwrap().doc.clone(); - let err = s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "includeName": true, "fontSize": size})).unwrap_err().to_string(); assert!(err.contains("size"), "{size}: {err}"); - assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "{size}: no file written"); + assert_eq!(std::fs::read_dir(&*d).unwrap().count(), 0, "{size}: no file written"); assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len(), "{size}: source unchanged"); } // A numeric string is its number, as the dialog's free text field sends it. @@ -193,11 +224,11 @@ fn bad_name_options_never_panic() { json!({"includeName": "yes"}), ] { let mut p = p; - p["dir"] = json!(d); + p["dir"] = json!(&*d); if p.get("includeName").is_none() { p["includeName"] = json!(true); } let _ = s.execute("file.export.artboardsToFiles", p); } - assert!(s.execute("file.export.artboardsToFiles", json!({"dir": d, "includeName": true, "extension": "purple"})).is_err()); + assert!(s.execute("file.export.artboardsToFiles", json!({"dir": &*d, "includeName": true, "extension": "purple"})).is_err()); } diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs index ef4938e680..0532489b41 100644 --- a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -100,10 +100,9 @@ fn the_checkbox_is_kept_per_file_type() { fn ok_runs_the_export_with_the_name_options() { let mut h = harness(); let dialog = open(&mut h, ARTBOARDS); - let dir = std::env::temp_dir().join(format!("photocraft-abname-ui-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - set(&mut h, dialog, "dir", json!(dir.to_string_lossy())); + // Removed when dropped, also when an assertion fails. + let dir = tempfile::tempdir().unwrap(); + set(&mut h, dialog, "dir", json!(dir.path().to_string_lossy())); h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); h.run_steps(4); set(&mut h, dialog, "extension", json!("black")); @@ -117,7 +116,6 @@ fn ok_runs_the_export_with_the_name_options() { set(&mut h, dialog, "fontSize", json!("abc")); let p = params(&mut h, dialog); assert!(h.state_mut().run(ARTBOARDS, p).is_err()); - let _ = std::fs::remove_dir_all(&dir); } #[test] From abdcbbd7917dbda419ad6b44e03adaa4e5ae4526 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 08:53:18 +0100 Subject: [PATCH 05/33] WIP: Artboards to PDF: Reverse Page Order option (#13644) From dd5acdc6e19ac9d5da865d1a345469db56a74099 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 09:04:03 +0100 Subject: [PATCH 06/33] Artboards to PDF: Reverse Page Order option (#13644) The dialog gets a Reverse Page Order checkbox, unticked on first open and remembered after a successful run; file.export.artboardsToPdf takes reversePageOrder (default false), which writes the default page order the other way round. A non-boolean value is an error. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 13 ++- .../pdf_reverse_page_order_tests.rs | 96 +++++++++++++++++++ .../src/artboards_to_pdf_reverse_tests.rs | 92 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/view_cmds.rs | 2 +- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 15 ++- 7 files changed, 220 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs create mode 100644 crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..e2cebb3f13 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -751,6 +751,11 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); + // Reverse Page Order (#13644): the default page order the other way round. + let reverse = match p.get("reversePageOrder") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`reversePageOrder` must be true or false"))?, + }; let mut pages = Vec::new(); for one in chosen_documents(&doc, p)? { let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); @@ -766,6 +771,9 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } + if reverse { + pages.reverse(); + } write_file(&path, &raster_pdf(&pages))?; Ok(json!({"path": path, "pages": pages.len()})) } @@ -837,7 +845,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, + r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board)"##, export_artboards, artboards_to_pdf ), @@ -848,5 +856,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] +mod pdf_reverse_page_order_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs new file mode 100644 index 0000000000..dc23d5858b --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs @@ -0,0 +1,96 @@ +//! Artboards to PDF's Reverse Page Order (#13644), on the measured document: 800 x 400 with Red, +//! Blue and Empty Board, bottom to top. The boards have three different sizes, so each page's +//! MediaBox says which board it is. + +use super::*; + +/// The measured document, and the ids of Red, Blue and Empty Board (bottom to top). +fn session() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": 8, "resolution": 72})).unwrap(); + let mut board = |rect: [i64; 4], name: &str| { + let r = s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap(); + r["layer"].as_u64().unwrap() + }; + let ids = [board([0, 0, 200, 150], "Red Board"), board([120, 30, 200, 200], "Blue Board"), board([600, 0, 100, 100], "Empty Board")]; + (s, ids) +} + +/// Runs the export with `params` (plus a fresh path) and returns its result. +fn export(s: &mut Session, params: Value, tag: &str) -> (Result, Vec) { + let dir = std::env::temp_dir().join(format!("photocraft-pdf-reverse-{}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = join(&dir.to_string_lossy(), "boards.pdf"); + let mut params = params; + params["path"] = json!(path); + let r = s.execute("file.export.artboardsToPdf", params); + let bytes = std::fs::read(&path).unwrap_or_default(); + let _ = std::fs::remove_dir_all(&dir); + (r, bytes) +} + +/// Each page's size in points, in page order. +fn page_sizes(s: &mut Session, params: Value, tag: &str) -> Vec<(u32, u32)> { + let (r, bytes) = export(s, params, tag); + r.unwrap(); + let text = String::from_utf8_lossy(&bytes).into_owned(); + text.split("/MediaBox [0 0 ") + .skip(1) + .map(|rest| { + let mut n = rest.split([' ', ']']).map(|v| v.parse::().unwrap().round() as u32); + (n.next().unwrap(), n.next().unwrap()) + }) + .collect() +} + +fn reversed(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> { + v.reverse(); + v +} + +#[test] +fn reverse_page_order_turns_the_default_order_round() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({}), "default"); + assert_eq!(default.len(), 3); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(100, 100), (200, 150), (200, 200)], "one page per board"); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true}), "reverse"), reversed(default)); +} + +#[test] +fn false_or_no_param_keeps_the_default_order() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({}), "none"); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false}), "false"), default); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null}), "null"), default); +} + +#[test] +fn chosen_artboards_come_in_the_reversed_order_too() { + let (mut s, [red, blue, _]) = session(); + let chosen = json!([red, blue]); + let default = page_sizes(&mut s, json!({"artboards": chosen}), "chosen"); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(200, 150), (200, 200)], "only Red and Blue Board"); + assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true}), "chosen-reverse"), reversed(default)); +} + +#[test] +fn a_non_boolean_value_is_an_error_not_a_panic() { + let (mut s, _) = session(); + for (i, v) in [json!("yes"), json!(1), json!([true]), json!({"on": true})].into_iter().enumerate() { + let (r, bytes) = export(&mut s, json!({"reversePageOrder": v}), &format!("bad-{i}")); + let e = r.unwrap_err().to_string(); + assert!(e.contains("reversePageOrder"), "{e}"); + assert!(bytes.is_empty(), "nothing is written for {v}"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToPdf").unwrap(); + assert!(spec.params.contains(r#""reversePageOrder":bool=false"#), "{}", spec.params); +} diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs new file mode 100644 index 0000000000..b4b0129d08 --- /dev/null +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -0,0 +1,92 @@ +//! #13644: the Artboards to PDF dialog has a Reverse Page Order checkbox. It is unticked on first +//! open, reaches the command, and reopens as the last successful run left it. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const COMMAND: &str = "file.export.artboardsToPdf"; + +/// A document with two artboards of different sizes, so a page's MediaBox says which board it is. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 200, 150], "name": "Low"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [250, 0, 100, 100], "name": "High"})).unwrap(); + app.sync_views(); + h +} + +fn open(h: &mut Harness<'_, PhotocraftApp>, path: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("path".into(), json!(path)); + h.run_steps(4); + dialog +} + +fn ticked(h: &Harness<'_, PhotocraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").accesskit_node().toggled() == Some(Toggled::True) +} + +fn tick(h: &mut Harness<'_, PhotocraftApp>) { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").click(); + h.run_steps(2); +} + +/// Each page's width in points, in page order. +fn page_widths(path: &str) -> Vec { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); + text.split("/MediaBox [0 0 ").skip(1).map(|rest| rest.split(' ').next().unwrap().parse::().unwrap().round() as u32).collect() +} + +#[test] +fn the_checkbox_starts_unticked_and_reverses_the_pages() { + let t = tempfile::tempdir().unwrap(); + let path = t.path().join("plain.pdf").to_string_lossy().into_owned(); + let mut h = harness(); + let d = open(&mut h, &path); + assert!(!ticked(&h), "unticked on first open"); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + let plain = page_widths(&path); + assert_eq!(plain.len(), 2); + + let path = t.path().join("reversed.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + assert!(ticked(&h)); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + let mut want = plain; + want.reverse(); + assert_eq!(page_widths(&path), want); +} + +#[test] +fn a_successful_run_is_remembered_a_failed_one_is_not() { + let t = tempfile::tempdir().unwrap(); + let mut h = harness(); + let path = t.path().join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + + // Reopens ticked; untick it and fail the run (the destination is a file, not a folder). + let blocked = t.path().join("file"); + std::fs::write(&blocked, b"x").unwrap(); + let bad = blocked.join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &bad); + assert!(ticked(&h), "remembered after a successful run"); + tick(&mut h); + assert!(!ticked(&h)); + assert!(crate::dialogs::confirm(h.state_mut(), d).is_err()); + + let d = open(&mut h, &path); + assert!(ticked(&h), "a failed run leaves the remembered value alone"); + h.state_mut().ui.close_dialog(d); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba..49939bb18d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1057,6 +1057,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, mut d: Dialog) -> Result String { } /// Handle menu commands that need a shell action or a parameter dialog before execution. +/// Artboards to PDF remembers Reverse Page Order after a successful run (#13644). +pub(crate) fn remember_artboards_to_pdf(app: &mut PhotocraftApp, params: &Value) { + let Some(reverse) = params.get("reversePageOrder").and_then(Value::as_bool) else { return }; + app.session.prefs.edit(|prefs| prefs.dialogs.insert("file.export.artboardsToPdf".into(), json!({"reversePageOrder": reverse}))); +} + pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if id == "file.closeAll" || id == "file.closeOthers" { // Keep the remaining document's view (views are index-aligned with documents). @@ -514,7 +520,14 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + // Reverse Page Order starts unticked and reopens as the last successful run left it (#13644). + let reverse = app.session.prefs().dialogs.get(id).and_then(|v| v.get("reversePageOrder")).and_then(Value::as_bool).unwrap_or(false); + dialog( + app, + json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10, "reversePageOrder": reverse, "__order": ["path", "quality", "reversePageOrder"], + "__labels": {"reversePageOrder": tl!("Reverse Page Order")}}), + json!({}), + ) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] From e72dc193ae9534d64946a293107067e211b3e5a8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 10:15:05 +0100 Subject: [PATCH 07/33] Artboards to PDF reverse tests: export into a fresh temporary folder Co-Authored-By: Claude Opus 5.5 --- .../pdf_reverse_page_order_tests.rs | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs index dc23d5858b..b3009e1251 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs @@ -16,22 +16,21 @@ fn session() -> (Session, [u64; 3]) { (s, ids) } -/// Runs the export with `params` (plus a fresh path) and returns its result. -fn export(s: &mut Session, params: Value, tag: &str) -> (Result, Vec) { - let dir = std::env::temp_dir().join(format!("photocraft-pdf-reverse-{}-{tag}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = join(&dir.to_string_lossy(), "boards.pdf"); +/// Runs the export with `params` (plus a path in a fresh temporary folder) and returns its result +/// and the bytes written (empty when nothing was). +fn export(s: &mut Session, params: Value) -> (Result, Vec) { + let dir = tempfile::tempdir().unwrap(); + let path = join(&dir.path().to_string_lossy(), "boards.pdf"); let mut params = params; params["path"] = json!(path); let r = s.execute("file.export.artboardsToPdf", params); let bytes = std::fs::read(&path).unwrap_or_default(); - let _ = std::fs::remove_dir_all(&dir); (r, bytes) } /// Each page's size in points, in page order. -fn page_sizes(s: &mut Session, params: Value, tag: &str) -> Vec<(u32, u32)> { - let (r, bytes) = export(s, params, tag); +fn page_sizes(s: &mut Session, params: Value) -> Vec<(u32, u32)> { + let (r, bytes) = export(s, params); r.unwrap(); let text = String::from_utf8_lossy(&bytes).into_owned(); text.split("/MediaBox [0 0 ") @@ -51,38 +50,38 @@ fn reversed(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> { #[test] fn reverse_page_order_turns_the_default_order_round() { let (mut s, _) = session(); - let default = page_sizes(&mut s, json!({}), "default"); + let default = page_sizes(&mut s, json!({})); assert_eq!(default.len(), 3); let mut sorted = default.clone(); sorted.sort_unstable(); assert_eq!(sorted, [(100, 100), (200, 150), (200, 200)], "one page per board"); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true}), "reverse"), reversed(default)); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true})), reversed(default)); } #[test] fn false_or_no_param_keeps_the_default_order() { let (mut s, _) = session(); - let default = page_sizes(&mut s, json!({}), "none"); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false}), "false"), default); - assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null}), "null"), default); + let default = page_sizes(&mut s, json!({})); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false})), default); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null})), default); } #[test] fn chosen_artboards_come_in_the_reversed_order_too() { let (mut s, [red, blue, _]) = session(); let chosen = json!([red, blue]); - let default = page_sizes(&mut s, json!({"artboards": chosen}), "chosen"); + let default = page_sizes(&mut s, json!({"artboards": chosen})); let mut sorted = default.clone(); sorted.sort_unstable(); assert_eq!(sorted, [(200, 150), (200, 200)], "only Red and Blue Board"); - assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true}), "chosen-reverse"), reversed(default)); + assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true})), reversed(default)); } #[test] fn a_non_boolean_value_is_an_error_not_a_panic() { let (mut s, _) = session(); - for (i, v) in [json!("yes"), json!(1), json!([true]), json!({"on": true})].into_iter().enumerate() { - let (r, bytes) = export(&mut s, json!({"reversePageOrder": v}), &format!("bad-{i}")); + for v in [json!("yes"), json!(1), json!([true]), json!({"on": true})] { + let (r, bytes) = export(&mut s, json!({"reversePageOrder": v})); let e = r.unwrap_err().to_string(); assert!(e.contains("reversePageOrder"), "{e}"); assert!(bytes.is_empty(), "nothing is written for {v}"); From df9ef26b8789e52c2680b74e4040911127f6e855 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 10:00:43 +0100 Subject: [PATCH 08/33] Artboards to PDF: Include Overlapping Areas / Artboard Content Only (#13646) The dialog gets the radio pair right below the file name, Include Overlapping Areas selected. file.export.artboardsToPdf takes "content": "overlapping" (default) or "artboard"; with overlapping, a board's page also shows the visible boards above it where they overlap it, built with the helper Artboards to Files uses. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 30 ++- .../pdf_overlapping_areas_tests.rs | 190 ++++++++++++++++++ .../src/artboards_overlap_dialog_tests.rs | 20 ++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 8 +- 4 files changed, 237 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index d29c389af0..eedb3a6e02 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -745,6 +745,19 @@ fn chosen_documents(doc: &Document, p: &Value, overlapping: bool) -> Result Result { + match p.get("content") { + None | Some(Value::Null) => Ok(true), + Some(v) => match v.as_str() { + Some("overlapping") => Ok(true), + Some("artboard") => Ok(false), + _ => Err(bad(cmd, format!("`content` must be \"overlapping\" or \"artboard\", not {v}"))), + }, + } +} + /// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first. fn chosen_artboards(doc: &Document, p: &Value) -> Vec { let all: Vec = doc.artboards().into_iter().rev().map(|b| b.0).collect(); @@ -765,14 +778,7 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let save = SaveOpts::from_params(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") { - None | Some(Value::Null) => true, - Some(v) => match v.as_str() { - Some("overlapping") => true, - Some("artboard") => false, - _ => return Err(bad(cmd, format!("`content` must be \"overlapping\" or \"artboard\", not {v}"))), - }, - }; + let overlapping = overlapping_param(p, cmd)?; let doc = d.doc.clone(); let mut files = Vec::new(); for (i, one) in chosen_documents(&doc, p, overlapping)?.into_iter().enumerate() { @@ -841,8 +847,9 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); + let overlapping = overlapping_param(p, cmd)?; let mut pages = Vec::new(); - for one in chosen_documents(&doc, p, false)? { + for one in chosen_documents(&doc, p, overlapping)? { 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); @@ -927,7 +934,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, + r##"{"path":str (.pdf),"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)"##, export_artboards, artboards_to_pdf ), @@ -941,5 +948,8 @@ mod first_board_background_tests; #[path = "artboard_cmds/overlapping_areas_tests.rs"] mod overlapping_areas_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_overlapping_areas_tests.rs"] +mod pdf_overlapping_areas_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs new file mode 100644 index 0000000000..cec96d44d7 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs @@ -0,0 +1,190 @@ +//! Artboards to PDF › Include Overlapping Areas / Artboard Content Only (#13646): a board's page +//! also shows the boards stacked above it where they overlap it, boards below never show, and the +//! source document is left alone. + +use super::*; +use photocraft_geom::Rect; + +const RED: [u8; 3] = [220, 30, 30]; +const BLUE: [u8; 3] = [30, 30, 220]; +const WHITE: [u8; 3] = [255, 255, 255]; +const CMD: &str = "file.export.artboardsToPdf"; + +/// The measured test document: 800 x 400, transparent, bottom to top `Red Board` 0,0-200,150 +/// (pixel layer `Red` at 20,20-120,100), `Blue Board` 120,30-320,230 (pixel layer `Blue` at +/// 130,40-230,140) and `Empty Board` 600,0-700,100, all with white backgrounds. +fn session(depth: u32) -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + let board = + |s: &mut Session, name: &str, rect: [i64; 4]| s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap()["layer"].as_u64().unwrap(); + let red = board(&mut s, "Red Board", [0, 0, 200, 150]); + let blue = board(&mut s, "Blue Board", [120, 30, 200, 200]); + let empty = board(&mut s, "Empty Board", [600, 0, 100, 100]); + paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), RED); + paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), BLUE); + (s, [red, blue, empty]) +} + +/// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers. +fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) { + s.edit(name, |doc, _| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + let [r, g, b] = color.map(|c| f32::from(c) / 255.0); + l.surface_mut().unwrap().fill_rect(rect, &photocraft_raster::from_rgba(&fmt, [r, g, b, 1.0])); + doc.layer_mut(LayerId(board)).unwrap().children_mut().unwrap().push(l); + Ok(()) + }) + .unwrap(); +} + +struct Out(std::path::PathBuf); + +impl Out { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("photocraft-pdf-overlap-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Out(dir) + } + fn pdf(&self) -> String { + self.0.join("boards.pdf").to_string_lossy().into_owned() + } +} + +impl Drop for Out { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The JPEG image of every page in a PDF written by [`raster_pdf`], decoded. +fn pages(pdf: &[u8]) -> Vec { + let key = b"/DCTDecode /Length "; + let mut out = Vec::new(); + let mut at = 0; + while let Some(i) = pdf[at..].windows(key.len()).position(|w| w == key) { + let start = at + i + key.len(); + let digits = pdf[start..].iter().take_while(|b| b.is_ascii_digit()).count(); + let len: usize = std::str::from_utf8(&pdf[start..start + digits]).unwrap().parse().unwrap(); + let data = start + digits + b" >>\nstream\n".len(); + out.push(photocraft_io::import("page.jpg", &pdf[data..data + len]).unwrap().document); + at = data + len; + } + out +} + +/// Exports board `board` with `extra` params and reads its one page back. +fn export(s: &mut Session, out: &Out, board: u64, extra: Value) -> Document { + let mut p = json!({"path": out.pdf(), "artboards": [board], "quality": 12}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute(CMD, p).unwrap(); + assert_eq!(r["pages"], 1, "{r}"); + let mut pages = pages(&std::fs::read(out.pdf()).unwrap()); + assert_eq!(pages.len(), 1); + pages.remove(0) +} + +/// The page's pixel at (x, y) as 8-bit RGB. +fn px(d: &Document, x: i32, y: i32) -> [u8; 3] { + let flat = photocraft_compose::flatten(d); + let w = d.size.width as usize; + let p = flat.px[y as usize * w + x as usize].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + [p[0], p[1], p[2]] +} + +/// Within JPEG tolerance. +fn near(got: [u8; 3], want: [u8; 3]) -> bool { + got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8) +} + +#[test] +fn include_overlapping_areas_is_the_default_and_shows_the_board_above() { + for depth in [8, 16] { + let (mut s, [red, _, _]) = session(depth); + let out = Out::new(&format!("default-{depth}")); + for extra in [json!({}), json!({"content": "overlapping"}), json!({"content": null})] { + let page = export(&mut s, &out, red, extra.clone()); + assert_eq!((page.size.width, page.size.height), (200, 150), "{depth} bit {extra}"); + assert!(near(px(&page, 150, 60), BLUE), "{depth} bit {extra}: Blue's pixels, got {:?}", px(&page, 150, 60)); + assert!(near(px(&page, 125, 35), WHITE), "{depth} bit {extra}: Blue Board's background, got {:?}", px(&page, 125, 35)); + assert!(near(px(&page, 110, 50), RED), "{depth} bit {extra}: Red stays red"); + } + } +} + +#[test] +fn artboard_content_only_keeps_todays_page() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("content-only"); + let page = export(&mut s, &out, red, json!({"content": "artboard"})); + assert!(near(px(&page, 150, 60), WHITE), "nothing of Blue Board, got {:?}", px(&page, 150, 60)); + assert!(near(px(&page, 110, 50), RED)); +} + +#[test] +fn boards_below_do_not_show_in_either_mode() { + let (mut s, [red, blue, _]) = session(8); + let out = Out::new("below"); + for content in ["overlapping", "artboard"] { + let page = export(&mut s, &out, blue, json!({"content": content})); + assert_eq!((page.size.width, page.size.height), (200, 200), "{content}"); + // Page (0,0) and (110,50): source (120,30) and (230,80), over Red Board's area or past it. + assert!(near(px(&page, 0, 0), WHITE), "{content}: got {:?}", px(&page, 0, 0)); + assert!(near(px(&page, 110, 50), WHITE), "{content}: got {:?}", px(&page, 110, 50)); + assert!(near(px(&page, 30, 30), BLUE), "{content}"); + } + // A transparent Blue Board would show Red Board's red through it if boards below leaked in. + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + paint(&mut s, red, "Red in overlap", Rect::new(120, 30, 200, 40), RED); + for content in ["overlapping", "artboard"] { + let page = export(&mut s, &out, blue, json!({"content": content})); + // Source (150,35): Red's pixels under Blue Board; the page stays white there. + assert!(near(px(&page, 30, 5), WHITE), "{content}: got {:?}", px(&page, 30, 5)); + } +} + +#[test] +fn every_board_gets_its_page_and_only_the_overlapped_one_changes() { + let (mut s, _) = session(8); + let out = Out::new("all"); + for content in ["overlapping", "artboard"] { + let r = s.execute(CMD, json!({"path": out.pdf(), "content": content, "quality": 12})).unwrap(); + assert_eq!(r["pages"], 3, "{content}"); + let pages = pages(&std::fs::read(out.pdf()).unwrap()); + let red = pages.iter().find(|p| (p.size.width, p.size.height) == (200, 150)).unwrap(); + let empty = pages.iter().find(|p| (p.size.width, p.size.height) == (100, 100)).unwrap(); + let want = if content == "overlapping" { BLUE } else { WHITE }; + assert!(near(px(red, 150, 60), want), "{content}: got {:?}", px(red, 150, 60)); + assert!(near(px(empty, 50, 50), WHITE), "{content}"); + } +} + +#[test] +fn the_source_document_is_unchanged_and_gets_no_history_entry() { + let (mut s, [red, blue, _]) = session(8); + let out = Out::new("source"); + for content in ["overlapping", "artboard"] { + for board in [red, blue] { + let d = s.active().unwrap(); + let (before, rev, past) = (d.doc.clone(), d.revision, d.history.past_len()); + export(&mut s, &out, board, json!({"content": content})); + let d = s.active().unwrap(); + assert!(d.doc == before, "{content} changed the document"); + assert_eq!((d.revision, d.history.past_len()), (rev, past), "{content}"); + } + } +} + +#[test] +fn a_bad_content_value_is_an_error_and_writes_nothing() { + let (mut s, _) = session(8); + let out = Out::new("bad"); + for bad in [json!("both"), json!(""), json!(1), json!(true), json!(["overlapping"]), json!({})] { + assert!(s.execute(CMD, json!({"path": out.pdf(), "content": bad})).is_err(), "{bad}"); + assert!(!std::path::Path::new(&out.pdf()).exists(), "{bad}"); + } +} diff --git a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs index 574e95a139..09ee896693 100644 --- a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs @@ -71,3 +71,23 @@ fn layer_comps_to_files_has_no_overlap_choice() { assert_eq!(h.query_all_by_role(Role::RadioButton).count(), 0); assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("content").is_none()); } + +/// #13646: Artboards to PDF has the same radio pair right below the file name, overlapping first +/// and selected, and OK passes the choice to `file.export.artboardsToPdf` as `content`. +#[test] +fn artboards_to_pdf_offers_the_two_radios_below_the_path() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.artboardsToPdf"); + let radios: Vec = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).collect(); + assert_eq!(radios, [OVERLAPPING, CONTENT_ONLY]); + assert!(selected(&h, OVERLAPPING) && !selected(&h, CONTENT_ONLY)); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + let keys = crate::view_cmds::form_keys(fields); + assert_eq!(keys.iter().position(|k| k == "content"), keys.iter().position(|k| k == "path").map(|i| i + 1), "{keys:?}"); + assert_eq!(crate::filter_dialog::params_of(fields)["content"], "overlapping"); + h.get_by_role_and_label(Role::RadioButton, CONTENT_ONLY).click(); + h.run_steps(4); + assert!(selected(&h, CONTENT_ONLY) && !selected(&h, OVERLAPPING)); + let fields = &h.state_mut().ui.dialog_mut(dialog).unwrap().fields; + assert_eq!(crate::filter_dialog::params_of(fields)["content"], "artboard"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index f0fc43aba6..803bdf7a7b 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -532,7 +532,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + // Include Overlapping Areas / Artboard Content Only, right below the file name. + dialog( + app, + json!({"path": format!("{dir}/{stem}.pdf"), "content": "overlapping", "quality": 10, "__radios": ["content"], + "__labels": {"overlapping": tl!("Include Overlapping Areas"), "artboard": tl!("Artboard Content Only")}, "__order": ["path", "content", "quality"]}), + json!({"content": ["overlapping", "artboard"]}), + ) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] From e55555c0a680f15f4e79cb35c373ef63823d61bb Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 10:36:10 +0100 Subject: [PATCH 09/33] Artboards to PDF: Include Background in Export (#13648) The Artboards to PDF dialog gets the checkbox "Include Background in Export", ticked on first open, and file.export.artboardsToPdf a matching includeBackground param (default true, today's pages unchanged). Unticked, a white board's fill is left out and its page image gets a soft mask (DeviceGray, 8 bpc, FlateDecode, /Matte [1 1 1]): alpha 0 where the board has no pixels. The colour image stays the composite over white, which is what the white matte expects. A page that ends up opaque everywhere gets no mask. Cases the reference application was not measured with (an empty board, other fills, other modes and depths) keep today's opaque page. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 97 ++++++- .../pdf_include_background_tests.rs | 238 ++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 8 +- 3 files changed, 332 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..cd376e09e1 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -701,6 +701,18 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { /// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). /// Pages are sized so the image prints at its resolution. pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { + let pages: Vec = pages.iter().map(|(w, h, dpi, jpeg)| (*w, *h, *dpi, jpeg.clone(), None)).collect(); + raster_pdf_masked(&pages) +} + +/// One page of [`raster_pdf_masked`]: width px, height px, dpi, JPEG bytes and, when the page +/// has transparency, its alpha as a Flate-compressed 8-bit DeviceGray image of the same size. +type PdfPage = (u32, u32, f32, Vec, Option>); + +/// [`raster_pdf`] where a page may carry a soft mask (`/SMask`). The mask has `/Matte [1 1 1]`: +/// the page's colours are already composited over white, so a viewer that honours the mask +/// recovers the true colours, and one that ignores it shows today's white page. +fn raster_pdf_masked(pages: &[PdfPage]) -> Vec { let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); let mut obj = |out: &mut Vec, body: &[u8]| { @@ -709,14 +721,24 @@ pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { out.extend_from_slice(body); out.extend_from_slice(b"\nendobj\n"); }; - // Objects: 1 catalog, 2 page tree, then per page: page, contents, image. - let kids: Vec = (0..pages.len()).map(|i| format!("{} 0 R", 3 + i * 3)).collect(); + // Objects: 1 catalog, 2 page tree, then per page: page, contents, image and, when the page + // has one, its soft mask; numbered in that order. + let mut next = 3; + let first: Vec = pages + .iter() + .map(|page| { + let n = next; + next += if page.4.is_some() { 4 } else { 3 }; + n + }) + .collect(); + let kids: Vec = first.iter().map(|n| format!("{n} 0 R")).collect(); obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); obj(&mut out, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).as_bytes()); - for (i, (w, h, dpi, jpeg)) in pages.iter().enumerate() { + for ((w, h, dpi, jpeg, mask), n) in pages.iter().zip(first) { let k = 72.0 / f64::from(dpi.max(1.0)); let (pw, ph) = (f64::from(*w) * k, f64::from(*h) * k); - let (contents, image) = (4 + i * 3, 5 + i * 3); + let (contents, image, smask) = (n + 1, n + 2, n + 3); obj( &mut out, format!( @@ -726,14 +748,25 @@ pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { ); let stream = format!("q {pw:.3} 0 0 {ph:.3} 0 0 cm /Im0 Do Q"); obj(&mut out, format!("<< /Length {} >>\nstream\n{stream}\nendstream", stream.len()).as_bytes()); + let soft = if mask.is_some() { format!(" /SMask {smask} 0 R") } else { String::new() }; let mut img = format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {} >>\nstream\n", + "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8{soft} /Filter /DCTDecode /Length {} >>\nstream\n", jpeg.len() ) .into_bytes(); img.extend_from_slice(jpeg); img.extend_from_slice(b"\nendstream"); obj(&mut out, &img); + if let Some(mask) = mask { + let mut m = format!( + "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Matte [1 1 1] /Filter /FlateDecode /Length {} >>\nstream\n", + mask.len() + ) + .into_bytes(); + m.extend_from_slice(mask); + m.extend_from_slice(b"\nendstream"); + obj(&mut out, &m); + } } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); @@ -744,16 +777,57 @@ pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { out } +/// Leaves out `one`'s board fill for Artboards to PDF's Include Background in Export unticked +/// (#13648), so what the board's layers don't cover becomes transparent. Only what the reference +/// application was measured with: a white board with layers in an 8-bit RGB document. Anything +/// else (an empty board, another fill, other modes and depths) keeps today's opaque page; the +/// return value says whether the fill was left out. +fn drop_white_fill(one: &mut Document) -> bool { + if one.mode != ColorMode::Rgb || one.depth != SampleType::U8 { + return false; + } + let mut dropped = false; + for board in &mut one.layers { + if board.children().is_some_and(|layers| !layers.is_empty()) + && let Some(artboard) = board.artboard_mut() + && artboard.background == ArtboardBackground::White + { + artboard.background = ArtboardBackground::Transparent; + dropped = true; + } + } + dropped +} + +/// A page's soft mask: its alpha as 8-bit gray, Flate-compressed. `None` when the page is opaque +/// everywhere, so a board its layers cover entirely keeps today's page. +fn soft_mask(px: &[[f32; 4]]) -> Result>> { + let alpha: Vec = px.iter().map(|p| (p[3].clamp(0.0, 1.0) * 255.0).round() as u8).collect(); + if alpha.iter().all(|a| *a == 255) { + return Ok(None); + } + let failed = |e: std::io::Error| EngineError::Other(format!("Artboards to PDF: soft mask: {e}")); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(6)); + std::io::Write::write_all(&mut z, &alpha).map_err(failed)?; + Ok(Some(z.finish().map_err(failed)?)) +} + /// File › Export › Artboards to PDF: one page per board (flattened over white, JPEG-encoded). +/// With `"includeBackground": false` a white board's fill is left out and the page gets a soft +/// mask, so a viewer shows its own background where the board has no pixels. fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToPdf"; let path = str_param(p, "path", cmd)?.to_string(); let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); + let background = p.get("includeBackground").and_then(Value::as_bool).unwrap_or(true); let mut pages = Vec::new(); - for one in chosen_documents(&doc, p)? { - let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); + for mut one in chosen_documents(&doc, p)? { + let masked = !background && drop_white_fill(&mut one); + let composite = photocraft_compose::flatten(&one); + let mask = if masked { soft_mask(&composite.px)? } else { None }; + let buf = composite.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); @@ -761,12 +835,12 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { surf.write_region(one.bounds(), &vals); flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); let (jpeg, _) = encode(&flat, "page.jpg", quality)?; - pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg)); + pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg, mask)); } if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } - write_file(&path, &raster_pdf(&pages))?; + write_file(&path, &raster_pdf_masked(&pages))?; Ok(json!({"path": path, "pages": pages.len()})) } @@ -837,7 +911,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, + r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"includeBackground":bool=true (false: a white board's fill is left out and the page gets a soft mask, so it is transparent where the board's layers have no pixels; an empty board, other fills and documents other than 8-bit RGB keep it)} → {path, pages} (one raster page per board)"##, export_artboards, artboards_to_pdf ), @@ -848,5 +922,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_include_background_tests.rs"] +mod pdf_include_background_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs new file mode 100644 index 0000000000..d95009707c --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs @@ -0,0 +1,238 @@ +//! Artboards to PDF's Include Background in Export (#13648): with `"includeBackground": false` +//! a white board's fill is left out and its page image gets a soft mask (`/SMask`, DeviceGray, +//! 8 bpc, FlateDecode, `/Matte [1 1 1]`), alpha 0 where the board has no pixels. Ticked (the +//! default) keeps today's pages, and so do the cases the reference application was not measured +//! with. +//! +//! The document is the issue's: 800 x 400, RGB, 8 bit, transparent, with, bottom to top, `Red +//! Board` 0,0-200,150 (white, pixel layer `Red` 220,30,30 at 20,20-120,100), `Blue Board` +//! 120,30-320,230 (white, pixel layer `Blue` 30,30,220 at 130,40-230,140) and `Empty Board` +//! 600,0-700,100 (white, no layers). + +use super::*; + +/// The issue's document at `depth` bits. Returns the session and the ids of Red, Blue and Empty +/// Board. +fn session(depth: u32) -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"name": "abpdf-test", "width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap(); + let mut board = |name: &str, rect: [u32; 4], layer: Option<(&str, [u32; 4], &str)>| { + let id = s.execute("layer.new.artboard", json!({"name": name, "rect": rect, "background": "white"})).unwrap()["layer"].as_u64().unwrap(); + if let Some((layer, [x, y, width, height], color)) = layer { + s.execute("layer.select", json!({"layer": id})).unwrap(); + s.execute("layer.new.layer", json!({"name": layer})).unwrap(); + s.execute("select.rect", json!({"x": x, "y": y, "width": width, "height": height, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + } + id + }; + let red = board("Red Board", [0, 0, 200, 150], Some(("Red", [20, 20, 100, 80], "#DC1E1E"))); + let blue = board("Blue Board", [120, 30, 200, 200], Some(("Blue", [130, 40, 100, 100], "#1E1EDC"))); + let empty = board("Empty Board", [600, 0, 100, 100], None); + (s, [red, blue, empty]) +} + +/// Runs the export into a fresh temp file and returns the PDF's bytes. +fn export(s: &mut Session, tag: &str, params: Value) -> Vec { + let path = std::env::temp_dir().join(format!("photocraft-abpdf-bg-{}-{tag}.pdf", std::process::id())); + let mut p = params; + p["path"] = json!(path.to_string_lossy()); + s.execute("file.export.artboardsToPdf", p).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + let _ = std::fs::remove_file(&path); + bytes +} + +/// One image XObject of a PDF: its object number, dictionary text and stream bytes. +struct Image { + num: usize, + dict: String, + data: Vec, +} + +/// The first index at or after `from` where `needle` starts in `hay`. +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option { + hay.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| i + from) +} + +/// Every image XObject in `pdf`, in file order. Searches bytes: the JPEG streams are binary, so +/// offsets in a lossy text copy would drift. +fn images(pdf: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut from = 0; + while let Some(at) = find(pdf, b"/Subtype /Image", from) { + let head = pdf[..at].windows(7).rposition(|w| w == b" 0 obj\n").unwrap(); + let line = pdf[..head].iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); + let num: usize = String::from_utf8_lossy(&pdf[line..head]).parse().unwrap(); + let start = find(pdf, b">>\nstream\n", at).unwrap(); + let dict = String::from_utf8_lossy(&pdf[head..start + 2]).into_owned(); + let len: usize = dict.split("/Length ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + let data_at = start + b">>\nstream\n".len(); + out.push(Image { num, dict, data: pdf[data_at..data_at + len].to_vec() }); + from = data_at + len; + } + out +} + +/// A page's colour image decoded to 8-bit RGBA, row by row. +fn colours(img: &Image) -> (u32, u32, Vec<[u8; 4]>) { + let doc = photocraft_io::import("page.jpg", &img.data).unwrap().document; + let px = photocraft_compose::flatten(&doc).px.iter().map(|p| p.map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + (doc.size.width, doc.size.height, px) +} + +/// A soft mask's Flate stream decoded to its alpha bytes. +fn alpha(mask: &Image) -> Vec { + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut flate2::read::ZlibDecoder::new(mask.data.as_slice()), &mut out).unwrap(); + out +} + +/// The image the colour image's `/SMask N 0 R` names. +fn mask_of<'a>(all: &'a [Image], colour: &Image) -> &'a Image { + let n: usize = colour.dict.split("/SMask ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + all.iter().find(|i| i.num == n).unwrap() +} + +fn close(a: [u8; 4], b: [u8; 3], tol: u8) -> bool { + a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= tol) +} + +#[test] +fn ticked_by_default_keeps_todays_opaque_pages() { + let (mut s, [red, blue, empty]) = session(8); + let default = export(&mut s, "default", json!({"artboards": [red, blue, empty]})); + let ticked = export(&mut s, "ticked", json!({"artboards": [red, blue, empty], "includeBackground": true})); + assert_eq!(default, ticked); + let text = String::from_utf8_lossy(&default); + assert!(!text.contains("/SMask") && !text.contains("/FlateDecode")); + let all = images(&default); + assert_eq!(all.len(), 3); + // The Red Board page: white where the board has no pixels, red inside the layer. + let (w, h, px) = colours(all.iter().find(|i| i.dict.contains("/Width 200 /Height 150")).unwrap()); + assert_eq!((w, h), (200, 150)); + assert!(close(px[(60 * w + 150) as usize], [255, 255, 255], 3)); + assert!(close(px[(60 * w + 70) as usize], [220, 30, 30], 12)); +} + +#[test] +fn unticked_the_red_board_page_gets_a_soft_mask() { + let (mut s, [red, ..]) = session(8); + let pdf = export(&mut s, "unticked", json!({"artboards": [red], "includeBackground": false})); + let all = images(&pdf); + assert_eq!(all.len(), 2, "the colour image and its soft mask"); + let colour = all.iter().find(|i| i.dict.contains("/DeviceRGB")).unwrap(); + let mask = mask_of(&all, colour); + for key in ["/Width 200", "/Height 150", "/ColorSpace /DeviceGray", "/BitsPerComponent 8", "/Matte [1 1 1]", "/Filter /FlateDecode"] { + assert!(mask.dict.contains(key), "{key} in {}", mask.dict); + } + let a = alpha(mask); + assert_eq!(a.len(), 200 * 150); + for y in 0..150u32 { + for x in 0..200u32 { + let inside = (20..120).contains(&x) && (20..100).contains(&y); + assert_eq!(a[(y * 200 + x) as usize], if inside { 255 } else { 0 }, "({x}, {y})"); + } + } + // The measured sample: alpha 0 at page pixel 150,60. + assert_eq!(a[60 * 200 + 150], 0); + // The colours inside the red layer stay red (within JPEG tolerance). + let (w, _, px) = colours(colour); + for (x, y) in [(30, 30), (70, 60), (110, 90)] { + assert!(close(px[(y * w + x) as usize], [220, 30, 30], 12), "({x}, {y}): {:?}", px[(y * w + x) as usize]); + } +} + +#[test] +fn unticked_every_page_with_layers_is_masked_and_the_xref_still_points_at_objects() { + let (mut s, [red, blue, empty]) = session(8); + let pdf = export(&mut s, "all", json!({"artboards": [red, blue, empty], "includeBackground": false})); + let text = String::from_utf8_lossy(&pdf); + assert_eq!(text.matches("/Type /Page ").count(), 3); + // Red and Blue get a mask; the empty board was not measured and keeps today's white page. + assert_eq!(text.matches("/SMask ").count(), 2); + assert_eq!(text.matches("/Matte [1 1 1]").count(), 2); + let all = images(&pdf); + let empty_page = all.iter().find(|i| i.dict.contains("/Width 100 /Height 100") && i.dict.contains("/DeviceRGB")).unwrap(); + assert!(!empty_page.dict.contains("/SMask")); + let (_, _, px) = colours(empty_page); + assert!(px.iter().all(|p| close(*p, [255, 255, 255], 3))); + // Blue Board: transparent outside its layer (board-local 10,10-110,110), opaque inside. + let blue_page = all.iter().find(|i| i.dict.contains("/Width 200 /Height 200") && i.dict.contains("/DeviceRGB")).unwrap(); + let a = alpha(mask_of(&all, blue_page)); + assert_eq!((a[5 * 200 + 5], a[50 * 200 + 50], a[150 * 200 + 150]), (0, 255, 0)); + // Every xref entry points at its own object. + let at = find(&pdf, b"startxref\n", 0).unwrap() + b"startxref\n".len(); + let xref: usize = String::from_utf8_lossy(&pdf[at..]).lines().next().unwrap().parse().unwrap(); + let table = String::from_utf8_lossy(&pdf[xref..]).into_owned(); + let entries: Vec = table.lines().skip(3).take_while(|l| l.ends_with(" n ")).map(|l| l[..10].parse().unwrap()).collect(); + assert_eq!(entries.len(), 2 + 3 * 3 + 2); + for (i, off) in entries.iter().enumerate() { + assert!(pdf[*off..].starts_with(format!("{} 0 obj\n", i + 1).as_bytes()), "object {}", i + 1); + } +} + +#[test] +fn unticked_a_board_its_layer_covers_entirely_stays_opaque() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 200, "background": "transparent"})).unwrap(); + let id = s.execute("layer.new.artboard", json!({"name": "Full", "rect": [0, 0, 120, 80]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": id})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Cover"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 120, "height": 80, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#DC1E1E"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let pdf = export(&mut s, "cover", json!({"includeBackground": false})); + let all = images(&pdf); + assert_eq!(all.len(), 1, "no mask when every pixel is opaque"); + assert!(!all[0].dict.contains("/SMask")); + let (w, h, px) = colours(&all[0]); + assert_eq!((w, h), (120, 80)); + assert!(px.iter().all(|p| close(*p, [220, 30, 30], 12))); +} + +#[test] +fn the_cases_not_measured_keep_todays_page() { + // 16 bit and 32 bit: no mask, white where the board has no pixels. + for depth in [16, 32] { + let (mut s, [red, ..]) = session(depth); + let pdf = export(&mut s, &format!("depth{depth}"), json!({"artboards": [red], "includeBackground": false})); + assert!(!String::from_utf8_lossy(&pdf).contains("/SMask"), "{depth} bit"); + let all = images(&pdf); + let (w, _, px) = colours(&all[0]); + assert!(close(px[(60 * w + 150) as usize], [255, 255, 255], 3), "{depth} bit"); + } + // A black board keeps its fill. + let (mut s, [red, ..]) = session(8); + s.execute("layer.artboard.set", json!({"layer": red, "background": "black"})).unwrap(); + let pdf = export(&mut s, "black", json!({"artboards": [red], "includeBackground": false})); + assert!(!String::from_utf8_lossy(&pdf).contains("/SMask")); + let all = images(&pdf); + let (w, _, px) = colours(&all[0]); + assert!(close(px[(60 * w + 150) as usize], [0, 0, 0], 3)); +} + +#[test] +fn the_source_document_is_unchanged_and_gets_no_history_entry() { + for background in [true, false] { + let (mut s, [red, blue, empty]) = session(8); + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.entries(); + export(&mut s, &format!("src{background}"), json!({"artboards": [red, blue, empty], "includeBackground": background})); + let d = s.active().unwrap(); + assert_eq!(d.history.entries(), steps, "includeBackground {background}"); + assert!(d.doc.artboards().iter().all(|b| b.2.background == ArtboardBackground::White), "includeBackground {background}"); + assert_eq!(d.doc.layers.len(), before.layers.len()); + } +} + +#[test] +fn a_param_that_is_not_a_bool_does_not_panic() { + let (mut s, [red, ..]) = session(8); + for bad in [json!("no"), json!(0), json!(null), json!([false]), json!({"x": 1})] { + let pdf = export(&mut s, "bad", json!({"artboards": [red], "includeBackground": bad})); + assert!(!String::from_utf8_lossy(&pdf).contains("/SMask"), "{bad}: treated as the default"); + } + assert!(s.execute("file.export.artboardsToPdf", json!({"includeBackground": false})).is_err(), "no path"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..37d3bfeb57 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -514,7 +514,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + // Include Background in Export is ticked on first open (#13648). + dialog( + app, + json!({"path": format!("{dir}/{stem}.pdf"), "includeBackground": true, "quality": 10, "__order": ["path", "includeBackground", "quality"], + "__labels": {"includeBackground": tl!("Include Background in Export")}}), + json!({}), + ) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] From d5f034563d61932efdfed8e89140117e8a93191f Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 11:11:28 +0100 Subject: [PATCH 10/33] Artboards: keep a clipped board's own effects and mask in overlapping exports The board above keeps all its layers when it has effects of its own, so its shadow or glow still comes from layers outside the exported board, and its mask now also clips those effects (Layer Mask Hides Effects), as the artboard did. A mask on that board is kept inside the board rect instead of being replaced. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 32 ++++++++-- .../pdf_overlapping_areas_tests.rs | 60 +++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index eedb3a6e02..187b4e9c5b 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -673,16 +673,19 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { continue; } let mut group = l.clone(); + // The board's own shadow or glow is built from all its layers, so they stay whole. + let fx = photocraft_compose::effects::has_effects(&group); if let LayerContent::Group(g) = &mut group.content { g.artboard = None; - cut_pixels(&mut g.children, overlap, 0); + if !fx { + cut_pixels(&mut g.children, overlap, 0); + } } let reach = photocraft_compose::change_bounds(&group, doc.bounds()); if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) { - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0]); - mask.surface.fill_rect(ab.rect, &[1.0]); - group.mask = Some(mask); + group.mask = Some(board_mask(group.mask.take(), ab.rect)); + // The artboard clipped its own effects too; a plain mask would only shape them. + group.advanced.layer_mask_hides_effects |= fx; } if let (Some(bg), Some(children)) = (ab.background.rgba(), group.children_mut()) { let fmt = doc.pixel_format(); @@ -695,6 +698,25 @@ fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { out } +/// A mask that hides everything outside `board` and, inside it, what the board's own `mask` hid +/// (its density baked in), so a board clipped to its rect keeps the mask the user painted. +fn board_mask(mask: Option, board: Rect) -> photocraft_doc::LayerMask { + let own = mask.filter(|m| m.enabled); + let mut out = own.clone().unwrap_or_else(photocraft_doc::LayerMask::reveal_all); + out.surface = Surface::with_default(out.surface.format(), &[0.0]); + out.density = 1.0; + let kept = own.and_then(|m| { + let mut px = m.surface.try_read_region(board).ok()?; + px.iter_mut().for_each(|v| *v = 1.0 - m.density * (1.0 - *v)); + out.surface.try_write_region(board, &px).ok() + }); + if kept.is_none() { + out.surface = Surface::with_default(out.surface.format(), &[0.0]); + out.surface.fill_rect(board, &[1.0]); + } + out +} + /// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to /// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers /// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board. diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs index cec96d44d7..0f55e3518e 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_overlapping_areas_tests.rs @@ -188,3 +188,63 @@ fn a_bad_content_value_is_an_error_and_writes_nothing() { assert!(!std::path::Path::new(&out.pdf()).exists(), "{bad}"); } } + +/// A drop shadow on the board above itself is built from all its layers, so a layer outside the +/// exported board still casts it into the page, as it does in the document. +#[test] +fn a_shadow_on_the_board_above_still_comes_from_layers_outside_the_page() { + use photocraft_doc::effects::{Contour, FxCommon, Shadow}; + let (mut s, [red, blue, _]) = session(8); + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + // Caster at 160..170 x 180..190 (in Blue Board, below Red Board); its shadow, 40 px up and to + // the left, falls on 120..130 x 140..150, inside both boards and clear of Blue's pixels. + paint(&mut s, blue, "Caster", Rect::new(160, 180, 170, 190), [0, 160, 0]); + s.edit("Shadow", |doc, _| { + doc.layer_mut(LayerId(blue)).unwrap().effects.items.push(photocraft_doc::Effect::DropShadow(Shadow { + common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + color: Color::rgb(0.0, 0.0, 0.0), + angle: -45.0, + use_global_light: false, + distance: 40.0_f32.hypot(40.0), + spread: 0.0, + size: 0.0, + contour: Contour::Linear, + anti_alias: false, + noise: 0.0, + knocks_out: true, + })); + Ok(()) + }) + .unwrap(); + let source = s.active().unwrap().doc.clone(); + let flat = photocraft_compose::flatten(&source); + let at = flat.px[145 * 800 + 125].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + assert_eq!([at[0], at[1], at[2]], [0, 0, 0], "the shadow lands there in the document"); + let out = Out::new("board-shadow"); + let page = export(&mut s, &out, red, json!({})); + assert!(near(px(&page, 125, 145), [0, 0, 0]), "got {:?}", px(&page, 125, 145)); + let src = flat.px[50 * 800 + 110].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(near(px(&page, 110, 50), RED), "got {:?}, source {src:?}", px(&page, 110, 50)); +} + +/// A mask on the board above keeps hiding what it hid when the board is clipped to its rect. +#[test] +fn a_mask_on_the_board_above_still_hides_its_part() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Mask", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + // A canvas-wide fill reaches past the board, so the export clips the board to its rect. + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + board.children_mut().unwrap().insert(0, fill); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(140, 50, 160, 70), &[0.0]); + board.mask = Some(mask); + Ok(()) + }) + .unwrap(); + let out = Out::new("board-mask"); + let page = export(&mut s, &out, red, json!({})); + assert!(near(px(&page, 150, 60), WHITE), "masked out: Red Board's background, got {:?}", px(&page, 150, 60)); + assert!(near(px(&page, 170, 60), BLUE), "got {:?}", px(&page, 170, 60)); + assert!(near(px(&page, 110, 50), RED), "outside Blue Board, got {:?}", px(&page, 110, 50)); +} From 5cc048f7b96c57983b64789c4e44a54ffd7104d1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 11:52:59 +0100 Subject: [PATCH 11/33] WIP: Artboards to PDF: Document Per Artboard (#13649) From fd841cddc6497124c3397f44c83176dfdaf0b7d4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 12:07:25 +0100 Subject: [PATCH 12/33] Artboards to PDF: a hidden board keeps its background (#13648) artboard_document shows the board it extracts, so Include Background unticked also emptied a hidden board's page. Hidden boards were not measured in the reference application; read the visibility from the source document and keep today's opaque page for them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 8 ++++++-- .../artboard_cmds/pdf_include_background_tests.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index cd376e09e1..f6b29ca89c 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -823,8 +823,12 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let quality = f64_param(p, "quality").or(Some(10.0)); let background = p.get("includeBackground").and_then(Value::as_bool).unwrap_or(true); let mut pages = Vec::new(); - for mut one in chosen_documents(&doc, p)? { - let masked = !background && drop_white_fill(&mut one); + for id in chosen_artboards(&doc, p) { + let Some(mut one) = artboard_document(&doc, id)? else { continue }; + // A hidden board was not measured and keeps today's opaque page. `artboard_document` + // shows the board, so its visibility is read from the source. + let visible = doc.layer(id).is_some_and(|l| l.visible); + let masked = !background && visible && drop_white_fill(&mut one); let composite = photocraft_compose::flatten(&one); let mask = if masked { soft_mask(&composite.px)? } else { None }; let buf = composite.over_background([1.0, 1.0, 1.0]); diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs index d95009707c..6d359b58a9 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs @@ -203,6 +203,18 @@ fn the_cases_not_measured_keep_todays_page() { let (w, _, px) = colours(&all[0]); assert!(close(px[(60 * w + 150) as usize], [255, 255, 255], 3), "{depth} bit"); } + // A hidden board keeps its fill. + let (mut s, [red, ..]) = session(8); + s.edit("Hide", |doc, _| { + doc.layer_mut(LayerId(red)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let pdf = export(&mut s, "hidden", json!({"artboards": [red], "includeBackground": false})); + assert!(!String::from_utf8_lossy(&pdf).contains("/SMask"), "hidden board"); + let all = images(&pdf); + let (w, _, px) = colours(&all[0]); + assert!(close(px[(60 * w + 150) as usize], [255, 255, 255], 3), "hidden board"); // A black board keeps its fill. let (mut s, [red, ..]) = session(8); s.execute("layer.artboard.set", json!({"layer": red, "background": "black"})).unwrap(); From 73bbd2afbcba8ea7683d49eb973424b17453f4a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 12:12:11 +0100 Subject: [PATCH 13/33] Artboards to PDF: Document Per Artboard (#13649) file.export.artboardsToPdf takes "mode": "multiPage" (default, one file at path) or "perArtboard" (one single-page PDF per board, /.pdf; dir and prefix default to those of path). Names are sanitized and a name an earlier board already took, ignoring case, gets -2, -3. Every page is encoded before any file is written. The dialog shows the Multi-Page Document / Document Per Artboard radio pair. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 69 ++++++- .../pdf_document_per_artboard_tests.rs | 173 ++++++++++++++++++ .../view_cmds/artboards_to_pdf_mode_tests.rs | 69 +++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 18 +- 4 files changed, 323 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs create mode 100644 crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 00b0f7e37f..4ee3f4b722 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -7,6 +7,8 @@ //! `layer.translate`) moves the board with its contents. The canvas grows to fit every board, //! in every direction, like Photoshop's auto-expanding artboard canvas ([`fit_canvas`]). +use std::collections::HashSet; + use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -744,14 +746,35 @@ pub fn raster_pdf(pages: &[(u32, u32, f32, Vec)]) -> Vec { out } -/// File › Export › Artboards to PDF: one page per board (flattened over white, JPEG-encoded). +/// File › Export › Artboards to PDF: one page per board (flattened over white, JPEG-encoded), +/// all in one file at `path`, or with `"mode": "perArtboard"` one single-page file per board +/// named by [`pdf_file_stems`]. Every page is encoded before any file is written. fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.artboardsToPdf"; - let path = str_param(p, "path", cmd)?.to_string(); + let per_artboard = match p.get("mode") { + None | Some(Value::Null) => false, + Some(Value::String(m)) if m == "multiPage" => false, + Some(Value::String(m)) if m == "perArtboard" => true, + Some(other) => return Err(bad(cmd, format!("\"mode\" must be \"multiPage\" or \"perArtboard\", not {other}"))), + }; + let path = if per_artboard { p.get("path").and_then(Value::as_str).unwrap_or_default().to_string() } else { str_param(p, "path", cmd)?.to_string() }; + // Document Per Artboard: the folder and prefix default to those of `path` (the dialog's + // `/.pdf`), so `/.pdf`. + let dir = match p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()) { + Some(d) => d.to_string(), + None if per_artboard && path.is_empty() => return Err(bad(cmd, "missing \"dir\" or \"path\"")), + None => path.rfind(['/', '\\']).map_or(String::new(), |i| path[..i].to_string()), + }; let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); + let prefix = match p.get("prefix").and_then(Value::as_str) { + Some(prefix) => prefix.to_string(), + None if path.is_empty() => stem(&doc.name), + None => stem(&path), + }; let quality = f64_param(p, "quality").or(Some(10.0)); let mut pages = Vec::new(); + let mut names = Vec::new(); for one in chosen_documents(&doc, p)? { let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); @@ -762,12 +785,45 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { flat.layers.push(Layer::new("Background", LayerContent::Raster(surf))); let (jpeg, _) = encode(&flat, "page.jpg", quality)?; pages.push((one.size.width, one.size.height, doc.resolution_dpi, jpeg)); + names.push(one.name); } if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } - write_file(&path, &raster_pdf(&pages))?; - Ok(json!({"path": path, "pages": pages.len()})) + if !per_artboard { + write_file(&path, &raster_pdf(&pages))?; + return Ok(json!({"path": path, "pages": pages.len(), "files": [path]})); + } + let mut files = Vec::new(); + for (page, name) in pages.iter().zip(pdf_file_stems(&prefix, &names)) { + let file = join(&dir, &format!("{name}.pdf")); + write_file(&file, &raster_pdf(std::slice::from_ref(page)))?; + files.push(file); + } + Ok(json!({"pages": pages.len(), "files": files})) +} + +/// Document Per Artboard's file names: ``, spaces kept and no separator +/// added, with characters a file name can't hold as `_`. A name an earlier board already took, +/// ignoring letter case, gets the first `-2`, `-3`… no other board's name takes, so every board +/// keeps a file of its own on case-insensitive file systems; the first board of a name keeps it. +fn pdf_file_stems(prefix: &str, names: &[String]) -> Vec { + // Upper case of lower case also folds `ß`/`ẞ` and `σ`/`ς`/`Σ` together, as NTFS does. + let key = |stem: &str| stem.to_lowercase().to_uppercase(); + let plain: Vec = names.iter().map(|name| sanitize(&format!("{prefix}{name}"))).collect(); + let mut taken: HashSet = plain.iter().map(|stem| key(stem)).collect(); + let mut seen = HashSet::new(); + plain + .into_iter() + .map(|stem| { + if seen.insert(key(&stem)) { + return stem; + } + // At most 2 x names keys are taken, so one of these many suffixes is always free. + let last = u64::try_from(names.len()).unwrap_or(u64::MAX).saturating_mul(2).saturating_add(2); + (2..=last).map(|n| format!("{stem}-{n}")).find(|candidate| taken.insert(key(candidate))).unwrap_or(stem) + }) + .collect() } pub fn specs() -> Vec { @@ -837,7 +893,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board)"##, + r##"{"path":str (.pdf; with "mode":"perArtboard" only gives the defaults of "dir" and "prefix"),"mode":"multiPage|perArtboard"="multiPage" (Multi-Page Document: one file at "path"; Document Per Artboard: one single-page file per board, "/.pdf", spaces kept, characters a file name can't hold become "_", a name an earlier board already took, ignoring case, gets "-2", "-3"…),"dir":folder=folder of "path","prefix":str=file name of "path" without ".pdf", else the document name,"artboards":[id]?,"quality":0..12=10} → {path (multi-page), pages, files} (one raster page per board)"##, export_artboards, artboards_to_pdf ), @@ -848,5 +904,8 @@ pub fn specs() -> Vec { #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_document_per_artboard_tests.rs"] +mod pdf_document_per_artboard_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs new file mode 100644 index 0000000000..ae9ea8b264 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs @@ -0,0 +1,173 @@ +//! Artboards to PDF's Document Per Artboard (#13649): one single-page PDF per board, named +//! `.pdf` as the reference application does, next to the default +//! Multi-Page Document (one file, a page per board). + +use super::*; + +/// The issue's measured boards, bottom to top in the Layers panel: name and `[x, y, w, h]`. +const MEASURED: [(&str, [u32; 4]); 3] = [("Red Board", [0, 0, 200, 150]), ("Blue Board", [120, 30, 200, 200]), ("Empty Board", [600, 0, 100, 100])]; + +/// The issue's test document: 800 x 400, RGB, 8 bit, 72 ppi, named `abpdf-test`, with `boards` +/// added bottom to top. +fn session(boards: &[(&str, [u32; 4])]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"name": "abpdf-test", "width": 800, "height": 400, "depth": 8, "resolution": 72})).unwrap(); + for (name, rect) in boards { + s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap(); + } + s +} + +/// A fresh empty folder for one test. +fn folder(test: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-13649-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The file names in `dir`, sorted. +fn listing(dir: &std::path::Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +/// The pages of the PDF at `path`: their MediaBox sizes in points. +fn pages(path: &std::path::Path) -> Vec { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); + text.split("/MediaBox [0 0 ").skip(1).map(|rest| rest.split(']').next().unwrap().to_string()).collect() +} + +fn sorted(mut v: Vec<&str>) -> Vec { + v.sort_unstable(); + v.into_iter().map(str::to_string).collect() +} + +#[test] +fn document_per_artboard_writes_one_single_page_file_per_board() { + let mut s = session(&MEASURED); + let dir = folder("per-board"); + let d = dir.to_string_lossy().into_owned(); + let r = s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "prefix": "pre_"})).unwrap(); + assert_eq!(listing(&dir), sorted(vec!["pre_Blue Board.pdf", "pre_Empty Board.pdf", "pre_Red Board.pdf"])); + for (name, size) in [("pre_Red Board.pdf", "200.000 150.000"), ("pre_Blue Board.pdf", "200.000 200.000"), ("pre_Empty Board.pdf", "100.000 100.000")] { + assert_eq!(pages(&dir.join(name)), [size], "{name}"); + } + // The result lists every written file. + let mut files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + files.sort(); + let mut want: Vec = listing(&dir).iter().map(|n| join(&d, n)).collect(); + want.sort(); + assert_eq!(files, want); + assert_eq!(r["pages"], 3); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn multi_page_document_stays_the_default() { + for mode in [None, Some(json!("multiPage")), Some(Value::Null)] { + let mut s = session(&MEASURED); + let dir = folder("multi"); + let path = join(&dir.to_string_lossy(), "abpdf-test.pdf"); + let mut p = json!({"path": path}); + if let Some(mode) = &mode { + p["mode"] = mode.clone(); + } + let r = s.execute("file.export.artboardsToPdf", p).unwrap(); + assert_eq!(listing(&dir), ["abpdf-test.pdf"], "{mode:?}"); + assert_eq!(pages(&dir.join("abpdf-test.pdf")).len(), 3, "{mode:?}"); + assert_eq!(r["files"], json!([path]), "{mode:?}"); + assert_eq!(r["path"], json!(path), "{mode:?}"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn folder_and_prefix_default_to_those_of_path() { + // The dialog's Path is `/.pdf`: per artboard, the files go into that + // folder as `.pdf`. + let mut s = session(&MEASURED); + let dir = folder("from-path"); + let path = join(&dir.to_string_lossy(), "abpdf-test.pdf"); + s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "path": path})).unwrap(); + assert_eq!(listing(&dir), sorted(vec!["abpdf-testBlue Board.pdf", "abpdf-testEmpty Board.pdf", "abpdf-testRed Board.pdf"])); + let _ = std::fs::remove_dir_all(&dir); + // With only a folder, the prefix is the document name; an empty prefix adds nothing. + let dir = folder("doc-name"); + let d = dir.to_string_lossy().into_owned(); + let red = s.active().unwrap().doc.artboards().into_iter().find(|b| b.1 == "Red Board").unwrap().0.0; + s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "artboards": [red]})).unwrap(); + s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "prefix": "", "artboards": [red]})).unwrap(); + assert_eq!(listing(&dir), ["Red Board.pdf", "abpdf-testRed Board.pdf"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn characters_a_file_name_cannot_hold_become_underscores() { + let mut s = session(&[("a/b:c*d", [0, 0, 20, 20]), ("con", [40, 0, 20, 20])]); + let dir = folder("sanitize"); + let d = dir.to_string_lossy().into_owned(); + s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "prefix": "p?"})).unwrap(); + assert_eq!(listing(&dir), ["p_a_b_c_d.pdf", "p_con.pdf"]); + let _ = std::fs::remove_dir_all(&dir); + // A Windows device name stays usable on its own. + assert_eq!(pdf_file_stems("", &["con".into()]), ["con_"]); +} + +#[test] +fn boards_with_equal_names_still_get_a_file_each() { + // In export order: the first of a name keeps it, a later one gets a free suffix, also when + // the names differ only in letter case or after sanitizing, and never another board's name. + let names: Vec = ["A", "a", "A-2", "A/", "A:"].into_iter().map(String::from).collect(); + assert_eq!(pdf_file_stems("p", &names), ["pA", "pa-3", "pA-2", "pA_", "pA_-2"]); + let mut s = session(&[("Board", [0, 0, 20, 20]), ("board", [40, 0, 20, 20]), ("Board", [80, 0, 20, 20])]); + let dir = folder("collide"); + let d = dir.to_string_lossy().into_owned(); + let r = s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "prefix": ""})).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 3); + let keys: HashSet = files.iter().map(|f| f.as_str().unwrap().to_lowercase()).collect(); + assert_eq!(keys.len(), 3, "{files:?}"); + for f in files { + assert_eq!(pages(std::path::Path::new(f.as_str().unwrap())).len(), 1, "{f}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_board_that_cannot_be_exported_writes_nothing() { + let mut s = session(&MEASURED); + s.execute("layer.new.artboard", json!({"x": i32::MIN, "width": 50, "height": 50, "name": "Far"})).unwrap(); + let dir = std::env::temp_dir().join(format!("photocraft-13649-far-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let d = dir.to_string_lossy().into_owned(); + assert!(s.execute("file.export.artboardsToPdf", json!({"mode": "perArtboard", "dir": d, "prefix": "pre_"})).is_err()); + assert!(!dir.exists(), "nothing was written"); +} + +#[test] +fn a_wrong_mode_or_missing_destination_is_an_error_not_a_panic() { + let mut s = session(&MEASURED); + let dir = std::env::temp_dir().join(format!("photocraft-13649-bad-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = join(&dir.to_string_lossy(), "x.pdf"); + for mode in [json!("nope"), json!("PerArtboard"), json!(""), json!(1), json!(true), json!(["perArtboard"]), json!({})] { + let err = s.execute("file.export.artboardsToPdf", json!({"mode": mode, "path": path})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{mode}: {err}"); + } + // Per artboard needs a folder: from "dir" or from "path". + for p in [json!({"mode": "perArtboard"}), json!({"mode": "perArtboard", "dir": "", "path": ""}), json!({"mode": "perArtboard", "path": 5})] { + let err = s.execute("file.export.artboardsToPdf", p.clone()).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}"); + } + assert!(!dir.exists(), "nothing was written"); +} + +#[test] +fn the_params_doc_names_the_mode() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToPdf").unwrap(); + for word in ["\"mode\"", "multiPage", "perArtboard", "\"dir\"", "\"prefix\"", "files"] { + assert!(spec.params.contains(word), "{word}"); + } +} diff --git a/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs b/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs new file mode 100644 index 0000000000..be1b7009bd --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs @@ -0,0 +1,69 @@ +//! #13649: the Artboards to PDF dialog has the radio pair Multi-Page Document / Document Per +//! Artboard, Multi-Page Document selected on first open, and the choice reaches the command. +use crate::PhotocraftApp; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const COMMAND: &str = "file.export.artboardsToPdf"; + +/// A document named `abpdf-test` with two artboards. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + let app = h.state_mut(); + app.run("file.new", json!({"name": "abpdf-test", "width": 400, "height": 200})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 200, 150], "name": "Red Board"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [250, 0, 100, 100], "name": "Blue Board"})).unwrap(); + app.sync_views(); + h +} + +/// Opens the dialog from its menu entry with Path set to `path`. +fn open(h: &mut Harness<'_, PhotocraftApp>, path: &str) -> u64 { + let ctx = h.ctx.clone(); + let dialog = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("path".into(), json!(path)); + h.run_steps(4); + dialog +} + +fn selected(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::RadioButton, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn listing(dir: &std::path::Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +#[test] +fn multi_page_document_is_selected_on_first_open() { + let t = tempfile::tempdir().unwrap(); + let path = t.path().join("abpdf-test.pdf").to_string_lossy().into_owned(); + let mut h = harness(); + let d = open(&mut h, &path); + assert!(selected(&h, "Multi-Page Document")); + assert!(!selected(&h, "Document Per Artboard")); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + assert_eq!(listing(t.path()), ["abpdf-test.pdf"]); +} + +#[test] +fn document_per_artboard_writes_a_file_per_board() { + let t = tempfile::tempdir().unwrap(); + let path = t.path().join("abpdf-test.pdf").to_string_lossy().into_owned(); + let mut h = harness(); + let d = open(&mut h, &path); + h.get_by_role_and_label(Role::RadioButton, "Document Per Artboard").click(); + h.run_steps(2); + assert!(selected(&h, "Document Per Artboard")); + assert!(!selected(&h, "Multi-Page Document")); + crate::dialogs::confirm(h.state_mut(), d).unwrap(); + assert_eq!(listing(t.path()), ["abpdf-testBlue Board.pdf", "abpdf-testRed Board.pdf"]); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 51c67b83e5..9496d94f4c 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -185,6 +185,18 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { ui.end_row(); continue; } + if k == "mode" && f.get("__command").and_then(Value::as_str) == Some("file.export.artboardsToPdf") { + // Artboards to PDF's page mode (#13649): a radio pair, Multi-Page Document first. + ui.label(""); + let mut mode = v.as_str().unwrap_or("multiPage").to_owned(); + ui.vertical(|ui| { + ui.radio_value(&mut mode, "multiPage".to_owned(), tl!("Multi-Page Document")); + ui.radio_value(&mut mode, "perArtboard".to_owned(), tl!("Document Per Artboard")); + }); + f.insert(k, json!(mode)); + ui.end_row(); + continue; + } if k == "quality" && f.contains_key(JPEG_QUALITY) { ui.label(label(&k)); jpeg_quality_field(ui, f); @@ -514,7 +526,7 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para "file.export.artboardsToPdf" => { let (_, _, name) = doc?; let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10, "mode": "multiPage", "__order": ["path", "quality", "mode"]}), json!({})) } "file.export.dataSetsAsFiles" => { #[cfg(target_arch = "wasm32")] @@ -765,3 +777,7 @@ fn export_contents(app: &mut PhotocraftApp) -> Result { Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()})) }) } + +#[cfg(test)] +#[path = "artboards_to_pdf_mode_tests.rs"] +mod artboards_to_pdf_mode_tests; From 87731277a359b63f1cf4a176fbec8e2309cee5bc Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 12:51:41 +0100 Subject: [PATCH 14/33] Artboards to PDF: a path at the root keeps the root as the per-artboard folder Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 8 +++++++- .../artboard_cmds/pdf_document_per_artboard_tests.rs | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 4ee3f4b722..3a6de02679 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -763,7 +763,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let dir = match p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()) { Some(d) => d.to_string(), None if per_artboard && path.is_empty() => return Err(bad(cmd, "missing \"dir\" or \"path\"")), - None => path.rfind(['/', '\\']).map_or(String::new(), |i| path[..i].to_string()), + None => folder_of(&path), }; let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); @@ -803,6 +803,12 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { Ok(json!({"pages": pages.len(), "files": files})) } +/// The folder part of `path`: `""` for a bare file name, and the root itself for a file at +/// the root (`/x.pdf` gives `/`, not the working directory). +fn folder_of(path: &str) -> String { + path.rfind(['/', '\\']).map_or(String::new(), |i| path[..i.max(1)].to_string()) +} + /// Document Per Artboard's file names: ``, spaces kept and no separator /// added, with characters a file name can't hold as `_`. A name an earlier board already took, /// ignoring letter case, gets the first `-2`, `-3`… no other board's name takes, so every board diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs index ae9ea8b264..2b2a6f6bbd 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_document_per_artboard_tests.rs @@ -171,3 +171,13 @@ fn the_params_doc_names_the_mode() { assert!(spec.params.contains(word), "{word}"); } } + +#[test] +fn the_folder_of_a_file_at_the_root_is_the_root() { + assert_eq!(folder_of("/abpdf-test.pdf"), "/"); + assert_eq!(folder_of(r"\abpdf-test.pdf"), r"\"); + assert_eq!(folder_of("/out/abpdf-test.pdf"), "/out"); + assert_eq!(folder_of(r"C:\out\abpdf-test.pdf"), r"C:\out"); + assert_eq!(folder_of("abpdf-test.pdf"), ""); + assert_eq!(join(&folder_of("/abpdf-test.pdf"), "pre_Red Board.pdf"), "/pre_Red Board.pdf"); +} From 3b6b44d1c89a818f8458f5c081b9363e7b04b395 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:02:50 +0100 Subject: [PATCH 15/33] cargo fmt after merging main Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 8db9463d15..f6b09d0ddd 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -913,11 +913,11 @@ mod file_names_tests; #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] -#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] -mod pdf_reverse_page_order_tests; -#[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] +mod pdf_reverse_page_order_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; From a8975b1505f5df0874ce72e9a757723c0f1a69b4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:57:29 +0100 Subject: [PATCH 16/33] Artboards to Files include-name tests: match main's file names Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds/include_name_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs index 0846e49bb1..228cbf022e 100644 --- a/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/include_name_tests.rs @@ -63,7 +63,8 @@ fn export(s: &mut Session, dir: &str, extra: Value) -> Vec<(String, Document)> { .iter() .map(|f| { let f = f.as_str().unwrap(); - let name = if f.contains("Red Board") { "Red" } else { "Blue" }; + // Files are named , spaces as hyphens (#13633). + let name = if f.contains("Red-Board") { "Red" } else { "Blue" }; (name.to_string(), photocraft_io::import("x.png", &std::fs::read(f).unwrap()).unwrap().document) }) .collect() From 67e1251ce6c620271da9901c9a9da5235eced9f0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 01:36:11 +0100 Subject: [PATCH 17/33] Address CodeRabbit review: test the board above's effects, mask and clip in overlapping exports Regression tests for the overlapping board rework: a Color Overlay on the board above no longer tints its added background, the background's shadow no longer escapes the board, a masked-out layer casts no shadow (Layer Mask Hides Effects stays off), and the board clip stays sharp under a feathered mask. Each compares the file with the document and fails on the previous board_mask version. Co-Authored-By: Claude Opus 5.5 --- .../artboard_cmds/overlapping_areas_tests.rs | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs index 616f0c2fbb..42aaa93194 100644 --- a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -312,3 +312,110 @@ fn a_mask_on_the_board_above_still_hides_its_part() { } } } + +/// A drop shadow at `angle` degrees, `distance` px away, hard-edged and black. +fn shadow(angle: f32, distance: f32) -> photocraft_doc::Effect { + use photocraft_doc::effects::{Contour, FxCommon, Shadow}; + photocraft_doc::Effect::DropShadow(Shadow { + common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), + color: Color::rgb(0.0, 0.0, 0.0), + angle, + use_global_light: false, + distance, + spread: 0.0, + size: 0.0, + contour: Contour::Linear, + anti_alias: false, + noise: 0.0, + knocks_out: true, + }) +} + +/// Exports Red Board as PNG and PSD and checks each file against the document at `points`. +fn assert_files_match_the_document(s: &mut Session, red: u64, tag: &str, points: &[(i32, i32)]) { + let out = Out::new(tag); + for format in ["png", "psd"] { + let f = export(s, &out, red, json!({"format": format})); + for &(x, y) in points { + assert_eq!(px(&f, x, y), source_px(s, x, y), "{format} at ({x},{y})"); + } + } +} + +/// The artboard painted its background beneath the board's own effects: a Color Overlay on the +/// board above tints its layers, not the "Background for" layer the export adds. +#[test] +fn a_color_overlay_on_the_board_above_leaves_its_background_alone() { + use photocraft_doc::effects::FxCommon; + let (mut s, [red, blue, _]) = session(8); + s.edit("Overlay", |doc, _| { + let overlay = + photocraft_doc::Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: Color::rgb(1.0, 0.0, 0.0) }; + doc.layer_mut(LayerId(blue)).unwrap().effects.items.push(overlay); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 125, 35)), WHITE, "Blue Board's background stays white in the document"); + assert_eq!(rgb(source_px(&s, 150, 60)), [255, 0, 0], "Blue is overlaid red in the document"); + assert_files_match_the_document(&mut s, red, "overlay", &[(125, 35), (125, 145), (150, 60), (110, 50)]); +} + +/// The board above's own shadow, cast by the background the export adds, would fall outside +/// that board; the board clip is decided with the background in place, so it is cut off there. +#[test] +fn a_shadow_of_the_added_background_stays_inside_the_board_above() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Shadow", |doc, _| { + // 5 px to the left: Blue's own shadow (125..225) stays inside Blue Board (120..320). + doc.layer_mut(LayerId(blue)).unwrap().effects.items.push(shadow(0.0, 5.0)); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 117, 60)), RED, "the artboard clips its shadow in the document"); + assert_files_match_the_document(&mut s, red, "bg-shadow", &[(115, 60), (117, 60), (119, 60), (125, 60), (110, 50)]); +} + +/// A mask on the board above shapes its effects by default (Layer Mask Hides Effects off): a +/// masked-out layer casts no shadow, in the file as in the document. +#[test] +fn a_masked_out_layer_of_the_board_above_casts_no_shadow() { + let (mut s, [red, blue, _]) = session(8); + // Transparent, so nothing of Blue Board but its layers and their shadow covers Red Board. + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + // Caster at 210..240 x 180..190 (in Blue Board, outside Red Board) under a mask; unmasked its + // shadow, 40 px up and to the left, would fall on 170..200 x 140..150, inside Red Board. + paint(&mut s, blue, "Caster", Rect::new(210, 180, 240, 190), [0, 160, 0]); + s.edit("Mask", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + board.effects.items.push(shadow(-45.0, 40.0_f32.hypot(40.0))); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(Rect::new(205, 175, 245, 195), &[0.0]); + board.mask = Some(mask); + Ok(()) + }) + .unwrap(); + assert!(!s.active().unwrap().doc.layer(LayerId(blue)).unwrap().advanced.layer_mask_hides_effects); + assert_eq!(rgb(source_px(&s, 185, 145)), WHITE, "no shadow from the masked-out caster in the document"); + assert_files_match_the_document(&mut s, red, "mask-shadow", &[(185, 145), (175, 142), (125, 35), (110, 50), (150, 60)]); +} + +/// The board clip is hard, as the artboard's was: a feathered mask on the board above keeps its +/// feather for itself, but the board edge in the file stays sharp. +#[test] +fn the_board_clip_stays_sharp_with_a_feathered_mask() { + let (mut s, [red, blue, _]) = session(8); + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + s.edit("Feather", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + // A canvas-wide fill reaches past the board, so the export clips the board to its rect. + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + board.children_mut().unwrap().insert(0, fill); + board.mask = Some(photocraft_doc::LayerMask { feather: 6.0, ..photocraft_doc::LayerMask::reveal_all() }); + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 120, 145)), [0, 255, 0], "inside Blue Board, at its edge"); + assert_eq!(rgb(source_px(&s, 119, 145)), WHITE, "outside Blue Board, Red Board's background"); + let points = [(114, 145), (117, 145), (119, 145), (120, 145), (122, 145), (126, 145), (150, 31), (150, 28), (110, 50)]; + assert_files_match_the_document(&mut s, red, "feather", &points); +} From 0848d7c51b852e4475b34183dae8b52f4ae24a3f Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 16 Nov 2026 02:05:38 +0100 Subject: [PATCH 18/33] Address CodeRabbit review: per-type tick when a control client sets the file type ui.dialog.set of `format` changed the field without bringing back the new type's Include Artboard Name, so an OK before the next frame sent the tick of the type it left. dialog_set now runs per_format_state right after a `format` change. Co-Authored-By: Claude Opus 5.5 --- .../artboards_include_name_dialog_tests.rs | 22 +++++++++++++++++++ crates/ui-egui/src/control/dispatch.rs | 5 +++++ crates/ui-egui/src/menus/view_cmds.rs | 2 +- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 5 +++-- 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs index 0532489b41..33c8aa14cd 100644 --- a/crates/ui-egui/src/artboards_include_name_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_include_name_dialog_tests.rs @@ -125,3 +125,25 @@ fn layer_comps_to_files_has_no_artboard_name() { assert_eq!(h.query_all_by_role_and_label(Role::CheckBox, INCLUDE).count(), 0); assert!(h.state_mut().ui.dialog_mut(dialog).unwrap().fields.get("includeName").is_none()); } + +/// A control client that picks another file type and confirms before the dialog is drawn again +/// exports with that type's own Include Artboard Name, not the tick of the type it left. +#[test] +fn a_file_type_set_by_a_control_client_brings_its_own_tick_at_once() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + let dir = tempfile::tempdir().unwrap(); + set(&mut h, dialog, "dir", json!(dir.path().to_string_lossy())); + h.get_by_role_and_label(Role::CheckBox, INCLUDE).click(); + h.run_steps(4); + assert!(ticked(&h), "PNG ticked"); + let ctx = h.ctx.clone(); + let (req, _rx) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": dialog, "field": "format", "value": "jpg"})); + assert!(matches!(crate::control::handle(h.state_mut(), &ctx, &req), crate::control::Outcome::Done(_))); + assert_eq!(params(&mut h, dialog)["includeName"], false, "JPEG keeps its own, unticked"); + // OK in the same frame: no border around the board. + let r = crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + let file = r["files"][0].as_str().unwrap().to_string(); + let img = photocraft_io::import("x.jpg", &std::fs::read(&file).unwrap()).unwrap().document; + assert_eq!((img.size.width, img.size.height), (64, 64)); +} diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 86a036a66b..af7a7a5d60 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1146,6 +1146,11 @@ fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { d.fields.remove("sourceLayer"); } d.fields.insert(field.to_string(), value); + // A new file type brings back its own per-type checkboxes now, not on the next frame: + // an OK before then would send the previous type's (#13637). + if field == "format" { + crate::view_cmds::per_format_state(&mut d.fields); + } // A Color Picker's colour shows in its target dialog at once, as a drag would. crate::color_picker_ui::live_preview::sync(app); ok(Value::Null) diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 60d2fadd77..89ef64d7ce 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -20,10 +20,10 @@ mod options; pub use arrange::{Border, borders, cells, drag_border}; pub(crate) use arrange::{document_is_floating, float_window}; -pub(crate) use dialogs::write_copy; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; +pub(crate) use dialogs::{per_format_state, write_copy}; #[cfg(test)] use dispatch::is_enabled_with_engine; pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_without_document}; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 4f9d409828..39150c7c91 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -339,8 +339,9 @@ const RESET_SHELL_KEYS: [&str; 5] = [BATCH_QUALITY, JPEG_CUSTOM, JPEG_QUALITY, P /// When the `format` field has changed, keeps the `__perFormat` keys' values under the type they /// were set for and brings back the new type's (their value at open for a type not seen yet), as -/// Artboards to Files keeps Include Artboard Name per file type. -fn per_format_state(f: &mut Map) { +/// Artboards to Files keeps Include Artboard Name per file type. Also run when a control client +/// sets `format`, so an OK before the next frame sends the new type's values. +pub(crate) fn per_format_state(f: &mut Map) { let Some(keys) = f.get("__perFormat").and_then(Value::as_array).cloned() else { return }; let format = f.get("format").and_then(Value::as_str).unwrap_or_default().to_string(); let seen = f.get(FORMAT_SEEN).and_then(Value::as_str).unwrap_or_default().to_string(); From 20b36b91ae4b9c8843abec29a3ecdf29713b753a Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:34:27 +0100 Subject: [PATCH 19/33] Address CodeRabbit review: check that the blocked Artboards to PDF run fails The reverse-order memory test now asserts that the run into a blocked folder really fails (an error or the status bar's error) and writes nothing, before it checks that the dialog reopens with the last successful value. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs index abef5f2f69..ebc7371bb7 100644 --- a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -99,7 +99,11 @@ fn a_successful_run_is_remembered_a_failed_one_is_not() { assert!(ticked(&h), "remembered after a successful run"); tick(&mut h); assert!(!ticked(&h)); - let _ = confirm(&mut h, d); + assert!(!h.state().ui.status_error, "the first run succeeded: {}", h.state().ui.status); + let r = confirm(&mut h, d); + // The run fails, so it must not be what the next open remembers. + assert!(r.is_err() || h.state().ui.status_error, "the blocked run fails: {r:?}, status {}", h.state().ui.status); + assert!(!std::path::Path::new(&bad).exists(), "the blocked run writes nothing"); if h.state().framework.dialogs.get_dyn(d).is_some() { let ctx = h.ctx.clone(); crate::dialogs::cancel(h.state_mut(), &ctx, d).unwrap(); From 2667bd6f15d13b83797e6f500493a8450fa7a99e Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:55:30 +0100 Subject: [PATCH 20/33] Address CodeRabbit review: a reopened recording keeps its JPEG quality The editor of a recorded Artboards to Files step is built from the command's own plain params, so its values carry no Export Options checkbox. `nest` removed the plain `quality` from every form, and a recorded quality never reached the command again. Values without the checkbox now go to the command as they are. Co-Authored-By: Claude Opus 5.5 --- .../artboards_export_options_dialog_tests.rs | 23 +++++++++++++++++++ .../view_cmds/artboard_export_options.rs | 6 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs index c4e183fc4a..fc4070f8ed 100644 --- a/crates/ui-egui/src/artboards_export_options_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_export_options_dialog_tests.rs @@ -204,3 +204,26 @@ fn options_are_remembered_after_a_successful_run_only() { set(&mut h, dialog, "format", json!("png")); assert!(ticked(&h, "Interlaced")); } + +/// Opens the editor of a recorded step with `recorded`, as Record Again and a playback with the step's dialog on do. +fn reopen(h: &mut H, recorded: Value) -> DialogId { + let dialog = crate::panels::actions::open_recorded_editor(h.state_mut(), ARTBOARDS, &recorded).unwrap(); + h.run_steps(4); + dialog +} + +/// The editor of a recorded step has the command's own plain params, the Export Options among them: OK without +/// changes sends what was recorded, the JPEG quality too. +#[test] +fn a_reopened_recording_keeps_its_export_options() { + let (_t, dir) = tmp(); + let mut h = harness(); + let dialog = reopen(&mut h, json!({"dir": dir, "prefix": "out", "format": "jpg", "quality": 3, "iccProfile": false})); + let p = sent(&h, dialog); + assert_eq!(p["quality"].as_f64(), Some(3.0), "{p}"); + assert_eq!(p["iccProfile"], false, "{p}"); + let mut h = harness(); + let dialog = reopen(&mut h, json!({"dir": dir, "format": "tiff", "tiffCompression": "lzw", "pngInterlaced": false})); + let p = sent(&h, dialog); + assert_eq!((&p["tiffCompression"], &p["pngInterlaced"]), (&json!("lzw"), &json!(false)), "{p}"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs index ebf88dd06f..36446c1fbb 100644 --- a/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs +++ b/crates/ui-egui/src/menus/view_cmds/artboard_export_options.rs @@ -76,9 +76,11 @@ pub(super) fn rows() -> Vec { /// The command params of the form's values `map`: the chosen type's settings under their plain names while the /// checkbox is ticked, else none; every type's own row keys and the checkbox go. TIFF sends its quality only with JPEG -/// compression, and the depths are numbers. +/// compression, and the depths are numbers. Values without the checkbox come from the editor of a recorded step, +/// whose rows are the command's own plain params: they go to the command as they are. pub(crate) fn nest(map: &mut Map) { - let on = map.remove(CHECKBOX).and_then(|v| v.as_bool()) == Some(true); + let Some(on) = map.remove(CHECKBOX) else { return }; + let on = on.as_bool() == Some(true); let chosen = map.get("format").and_then(Value::as_str).and_then(kind).filter(|_| on); let own: Vec = map.keys().filter(|k| k.split_once('.').is_some_and(|(kind, _)| KINDS.contains(&kind))).cloned().collect(); let mut settings = Map::new(); From ff4fbc294eff0232603f1b963f35df93f45b01c7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:55:31 +0100 Subject: [PATCH 21/33] Address CodeRabbit review: report Interlaced on palette PNG exports The palette PNG path wrote an Indexed Color document without interlacing and said nothing; the band-wise PNG path warns when it turns interlacing off. The palette path now adds the same kind of warning. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/flat.rs | 3 +++ crates/io/tests/it/modes.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index c299a34908..b12104ab70 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -2396,6 +2396,9 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi)); let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi, opts.encode.png_stereo)?; let mut warnings = vec![format!("written as an 8-bit palette PNG ({} colours)", table.colors.len())]; + if opts.encode.png_interlaced { + warnings.push("written without interlacing: the palette PNG exporter does not interlace".into()); + } if opts.encode.embed_metadata && opts.xmp == XmpEmbed::All && !doc.metadata.text.is_empty() { warnings.push("text metadata is not supported by the palette PNG exporter; it will be dropped".into()); } diff --git a/crates/io/tests/it/modes.rs b/crates/io/tests/it/modes.rs index b1bfff3d30..ad3ac65415 100644 --- a/crates/io/tests/it/modes.rs +++ b/crates/io/tests/it/modes.rs @@ -153,6 +153,20 @@ fn indexed_png_keeps_the_document_resolution() { assert!((back.resolution_dpi - 300.0).abs() < 0.01, "{}", back.resolution_dpi); } +#[test] +fn indexed_png_reports_that_it_is_not_interlaced() { + // Interlaced was dropped without a word for an Indexed Color document; the RGB path warns. + let mut d = doc(ColorMode::Indexed); + d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0]], transparent: None }); + let mut opts = photocraft_io::ExportOptions::default(); + opts.encode.png_interlaced = true; + let r = photocraft_io::export(&d, "x.png", &opts).unwrap(); + assert_eq!((r.bytes[25], r.bytes[28]), (3, 0), "a palette PNG, not interlaced"); + assert!(r.warnings.iter().any(|w| w.contains("without interlacing")), "{:?}", r.warnings); + let plain = photocraft_io::export(&d, "x.png", &Default::default()).unwrap(); + assert!(!plain.warnings.iter().any(|w| w.contains("interlac")), "{:?}", plain.warnings); +} + #[test] fn indexed_bmp_is_palette_bmp() { // The BMP export wrote an Indexed Color document as 24-bit RGB, so reopening it lost the mode (#3869 follow-up). From 0bd8b76c73967b47063cf576b8499fb13dbab150 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 13:12:19 +0100 Subject: [PATCH 22/33] PR #14292: refuse JPEG quality outside 0-12, return export warnings Artboards to Files accepted any number as `quality` and clamped it while writing, though the params string documents 0..12; it now returns BadParams before any file is written. The warnings of each file's save were dropped; they now come back as `warnings`, each prefixed with the file name, as Save a Copy returns them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 7 ++++--- .../src/cmd/artboard_cmds/export_options.rs | 2 +- .../cmd/artboard_cmds/export_options_tests.rs | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 452ff70758..267c17ad48 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -875,16 +875,17 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect(); let stems = artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str())); let mut files = Vec::new(); + let mut warnings = Vec::new(); for (mut one, name) in boards.into_iter().zip(stems) { board.apply(&mut one, &format); let path = join(&dir, &format!("{name}.{format}")); - save_doc(&one, &path, save)?; + warnings.extend(save_doc(&one, &path, save)?.into_iter().map(|w| format!("{name}.{format}: {w}"))); files.push(path); } if files.is_empty() { return Err(bad(cmd, "no matching artboards")); } - Ok(json!({"files": files})) + Ok(json!({"files": files, "warnings": warnings})) } /// A minimal PDF with one page per JPEG image: (width px, height px, dpi, JPEG bytes). @@ -1020,7 +1021,7 @@ pub fn specs() -> Vec { "file.export.artboardsToFiles", "Artboards to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files} (one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for \" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12? (JPEG),"iccProfile":bool=true,"bmpBits":24|32? (16 unsupported),"tgaBits":24|32?,"tiffCompression":"none|lzw|zip"="none" ("jpeg" unsupported),"pngInterlaced":bool=false,"transparency":bool=true (PNG; false: over white, no alpha),"maximizeCompatibility":bool? (PSD),"preserveArtboard":bool=true (PSD; false: a plain group)} → {files, warnings} (warnings: what a file could not hold, each ": "; one "." per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##, export_artboards, artboards_to_files ), diff --git a/crates/engine/src/cmd/artboard_cmds/export_options.rs b/crates/engine/src/cmd/artboard_cmds/export_options.rs index 9be7249c32..354b2cdf5c 100644 --- a/crates/engine/src/cmd/artboard_cmds/export_options.rs +++ b/crates/engine/src/cmd/artboard_cmds/export_options.rs @@ -51,7 +51,7 @@ pub(super) fn parse(s: &Session, p: &Value, cmd: &str) -> Result<(SaveOpts, Boar } match p.get("quality") { None | Some(Value::Null) => {} - Some(v) if v.as_f64().is_some() => {} + Some(v) if v.as_f64().is_some_and(|q| (0.0..=12.0).contains(&q)) => {} Some(v) => return Err(bad(cmd, format!("`quality` must be a number from 0 to 12, got {v}"))), } let mut save = SaveOpts::from_params(s, p, cmd)?; diff --git a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs index f4eec3589f..62345e5668 100644 --- a/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/export_options_tests.rs @@ -194,6 +194,9 @@ fn bad_option_values_are_errors_and_write_nothing() { json!({"bmpBits": -1}), json!({"quality": "high"}), json!({"quality": [8]}), + json!({"quality": -1}), + json!({"quality": 12.5}), + json!({"quality": 13}), json!({"iccProfile": "yes"}), json!({"pngInterlaced": 1}), json!({"transparency": {}}), @@ -210,3 +213,17 @@ fn bad_option_values_are_errors_and_write_nothing() { assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{bad}: nothing written"); } } + +/// What a file could not hold comes back as a warning naming the file, as Save a Copy reports it: +/// a 24-bit BMP of the transparent board is composited over white. +#[test] +fn export_warnings_reach_the_result() { + let (mut s, clear, white) = session(); + let dir = &tmp("warnings"); + let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "prefix": "", "format": "bmp", "artboards": [clear], "bmpBits": 24})).unwrap(); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("Clear.bmp: ") && w.contains("over white"))), "{r}"); + let opaque = s.execute("file.export.artboardsToFiles", json!({"dir": dir, "prefix": "", "format": "png", "artboards": [white]})).unwrap(); + let warnings = opaque["warnings"].as_array().unwrap(); + assert!(warnings.iter().all(|w| w.as_str().is_some_and(|w| w.starts_with("White.png: ") && !w.contains("over white"))), "{opaque}"); +} From 2d4fcc5e2e7c2ef4ec7d454c088885a3ceb42361 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 13:06:17 +0100 Subject: [PATCH 23/33] Title bar, options bar and panel bodies replay again: memoized views keyed by their versions (#16118) The move to memoized views (#16002) removed the content versions of the shell slots and the panel bodies, and nothing memoized them instead: the shell runs a slot every pass and the dock a panel body, and both leave memoizing to the app. The title bar, the options bar and every panel body but the canvas are now MemoViews whose key is the version of what they show (panels::region_versions, restored from before #16002), with the app as a covered_by field. The Layers panel's version also holds the effects and group disclosure, which are off the document's revision. The status bar is #16180's own view (StatusProps), so it gets no version here. With more of the window replaying, two things a panel did once per run broke and are fixed: the Layers panel's version holds what it is asked to do in its next pass (open a row for renaming, focus its Name filter, reveal a layer, the Move tool's pick, the picked Smart Filter row), and the Properties Reset session counts the passes the panel showed something else or nothing instead of every pass, since a replayed pass still shows the layer (it took the settings anew and Reset went to the defaults). On top of #16180: commands_run comes back, since every version holds it (a command fired from a key or a menu may change what a bar or panel shows without moving the document revision). The views #16180 puts inside the title and options bars are not decided while the bar's view replays, so the menu bar and Brush Preset trials count that as a replay. The chrome trials run again (no #[ignore]); a dock group itself holds its memoized tab strip and body and runs with the dock area, so it is not counted. A new trial checks that a canvas hover replays the bars and the panel bodies. The Layers panel still runs on pointer moves until storytold/craft-libs#2812 is pinned. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/app.rs | 3 + crates/ui-egui/src/app/frame.rs | 8 +- crates/ui-egui/src/brush_settle_trials.rs | 7 +- crates/ui-egui/src/chrome_settle_trials.rs | 56 ++- crates/ui-egui/src/control.rs | 5 +- .../src/dialogs/adjust_editors/session.rs | 6 +- crates/ui-egui/src/dialogs/color_picker_ui.rs | 14 + crates/ui-egui/src/input/shortcut_dispatch.rs | 8 +- crates/ui-egui/src/lib.rs | 9 + crates/ui-egui/src/menus/invoke.rs | 3 +- crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/options_bar.rs | 7 + crates/ui-egui/src/panels/panel_docking.rs | 8 +- crates/ui-egui/src/panels/properties.rs | 9 + crates/ui-egui/src/panels/region_versions.rs | 323 ++++++++++++++++++ crates/ui-egui/src/tools/crop_ui/bar.rs | 11 + crates/ui-egui/src/tools/perspective_ui.rs | 6 + crates/ui-egui/src/tools/puppet_ui.rs | 13 + crates/ui-egui/src/tools/transform_tool.rs | 1 + .../src/tools/transform_tool/options_bar.rs | 21 ++ 20 files changed, 494 insertions(+), 25 deletions(-) create mode 100644 crates/ui-egui/src/panels/region_versions.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a7ae862e55..231e96f9da 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -114,6 +114,8 @@ impl PhotocraftApp { filter_live: craft::imaging::ui::LivePreview::new(craft::imaging::ui::PreviewLane::Dialog), adjust_open: None, adjust_session: None, + properties_hidden: 0, + properties_tracked: false, dialog_dropper: None, layer_style_child: None, color_targets: HashMap::new(), @@ -153,6 +155,7 @@ impl PhotocraftApp { layer_box: None, finished_pens: Vec::new(), hover_doc: None, + commands_run: 0, hover_layer: None, layers_rename: None, smart_filter_picks: HashMap::new(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 4c418e2e4d..a11b0c1358 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -231,8 +231,8 @@ impl PhotocraftApp { AppShell::new(WindowKey::main()) .window_title(window_title) .screen_mode(Bind::bound(&mut mode)) - .title_bar_if(menu_bar, |ui, _cx, app| panels::title_bar(app, ui)) - .options_bar(options_bar && !home, |ui, _cx, app| panels::options_bar(app, ui)) + .title_bar_if(menu_bar, |ui, _cx, app| panels::region_versions::show_title_bar(app, ui)) + .options_bar(options_bar && !home, |ui, _cx, app| panels::region_versions::show_options_bar(app, ui)) .status(status_bar && !home, |ui, _cx, app| panels::status_bar(app, ui)) .body(|ui, cx, app| { if home { @@ -247,6 +247,10 @@ impl PhotocraftApp { }) .show(ui, self); self.ui.view.screen_mode = mode; + // The Properties Reset session starts anew once the panel was not shown (`properties_hidden`). + if !crate::panel_docking::is_front(self, "properties") { + self.properties_hidden = self.properties_hidden.saturating_add(2); + } // Over the window: the background job and update dialogs before the host runs, then every // hosted dialog, then the other OS windows' contents. jobs_ui::dialog(self, ui); diff --git a/crates/ui-egui/src/brush_settle_trials.rs b/crates/ui-egui/src/brush_settle_trials.rs index b1b818bb82..43a83c247d 100644 --- a/crates/ui-egui/src/brush_settle_trials.rs +++ b/crates/ui-egui/src/brush_settle_trials.rs @@ -12,9 +12,12 @@ use crate::state::Tool; type H = Harness<'static, Box>; -/// How the memoized view whose props type is named `props` took part in the last pass. +/// How the memoized view whose props type is named `props` took part in the last pass. A view inside the options bar's +/// own view (`region_versions::OptionsSlot`) is not decided when that view replays: it replays with it. fn run_of(h: &H, props: &str) -> Option { - last_pass_memo_runs(&h.ctx).into_iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| run) + let runs = last_pass_memo_runs(&h.ctx); + let own = runs.iter().find(|(name, _, _)| name.contains(props)).map(|(_, _, run)| *run); + own.or_else(|| runs.iter().any(|(name, _, run)| name.contains("OptionsSlot<") && *run == MemoRun::Replayed).then_some(MemoRun::Replayed)) } #[test] diff --git a/crates/ui-egui/src/chrome_settle_trials.rs b/crates/ui-egui/src/chrome_settle_trials.rs index 4d6338c043..cc375b8b22 100644 --- a/crates/ui-egui/src/chrome_settle_trials.rs +++ b/crates/ui-egui/src/chrome_settle_trials.rs @@ -1,9 +1,10 @@ -//! The window's chrome settles (#15493): a frame whose only input is the pointer moving over the canvas runs no dock -//! group header, panel tab strip or grip and no title bar; each repaints its last run. Before, every frame ran them. -//! What the chrome shows runs it again: the UI language, the toolbar's slots, the title and whether the menu bar -//! takes the menu keys. +//! The window's chrome settles (#15493, #16118): a frame whose only input is the pointer moving over the canvas runs no +//! panel tab strip or grip, no title bar, options bar or status bar and no panel body; each repaints its last run. +//! Before, every frame ran them. What the chrome shows runs it again: the UI language, the toolbar's slots, the title +//! and whether the menu bar takes the menu keys. A dock group itself holds its tab strip and body, which are memoized +//! views, and runs with the dock area around them, so it is not counted. -use craft::ui::runtime::measure::{MemoRun, last_pass_memo_runs, last_pass_runs}; +use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; use egui::accesskit::Role; use egui::{Event, Key, Modifiers, vec2}; use egui_kittest::Harness; @@ -31,11 +32,20 @@ fn harness() -> H { /// The chrome components the last pass ran, by type name. fn chrome_runs(h: &H) -> Vec<(&'static str, u32)> { - const CHROME: [&str; 4] = - ["docking::group::DockGroup<", "docking::group::GroupGrip<", "TabStrip<'_, craft_ui_panels::docking::PanelKey>", "title_bar::bar::TitleBar<"]; + const CHROME: [&str; 3] = ["docking::group::GroupGrip<", "TabStrip<'_, craft_ui_panels::docking::PanelKey>", "title_bar::bar::TitleBar<"]; last_pass_runs(&h.ctx).into_iter().filter(|(ty, _)| CHROME.iter().any(|name| ty.contains(name))).collect() } +/// The memoized views whose type name holds `name` that took part in the last frame as `how`. +fn views(h: &H, name: &str, how: MemoRun) -> usize { + last_frame_memo_runs(&h.ctx).into_iter().filter(|(ty, _, run)| ty.contains(name) && *run == how).count() +} + +/// The memoized views whose type name holds `name` that ran in the last frame. +fn views_ran(h: &H, name: &str) -> usize { + views(h, name, MemoRun::Ran) +} + /// Whether the chrome component named `name` ran in the last pass. fn ran(h: &H, name: &str) -> bool { chrome_runs(h).iter().any(|(ty, _)| ty.contains(name)) @@ -62,9 +72,12 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { for step in 1..=3 { h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); h.run_steps(1); + // The menu bar sits in the title bar's own view: while that replays, the menu bar replays with it. + let title_replayed = views(&h, "TitleSlot<", MemoRun::Replayed) == 1; let views = chrome_views(&h); for kind in ["TabRow", "dock_column::bar::BarProps", "menu::bar::BarProps"] { - assert!(views.iter().any(|(name, _)| name.contains(kind)), "hover step {step}: the chrome shows a {kind} view: {views:?}"); + let shown = views.iter().any(|(name, _)| name.contains(kind)) || (kind == "menu::bar::BarProps" && title_replayed); + assert!(shown, "hover step {step}: the chrome shows a {kind} view: {views:?}"); } let ran: Vec<_> = views.iter().filter(|(_, run)| *run != MemoRun::Replayed).collect(); assert_eq!(ran, Vec::<&(&str, MemoRun)>::new(), "hover step {step}: the chrome's views replay their last run"); @@ -72,8 +85,25 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { } } +/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and the panel bodies. The Layers +/// panel reads the pointer frame for its modifiers and runs on every pointer move until storytold/craft-libs#2812 is +/// pinned, so one panel body may run. +#[test] +fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { + let mut h = harness(); + let at = h.state().last_canvas_rect.center(); + for step in 1..=3 { + h.event(Event::PointerMoved(at + vec2(step as f32, 0.0))); + h.run_steps(1); + for slot in ["TitleSlot<", "OptionsSlot<", "status_bar::StatusProps<"] { + assert_eq!((views_ran(&h, slot), views(&h, slot, MemoRun::Replayed)), (0, 1), "hover step {step}: the {slot} view replays"); + } + let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); + assert!(bodies.0 <= 1 && bodies.1 >= 2, "hover step {step}: the panel bodies replay, Layers aside: {bodies:?}"); + } +} + #[test] -#[ignore = "#15709: the memoized title bar and dock groups replay only once the app state they read is tracked"] fn a_hover_over_the_canvas_runs_no_dock_chrome_and_no_title_bar() { let mut h = harness(); let at = h.state().last_canvas_rect.center(); @@ -89,7 +119,6 @@ fn a_hover_over_the_canvas_runs_no_dock_chrome_and_no_title_bar() { /// and menu titles), a toolbar slot taken off the rail (the toolbar column's grid) and an edit that marks the document unsaved /// (the title). A version that missed one would replay the old chrome. #[test] -#[ignore = "#15709: the memoized title bar and dock groups replay only once the app state they read is tracked"] fn the_chrome_runs_when_what_it_shows_changes() { let mut h = harness(); assert_eq!(chrome_runs(&h), [], "settled"); @@ -98,20 +127,21 @@ fn the_chrome_runs_when_what_it_shows_changes() { if crate::i18n::needs_catalogs() { h.state_mut().session.prefs.edit(|prefs| prefs.interface.language = "fr".into()); h.run_steps(1); - assert!(ran(&h, "TabStrip<") && ran(&h, "TitleBar<"), "a new language runs the tab strips and the title bar: {:?}", chrome_runs(&h)); + assert!(ran(&h, "TabStrip<") && views_ran(&h, "TitleSlot<") > 0, "a new language runs the tab strips and the title bar: {:?}", chrome_runs(&h)); h.run_steps(2); } // Move and Artboard are the first slot's tools: hiding both takes the slot off the rail. h.state_mut().session.prefs.edit(|prefs| prefs.toolbar.hidden.extend(["Move".to_string(), "Artboard".to_string()])); h.run_steps(1); - assert!(ran(&h, "DockGroup<"), "a slot taken off the rail runs the dock groups: {:?}", chrome_runs(&h)); + assert!(views_ran(&h, "Tool>") > 0, "a slot taken off the rail runs the toolbar rail"); h.run_steps(2); assert!(!h.state().session.active().unwrap().is_dirty(), "the new document is saved"); h.state_mut().run("layer.new.layer", json!({})).unwrap(); h.run_steps(1); - assert!(ran(&h, "TitleBar<"), "an unsaved edit runs the title bar: {:?}", chrome_runs(&h)); + // The edit's frame takes two passes, and its second replays what the first ran: the frame's views tell. + assert!(views_ran(&h, "TitleSlot<") > 0, "an unsaved edit runs the title bar"); } /// A dialog closed with Escape runs no command, and the menu bar takes the menu keys again: Alt+F opens the File menu. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 4f80cdd8ae..a91ad8e044 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -83,8 +83,8 @@ fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut Photoc } } -/// The methods that only hand the window input (it reaches a view as a hand's does) or only read: every other method -/// may change app state a view shows, so the window repaints after it. +/// The methods that only hand the window input (it reaches a region as a hand's does) or only read: every other method +/// may change what a settling region shows, so it counts as a command run (`PhotocraftApp::commands_run`). const INPUT_OR_READ: &[&str] = &[ "engine.commands", "jobs.list", @@ -103,6 +103,7 @@ const INPUT_OR_READ: &[&str] = &[ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Reply { if !INPUT_OR_READ.contains(&req.method.as_str()) { + app.commands_run += 1; ctx.request_repaint(); } let saved = app.session.authorize; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 272a14d8f7..9497cb8cbd 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -177,7 +177,11 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj }; let session = photoshop_session(kind); if session { - record.session.track(session_target(doc, id), ui.ctx().cumulative_pass_nr(), &committed); + // The panel's body is a memoized view, so a frame that replays it runs no pass of it: the session follows the + // count of passes the panel showed something else or nothing (`PhotocraftApp::properties_hidden`), which stays + // put while it shows this layer, replays included. + record.session.track(session_target(doc, id), app.properties_hidden, &committed); + app.properties_tracked = true; } follow_color_pick(app, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index 7ee7d34a86..eefb909743 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -275,6 +275,20 @@ pub(crate) fn window_picker_open(app: &PhotocraftApp, window: PickWindow) -> boo .any(|(id, t)| matches!(t, PickTarget::Window { window: w, .. } if *w == window) && app.framework.dialogs.get_by_id::(*id).is_some()) } +/// What `window` shows of its picker, for the content version of the region that holds it: the colour its open +/// picker shows (`None` while none is open) and how many of its answers wait. A settled region runs again when either +/// changes, so it previews the picker's colour and takes its answer without input of its own. +pub(crate) fn window_picker_state(app: &PhotocraftApp, window: PickWindow) -> (Option>, usize) { + let shown = find(app, |t| matches!(t, PickTarget::Window { window: w, .. } if *w == window)).map(|(id, _)| { + app.framework.dialogs.get_by_id::(id).and_then(ColorPickerDialog::current).map(|picked| { + let c = picked.color; + [c.r, c.g, c.b, c.a].map(f32::to_bits) + }) + }); + let waiting = app.color_answers.iter().filter(|(parent, ..)| *parent == window.answers()).count(); + (shown, waiting) +} + /// The Color Picker, when it is the top dialog (another dialog opened over it takes the input). pub(crate) fn top(app: &PhotocraftApp) -> Option { let id = app.framework.dialogs.stack().top()?; diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 8c6d6d14d5..f0af34bbdf 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -579,10 +579,12 @@ pub(crate) fn record_chrome_toggles(ctx: &egui::Context, toggles: &[(egui::Viewp /// group's tool on the press and releases the spring on the key-up; every other command runs on its press only. /// A framework command goes to [`crate::app::framework::run_command`], a PhotoCraft id to [`dispatch_as`]. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, fired: &[Fired]) { - // A fired command repaints the window, as `menus::invoke` does: many of these (the opacity and blend keys, the - // Artboard, Slice and panel commands) change app state without going through `invoke`. A key's repeats change only - // what has a revision or a tool option (brush size, a nudge, a mode step), so they request no repaint here. + // A fired command is a command run, as `menus::invoke` counts one: many of these (the opacity and blend keys, the + // Artboard, Slice and panel commands) change what a settled region shows without going through `invoke`. A key's + // repeats change only what has a revision or a tool option (brush size, a nudge, a mode step), so a held key + // doesn't run every region at the repeat rate. if fired.iter().any(|f| f.target.is_none() && f.phase != FirePhase::Repeat) { + app.commands_run += 1; ctx.request_repaint(); } for f in fired { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 75691ac40b..bf2e942920 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -454,6 +454,12 @@ pub struct PhotocraftApp { /// The Properties panel's adjustment edit in progress, with the tone editor's shown channel /// (`adjust_editors::PropertiesAdjust`). pub(crate) adjust_session: Option, + /// Twice the passes the Properties panel was not in front or ran without showing the Reset session's layer: the + /// session (`adjust_editors`) takes a layer's settings anew after the panel stopped showing it. A pass count would + /// also move while the panel replays its memoized body, which is still showing it. + pub(crate) properties_hidden: u64, + /// Whether the Properties panel's run showed the Reset session's layer (`properties_hidden`). + pub(crate) properties_tracked: bool, /// The Color Picker dialog asking for a screen sample: the dialog and the field that took it. pub(crate) dialog_dropper: Option<(craft::ui::dialog::DialogId, String)>, /// The child dialog (colour picker or contour editor) the open Layer Style dialog has, with that dialog's id. @@ -585,6 +591,9 @@ pub struct PhotocraftApp { pub(crate) hover_doc: Option<[f64; 2]>, /// Layer hovered in the Layers panel, outlined on the canvas. pub(crate) hover_layer: Option, + /// The commands run from any source (`menus::invoke`, the commands keys and surfaces fire, the control channel). Every + /// bar's and panel's version holds it (`panels::region_versions`): a command may change anything a slot shows. + pub(crate) commands_run: u64, /// A layer whose row the Layers panel opens for renaming in its next pass (Layer › Rename /// Layer, the row menu's Rename Layer…). pub(crate) layers_rename: Option, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index a1d93e054c..9b24124092 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -70,7 +70,8 @@ fn keeps_box_drag(id: &str) -> bool { /// Run a command id from any source (menu, shortcut, palette, automation). pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { - // The views that ran before it in this pass show its change in the next one. + // The regions that ran before it in this pass show its change in the next one. + app.commands_run += 1; ctx.request_repaint(); if app.automation_input && let Some(authorize) = app.services.automation_command.as_ref() diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index abafb1bcd3..eaace9cd1b 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -57,6 +57,7 @@ pub(super) mod panel_docking; pub(crate) mod preset_browser; pub mod preset_panels; mod properties; +pub(crate) mod region_versions; pub(crate) mod registry; pub mod smart_ui; pub(crate) mod status_bar; diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index fe52a1a33c..5679c97ced 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -87,6 +87,13 @@ fn ending(app: &PhotocraftApp, tool: Tool) -> Option { } } +/// A key of the bar's commit and cancel cells and of the open outline its hints follow: the canvas opens and ends these +/// edits (a type session, a crop frame, a removal stroke, a lasso outline) without a command, so the options bar's +/// content version holds this key. +pub(crate) fn edit_key(app: &PhotocraftApp) -> (Option, bool) { + (ending(app, app.ui.tool).map(|ending| ending.end), app.canvas_tools.selection.outline_open()) +} + /// The options bar of the active tool. It is the same arrangement in every theme. /// /// Each pass applies the commit or cancel its own bar took; a second pass of a frame applies none of the first pass's. diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 38304229f5..c04b24a2f8 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -221,8 +221,14 @@ struct Panels<'a> { } impl DockPanels for Panels<'_> { + /// A panel body is a memoized view keyed by its version (#16118); the canvas shows state that changes without a + /// command (the view, redraw progress, animation and job overlays), so it runs every pass. fn body(&mut self, panel: &String, ui: &mut egui::Ui, _: &mut BodyCx<'_>) { - body(self.app, ui, panel); + if panel == CANVAS { + body(self.app, ui, panel); + } else { + super::region_versions::show_panel(self.app, ui, panel); + } } /// The canvas group is the document area: it draws its own tabs and documents in the group's rect. The toolbar's diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 97891f5de1..08dd6ac85c 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -58,6 +58,15 @@ fn kind_label(layer: &Layer) -> String { /// mask targets, the layer the panel was opened for) keys the inspector, so a field's typing or /// scrub state stays with its layer. pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // A run that shows no adjustment session ends the one kept (`PhotocraftApp::properties_hidden`). + app.properties_tracked = false; + body(app, ui); + if !app.properties_tracked { + app.properties_hidden = app.properties_hidden.saturating_add(2); + } +} + +fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let inspector = Inspector::new(tl!("Properties")).empty(tl!("No properties")); let Some(st) = app.session.active() else { inspector.show(ui, |_, _| {}); diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs new file mode 100644 index 0000000000..125fdf750b --- /dev/null +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -0,0 +1,323 @@ +//! The shell's title bar and options bar and every docked panel body as memoized views (#16118). The shell runs a slot +//! every pass and the dock a panel body, and leave memoizing to the app; each reads the whole app, so it is a `MemoView` +//! whose key is a version of what it shows: while the version is the same and no input reaches the slot, the frame adds +//! its last run again instead of running every control in it. The status bar is a memoized view of its own +//! (`status_bar::StatusProps`), over the values it shows. A version covers the app data its slot shows that can change while no +//! input reaches the slot: what a command changes, the active document and layer and the tool in every version; what +//! the slot shows of the canvas view, a job or the brush and colours; and what an edit elsewhere changes without a +//! command, such as a box or pin dragged on the canvas. Input inside a slot runs it whatever its version, and so does a +//! repaint it asks for itself. + +use std::hash::{Hash, Hasher}; + +use craft::ui::contract::{MemoProps, MemoView}; + +use super::PhotocraftApp; +use crate::color_picker_ui::PickWindow; + +/// The props of a shell slot's view: the app the slot reads, which its version stands for. One type per slot, so a +/// trial and the frame's memo log tell the views apart. +macro_rules! slot_props { + ($($name:ident: $what:literal),*) => {$( + #[doc = concat!("The ", $what, "'s view: the app it reads, which its version stands for.")] + #[derive(MemoProps)] + struct $name<'a> { + version: u64, + #[memo_props(covered_by = "version", reason = "the slot's version holds everything the slot shows of the app")] + app: &'a mut PhotocraftApp, + } + )*}; +} +slot_props!(TitleSlot: "title bar", OptionsSlot: "options bar"); + +/// The title bar in its slot, replaying while [`title_bar`]'s version holds. +pub(crate) fn show_title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let version = title_bar(app); + let _ = MemoView::new("photocraft.title_bar", TitleSlot { version, app }, |slot: &mut TitleSlot<'_>, ui: &mut egui::Ui| super::title_bar(slot.app, ui)) + .show(ui); +} + +/// The options bar in its slot, replaying while [`options_bar`]'s version holds. +pub(crate) fn show_options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let version = options_bar(app); + let _ = + MemoView::new("photocraft.options_bar", OptionsSlot { version, app }, |slot: &mut OptionsSlot<'_>, ui: &mut egui::Ui| super::options_bar(slot.app, ui)) + .show(ui); +} + +/// A docked panel's body: the panel and the app it reads, which its version stands for. +#[derive(MemoProps)] +struct PanelBody<'a> { + id: &'a str, + version: u64, + #[memo_props(covered_by = "version", reason = "the panel's version holds everything its body shows of the app")] + app: &'a mut PhotocraftApp, +} + +/// Panel `id`'s body, replaying while [`panel`]'s version holds. +pub(crate) fn show_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { + let version = panel(app, id); + let body = PanelBody { id, version, app }; + let _ = + MemoView::new(("photocraft.panel", id), body, |body: &mut PanelBody<'_>, ui: &mut egui::Ui| super::panel_docking::body(body.app, ui, body.id)).show(ui); +} + +/// The version of the options bar: every tool option (`app.ui.tool_options`, all of which the bar shows; keys, the +/// canvas menu, the canvas and its task bars, panels and presets write them without a command), the commit and cancel +/// cells and hints of an edit the canvas opens or ends ([`options_bar::edit_key`](super::options_bar::edit_key)), the +/// Zoom tool's view, and an open Free Transform, Puppet Warp or Perspective Warp, which shows its own members in place +/// of the tool's, with what a drag on the canvas changes (the box, the picked pin, the planes; Escape ends them without +/// a command, #15547), the Crop tool's frame state, the type members' caret or selection, the brush and its presets and +/// the colours. +pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { + let sessions = + (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); + let shown = (serialized(&app.ui.tool_options), super::options_bar::edit_key(app), text_target(app)); + version(app, (view(app), sessions, shown, brush(app), colours(app))) +} + +/// The version of the title bar: the title it shows (the active document's name and its unsaved mark), the language +/// its menu titles are in, whether the menus are in the bar (not in the macOS menu bar) and whether the bar takes the +/// menu keys (F10, Alt, Alt+letter), which a dialog or the shortcut recorder holds back: a dialog closed with Escape +/// runs no command, and the bar registers for the keys again only when it runs. An open menu is an overlay, so the +/// view runs while one is shown. +pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { + let (gate, _) = crate::menus::menu_gate(app); + let keys = (gate.modal, gate.recording_shortcut); + version(app, (super::title_bar::title_text(app), crate::i18n::current().code(), app.services.native_menu.is_none(), keys)) +} + +/// The version of panel `id`'s body. The Navigator shows the active view, the Layers panel the layer the Move tool's +/// rollover outlines on the canvas, which effects lists and groups are open (view state off the document's revision, +/// `DocState::layers_view_revision`), the Smart Filter row picked on its own and what it is asked to do in its next +/// pass (open a row for renaming, focus its Name filter, reveal a layer, follow the Move tool's pick), the Info panel the pointer's document pixel, the zoom and the Eyedropper's Sample +/// Size it samples at and the Crop tool's frame size, the Clone Source panel the pairing at the last hover point, the +/// Modifier Keys panel the latched keys, which their use releases, the Properties panel the colour its well's open +/// Color Picker previews and the answer that picker left, the Histogram the adjustment preview it counts. Brush +/// Settings and Brushes show the brush and its presets; Color, Swatches, Gradients and the Gradient Editor show the +/// colours, and so do Properties (a shape layer's fill and stroke swatches, a gradient fill's Foreground and +/// Background stops, the adjustment editors' swatches) and Character (the colour of new type is the foreground). +/// Character and Paragraph show the type defaults, and they and Properties the values at the caret or selection of the +/// type being edited, which Glyphs inserts at. Every other panel shows only what every version holds. +pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { + match id { + "navigator" => version(app, view(app)), + "layers" => { + let filter_pick = app.session.active().and_then(|st| app.smart_filter_picks.get(&st.doc.id).copied()); + let requests = (app.layers_rename, app.find_layers_focus, app.pending_reveal.as_ref().map(|(layer, _)| *layer), app.move_pick, filter_pick); + version(app, (app.canvas_hover_layer, app.session.active().map(|st| st.layers_view_revision()), requests)) + } + "info" => { + let crop = crate::crop_ui::info_size(app).map(|size| size.map(f64::to_bits)); + version(app, (app.hover_doc.map(|at| at.map(f64::to_bits)), app.current_zoom().to_bits(), app.ui.tool_options.eyedropper.size.pixels(), crop)) + } + "cloneSource" => version(app, app.ui.presets_ui.clone_cursor.map(|(document, at)| (document, at.map(f64::to_bits)))), + "modifierKeys" => version(app, app.ui.shell.latched), + "properties" => version(app, (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app))), + "brushSettings" | "brushes" => version(app, brush(app)), + "histogram" => version(app, adjustment_preview(app)), + "character" => version(app, (colours(app), type_defaults(app), text_target(app))), + "paragraph" => version(app, (type_defaults(app), text_target(app))), + "glyphs" => version(app, text_target(app)), + "color" | "swatches" | "gradients" | "gradientEditor" => version(app, colours(app)), + _ => version(app, ()), + } +} + +/// What every slot may show, joined with `extra`: the commands run (any of them may change anything), the active +/// document, its revision, its active layers and which part of them is targeted (the layer mask, the vector mask, a +/// filter mask, the selected path; the Layers, Channels, Paths and Properties panels and the canvas set it without a +/// command), and the tool. +fn version(app: &PhotocraftApp, extra: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + app.commands_run.hash(&mut hasher); + app.session.active_generation().hash(&mut hasher); + app.session.active_layer_changes().hash(&mut hasher); + app.session.active().map(|st| st.revision).hash(&mut hasher); + (app.ui.mask_target, app.ui.vector_mask_target, app.ui.filter_mask_target, &app.ui.selected_path).hash(&mut hasher); + app.ui.tool.hash(&mut hasher); + extra.hash(&mut hasher); + hasher.finish() +} + +/// A hash of `value` through its serialized form, which holds every stored field: for app state whose type has no +/// `Hash` (floats, framework types). +fn serialized(value: &impl serde::Serialize) -> u64 { + struct HashWriter<'a>(&'a mut std::collections::hash_map::DefaultHasher); + impl std::io::Write for HashWriter<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.write(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + // Writing to a hasher cannot fail, and every tool option serializes (they are saved). + let _ = serde_json::to_writer(HashWriter(&mut hasher), value); + hasher.finish() +} + +/// The brush and its presets, for the options bar: their revisions move with every change of either. +fn brush(app: &PhotocraftApp) -> (u64, u64) { + (app.session.tools.brush_rev, app.session.tools.presets_rev) +} + +/// The Type tool's defaults for new type, for the panels that show them with no type target: an edit in one of them +/// with nothing targeted changes the defaults and runs no command. +fn type_defaults(app: &PhotocraftApp) -> impl Hash + '_ { + let o = &app.ui.tool_options; + (&o.type_font, &o.type_style, o.type_size.to_bits(), &o.type_aa, &o.type_align, &o.type_direction, &o.type_style_defaults) +} + +/// The adjustment preview the Histogram counts while it shows: an adjustment layer's Properties drag (its proposed +/// values) or an Image › Adjustments dialog's preview. Both change on every move with no command until the release. +fn adjustment_preview(app: &PhotocraftApp) -> impl Hash + '_ { + (app.live_adjust.as_ref(), crate::adjust_preview::shown_key(app)) +} + +/// The caret and selection of the type being edited: the type members show the values there, and a click, a drag or an +/// arrow key on the canvas moves them without a command. +fn text_target(app: &PhotocraftApp) -> Option<(u64, Option, usize, usize)> { + app.ui.text_edit.as_ref().map(|edit| (edit.layer, edit.document, edit.caret, edit.anchor)) +} + +/// The foreground and background colours, for the bars and panels that show them. +fn colours(app: &PhotocraftApp) -> [u32; 8] { + let tools = &app.session.tools; + let mut bits = [0; 8]; + for (bit, channel) in bits.iter_mut().zip(tools.foreground.iter().chain(&tools.background)) { + *bit = channel.to_bits(); + } + bits +} + +/// The active document's view as the canvas showed it: its zoom, centre and turn. +fn view(app: &PhotocraftApp) -> Option<[u64; 5]> { + crate::canvas::active_view(app) + .map(|view| [view.zoom.to_bits(), view.center.x.to_bits(), view.center.y.to_bits(), view.rotation.to_bits(), u64::from(view.flip_x)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Tool; + + /// The brush, the colours, the type defaults, the tool options, the type caret, the Move tool's rollover and an + /// adjustment's live preview move the versions of the bars and panels that show them and of no other, so a drag that + /// edits one leaves the rest replaying; a version that missed one would replay a stale bar or panel. + #[test] + fn what_a_region_shows_moves_only_its_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let regions = |app: &PhotocraftApp| -> Vec<(&'static str, u64)> { + let mut all: Vec<(&'static str, u64)> = [ + "layers", + "history", + "navigator", + "info", + "histogram", + "properties", + "character", + "paragraph", + "glyphs", + "brushSettings", + "brushes", + "color", + "swatches", + "gradients", + "gradientEditor", + ] + .into_iter() + .map(|id| (id, panel(app, id))) + .collect(); + all.extend([("optionsBar", options_bar(app)), ("titleBar", title_bar(app))]); + all + }; + let moved = |app: &mut PhotocraftApp, change: &dyn Fn(&mut PhotocraftApp)| -> Vec<&'static str> { + let before = regions(app); + change(app); + regions(app).into_iter().zip(before).filter(|((_, now), (_, was))| now != was).map(|((id, _), _)| id).collect() + }; + assert_eq!(regions(&app), regions(&app), "the same state settles"); + let brush = moved(&mut app, &|app| { + app.session.tools.brush.size += 1.0; + app.session.tools.brush_changed(); + }); + assert_eq!(brush, ["brushSettings", "brushes", "optionsBar"], "the brush"); + assert_eq!(moved(&mut app, &|app| app.session.tools.presets_rev += 1), ["brushSettings", "brushes", "optionsBar"], "the brush presets"); + let colours = moved(&mut app, &|app| app.session.tools.background[2] = 0.5); + assert_eq!(colours, ["properties", "character", "color", "swatches", "gradients", "gradientEditor", "optionsBar"], "the colours"); + assert_eq!(moved(&mut app, &|app| app.ui.tool_options.type_size += 1.0), ["character", "paragraph", "optionsBar"], "the type defaults"); + app.ui.tool = Tool::Crop; + let ratio = moved(&mut app, &|app| app.ui.tool_options.crop.ratio = craft::draw::ui::crop::CROP_RATIOS[1]); + assert_eq!(ratio, ["optionsBar"], "a crop ratio picked in the task bar"); + assert_eq!(moved(&mut app, &|app| crate::crop_ui::toggle_straighten(app)), ["optionsBar"], "Straighten pressed in the task bar"); + assert_eq!(moved(&mut app, &|app| app.ui.tool_options.fill_opacity = 50.0), ["optionsBar"], "a tool option a key sets"); + let sample = moved(&mut app, &|app| app.ui.tool_options.eyedropper.size = craft::color_ui::ui::SampleSize::Avg5); + assert_eq!(sample, ["info", "optionsBar"], "the Sample Size the canvas menu picks"); + app.ui.tool = Tool::Type; + let edit = |caret| crate::state::TextEdit { layer: 1, document: None, caret, anchor: 0, session: String::new(), created: false, mask: false }; + app.ui.text_edit = Some(edit(0)); + let caret = moved(&mut app, &|app| app.ui.text_edit = Some(edit(2))); + assert_eq!(caret, ["properties", "character", "paragraph", "glyphs", "optionsBar"], "the caret moved in the type being edited"); + assert_eq!(moved(&mut app, &|app| app.canvas_hover_layer = Some(photocraft_doc::LayerId(1))), ["layers"], "the Move tool's rollover on the canvas"); + let preview = moved(&mut app, &|app| app.live_adjust = Some((photocraft_doc::LayerId(1), serde_json::json!({"brightness": 10})))); + assert_eq!(preview, ["histogram"], "an adjustment layer's live preview"); + } + + /// Opening or closing a layer's effects list or a group is view state off the document's revision, and a command + /// the engine runs directly is no counted command: the Layers panel's version still moves, so it shows the new rows. + #[test] + fn a_disclosure_toggle_moves_the_layers_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", serde_json::json!({"width": 100, "height": 100})).unwrap(); + let layer = app.session.execute("layer.new.layer", serde_json::json!({})).unwrap()["layer"].as_u64().unwrap(); + app.session.execute("layer.layerStyle.dropShadow", serde_json::json!({"layer": layer})).unwrap(); + let before = panel(&app, "layers"); + app.session.execute("layer.setEffectsExpanded", serde_json::json!({"layer": layer, "expanded": false})).unwrap(); + assert_ne!(panel(&app, "layers"), before, "closing the effects list moves the Layers version"); + } + + /// What every slot may show moves every version: the tool, a targeted layer mask or a selected path (panels and the + /// canvas set them without a command). + #[test] + fn the_tool_and_the_target_move_every_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let all = |app: &PhotocraftApp| (options_bar(app), panel(app, "layers"), title_bar(app)); + let every = |app: &mut PhotocraftApp, name: &str, change: &dyn Fn(&mut PhotocraftApp)| { + let before = all(app); + change(app); + let after = all(app); + assert!(after.0 != before.0 && after.1 != before.1 && after.2 != before.2, "{name} moves every version"); + }; + every(&mut app, "the tool", &|app| app.ui.tool = Tool::Brush); + every(&mut app, "the layer mask targeted", &|app| app.ui.mask_target = true); + every(&mut app, "a path selected", &|app| app.ui.selected_path = Some("work".into())); + } + + /// The UI language moves the title bar's version (its menu titles). + #[test] + fn the_language_moves_the_title_bar() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + if crate::i18n::needs_catalogs() { + let before = title_bar(&app); + let fr = crate::i18n::Lang::from_code("fr").expect("registered language"); + let _lang = crate::i18n::language_scope(fr); + assert_ne!(title_bar(&app), before, "a new UI language"); + } + } + + /// A command a key fires is a command run, as one from a menu is: the opacity and blend keys and the Artboard, + /// Slice and panel commands change what a slot shows without going through `menus::invoke`. + #[test] + fn a_fired_command_moves_every_version() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let before = (options_bar(&app), panel(&app, "layers"), title_bar(&app)); + let fired = crate::blend_keys::test_fired(craft::draw::ui::artboard::ArtboardCommand::AddNew.into()); + crate::shortcut_dispatch::run_fired(&mut app, &egui::Context::default(), &[fired]); + assert!(app.ui.artboard_tool.adding, "Add New Artboard ran"); + let after = (options_bar(&app), panel(&app, "layers"), title_bar(&app)); + assert!(after.0 != before.0 && after.1 != before.1 && after.2 != before.2, "every version moved"); + } +} diff --git a/crates/ui-egui/src/tools/crop_ui/bar.rs b/crates/ui-egui/src/tools/crop_ui/bar.rs index be0399ff65..cdd56b06c9 100644 --- a/crates/ui-egui/src/tools/crop_ui/bar.rs +++ b/crates/ui-egui/src/tools/crop_ui/bar.rs @@ -95,6 +95,17 @@ fn preset_outputs(app: &mut PhotocraftApp, ratio: Option, new_p } } +/// A key of what the bar shows of the Crop tool's frame: Straighten, Reset, the Selection entry and the ✓ and ⊘ cells. +/// The task bar's Straighten and Cancel, the tool's keys and a drag of the frame change them without a command, so the +/// options bar's content version holds this key beside the tool options. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option<(bool, bool, bool, bool)> { + if app.ui.tool != Tool::Crop { + return None; + } + let tool = &app.canvas_tools.crop.tool; + Some((tool.straighten_armed(), tool.modified(), tool.shows_selection_entry(&app.ui.tool_options.crop), commits_shown(app))) +} + /// The ✓ and ⊘ cells show while a crop is pending or the frame was edited. pub(crate) fn commits_shown(app: &PhotocraftApp) -> bool { app.ui.tool == Tool::Crop && (super::pending(app) || app.canvas_tools.crop.tool.modified()) diff --git a/crates/ui-egui/src/tools/perspective_ui.rs b/crates/ui-egui/src/tools/perspective_ui.rs index 22816e725e..6dab3426a1 100644 --- a/crates/ui-egui/src/tools/perspective_ui.rs +++ b/crates/ui-egui/src/tools/perspective_ui.rs @@ -186,6 +186,12 @@ pub fn canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Rect) { } } +/// What the options bar shows of the open session: the mode and the plane count. A plane drawn on the canvas changes +/// them without a command, so the options bar's content version holds them. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option<(PlaneMode, usize)> { + app.distort.perspective.as_ref().map(|s| (s.warp.mode(), s.warp.planes().len())) +} + /// The options bar: the Layout and Warp tabs, the plane count and Remove Planes or the straighten buttons, commit and /// cancel. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/tools/puppet_ui.rs b/crates/ui-egui/src/tools/puppet_ui.rs index 476ba05077..769309c1f5 100644 --- a/crates/ui-egui/src/tools/puppet_ui.rs +++ b/crates/ui-egui/src/tools/puppet_ui.rs @@ -366,6 +366,19 @@ pub fn canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Rect) { } } +/// A key of what the options bar shows of the open session: the options, Show Mesh, the notice, the selected pin's +/// depth and rotation and whether there are pins. A pin added, picked or turned on the canvas changes them without a +/// command, so the options bar's content version holds this key. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option { + use std::hash::{Hash, Hasher}; + let s = app.distort.puppet.as_ref()?; + let (options, pins) = (s.warp.options(), s.warp.pins()); + let picked = s.warp.selected().first().and_then(|&i| pins.get(i).map(|pin| (i, pin.depth, pin.angle.map(f64::to_bits)))); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (options.mode, options.density, options.expansion.to_bits(), s.warp.show_mesh(), &s.notice, picked, pins.is_empty()).hash(&mut hasher); + Some(hasher.finish()) +} + /// The options bar: Mode, Density, Expansion, Show Mesh, the selected pin's depth and rotation, Remove All Pins, /// commit and cancel. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 23929a8c8b..d881c0b6b7 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -42,6 +42,7 @@ pub use commit::{apply_click, auto_commit, cancel, commit, end_if_left, follow_e pub(crate) use draw::styled_composite; pub use draw::{SessionShown, show_in_canvas}; pub(crate) use draw::{moves_selection, selection_map}; +pub(crate) use options_bar::bar_key; pub use options_bar::{options_bar, reset_warp}; pub(crate) use preview::read_surface; pub(crate) use preview::solo_layer; diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index aeb0ce58ba..83369eb96f 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -82,6 +82,27 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// A key of what the bar shows of the open session: the box, its skew, the phase, the interpolation, the reference +/// point, the Warp group's values and the armed split. A drag on the canvas changes them without a command, so the +/// options bar's content version holds this key. +pub(crate) fn bar_key(app: &PhotocraftApp) -> Option { + use std::hash::{Hash, Hasher}; + let t = app.ui.transform.as_ref()?; + let s = &t.session; + let state = s.state(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for p in state.quad.iter().chain([&state.pivot]) { + (p.x.to_bits(), p.y.to_bits()).hash(&mut hasher); + } + (s.skew_v().to_bits(), s.phase(), s.interpolation(), s.reference_point(), s.allows()).hash(&mut hasher); + if let Some(w) = s.warp() { + let v = warp_values(w); + (v.style, v.vertical, v.bend.to_bits(), v.horizontal.to_bits(), v.vertical_distortion.to_bits(), v.grid, w.on_type).hash(&mut hasher); + } + app.transform_preview.as_ref().and_then(|pv| pv.split).hash(&mut hasher); + Some(hasher.finish()) +} + /// The units of the W and H menu, in Photoshop's order. fn size_unit_entries() -> Vec> { let name = |name: &str| Label::from(name.to_string()); From d5a3e093a45771eb303f85fcf650c8edd5779a32 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 17:38:14 +0100 Subject: [PATCH 24/33] PR #14361: the Artboards to PDF params doc has a plain arrow again The Reverse Page Order change wrote the arrow before the result as mis-decoded UTF-8 (three Latin-1 characters). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index d85ddba7e9..c3ebfc8551 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -1154,7 +1154,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##, + r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##, export_artboards, artboards_to_pdf ), From 02e6d6966e0da8df3bb392e1bec15c0c32754e5d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 17:40:50 +0100 Subject: [PATCH 25/33] cargo fmt after merging #14272 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 8bed43f0fb..b59828a0ef 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -940,7 +940,9 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { 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 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()?; From 449cec5def27427dd48fc44e783952f76117054c Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 17:41:25 +0100 Subject: [PATCH 26/33] PR #14454: the PDF overlap radio test reads the first radio pair, now that the page mode pair is below it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/artboards_overlap_dialog_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs index 9be91a4392..5e11c3e424 100644 --- a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs +++ b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs @@ -92,7 +92,8 @@ fn layer_comps_to_files_has_no_overlap_choice() { fn artboards_to_pdf_offers_the_two_radios_below_the_path() { let mut h = harness(); let dialog = open(&mut h, "file.export.artboardsToPdf"); - let radios: Vec = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).collect(); + // The page mode pair (#13649) follows further down; this pair comes first. + let radios: Vec = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).take(2).collect(); assert_eq!(radios, [OVERLAPPING, CONTENT_ONLY]); assert!(selected(&h, OVERLAPPING) && !selected(&h, CONTENT_ONLY)); let radio = top(&h, OVERLAPPING); From 1a7f95c13e5f3a62deb2f18bcfe45306f3b1ba53 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 18:35:40 +0100 Subject: [PATCH 27/33] PR #14292: drop the import the merged export loop no longer uses Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index b59828a0ef..f0c1308a62 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -16,7 +16,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::{CommandSpec, color_param, int, int_i32}; -use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, stem, str_param, write_file}; +use crate::file_cmds::{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. From ef6b794a245a3985626e0e4da460243288e981f8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 18:39:00 +0100 Subject: [PATCH 28/33] Repin craft-libs next at 77c7c623; panel bodies replay on a hover; versions follow review (#16145) craft-libs 77c7c623 brings storytold/craft-libs#2830 (#2812: panels and widgets read the modifiers, not the pointer frame) and #2860 (RasterDisplay::region_fill). With it a canvas hover replays every panel body, and the hover trial now requires that. Versions, from the review: - every version holds the preferences' revision: Preferences' Apply and OK and other prefs writers run no counted command (units on the options bar and Info panel); - the Navigator's version holds the adjustment preview its picture shows, as the Histogram's does; - the Histogram's version holds when its histograms landed, since the worker lands them with no command or revision; - the options bar's version holds whether a canvas gesture runs (the symmetry menu's Transform entry); - Home counts as the Properties panel not shown, so its Reset session starts anew after a Home visit. The chrome trials look at the whole frame (a view that ran in a discarded pass and replayed in the last counts as run); the language check counts the tab rows frame-wide, since the new titles take a second pass. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 170 +++++++++---------- Cargo.toml | 78 ++++----- crates/engine/Cargo.toml | 2 +- crates/ipp/Cargo.toml | 2 +- crates/ui-egui/src/app/frame.rs | 3 +- crates/ui-egui/src/chrome_settle_trials.rs | 24 ++- crates/ui-egui/src/panels/region_versions.rs | 33 +++- 7 files changed, 165 insertions(+), 147 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc668196ee..cde56ccece 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-automation", "craft-behavior", @@ -1406,7 +1406,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "crc32fast", "flate2", @@ -1427,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "rustix 1.1.5", ] @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "base64 0.22.1", "craft-behavior", @@ -1460,7 +1460,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-docpath", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "egui", ] @@ -1504,7 +1504,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "md-5", "rayon", @@ -1513,12 +1513,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-cms", @@ -1538,7 +1538,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-metadata", "craft-xml", @@ -1563,7 +1563,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "thiserror 2.0.21", ] @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "rayon", ] @@ -1579,7 +1579,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1604,7 +1604,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "serde", ] @@ -1612,7 +1612,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1631,12 +1631,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-eps", "craft-idml", @@ -1654,7 +1654,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-atomic", "dirs", @@ -1664,7 +1664,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1679,7 +1679,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1698,7 +1698,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "cap-primitives", "craft-atomic", @@ -1719,12 +1719,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "heic-rs", "rayon", @@ -1733,7 +1733,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1746,7 +1746,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "chrono", "fixed_decimal", @@ -1774,7 +1774,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-xml", "craft-zip", @@ -1784,7 +1784,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-dds", "craft-heif", @@ -1812,7 +1812,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1830,12 +1830,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "thiserror 2.0.21", ] @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-host", "craft-i18n", @@ -1858,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-xml", "craft-zip", @@ -1868,7 +1868,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-i18n", @@ -1882,7 +1882,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -1900,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1912,7 +1912,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-xml", "craft-zip", @@ -1922,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-keymap", @@ -1937,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "blake3", "craft-atomic", @@ -1950,7 +1950,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "flate2", "serde", @@ -1961,7 +1961,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bytemuck", "flate2", @@ -1976,7 +1976,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1985,7 +1985,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "async-channel", "async-io", @@ -2015,7 +2015,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "thiserror 2.0.21", ] @@ -2023,7 +2023,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "encoding_rs", "flate2", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "dispatch2", "egui", @@ -2068,7 +2068,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "chrono", "craft-crw", @@ -2086,7 +2086,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-atomic", "craft-host", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2142,7 +2142,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-keymap", @@ -2154,7 +2154,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2177,7 +2177,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2192,7 +2192,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-theme", @@ -2203,7 +2203,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-atomic", "craft-behavior", @@ -2218,7 +2218,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "serde", "thiserror 2.0.21", @@ -2227,7 +2227,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "serde", "thiserror 2.0.21", @@ -2236,7 +2236,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-keymap", @@ -2251,7 +2251,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "serde", ] @@ -2259,7 +2259,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-i18n", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "accesskit", "craft-behavior", @@ -2329,7 +2329,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2340,7 +2340,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-behavior", "craft-host", @@ -2415,7 +2415,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "chrono", "craft-host", @@ -2444,7 +2444,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "winsafe", ] @@ -2452,7 +2452,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "craft-atomic", "craft-behavior", @@ -2482,7 +2482,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2491,7 +2491,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2501,7 +2501,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3964,7 +3964,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bytemuck", "hayro-interpret", @@ -3994,7 +3994,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4012,7 +4012,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4036,7 +4036,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "flate2", "hayro-ccitt", @@ -5120,7 +5120,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -9513,7 +9513,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bytemuck", "fearless_simd", @@ -9561,7 +9561,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -11197,14 +11197,14 @@ source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2 [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3#7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" +source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" diff --git a/Cargo.toml b/Cargo.toml index 6ad20d8888..0bbdcba3f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,21 +12,21 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -45,34 +45,34 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -337,16 +337,16 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 5a57d66c0b..6cf1a53a76 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,7 +19,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index 9a94307cce..f9480715c4 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "7d8b9615150cc8cdb70d2ca2c3ac085b42af99f3" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } [lints] workspace = true diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index a11b0c1358..7478ecacb6 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -248,7 +248,8 @@ impl PhotocraftApp { .show(ui, self); self.ui.view.screen_mode = mode; // The Properties Reset session starts anew once the panel was not shown (`properties_hidden`). - if !crate::panel_docking::is_front(self, "properties") { + // Home shows no dock, so no Properties panel either. + if home || !crate::panel_docking::is_front(self, "properties") { self.properties_hidden = self.properties_hidden.saturating_add(2); } // Over the window: the background job and update dialogs before the host runs, then every diff --git a/crates/ui-egui/src/chrome_settle_trials.rs b/crates/ui-egui/src/chrome_settle_trials.rs index cc375b8b22..33b0617853 100644 --- a/crates/ui-egui/src/chrome_settle_trials.rs +++ b/crates/ui-egui/src/chrome_settle_trials.rs @@ -4,7 +4,7 @@ //! and whether the menu bar takes the menu keys. A dock group itself holds its tab strip and body, which are memoized //! views, and runs with the dock area around them, so it is not counted. -use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; +use craft::ui::runtime::measure::{MemoRun, last_frame_memo_runs, last_pass_runs}; use egui::accesskit::Role; use egui::{Event, Key, Modifiers, vec2}; use egui_kittest::Harness; @@ -46,15 +46,11 @@ fn views_ran(h: &H, name: &str) -> usize { views(h, name, MemoRun::Ran) } -/// Whether the chrome component named `name` ran in the last pass. -fn ran(h: &H, name: &str) -> bool { - chrome_runs(h).iter().any(|(ty, _)| ty.contains(name)) -} - -/// The chrome's memoized views in the last pass, by type name, and how each took part. +/// The chrome's memoized views in the last frame, by type name, and how each took part: a view that ran in a discarded +/// pass and replayed in the last one counts as run. fn chrome_views(h: &H) -> Vec<(&'static str, MemoRun)> { const CHROME: [&str; 3] = ["docking::group::TabRow<", "dock_column::bar::BarProps<", "menu::bar::BarProps<"]; - last_pass_memo_runs(&h.ctx).into_iter().filter(|(name, _, _)| CHROME.iter().any(|c| name.contains(c))).map(|(name, _, run)| (name, run)).collect() + last_frame_memo_runs(&h.ctx).into_iter().filter(|(name, _, _)| CHROME.iter().any(|c| name.contains(c))).map(|(name, _, run)| (name, run)).collect() } /// The panel tab strips the last pass ran. @@ -85,9 +81,8 @@ fn a_hover_over_the_canvas_replays_the_dock_chrome_and_the_menu_bar() { } } -/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and the panel bodies. The Layers -/// panel reads the pointer frame for its modifiers and runs on every pointer move until storytold/craft-libs#2812 is -/// pinned, so one panel body may run. +/// A hover over the canvas replays the title bar, the options bar, the status bar (its own view) and every panel body: the +/// panels read the modifiers, not the pointer frame (storytold/craft-libs#2812), so a pointer move runs none of them. #[test] fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { let mut h = harness(); @@ -99,7 +94,7 @@ fn a_hover_over_the_canvas_replays_the_bars_and_the_panel_bodies() { assert_eq!((views_ran(&h, slot), views(&h, slot, MemoRun::Replayed)), (0, 1), "hover step {step}: the {slot} view replays"); } let bodies = (views_ran(&h, "region_versions::PanelBody<"), views(&h, "region_versions::PanelBody<", MemoRun::Replayed)); - assert!(bodies.0 <= 1 && bodies.1 >= 2, "hover step {step}: the panel bodies replay, Layers aside: {bodies:?}"); + assert!(bodies.0 == 0 && bodies.1 >= 2, "hover step {step}: every panel body replays: {bodies:?}"); } } @@ -127,7 +122,10 @@ fn the_chrome_runs_when_what_it_shows_changes() { if crate::i18n::needs_catalogs() { h.state_mut().session.prefs.edit(|prefs| prefs.interface.language = "fr".into()); h.run_steps(1); - assert!(ran(&h, "TabStrip<") && views_ran(&h, "TitleSlot<") > 0, "a new language runs the tab strips and the title bar: {:?}", chrome_runs(&h)); + // The new tab titles change label widths, so the frame takes a second pass that replays what the first ran: + // the frame's views tell. + let (tabs, title) = (views_ran(&h, "docking::group::TabRow<"), views_ran(&h, "TitleSlot<")); + assert!(tabs > 0 && title > 0, "a new language runs the tab rows and the title bar: {tabs} tab rows, {title} title bars"); h.run_steps(2); } diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index 125fdf750b..aaad942418 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -73,7 +73,9 @@ pub(crate) fn options_bar(app: &PhotocraftApp) -> u64 { let sessions = (crate::transform_tool::bar_key(app), crate::puppet_ui::bar_key(app), crate::perspective_ui::bar_key(app), crate::crop_ui::bar::bar_key(app)); let shown = (serialized(&app.ui.tool_options), super::options_bar::edit_key(app), text_target(app)); - version(app, (view(app), sessions, shown, brush(app), colours(app))) + // A canvas gesture's start and end change what the bar enables (the symmetry menu's Transform entry). + let gesture = crate::canvas::tools::in_gesture(app); + version(app, (view(app), sessions, shown, brush(app), colours(app), gesture)) } /// The version of the title bar: the title it shows (the active document's name and its unsaved mark), the language @@ -87,13 +89,15 @@ pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { version(app, (super::title_bar::title_text(app), crate::i18n::current().code(), app.services.native_menu.is_none(), keys)) } -/// The version of panel `id`'s body. The Navigator shows the active view, the Layers panel the layer the Move tool's +/// The version of panel `id`'s body. The Navigator shows the active view and the adjustment preview its picture +/// shows, the Layers panel the layer the Move tool's /// rollover outlines on the canvas, which effects lists and groups are open (view state off the document's revision, /// `DocState::layers_view_revision`), the Smart Filter row picked on its own and what it is asked to do in its next /// pass (open a row for renaming, focus its Name filter, reveal a layer, follow the Move tool's pick), the Info panel the pointer's document pixel, the zoom and the Eyedropper's Sample /// Size it samples at and the Crop tool's frame size, the Clone Source panel the pairing at the last hover point, the /// Modifier Keys panel the latched keys, which their use releases, the Properties panel the colour its well's open -/// Color Picker previews and the answer that picker left, the Histogram the adjustment preview it counts. Brush +/// Color Picker previews and the answer that picker left, the Histogram the adjustment preview it counts and the +/// histograms its worker lands (`histogram_panel::update`, with no command). Brush /// Settings and Brushes show the brush and its presets; Color, Swatches, Gradients and the Gradient Editor show the /// colours, and so do Properties (a shape layer's fill and stroke swatches, a gradient fill's Foreground and /// Background stops, the adjustment editors' swatches) and Character (the colour of new type is the foreground). @@ -101,7 +105,7 @@ pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { /// type being edited, which Glyphs inserts at. Every other panel shows only what every version holds. pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { match id { - "navigator" => version(app, view(app)), + "navigator" => version(app, (view(app), adjustment_preview(app))), "layers" => { let filter_pick = app.session.active().and_then(|st| app.smart_filter_picks.get(&st.doc.id).copied()); let requests = (app.layers_rename, app.find_layers_focus, app.pending_reveal.as_ref().map(|(layer, _)| *layer), app.move_pick, filter_pick); @@ -115,7 +119,7 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { "modifierKeys" => version(app, app.ui.shell.latched), "properties" => version(app, (crate::color_picker_ui::window_picker_state(app, PickWindow::Properties), colours(app), text_target(app))), "brushSettings" | "brushes" => version(app, brush(app)), - "histogram" => version(app, adjustment_preview(app)), + "histogram" => version(app, (adjustment_preview(app), histograms(app))), "character" => version(app, (colours(app), type_defaults(app), text_target(app))), "paragraph" => version(app, (type_defaults(app), text_target(app))), "glyphs" => version(app, text_target(app)), @@ -127,10 +131,12 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { /// What every slot may show, joined with `extra`: the commands run (any of them may change anything), the active /// document, its revision, its active layers and which part of them is targeted (the layer mask, the vector mask, a /// filter mask, the selected path; the Layers, Channels, Paths and Properties panels and the canvas set it without a -/// command), and the tool. +/// command), the tool and the preferences (Preferences' Apply and OK and other writers change them through the engine +/// or `prefs.edit`, not as a counted command: units, the language, toolbar slots). fn version(app: &PhotocraftApp, extra: impl Hash) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); app.commands_run.hash(&mut hasher); + app.session.prefs.rev().hash(&mut hasher); app.session.active_generation().hash(&mut hasher); app.session.active_layer_changes().hash(&mut hasher); app.session.active().map(|st| st.revision).hash(&mut hasher); @@ -177,6 +183,11 @@ fn adjustment_preview(app: &PhotocraftApp) -> impl Hash + '_ { (app.live_adjust.as_ref(), crate::adjust_preview::shown_key(app)) } +/// The histograms the Histogram panel shows, by when each landed: a worker lands one with no command or revision. +fn histograms(app: &PhotocraftApp) -> [Option; 2] { + [app.doc_hist.as_ref().map(|h| h.at.to_bits()), app.doc_hist_preview.as_ref().map(|h| h.at.to_bits())] +} + /// The caret and selection of the type being edited: the type members show the values there, and a click, a drag or an /// arrow key on the canvas moves them without a command. fn text_target(app: &PhotocraftApp) -> Option<(u64, Option, usize, usize)> { @@ -263,7 +274,12 @@ mod tests { assert_eq!(caret, ["properties", "character", "paragraph", "glyphs", "optionsBar"], "the caret moved in the type being edited"); assert_eq!(moved(&mut app, &|app| app.canvas_hover_layer = Some(photocraft_doc::LayerId(1))), ["layers"], "the Move tool's rollover on the canvas"); let preview = moved(&mut app, &|app| app.live_adjust = Some((photocraft_doc::LayerId(1), serde_json::json!({"brightness": 10})))); - assert_eq!(preview, ["histogram"], "an adjustment layer's live preview"); + assert_eq!(preview, ["navigator", "histogram"], "an adjustment layer's live preview"); + let landed = moved(&mut app, &|app| { + let key = crate::histogram_panel::HistKey { doc: photocraft_doc::DocId(1), revision: 0, source: 0, preview: 0, max_level: 0 }; + app.doc_hist = Some(crate::histogram_panel::PanelHist { key, at: 30.0, hist: Default::default() }); + }); + assert_eq!(landed, ["histogram"], "a histogram the worker landed"); } /// Opening or closing a layer's effects list or a group is view state off the document's revision, and a command @@ -294,6 +310,9 @@ mod tests { every(&mut app, "the tool", &|app| app.ui.tool = Tool::Brush); every(&mut app, "the layer mask targeted", &|app| app.ui.mask_target = true); every(&mut app, "a path selected", &|app| app.ui.selected_path = Some("work".into())); + every(&mut app, "a preference written", &|app| { + app.session.prefs.edit(|p| p.general.image_interpolation = photocraft_engine::prefs::Interpolation::Nearest) + }); } /// The UI language moves the title bar's version (its menu titles). From 9c3a994ed6d5f90f3e5a4e9178266e21214b7cd9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 18:47:52 +0100 Subject: [PATCH 29/33] PR #14361: the Reverse Page Order dialog test exports every board Export Selected Artboards from main opens ticked while a board is selected, so the dialog exported one page and the test, written before it, expected two. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs index ebc7371bb7..50c0e480fe 100644 --- a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -35,6 +35,8 @@ fn open(h: &mut H, path: &str) -> DialogId { 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(); + // Every board, not only the selected one: Export Selected Artboards opens ticked while a board is selected (#13647). + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "artboards", serde_json::Value::Null).unwrap(); h.run_steps(4); dialog } From b689784b4b4a6bf3c49166c868406d223d10fbf6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 19:03:40 +0100 Subject: [PATCH 30/33] PR #14321: Include Artboard Name shows without Export Options A form section's body runs to the next section and hides with it. Below the Export Options section the Include Artboard Name checkbox showed only while Export Options was ticked; both checkboxes now come before either section. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/artboard_cmds.rs | 6 +++--- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 13 +++++++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index a6d3a77b5c..ccc6af102e 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -1300,11 +1300,11 @@ mod file_types_tests; #[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; +#[cfg(test)] +#[path = "artboard_cmds/include_name_tests.rs"] +mod include_name_tests; #[cfg(test)] #[path = "artboard_cmds/from_layers_history_name_tests.rs"] diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index d90d7c0121..e6fd03da0f 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -322,10 +322,15 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec { From e33b62659d92f042f71f4f6079e1197fec2c3e4e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 19:18:53 +0100 Subject: [PATCH 31/33] PR #14413: the Include Background tests export Artboard Content Only Red and Blue Board overlap in the test document. Include Overlapping Areas, the default since #14381, puts Blue Board's pixels on the Red Board page, so the tests, written before it, now ask for Artboard Content Only unless they set the content themselves. Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/artboard_cmds/pdf_include_background_tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs index 6d359b58a9..cf9d883e73 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_include_background_tests.rs @@ -38,6 +38,11 @@ fn export(s: &mut Session, tag: &str, params: Value) -> Vec { let path = std::env::temp_dir().join(format!("photocraft-abpdf-bg-{}-{tag}.pdf", std::process::id())); let mut p = params; p["path"] = json!(path.to_string_lossy()); + // Artboard Content Only unless a test says otherwise: Red and Blue Board overlap, and Include Overlapping Areas + // (#13646, the default) would put Blue Board's pixels on the Red Board page. + if p.get("content").is_none() { + p["content"] = json!("artboard"); + } s.execute("file.export.artboardsToPdf", p).unwrap(); let bytes = std::fs::read(&path).unwrap(); let _ = std::fs::remove_file(&path); From f61383181c9723619c1205798042e67abba43102 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 19:27:05 +0100 Subject: [PATCH 32/33] PR #14454: the Document Per Artboard dialog tests export every board Export Selected Artboards from main opens ticked while a board is selected, so the dialog wrote one file where the test expects one per board. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs b/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs index a98a659fbc..5e15b28188 100644 --- a/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/artboards_to_pdf_mode_tests.rs @@ -35,6 +35,8 @@ fn open(h: &mut H, path: &str) -> DialogId { 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(); + // Every board, not only the selected one: Export Selected Artboards opens ticked while a board is selected (#13647). + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "artboards", serde_json::Value::Null).unwrap(); h.run_steps(4); dialog } From 21ecb68b4fade0029b0044c10f1aaae8f0d9556e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 19:32:58 +0100 Subject: [PATCH 33/33] Layers panel version: the document's Tracked revision, after #16197 #16197 (Document state is Tracked, #15709) removed DocState::layers_view_revision: an effects list or group opened or closed now moves the document's Tracked revision, which the Layers panel's version now holds instead. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/region_versions.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index aaad942418..4d2a087910 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -92,7 +92,7 @@ pub(crate) fn title_bar(app: &PhotocraftApp) -> u64 { /// The version of panel `id`'s body. The Navigator shows the active view and the adjustment preview its picture /// shows, the Layers panel the layer the Move tool's /// rollover outlines on the canvas, which effects lists and groups are open (view state off the document's revision, -/// `DocState::layers_view_revision`), the Smart Filter row picked on its own and what it is asked to do in its next +/// the active document's `Tracked` revision, #15709), the Smart Filter row picked on its own and what it is asked to do in its next /// pass (open a row for renaming, focus its Name filter, reveal a layer, follow the Move tool's pick), the Info panel the pointer's document pixel, the zoom and the Eyedropper's Sample /// Size it samples at and the Crop tool's frame size, the Clone Source panel the pairing at the last hover point, the /// Modifier Keys panel the latched keys, which their use releases, the Properties panel the colour its well's open @@ -109,7 +109,7 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { "layers" => { let filter_pick = app.session.active().and_then(|st| app.smart_filter_picks.get(&st.doc.id).copied()); let requests = (app.layers_rename, app.find_layers_focus, app.pending_reveal.as_ref().map(|(layer, _)| *layer), app.move_pick, filter_pick); - version(app, (app.canvas_hover_layer, app.session.active().map(|st| st.layers_view_revision()), requests)) + version(app, (app.canvas_hover_layer, app.session.active_tracked().map(|st| st.revision().count), requests)) } "info" => { let crop = crate::crop_ui::info_size(app).map(|size| size.map(f64::to_bits));