diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs index 493559f13d..989f312db8 100644 --- a/crates/engine/src/vector_cmds.rs +++ b/crates/engine/src/vector_cmds.rs @@ -163,6 +163,11 @@ pub(crate) fn color(v: &Value) -> Option { _ => None, } } + // A stored `Color` (mode + components), so a CMYK or Lab gradient stop survives a + // read-modify-write through the shape swatches. + Value::Object(_) => serde_json::from_value::(v.clone()) + .ok() + .filter(|c| c.c.iter().all(|x| x.is_finite()) && c.alpha.is_finite() && (0.0..=1.0).contains(&c.alpha)), _ => None, } } @@ -271,9 +276,11 @@ fn parse_fill(v: &Value) -> std::result::Result, String> { } if let Some(g) = v.get("gradient") { // Stop lists are capped as `gradient.fill.stop` caps them: more is an error, not a cut. - let list = |key: &str, what: &str| match g.get(key).and_then(Value::as_array) { - Some(a) if a.len() > MAX_GRADIENT_STOPS => Err(format!("too many {what} (max {MAX_GRADIENT_STOPS})")), - a => Ok(a), + let list = |key: &str, what: &str| match g.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() > MAX_GRADIENT_STOPS => Err(format!("too many {what} (max {MAX_GRADIENT_STOPS})")), + Some(Value::Array(a)) => Ok(Some(a)), + Some(_) => Err(format!("gradient `{key}` must be an array")), }; let stops: Vec<(f32, Color)> = list("stops", "colour stops")? .map(|a| a.iter().filter_map(|s| Some((s.get(0)?.as_f64()? as f32, color(s.get(1)?)?))).collect()) @@ -1787,7 +1794,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"|[r,g,b,a]]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"opacityStops":[[t,0..1]]?,"midpoints":[0..1]?,"offset":[x,y]?,"dither":bool?,"align":bool?}}|{"pattern":name}|null (no fill)"##; + let fill = r##""fill":"#rrggbb"|[r,g,b,a]|{"gradient":{"stops":[[t,"#hex"|[r,g,b,a]|stored Color]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"opacityStops":[[t,0..1]]?,"midpoints":[0..1]?,"offset":[x,y]?,"dither":bool?,"align":bool?}}|{"pattern":name}|null (no fill)"##; vec![ spec!( "shape.create", diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rs index 285311ebd2..0b5b89aae9 100644 --- a/crates/engine/src/vector_cmds/tests.rs +++ b/crates/engine/src/vector_cmds/tests.rs @@ -33,12 +33,18 @@ fn stroke_validation_rejects_hostile_values_without_editing_history() { json!({"color": {"gradient": {"stops": vec![json!([0.5, "#ff0000"]); 1025]}}}), json!({"color": {"gradient": {"opacityStops": vec![json!([0.5, 1.0]); 1025]}}}), json!({"color": {"gradient": {"midpoints": vec![0.5; 1025]}}}), + // A stop list that is not an array is an error, not the default black-to-white. + json!({"color": {"gradient": {"stops": "red"}}}), + json!({"color": {"gradient": {"opacityStops": {}}}}), + json!({"color": {"gradient": {"midpoints": 1}}}), ]; for stroke in invalid { assert!(s.execute("shape.edit", json!({"layer": id, "stroke": stroke})).is_err(), "{stroke}"); assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); assert!(s.execute("shape.create", json!({"rect": [20, 20, 50, 30], "stroke": stroke})).is_err(), "{stroke}"); + assert_eq!(s.active().unwrap().doc, before, "{stroke}: a rejected create adds no layer"); + assert_eq!(s.active().unwrap().history.past_len(), history, "{stroke}: nor a history state"); } assert!(s.execute("shape.edit", json!({"layer": id, "rect": [1e100, 0, 20, 20]})).is_err()); assert_eq!(s.active().unwrap().doc, before); @@ -47,6 +53,29 @@ fn stroke_validation_rejects_hostile_values_without_editing_history() { s.execute("shape.edit", json!({"layer": id, "stroke": at_cap})).unwrap(); } +/// A gradient stop given as a stored `Color` keeps its colour model: a CMYK stop stays CMYK. +#[test] +fn gradient_stops_take_a_stored_color_and_keep_its_model() { + let mut s = session(100, 80, 8); + let id = s.execute("shape.create", json!({"rect": [20, 20, 50, 30], "stroke": {"width": 6}})).unwrap()["layer"].as_u64().unwrap(); + let cmyk = Color { mode: photocraft_doc::ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.9], alpha: 0.75 }; + let stops = json!([[0.0, cmyk], [1.0, "#ffffff"]]); + s.execute("shape.edit", json!({"layer": id, "stroke": {"color": {"gradient": {"stops": stops}}}})).unwrap(); + let doc = &s.active().unwrap().doc; + let LayerContent::Shape(sh) = &doc.layer(LayerId(id)).unwrap().content else { panic!("a shape layer") }; + let Fill::Gradient { stops, .. } = &sh.stroke.as_ref().unwrap().paint else { panic!("a gradient stroke") }; + assert_eq!(stops[0], (0.0, cmyk)); + assert_eq!(stops[1], (1.0, Color::WHITE), "hex stops still parse as before"); + // A stored colour that isn't finite or has alpha past 1 is not a colour: the stop is dropped, + // as an unparseable hex stop is. + let bad = json!({"mode": "Cmyk", "c": [0.1, 0.2, 0.3, 0.9], "alpha": 2.0}); + s.execute("shape.edit", json!({"layer": id, "stroke": {"color": {"gradient": {"stops": [[0.0, bad], [1.0, "#000000"]]}}}})).unwrap(); + let doc = &s.active().unwrap().doc; + let LayerContent::Shape(sh) = &doc.layer(LayerId(id)).unwrap().content else { panic!("a shape layer") }; + let Fill::Gradient { stops, .. } = &sh.stroke.as_ref().unwrap().paint else { panic!("a gradient stroke") }; + assert_eq!(stops.as_slice(), [(1.0, Color::BLACK)]); +} + /// A gradient stroke keeps every gradient field through `shape.edit`, and `shape.info` reports /// them, so the shape swatches can change one setting without dropping the rest. #[test] diff --git a/crates/ui-egui/src/shape_options.rs b/crates/ui-egui/src/shape_options.rs index 231e206d3f..eeeaf54f3e 100644 --- a/crates/ui-egui/src/shape_options.rs +++ b/crates/ui-egui/src/shape_options.rs @@ -72,7 +72,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool if stroke.is_some() || width > 0.0 { let mut p = json!({"width": width}); if stroke.is_none() { - p["color"] = json!(bg); + p["color"] = o.shape_stroke_gradient.as_ref().map_or_else(|| json!(bg), paint_param); } edit = Some(json!({"stroke": p, "coalesce": key("stroke-w")})); } @@ -86,7 +86,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool p["width"] = json!(3.0); } if stroke.is_none() { - p["color"] = json!(bg); + p["color"] = o.shape_stroke_gradient.as_ref().map_or_else(|| json!(bg), paint_param); } edit = Some(json!({"stroke": p, "coalesce": change.coalesce})); o.shape_stroke = change.options; diff --git a/crates/ui-egui/src/shape_paint_ui.rs b/crates/ui-egui/src/shape_paint_ui.rs index 155e3220c5..341109d697 100644 --- a/crates/ui-egui/src/shape_paint_ui.rs +++ b/crates/ui-egui/src/shape_paint_ui.rs @@ -19,13 +19,14 @@ pub(crate) fn rgba_of(c: &photocraft_doc::Color) -> [f32; 4] { [r, g, b, c.alpha] } -/// A solid or gradient paint exactly as `shape.create` / `shape.edit` take it: float RGBA and -/// every gradient field, so a swatch edit (angle, style…) keeps the rest of the gradient. The -/// swatches never hand it a pattern (they don't offer one). +/// A solid or gradient paint exactly as `shape.create` / `shape.edit` take it: float RGBA, the +/// gradient's stops as stored colours (a CMYK or Lab stop keeps its model) and every gradient +/// field, so a swatch edit (angle, style…) keeps the rest of the gradient. The swatches never +/// hand it a pattern (they don't offer one). pub(crate) fn paint_param(f: &photocraft_doc::Fill) -> Value { match f { photocraft_doc::Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => json!({"gradient": { - "stops": stops.iter().map(|(t, c)| json!([t, rgba_of(c)])).collect::>(), + "stops": stops.iter().map(|(t, c)| json!([t, c])).collect::>(), "angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse, "opacityStops": opacity_stops, "midpoints": midpoints, "offset": [offset.0, offset.1], "dither": dither, "align": align, }}), diff --git a/crates/ui-egui/src/vector_paint_tests.rs b/crates/ui-egui/src/vector_paint_tests.rs index 578ecfaf17..d71a8fca78 100644 --- a/crates/ui-egui/src/vector_paint_tests.rs +++ b/crates/ui-egui/src/vector_paint_tests.rs @@ -757,6 +757,52 @@ fn gradient_tab_keeps_the_stop_colour_after_a_preset_with_fewer_stops() { assert_eq!(after[1].0, before[1].0); } +/// A swatch edit that only changes the gradient's settings (Reverse) keeps a CMYK document's +/// stops as they are: before, every stop went out as sRGB RGBA and came back in the RGB model. +#[test] +fn gradient_tab_edit_keeps_cmyk_stops_in_their_model() { + let cmyk = |c: [f32; 4]| photocraft_doc::Color { mode: photocraft_doc::ColorMode::Cmyk, c, alpha: 1.0 }; + let stops = vec![(0.0, cmyk([0.1, 0.2, 0.3, 0.9])), (1.0, cmyk([0.75, 0.0, 0.5, 0.0]))]; + for (properties, label) in [(true, "Set shape stroke type"), (false, "Stroke color")] { + let mut app = app("cmyk", 8); + let stroke = json!({"width": 4, "color": {"gradient": {"stops": [[0.0, stops[0].1], [1.0, stops[1].1]]}}}); + app.run("shape.create", json!({"rect": [20, 20, 60, 40], "stroke": stroke})).unwrap(); + assert_eq!(gradient_stops(&shape(&app).stroke.as_ref().unwrap().paint).0, stops); + let mut h = harness(app, properties); + h.get_by_label(label).click(); + h.run_steps(3); + h.get_by_label("Reverse").click(); + h.run_steps(3); + let paint = shape(h.state()).stroke.clone().unwrap().paint; + assert!(matches!(paint, photocraft_doc::Fill::Gradient { reverse: true, .. }), "Properties={properties}: Reverse applied"); + assert_eq!(gradient_stops(&paint).0, stops, "Properties={properties}: the stops keep their CMYK model and values"); + } +} + +/// Options bar with a strokeless shape selected and the stroke swatch's gradient chosen: giving +/// the shape a stroke through the width field or the stroke type takes that gradient, as the next +/// shape does, not a solid background colour. +#[test] +fn width_and_stroke_type_give_a_strokeless_shape_the_tool_stroke_gradient() { + for via_width in [true, false] { + let mut app = app("rgb", 8); + app.run("shape.create", json!({"rect": [20, 20, 80, 60], "fill": "#336699", "stroke": null})).unwrap(); + set_tool_paint(&mut app, true, PaintChange::Gradient(test_gradient())).unwrap(); + let mut h = harness(app, false); + if via_width { + stroke_width(&mut h, "5"); + } else { + h.get_by_label("Stroke Options").click(); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Dotted").click(); + h.run_steps(3); + } + let stroke = shape(h.state()).stroke.clone().expect("a stroke"); + assert_eq!(stroke.paint, test_gradient(), "via_width={via_width}"); + assert_eq!(stroke.width, if via_width { 5.0 } else { 3.0 }); + } +} + /// An arrow-key step at 0 px on a strokeless shape must not add an invisible stroke. #[test] fn arrow_down_at_zero_width_keeps_a_strokeless_shape_strokeless() {