diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 288afce28f..ab5be3e67c 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -364,6 +364,10 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: }; } } + // A Frame's stroke over the frame's content, at the group's opacity. + if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) { + blend_into(backdrop, &surface_to_buffer(&stroke, rect), BlendMode::Normal, opacity); + } // Layers clipped to a pass-through group sit atop the group's // isolated rendering; their effect (isolated result with vs. without // them, each placed over the original backdrop) is added to the @@ -629,7 +633,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { } /// Blend an isolated layer buffer into the backdrop. -fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { +pub(crate) fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { blend_into_g(backdrop, src, mode, opacity, 1.0); } diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index 88ec2751a9..4f9999fe6e 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -1,4 +1,4 @@ -use super::composite::{adjustment_quantum, composite_stack}; +use super::composite::{adjustment_quantum, blend_into, composite_stack}; use super::ctx::Ctx; use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside}; use super::fx_cache::effect_maps; @@ -94,6 +94,10 @@ pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option Rect { } match &layer.content { LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(frame_stroke_bounds(layer, canvas), |acc, c| { let b = layer_bounds(c, canvas); if b.is_empty() { acc @@ -47,23 +47,36 @@ pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { } } +/// Where a Photoshop Frame's stroke ([`shape_split::frame_shape`]) draws, within `canvas`; empty +/// for other layers. Taken from the compiled stroke the renderer draws, not the path grown by the +/// stroke width: a mitered corner reaches up to `miter_limit` widths past the path, and a frame +/// has no pixels of its own that would cover it. +fn frame_stroke_bounds(layer: &Layer, canvas: Rect) -> Rect { + shape_split::frame_shape(layer) + .and_then(|sh| photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, canvas).bounds()) + .map_or(Rect::EMPTY, |r| r.intersect(&canvas)) +} + /// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's /// children count with their own effects (a child's outside stroke shapes the group's drop /// shadow and must not be cut off at the child's pixels, #3274). pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; - let b = effect_source_bounds(c, canvas); - let b = if b.is_empty() { b } else { b.inflate(m) }; - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), + // A Frame's stroke is part of the group's content its effects are built from. + LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => { + g.children.iter().filter(|c| c.visible).fold(frame_stroke_bounds(layer, canvas), |acc, c| { + let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; + let b = effect_source_bounds(c, canvas); + let b = if b.is_empty() { b } else { b.inflate(m) }; + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }) + } _ => layer_bounds(layer, canvas), } } @@ -343,7 +356,7 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { } let own = match &layer.content { LayerContent::Group(g) if g.artboard.is_none() => { - let mut acc = Rect::EMPTY; + let mut acc = frame_stroke_bounds(layer, canvas); for c in g.children.iter().filter(|c| c.visible) { let b = composite_bounds(c, canvas)?; if !b.is_empty() { diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index cd08eaff7c..1907a565f1 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -44,7 +44,7 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map:: format!("{:?}", c.blend).hash(h); layer_identity(c, h, pin); } - format!("{:?}", g.artboard).hash(h); + format!("{:?}{:?}", g.artboard, g.frame_stroke).hash(h); } LayerContent::Fill(f) => { format!("{f:?}").hash(h); diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index b2fd28116e..c6e76fb0b2 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -8,6 +8,7 @@ use std::sync::{Mutex, OnceLock}; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::vector::ShapeLayer; +use photocraft_doc::{Layer, LayerContent}; use photocraft_geom::{Rect, TileCoord}; use photocraft_raster::Surface; @@ -97,6 +98,22 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac Some(parts) } +/// The stroke-only shape a Photoshop Frame's stroke draws: `Group::frame_stroke` along the +/// group's enabled vector mask (the frame outline). `None` for other layers and for a frame +/// without a visible stroke or a vector mask. +pub fn frame_shape(layer: &Layer) -> Option { + let LayerContent::Group(g) = &layer.content else { return None }; + let stroke = g.frame_stroke.as_ref().filter(|s| s.width.is_finite() && s.width > 0.0 && s.opacity > 0.0)?; + let vm = layer.vector_mask.as_ref().filter(|m| m.enabled && !m.path.is_empty())?; + Some(ShapeLayer { path: vm.path.clone(), fill: None, stroke: Some(stroke.clone()), ..ShapeLayer::default() }) +} + +/// A Photoshop Frame's stroke ([`frame_shape`]) rendered over `canvas` in RGBA at `depth`, from +/// the same cache as the shape strokes. It goes above the frame's (masked) content. +pub fn frame_stroke(layer: &Layer, canvas: Rect, depth: SampleType) -> Option { + split(&frame_shape(layer)?, canvas, depth).map(|(_, stroke)| stroke) +} + /// Fits the stroke part to the shape's own pixels: where they reach past the fill, the stroke /// covers what the fill doesn't (`(pixels - fill) / (1 - fill)`), in the pixels' colour where we /// drew no stroke, and elsewhere in the colour that, drawn over the fill, gives back the pixels' diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 76ba8dc72b..a9b257422b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1358,6 +1358,46 @@ fn group_effects_reach_past_children_effects() { assert!(close4(px(&d, 24, 43), [1.0; 4]), "nothing past the shadow: {:?}", px(&d, 24, 43)); } +/// An empty Photoshop Frame with an outside stroke along `points` (#4381). +fn stroked_frame(points: &[(f64, f64)], width: f32) -> Layer { + use photocraft_doc::vector::{Path, ShapeStroke, StrokeAlign, Subpath, VectorMask}; + let mut l = Layer::group("Frame 1", vec![]); + l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(points)]))); + if let LayerContent::Group(g) = &mut l.content { + g.frame_stroke = Some(ShapeStroke { width, align: StrokeAlign::Outside, paint: Fill::Solid(Color::rgb(0.0, 0.0, 1.0)), ..Default::default() }); + } + l +} + +#[test] +fn frame_stroke_bounds_hold_its_mitered_corners() { + // A flat triangle's sharp corners miter far past the path (Photoshop's miter limit is 100): + // more than the stroke width, which is all the path's bounds grow by. + let canvas = Rect::new(0, 0, 64, 64); + let frame = stroked_frame(&[(20.0, 32.0), (44.0, 32.0), (32.0, 29.0)], 2.0); + let drawn = crate::bounds::content_bounds(&shape_split::frame_stroke(&frame, canvas, SampleType::U8).unwrap()); + assert!(drawn.x0 < 20 - 2 && drawn.x1 > 44 + 2, "the miters reach past the width: {drawn:?}"); + for b in [layer_bounds(&frame, canvas), composite_bounds(&frame, canvas).unwrap(), effect_source_bounds(&frame, canvas)] { + assert_eq!(b.union(&drawn), b, "{b:?} holds the stroke {drawn:?}"); + } +} + +#[test] +fn an_empty_frames_effects_follow_its_stroke() { + // No children: the frame's drop shadow is shaped by its stroke alone. + let mut d = doc_white(48, 48); + let mut frame = stroked_frame(&[(14.0, 14.0), (34.0, 14.0), (34.0, 34.0), (14.0, 34.0)], 4.0); + frame.effects.items = vec![Effect::DropShadow(shadow(3.0, 90.0))]; + d.layers.push(frame); + let canvas = d.bounds(); + let drawn = crate::bounds::content_bounds(&shape_split::frame_stroke(&d.layers[1], canvas, SampleType::U8).unwrap()); + let b = effect_source_bounds(&d.layers[1], canvas); + assert!(!drawn.is_empty() && b.union(&drawn) == b, "{b:?} holds the stroke {drawn:?}"); + assert!(close4(px(&d, 24, 36), [0.0, 0.0, 1.0, 1.0]), "stroke below the frame: {:?}", px(&d, 24, 36)); + assert!(close4(px(&d, 24, 39), [0.0, 0.0, 0.0, 1.0]), "shadow below the stroke: {:?}", px(&d, 24, 39)); + assert!(close4(px(&d, 24, 24), [1.0; 4]), "the frame's inside is empty: {:?}", px(&d, 24, 24)); +} + #[test] fn drop_shadow_uses_global_light_and_knockout() { let mut d = fx_doc(vec![Effect::DropShadow(Shadow { use_global_light: true, ..shadow(5.0, 0.0) })]); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6ec9bc67e3..33589e731e 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -318,6 +318,10 @@ pub struct Group { pub expanded: bool, /// Set when this (top-level) group is an artboard: children are clipped to its rect. pub artboard: Option, + /// A Photoshop Frame's stroke (Properties › Stroke; PSD `vstk` on the frame group): drawn + /// along the group's enabled vector mask (the frame outline), above the framed content and + /// not clipped by the frame. Ignored without a vector mask. + pub frame_stroke: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -703,7 +707,7 @@ impl Layer { Self::new(name, LayerContent::Raster(Surface::new(format))) } pub fn group(name: impl Into, children: Vec) -> Self { - let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true, artboard: None })); + let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); l.blend = BlendMode::PassThrough; l } @@ -1509,7 +1513,7 @@ mod tests { assert_eq!(LayerContent::Adjustment(Adjustment::Invert).article(), "an"); assert_eq!(LayerContent::Adjustment(Adjustment::Invert).kind_name(), "Adjustment"); assert_eq!(LayerContent::Raster(Surface::new(PixelFormat::RGBA8)).article(), "a"); - assert_eq!(LayerContent::Group(Group { children: Vec::new(), expanded: true, artboard: None }).article(), "a"); + assert_eq!(LayerContent::Group(Group { children: Vec::new(), expanded: true, artboard: None, frame_stroke: None }).article(), "a"); } } diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index b0cceb72a8..702d65891b 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -432,7 +432,7 @@ fn stack_modes_render_from_the_nested_layers() { surf.write_region(Rect::new(3, 3, 4, 4), &photocraft_raster::from_rgba(&fmt, [v, v, v, 1.0])); kids.push(l); } - let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None })); + let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None, frame_stroke: None })); let smart = crate::smart_cmds::layer_to_smart(doc, &g)?; let id = smart.id; doc.layers = vec![smart]; diff --git a/crates/engine/src/cmd/smart_cmds/unpack.rs b/crates/engine/src/cmd/smart_cmds/unpack.rs index 0fdf3ac3fa..af7510da8d 100644 --- a/crates/engine/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine/src/cmd/smart_cmds/unpack.rs @@ -161,7 +161,7 @@ fn unpacked(so: &Layer, mut layers: Vec) -> Layer { g.id = LayerId::fresh(); g.psd_id = None; g.blend = blend; - g.content = LayerContent::Group(Group { children: layers, expanded: true, artboard: None }); + g.content = LayerContent::Group(Group { children: layers, expanded: true, artboard: None, frame_stroke: None }); detach_psd(&mut g); g } diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index 38fa82c188..00c4d4d49e 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -661,7 +661,10 @@ fn image_assets_are_generated_now_and_on_save() { let s2 = session(8); let doc = s2.active().unwrap().doc.clone(); let mut d = (*doc).clone(); - d.layers.push(Layer::new("default 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }))); + d.layers.push(Layer::new( + "default 200% @2x", + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), + )); let lid = d.layers[1].id; d.layer_mut(lid).unwrap().name = "icon.png".into(); let (files, errors) = generate_assets(&d, &dir); @@ -684,7 +687,7 @@ fn image_assets_keep_full_artboards() { logo.surface_mut().unwrap().fill_rect(Rect::new(12, 10, 20, 16), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); let board = photocraft_doc::Artboard { rect: Rect::new(4, 6, 44, 36), background: photocraft_doc::ArtboardBackground::Transparent, preset: String::new() }; - let group = photocraft_doc::Group { children: vec![logo], expanded: true, artboard: Some(board) }; + let group = photocraft_doc::Group { children: vec![logo], expanded: true, artboard: Some(board), frame_stroke: None }; doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))]; Ok(()) }) @@ -722,8 +725,8 @@ fn image_assets_refuse_empty_artboards() { background: photocraft_doc::ArtboardBackground::Transparent, preset: String::new(), }; - let empty = photocraft_doc::Group { children: vec![], expanded: true, artboard: Some(board(0)) }; - let off = photocraft_doc::Group { children: vec![outside], expanded: true, artboard: Some(board(24)) }; + let empty = photocraft_doc::Group { children: vec![], expanded: true, artboard: Some(board(0)), frame_stroke: None }; + let off = photocraft_doc::Group { children: vec![outside], expanded: true, artboard: Some(board(24)), frame_stroke: None }; doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))]; Ok(()) }) @@ -770,8 +773,10 @@ fn image_assets_never_write_one_file_twice() { let dir = tmp("asset-variant-collisions"); d.layer_mut(top).unwrap().name = "icon.png".into(); d.layer_mut(logo).unwrap().name = "Logo".into(); - d.layers - .push(Layer::new("default 50% + 200% + 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }))); + d.layers.push(Layer::new( + "default 50% + 200% + 200% @2x", + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), + )); let (files, errors) = generate_assets(&d, &dir); let names: Vec<_> = files.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); assert_eq!(names, ["icon.png", "icon@2x.png"]); @@ -799,7 +804,7 @@ fn image_assets_reject_traversal_from_names_and_defaults() { d.layer_mut(id).unwrap().name = "safe.png".into(); d.layers.push(Layer::new( "default ../ + /outside/ + ..\\bad/ + C:\\drive/ + 50% nested/", - LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }), + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), )); let (files, errors) = generate_assets(&d, &dir); assert_eq!( diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 65f06fd8e2..8b26f17940 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -125,9 +125,12 @@ fn video_m(v: &photocraft_doc::VideoData, sink: &mut dyn Sink) -> crate::manifes fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { let content = match &l.content { LayerContent::Raster(s) => ContentM::Raster { surface: surface_m(s, sink) }, - LayerContent::Group(g) => { - ContentM::Group { children: g.children.iter().map(|c| layer_m(c, sink)).collect(), expanded: g.expanded, artboard: g.artboard.clone() } - } + LayerContent::Group(g) => ContentM::Group { + children: g.children.iter().map(|c| layer_m(c, sink)).collect(), + expanded: g.expanded, + artboard: g.artboard.clone(), + frame_stroke: g.frame_stroke.clone(), + }, LayerContent::Adjustment(a) => ContentM::Adjustment { adjustment: a.clone() }, LayerContent::Fill(f) => ContentM::Fill { fill: f.clone() }, LayerContent::Text(t) => ContentM::Text { @@ -449,7 +452,9 @@ impl Loader<'_> { fn layer_with(&mut self, m: &LayerM, children: Vec) -> Result { let content = match &m.content { ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?), - ContentM::Group { expanded, artboard, .. } => LayerContent::Group(Group { artboard: artboard.clone(), children, expanded: *expanded }), + ContentM::Group { expanded, artboard, frame_stroke, .. } => { + LayerContent::Group(Group { artboard: artboard.clone(), children, expanded: *expanded, frame_stroke: frame_stroke.clone() }) + } ContentM::Adjustment { adjustment } => LayerContent::Adjustment(adjustment.clone()), ContentM::Fill { fill } => LayerContent::Fill(fill.clone()), ContentM::Text { text, font_family, size_pt, color, transform, cache, psd_raw, runs, paragraphs, shape, orientation, antialias, warp } => { diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 72192c79f6..0b1e08b706 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -259,6 +259,9 @@ pub enum ContentM { /// Artboard (Layer › New › Artboard). #[serde(default)] artboard: Option, + /// A Photoshop Frame's stroke, drawn along the group's vector mask. + #[serde(default, skip_serializing_if = "Option::is_none")] + frame_stroke: Option, }, Adjustment { adjustment: Adjustment, diff --git a/crates/format/tests/it/frame_stroke.rs b/crates/format/tests/it/frame_stroke.rs new file mode 100644 index 0000000000..89567ee7f0 --- /dev/null +++ b/crates/format/tests/it/frame_stroke.rs @@ -0,0 +1,37 @@ +//! A Photoshop Frame's stroke (`Group::frame_stroke`) survives a `.pcraft` round trip; older +//! manifests, written before it existed, load without one (#4381). + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Fill, Layer, LayerContent, ShapeStroke, Size, StrokeAlign}; +use photocraft_format::*; + +fn stroke_of(d: &Document) -> Option { + match &d.layers.first()?.content { + LayerContent::Group(g) => g.frame_stroke.clone(), + _ => None, + } +} + +#[test] +fn frame_stroke_roundtrips_and_defaults_when_absent() { + let mut doc = Document::new("a", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + let stroke = + ShapeStroke { width: 8.0, align: StrokeAlign::Inside, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), dashes: vec![2.0, 1.0], ..ShapeStroke::default() }; + let mut g = Layer::group("Frame 1", vec![]); + if let LayerContent::Group(gr) = &mut g.content { + gr.frame_stroke = Some(stroke.clone()); + } + doc.layers.push(g); + let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(stroke_of(&load_from_bytes(&bytes).unwrap()), Some(stroke)); + + // A manifest without the key (older files) loads with no stroke. + let m = read_manifest(&bytes).unwrap(); + let mut v = serde_json::to_value(&m.document).unwrap(); + let content = &mut v["layers"][0]["content"]; + assert!(content.get("frame_stroke").is_some()); + content.as_object_mut().unwrap().remove("frame_stroke"); + let old: photocraft_format::manifest::DocM = serde_json::from_value(v).unwrap(); + let photocraft_format::manifest::ContentM::Group { frame_stroke, .. } = &old.layers[0].content else { panic!("not a group") }; + assert!(frame_stroke.is_none()); +} diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs index 6c822f4282..71eae66ddd 100644 --- a/crates/format/tests/it/main.rs +++ b/crates/format/tests/it/main.rs @@ -6,6 +6,7 @@ mod common; mod corruption; mod directory_symlinks; mod float_roundtrip; +mod frame_stroke; mod layer_labels; mod roundtrip; mod smart_contents; diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 577237e975..27d7bf589a 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -374,6 +374,15 @@ impl<'a> Planner<'a> { p.mask = self.mask_use(layer); after = self.emit(p); } + // A Frame's stroke over the frame's content, at the group's opacity (compose). + if let Some(stroke) = photocraft_compose::shape_split::frame_stroke(layer, self.cx.canvas, self.cx.depth) { + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(after); + p.b = Some(stroke); + p.opacity = opacity; + after = self.emit(p); + } if visible_clipped.is_empty() { self.release(before); return Ok(after); @@ -554,12 +563,20 @@ impl<'a> Planner<'a> { match &layer.content { LayerContent::Group(g) => { let empty = self.clear(); - let s = self.stack(&g.children, empty)?; + let mut s = self.stack(&g.children, empty)?; if layer.mask.is_some() || layer.vector_mask.is_some() { let mut p = Pass::new(Kernel::Mask, 0); p.a = Some(s); p.mask = self.mask_use(layer); - return Ok(self.emit(p)); + s = self.emit(p); + } + // A Frame's stroke over its masked content (compose::render_content). + if let Some(stroke) = photocraft_compose::shape_split::frame_stroke(layer, self.cx.canvas, self.cx.depth) { + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(s); + p.b = Some(stroke); + s = self.emit(p); } Ok(s) } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 8f36da1f67..ef78d032d4 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -2482,6 +2482,36 @@ fn stroked_shapes_with_clipped_layers() { } } +/// A Photoshop Frame's stroke (#4381): along the group's vector mask, above its masked content, +/// for an empty frame and one holding a layer, pass-through and isolated. +#[test] +fn frame_strokes() { + let Some(mut g) = gpu() else { return }; + use photocraft_doc::vector::{Path, ShapeStroke, StrokeAlign, Subpath, VectorMask}; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (blend, align, content) in [ + (BlendMode::PassThrough, StrokeAlign::Inside, false), + (BlendMode::PassThrough, StrokeAlign::Outside, true), + (BlendMode::Multiply, StrokeAlign::Center, true), + ] { + let mut d = Document::new("t", Size::new(80, 64), ColorMode::Rgb, depth); + d.layers.push(noise_layer("bg", d.pixel_format(), Rect::from_xywh(0, 0, 80, 64), 1, 0.3)); + let kids = if content { vec![noise_layer("c", d.pixel_format(), Rect::from_xywh(0, 0, 80, 64), 7, 0.4)] } else { vec![] }; + let mut l = Layer::group("Frame 1", kids); + l.blend = blend; + l.opacity = 0.8; + l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(10.3, 8.6), (66.2, 12.1), (58.7, 54.4), (16.9, 48.2)])]))); + if let LayerContent::Group(gr) = &mut l.content { + gr.frame_stroke = Some(ShapeStroke { width: 5.0, align, paint: Fill::Solid(Color::rgb(0.9, 0.1, 0.1)), ..Default::default() }); + } + d.layers.push(l); + let st = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds()); + assert!(st.is_ok(), "planned on the GPU"); + check(&mut g, &d, &format!("{depth:?} frame stroke {blend:?} {align:?} content {content}")); + } + } +} + #[test] fn artboards() { let Some(mut g) = gpu() else { return }; diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index f794e1be40..4e5ed90f86 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -149,7 +149,7 @@ impl Builder { let r = self.bbox(to_doc, page); let mut g = Layer::new( format!("Page {}", i + 1), - LayerContent::Group(Group { children: std::mem::take(&mut children), expanded: true, artboard: None }), + LayerContent::Group(Group { children: std::mem::take(&mut children), expanded: true, artboard: None, frame_stroke: None }), ); if let LayerContent::Group(gr) = &mut g.content { gr.artboard = Some(Artboard { rect: r, background: ArtboardBackground::White, preset: String::new() }); @@ -244,7 +244,7 @@ impl Builder { fn group(&mut self, n: &af::Node, children: Vec) -> Layer { // Pass-through and Normal (isolated) groups map one to one. - self.base(n, LayerContent::Group(Group { children, expanded: false, artboard: None })) + self.base(n, LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None })) } /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas. diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 8c9d5e310d..20207e44eb 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -542,7 +542,23 @@ impl Ex { let masked = l.vector_mask.is_some(); raw.retain(|(k, _)| !(RASTER_STALE_KEYS.contains(&k) || adjust_map::ADJUSTMENT_KEYS.contains(&k) || k == b"CgEd" || (k == b"vstk" && masked))); } - LayerContent::Group(_) => {} + // A Frame's stroke (`vstk`), kept byte-identical while it still decodes to the model. + LayerContent::Group(g) => { + let pos = raw.iter().position(|(k, _)| k == b"vstk"); + let old = pos.and_then(|i| raw.get(i)).and_then(|(_, d)| crate::vector_map::parse_vstk(d, self.dpi)); + // One we can't decode stays as it was unless the model has a stroke to write. + let stale = match &old { + Some(v) => v.stroke != g.frame_stroke, + None => g.frame_stroke.is_some(), + }; + if stale { + let data = crate::vector_map::vstk_bytes(g.frame_stroke.as_ref(), old.is_none_or(|v| v.fill_enabled), self.dpi); + match pos.and_then(|i| raw.get_mut(i)) { + Some(e) => e.1 = data, + None => raw.push((*b"vstk", data)), + } + } + } } // Effects reference point: written from the field (in place, keeping block order). match l.effects.reference { diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 2a0f982514..f26574153f 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -633,7 +633,9 @@ impl Ctx<'_> { let sd = rec.section_divider(); let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder); let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data)); - let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard })); + // A Photoshop Frame's stroke: `vstk` on the frame group, in a shape's layout. + let frame_stroke = rec.block(b"vstk").and_then(|b| crate::vector_map::parse_vstk(&b.data, self.dpi)).and_then(|v| v.stroke); + let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke })); l.psd_blocks = preserved_blocks(rec); self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode)); self.apply_vector_mask(&mut l, rec); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 98161732de..b2b3dcd1a7 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -672,7 +672,7 @@ impl Conv { } return; } - let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None })); + let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None })); l.opacity = g.opacity().get(); l.blend = blend(g.blend_mode()); l.vector_mask = clip; @@ -699,7 +699,7 @@ impl Conv { } else { t.id().to_string() }; - out.push(Layer::new(name, LayerContent::Group(Group { children, expanded: false, artboard: None }))); + out.push(Layer::new(name, LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None }))); } } } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 94f4ba715d..27b7b9b4ef 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -50,6 +50,7 @@ mod psd_block_layout; mod psd_damaged_merged; mod psd_empty_channels; mod psd_font_identity; +mod psd_frame_stroke; mod psd_kerning; mod psd_layer_block_length; mod psd_maximize_compatibility; diff --git a/crates/io/tests/it/psd_frame_stroke.rs b/crates/io/tests/it/psd_frame_stroke.rs new file mode 100644 index 0000000000..3ae2284543 --- /dev/null +++ b/crates/io/tests/it/psd_frame_stroke.rs @@ -0,0 +1,117 @@ +//! A Photoshop Frame (Frame tool, K) is a layer group whose record carries the frame outline as a +//! vector mask (`vsms`) and its Properties › Stroke as a shape-style `vstk`. The stroke draws +//! along the outline even when nothing is placed in the frame (#4381). + +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Fill, Group, Layer, LayerContent, Path, ShapeStroke, Size, StrokeAlign, Subpath, VectorMask}; +use photocraft_io::vector_map::{parse_vstk, vstk_bytes}; +use photocraft_io::*; +use photocraft_psd::{PsdFile, SectionType, TaggedBlock}; + +fn red_inside(width: f32) -> ShapeStroke { + ShapeStroke { width, align: StrokeAlign::Inside, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..ShapeStroke::default() } +} + +/// An 80 × 60 white document with an empty rectangular frame over (20, 10)–(60, 50). +fn frame_doc(depth: SampleType, stroke: Option) -> Document { + let mut d = Document::with_background("f", Size::new(80, 60), ColorMode::Rgb, depth, Color::WHITE); + let mut g = Layer::group("Frame 1", vec![]); + if let LayerContent::Group(Group { frame_stroke, .. }) = &mut g.content { + *frame_stroke = stroke; + } + g.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(20.0, 10.0), (60.0, 10.0), (60.0, 50.0), (20.0, 50.0)])]))); + d.layers.push(g); + d +} + +fn frame_stroke(d: &Document) -> Option { + d.layers.iter().find_map(|l| match &l.content { + LayerContent::Group(g) => Some(g.frame_stroke.clone()), + _ => None, + })? +} + +fn px(d: &Document, x: i32, y: i32) -> [f32; 4] { + photocraft_compose::flatten_to_surface(d, PixelFormat::RGBA8.with_sample(SampleType::F32), None).rgba(x, y) +} + +/// The group's own record (its top, `lsct` 1 or 2) in a PSD file. +fn frame_record(f: &mut PsdFile) -> &mut photocraft_psd::LayerRecord { + f.layers_mut() + .iter_mut() + .find(|r| r.section_divider().is_some_and(|s| matches!(s.kind, SectionType::OpenFolder | SectionType::ClosedFolder))) + .expect("the frame's group record") +} + +#[test] +fn a_photoshop_frames_vstk_draws_its_stroke_along_the_outline() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // A file shaped like Photoshop's: the group record carries `vsms` and a `vstk`. + let mut f = document_to_psd(&frame_doc(depth, None)); + frame_record(&mut f).blocks.push(TaggedBlock::new(*b"vstk", vstk_bytes(Some(&red_inside(4.0)), true, 72.0))); + let (d, _) = psd_to_document(&f); + assert_eq!(frame_stroke(&d), Some(red_inside(4.0)), "{depth:?}"); + // Inside the outline, 4 px wide: red on the frame's edge band, white in the middle and + // outside it. + let close = |a: [f32; 4], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 0.02); + for (x, y) in [(21, 30), (58, 30), (40, 11), (40, 48)] { + assert!(close(px(&d, x, y), [1.0, 0.0, 0.0]), "{depth:?} ({x}, {y}): {:?}", px(&d, x, y)); + } + for (x, y) in [(40, 30), (18, 30), (62, 30), (40, 8)] { + assert!(close(px(&d, x, y), [1.0, 1.0, 1.0]), "{depth:?} ({x}, {y}): {:?}", px(&d, x, y)); + } + } +} + +#[test] +fn a_frame_stroke_round_trips_through_psd() { + let stroke = ShapeStroke { dashes: vec![2.0, 1.0], opacity: 0.5, align: StrokeAlign::Outside, ..red_inside(3.0) }; + let d = frame_doc(SampleType::U8, Some(stroke.clone())); + let bytes = export(&d, "f.psd", &ExportOptions::default()).unwrap().bytes; + let back = import("f.psd", &bytes).unwrap().document; + assert_eq!(frame_stroke(&back), Some(stroke.clone())); + // Outside the outline at half opacity: pink just outside the edge. + let p = px(&back, 18, 30); + assert!((p[1] - 0.5).abs() < 0.05 && p[0] > 0.98, "{p:?}"); + + // Saved again unchanged, the imported `vstk` stays byte for byte. + let mut f = PsdFile::from_bytes(&bytes).unwrap(); + let first = frame_record(&mut f).block(b"vstk").unwrap().data.clone(); + let again = export(&back, "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f2 = PsdFile::from_bytes(&again).unwrap(); + assert_eq!(frame_record(&mut f2).block(b"vstk").unwrap().data, first); + + // Removing the stroke writes it disabled; no stroke at all writes no `vstk`. + let mut cleared = back.clone(); + if let Some(LayerContent::Group(g)) = cleared.layers.iter_mut().map(|l| &mut l.content).find(|c| matches!(c, LayerContent::Group(_))) { + g.frame_stroke = None; + } + let out = export(&cleared, "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f3 = PsdFile::from_bytes(&out).unwrap(); + assert_eq!(parse_vstk(&frame_record(&mut f3).block(b"vstk").unwrap().data, 72.0).unwrap().stroke, None); + let plain = export(&frame_doc(SampleType::U8, None), "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f4 = PsdFile::from_bytes(&plain).unwrap(); + assert!(frame_record(&mut f4).block(b"vstk").is_none()); +} + +#[test] +fn a_frame_stroke_without_a_vector_mask_or_width_draws_nothing() { + let mut d = frame_doc(SampleType::U8, Some(red_inside(4.0))); + d.layers[1].vector_mask = None; + assert_eq!(px(&d, 21, 30), [1.0, 1.0, 1.0, 1.0]); + let d = frame_doc(SampleType::U8, Some(ShapeStroke { width: 0.0, ..red_inside(4.0) })); + assert_eq!(px(&d, 21, 30), [1.0, 1.0, 1.0, 1.0]); + // Hostile widths from a file render without panicking. + for width in [f32::NAN, f32::INFINITY, -5.0, 1e9] { + let _ = px(&frame_doc(SampleType::U8, Some(ShapeStroke { width, ..red_inside(4.0) })), 21, 30); + } +} + +#[test] +fn an_isolated_frame_draws_its_outside_stroke_past_the_outline() { + let mut d = frame_doc(SampleType::U8, Some(ShapeStroke { align: StrokeAlign::Outside, ..red_inside(3.0) })); + d.layers[1].blend = photocraft_color::BlendMode::Normal; + let p = px(&d, 18, 30); + assert!(p[0] > 0.98 && p[1] < 0.02, "{p:?}"); + assert!(px(&d, 22, 30)[1] > 0.98, "inside stays white"); +}