mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
M4: add editable chamfered and concave corners (#1680)
This commit is contained in:
1 parent
a2e87433d8
commit
edbfb114b4
21 files changed
+247
-27
No files matched your search
@@ -115,3 +115,6 @@ display_name = "Hamza0101"
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
[people.victorazesc]
|
||||
sync_github_name = true
|
||||
@@ -14,7 +14,7 @@ pub fn shape_path(n: &Node) -> Option<BezPath> {
|
||||
| NodeKind::Component { .. }
|
||||
| NodeKind::ComponentSet { .. }
|
||||
| NodeKind::Instance { .. }
|
||||
| NodeKind::Section { .. } => figcraft_geom::rounded_rect(w, h, c.radii, c.smoothing),
|
||||
| NodeKind::Section { .. } => figcraft_geom::styled_rect(w, h, c.radii, c.smoothing, c.style),
|
||||
NodeKind::Slice => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0),
|
||||
NodeKind::Ellipse { start, sweep, inner } => figcraft_geom::ellipse(w, h, *start, *sweep, *inner),
|
||||
NodeKind::Polygon { count } => figcraft_geom::smoothed_polygon(&figcraft_geom::polygon_points(w, h, *count), c.radii[0], c.smoothing),
|
||||
@@ -84,6 +84,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
|
||||
}
|
||||
NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. } | NodeKind::Section { .. } => {
|
||||
n.local_rect().inflate(tol_l, tol_l).contains(lp)
|
||||
&& (n.corners.style.is_round() || shape_path(n).is_some_and(|path| path.contains(lp) || (tol_l > 0.0 && near_path(&path, lp, tol_l))))
|
||||
}
|
||||
NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => {
|
||||
let drawn = drawn_network(network, n.corners.smoothing);
|
||||
|
||||
@@ -694,7 +694,7 @@ impl Node {
|
||||
let blend = if kind.is_container() { BlendMode::PassThrough } else { BlendMode::Normal };
|
||||
let clip = matches!(kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. });
|
||||
let corners = match &kind {
|
||||
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], smoothing: 0.0 },
|
||||
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], ..Corners::default() },
|
||||
_ => Corners::default(),
|
||||
};
|
||||
Self {
|
||||
|
||||
@@ -1004,6 +1004,8 @@ impl Effect {
|
||||
pub struct Corners {
|
||||
pub radii: [f64; 4],
|
||||
pub smoothing: f64,
|
||||
#[serde(skip_serializing_if = "figcraft_geom::CornerStyle::is_round")]
|
||||
pub style: figcraft_geom::CornerStyle,
|
||||
}
|
||||
|
||||
impl Corners {
|
||||
|
||||
@@ -305,6 +305,20 @@ fn collections_and_modes_resolve_stored_ids_never_by_name() {
|
||||
assert_eq!(theme.find_mode("Dark").map(|m| m.id.as_str()), Some("m2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_style_roundtrips_and_old_radii_default_to_round() {
|
||||
use figcraft_geom::CornerStyle;
|
||||
let legacy = serde_json::json!({"radii": [2.0, 4.0, 6.0, 8.0], "smoothing": 0.4});
|
||||
let mut corners: crate::Corners = serde_json::from_value(legacy.clone()).unwrap();
|
||||
assert_eq!(corners.style, CornerStyle::Round);
|
||||
assert_eq!(serde_json::to_value(corners).unwrap(), legacy);
|
||||
for style in [CornerStyle::Chamfer, CornerStyle::Concave] {
|
||||
corners.style = style;
|
||||
let saved = serde_json::to_value(corners).unwrap();
|
||||
assert_eq!(serde_json::from_value::<crate::Corners>(saved).unwrap(), corners);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_roundtrip_and_repair() {
|
||||
let mut d = Document::new("x");
|
||||
|
||||
@@ -26,6 +26,7 @@ pub const NODE_KEYS: &[&str] = &[
|
||||
"componentPropertyDefinitions",
|
||||
"constraints",
|
||||
"cornerRadius",
|
||||
"cornerStyle",
|
||||
"cornerSmoothing",
|
||||
"dashes",
|
||||
"description",
|
||||
@@ -275,6 +276,9 @@ fn paint_props(n: &Node, o: &mut serde_json::Map<String, Value>, options: &Inspe
|
||||
if !n.effects.is_empty() {
|
||||
insert_prop(o, options, "effects", || camel(serde_json::to_value(&n.effects).unwrap_or(Value::Null)));
|
||||
}
|
||||
if n.kind.has_independent_corners() {
|
||||
insert_prop(o, options, "cornerStyle", || json!(n.corners.style));
|
||||
}
|
||||
if n.corners.radii.iter().any(|r| *r > 0.0) {
|
||||
insert_prop(o, options, "cornerRadius", || match n.corners.uniform() {
|
||||
Some(r) => json!(r),
|
||||
|
||||
@@ -339,6 +339,9 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
|
||||
v["cornerRadius"] = json!(n.corners.radii);
|
||||
v["cornerSmoothing"] = json!(n.corners.smoothing);
|
||||
}
|
||||
if n.kind.has_independent_corners() {
|
||||
v["cornerStyle"] = json!(n.corners.style);
|
||||
}
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
v["fontFamily"] = json!(t.style.font_family);
|
||||
v["fontStyle"] = json!(t.style.font_style);
|
||||
@@ -365,6 +368,9 @@ pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, prop
|
||||
if !is_text {
|
||||
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
|
||||
}
|
||||
if !doc.get(id)?.kind.has_independent_corners() {
|
||||
m.remove("cornerStyle");
|
||||
}
|
||||
if !doc.get(id)?.kind.has_corner_radius() {
|
||||
m.remove("cornerRadius");
|
||||
m.remove("cornerSmoothing");
|
||||
|
||||
@@ -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), \
|
||||
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]), 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), 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}]), \
|
||||
@@ -707,6 +707,13 @@ fn apply_corners(cmd: &str, doc: &mut Document, id: NodeId, k: &str, v: &Value)
|
||||
*slot = r;
|
||||
}
|
||||
}
|
||||
"cornerStyle" => {
|
||||
let n = doc.get_mut(id)?;
|
||||
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"))?;
|
||||
}
|
||||
"cornerSmoothing" => doc.get_mut(id)?.corners.smoothing = f64_of(v).unwrap_or(0.0).clamp(0.0, 1.0),
|
||||
"effects" => doc.get_mut(id)?.effects = effects_from(cmd, v)?,
|
||||
"clip" | "clipsContent" => doc.get_mut(id)?.clip = v.as_bool().ok_or_else(|| bad(cmd, "`clip` must be a boolean"))?,
|
||||
@@ -1255,7 +1262,9 @@ pub fn override_group(k: &str) -> &'static str {
|
||||
"characters" | "text" => "characters",
|
||||
"features" | "fontFeatures" | "openTypeFeatures" | "listStyle" | "indentation" | "listSpacing" | "maxLines" | "variationSettings"
|
||||
| "hangingPunctuation" | "hangingList" | "wrapStyle" | "textWrap" | "textDirection" | "direction" => "textStyle",
|
||||
"cornerRadius" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "corners",
|
||||
"cornerRadius" | "cornerStyle" | "cornerSmoothing" | "topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => {
|
||||
"corners"
|
||||
}
|
||||
"width" | "height" | "w" | "h" => "size",
|
||||
"sizingH" | "sizingV" | "layoutSizingHorizontal" | "layoutSizingVertical" | "minWidth" | "maxWidth" | "minHeight" | "maxHeight" => "resizing",
|
||||
"gap" | "itemSpacing" | "columnGap" | "crossGap" | "counterAxisSpacing" | "rowGap" => "gap",
|
||||
|
||||
@@ -170,6 +170,9 @@ impl<'d> Exporter<'d> {
|
||||
_ => {}
|
||||
}
|
||||
let boxy = n.kind.is_frame_like() || matches!(n.kind, NodeKind::Rectangle | NodeKind::Section { .. });
|
||||
if boxy && !n.corners.style.is_round() {
|
||||
self.warn("chamfered and concave corners use outline geometry; .fig has no editable corner style");
|
||||
}
|
||||
if (boxy || matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Polygon { .. } | NodeKind::Star { .. }))
|
||||
&& let Some(p) = figcraft_doc::geometry::shape_path(n)
|
||||
{
|
||||
|
||||
@@ -296,7 +296,12 @@ impl<'d> Exporter<'d> {
|
||||
return;
|
||||
}
|
||||
let whole = matches!(n.kind, NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_doc::geom::full_sweep(sweep));
|
||||
if boxy || whole {
|
||||
if boxy && !n.corners.style.is_round() {
|
||||
if let Some(path) = figcraft_doc::geometry::shape_path(n) {
|
||||
let outline = figcraft_pathops::stroke_outline(&path, sp, true);
|
||||
self.geometry("strokeGeometry", &outline, WindingRule::NonZero, f);
|
||||
}
|
||||
} else if boxy || whole {
|
||||
let (out, inset) = match sp.align {
|
||||
StrokeAlign::Inside => (0.0, weight),
|
||||
StrokeAlign::Center => (weight / 2.0, weight / 2.0),
|
||||
|
||||
+38
-3
@@ -18,6 +18,22 @@ pub use transform::*;
|
||||
/// Corner radii in clockwise order from the top-left: `[tl, tr, br, bl]`.
|
||||
pub type Radii = [f64; 4];
|
||||
|
||||
/// How the outline joins two sides at a rectangle's corners.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CornerStyle {
|
||||
#[default]
|
||||
Round,
|
||||
Chamfer,
|
||||
Concave,
|
||||
}
|
||||
|
||||
impl CornerStyle {
|
||||
pub fn is_round(&self) -> bool {
|
||||
*self == Self::Round
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest magnitude a shape builder takes for a size, radius or angle. kurbo subdivides an
|
||||
/// arc in proportion to the sixth root of its radius, so an uncapped radius means an unbounded
|
||||
/// number of segments: 1e36 is about a million cubics and 1e60 never returns. Sizes come from
|
||||
@@ -96,13 +112,18 @@ fn finite(v: f64) -> f64 {
|
||||
/// Radii are clamped so adjacent corners never overlap; when smoothing doesn't fit, it is reduced
|
||||
/// first, then the radius.
|
||||
pub fn rounded_rect(width: f64, height: f64, radii: Radii, smoothing: f64) -> BezPath {
|
||||
styled_rect(width, height, radii, smoothing, CornerStyle::Round)
|
||||
}
|
||||
|
||||
/// A rectangle with editable corner cuts. Smoothing applies to round corners.
|
||||
pub fn styled_rect(width: f64, height: f64, radii: Radii, smoothing: f64, style: CornerStyle) -> BezPath {
|
||||
let w = bounded(width).max(0.0);
|
||||
let h = bounded(height).max(0.0);
|
||||
let mut path = BezPath::new();
|
||||
if w <= 0.0 && h <= 0.0 {
|
||||
return path;
|
||||
}
|
||||
let s = bounded(smoothing).clamp(0.0, 1.0);
|
||||
let s = if style.is_round() { bounded(smoothing).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let max_r = w.min(h) / 2.0;
|
||||
let radii = radii.map(|r| bounded(r).clamp(0.0, max_r));
|
||||
if radii.iter().all(|r| *r <= 0.0) {
|
||||
@@ -124,8 +145,22 @@ pub fn rounded_rect(width: f64, height: f64, radii: Radii, smoothing: f64) -> Be
|
||||
// Start on the top edge just after the top-left corner.
|
||||
path.move_to((first.p, 0.0));
|
||||
for (c, din, dout, r) in corners {
|
||||
let prof = corner_profile(r, s, max_r);
|
||||
append_corner(&mut path, c, din, dout, &prof);
|
||||
if style.is_round() {
|
||||
append_corner(&mut path, c, din, dout, &corner_profile(r, s, max_r));
|
||||
} else if r == 0.0 {
|
||||
path.line_to(c);
|
||||
} else {
|
||||
let from = c - din * r;
|
||||
let to = c + dout * r;
|
||||
path.line_to(from);
|
||||
if style == CornerStyle::Chamfer {
|
||||
path.line_to(to);
|
||||
} else {
|
||||
// An inward quarter circle centred on the original corner.
|
||||
let handle = 0.552_284_749_830_793_6 * r;
|
||||
path.curve_to(from + dout * handle, to - din * handle, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
path.close_path();
|
||||
path
|
||||
|
||||
@@ -18,6 +18,24 @@ fn rounded_rect_area_matches_circle_corners() {
|
||||
assert!((area(&p) - expected).abs() < 0.5, "{} vs {}", area(&p), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_styles_cut_each_corner_at_its_own_radius() {
|
||||
let radii = [20.0, 8.0, 0.0, 4.0];
|
||||
let cut = radii.iter().map(|r| r * r).sum::<f64>();
|
||||
let rect = |style| styled_rect(100.0, 50.0, radii, 0.6, style);
|
||||
let chamfer = rect(CornerStyle::Chamfer);
|
||||
let concave = rect(CornerStyle::Concave);
|
||||
assert!((area(&chamfer) - (5000.0 - cut / 2.0)).abs() < 1e-6);
|
||||
assert!((area(&concave) - (5000.0 - PI * cut / 4.0)).abs() < 0.2);
|
||||
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] {
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_radius_is_capsule_and_bounds_hold() {
|
||||
let p = rounded_rect(100.0, 40.0, [1000.0; 4], 0.0);
|
||||
|
||||
@@ -175,17 +175,48 @@ pub(crate) fn hash_path(p: &BezPath, h: &mut impl Hasher) {
|
||||
fn side_strokes(n: &Node) -> Option<Arc<BezPath>> {
|
||||
let props = &n.stroke;
|
||||
let sides = props.sides?;
|
||||
if !matches!(n.kind, NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. }) {
|
||||
if !n.kind.has_independent_corners() {
|
||||
return None;
|
||||
}
|
||||
let c = &n.corners;
|
||||
Some(Arc::new(if c.uniform() == Some(0.0) {
|
||||
figcraft_pathops::rect_side_strokes(n.width, n.height, sides, props.align)
|
||||
} else {
|
||||
} else if c.style.is_round() {
|
||||
figcraft_pathops::rounded_side_strokes(n.width, n.height, c.radii, c.smoothing, sides, props.align)
|
||||
} else {
|
||||
cut_side_strokes(n, &figcraft_doc::geometry::shape_path(n)?, sides)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Stroke each side at its own weight, meeting its neighbours on the corner bisectors.
|
||||
fn cut_side_strokes(n: &Node, path: &BezPath, sides: [f64; 4]) -> BezPath {
|
||||
let band = |weight| figcraft_pathops::stroke_outline(path, &figcraft_doc::StrokeProps { weight, sides: None, ..n.stroke.clone() }, true);
|
||||
if sides.iter().all(|w| *w == sides[0]) {
|
||||
return band(sides[0]);
|
||||
}
|
||||
let (w, h) = (n.width, n.height);
|
||||
let mid = w.min(h) / 2.0;
|
||||
let inner = [(mid, mid), (w - mid, mid), (w - mid, h - mid), (mid, h - mid)];
|
||||
let mut out = BezPath::new();
|
||||
for (i, weight) in sides.into_iter().enumerate().filter(|(_, weight)| *weight > 0.0) {
|
||||
let stroke = band(weight);
|
||||
let b = stroke.bounding_box();
|
||||
let pad = 1.0 + (-b.x0).max(-b.y0).max(b.x1 - w).max(b.y1 - h).max(0.0);
|
||||
let outer = [(-pad, -pad), (w + pad, -pad), (w + pad, h + pad), (-pad, h + pad)];
|
||||
let next = (i + 1) % 4;
|
||||
let mut side = BezPath::new();
|
||||
side.move_to(outer[i]);
|
||||
side.line_to(outer[next]);
|
||||
side.line_to(inner[next]);
|
||||
side.line_to(inner[i]);
|
||||
side.close_path();
|
||||
if let Ok(part) = figcraft_pathops::boolean_step(&stroke, &side, figcraft_doc::BoolOp::Intersect) {
|
||||
out.extend(part.elements().iter().copied());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The stroke area of a node in local coordinates.
|
||||
pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
|
||||
let props = &n.stroke;
|
||||
@@ -210,7 +241,7 @@ pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc<BezPath> {
|
||||
| NodeKind::ComponentSet { .. }
|
||||
| NodeKind::Instance { .. }
|
||||
| NodeKind::Section { .. }
|
||||
if n.corners.smoothing == 0.0 =>
|
||||
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
|
||||
{
|
||||
let radii = n.corners.radii.map(|r| if r > 0.0 { (r - inset).max(0.0) } else { 0.0 });
|
||||
let mut p = figcraft_geom::rounded_rect(ww, hh, radii, 0.0);
|
||||
|
||||
@@ -790,7 +790,7 @@ impl RoundedRect {
|
||||
| NodeKind::Section { .. }
|
||||
);
|
||||
let sized = n.width.is_finite() && n.height.is_finite() && n.width > 0.0 && n.height > 0.0;
|
||||
(rect_like && sized && n.corners.smoothing == 0.0).then(|| {
|
||||
(rect_like && sized && n.corners.style.is_round() && n.corners.smoothing == 0.0).then(|| {
|
||||
// Clamped as `rounded_rect` clamps them: each radius to half the shorter side.
|
||||
let most = n.width.min(n.height) / 2.0;
|
||||
let radii = n.corners.radii.map(|r| if r.is_finite() { r.clamp(0.0, most) } else { 0.0 });
|
||||
|
||||
@@ -139,10 +139,15 @@ fn fill_share(n: &Node) -> f32 {
|
||||
NodeKind::Polygon { .. } => 0.6,
|
||||
NodeKind::Star { .. } | NodeKind::Vector { .. } | NodeKind::BooleanOp { .. } => 0.5,
|
||||
_ => {
|
||||
// Rounded corners cut (4 − π) r² from the box.
|
||||
let r = (n.corners.radii.iter().sum::<f64>() / 4.0).clamp(0.0, w.min(h) / 2.0);
|
||||
use figcraft_geom::CornerStyle;
|
||||
let cut = match n.corners.style {
|
||||
CornerStyle::Round => 1.0 - std::f64::consts::FRAC_PI_4,
|
||||
CornerStyle::Chamfer => 0.5,
|
||||
CornerStyle::Concave => std::f64::consts::FRAC_PI_4,
|
||||
};
|
||||
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;
|
||||
if area > 0.0 { (1.0 - (4.0 - std::f64::consts::PI) * r * r / area).clamp(0.0, 1.0) as f32 } else { 1.0 }
|
||||
if area > 0.0 { (1.0 - cut * squared_radii / area).clamp(0.0, 1.0) as f32 } else { 1.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,6 +300,30 @@ fn strokes_align() {
|
||||
assert_eq!(px(&pix, 30, 8)[0], 0xF5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_corners_clip_children_and_follow_individual_stroke_weights() {
|
||||
use figcraft_geom::CornerStyle;
|
||||
let mut d = figcraft_doc::Document::new("cut corners");
|
||||
let p = d.first_page().unwrap();
|
||||
let f = d.create(p, NodeKind::Frame, "Frame", 0.0, 0.0, 80.0, 80.0).unwrap();
|
||||
let child = d.create(f, NodeKind::Rectangle, "Child", 0.0, 0.0, 80.0, 80.0).unwrap();
|
||||
d.get_mut(child).unwrap().fills = vec![Paint::solid(Color::WHITE)];
|
||||
for (style, inside) in [(CornerStyle::Chamfer, true), (CornerStyle::Concave, false)] {
|
||||
let n = d.get_mut(f).unwrap();
|
||||
n.clip = true;
|
||||
n.corners.style = style;
|
||||
n.corners.radii = [24.0; 4];
|
||||
n.strokes = vec![Paint::solid(Color::BLACK)];
|
||||
n.stroke.align = StrokeAlign::Inside;
|
||||
n.stroke.sides = Some([4.0, 0.0, 0.0, 2.0]);
|
||||
let pix = render_view(&d, p, &view(80, 80), &Options::default()).unwrap();
|
||||
assert_eq!(px(&pix, 14, 14)[0] != 0xF5, inside);
|
||||
assert_eq!(px(&pix, 40, 2), [0, 0, 0, 255]);
|
||||
assert_eq!(px(&pix, 1, 40), [0, 0, 0, 255]);
|
||||
assert_eq!(px(&pix, 40, 78), [255, 255, 255, 255]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_strokes_follow_rounded_corners() {
|
||||
// border-l-4 rounded-r-lg: a straight 4 px bar on the left, nothing on the other edges.
|
||||
|
||||
@@ -805,7 +805,9 @@ impl W<'_> {
|
||||
NodeKind::Ellipse { sweep, inner, .. } if inner == 0.0 && figcraft_geom::full_sweep(sweep) => {
|
||||
figcraft_geom::kurbo::Shape::to_path(&figcraft_geom::kurbo::Ellipse::from_rect(r), 0.1)
|
||||
}
|
||||
NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. } if n.corners.smoothing == 0.0 => {
|
||||
NodeKind::Rectangle | NodeKind::Frame | NodeKind::Component { .. } | NodeKind::Instance { .. }
|
||||
if n.corners.style.is_round() && n.corners.smoothing == 0.0 =>
|
||||
{
|
||||
// A rounded corner keeps a radius only while the shifted radius stays positive.
|
||||
let radii = n.corners.radii.map(|c| if c > 0.0 { c + d } else { 0.0 });
|
||||
if n.corners.radii.iter().zip(radii).any(|(c, r)| *c > 0.0 && r <= 0.0) {
|
||||
|
||||
@@ -362,6 +362,10 @@ name = "English"
|
||||
"Copy the {label}" = "Copy the {label}"
|
||||
"Copy {value}" = "Copy {value}"
|
||||
"Corner radius" = "Corner radius"
|
||||
"Corner style" = "Corner style"
|
||||
"Round|corner" = "Round"
|
||||
"Chamfered|corner" = "Chamfered"
|
||||
"Concave|corner" = "Concave"
|
||||
"Corner smoothing" = "Corner smoothing"
|
||||
"Couldn't download the variables" = "Couldn't download the variables"
|
||||
"Couldn't download {name}" = "Couldn't download {name}"
|
||||
|
||||
@@ -322,6 +322,10 @@ status = "draft — needs native review"
|
||||
"Copy the {label}" = "Copiar {label}"
|
||||
"Copy {value}" = "Copiar {value}"
|
||||
"Corner radius" = "Raio do canto"
|
||||
"Corner style" = "Tipo de borda"
|
||||
"Round|corner" = "Redonda"
|
||||
"Chamfered|corner" = "Chanfrada"
|
||||
"Concave|corner" = "Côncava"
|
||||
"Corner smoothing" = "Suavização de cantos"
|
||||
"Couldn't download the variables" = "Não foi possível baixar as variáveis"
|
||||
"Couldn't reach {server}: showing what this computer remembers." = "Não foi possível alcançar {server}: mostrando o que este computador lembra."
|
||||
@@ -634,7 +638,7 @@ status = "draft — needs native review"
|
||||
"Include id attribute" = "Incluir atributo id"
|
||||
"Included" = "Incluídos"
|
||||
"Included in layout" = "Incluídos no layout"
|
||||
"Individual corners" = "Cantos individuais"
|
||||
"Individual corners" = "Ajustes da borda"
|
||||
"Individual strokes" = "Traços individuais"
|
||||
"Ink" = "Tinta"
|
||||
"Inner shadow" = "Sombra interna"
|
||||
|
||||
@@ -41,11 +41,15 @@ fn enter(u: &mut Ui) {
|
||||
|
||||
/// The middle of the toggle button named `label`, found in the AccessKit tree.
|
||||
fn named_button(u: &mut Ui, label: &str) -> Pos2 {
|
||||
named_control(u, Role::Button, label)
|
||||
}
|
||||
|
||||
fn named_control(u: &mut Ui, role: Role, label: &str) -> Pos2 {
|
||||
u.ctx.enable_accesskit();
|
||||
u.frame(vec![]);
|
||||
let out = u.frame_output(vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::Button && n.label() == Some(label)).expect(label);
|
||||
let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == role && (n.label() == Some(label) || n.value() == Some(label))).expect(label);
|
||||
let b = n.bounds().expect("bounds");
|
||||
pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
|
||||
}
|
||||
@@ -55,6 +59,27 @@ fn field(u: &Ui, k: usize) -> Rect {
|
||||
u.ctx.read_response(Id::unique(("corner", k)).with("field")).expect("corner field shows").rect
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_style_menu_changes_the_outline_without_losing_individual_radii() {
|
||||
use figcraft_doc::geom::CornerStyle;
|
||||
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)]
|
||||
{
|
||||
let dropdown = named_control(&mut u, Role::ComboBox, current);
|
||||
click(&mut u, dropdown);
|
||||
let action = named_control(&mut u, Role::MenuItemCheckBox, choice);
|
||||
let history = u.app.session.undo_depth().0;
|
||||
click(&mut u, action);
|
||||
let corners = u.app.session.doc().unwrap().node(r).unwrap().corners;
|
||||
assert_eq!(corners.style, expected);
|
||||
assert_eq!(corners.radii, [30.0, 0.0, 0.0, 30.0]);
|
||||
assert_eq!(u.app.session.undo_depth().0, history + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// The iOS button next to Corner smoothing sets 60% in one undo step, as the help page's "click
|
||||
/// iOS to set corner smoothing to 60%" describes.
|
||||
#[test]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use figcraft_doc::geom::CornerStyle;
|
||||
|
||||
use super::menu::{blend_menu, context_popup, menu_check, menu_item, menu_popup, preview_blend, row, row_context_menu, row_rect};
|
||||
use super::stroke::stroke_settings;
|
||||
use super::{
|
||||
@@ -85,6 +87,26 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N
|
||||
}
|
||||
});
|
||||
if smooth_ok && ui.data(|d| d.get_temp::<bool>(Id::unique("indep_corners"))).unwrap_or(false) {
|
||||
if indep_ok {
|
||||
let style = common(doc, sel, |n| n.corners.style);
|
||||
let label = |style| match style {
|
||||
CornerStyle::Round => tr("Round|corner"),
|
||||
CornerStyle::Chamfer => tr("Chamfered|corner"),
|
||||
CornerStyle::Concave => tr("Concave|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] {
|
||||
if menu_check(ui, style == Some(choice), label(choice), "") {
|
||||
app.set_props(&ids, json!({"cornerStyle": choice}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
let radii = common(doc, sel, |n| n.corners.radii);
|
||||
// `k` indexes `radii` ([top left, top right, bottom right, bottom left]); the fields sit
|
||||
// where their corners are: top left, top right / bottom left, bottom right.
|
||||
@@ -113,15 +135,18 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N
|
||||
}
|
||||
});
|
||||
}
|
||||
let sm = common(doc, sel, |n| n.corners.smoothing * 100.0);
|
||||
widgets::sublabels(ui, tr("Corner smoothing"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let e = widgets::number_field(ui, Id::unique("smoothing"), Lead::Icon(Icon::CornerSmoothing, tr("Corner smoothing")), sm, "%", col, 1.0);
|
||||
app.field(&ids, "cornerSmoothing", e, |v| json!((v / 100.0).clamp(0.0, 1.0)));
|
||||
if widgets::button(ui, tr("iOS"), false, true).on_hover_text(tr("Set corner smoothing to 60%")).clicked() {
|
||||
app.set_props(&ids, json!({"cornerSmoothing": 0.6}));
|
||||
}
|
||||
});
|
||||
if crate::selection_cache::every(doc, sel, |n| n.corners.style.is_round()) {
|
||||
let sm = common(doc, sel, |n| n.corners.smoothing * 100.0);
|
||||
widgets::sublabels(ui, tr("Corner smoothing"), None);
|
||||
row(ui, 32.0, |ui| {
|
||||
let e =
|
||||
widgets::number_field(ui, Id::unique("smoothing"), Lead::Icon(Icon::CornerSmoothing, tr("Corner smoothing")), sm, "%", col, 1.0);
|
||||
app.field(&ids, "cornerSmoothing", e, |v| json!((v / 100.0).clamp(0.0, 1.0)));
|
||||
if widgets::button(ui, tr("iOS"), false, true).on_hover_text(tr("Set corner smoothing to 60%")).clicked() {
|
||||
app.set_props(&ids, json!({"cornerSmoothing": 0.6}));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let blend = common(doc, sel, |n| n.blend);
|
||||
let show_blend = ui.data(|d| d.get_temp::<bool>(Id::unique("blend_open"))).unwrap_or(false)
|
||||
|
||||
Reference in new issue
Block a user