From c4de6fb24eebcc25ff9e9946dc039ac6d87f2071 Mon Sep 17 00:00:00 2001 From: Skyfuller1303 Date: Tue, 13 Oct 2026 19:53:02 +0200 Subject: [PATCH] feat(engine): independent shape fill/stroke paint parameters shape.create and shape.edit accept the full paint model for fill and stroke: solid colours with alpha or a model colour, gradients with opacity stops, midpoints, offset, dither and align, and patterns with id, angle, link and phase. Malformed paint values are rejected before the document changes. shape.info reports the same complete paint JSON. Pattern paints resolve a document or library pattern and embed its tile in the same undo step, and shape caches render with the document's patterns. Copy/Paste Fill and Stroke keep a snapshot of the referenced pattern so pasting still works after the source document is closed, and refuse to overwrite a different pattern with the same id. Refs #2496 --- crates/engine/src/lib.rs | 3 + crates/engine/src/vector_cmds.rs | 329 +++++++++++++++--- crates/engine/tests/shape_paint_fidelity.rs | 175 ++++++++++ .../engine/tests/shape_pattern_clipboard.rs | 222 ++++++++++++ crates/engine/tests/shape_patterns.rs | 74 ++++ docs/control-protocol.md | 6 + 6 files changed, 762 insertions(+), 47 deletions(-) create mode 100644 crates/engine/tests/shape_paint_fidelity.rs create mode 100644 crates/engine/tests/shape_pattern_clipboard.rs create mode 100644 crates/engine/tests/shape_patterns.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ff3cde6e4c..80b190cff2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -405,6 +405,9 @@ pub struct Session { /// Shape path context menu: copied vector fill and stroke styles. pub path_fill_clipboard: Option, pub path_stroke_clipboard: Option, + /// Pattern tiles referenced by copied paints; surfaces retain their COW snapshots. + pub(crate) path_fill_pattern: Option, + pub(crate) path_stroke_pattern: Option, /// Colour management: proofing state, monitor profile, display transforms. pub color: color_cmds::ColorState, /// Open Edit Contents documents and the smart objects they update. diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index 14579e5954..cd35f105ff 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -78,21 +78,31 @@ fn can_paste_shape_stroke(s: &Session) -> std::result::Result<(), String> { } fn copy_shape_fill(s: &mut Session, _p: &Value) -> Result { - let fill = active_shape(s).map_err(EngineError::Other)?.fill.clone().ok_or_else(|| EngineError::Other("shape has no fill".into()))?; + let mut fill = active_shape(s).map_err(EngineError::Other)?.fill.clone().ok_or_else(|| EngineError::Other("shape has no fill".into()))?; + let pattern = clipboard_pattern(s, &fill, None)?; + set_clipboard_pattern_id(&mut fill, pattern.as_ref()); s.path_fill_clipboard = Some(fill); + s.path_fill_pattern = pattern; Ok(Value::Null) } fn copy_shape_stroke(s: &mut Session, _p: &Value) -> Result { - let stroke = active_shape(s).map_err(EngineError::Other)?.stroke.clone().ok_or_else(|| EngineError::Other("shape has no stroke".into()))?; + let mut stroke = active_shape(s).map_err(EngineError::Other)?.stroke.clone().ok_or_else(|| EngineError::Other("shape has no stroke".into()))?; + let pattern = clipboard_pattern(s, &stroke.paint, None)?; + set_clipboard_pattern_id(&mut stroke.paint, pattern.as_ref()); s.path_stroke_clipboard = Some(stroke); + s.path_stroke_pattern = pattern; Ok(Value::Null) } fn paste_shape_fill(s: &mut Session, p: &Value) -> Result { - let fill = s.path_fill_clipboard.clone().ok_or_else(|| EngineError::Other("no shape fill copied".into()))?; + let mut fill = s.path_fill_clipboard.clone().ok_or_else(|| EngineError::Other("no shape fill copied".into()))?; + let pattern = clipboard_pattern(s, &fill, s.path_fill_pattern.as_ref())?; + set_clipboard_pattern_id(&mut fill, pattern.as_ref()); + let patterns: Vec<_> = pattern.into_iter().collect(); + check_clipboard_pattern_collision(s, &patterns)?; let id = layer_id(s, p)?; - with_shape(s, id, "Paste Fill", |shape, _| { + with_shape_patterns(s, id, "Paste Fill", &patterns, |shape, _| { shape.fill = Some(fill); Ok(()) })?; @@ -100,15 +110,51 @@ fn paste_shape_fill(s: &mut Session, p: &Value) -> Result { } fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result { - let stroke = s.path_stroke_clipboard.clone().ok_or_else(|| EngineError::Other("no shape stroke copied".into()))?; + let mut stroke = s.path_stroke_clipboard.clone().ok_or_else(|| EngineError::Other("no shape stroke copied".into()))?; + let pattern = clipboard_pattern(s, &stroke.paint, s.path_stroke_pattern.as_ref())?; + set_clipboard_pattern_id(&mut stroke.paint, pattern.as_ref()); + let patterns: Vec<_> = pattern.into_iter().collect(); + check_clipboard_pattern_collision(s, &patterns)?; let id = layer_id(s, p)?; - with_shape(s, id, "Paste Complete Stroke", |shape, _| { + with_shape_patterns(s, id, "Paste Complete Stroke", &patterns, |shape, _| { shape.stroke = Some(stroke); Ok(()) })?; shape_info(s, id) } +fn set_clipboard_pattern_id(fill: &mut Fill, pattern: Option<&photocraft_doc::Pattern>) { + if let (Fill::Pattern { id, .. }, Some(pattern)) = (fill, pattern) { + *id = pattern.id.clone(); + } +} + +fn clipboard_pattern(s: &Session, fill: &Fill, snapshot: Option<&photocraft_doc::Pattern>) -> Result> { + let Fill::Pattern { id, name, .. } = fill else { return Ok(None) }; + let find = |patterns| photocraft_doc::pattern::find(patterns, id, name).cloned(); + let pattern = snapshot + .and_then(|p| find(std::slice::from_ref(p))) + .or_else(|| s.active().and_then(|st| find(&st.doc.patterns))) + .or_else(|| find(&s.patterns.items)) + .ok_or_else(|| EngineError::Other(format!("no copied pattern \"{name}\" (see pattern.list)")))?; + if pattern.is_empty() { + return Err(EngineError::Other("the copied pattern is empty".into())); + } + Ok(Some(pattern)) +} + +fn check_clipboard_pattern_collision(s: &Session, patterns: &[photocraft_doc::Pattern]) -> Result<()> { + let st = s.active().ok_or(EngineError::NoDocument)?; + for pattern in patterns { + if let Some(existing) = st.doc.patterns.iter().find(|p| p.id == pattern.id) + && (existing.width != pattern.width || existing.height != pattern.height || existing.surface != pattern.surface) + { + return Err(EngineError::Other("A different pattern with the copied pattern's id already exists in this document".into())); + } + } + Ok(()) +} + pub(crate) fn layer_id(s: &Session, p: &Value) -> Result { match p.get("layer").and_then(Value::as_u64) { Some(id) => Ok(LayerId(id)), @@ -246,65 +292,213 @@ pub fn path_json(p: &Path) -> Value { fn fill_json(f: &Fill) -> Value { match f { - Fill::Solid(c) => json!(hex(c)), - Fill::Gradient { stops, angle, scale, style, reverse, .. } => json!({ "gradient": { - "stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::>(), - "angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse } }), - Fill::Pattern { name, scale, .. } => json!({ "pattern": name, "scale": scale * 100.0 }), + Fill::Solid(c) => paint_color_json(c), + Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => json!({ "gradient": { + "stops": stops.iter().map(|(t, c)| json!([t, paint_color_json(c)])).collect::>(), + "angle": angle, "scale": f64::from(*scale) * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse, + "opacityStops": opacity_stops, "midpoints": midpoints, "offset": offset, "dither": dither, "align": align } }), + Fill::Pattern { name, scale, id, angle, link, phase } => json!({ "pattern": name, "scale": f64::from(*scale) * 100.0, + "id":id, "angle":angle, "link":link, "phase":phase }), } } -/// `"#rrggbb"` / `[r,g,b,a]` / `{"gradient":{"stops":[[t,"#hex"],…],"angle","scale","style","reverse"}}` / -/// `{"pattern":name,"scale"}`. `null` → `Ok(None)` (no fill). +fn paint_color_json(c: &Color) -> Value { + if c.mode != photocraft_color::ColorMode::Rgb || c.c[3] != 0.0 { + return json!({"color":c}); + } + if c.alpha == 1.0 && c.c.iter().take(3).all(|v| (0.0..=1.0).contains(v) && (v * 255.0).round() / 255.0 == *v) { + json!(hex(c)) + } else { + json!([c.c[0], c.c[1], c.c[2], c.alpha]) + } +} + +fn fill_number(v: &Value, label: &str, lo: f64, hi: f64) -> std::result::Result { + v.as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .map(|n| n as f32) + .ok_or_else(|| format!("{label} must be a finite number between {lo} and {hi}")) +} + +fn fill_bool(v: &Value, key: &str, default: bool) -> std::result::Result { + v.get(key).map_or(Ok(default), |v| v.as_bool().ok_or_else(|| format!("{key} must be a boolean"))) +} + +fn fill_pair(v: &Value, key: &str) -> std::result::Result<(f32, f32), String> { + let Some(value) = v.get(key) else { return Ok((0.0, 0.0)) }; + let Some(values) = value.as_array().filter(|a| a.len() == 2) else { return Err(format!("{key} must contain two numbers")) }; + let mut values = values.iter(); + let a = values.next().ok_or_else(|| format!("{key} needs an x value"))?; + let b = values.next().ok_or_else(|| format!("{key} needs a y value"))?; + Ok((fill_number(a, key, -1_000_000.0, 1_000_000.0)?, fill_number(b, key, -1_000_000.0, 1_000_000.0)?)) +} + +fn fill_scale(v: &Value) -> std::result::Result { + let Some(value) = v.get("scale") else { return Ok(1.0) }; + let n = value.as_f64().filter(|n| n.is_finite() && *n > 0.0 && *n <= 1_000_000.0).ok_or("scale must be greater than 0 and at most 1000000 percent")?; + let scale = (n / 100.0) as f32; + if scale <= 0.0 { + return Err("scale is too small".into()); + } + Ok(scale) +} + +fn paint_color(v: &Value) -> std::result::Result { + let c = if let Some(raw) = v.get("color") { + serde_json::from_value::(raw.clone()).map_err(|e| format!("invalid model colour: {e}"))? + } else { + if let Some(values) = v.as_array() { + if !matches!(values.len(), 3 | 4) { + return Err("colour must contain three or four numbers".into()); + } + for value in values.iter().take(3) { + fill_number(value, "colour component", -1_000_000.0, 1_000_000.0)?; + } + if let Some(alpha) = values.get(3) { + fill_number(alpha, "colour alpha", 0.0, 1.0)?; + } + } + color(v).ok_or("colour must be hex, RGB(A) numbers or a model colour object")? + }; + if !c.c.iter().all(|n| n.is_finite() && n.abs() <= 1_000_000.0) || !c.alpha.is_finite() || !(0.0..=1.0).contains(&c.alpha) { + return Err("colour components must be finite and within ±1000000; alpha must be 0..1".into()); + } + Ok(c) +} + +/// Legacy colour/gradient/pattern forms plus complete geometry and opacity metadata. +/// Gradient locations, opacity stops and midpoints are fractions; scale is percent. fn parse_fill(v: &Value) -> std::result::Result, String> { if v.is_null() { return Ok(None); } - if let Some(c) = color(v) { - return Ok(Some(Fill::Solid(c))); + if v.is_array() || v.is_string() || v.get("color").is_some() { + return Ok(Some(Fill::Solid(paint_color(v)?))); } if let Some(g) = v.get("gradient") { - let stops: Vec<(f32, Color)> = g - .get("stops") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|s| Some((s.get(0)?.as_f64()? as f32, color(s.get(1)?)?))).collect()) - .unwrap_or_else(|| vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); - let style = match g.get("style").and_then(Value::as_str).unwrap_or("linear") { + if !g.is_object() { + return Err("gradient must be an object".into()); + } + let stops = match g.get("stops") { + None => vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], + Some(Value::Array(stops)) if stops.len() <= 4096 => stops + .iter() + .map(|stop| { + let values = stop.as_array().filter(|a| a.len() == 2).ok_or("gradient stop must contain a location and colour")?; + let t = values.first().ok_or("missing stop location")?; + let c = values.get(1).ok_or("missing stop colour")?; + Ok((fill_number(t, "stop location", 0.0, 1.0)?, paint_color(c)?)) + }) + .collect::, String>>()?, + _ => return Err("gradient stops must contain at most 4096 location/colour pairs".into()), + }; + let style = match g.get("style").map_or(Some("linear"), Value::as_str).ok_or("gradient style must be a string")? { + "linear" => GradientStyle::Linear, "radial" => GradientStyle::Radial, "angle" => GradientStyle::Angle, "reflected" => GradientStyle::Reflected, "diamond" => GradientStyle::Diamond, - _ => GradientStyle::Linear, + _ => return Err("unknown gradient style".into()), }; - return Ok(Some(Fill::gradient( + let opacity_stops = match g.get("opacityStops") { + None => Vec::new(), + Some(Value::Array(stops)) if stops.len() <= 4096 => stops + .iter() + .map(|stop| { + let values = stop.as_array().filter(|a| a.len() == 2).ok_or("opacity stop must contain a location and opacity")?; + Ok(( + fill_number(values.first().ok_or("missing opacity location")?, "opacity location", 0.0, 1.0)?, + fill_number(values.get(1).ok_or("missing opacity value")?, "opacity value", 0.0, 1.0)?, + )) + }) + .collect::, String>>()?, + _ => return Err("opacityStops must contain at most 4096 location/opacity pairs".into()), + }; + let midpoints = match g.get("midpoints") { + None => Vec::new(), + Some(Value::Array(values)) if values.len() <= 4096 => { + values.iter().map(|v| fill_number(v, "midpoint", 0.0, 1.0)).collect::, _>>()? + } + _ => return Err("midpoints must contain at most 4096 fractions".into()), + }; + return Ok(Some(Fill::Gradient { stops, - f64p(g, "angle").unwrap_or(90.0) as f32, - f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0, + angle: g.get("angle").map_or(Ok(90.0), |v| fill_number(v, "angle", -1_000_000.0, 1_000_000.0))?, + scale: fill_scale(g)?, style, - g.get("reverse").and_then(Value::as_bool).unwrap_or(false), - ))); - } - if let Some(name) = v.get("pattern").and_then(Value::as_str) { - return Ok(Some(Fill::Pattern { - name: name.into(), - scale: f64p(v, "scale").unwrap_or(100.0) as f32 / 100.0, - id: String::new(), - angle: 0.0, - link: true, - phase: (0.0, 0.0), + reverse: fill_bool(g, "reverse", false)?, + opacity_stops, + midpoints, + offset: fill_pair(g, "offset")?, + dither: fill_bool(g, "dither", false)?, + align: fill_bool(g, "align", true)?, })); } - Err(format!("unrecognised fill {v}")) + if let Some(pattern) = v.get("pattern") { + let name = pattern.as_str().filter(|s| s.len() <= 65536).ok_or("pattern must be a string of at most 65536 bytes")?; + let id = v.get("id").map_or(Some(""), Value::as_str).filter(|s| s.len() <= 65536).ok_or("pattern id must be a string of at most 65536 bytes")?; + return Ok(Some(Fill::Pattern { + name: name.into(), + scale: fill_scale(v)?, + id: id.into(), + angle: v.get("angle").map_or(Ok(0.0), |v| fill_number(v, "angle", -1_000_000.0, 1_000_000.0))?, + link: fill_bool(v, "link", true)?, + phase: fill_pair(v, "phase")?, + })); + } + Err("unrecognised fill".into()) } fn stroke_json(s: &ShapeStroke) -> Value { json!({ - "width": s.width, "fill": fill_json(&s.paint), "opacity": s.opacity * 100.0, + "width": s.width, "fill": fill_json(&s.paint), "opacity": f64::from(s.opacity) * 100.0, "align": format!("{:?}", s.align).to_ascii_lowercase(), "cap": format!("{:?}", s.cap).to_ascii_lowercase(), "join": format!("{:?}", s.join).to_ascii_lowercase(), "miterLimit": s.miter_limit, "dashes": s.dashes, "dashOffset": s.dash_offset, }) } +/// Shape-tool creation uses the paint displayed for the active shape, including gradients. +pub fn shape_paint_params(fill: Option<&Fill>, stroke: Option<&ShapeStroke>) -> Value { + json!({"fill":fill.map_or(Value::Null,fill_json),"stroke":stroke.map_or(Value::Null,stroke_json)}) +} + +fn pattern_for_fill(s: &Session, fill: &mut Fill) -> Result> { + let Fill::Pattern { name, id, .. } = fill else { return Ok(None) }; + let pattern = if id.is_empty() { + crate::pattern_cmds::resolve(s, name) + } else { + let by_id = s.active().and_then(|st| st.doc.patterns.iter().find(|p| p.id == *id)).or_else(|| s.patterns.items.iter().find(|p| p.id == *id)); + let by_name = s + .active() + .and_then(|st| photocraft_doc::pattern::find(&st.doc.patterns, "", name)) + .or_else(|| photocraft_doc::pattern::find(&s.patterns.items, "", name)); + if let (Some(a), Some(b)) = (by_id, by_name) + && a.id != b.id + { + return Err(EngineError::Other("pattern id and name refer to different tiles".into())); + } + by_id.or(by_name).cloned() + } + .ok_or_else(|| EngineError::Other(format!("no pattern \"{name}\" (see pattern.list)")))?; + if pattern.width == 0 || pattern.height == 0 { + return Err(EngineError::Other("the pattern is empty".into())); + } + if id.is_empty() { + *name = pattern.name.clone(); + } + *id = pattern.id.clone(); + Ok(Some(pattern)) +} + +/// Validate a shape paint without changing the document, resolving catalog pattern references. +pub fn shape_fill(s: &Session, value: &Value) -> Result> { + let mut fill = parse_fill(value).map_err(EngineError::Other)?; + if let Some(fill) = &mut fill { + pattern_for_fill(s, fill)?; + } + Ok(fill) +} + /// Applies stroke keys onto `base` (`null` → no stroke). pub fn parse_stroke(v: &Value, base: Option, fg: Color) -> std::result::Result, String> { if v.is_null() || v.as_bool() == Some(false) { @@ -454,7 +648,7 @@ fn live_kind(l: &LiveShape) -> &'static str { /// Re-renders a shape layer's cache for `doc` (canvas-clipped, document pixel format). pub fn refresh_shape(doc: &Document, sh: &mut ShapeLayer) { - sh.cache = Some(vector::render_shape(sh, doc.pixel_format(), doc.bounds())); + sh.cache = Some(vector::render_shape_with_patterns(sh, doc.pixel_format(), doc.bounds(), &doc.patterns)); } /// A staged stroke edit rendered with the same validation and cache refresh as `shape.edit`. @@ -607,6 +801,16 @@ fn shape_info(s: &Session, id: LayerId) -> Result { } pub(crate) fn with_shape(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result) -> Result { + with_shape_patterns(s, id, label, &[], f) +} + +fn with_shape_patterns( + s: &mut Session, + id: LayerId, + label: &str, + patterns: &[photocraft_doc::Pattern], + f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result, +) -> Result { if let Some(st) = s.active() { let locks = st.doc.effective_locks(id); if locks.all || locks.pixels { @@ -614,6 +818,9 @@ pub(crate) fn with_shape(s: &mut Session, id: LayerId, label: &str, f: impl F } } s.edit(label, |doc, _| { + for pattern in patterns { + crate::pattern_cmds::ensure_in_doc(doc, pattern); + } let snapshot = doc.clone(); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if !matches!(l.content, LayerContent::Shape(_)) { @@ -655,14 +862,25 @@ fn shape_create(s: &mut Session, p: &Value) -> Result { }; let fg = s.tools.foreground; let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); - let fill = match p.get("fill") { + let mut fill = match p.get("fill") { Some(v) => parse_fill(v).map_err(|e| bad(CMD, e))?, None => Some(Fill::Solid(fgc)), }; - let stroke = match p.get("stroke") { + let mut stroke = match p.get("stroke") { Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(CMD, e))?, None => None, }; + let mut patterns = Vec::new(); + if let Some(fill) = &mut fill + && let Some(pattern) = pattern_for_fill(s, fill)? + { + patterns.push(pattern); + } + if let Some(stroke) = &mut stroke + && let Some(pattern) = pattern_for_fill(s, &mut stroke.paint)? + { + patterns.push(pattern); + } vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?; // Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode). if let Some(target) = p.get("addTo").and_then(Value::as_u64) { @@ -683,6 +901,9 @@ fn shape_create(s: &mut Session, p: &Value) -> Result { let name = p.get("name").and_then(Value::as_str).map(str::to_string); let mut sh = ShapeLayer { path, fill, stroke, live, ..Default::default() }; let id = s.edit("New Shape Layer", |doc, active| { + for pattern in &patterns { + crate::pattern_cmds::ensure_in_doc(doc, pattern); + } refresh_shape(doc, &mut sh); let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh))); @@ -698,7 +919,21 @@ fn shape_edit(s: &mut Session, p: &Value) -> Result { let fg = s.tools.foreground; let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); let name = p.get("name").and_then(Value::as_str).map(str::to_string); - with_shape(s, id, "Edit Shape", |sh, layer| { + let fill = p.get("fill").map(|value| shape_fill(s, value)).transpose()?; + let base = s.active().and_then(|st| st.doc.layer(id)).and_then(|l| if let LayerContent::Shape(sh) = &l.content { sh.stroke.clone() } else { None }); + let mut stroke = p.get("stroke").map(|value| parse_stroke(value, base, fgc).map_err(|e| bad(CMD, e))).transpose()?; + let mut patterns = Vec::new(); + if let Some(Some(mut fill)) = fill.clone() + && let Some(pattern) = pattern_for_fill(s, &mut fill)? + { + patterns.push(pattern); + } + if let Some(Some(stroke)) = &mut stroke + && let Some(pattern) = pattern_for_fill(s, &mut stroke.paint)? + { + patterns.push(pattern); + } + with_shape_patterns(s, id, "Edit Shape", &patterns, |sh, layer| { if let Some(v) = p.get("path") { sh.path = parse_path(v).map_err(|e| bad(CMD, e))?; sh.live = None; @@ -738,11 +973,11 @@ fn shape_edit(s: &mut Session, p: &Value) -> Result { if let Some(r) = p.get("fillRule").and_then(Value::as_str) { sh.path.fill_rule = if r.eq_ignore_ascii_case("evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }; } - if let Some(v) = p.get("fill") { - sh.fill = parse_fill(v).map_err(|e| bad(CMD, e))?; + if let Some(fill) = fill { + sh.fill = fill; } - if let Some(v) = p.get("stroke") { - sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?; + if let Some(stroke) = stroke { + sh.stroke = stroke; } if let Some(n) = name { layer.name = n; @@ -1676,7 +1911,7 @@ pub(crate) fn leak(s: String) -> &'static str { pub fn specs() -> Vec { let stroke = r##""stroke":{"width":px,"color":"#rrggbb"|fill,"opacity":0..100,"align":"inside|center|outside","cap":"butt|round|square","join":"miter|round|bevel","miterLimit":n,"dashes":[multiples of width],"dashOffset":n}|null"##; - let fill = r##""fill":"#rrggbb"|[r,g,b,a]|{"gradient":{"stops":[[t,"#hex"]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool}}|{"pattern":name}|null (no fill)"##; + let fill = r##""fill":"#rrggbb[aa]"|[r,g,b,a]|{"color":{mode,c:[4 channels],alpha}}|{"gradient":{"stops":[[0..1,colour]],"angle":deg,"scale":%>0,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"opacityStops":[[0..1,0..1]],"midpoints":[0..1],"offset":[fractionX,fractionY],"dither":bool,"align":bool}}|{"pattern":name|id,"id":str?,"scale":%>0,"angle":deg,"link":bool,"phase":[px,px]}|null (no fill)"##; vec![ spec!( "shape.create", diff --git a/crates/engine/tests/shape_paint_fidelity.rs b/crates/engine/tests/shape_paint_fidelity.rs new file mode 100644 index 0000000000..449a91f06c --- /dev/null +++ b/crates/engine/tests/shape_paint_fidelity.rs @@ -0,0 +1,175 @@ +//! Shape paint JSON preserves model colours and all gradient/pattern placement fields. +use photocraft_color::{Color, ColorMode}; +use photocraft_doc::{Fill, GradientStyle, LayerContent, LayerId, ShapeLayer, ShapeStroke}; +use photocraft_engine::{ + Session, + vector_cmds::{shape_fill, shape_paint_params}, +}; +use serde_json::json; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":64,"height":48,"depth":depth,"background":"transparent"})).unwrap(); + s +} + +fn active_shape(s: &Session) -> &ShapeLayer { + let st = s.active().unwrap(); + let LayerContent::Shape(shape) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape layer") }; + shape +} + +#[test] +fn exact_paints_roundtrip_through_create_edit_and_undo() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let pattern = s.patterns.items[0].clone(); + let mut fills = vec![ + Fill::Solid(Color::rgba(0.1234567, 0.3737, 0.919191, 0.4737)), + Fill::Solid(Color { mode: ColorMode::Grayscale, c: [0.314159, 0.0, 0.0, 0.0], alpha: 0.3737 }), + Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.17, 0.28, 0.39, 0.41], alpha: 0.73 }), + Fill::Solid(Color { mode: ColorMode::Lab, c: [57.3, -14.8, 23.9, 0.0], alpha: 0.63 }), + Fill::Pattern { name: "Stored pattern alias".into(), id: pattern.id, scale: 0.3737, angle: 27.3, link: false, phase: (-7.3, 4.1) }, + ]; + for style in [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond] { + fills.push(Fill::Gradient { + stops: vec![(0.1737, Color::rgba(0.12345, 0.34567, 0.56789, 0.61)), (0.9137, Color::rgba(0.9191, 0.8181, 0.7171, 0.82))], + angle: 37.3, + scale: 0.3737, + style, + reverse: true, + opacity_stops: vec![(0.07, 0.23), (0.91, 0.79)], + midpoints: vec![0.27], + offset: (-0.13, 0.21), + dither: true, + align: false, + }); + } + for fill in fills { + let stroke = ShapeStroke { paint: fill.clone(), opacity: 0.3737, width: 2.3, dashes: vec![2.1, 1.3], ..Default::default() }; + let before_parse = s.active().unwrap().doc.clone(); + let paint = shape_paint_params(Some(&fill), Some(&stroke)); + assert_eq!(shape_fill(&s, &paint["fill"]).unwrap(), Some(fill.clone())); + assert_eq!(s.active().unwrap().doc, before_parse, "view-only paint validation edited the document"); + let mut create = paint.clone(); + create["rect"] = json!([8, 8, 40, 24]); + s.execute("shape.create", create).unwrap(); + assert_eq!(active_shape(&s).fill, Some(fill.clone())); + assert_eq!(active_shape(&s).stroke, Some(stroke.clone())); + s.execute("shape.edit", json!({"fill":"#0000ff","stroke":null})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute("shape.edit", paint).unwrap(); + assert_eq!(active_shape(&s).fill, Some(fill)); + assert_eq!(active_shape(&s).stroke, Some(stroke)); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + let after = s.active().unwrap().doc.clone(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after); + } + } +} + +#[test] +fn solid_alpha_and_library_patterns_render_and_embed_in_the_same_history_step() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let library = s.patterns.items.clone(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let id = LayerId(s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":[0.17,0.31,0.43,0.3737]})).unwrap()["layer"].as_u64().unwrap()); + let alpha: [f32; 4] = serde_json::from_value(s.execute("document.pixel", json!({"x":24,"y":20})).unwrap()).unwrap(); + assert!((alpha[3] - 0.3737).abs() < 0.005, "depth={depth}: {alpha:?}"); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + s.execute("edit.redo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(id).is_some()); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute("shape.edit", json!({"fill":{"pattern":library[0].name},"stroke":{"width":4,"fill":{"pattern":library[1].id}}})).unwrap(); + assert_eq!(s.active().unwrap().doc.patterns.len(), 2); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + let pixel: [f32; 4] = serde_json::from_value(s.execute("document.pixel", json!({"x":24,"y":20})).unwrap()).unwrap(); + assert!(pixel[3] > 0.99 && pixel[0] > 0.1, "library pattern did not render: {pixel:?}"); + let stroke_pixel: [f32; 4] = serde_json::from_value(s.execute("document.pixel", json!({"x":7,"y":20})).unwrap()).unwrap(); + assert!(stroke_pixel[3] > 0.99, "library pattern stroke did not render: {stroke_pixel:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + assert!(s.active().unwrap().doc.patterns.is_empty()); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.patterns.len(), 2); + // A freshly created patterned shape carries its own tile too. + let mut fresh = session(depth); + fresh.execute("shape.create", json!({"rect":[8,8,40,24],"fill":{"pattern":library[0].id}})).unwrap(); + assert_eq!(fresh.active().unwrap().doc.patterns.len(), 1); + let pixel: [f32; 4] = serde_json::from_value(fresh.execute("document.pixel", json!({"x":24,"y":20})).unwrap()).unwrap(); + assert!(pixel[3] > 0.99); + fresh.execute("edit.undo", json!({})).unwrap(); + assert!(fresh.active().unwrap().doc.patterns.is_empty()); + } +} + +#[test] +fn imported_document_pattern_resolves_without_a_global_library_entry() { + let mut s = session(16); + let imported = s.patterns.items[0].clone(); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(imported.clone()); + s.patterns.items.clear(); + let fill = Fill::Pattern { name: "Imported name preserved".into(), id: imported.id, scale: 0.3737, angle: -17.3, link: false, phase: (3.1, -2.7) }; + let paint = shape_paint_params(Some(&fill), None); + let before = s.active().unwrap().doc.clone(); + assert_eq!(shape_fill(&s, &paint["fill"]).unwrap(), Some(fill.clone())); + assert_eq!(s.active().unwrap().doc, before); + let mut create = paint; + create["rect"] = json!([8, 8, 40, 24]); + s.execute("shape.create", create).unwrap(); + assert_eq!(active_shape(&s).fill, Some(fill)); + assert_eq!(s.active().unwrap().doc.patterns.len(), 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn legacy_defaults_and_malformed_paint_inputs_are_explicit_and_atomic() { + let mut s = session(8); + assert_eq!( + shape_fill(&s, &json!({"gradient":{}})).unwrap(), + Some(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 90.0, 1.0, GradientStyle::Linear, false)) + ); + assert_eq!(shape_fill(&s, &json!("#ff000080")).unwrap(), Some(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 128.0 / 255.0)))); + s.execute("shape.create", json!({"rect":[8,8,40,24]})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + for fill in [ + json!([0, "bad", 1, 0.5]), + json!([0, 0, 0, 2]), + json!([0, 0, 0, 1, 1]), + json!({"gradient":null}), + json!({"gradient":{"stops":[[0,"#000000"],["bad","#ffffff"]]}}), + json!({"gradient":{"stops":[[2,"#000000"]]}}), + json!({"gradient":{"opacityStops":[[0,2]]}}), + json!({"gradient":{"midpoints":[-0.1]}}), + json!({"gradient":{"offset":[0]}}), + json!({"gradient":{"scale":0}}), + json!({"gradient":{"scale":1e100}}), + json!({"gradient":{"align":"false"}}), + json!({"gradient":{"dither":null}}), + json!({"gradient":{"style":"unknown"}}), + json!({"pattern":1}), + json!({"pattern":"missing pattern"}), + json!({"pattern":"Checkerboard","link":0}), + json!({"pattern":"Checkerboard","phase":[0,1e100]}), + json!({"pattern":"Checkerboard","id":1}), + json!({"color":{"mode":"Rgb","c":[0,0,0,0],"alpha":-1}}), + json!({"gradient":{"stops":vec![json!([0,"#000000"]);4097]}}), + ] { + assert!(shape_fill(&s, &fill).is_err(), "{fill}"); + assert!(s.execute("shape.edit", json!({"fill":fill.clone()})).is_err(), "{fill}"); + assert!(s.execute("shape.create", json!({"rect":[0,0,5,5],"stroke":{"fill":fill}})).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + } +} diff --git a/crates/engine/tests/shape_pattern_clipboard.rs b/crates/engine/tests/shape_pattern_clipboard.rs new file mode 100644 index 0000000000..311eee639a --- /dev/null +++ b/crates/engine/tests/shape_pattern_clipboard.rs @@ -0,0 +1,222 @@ +//! Vector style clipboards retain the pattern tile after its source document closes. +use photocraft_doc::{Color, Fill, LayerContent, Pattern, PixelFormat, ShapeLayer, ShapeStroke}; +use photocraft_engine::{Session, vector_cmds::shape_fill}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +fn imported_pattern() -> Pattern { + let mut surface = Surface::new(PixelFormat::RGBA16); + surface.fill_rect(Rect::new(0, 0, 4, 4), &[0.13, 0.27, 0.91, 1.0]); + Pattern::new("$$$/Patterns/Test/Blue=Imported Blue", surface, 4, 4) +} + +fn new_doc(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width":64,"height":48,"depth":depth,"background":"transparent"})).unwrap(); +} + +fn shape(s: &Session) -> &ShapeLayer { + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("shape") }; + sh +} + +#[test] +fn patterned_fill_and_stroke_clipboards_keep_cow_tiles_after_source_closes() { + for depth in [8, 16, 32] { + for imported in [false, true] { + let mut s = Session::new(); + new_doc(&mut s, depth); + let pattern = if imported { + let p = imported_pattern(); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(p.clone()); + s.patterns.items.clear(); + p + } else { + s.patterns.items[0].clone() + }; + let paint = json!({"pattern":pattern.name,"id":pattern.id,"scale":100,"angle":0,"link":false,"phase":[0,0]}); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":paint,"stroke":{"width":4,"fill":paint}})).unwrap(); + let copied_fill = shape(&s).fill.clone(); + let copied_stroke = shape(&s).stroke.clone(); + let fill_pixel = shape(&s).cache.as_ref().unwrap().rgba(24, 20); + let stroke_pixel = shape(&s).cache.as_ref().unwrap().rgba(7, 20); + let original = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute("path.style.copyFill", json!({})).unwrap(); + s.execute("path.style.copyStroke", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, original); + assert_eq!(s.active().unwrap().history.past_len(), history); + // Editing the source tile after Copy must not change the copied COW snapshot. + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns[0].surface.fill_rect(pattern.rect(), &[1.0, 0.0, 0.0, 1.0]); + s.patterns.items.clear(); + assert!(s.close(0).is_some()); + for (paste, sample, expected) in [("path.style.pasteFill", (24, 20), fill_pixel), ("path.style.pasteStroke", (7, 20), stroke_pixel)] { + new_doc(&mut s, depth); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":null})).unwrap(); + assert!(s.active().unwrap().doc.patterns.is_empty()); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute(paste, json!({})).unwrap(); + let after = s.active().unwrap().doc.clone(); + assert_eq!(after.patterns, vec![pattern.clone()]); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + if paste == "path.style.pasteFill" { + assert_eq!(shape(&s).fill, copied_fill); + } else { + assert_eq!(shape(&s).stroke, copied_stroke); + } + let pixel = shape(&s).cache.as_ref().unwrap().rgba(sample.0, sample.1); + assert!(pixel[3] > 0.99, "{paste}: copied pattern remained transparent"); + assert!( + pixel.iter().zip(expected).all(|(a, b)| (*a - b).abs() < 0.005), + "{paste}, imported={imported}, depth={depth}: {pixel:?} != {expected:?}" + ); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + assert!(s.active().unwrap().doc.patterns.is_empty()); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after); + } + } + } +} + +#[test] +fn replacing_public_clipboards_with_plain_paints_ignores_old_pattern_snapshots() { + let mut s = Session::new(); + new_doc(&mut s, 8); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":{"pattern":"Checkerboard"},"stroke":{"width":4,"fill":{"pattern":"Checkerboard"}}})).unwrap(); + s.execute("path.style.copyFill", json!({})).unwrap(); + s.execute("path.style.copyStroke", json!({})).unwrap(); + new_doc(&mut s, 8); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":null})).unwrap(); + let fill = Fill::Solid(Color::rgba(0.13, 0.27, 0.91, 0.73)); + let stroke = ShapeStroke { paint: fill.clone(), width: 4.0, ..Default::default() }; + s.path_fill_clipboard = Some(fill.clone()); + s.path_stroke_clipboard = Some(stroke.clone()); + s.execute("path.style.pasteFill", json!({})).unwrap(); + s.execute("path.style.pasteStroke", json!({})).unwrap(); + assert_eq!(shape(&s).fill, Some(fill)); + assert_eq!(shape(&s).stroke, Some(stroke)); + assert!(s.active().unwrap().doc.patterns.is_empty()); +} + +#[test] +fn legacy_pattern_clipboard_without_a_snapshot_resolves_the_library() { + let mut s = Session::new(); + let p = s.patterns.items[0].clone(); + for old_id in ["", "obsolete-library-id"] { + new_doc(&mut s, 16); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":null})).unwrap(); + s.path_fill_clipboard = Some(Fill::Pattern { name: p.name.clone(), id: old_id.into(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) }); + s.execute("path.style.pasteFill", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.patterns, vec![p.clone()]); + assert_eq!(shape(&s).fill, Some(Fill::Pattern { name: p.name.clone(), id: p.id.clone(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) })); + assert!(shape(&s).cache.as_ref().unwrap().rgba(24, 20)[3] > 0.99); + } +} + +#[test] +fn copied_name_only_and_obsolete_ids_bind_to_the_snapshot_despite_destination_conflicts() { + for old_id in ["", "obsolete-imported-id"] { + for stroke in [false, true] { + let mut s = Session::new(); + new_doc(&mut s, 16); + let pattern = imported_pattern(); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(pattern.clone()); + let paint = json!({"pattern":pattern.name,"id":pattern.id,"scale":37.37,"angle":17.3,"link":false,"phase":[-2.7,3.1]}); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":paint,"stroke":{"width":4,"fill":paint}})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let LayerContent::Shape(source) = &mut doc.layer_mut(id).unwrap().content else { panic!("source shape") }; + if let Some(Fill::Pattern { id, .. }) = &mut source.fill { + *id = old_id.into(); + } + if let Some(ShapeStroke { paint: Fill::Pattern { id, .. }, .. }) = &mut source.stroke { + *id = old_id.into(); + } + let mut expected_fill = shape(&s).fill.clone().unwrap(); + let mut expected_stroke = shape(&s).stroke.clone().unwrap(); + if let Fill::Pattern { id, .. } = &mut expected_fill { + *id = pattern.id.clone(); + } + if let Fill::Pattern { id, .. } = &mut expected_stroke.paint { + *id = pattern.id.clone(); + } + let original = s.active().unwrap().doc.clone(); + s.execute(if stroke { "path.style.copyStroke" } else { "path.style.copyFill" }, json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, original, "normalization changes the clipboard, not imported source metadata"); + if stroke { + assert_eq!(s.path_stroke_clipboard, Some(expected_stroke.clone())); + } else { + assert_eq!(s.path_fill_clipboard, Some(expected_fill.clone())); + } + s.patterns.items.clear(); + new_doc(&mut s, 16); + let mut conflicting = pattern.clone(); + conflicting.id = if old_id.is_empty() { "destination-pattern-id".into() } else { old_id.into() }; + conflicting.surface.fill_rect(pattern.rect(), &[1.0, 0.0, 0.0, 1.0]); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(conflicting.clone()); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":null})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute(if stroke { "path.style.pasteStroke" } else { "path.style.pasteFill" }, json!({})).unwrap(); + let after = s.active().unwrap().doc.clone(); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + assert_eq!(after.patterns, vec![conflicting, pattern.clone()]); + if stroke { + assert_eq!(shape(&s).stroke, Some(expected_stroke)); + } else { + assert_eq!(shape(&s).fill, Some(expected_fill)); + } + let pixel = shape(&s).cache.as_ref().unwrap().rgba(if stroke { 7 } else { 24 }, 20); + assert!( + pixel[2] > 0.85 && pixel[0] < 0.2 && pixel[3] > 0.99, + "stroke={stroke}, old_id={old_id:?}: destination pattern replaced copied blue: {pixel:?}" + ); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after); + } + } +} + +#[test] +fn unresolved_and_conflicting_pattern_clipboards_fail_atomically() { + let mut s = Session::new(); + new_doc(&mut s, 16); + let p = imported_pattern(); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(p.clone()); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":{"pattern":p.name,"id":p.id}})).unwrap(); + s.execute("path.style.copyFill", json!({})).unwrap(); + new_doc(&mut s, 16); + s.execute("shape.create", json!({"rect":[8,8,40,24],"fill":null})).unwrap(); + let mut conflicting = p.clone(); + conflicting.surface.fill_rect(p.rect(), &[1.0, 0.0, 0.0, 1.0]); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(conflicting); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let error = s.execute("path.style.pasteFill", json!({})).unwrap_err(); + assert!(error.to_string().contains("different pattern")); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); + s.path_fill_clipboard = Some(Fill::Pattern { name: "Missing".into(), id: "missing".into(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) }); + assert!(s.execute("path.style.pasteFill", json!({})).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + +#[test] +fn pattern_parser_falls_back_to_imported_display_names_and_rejects_conflicting_ids() { + let mut s = Session::new(); + new_doc(&mut s, 16); + let p = imported_pattern(); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).patterns.push(p.clone()); + let before = s.active().unwrap().doc.clone(); + let fill = shape_fill(&s, &json!({"pattern":"Imported Blue","id":"obsolete-id","angle":17,"phase":[3,4]})).unwrap().unwrap(); + assert_eq!(fill, Fill::Pattern { name: "Imported Blue".into(), id: p.id.clone(), scale: 1.0, angle: 17.0, link: true, phase: (3.0, 4.0) }); + assert!(shape_fill(&s, &json!({"pattern":s.patterns.items[0].name,"id":p.id})).is_err()); + assert_eq!(s.active().unwrap().doc, before); +} diff --git a/crates/engine/tests/shape_patterns.rs b/crates/engine/tests/shape_patterns.rs new file mode 100644 index 0000000000..abfd9de283 --- /dev/null +++ b/crates/engine/tests/shape_patterns.rs @@ -0,0 +1,74 @@ +use photocraft_doc::{LayerContent, LayerId, Pattern, PixelFormat}; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +fn library_pattern() -> Pattern { + let mut surface = Surface::new(PixelFormat::RGBA16); + surface.fill_rect(Rect::new(0, 0, 2, 2), &[0.1, 0.2, 0.9, 1.0]); + surface.fill_rect(Rect::new(1, 0, 2, 2), &[0.9, 0.7, 0.1, 1.0]); + Pattern::new("Shape tile", surface, 2, 2) +} + +#[test] +fn patterned_shapes_embed_render_and_undo_in_one_command_at_every_depth() { + for depth in [8, 16, 32] { + let mut session = Session::new(); + session.execute("file.new", json!({"width":32,"height":32,"depth":depth})).unwrap(); + let p = library_pattern(); + session.patterns.items.push(p.clone()); + let history = session.active().unwrap().history.past_len(); + let f = json!({"pattern":p.name,"id":p.id,"scale":100,"angle":0,"link":true}); + let id = LayerId( + session.execute("shape.create", json!({"kind":"rect","rect":[8,8,16,16],"fill":f,"stroke":{"width":4,"fill":f}})).unwrap()["layer"] + .as_u64() + .unwrap(), + ); + let doc = session.active().unwrap().doc.clone(); + assert_eq!(session.active().unwrap().history.past_len(), history + 1); + assert_eq!(doc.patterns, vec![p.clone()]); + let surface = doc.layer(id).unwrap().surface().unwrap(); + let q = surface.rgba(10, 10); + assert!(q[2] > 0.85 && q[0] < 0.15 && q[3] > 0.99, "pattern fill is visible: {q:?}"); + let q = surface.rgba(6, 12); + assert!(q[2] > 0.85 && q[3] > 0.99, "pattern stroke is visible: {q:?}"); + assert!(session.undo()); + assert!(session.active().unwrap().doc.patterns.is_empty()); + assert!(session.active().unwrap().doc.layer(id).is_none()); + assert!(session.redo()); + assert_eq!(session.active().unwrap().doc, doc); + + let saved = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + let native = photocraft_format::load_from_bytes(&saved).unwrap(); + assert_eq!(&native, doc.as_ref()); + let bytes = photocraft_io::export(&doc, "psd", &Default::default()).unwrap().bytes; + let mut imported = photocraft_io::import("shape-pattern.psd", &bytes).unwrap().document; + assert_eq!(imported.patterns.len(), 1); + let imported_id = imported.layers.iter().find(|l| matches!(l.content, LayerContent::Shape(_))).unwrap().id; + // Prove editable paint survives, rather than relying on the PSD's cached pixels. + let source = imported.clone(); + if let LayerContent::Shape(sh) = &mut imported.layer_mut(imported_id).unwrap().content { + photocraft_engine::vector_cmds::refresh_shape(&source, sh); + } + let q = imported.layer(imported_id).unwrap().surface().unwrap().rgba(10, 10); + assert!(q[2] > 0.8 && q[0] < 0.2 && q[3] > 0.99, "PSD pattern remains renderable after refresh: {q:?}"); + } +} + +#[test] +fn editing_a_solid_shape_to_pattern_embeds_and_undoes_the_tile() { + let mut session = Session::new(); + session.execute("file.new", json!({"width":32,"height":32})).unwrap(); + let p = library_pattern(); + session.patterns.items.push(p.clone()); + let id = session.execute("shape.create", json!({"kind":"rect","rect":[8,8,16,16],"fill":"#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + let original = session.active().unwrap().doc.clone(); + session.execute("shape.edit", json!({"layer":id,"fill":{"pattern":p.name,"id":p.id}})).unwrap(); + assert_eq!(session.active().unwrap().doc.patterns, vec![p]); + let edited = session.active().unwrap().doc.clone(); + assert!(session.undo()); + assert_eq!(session.active().unwrap().doc, original); + assert!(session.redo()); + assert_eq!(session.active().unwrap().doc, edited); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 771fec92e9..3f532c9320 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -267,6 +267,12 @@ toolbox colour as `backgroundColor: [r,g,b]` (0..1), so reusing it does not foll changes. Up to 256 presets are kept. Invalid saved entries are skipped independently; other presets and preferences still load. Automatic Recent configurations are separate follow-up work. +## Shape tools + +Paint JSON retains solid alpha/model colours; gradient `opacityStops`, `midpoints`, `offset`, +`dither`, `align`; pattern `id`, `angle`, `link`, `phase` alongside legacy stops/name/scale. +Shape create/edit resolves document or preset pattern tiles and embeds them in the same undo step. + ## Snapping With View › Snap on, tool gestures snap to the View › Snap To targets (guides and grid while they