diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index e7f50fa8ee..ba12eafabb 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -36,14 +36,14 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { let was_relative = live.radii_relative(); let base = match live { LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)), - LiveShape::Polygon { .. } => live.polygon_outline(), + LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(), LiveShape::Path { base, .. } => base.clone(), LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; let corners = path_corners(&base); let radii: &mut [f64] = match live { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii, LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, }; @@ -62,6 +62,7 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { match live { LiveShape::Rectangle { radii_relative: rel, .. } | LiveShape::Polygon { radii_relative: rel, .. } + | LiveShape::Star { radii_relative: rel, .. } | LiveShape::Path { radii_relative: rel, .. } => { *rel = relative; } @@ -99,7 +100,7 @@ impl<'a> LiveCorners<'a> { let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None }; (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative) } - Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => { + Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => { (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) } Some(LiveShape::Path { base, radii, kinds, radii_relative }) => { @@ -258,6 +259,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne edit(&outline, relative, radii, kinds, corners, radius, kind); trim_vec_radii(radii, kinds); } + LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => { + let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf); + let n = 2 * *points as usize; + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(&outline, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } LiveShape::Path { base, radii, kinds, .. } => { let n = base.anchor_count(); radii.resize(n, 0.0); diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c29e8464ea..fe2ffc0fd1 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -239,6 +239,52 @@ impl Document { round_json_paths(brushes, &round); } } + + /// Make every live star a plain path of the outline it draws, for a save that versions before + /// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the + /// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and + /// in the brush definitions. + pub fn live_stars_to_paths(&mut self) { + let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. })); + let mut plain = |n: &mut Node| { + if let NodeKind::Path { live, .. } = &mut n.kind + && matches!(live.as_deref(), Some(LiveShape::Star { .. })) + { + *live = None; + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + edit_branches_where(root, &is_star, &mut plain); + } + if let Some(brushes) = self.unknown.get_mut("brushes") { + json_stars_to_paths(brushes); + } + } +} + +/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a +/// star. +fn json_stars_to_paths(v: &mut serde_json::Value) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("path") + && o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") + { + o.remove("live"); + } + o.values_mut().for_each(json_stars_to_paths); + } + Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths), + _ => {} + } } /// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds, diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 0a17301331..33b3f10868 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -46,11 +46,32 @@ pub enum LiveShape { #[serde(default, skip_serializing_if = "is_false")] radii_relative: bool, }, + /// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable. + Star { + /// Outer radius: centre to each tip. + r1: f64, + /// Inner radius: centre to each point between two tips. + r2: f64, + /// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_points")] + points: u32, + /// Maps the star (centred on the origin, first tip straight up) into the document. + xf: Affine, + /// Corner radii in document units, by vertex from the first tip clockwise, tips and inner + /// points alternating (none: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (none: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, Line { a: Point, b: Point, }, - /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut + /// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut /// outline so the corners stay editable. Without a cut corner it is a plain path again. Path { /// The path with its corners uncut, in the document. @@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool { impl LiveShape { pub fn radii_relative(&self) -> bool { match self { - LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => { - *radii_relative - } + LiveShape::Rectangle { radii_relative, .. } + | LiveShape::Polygon { radii_relative, .. } + | LiveShape::Star { radii_relative, .. } + | LiveShape::Path { radii_relative, .. } => *radii_relative, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false, } } @@ -86,6 +108,7 @@ impl LiveShape { LiveShape::Rectangle { .. } => "Rectangle", LiveShape::Ellipse { .. } => "Ellipse", LiveShape::Polygon { .. } => "Polygon", + LiveShape::Star { .. } => "Star", LiveShape::Line { .. } => "Line", LiveShape::Path { .. } => "Path", } @@ -100,7 +123,7 @@ impl LiveShape { shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf) } LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), - LiveShape::Polygon { radii, kinds, radii_relative, .. } => { + LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => { let outline = self.polygon_outline(); let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative); cut_corners(&outline, &radii, kinds).0 @@ -112,10 +135,12 @@ impl LiveShape { } } } - /// A polygon's outline with its corners uncut, in the document (empty for other shapes). + /// A polygon's or star's outline with its corners uncut, in the document (empty for other + /// shapes). pub fn polygon_outline(&self) -> PathData { match self { LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), + LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf), _ => PathData::default(), } } @@ -123,16 +148,38 @@ impl LiveShape { /// the corners past the old last one are sharp. pub fn set_sides(&mut self, n: u64) { let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; + let old = *sides as usize; *sides = n.clamp(3, 1000) as u32; - fn spread(v: &mut Vec, n: usize) { - match v.first().copied() { - Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], - Some(_) => v.resize(n, T::default()), - None => {} - } + spread(radii, old, *sides as usize); + spread(kinds, old, *sides as usize); + } + /// A star's point count. None for other shapes. + pub fn star_points(&self) -> Option { + let LiveShape::Star { points, .. } = self else { return None }; + Some(*points) + } + /// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the + /// corners past the old last one are sharp. + pub fn set_points(&mut self, n: u64) { + let LiveShape::Star { points, radii, kinds, .. } = self else { return }; + let old = 2 * *points as usize; + *points = n.clamp(2, 1000) as u32; + spread(radii, old, 2 * *points as usize); + spread(kinds, old, 2 * *points as usize); + } + /// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None + /// for other shapes. + pub fn star_ratio(&self) -> Option { + let LiveShape::Star { r1, r2, .. } = self else { return None }; + Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 }) + } + /// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer + /// radius. Nothing changes for other shapes or a ratio outside 0 to 1. + pub fn set_star_ratio(&mut self, ratio: f64) { + let LiveShape::Star { r1, r2, .. } = self else { return }; + if ratio.is_finite() && (0.0..=1.0).contains(&ratio) { + *r2 = *r1 * ratio; } - spread(radii, *sides as usize); - spread(kinds, *sides as usize); } /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of /// `xf` (exact while its sides are equal). None for other shapes. @@ -151,7 +198,9 @@ impl LiveShape { /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for /// other shapes. pub fn shape_angle(&self) -> Option { - let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else { + return None; + }; // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) @@ -168,7 +217,7 @@ impl LiveShape { let angle = angle.rem_euclid(360.0); let (xf, local) = match self { LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), - LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO), LiveShape::Line { .. } | LiveShape::Path { .. } => return, }; let center = *xf * local; @@ -274,7 +323,7 @@ impl LiveShape { *xf = a * *xf; false } - LiveShape::Polygon { xf, radii, radii_relative, .. } => { + LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => { *xf = a * *xf; scale_radii(radii, a, *radii_relative) } @@ -326,7 +375,7 @@ impl LiveShape { let relative = self.radii_relative(); let radii: &mut [f64] = match self { LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii, LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, }; if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { @@ -338,7 +387,7 @@ impl LiveShape { /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). pub fn angle_deg(&self) -> f64 { match self { - LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { + LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => { let c = xf.as_coeffs(); c[1].atan2(c[0]).to_degrees() } @@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { u32::deserialize(d).map(|n| n.clamp(3, 1000)) } +/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]). +fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + +/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it; +/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list +/// shorter than `old` holds the default for its missing corners, so it is shared only when that +/// default is; entries of a longer list past `old` name no corner and go first. An empty list +/// stays empty. +fn spread(v: &mut Vec, old: usize, n: usize) { + v.truncate(old); + if !v.is_empty() && v.len() < old { + v.resize(old, T::default()); + } + match v.first().copied() { + Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], + Some(_) => v.resize(n, T::default()), + None => {} + } +} + /// Whether `a` only moves (no rotation, scale, shear or reflection). pub(super) fn moves_only(a: Affine) -> bool { let [a0, a1, a2, a3, _, _] = a.as_coeffs(); diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 480e201e2d..2ecdda06bd 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() { assert_eq!(huge.polygon_outline().anchor_count(), 1000); } +/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points. +#[test] +fn a_star_round_trips_and_its_file_count_is_clamped() { + let star = LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 7, + xf: Affine::translate((10.0, 20.0)), + radii: vec![2.0; 14], + kinds: vec![], + radii_relative: false, + }; + let text = serde_json::to_string(&star).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), star); + assert_eq!(star.label(), "Star"); + let read = |points: u64| { + let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap().star_points().unwrap() + }; + assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]); + // Points and ratio change; the outer radius stays. + let mut s = star.clone(); + s.set_points(9); + s.set_star_ratio(0.25); + assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18])); + assert_eq!(s.polygon_outline().anchor_count(), 18); +} + +/// A corner list shorter than the corners holds sharp corners past its end, so a new point or +/// side count does not give those corners the first corner's radius. +#[test] +fn a_short_corner_list_keeps_its_missing_corners_sharp() { + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + star.set_points(6); + let mut want = vec![0.0; 12]; + want[0] = 2.0; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}"); + let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false }; + polygon.set_sides(6); + let mut want = vec![0.0; 6]; + want[0] = 2.0; + assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}"); +} + +/// A corner list longer than the corners drops its entries past the old last corner, so the +/// corners a new point count adds are sharp and keep the default kind. +#[test] +fn a_long_corner_list_drops_its_entries_past_the_corners() { + let mut radii = vec![0.0; 12]; + radii[0] = 2.0; + radii[10] = 7.0; + radii[11] = 7.0; + let mut kinds = vec![CornerKind::Round; 12]; + kinds[0] = CornerKind::Chamfer; + kinds[10] = CornerKind::Chamfer; + kinds[11] = CornerKind::Chamfer; + let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false }; + star.set_points(6); + let mut want_radii = vec![0.0; 12]; + want_radii[0] = 2.0; + let mut want_kinds = vec![CornerKind::Round; 12]; + want_kinds[0] = CornerKind::Chamfer; + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}"); + assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}"); + // A complete list that all corners share still fills the new corners. + let mut star = + LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false }; + star.set_points(6); + assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}"); +} + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs index 7fc935546e..43e8948118 100644 --- a/crates/engine/src/cmd/addons/shapes.rs +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result { pie, arc_mode, }; - insert_custom(s, "Star", None, cs) + insert_custom(s, "Star", cs.to_live_shape(), cs) } fn spiral(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs index bc5f1359e2..274678dd62 100644 --- a/crates/engine/src/cmd/addons/shapes/tests.rs +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -144,6 +144,68 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape { CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap() } +#[test] +fn configuring_a_live_star_keeps_its_live_shape() { + let mut s = new_session(); + for cmd in ["shape.star", "addon.shapes.star"] { + let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. }))); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. }))); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert_eq!(path, &live.to_path()); + + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. })); + assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9); + assert_eq!(path, &live.to_path()); + } +} + +/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner +/// radius and stays live when it is configured without a ratio. +#[test] +fn configuring_a_live_star_keeps_a_small_ratio() { + let mut s = new_session(); + let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5})); + s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap(); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") }; + assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}"); + assert_eq!(path, &live.to_path()); +} + +/// Angles configured on a whole shape stay live and are kept for a later arc mode. +#[test] +fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() { + let mut s = new_session(); + let shapes = [ + ("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})), + ("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})), + ("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})), + ("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})), + ]; + for (cmd, p) in shapes { + let id = id_of(&mut s, cmd, p); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live"); + s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap(); + let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) { + Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie, + other => panic!("{cmd}: {other:?}"), + }; + assert_eq!(pie, (0.0, 90.0), "{cmd}"); + } +} + /// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they /// were. fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) { diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 083cfa65d9..934151589b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes", has_doc, star ), @@ -655,14 +655,11 @@ fn star(s: &mut Session, p: &Value) -> Result { let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32; let rot = f64_or(p, "rotation", 0.0); - let turn = vectorcraft_geom::rotate_deg(rot); // A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly. - let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) { - shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn) - } else { - shapes::star(c, r1, r2, n, rot) - }; - add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) + let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + // The star stays live: its point count and ratio can change later (`object.setLiveShape`). + let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false }; + add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot)) } fn line(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index ce1cff9107..d5a89f8789 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -314,7 +314,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b8bd5ff8c6..79a26dd73f 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -103,7 +103,7 @@ fn corners_param(p: &Value) -> Result>> { /// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live /// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are. fn takes_rounding(live: Option<&LiveShape>) -> bool { - matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. })) + matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. } | LiveShape::Path { .. })) } /// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about @@ -130,6 +130,16 @@ fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option bool { + fn layout(l: &LiveShape) -> Option>> { + let path = l.to_path(); + LiveCorners::new(&path, Some(l)).map(|c| c.sources().to_vec()) + } + old.star_points().is_some() && (old.star_points() != new.star_points() || layout(old) != layout(new)) +} + /// The transform that takes live shape `old` to `new` where they differ only in place, angle and /// size (a new Rectangle, Ellipse or Polygon Angle, Polygon Radius, Side Length, Make Sides Equal, /// Line Length or Line Angle): what moves, turns and scales the rest of the object (a linked @@ -175,7 +185,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"], "object.setLiveShape", )?; - check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; + check_numbers(p, &["radius", "sides", "points", "ratio"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { None => None, @@ -240,6 +250,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64) }; + // A star's Star Properties: its point count (a whole number from 2 to 1000, as `shape.star` + // takes it) and its ratio (inner radius over outer radius, above 0 and up to 1). Both are + // checked on replay too: no recording predates them. + let points = number("points", |n| n.fract() == 0.0 && (2.0..=1000.0).contains(&n), "a whole number from 2 to 1000")?.map(|n| n as u64); + let ratio = number("ratio", |r| r > 0.0 && r <= 1.0, "a ratio above 0 and up to 1")?; + // A new point count lays a star's corners out again, so the corners a radius or kind would set + // can't be told from the anchors selected before it. + if points.is_some() && (radius.is_some() || kind.is_some()) { + return Err(bad("object.setLiveShape", "`points` can't be set with `radius` or `kind`: set the corners in a call of their own")); + } // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); @@ -292,6 +312,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } else { ids }; + // A ratio is the inner radius over the outer one: a star whose outer radius is 0 has none to set. + if ratio.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).and_then(|n| n.live_shape()), Some(LiveShape::Star { r1, .. }) if *r1 <= 0.0)) + { + return Err(bad("object.setLiveShape", "a star whose outer radius is 0 has no ratio to set")); + } // The lines that Line Length or Line Angle changes, as they become. A line that would reach // past the document's coordinate limit is an error before anything changes. let mut lines = std::collections::BTreeMap::new(); @@ -321,6 +346,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { { return false; } + Some(l @ LiveShape::Star { points: now, .. }) + if !(points.is_none_or(|n| n.clamp(2, 1000) == u64::from(*now)) + && ratio.is_none_or(|r| l.star_ratio().is_some_and(|k| (k - r).abs() < 1e-12))) => + { + return false; + } Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => { return false; } @@ -386,6 +417,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } edited = true; } + if let l @ LiveShape::Star { .. } = &mut new + && (points.is_some() || ratio.is_some()) + { + if let Some(n) = points { + l.set_points(n); + } + if let Some(r) = ratio { + l.set_star_ratio(r); + } + edited = true; + } if let Some(a) = rectangle_angle && let l @ LiveShape::Rectangle { .. } = &mut new { @@ -411,6 +453,14 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { reshaped.insert(*id, ((**old).clone(), new)); } } + // A ratio that changes which corners a rounded star cuts lays its anchors out again, as a new + // point count does, so the corners a radius or kind would set can't be told apart. + if ratio.is_some() && (radius.is_some() || kind.is_some()) && reshaped.values().any(|(old, new)| star_relaid(old, new)) { + return Err(bad( + "object.setLiveShape", + "this `ratio` changes the star's anchors, so it can't be set with `radius` or `kind`: set the corners in a call of their own", + )); + } // A shape that moves, turns or scales takes the rest of the object along as a transform does: // Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the // preferences, and are noted in the journal so a replay does the same. Corner radii in the rest @@ -439,6 +489,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { *live = Some(Box::new(new.clone())); *path = new.to_path(); } + // A new point count, or a ratio that changes which corners the rounded star cuts, lays its + // anchors out again: anchors and segments selected on the old layout would name others, + // or none. + if star_relaid(old, new) { + sel.anchors.remove(id); + sel.segments.remove(id); + } } for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 982bf51d24..3d86e558b6 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -173,12 +173,12 @@ fn export_writes_the_sheet_and_rasterized_art() { // Without a path: the CSS as data, the pictures as base64. let r = run(&mut s, "css.export", json!({"scope": "all", "rasterize": true})); let data = r["data"].as_str().unwrap(); - assert!(data.contains(".rectangle {") && data.contains(".path {\n") && data.contains("background-image: url(path.png);"), "{data}"); + assert!(data.contains(".rectangle {") && data.contains(".star {\n") && data.contains("background-image: url(star.png);"), "{data}"); assert!(data.ends_with("}\n")); assert_eq!(r["rules"], json!(2)); let images = r["images"].as_array().unwrap(); assert_eq!(images.len(), 1, "only the star is rasterized"); - assert_eq!(images[0]["name"], json!("path.png")); + assert_eq!(images[0]["name"], json!("star.png")); let png = vectorcraft_format::base64_decode(images[0]["dataBase64"].as_str().unwrap()).unwrap(); assert!(png.starts_with(b"\x89PNG")); // The selection alone (the star, selected last). @@ -263,9 +263,9 @@ fn export_to_a_path_puts_the_pictures_next_to_the_sheet() { let path = dir.join("site.css"); let r = run(&mut s, "css.export", json!({"path": path.to_string_lossy(), "rasterize": true})); let written = std::fs::read_to_string(&path).unwrap(); - assert!(written.contains("url(path.png)"), "{written}"); + assert!(written.contains("url(star.png)"), "{written}"); assert_eq!(r["bytes"], json!(written.len())); - let png = dir.join("path.png"); + let png = dir.join("star.png"); assert_eq!(r["images"], json!([png.to_string_lossy()])); assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG")); std::fs::remove_dir_all(&dir).ok(); diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 42e39552aa..46a4ace011 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -334,7 +334,7 @@ fn corners_of_a_non_square_rectangle_are_alike_circles() { assert_spans(&s, id, [8.0; 4]); } -/// A selected five-pointed star at (200, 200) of radii 60 and 30: a plain path. +/// A selected five-pointed live star at (200, 200) of radii 60 and 30. fn star(s: &mut Session) -> NodeId { NodeId(s.execute("shape.star", &json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap()) } @@ -357,8 +357,8 @@ fn radii(s: &Session, id: NodeId) -> [f64; N] { std::array::from_fn(|k| c.radius(k)) } -/// #511: a star (a plain path) rounds all ten corners as one step, keeps them editable (a new -/// radius cuts the outline again rather than the cut path), and is the plain star again at 0. +/// #511: a live star rounds all ten corners as one step, keeps them editable (a new radius cuts +/// the outline again rather than the cut path), and is the sharp star again at 0. #[test] fn a_star_rounds_its_corners_and_keeps_them_live() { let (mut s, _) = session(); @@ -370,17 +370,102 @@ fn a_star_rounds_its_corners_and_keeps_them_live() { assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); let (path, live) = node_path(&s, id); assert_eq!(path.anchor_count(), 20); - assert!(matches!(&live, Some(LiveShape::Path { base, .. }) if *base == sharp), "{live:?}"); + assert!(matches!(&live, Some(l @ LiveShape::Star { points: 5, .. }) if l.polygon_outline() == sharp), "{live:?}"); assert_eq!(style(&s, id), (Some(4.0), Some(CornerKind::Round), 10)); - assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Path"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Star"); run(&mut s, json!({"radius": 6, "kind": "chamfer"})); assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (20, (Some(6.0), Some(CornerKind::Chamfer), 10))); run(&mut s, json!({"radius": 0, "kind": "round"})); - assert_eq!(node_path(&s, id), (sharp, None)); + let (path, live) = node_path(&s, id); + assert_eq!(path, sharp); + assert!(matches!(&live, Some(LiveShape::Star { radii, kinds, .. }) if radii.is_empty() && kinds.is_empty()), "{live:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(style(&s, id).0, Some(6.0)); } +/// #4339: a live star takes a new point count and ratio from `object.setLiveShape` in one undo +/// step each, keeps the corner radius its corners shared, and records nothing when the values +/// are the ones it has. A count or ratio out of range is an error that changes nothing. +#[test] +fn a_live_star_takes_a_new_point_count_and_ratio() { + let (mut s, _) = session(); + let id = star(&mut s); + assert_eq!(node_path(&s, id).0.anchor_count(), 10); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 16); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(8)); + // The same count again: no undo step. + run(&mut s, json!({"points": 8})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, json!({"ratio": 0.25})); + let (_, live) = node_path(&s, id); + assert!(matches!(live, Some(LiveShape::Star { r1, r2, .. }) if r1 == 60.0 && (r2 - 15.0).abs() < 1e-9)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2); + // The shared corner radius spreads to the new corners. + run(&mut s, json!({"radius": 3})); + run(&mut s, json!({"points": 6})); + assert_eq!(style(&s, id), (Some(3.0), Some(CornerKind::Round), 12)); + for bad in [ + json!({"points": 1}), + json!({"points": 1001}), + json!({"points": 5.5}), + json!({"ratio": 1.5}), + json!({"ratio": -0.1}), + json!({"ratio": 0}), + json!({"points": 7, "radius": 2}), + ] { + let before = node_path(&s, id); + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(node_path(&s, id), before, "{bad}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let (path, live) = node_path(&s, id); + assert_eq!(path.anchor_count(), 10); + assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(5)); + // Anchors selected on the old layout are dropped with a new point count. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 8]], "mode": "set"})).unwrap(); + run(&mut s, json!({"id": id.0, "points": 3})); + assert_eq!(selected_anchors(&s, id), None); + // A star whose outer radius is 0 has no ratio to set. + let flat = NodeId(s.execute("shape.star", &json!({"cx": 50, "cy": 50, "radius1": 0, "radius2": 10})).unwrap()["id"].as_u64().unwrap()); + let before = node_path(&s, flat); + assert!(s.execute("object.setLiveShape", &json!({"id": flat.0, "ratio": 0.5})).is_err()); + assert_eq!(node_path(&s, flat), before); +} + +/// A ratio that changes how many anchors a rounded star draws can't come with a radius: the +/// corners selected before it would no longer name the same corners. A ratio alone still drops +/// the stale anchor selection. +#[test] +fn a_ratio_that_relays_a_rounded_star_is_not_set_with_a_radius() { + let (mut s, _) = session(); + // At this ratio the inner points lie on the lines between the outer ones. + let flat = 36f64.to_radians().cos(); + let id = star(&mut s); + run(&mut s, json!({"id": id.0, "radius": 4})); + let rounded = node_path(&s, id).0.anchor_count(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let before = (node_path(&s, id), selected_anchors(&s, id)); + let err = s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": flat, "radius": 6})).unwrap_err(); + assert!(err.to_string().contains("`ratio`"), "{err}"); + assert_eq!((node_path(&s, id), selected_anchors(&s, id)), before); + // The same ratio alone lays the anchors out again and drops the selection. + run(&mut s, json!({"id": id.0, "ratio": flat})); + assert_ne!(node_path(&s, id).0.anchor_count(), rounded); + assert_eq!(selected_anchors(&s, id), None); + // A ratio that keeps the anchors still goes with a radius. + let other = star(&mut s); + run(&mut s, json!({"id": other.0, "radius": 4})); + run(&mut s, json!({"id": other.0, "ratio": 0.4, "radius": 5})); + assert_eq!(style(&s, other).0, Some(5.0)); +} + /// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a /// star's neighbouring corners meet without overlapping. #[test] @@ -389,7 +474,8 @@ fn star_corners_stop_at_their_own_limit() { let id = star(&mut s); run(&mut s, json!({"radius": 1000})); let (path, live) = node_path(&s, id); - let Some(LiveShape::Path { base, .. }) = live else { panic!("live corners") }; + let Some(l @ LiveShape::Star { .. }) = live else { panic!("live corners") }; + let base = l.polygon_outline(); // Every cut ends at the middle of a side: each side's two cuts meet there. let sp = &base.subpaths[0]; for (i, a) in sp.anchors.iter().enumerate() { diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 41f9f0e7e2..3ba1adbb43 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -53,7 +53,9 @@ pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are lef pub(super) fn redrawn(n: &Node) -> bool { let rounded = |l: &vectorcraft_doc::LiveShape| match l { vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0), - vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), + vectorcraft_doc::LiveShape::Polygon { radii, .. } + | vectorcraft_doc::LiveShape::Star { radii, .. } + | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false, }; match &n.kind { diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index c7157df94d..9ecba0c7ca 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -275,6 +275,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } + // Older apps don't know live stars: they get the outline a star draws as a plain path. + if version < VERSION { + d.live_stars_to_paths(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index afc3bea9d2..0305246868 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -19,6 +19,20 @@ fn json_of(bytes: &[u8]) -> Value { serde_json::from_slice(bytes).unwrap() } +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn gzip(bytes: &[u8]) -> Vec { let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); gz.write_all(bytes).unwrap(); @@ -274,7 +288,9 @@ fn version_1_files_load() { fn saves_down_to_older_versions() { let mut d = rich_doc(); d.color_profiles = ColorProfiles { rgb: None, cmyk: Some("Coated".into()) }; - let current = doc_json(&load(&save(&d, false)).unwrap()); + let mut current = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + without_live_stars(&mut current); for version in [1, 2] { let bytes = save_with(&d, &opts(version, false)).unwrap(); let v = json_of(&bytes); @@ -299,6 +315,47 @@ fn saves_down_to_older_versions() { assert!(matches!(save_with(&d, &opts(2, true)), Err(FormatError::CompressedTooOld(2)))); } +/// Versions before [`VERSION`] don't know live stars: a save for them writes the star's outline as +/// a plain path, which those versions read; the current version keeps the star live. +#[test] +fn older_versions_get_a_live_star_as_its_path() { + let mut d = Document::new(100.0, 100.0); + let star = vectorcraft_doc::LiveShape::Star { + r1: 40.0, + r2: 20.0, + points: 5, + xf: Affine::translate((50.0, 50.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + let id = d.alloc_id(); + let mut node = Node::path(id, star.to_path(), Default::default()); + if let NodeKind::Path { live, .. } = &mut node.kind { + *live = Some(Box::new(star.clone())); + } + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, node).unwrap(); + for version in 1..VERSION { + let bytes = save_with(&d, &opts(version, false)).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(!text.contains("\"star\""), "v{version} writes no live star"); + let back = load(&bytes).unwrap(); + let mut anchors = None; + back.walk(|n| { + if let NodeKind::Path { path, live, .. } = &n.kind { + assert!(live.is_none(), "v{version}"); + anchors = Some(path.anchor_count()); + } + }); + assert_eq!(anchors, Some(10), "v{version} keeps the star's outline"); + } + let back = load(&save(&d, false)).unwrap(); + let mut live = None; + back.walk(|n| live = live.clone().or(n.live_shape().cloned())); + assert_eq!(live, Some(star)); +} + #[test] fn preview_is_embedded_and_read_back() { let d = Document::new(10.0, 10.0); diff --git a/crates/format/tests/prop_format.rs b/crates/format/tests/prop_format.rs index faecc37a8c..26d91ccf97 100644 --- a/crates/format/tests/prop_format.rs +++ b/crates/format/tests/prop_format.rs @@ -11,6 +11,20 @@ use vectorcraft_testkit::fixtures; use vectorcraft_testkit::invariants::{check_document, check_native_roundtrip, check_native_roundtrip_exact, doc_json, json_approx_eq}; use vectorcraft_testkit::strategies::arb_ops; +/// `v` (a document's JSON) with every live star's `live` taken off its path. +fn without_live_stars(v: &mut Value) { + match v { + Value::Object(o) => { + if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") { + o.remove("live"); + } + o.values_mut().for_each(without_live_stars); + } + Value::Array(a) => a.iter_mut().for_each(without_live_stars), + _ => {} + } +} + fn rich_doc() -> Document { (*fixtures::rich_session().doc().unwrap().doc).clone() } @@ -117,9 +131,13 @@ proptest! { } let d = s.doc().unwrap().doc.clone(); let want = doc_json(&load(&save(&d, false)).unwrap()); + // Older versions get live stars as plain paths. + let mut older = want.clone(); + without_live_stars(&mut older); for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] { let back = load(&save_with(&d, &o).unwrap()).unwrap(); - prop_assert!(json_approx_eq(&doc_json(&back), &want, 1e-12), "{:?} differs", o); + let want = if o.version < vectorcraft_format::VERSION { &older } else { &want }; + prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o); } } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 3a3cc606c5..8550807893 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -455,9 +455,9 @@ pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg: contour_with_rounding(&pts, rounded) } -/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up. +/// Star with `points` tips (2–1000), outer radius `r1`, inner radius `r2`, first tip up. pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData { - let n = points.max(2) * 2; + let n = points.clamp(2, 1000) * 2; let rot = rotation_deg.to_radians(); let pts: Vec = (0..n) .map(|i| { @@ -1485,6 +1485,12 @@ mod tests { assert!((d[0] - 10.0).abs() < 1e-9 && (d[1] - 5.0).abs() < 1e-9); } + #[test] + fn star_keeps_to_a_thousand_points() { + assert_eq!(star(Point::ZERO, 10.0, 5.0, 5000, 0.0).anchor_count(), 2000); + assert_eq!(star(Point::ZERO, 10.0, 5.0, 1, 0.0).anchor_count(), 4); + } + #[test] fn straight_star_five_points() { let r2 = straight_star_inner_radius(100.0, 5); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index d37715f9b9..fca1b86de3 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -805,7 +805,12 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { (sweep < 1e-6 || (sweep - 360.0).abs() < 1e-6).then_some(Corners::Ellipse) } Some( - LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Line { .. } | LiveShape::Path { .. }, + LiveShape::Rectangle { .. } + | LiveShape::Ellipse { .. } + | LiveShape::Polygon { .. } + | LiveShape::Star { .. } + | LiveShape::Line { .. } + | LiveShape::Path { .. }, ) => None, None => is_upright_rectangle(path).then_some(Corners::Square), } diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index e4f4b272c5..0fbc4c5522 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -24,8 +24,9 @@ pub const ID: &str = "box3d"; /// The `vc-` prefix marks it as internal so SVG export omits it from `data-*` attributes. pub const KEY: &str = "vc-shape-tools"; -/// Maximum stored JSON length read back from a file. -const MAX_STORED: usize = 4096; +/// Maximum stored JSON length read back from a file: room for a 1000-point star's 2000 corner +/// radii and kinds. +const MAX_STORED: usize = 128 * 1024; fn whole_mode() -> EllipseMode { EllipseMode::Whole @@ -35,6 +36,11 @@ fn default_pie() -> (f64, f64) { (0.0, 360.0) } +/// A polygon's sides or a star's points read from a file, clamped as the tools clamp them. +fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(2, 1000)) +} + /// Parse an [`EllipseMode`] from a command or tool option string (`"slice"`/`"pie"`, `"arc"`/`"open"`, /// `"chord"`, `"whole"`/`"full"`/`"closed"`). pub fn parse_arc_mode(s: &str) -> Option { @@ -86,6 +92,9 @@ pub enum CustomShape { }, Polygon { radius: f64, + /// Sides, or a star's points: 2–1000, as the Polygon and Star tools give them; a file's + /// count is clamped when read. + #[serde(deserialize_with = "de_sides")] sides: u32, xf: Affine, #[serde(default)] @@ -144,7 +153,8 @@ impl CustomShape { CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode } => { let raw = match spoke_ratio { Some(ratio) => { - let r2 = (*radius * ratio.clamp(0.01, 1.0)).max(0.01); + // Any ratio a live star takes (0 to 1) draws as it is. + let r2 = *radius * if ratio.is_finite() { ratio.clamp(0.0, 1.0) } else { 0.01 }; shapes::star_configured(Point::ZERO, *radius, r2, *sides, 0.0, *rounded, *randomized) } None => shapes::polygon_configured(Point::ZERO, *radius, *sides, 0.0, *rounded, *randomized), @@ -184,7 +194,20 @@ impl CustomShape { { Some(LiveShape::Polygon { radius: *radius, - sides: *sides, + sides: (*sides).clamp(3, 1000), + xf: *xf, + radii: radii.clone(), + kinds: kinds.clone(), + radii_relative: *radii_relative, + }) + } + CustomShape::Polygon { + radius, sides, xf, radii, kinds, radii_relative, spoke_ratio: Some(ratio), rounded, randomized, arc_mode, .. + } if (0.0..=1.0).contains(ratio) && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole => { + Some(LiveShape::Star { + r1: *radius, + r2: *radius * ratio, + points: (*sides).clamp(2, 1000), xf: *xf, radii: radii.clone(), kinds: kinds.clone(), @@ -197,7 +220,13 @@ impl CustomShape { /// Whether this shape uses extended add-on parameters beyond what `LiveShape` stores on its own. pub fn needs_extra_storage(&self) -> bool { - self.to_live_shape().is_none() + // A whole shape's `LiveShape` keeps no angles, so angles set for a later arc mode are + // stored with it. + let angles = match self { + CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. } => *pie != (0.0, 360.0), + _ => false, + }; + self.to_live_shape().is_none() || angles } /// Write this shape's regenerated path, `LiveShape` (if standard) and `vc-shape-tools` attribute @@ -279,9 +308,14 @@ impl CustomShape { LiveShape::Ellipse { w, h, pie, xf } => { let span = (pie.1 - pie.0).rem_euclid(360.0); let default_mode = if span < 1e-9 || 360.0 - span < 1e-9 { EllipseMode::Whole } else { EllipseMode::Slice }; - let arc_mode = match stored { - Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => arc_mode, - _ => default_mode, + let (pie, arc_mode) = match stored { + // A whole ellipse's `LiveShape` draws the full turn; its stored angles wait + // for another arc mode. + Some(CustomShape::Ellipse { arc_mode: EllipseMode::Whole, pie: angles, .. }) if default_mode != EllipseMode::Slice => { + (angles, EllipseMode::Whole) + } + Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => (pie, arc_mode), + _ => (pie, default_mode), }; Some(CustomShape::Ellipse { w, h, pie, arc_mode, xf }) } @@ -294,6 +328,26 @@ impl CustomShape { }; Some(CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode }) } + LiveShape::Star { r1, r2, points, xf, radii, kinds, radii_relative } => { + let (rounded, randomized, pie, arc_mode) = match stored { + Some(CustomShape::Polygon { rounded, randomized, pie, arc_mode, .. }) => (rounded, randomized, pie, arc_mode), + _ => (0.0, 0.0, (0.0, 360.0), EllipseMode::Whole), + }; + let spoke_ratio = Some(if r1 > 0.0 { r2 / r1 } else { 0.0 }); + Some(CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii, + kinds, + radii_relative, + spoke_ratio, + rounded, + randomized, + pie, + arc_mode, + }) + } LiveShape::Line { .. } | LiveShape::Path { .. } => stored, } } @@ -759,3 +813,100 @@ impl Tool for Box3dTool { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn read_back(spoke_ratio: Option, sides: u64) -> CustomShape { + let shape = CustomShape::Polygon { + radius: 10.0, + sides: 5, + xf: Affine::IDENTITY, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio, + rounded: 0.0, + randomized: 0.0, + pie: (0.0, 360.0), + arc_mode: EllipseMode::Whole, + }; + let mut v = serde_json::to_value(&shape).unwrap_or_default(); + v["sides"] = json!(sides); + serde_json::from_value(v).unwrap_or_else(|e| panic!("{e}")) + } + + #[test] + fn a_file_point_count_is_clamped_as_the_tools_clamp_it() { + let star = read_back(Some(0.5), u64::from(u32::MAX)); + let CustomShape::Polygon { sides, .. } = &star else { panic!("a polygon") }; + assert_eq!(*sides, 1000); + let CustomShape::Polygon { sides, .. } = read_back(None, 0) else { panic!("a polygon") }; + assert_eq!(sides, 2); + let Some(LiveShape::Star { points, .. }) = star.to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 1000); + assert_eq!(star.to_path().anchor_count(), 2000); + let polygon = read_back(None, u64::from(u32::MAX)); + let Some(LiveShape::Polygon { sides, .. }) = polygon.to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 1000); + let Some(LiveShape::Polygon { sides, .. }) = read_back(None, 0).to_live_shape() else { panic!("a live polygon") }; + assert_eq!(sides, 3); + let Some(LiveShape::Star { points, .. }) = read_back(Some(0.5), 0).to_live_shape() else { panic!("a live star") }; + assert_eq!(points, 2); + } + + /// A whole star draws every point whatever its pie angles hold, so it stays live. + #[test] + fn a_whole_star_with_other_pie_angles_is_live() { + let mut star = read_back(Some(0.5), 5); + let CustomShape::Polygon { pie, .. } = &mut star else { panic!("a polygon") }; + *pie = (0.0, 90.0); + assert!(matches!(star.to_live_shape(), Some(LiveShape::Star { points: 5, .. })), "{star:?}"); + } + + /// A 1000-point star with a radius on each of its 2000 corners, written and read back. + fn round_trip(arc_mode: EllipseMode) -> CustomShape { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radii, kinds, pie, arc_mode: mode, .. } = &mut star else { panic!("a polygon") }; + *radii = vec![12.0; 2000]; + *kinds = vec![CornerKind::Round; 2000]; + *pie = (0.0, 90.0); + *mode = arc_mode; + let mut node = Node::path(vectorcraft_doc::NodeId(1), PathData::default(), vectorcraft_doc::Appearance::default_art()); + star.write_to_node(&mut node); + CustomShape::read(&node).unwrap_or_else(|| panic!("a shape")) + } + + /// A live star's stored entry holds a long corner list, and its pie angles still read back. + #[test] + fn a_live_star_with_many_corners_keeps_its_pie_angles() { + let back = round_trip(EllipseMode::Whole); + let CustomShape::Polygon { pie, radii, kinds, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(radii.len(), 2000); + assert_eq!(kinds.len(), 2000); + } + + /// A sliced star has no `LiveShape`, so its stored entry holds every corner and still reads back. + #[test] + fn a_sliced_star_with_many_corners_reads_back() { + let back = round_trip(EllipseMode::Slice); + let CustomShape::Polygon { pie, radii, arc_mode, .. } = &back else { panic!("a polygon") }; + assert_eq!(*pie, (0.0, 90.0)); + assert_eq!(*arc_mode, EllipseMode::Slice); + assert_eq!(radii.len(), 2000); + } + + /// The longest corner values a 1000-point star can hold still fit in the stored entry. + #[test] + fn the_longest_star_entry_fits_the_read_limit() { + let mut star = read_back(Some(0.5), 1000); + let CustomShape::Polygon { radius, radii, kinds, .. } = &mut star else { panic!("a polygon") }; + *radius = -f64::MAX; + *radii = vec![-1.2345678901234567e-300; 2000]; + *kinds = vec![CornerKind::InvertedRound; 2000]; + let len = serde_json::to_string(&star).map(|s| s.len()).unwrap_or(usize::MAX); + assert!(len <= MAX_STORED, "{len}"); + } +} diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs index 361430dcf5..82668516c7 100644 --- a/crates/tools/src/sidewidget.rs +++ b/crates/tools/src/sidewidget.rs @@ -6,6 +6,10 @@ //! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began. //! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it //! from the same geometry. +//! +//! A live star shows the same widget +//! (): +//! its drag sends `points`, from 3 to 20, with the same rule for a count past either end. use serde_json::json; use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection}; @@ -27,35 +31,45 @@ pub const STEP_PX: f64 = 12.0; pub const MIN_SIDES: u32 = 3; /// The most sides a drag gives. pub const MAX_SIDES: u32 = 11; +/// The fewest points a drag gives a star. +pub const MIN_POINTS: u32 = 3; +/// The most points a drag gives a star. +pub const MAX_POINTS: u32 = 20; -/// The side widget of a selection that is exactly one editable live polygon. +/// The side widget of a selection that is exactly one editable live polygon or star. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SideWidget { pub id: NodeId, /// Center in document coordinates. pub at: Point, - /// The polygon's side count. + /// The polygon's side count, or the star's point count. pub sides: u32, + /// The shape is a star: the drag sets its points (3 to 20) instead of a polygon's sides. + pub star: bool, } impl SideWidget { /// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document - /// point). None unless the selection is one whole editable live polygon, with no anchors or - /// segments of it selected. + /// point). None unless the selection is one whole editable live polygon or star, with no + /// anchors or segments of it selected. pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { let [id] = selection.objects[..] else { return None }; if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !zoom.is_finite() || zoom <= 0.0 { return None; } let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; - let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + let (sides, star) = match live.as_deref() { + Some(LiveShape::Polygon { sides, .. }) => (*sides, false), + Some(LiveShape::Star { points, .. }) => (*points, true), + _ => return None, + }; // After the kind: on a locked artboard it measures the art of the layer object holding `id`. if !doc.is_editable(id) { return None; } let r = bx.rect; let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); - (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) + (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides, star }) } /// The widget the tool can drag (its bounding box and the shape widgets showing). @@ -82,15 +96,35 @@ pub fn over_widget(cx: &ToolContext, p: Point) -> bool { /// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11, /// and `from` itself while a polygon of more than 11 sides has not been dragged up. pub fn sides_after(from: u32, steps: i64) -> u32 { - let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES)); - let to = if from <= MAX_SIDES { - i64::from(from).saturating_add(steps) - } else if steps >= 0 { - return from; + count_after(from, steps, MIN_SIDES, MAX_SIDES) +} + +/// The point count a drag of `steps` (down positive) gives a star of `from` points: within 3 to 20, +/// and `from` itself while a star of more than 20 points has not been dragged up, or a star of +/// fewer than 3 has not been dragged down. +pub fn points_after(from: u32, steps: i64) -> u32 { + count_after(from, steps, MIN_POINTS, MAX_POINTS) +} + +/// A count a drag of `steps` gives from `from`, within `min` to `max`. A count past `max` stays +/// until the drag goes up a step, which gives `max`; one below `min` stays until it goes down a +/// step, which gives `min`. +fn count_after(from: u32, steps: i64, min: u32, max: u32) -> u32 { + let (lo, hi) = (i64::from(min), i64::from(max)); + let to = if from > max { + if steps >= 0 { + return from; + } + (hi + 1).saturating_add(steps) + } else if from < min { + if steps <= 0 { + return from; + } + (lo - 1).saturating_add(steps) } else { - (max + 1).saturating_add(steps) + i64::from(from).saturating_add(steps) }; - to.clamp(min, max) as u32 + to.clamp(lo, hi) as u32 } /// Dragging the side widget. @@ -139,7 +173,7 @@ impl SideDrag { return vec![]; } // The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN. - let sides = sides_after(self.widget.sides, steps as i64); + let sides = if self.widget.star { points_after(self.widget.sides, steps as i64) } else { sides_after(self.widget.sides, steps as i64) }; if sides == self.sides { return vec![]; } @@ -149,7 +183,8 @@ impl SideDrag { out.push(Action::Begin("Live Shape".into())); } self.sides = sides; - out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides }))); + let key = if self.widget.star { "points" } else { "sides" }; + out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, key: sides }))); out } @@ -172,7 +207,8 @@ impl SideDrag { if !self.moved || !cx.measurement_labels { return vec![]; } - vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }] + let label = if self.widget.star { "Points" } else { "Sides" }; + vec![Overlay::Measure { p: self.at, text: format!("{label}: {}", self.sides) }] } } @@ -188,7 +224,17 @@ mod tests { /// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a /// selection of it. fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) { - let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + shape_doc(LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding a live star of `points` points, radii 100 and 50, placed by `xf`, and a + /// selection of it. + fn star_doc(points: u32, xf: Affine) -> (Document, NodeId, Selection) { + shape_doc(LiveShape::Star { r1: 100.0, r2: 50.0, points, xf, radii: vec![], kinds: vec![], radii_relative: false }) + } + + /// A document holding the live shape `live`, and a selection of it. + fn shape_doc(live: LiveShape) -> (Document, NodeId, Selection) { let mut d = Document::new(800.0, 800.0); let l = d.layers[0].id; let id = d.alloc_id(); @@ -226,6 +272,42 @@ mod tests { assert_eq!(sides_after(1000, -100), 3); } + #[test] + fn a_star_s_counts_stay_within_three_and_twenty() { + assert_eq!(points_after(5, 1), 6); + assert_eq!(points_after(5, 100), 20); + assert_eq!(points_after(5, -100), 3); + assert_eq!(points_after(20, i64::MAX), 20); + // Over 20: unchanged until the drag goes up, which gives 20. + assert_eq!(points_after(40, 3), 40); + assert_eq!(points_after(40, -1), 20); + // Under 3 (a two-point star): unchanged until the drag goes down, which gives 3. + assert_eq!(points_after(2, 0), 2); + assert_eq!(points_after(2, -4), 2); + assert_eq!(points_after(2, 1), 3); + assert_eq!(points_after(2, 2), 4); + assert_eq!(points_after(2, i64::MIN), 2); + } + + /// A live star shows the widget, and dragging it down a step gives the star a point, in one + /// undo step, with the count beside the pointer. + #[test] + fn dragging_a_star_s_widget_down_adds_a_point() { + let (d, id, s) = star_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).expect("a widget on a live star"); + assert_eq!((w.id, w.sides, w.star), (id, 5, true)); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let to = w.at + vectorcraft_geom::Vec2::new(0.0, STEP_PX + 1.0); + let out = t.pointer(&c, &ev(PointerKind::Drag, to)); + assert_eq!(out[0], Action::Begin("Live Shape".into())); + assert!(matches!(&out[1], Action::Preview(cmd, v) if cmd == "object.setLiveShape" && *v == json!({ "id": id.0, "points": 6 })), "{out:?}"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Points: 6"))); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, to)), vec![Action::Commit]); + } + #[test] fn the_longest_drags_stay_within_three_and_eleven() { assert_eq!(sides_after(5, i64::MAX), 11); diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 29b5962d3e..f3a6bc366a 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -311,7 +311,7 @@ mod tests { set(&app, "radius", json!(5)); confirm(&mut app); let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); - assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); + assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(&**l, LiveShape::Star { radii, .. } if !radii.is_empty()))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } diff --git a/crates/ui-egui/src/panels/tests_css_properties.rs b/crates/ui-egui/src/panels/tests_css_properties.rs index af606593c0..3c4e17cfba 100644 --- a/crates/ui-egui/src/panels/tests_css_properties.rs +++ b/crates/ui-egui/src/panels/tests_css_properties.rs @@ -75,13 +75,13 @@ fn copy_and_export_go_through_the_ui_commands() { app.run("shape.star", json!({"cx": 100, "cy": 50, "radius1": 30, "radius2": 15})).unwrap(); let r = app.run("css.exportFile", json!({"path": "/tmp/site/site.css", "scope": "all", "rasterize": true})).unwrap(); assert_eq!(r["rules"], json!(2)); - let png = std::path::Path::new("/tmp/site").join("path.png").to_string_lossy().into_owned(); + let png = std::path::Path::new("/tmp/site").join("star.png").to_string_lossy().into_owned(); assert_eq!(r["images"], json!([png])); let log = log.borrow(); let names: Vec<&str> = log.iter().map(|(p, _)| p.as_str()).collect(); assert_eq!(names, ["/tmp/site/site.css", png.as_str()]); let css = String::from_utf8(log[0].1.clone()).unwrap(); - assert!(css.contains(".rectangle {") && css.contains("background-image: url(path.png);"), "{css}"); + assert!(css.contains(".rectangle {") && css.contains("background-image: url(star.png);"), "{css}"); assert!(log[1].1.starts_with(b"\x89PNG")); } diff --git a/crates/ui-egui/src/panels/transform/shape.rs b/crates/ui-egui/src/panels/transform/shape.rs index 8530a90390..d493cdee9c 100644 --- a/crates/ui-egui/src/panels/transform/shape.rs +++ b/crates/ui-egui/src/panels/transform/shape.rs @@ -1,5 +1,5 @@ -//! The Transform panel's live-shape rows: the Rectangle, Polygon, Ellipse and Line Properties, also shown by the -//! Properties panel and the Contextual Task Bar. +//! The Transform panel's live-shape rows: the Rectangle, Polygon, Star, Ellipse and Line Properties, also shown by +//! the Properties panel and the Contextual Task Bar. use std::ops::RangeInclusive; @@ -28,6 +28,8 @@ enum Quantity { Degrees, /// A length in the document's general unit. Length, + /// A fraction from 0.001 to 1, three decimals. + Ratio, } /// The side counts Polygon Properties' Sides slider spans; the field beside it takes 3 to 1000. @@ -44,6 +46,7 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l corner_radius_row(app, ui, n); }), LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| polygon_rows(app, ui, n, live)), + LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| star_rows(app, ui, live)), LiveShape::Ellipse { pie, .. } => under_heading(ui, Some(tl!("Ellipse Properties:")), |ui| { angle_row(app, ui, live, "ellipseAngle"); pie_rows(app, ui, *pie); @@ -79,6 +82,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: let field = match quantity { Quantity::Length => NumberField::length(label, bind, general_lengths(app)), Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1), + Quantity::Ratio => NumberField::new(label, bind).range(0.001..=1.0).step(0.001).commit_decimals(3), }; edit = Some(field.show(ui).edit); }); @@ -197,12 +201,17 @@ fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShap /// one undo step; Escape during the drag puts the count back. A click on the rail or an arrow key sets the count in /// one undo step. A count above 20 puts the thumb at the rail's right end, and screen readers read the real count. fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { - let label = tl!("Sides"); + count_row(app, ui, tl!("Sides"), "sides", sides, 3.0); +} + +/// A count row (Polygon Properties' Sides, Star Properties' Points) whose edits set `key`: a field that takes `min` +/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. +fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64) { let count = f64::from(sides); let (mut typed, mut slid) = (None, None); Field::new(label).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - typed = Some(NumberField::new(label, Bind::given(Some(count))).range(3.0..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit); + typed = Some(NumberField::new(label, Bind::given(Some(count))).range(min..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit); let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end()); slid = Some( Slider::new(Bind::given(count.clamp(lo, hi)), SIDES_SLIDER) @@ -218,17 +227,26 @@ fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { if let Some(edit) = typed { apply_edits(app, &edit, EditPath::Scope, |app, v, _| { if let Some(v) = v { - set_live_shape(app, json!({ "sides": *v as u64 })); + set_live_shape(app, json!({ key: *v as u64 })); } }); } if let Some(edit) = slid { apply_edits(app, &edit, EditPath::Preview, |app, v, phase| { - crate::panels::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ "sides": v.round() as u64 }), phase); + crate::panels::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ key: v.round() as u64 }), phase); }); } } +/// A live star's Star Properties: its point count (a field that takes 2 to 1000 and a slider over 3 to 20) and its +/// ratio (inner radius over outer radius, 0.001 to 1). Its corners stay with Live Corners and Direct Selection, as any +/// path's do. +fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) { + let Some(points) = live.star_points() else { return }; + count_row(app, ui, tl!("Points"), "points", points, 2.0); + number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, |r| json!({ "ratio": r })); +} + /// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the /// number fields of its column are. fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option) { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 8cca161107..15414aba1b 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -1133,6 +1133,35 @@ fn polygon_app(sides: u32) -> VectorcraftApp { app } +/// The selected live star's point count and ratio. +fn star_points(app: &VectorcraftApp) -> (u32, f64) { + let l = first_selected(app).unwrap().live_shape().cloned(); + match l { + Some(l @ LiveShape::Star { points, .. }) => (points, l.star_ratio().unwrap()), + k => panic!("{k:?}"), + } +} + +/// Star Properties' Points field sets a live star's point count past the slider's 20, and its Ratio field sets the +/// inner radius against the outer one, each in one undo step. +#[test] +fn star_points_and_ratio_fields_edit_a_live_star() { + use craft::ui::contract::Role; + let mut app = new_app(); + app.run("shape.star", json!({"cx": 150, "cy": 150, "radius1": 50, "radius2": 25, "points": 5})).unwrap(); + let mut p = Panel::new(app, show); + assert_eq!(p.value_role("Points", Role::SLIDER).as_deref(), Some("5")); + let depth = undo_depth(&p.app()); + p.type_into("Points", "12"); + assert_eq!(star_points(&p.app()).0, 12); + assert_eq!(undo_depth(&p.app()), depth + 1); + p.type_into("Ratio", "0.3"); + let (points, ratio) = star_points(&p.app()); + assert_eq!(points, 12); + assert!((ratio - 0.3).abs() < 1e-9, "{ratio}"); + assert_eq!(undo_depth(&p.app()), depth + 2); +} + fn undo_depth(app: &VectorcraftApp) -> usize { app.session.doc().unwrap().history.undo.len() } diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index da78e247f2..f98a9bdd96 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -546,7 +546,7 @@ fn selection_kinds_offer_their_actions() { let s = id(app.run("shape.star", json!({"cx": 300, "cy": 150, "radius1": 40})).unwrap()); select(app, &[s]); app.run("object.setLiveShape", json!({"radius": 4})).unwrap(); - assert!(matches!(live(app, s), vectorcraft_doc::LiveShape::Path { .. })); + assert!(matches!(live(app, s), vectorcraft_doc::LiveShape::Star { radii, .. } if !radii.is_empty())); }, &["lock"], &["shapeProperties"], diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 06d6651315..6bea16b5e5 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -259,10 +259,13 @@ fn polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs() { app.select_tool(tool); } let view = app.view_info(); + // Each round starts clear of the last shape, whose center point and side widget (a live + // star's too) take a press. + let (dx, dy) = [(0.0, 0.0), (150.0, 150.0), (0.0, 180.0)][round]; for (kind, x, y) in [ - (vectorcraft_tools::PointerKind::Down, 50.0, 50.0), - (vectorcraft_tools::PointerKind::Drag, 90.0, 90.0), - (vectorcraft_tools::PointerKind::Up, 90.0, 90.0), + (vectorcraft_tools::PointerKind::Down, 50.0 + dx, 50.0 + dy), + (vectorcraft_tools::PointerKind::Drag, 90.0 + dx, 90.0 + dy), + (vectorcraft_tools::PointerKind::Up, 90.0 + dx, 90.0 + dy), ] { app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, x, y), view).unwrap(); } diff --git a/docs/mcp.md b/docs/mcp.md index f7c53f97a1..8b91d156aa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -867,7 +867,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | -| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | +| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | @@ -10347,7 +10347,11 @@ The same command sets the rest of a live shape's properties, as the Properties a polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counterclockwise, its first vertex straight up at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or -length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees +length that isn't a number above 0 is an error. A star drawn with the Star tool or `shape.star` stays live (Star +Properties): `points` (a whole number from 2 to 1000; its corners keep the radius and kind they shared) and `ratio` +(its inner radius over its outer radius, above 0 and up to 1; the outer radius stays); any other count or ratio is an error, and a +count or ratio the star already has adds no undo step. A change to the point count, or a ratio that changes which corners a rounded star cuts, drops the star's selected anchors and segments; +`points` with `radius` or `kind` in one call is an error, as is such a `ratio` with `radius` or `kind`, and so is a `ratio` for a star whose outer radius is 0. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. `constrainPie: true` with one of `pieStart` and `pieEnd` (the panels' Constrain Pie Angle link) moves the other angle by as much, so each selected ellipse keeps its own span, counterclockwise from its start to its end; a whole ellipse diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 25d2e39d61..c101ee192d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1662,6 +1662,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). + - **Live stars:** a star drawn with the Star tool or `shape.star` stays a live shape (#4339), so its point count and ratio stay editable after it is drawn, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-stars.html) describes. A selected live star shows the side widget; its drag sets the point count from 3 to 20, and a star of more than 20 points keeps its count until the drag goes up. Star Properties in the Transform panel and the Properties panel's Transform section have a Points field (2 to 1000) with a slider over 3 to 20, and a Ratio field (inner radius over outer radius, 0.001 to 1). The command accepts a ratio above 0 and up to 1. Both send `object.setLiveShape {points, ratio}`, one undo step each, and a value the star already has adds none. Live Corners round a live star's corners and keep them through a new point count. The help page covers the widget and the editable point count; the widget's drag range of 3 to 20, the Points field's range of 2 to 1000 and the Ratio field are VectorCraft's own (tests `a_live_star_takes_a_new_point_count_and_ratio`, `dragging_a_star_s_widget_down_adds_a_point`, `star_points_and_ratio_fields_edit_a_live_star`). - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}` and its release adds one undo step; Escape during the drag puts the count back and adds no undo step. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html).