M4, #1680: notched (inside square) corners, and .sketch corner styles stay live

This commit is contained in:
bflatastic
2026-12-02 07:50:39 +07:00
parent 5975fa0ded
commit 449fa747b3
15 changed files with 72 additions and 112 deletions
+2 -2
View File
@@ -18,7 +18,7 @@ pub const STROKE_SIDES: [&str; 4] = ["strokeTopWeight", "strokeRightWeight", "st
/// Keys `node.set` understands (documented for agents).
pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page: the layer's angle plus its parents', what the Design panel's field shows; one of the two per call), \
fills (paints or colours; gradients as {type: linearGradient|radialGradient|angularGradient|diamondGradient, stops: [\"#hex\", ...], from?, to?} too), fill (colour, {$var: variable id or name}, or \"none\"/null: no fill), strokes, stroke (colour, {$var: variable id or name}, or \"none\"/null: no stroke), strokeWeight, strokeAlign (inside|center|outside), strokeSides [t,r,b,l], strokeTopWeight / strokeRightWeight / strokeBottomWeight / strokeLeftWeight (one side; turns on individual strokes), \
strokeCap / startCap / endCap, strokeJoin, miterAngle (degrees: sharper joins bevel; or miterLimit as a ratio), dashes [..], dashCap (none|round|square; null: dashes take startCap and endCap), widthProfile (preset uniform|wedge|taper|eye|rounded|pinch, [[t, scale], ...] or null), brush (preset id, {preset, spacing, sizeJitter, rotationJitter, scatter, seed} or null), cornerRadius (n or [tl,tr,br,bl]), cornerStyle (round|chamfer|concave), cornerSmoothing (0-1), effects, \
strokeCap / startCap / endCap, strokeJoin, miterAngle (degrees: sharper joins bevel; or miterLimit as a ratio), dashes [..], dashCap (none|round|square; null: dashes take startCap and endCap), widthProfile (preset uniform|wedge|taper|eye|rounded|pinch, [[t, scale], ...] or null), brush (preset id, {preset, spacing, sizeJitter, rotationJitter, scatter, seed} or null), cornerRadius (n or [tl,tr,br,bl]), cornerStyle (round|chamfer|concave|notch), cornerSmoothing (0-1), effects, \
clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, padding (n or [t,r,b,l]), paddingTop/Right/Bottom/Left, \
mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \
columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \
@@ -733,7 +733,7 @@ fn apply_corners(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value)
if !n.kind.has_independent_corners() {
return Err(bad(cmd, "cornerStyle requires a rectangular layer"));
}
n.corners.style = serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "cornerStyle: round|chamfer|concave"))?;
n.corners.style = serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "cornerStyle: round|chamfer|concave|notch"))?;
}
"cornerSmoothing" => {
doc.get_mut(id)?.corners.smoothing = f64_of(v).ok_or_else(|| bad(cmd, "`cornerSmoothing` must be a number"))?.clamp(0.0, 1.0)
+6 -2
View File
@@ -744,7 +744,10 @@ impl<'a> Ctx<'a> {
props::stroke_props(j, &mut n.stroke);
n.effects = props::effects(self, j);
if n.kind.has_corner_radius() {
props::corners(j, &mut n.corners.radii, &mut n.corners.smoothing);
props::corners(j, &mut n.corners);
if !n.kind.has_independent_corners() {
n.corners.style = Default::default();
}
}
if let Some(c) = props::constraints(j) {
n.constraints = c;
@@ -1611,7 +1614,8 @@ fn override_group(field: &str) -> Option<&'static str> {
| "topRightRadius"
| "bottomLeftRadius"
| "bottomRightRadius"
| "cornerSmoothing" => "corners",
| "cornerSmoothing"
| "cornerStyle" => "corners",
"characters" => "characters",
"fontName"
| "fontFamily"
+10 -6
View File
@@ -410,18 +410,22 @@ pub(super) fn stroke_props(v: &Value, sp: &mut StrokeProps) {
}
}
/// `[tl, tr, br, bl]` radii and smoothing, when the node sets them.
pub(super) fn corners(v: &Value, radii: &mut [f64; 4], smoothing: &mut f64) {
/// `[tl, tr, br, bl]` radii, smoothing and (FigCraft's own `cornerStyle`, which `.sketch` import
/// writes) the corner style, when the node sets them.
pub(super) fn corners(v: &Value, c: &mut figcraft_doc::Corners) {
if let Some(r) = len(v, "cornerRadius") {
*radii = [r; 4];
c.radii = [r; 4];
}
let each: Vec<f64> =
list(v, "rectangleCornerRadii").iter().filter_map(Value::as_f64).filter(|r| r.is_finite()).map(|r| r.clamp(0.0, MAX_SIZE)).collect();
if let [a, b, c, d] = each.as_slice() {
*radii = [*a, *b, *c, *d];
if let [a, b, c_, d] = each.as_slice() {
c.radii = [*a, *b, *c_, *d];
}
if let Some(s) = num(v, "cornerSmoothing") {
*smoothing = s.clamp(0.0, 1.0);
c.smoothing = s.clamp(0.0, 1.0);
}
if let Some(style) = v.get("cornerStyle").and_then(|s| serde_json::from_value(s.clone()).ok()) {
c.style = style;
}
}
+14 -17
View File
@@ -366,28 +366,25 @@ fn glass_and_progressive_blurs() {
assert_eq!((b.start_radius, b.radius), (48.0, 0.0));
}
/// Angled (2), inside-square (3) and inside-arc (4) corners make the rectangle a path of that outline.
/// Angled (2), inside-square (3) and inside-arc (4) corners stay a rectangle with that corner
/// style and its radii, so the corners can still be edited.
#[test]
fn cut_corners_become_paths() {
fn cut_corners_stay_live() {
use figcraft_doc::geom::CornerStyle;
let cut = |name: &str, style: i64| {
let mut r = rect(name, 0.0, 0.0, 100.0, 80.0);
r["style"]["corners"] = json!({"_class": "MSImmutableStyleCorners", "radii": [10], "style": style, "smoothing": 0.6});
r["style"]["corners"] = json!({"_class": "MSImmutableStyleCorners", "radii": [10, 4], "style": style, "smoothing": 0.6});
r
};
let (doc, _) = open(vec![cut("Angled", 2), cut("Square", 3), cut("Arc", 4)]);
let net = |n: &str| match &node(&doc, n).kind {
NodeKind::Vector { network } => network.clone(),
other => panic!("{n}: {other:?}"),
};
let a = net("Angled");
assert_eq!(a.vertices.len(), 8);
assert!(a.vertices.iter().any(|v| (v.x, v.y) == (0.0, 10.0)) && a.vertices.iter().any(|v| (v.x, v.y) == (10.0, 0.0)));
let s = net("Square");
assert_eq!(s.vertices.len(), 12);
assert!(s.vertices.iter().any(|v| (v.x, v.y) == (10.0, 10.0)) && s.vertices.iter().any(|v| (v.x, v.y) == (90.0, 70.0)));
let arc = net("Arc");
assert_eq!(arc.vertices.len(), 8);
assert!(arc.segments.iter().any(|g| g.ta != (0.0, 0.0)), "the corners are arcs");
let (doc, _) = open(vec![cut("Angled", 2), cut("Square", 3), cut("Arc", 4), cut("Smooth", 1)]);
for (name, style) in
[("Angled", CornerStyle::Chamfer), ("Square", CornerStyle::Notch), ("Arc", CornerStyle::Concave), ("Smooth", CornerStyle::Round)]
{
let n = node(&doc, name);
assert!(matches!(n.kind, NodeKind::Rectangle), "{name}: {:?}", n.kind);
assert_eq!((n.corners.style, n.corners.radii), (style, [10.0, 4.0, 10.0, 4.0]), "{name}");
}
assert!(node(&doc, "Smooth").corners.smoothing > 0.0 && node(&doc, "Angled").corners.smoothing == 0.0);
}
/// Tints and colour overrides that aren't colours, and fills that aren't objects, are junk: left
-59
View File
@@ -100,65 +100,6 @@ pub(crate) fn network(cx: &mut Cx, l: &Value, w: f64, h: f64, fill_open: bool) -
Some(VectorNetwork { vertices, segments, regions })
}
/// Rectangle `l` with angled (corner style 2), inside-square (3) or inside-arc (4) corners in its
/// style (Sketch 2025 and newer) as an edited rectangle whose points draw that outline, the
/// corners' `radii` (top left, top right, bottom right, bottom left; repeating) being how far
/// each cut reaches along both edges. `None` for any other layer.
pub(crate) fn cut_corners(l: &Value) -> Option<Value> {
if l.get("_class").and_then(Value::as_str) != Some("rectangle") || l.get("edited").and_then(Value::as_bool) == Some(true) {
return None;
}
let c = l.get("style")?.get("corners")?;
let style = c.get("style").and_then(Value::as_i64).filter(|s| (2..=4).contains(s))?;
let radii: Vec<f64> = c.get("radii")?.as_array()?.iter().filter_map(Value::as_f64).filter(|r| r.is_finite()).take(4).collect();
if radii.iter().all(|r| *r <= 0.0) {
return None;
}
let (w, h) = size(l);
if w <= 0.0 || h <= 0.0 {
return None;
}
// Arc handles: a quarter circle's.
const K: f64 = 0.552_284_749_8;
let fmt = |(x, y): (f64, f64)| format!("{{{}, {}}}", x / w, y / h);
let curve = |p: (f64, f64), from: Option<(f64, f64)>, to: Option<(f64, f64)>| {
json!({"_class": "curvePoint", "cornerRadius": 0, "point": fmt(p), "curveMode": if from.or(to).is_some() { 4 } else { 1 },
"hasCurveFrom": from.is_some(), "hasCurveTo": to.is_some(), "curveFrom": fmt(from.unwrap_or(p)), "curveTo": fmt(to.unwrap_or(p))})
};
// Corners clockwise from the top left, each with the directions to the edge before and after.
let corners = [
((0.0, 0.0), (0.0, 1.0), (1.0, 0.0)),
((w, 0.0), (-1.0, 0.0), (0.0, 1.0)),
((w, h), (0.0, -1.0), (-1.0, 0.0)),
((0.0, h), (1.0, 0.0), (0.0, -1.0)),
];
let mut points = Vec::new();
for (i, ((cx, cy), (px, py), (nx, ny))) in corners.into_iter().enumerate() {
let r = radii.get(i % radii.len()).copied().unwrap_or(0.0).clamp(0.0, w.min(h) / 2.0);
if r <= 0.0 {
points.push(curve((cx, cy), None, None));
continue;
}
let a = (cx + r * px, cy + r * py);
let b = (cx + r * nx, cy + r * ny);
match style {
2 => points.extend([curve(a, None, None), curve(b, None, None)]),
3 => points.extend([curve(a, None, None), curve((cx + r * (px + nx), cy + r * (py + ny)), None, None), curve(b, None, None)]),
// A quarter circle about the corner, bulging into the shape.
_ => points
.extend([curve(a, Some((a.0 + K * r * nx, a.1 + K * r * ny)), None), curve(b, None, Some((b.0 + K * r * px, b.1 + K * r * py)))]),
}
}
let mut out = l.clone();
out["edited"] = json!(true);
out["isClosed"] = json!(true);
out["points"] = Value::Array(points);
if let Some(st) = out.get_mut("style").and_then(Value::as_object_mut) {
st.remove("corners");
}
Some(out)
}
/// A path, star, polygon or triangle layer: a star or polygon while its points are still the
/// generated ones (same as FigCraft's, within half a percent), else an editable vector.
pub(crate) fn shape(cx: &mut Cx, l: &Value, w: f64, h: f64) -> Option<Shape> {
+13 -15
View File
@@ -176,15 +176,6 @@ pub(crate) fn layer(cx: &mut Cx, l: &Value, parent: Affine, depth: usize, root:
cx.too_old = true;
return None;
}
// A rectangle with angled or inside corners is a path of that outline.
let outlined;
let l = match super::path::cut_corners(l) {
Some(p) => {
outlined = p;
&outlined
}
None => l,
};
let class = str_field(l, "_class")?;
if class == "shapeGroup" {
return count(cx).then(|| super::path::shape_group(cx, l, parent, depth, root)).flatten();
@@ -350,7 +341,8 @@ pub(crate) fn is_frame(l: &Value) -> bool {
}
/// Corners kept in the style (Sketch 2025+: one radius for all, or one per corner from the top
/// left, clockwise) on shapes and frames that have corners; smooth corners keep their smoothing.
/// left, clockwise) on shapes and frames that have corners; smooth corners keep their smoothing,
/// and angled, inside-square and inside-arc corners stay live as that corner style.
pub(crate) fn style_corners(l: &Value, node: &mut JsonMap<String, Value>) {
let Some(c) = l.get("style").and_then(|s| s.get("corners")) else { return };
if !matches!(node.get("type").and_then(Value::as_str), Some("RECTANGLE" | "FRAME" | "COMPONENT" | "INSTANCE")) {
@@ -379,11 +371,17 @@ pub(crate) fn style_corners(l: &Value, node: &mut JsonMap<String, Value>) {
node.insert("rectangleCornerRadii".into(), json!(all));
}
}
// Style 1 is smooth: its smoothing applies.
if c.get("style").and_then(Value::as_i64) == Some(1)
&& let Some(sm) = c.get("smoothing").and_then(Value::as_f64).filter(|v| v.is_finite())
{
node.insert("cornerSmoothing".into(), json!(sm.clamp(0.0, 1.0)));
match c.get("style").and_then(Value::as_i64) {
// Smooth: its smoothing applies.
Some(1) => {
if let Some(sm) = c.get("smoothing").and_then(Value::as_f64).filter(|v| v.is_finite()) {
node.insert("cornerSmoothing".into(), json!(sm.clamp(0.0, 1.0)));
}
}
Some(2) => _ = node.insert("cornerStyle".into(), json!("chamfer")),
Some(3) => _ = node.insert("cornerStyle".into(), json!("notch")),
Some(4) => _ = node.insert("cornerStyle".into(), json!("concave")),
_ => {}
}
}
+5
View File
@@ -28,6 +28,8 @@ pub enum CornerStyle {
Round,
Chamfer,
Concave,
/// A square notch: the corner cut out as a square of the radius's side.
Notch,
}
impl CornerStyle {
@@ -169,6 +171,9 @@ pub fn styled_rect(width: f64, height: f64, radii: Radii, smoothing: f64, style:
path.line_to(from);
if style == CornerStyle::Chamfer {
path.line_to(to);
} else if style == CornerStyle::Notch {
path.line_to(from + dout * r);
path.line_to(to);
} else {
// An inward quarter circle centred on the original corner.
let handle = 0.552_284_749_830_793_6 * r;
+4 -1
View File
@@ -25,12 +25,15 @@ fn corner_styles_cut_each_corner_at_its_own_radius() {
let rect = |style| styled_rect(100.0, 50.0, radii, 0.6, style);
let chamfer = rect(CornerStyle::Chamfer);
let concave = rect(CornerStyle::Concave);
let notch = rect(CornerStyle::Notch);
assert!((area(&chamfer) - (5000.0 - cut / 2.0)).abs() < 1e-6);
assert!((area(&concave) - (5000.0 - PI * cut / 4.0)).abs() < 0.2);
assert!((area(&notch) - (5000.0 - cut)).abs() < 1e-6);
assert!(!notch.contains(Point::new(19.0, 19.0)) && notch.contains(Point::new(21.0, 21.0)));
assert!(chamfer.contains(Point::new(11.0, 11.0)));
assert!(!concave.contains(Point::new(11.0, 11.0)));
assert!(concave.contains(Point::new(99.0, 49.0)));
for style in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave] {
for style in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave, CornerStyle::Notch] {
assert_eq!(styled_rect(100.0, 50.0, [0.0; 4], 0.6, style), rounded_rect(100.0, 50.0, [0.0; 4], 0.0));
assert_eq!(styled_rect(100.0, 50.0, [900.0; 4], 0.0, style), styled_rect(100.0, 50.0, [25.0; 4], 0.0, style));
}
+3 -3
View File
@@ -118,11 +118,11 @@ fn a_view_inside_clipping_frames_holds_no_layer_for_them() {
assert!(before >= u64::from(v.width) * u64::from(v.height) * 4, "as it was: {before} bytes held");
}
/// A chamfered or concave corner cuts off more than a round one of the same radius: a view
/// A chamfered, concave or notched corner cuts off more than a round one of the same radius: a view
/// between the two is outside the frame, and the frame's children don't show there.
#[test]
fn a_view_in_a_corner_a_chamfer_cuts_off_shows_nothing_of_the_frame() {
for style in [figcraft_geom::CornerStyle::Chamfer, figcraft_geom::CornerStyle::Concave] {
for style in [figcraft_geom::CornerStyle::Chamfer, figcraft_geom::CornerStyle::Concave, figcraft_geom::CornerStyle::Notch] {
let mut d = Document::new("corner styles");
let page = d.first_page().unwrap();
let f = d.create(page, NodeKind::Frame, "Frame", 0.0, 0.0, 1000.0, 1000.0).unwrap();
@@ -130,7 +130,7 @@ fn a_view_in_a_corner_a_chamfer_cuts_off_shows_nothing_of_the_frame() {
(n.corners.radii, n.corners.style, n.clip) = ([100.0; 4], style, true);
let c = d.create(f, NodeKind::Rectangle, "Child", 0.0, 0.0, 1000.0, 1000.0).unwrap();
d.get_mut(c).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())];
// Inside the arc a round corner would have, outside the chamfer and the concave corner.
// Inside the arc a round corner would have, outside the chamfer, the concave corner and the notch.
let v = View { origin: (30.0, 30.0), scale: 1.0, width: 10, height: 10 };
let (new, old) = both(&d, page, &v);
assert_eq!(new.data(), old.data(), "{style:?}");
+1
View File
@@ -144,6 +144,7 @@ fn fill_share(n: &Node) -> f32 {
CornerStyle::Round => 1.0 - std::f64::consts::FRAC_PI_4,
CornerStyle::Chamfer => 0.5,
CornerStyle::Concave => std::f64::consts::FRAC_PI_4,
CornerStyle::Notch => 1.0,
};
let squared_radii: f64 = n.corners.radii.iter().map(|r| r.clamp(0.0, w.min(h) / 2.0).powi(2)).sum();
let area = w * h;
+1
View File
@@ -556,6 +556,7 @@ name = "English"
"Round|corner" = "Round"
"Chamfered|corner" = "Chamfered"
"Concave|corner" = "Concave"
"Notched|corner" = "Notched"
"Corner smoothing" = "Corner smoothing"
"Couldn't download the variables" = "Couldn't download the variables"
"Couldn't download {name}" = "Couldn't download {name}"
@@ -65,9 +65,12 @@ fn corner_style_menu_changes_the_outline_without_losing_individual_radii() {
let (mut u, r) = scene();
let toggle = named_button(&mut u, "Individual corners");
click(&mut u, toggle);
for (current, choice, expected) in
[("Round", "Chamfered", CornerStyle::Chamfer), ("Chamfered", "Concave", CornerStyle::Concave), ("Concave", "Round", CornerStyle::Round)]
{
for (current, choice, expected) in [
("Round", "Chamfered", CornerStyle::Chamfer),
("Chamfered", "Concave", CornerStyle::Concave),
("Concave", "Notched", CornerStyle::Notch),
("Notched", "Round", CornerStyle::Round),
] {
let dropdown = named_control(&mut u, Role::ComboBox, current);
click(&mut u, dropdown);
let action = named_control(&mut u, Role::MenuItemCheckBox, choice);
+2 -1
View File
@@ -101,12 +101,13 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N
CornerStyle::Round => tr("Round|corner"),
CornerStyle::Chamfer => tr("Chamfered|corner"),
CornerStyle::Concave => tr("Concave|corner"),
CornerStyle::Notch => tr("Notched|corner"),
};
widgets::sublabels(ui, tr("Corner style"), None);
row(ui, 32.0, |ui| {
let resp = widgets::dropdown(ui, style.map(label).unwrap_or(tr("Mixed")), col * 2.0 + 8.0, Some(Icon::CornerRadius));
menu_popup(&resp).show(|ui| {
for choice in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave] {
for choice in [CornerStyle::Round, CornerStyle::Chamfer, CornerStyle::Concave, CornerStyle::Notch] {
if menu_check(ui, style == Some(choice), label(choice), "") {
app.set_props(&ids, json!({"cornerStyle": choice}));
ui.close();
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long