diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index af62d62696..4e7200882c 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -659,10 +659,126 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result Ok(Some(one)) } +/// Include Overlapping Areas: each visible artboard stacked above board `id` that overlaps it, as +/// the reference application writes it into the board's file: a plain group (no longer an +/// artboard) holding its layers over a new pixel layer "Background for " filled with the +/// board's background where the two boards overlap, in source coordinates and bottom to top. A +/// group whose layers reach past its own board (effects, pixels outside the board, adjustments) +/// gets a hard mask to its board, which the artboard clipped them to. +/// +/// The artboard painted its background beneath the group and then composited the group (its +/// blend mode, opacity, effects and masks) over it. A board with any of those keeps them on a +/// group of its own inside the plain group, above the background, so they still apply to its +/// layers only and its own mask keeps its feather and Layer Mask Hides Effects setting; the plain +/// group then carries nothing but the board clip. +fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec { + let above = doc.layers.iter().skip_while(|l| l.id != id).skip(1); + let mut out = Vec::new(); + for l in above.filter(|l| l.visible) { + let Some(ab) = l.artboard().cloned() else { continue }; + let overlap = ab.rect.intersect(&rect); + if overlap.is_empty() { + continue; + } + let mut board = l.clone(); + if let LayerContent::Group(g) = &mut board.content { + g.artboard = None; + cut_pixels(&mut g.children, overlap, 0); + } + let bg = ab.background.rgba(); + let mut group = if stacks_like_its_layers(&board) { + board + } else { + board.clipped = false; + let mut plain = Layer::group(l.name.clone(), vec![board]); + plain.label = l.label; + plain + }; + if let (Some(bg), Some(children)) = (bg, group.children_mut()) { + let fmt = doc.pixel_format(); + let mut surf = Surface::new(fmt); + surf.fill_rect(overlap, &photocraft_raster::from_rgba(&fmt, bg)); + children.insert(0, Layer::new(format!("Background for {}", l.name), LayerContent::Raster(surf))); + } + // With the background in place: its pixels widen what the group's layers can reach. + 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(PixelFormat::GRAY8, &[0.0]); + mask.surface.fill_rect(ab.rect, &[1.0]); + group.mask = Some(mask); + } + out.push(group); + } + out +} + +/// Whether artboard `board` (already a plain group) composites over its background exactly as +/// its layers stacked over that background in one pass-through group do: pass-through (a Normal +/// group renders its layers on their own first, so a Multiply or Screen layer in it never blends +/// with the background), and no effects, masks, opacity, Blend If or other blending options of +/// its own, nor a mask the board clip would replace. +fn stacks_like_its_layers(board: &Layer) -> bool { + board.blend == photocraft_color::BlendMode::PassThrough + && board.opacity >= 1.0 + && board.fill_opacity >= 1.0 + && board.mask.is_none() + && board.vector_mask.is_none() + && board.frame.is_none() + && board.excluded_channels == 0 + && board.blend_if == photocraft_doc::BlendIf::default() + && board.advanced == photocraft_doc::AdvancedBlending::default() + && !photocraft_compose::effects::has_effects(board) +} + +/// 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. +/// A layer with effects, or inside a group with effects, stays whole too: pixels outside `keep` +/// can cast a shadow or glow into it. +fn cut_pixels(layers: &mut [Layer], keep: Rect, depth: usize) { + const MAX_DEPTH: usize = 64; + for l in layers { + if photocraft_compose::effects::has_effects(l) { + continue; + } + match &mut l.content { + LayerContent::Group(g) if depth < MAX_DEPTH => cut_pixels(&mut g.children, keep, depth + 1), + LayerContent::Raster(surf) => { + let r = surf.content_bounds().intersect(&keep); + let mut cut = Surface::with_default(surf.format(), &surf.default_pixel()); + if !r.is_empty() { + let Ok(px) = surf.try_read_region(r) else { continue }; + if cut.try_write_region(r, &px).is_err() { + continue; + } + } + *surf = cut; + } + _ => {} + } + } +} + /// [`artboard_document`] for each chosen board, all built before any file is written so a -/// board that can't be exported fails the export without leaving a partial set behind. -fn chosen_documents(doc: &Document, p: &Value) -> Result> { - chosen_artboards(doc, p).into_iter().filter_map(|id| artboard_document(doc, id).transpose()).collect() +/// board that can't be exported fails the export without leaving a partial set behind. With +/// `overlapping`, each file also holds the boards above that overlap it ([`overlapping_boards`]). +fn chosen_documents(doc: &Document, p: &Value, overlapping: bool) -> Result> { + let mut out = Vec::new(); + for id in chosen_artboards(doc, p) { + let Some(mut one) = artboard_document(doc, id)? else { continue }; + if overlapping && let Some(r) = doc.layer(id).and_then(|l| l.artboard()).map(|a| a.rect) { + // `artboard_document` has checked that the board's origin negates. + let (dx, dy) = (r.x0.saturating_neg(), r.y0.saturating_neg()); + for mut group in overlapping_boards(doc, id, r) { + crate::commands::translate_layer(doc, &mut group, dx, dy); + crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(dx), f64::from(dy)); + one.layers.push(group); + } + } + out.push(one); + } + Ok(out) } /// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first. @@ -735,8 +851,16 @@ 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 doc = d.doc.clone(); - let boards = chosen_documents(&doc, p)?; + let boards = chosen_documents(&doc, p, overlapping)?; let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect(); let mut files = Vec::new(); for (one, name) in boards.iter().zip(artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str()))) { @@ -806,7 +930,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let mut pages = Vec::new(); // Pages go bottom artboard of the Layers panel first, as in the reference application (#13643); // `chosen_documents` lists them top first, the order Artboards to Files keeps. - for one in chosen_documents(&doc, p)?.into_iter().rev() { + for one in chosen_documents(&doc, p, false)?.into_iter().rev() { let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8); @@ -883,7 +1007,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} (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?} → {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"…)"##, export_artboards, artboards_to_files ), @@ -905,6 +1029,9 @@ mod file_names_tests; #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; #[cfg(test)] +#[path = "artboard_cmds/overlapping_areas_tests.rs"] +mod overlapping_areas_tests; +#[cfg(test)] #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs new file mode 100644 index 0000000000..86df170247 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/overlapping_areas_tests.rs @@ -0,0 +1,340 @@ +//! Artboards to Files › Include Overlapping Areas / Artboard Content Only (#13629): the boards +//! stacked above an exported board that overlap it show in its file (PNG pixels, PSD structure), +//! boards below never do, 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]; + +/// 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-overlap-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Out(dir) + } + fn dir(&self) -> String { + self.0.to_string_lossy().into_owned() + } +} + +impl Drop for Out { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Exports board `board` with `extra` params and reads the one file back. +fn export(s: &mut Session, out: &Out, board: u64, extra: Value) -> Document { + let mut p = json!({"dir": out.dir(), "prefix": "", "artboards": [board]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let format = p.get("format").and_then(Value::as_str).unwrap_or("png").to_string(); + let r = s.execute("file.export.artboardsToFiles", p).unwrap(); + let files = r["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{r}"); + let path = files[0].as_str().unwrap(); + photocraft_io::import(&format!("x.{format}"), &std::fs::read(path).unwrap()).unwrap().document +} + +/// The file's composite pixel at (x, y) as 8-bit RGBA. +fn px(d: &Document, x: i32, y: i32) -> [u8; 4] { + let flat = photocraft_compose::flatten(d); + let w = d.size.width as usize; + flat.px[y as usize * w + x as usize].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn rgb(p: [u8; 4]) -> [u8; 3] { + [p[0], p[1], p[2]] +} + +fn names(layers: &[Layer]) -> Vec<&str> { + layers.iter().map(|l| l.name.as_str()).collect() +} + +#[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"})] { + let f = export(&mut s, &out, red, extra.clone()); + assert_eq!((f.size.width, f.size.height), (200, 150), "{depth} bit {extra}"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{depth} bit {extra}: Blue's pixels"); + assert_eq!(rgb(px(&f, 125, 35)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 125, 50)), WHITE, "{depth} bit {extra}: Blue Board's background"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{depth} bit {extra}: Red stays red"); + } + } +} + +#[test] +fn artboard_content_only_keeps_the_board_on_its_own() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("content-only"); + let f = export(&mut s, &out, red, json!({"content": "artboard"})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE, "nothing of Blue Board"); + assert_eq!(rgb(px(&f, 110, 50)), RED); + let psd = export(&mut s, &out, red, json!({"content": "artboard", "format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn an_overlapping_psd_holds_the_board_above_as_a_plain_group_with_its_background() { + let (mut s, [red, _, _]) = session(8); + let out = Out::new("psd"); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!((psd.size.width, psd.size.height), (200, 150)); + // Bottom to top: the exported artboard, then the overlapping board as a plain group. + assert_eq!(names(&psd.layers), ["Red Board", "Blue Board"]); + let [board, group] = [&psd.layers[0], &psd.layers[1]]; + assert_eq!(board.artboard().map(|a| a.rect), Some(Rect::new(0, 0, 200, 150))); + assert_eq!(names(board.children().unwrap()), ["Red"]); + assert!(matches!(&group.content, LayerContent::Group(g) if g.artboard.is_none()), "no longer an artboard"); + let kids = group.children().unwrap(); + assert_eq!(names(kids), ["Background for Blue Board", "Blue"]); + // Blue (130,40-230,140 in the source) is cut to the file: 130,40-200,140. + let blue = photocraft_compose::bounds::content_bounds(kids[1].surface().unwrap()); + assert_eq!(blue, Rect::new(130, 40, 200, 140)); + // The background covers where the boards overlap: 120..200 x 30..150. + let bg = photocraft_compose::bounds::content_bounds(kids[0].surface().unwrap()); + assert_eq!(bg, Rect::new(120, 30, 200, 150)); + assert_eq!(rgb(px(&psd, 150, 60)), BLUE); + assert_eq!(rgb(px(&psd, 125, 35)), WHITE); + assert_eq!(rgb(px(&psd, 110, 50)), RED); +} + +#[test] +fn boards_below_do_not_show_in_either_mode() { + let (mut s, [_, blue, _]) = session(8); + // A transparent Blue Board shows whatever leaks in from Red Board's white background below. + s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap(); + let out = Out::new("below"); + for content in ["overlapping", "artboard"] { + let f = export(&mut s, &out, blue, json!({"content": content})); + assert_eq!((f.size.width, f.size.height), (200, 200), "{content}"); + // Source (125,35): Red Board's background, outside Blue's pixels. + assert_eq!(px(&f, 5, 5)[3], 0, "{content}: nothing of Red Board"); + assert_eq!(rgb(px(&f, 30, 30)), BLUE, "{content}"); + let psd = export(&mut s, &out, blue, json!({"content": content, "format": "psd"})); + assert_eq!(names(&psd.layers), ["Blue Board"], "{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, "format": "psd"})); + let d = s.active().unwrap(); + assert!(d.doc == before, "{content} changed the document"); + assert_eq!((d.revision, d.history.past_len()), (rev, past), "{content}"); + } + } +} + +/// The artboard clipped its layers to the board; as a plain group in the file they still stop +/// at the board's edge, so Blue pixels outside Blue Board never cover Red Board. +#[test] +fn the_layers_of_the_board_above_stay_inside_their_board() { + let (mut s, [red, blue, _]) = session(8); + paint(&mut s, blue, "Spill", Rect::new(100, 45, 125, 55), BLUE); + let out = Out::new("spill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 122, 50)), BLUE, "{format}: inside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{format}"); + } +} + +/// A layer that covers the whole canvas (a solid colour fill) in the board above is clipped to +/// that board by a mask on the group, so it can't paint over the rest of the exported board. +#[test] +fn a_fill_layer_in_the_board_above_stays_inside_its_board() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Fill", |doc, _| { + let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0)))); + doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().push(fill); + Ok(()) + }) + .unwrap(); + let out = Out::new("fill"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 10, 140)), WHITE, "{format}: outside Blue Board"); + assert_eq!(rgb(px(&f, 150, 60)), [0, 255, 0], "{format}: inside Blue Board"); + } +} + +/// A layer of the board above that lies outside the exported board still casts its drop shadow +/// into it, as it does in the document: its pixels are not cut away before the effect is built. +#[test] +fn a_shadow_cast_into_the_exported_board_from_outside_it_still_shows() { + use photocraft_doc::effects::{Contour, FxCommon, Shadow}; + let (mut s, [red, blue, _]) = session(8); + // Caster at 210..240 x 160..180 (in Blue Board, outside Red Board); its shadow, 40 px up and + // to the left, falls on 170..200 x 120..140, inside Red Board. + paint(&mut s, blue, "Caster", Rect::new(210, 160, 240, 180), [0, 160, 0]); + s.edit("Shadow", |doc, _| { + let caster = doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().last_mut().unwrap(); + caster.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 = px(&s.active().unwrap().doc, 185, 130); + assert_eq!(rgb(source), [0, 0, 0], "the shadow lands there in the document"); + let out = Out::new("shadow"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + assert_eq!(px(&f, 185, 130), source, "{format}"); + assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}"); + } +} + +/// Not measured (keeps today's behaviour): a hidden board above shows nothing. +#[test] +fn a_hidden_board_above_does_not_show() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Hide", |doc, _| { + doc.layer_mut(LayerId(blue)).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let out = Out::new("hidden"); + let f = export(&mut s, &out, red, json!({})); + assert_eq!(rgb(px(&f, 150, 60)), WHITE); + let psd = export(&mut s, &out, red, json!({"format": "psd"})); + assert_eq!(names(&psd.layers), ["Red Board"]); +} + +#[test] +fn a_bad_content_value_is_rejected_without_writing_anything() { + let (mut s, _) = session(8); + let out = Out::new("bad"); + for bad in [json!("both"), json!(""), json!(1), json!(true), json!(["overlapping"])] { + let d = s.active().unwrap(); + let (before, past) = (d.doc.clone(), d.history.past_len()); + let err = s.execute("file.export.artboardsToFiles", json!({"dir": out.dir(), "content": bad})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{bad}: {err}"); + let d = s.active().unwrap(); + assert!(d.doc == before && d.history.past_len() == past, "{bad}"); + assert_eq!(std::fs::read_dir(&out.0).unwrap().count(), 0, "{bad}: nothing written"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToFiles").unwrap(); + assert!(spec.params.contains(r#""content":"overlapping|artboard"="overlapping""#), "{}", spec.params); +} + +/// The source document's composite pixel at (x, y); Red Board sits at the canvas origin, so its +/// file pixels line up with these. +fn source_px(s: &Session, x: i32, y: i32) -> [u8; 4] { + px(&s.active().unwrap().doc, x, y) +} + +/// A mask on the board above keeps hiding what it hid when the export clips that board to its +/// rect: the board clip is added beside it instead of replacing it. +#[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(); + assert_eq!(rgb(source_px(&s, 150, 60)), WHITE, "the mask shows Blue Board's background there"); + let out = Out::new("board-mask"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (145, 55), (170, 60), (125, 140), (110, 50), (10, 140)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} + +/// A Normal board renders its layers on their own before they go over its background, so a +/// Multiply layer in it does not blend with that background; the export keeps the board as a +/// group of its own above the background layer instead of stacking its layers on it. +#[test] +fn a_multiply_layer_in_a_normal_board_above_does_not_blend_with_its_background() { + let (mut s, [red, blue, _]) = session(8); + s.edit("Normal", |doc, _| { + let board = doc.layer_mut(LayerId(blue)).unwrap(); + board.blend = photocraft_color::BlendMode::Normal; + if let LayerContent::Group(g) = &mut board.content { + g.artboard.as_mut().unwrap().background = photocraft_doc::ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)); + } + board.children_mut().unwrap().last_mut().unwrap().blend = photocraft_color::BlendMode::Multiply; + Ok(()) + }) + .unwrap(); + assert_eq!(rgb(source_px(&s, 150, 60)), BLUE, "Blue, rendered on its own, covers the green background"); + let out = Out::new("normal-multiply"); + for format in ["png", "psd"] { + let f = export(&mut s, &out, red, json!({"format": format})); + for (x, y) in [(150, 60), (125, 35), (110, 50)] { + assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})"); + } + } +} diff --git a/crates/ui-egui/src/artboards_overlap_dialog_tests.rs b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs new file mode 100644 index 0000000000..0d79a8e886 --- /dev/null +++ b/crates/ui-egui/src/artboards_overlap_dialog_tests.rs @@ -0,0 +1,87 @@ +//! #13629: the Artboards to Files dialog has the radio pair Include Overlapping Areas (selected +//! by default) / Artboard Content Only right below the prefix, and OK passes the choice to +//! `file.export.artboardsToFiles` as `content`. Layer Comps to Files has no such choice. +use crate::PhotocraftApp; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +const ARTBOARDS: &str = "file.export.artboardsToFiles"; +const OVERLAPPING: &str = "Include Overlapping Areas"; +const CONTENT_ONLY: &str = "Artboard Content Only"; + +type H = Harness<'static, Box>; + +fn harness() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).unwrap(); + app.run("layerComp.new", json!({"name": "Comp"})).unwrap(); + app.sync_views(); + let h = Harness::builder() + .with_size(egui::vec2(1440.0, 900.0)) + .with_max_steps(64) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h +} + +fn open(h: &mut H, command: &str) -> DialogId { + let ctx = h.ctx.clone(); + let reply = crate::menus::invoke(h.state_mut(), &ctx, command, json!({})).unwrap(); + let want = reply["dialog"].as_str().unwrap().to_owned(); + let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap(); + h.run_steps(4); + dialog +} + +fn field(h: &H, dialog: DialogId, key: &str) -> Option { + let form = h.state().framework.dialogs.get_by_id::(dialog)?; + serde_json::to_value(form.fields()).ok()?.get(key).cloned() +} + +fn selected(h: &H, label: &str) -> bool { + h.get_by_role_and_label(Role::RadioButton, label).accesskit_node().toggled() == Some(Toggled::True) +} + +/// The top edge of the first node labelled `label`. +fn top(h: &H, label: &str) -> f32 { + h.query_all_by_label(label).next().unwrap_or_else(|| panic!("{label} is shown")).rect().top() +} + +#[test] +fn the_dialog_offers_the_two_radios_below_the_prefix_overlapping_first_and_selected() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + 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 radio = top(&h, OVERLAPPING); + assert!(top(&h, "File Name Prefix") < radio && radio < top(&h, "File Type"), "the radios sit between the prefix and the file type"); + assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping"))); +} + +#[test] +fn clicking_artboard_content_only_passes_it_to_the_command() { + let mut h = harness(); + let dialog = open(&mut h, ARTBOARDS); + h.get_by_role_and_label(Role::RadioButton, CONTENT_ONLY).click(); + h.run_steps(4); + assert!(selected(&h, CONTENT_ONLY) && !selected(&h, OVERLAPPING)); + assert_eq!(field(&h, dialog, "content"), Some(json!("artboard"))); + h.get_by_role_and_label(Role::RadioButton, OVERLAPPING).click(); + h.run_steps(4); + assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping"))); +} + +#[test] +fn layer_comps_to_files_has_no_overlap_choice() { + let mut h = harness(); + let dialog = open(&mut h, "file.export.layerCompsToFiles"); + assert_eq!(h.query_all_by_role(Role::RadioButton).count(), 0); + assert_eq!(field(&h, dialog, "content"), None); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e8cacf543c..47254c23cd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -993,6 +993,8 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; +#[cfg(test)] +mod artboards_overlap_dialog_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 9d3befb5a9..47080b68ad 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -262,6 +262,15 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec