From edbfb114b46bb44327182b06d32720538b1d628d Mon Sep 17 00:00:00 2001 From: Victor Azevedo <95045208+victorazesc@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:29:50 -0300 Subject: [PATCH 01/38] M4: add editable chamfered and concave corners (#1680) --- contributors/people.toml | 3 ++ crates/doc/src/geometry.rs | 3 +- crates/doc/src/node.rs | 2 +- crates/doc/src/props.rs | 2 + crates/doc/src/tests.rs | 14 ++++++ crates/engine/src/automation/inspect.rs | 4 ++ crates/engine/src/cmd/edit/clipboard.rs | 6 +++ crates/engine/src/cmd/props.rs | 13 +++++- crates/format/src/fig/export/layer.rs | 3 ++ crates/format/src/fig/export/shape.rs | 7 ++- crates/geom/src/lib.rs | 41 ++++++++++++++++-- crates/geom/src/tests.rs | 18 ++++++++ crates/render/src/draw.rs | 37 ++++++++++++++-- crates/render/src/glass.rs | 2 +- crates/render/src/lod.rs | 11 +++-- crates/render/src/tests.rs | 24 +++++++++++ crates/svg/src/lib.rs | 4 +- crates/ui-egui/locales/en.toml | 4 ++ crates/ui-egui/locales/pt-BR.toml | 6 ++- crates/ui-egui/src/corner_individual_tests.rs | 27 +++++++++++- crates/ui-egui/src/panels/right/paints.rs | 43 +++++++++++++++---- 21 files changed, 247 insertions(+), 27 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index c6924df5f..222f99aff 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -115,3 +115,6 @@ display_name = "Hamza0101" [people.ashokram-si] real_name = "Ashok Ram" + +[people.victorazesc] +sync_github_name = true diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 189e06192..3948cd619 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -14,7 +14,7 @@ pub fn shape_path(n: &Node) -> Option { | 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); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5b90b3bff..e437cae90 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -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 { diff --git a/crates/doc/src/props.rs b/crates/doc/src/props.rs index 99b9d9c39..64277d24b 100644 --- a/crates/doc/src/props.rs +++ b/crates/doc/src/props.rs @@ -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 { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 75dbe7cf1..9ce22ea5f 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -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::(saved).unwrap(), corners); + } +} + #[test] fn serde_roundtrip_and_repair() { let mut d = Document::new("x"); diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 324635071..2adddb2a5 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -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, 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), diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 150a3b577..1e68e82a5 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -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"); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 2e5da37bd..e82c99f4c 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -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", diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index bebd09059..9b85d6c01 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -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) { diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index ca5846cde..2ff094f77 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -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), diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index a775a4170..928fc3d8e 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -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 diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 459b2b101..d1e4ed607 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -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::(); + 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); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index ff3a06270..54d8b22c1 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -175,17 +175,48 @@ pub(crate) fn hash_path(p: &BezPath, h: &mut impl Hasher) { fn side_strokes(n: &Node) -> Option> { 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 { let props = &n.stroke; @@ -210,7 +241,7 @@ pub fn stroke_area(n: &Node, path: &BezPath, closed: bool) -> Arc { | 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); diff --git a/crates/render/src/glass.rs b/crates/render/src/glass.rs index e97783d16..4267e7c0c 100644 --- a/crates/render/src/glass.rs +++ b/crates/render/src/glass.rs @@ -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 }); diff --git a/crates/render/src/lod.rs b/crates/render/src/lod.rs index aaa77b985..ed834a4ae 100644 --- a/crates/render/src/lod.rs +++ b/crates/render/src/lod.rs @@ -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::() / 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 } } } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 8e5943b5a..bb17c44d5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -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. diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index f9ce81e89..9c4e7feb5 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -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) { diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 625ee3bd8..f4faf15dc 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -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}" diff --git a/crates/ui-egui/locales/pt-BR.toml b/crates/ui-egui/locales/pt-BR.toml index 9108dea4d..0025a7407 100644 --- a/crates/ui-egui/locales/pt-BR.toml +++ b/crates/ui-egui/locales/pt-BR.toml @@ -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" diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index 281ab6f2a..4ced2c84b 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -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] diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 967ae266b..50b843879 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -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::(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::(Id::unique("blend_open"))).unwrap_or(false) From b84878e4c1aeb43eda25f6e1a23b2ac8331c5f50 Mon Sep 17 00:00:00 2001 From: Victor Azevedo <95045208+victorazesc@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:51:02 -0300 Subject: [PATCH 02/38] M4: preserve sparse inspection for default round corners (#1680) --- crates/engine/src/automation/inspect.rs | 2 +- crates/engine/src/inspect_fields_tests.rs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 2adddb2a5..9beb69706 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -276,7 +276,7 @@ fn paint_props(n: &Node, o: &mut serde_json::Map, 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() { + if n.kind.has_independent_corners() && (!n.corners.style.is_round() || options.explicit("cornerStyle")) { insert_prop(o, options, "cornerStyle", || json!(n.corners.style)); } if n.corners.radii.iter().any(|r| *r > 0.0) { diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..0f5e92c8b 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -37,6 +37,17 @@ fn keys(v: &Value, allowed: &[&str]) { } } +#[test] +fn corner_style_is_sparse_and_can_be_requested_explicitly() { + let (mut s, frame, text) = tree(); + let fields = json!({"fields": ["cornerStyle"]}); + assert!(node(&s, frame, 0, json!({})).get("cornerStyle").is_none()); + assert_eq!(node(&s, frame, 0, fields.clone())["cornerStyle"], "round"); + assert!(node(&s, text, 0, fields).get("cornerStyle").is_none()); + run(&mut s, "node.set", json!({"id": frame, "props": {"cornerStyle": "concave"}})); + assert_eq!(node(&s, frame, 0, json!({}))["cornerStyle"], "concave"); +} + fn golden_tree() -> (Session, NodeId) { let mut s = Session::new(); let frame = create( From 91eb2fc2ab70c34daed8520efd49b06ddfe306f3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 20:01:32 -0500 Subject: [PATCH 03/38] Read Penpot archives through craft-zip --- crates/format/Cargo.toml | 4 +- crates/format/src/penpot.rs | 112 ++++++++++++--------- crates/format/src/penpot/embedded_fonts.rs | 17 ++-- 3 files changed, 73 insertions(+), 60 deletions(-) diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 2a0101b04..bf00e6aeb 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -14,7 +14,6 @@ figcraft-pathops = { workspace = true } figcraft-layout = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -zip = { workspace = true } flate2 = { workspace = true } ruzstd = { workspace = true } sha1 = { workspace = true } @@ -28,3 +27,6 @@ craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } craft-jpeg = { workspace = true } craft-image-codecs = { workspace = true } + +[dev-dependencies] +zip = { workspace = true } diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index c47b55b18..16a873d6a 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -8,6 +8,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::{self, Cursor, Read}; +use crate::{FormatError, add_image}; +use craft_zip::{SeekableArchive, SeekableLimits}; use figcraft_doc::color::{BlendMode, Color, ColorStop, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::{Affine, BezPath, Shape}; use figcraft_doc::{ @@ -17,9 +19,8 @@ use figcraft_doc::{ Variable, VariableType, VariableValue, VectorNetwork, }; use serde_json::Value; -use zip::ZipArchive; -use crate::{FormatError, add_image}; +type PenpotArchive<'a> = SeekableArchive>; mod embedded_fonts; mod export; @@ -135,11 +136,12 @@ impl Read for BudgetReader<'_, R> { } /// Read a JSON archive member within the per-member decompression limit. -fn json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudget) -> Result { - let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?; - if entry.size() > MAX_JSON { +fn json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget) -> Result { + let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; + if declared > MAX_JSON { return Err(corrupt(format!("JSON member too large: {path}"))); } + let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; let mut data = Vec::new(); BudgetReader { inner: entry, budget }.take(MAX_JSON + 1).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?; if data.len() as u64 > MAX_JSON { @@ -149,14 +151,15 @@ fn json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudge } /// Read a shape JSON member within member and per-page decompression limits. -fn shape_json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result { - let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?; - if entry.size() > MAX_JSON { +fn shape_json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result { + let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; + if declared > MAX_JSON { return Err(corrupt(format!("JSON member too large: {path}"))); } - if entry.size() > *page_budget { + if declared > *page_budget { return Err(corrupt("page shapes exceed byte budget")); } + let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; let mut data = Vec::new(); let max_read = (MAX_JSON + 1).min(*page_budget + 1); BudgetReader { inner: entry, budget }.take(max_read).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?; @@ -360,29 +363,35 @@ fn finish_masked_group(doc: &mut Document, group: NodeId, source: &Value, warnin } } +fn open_archive(bytes: &[u8]) -> Result, FormatError> { + let limits = SeekableLimits { + max_entries: MAX_ENTRIES as u64, + max_metadata_bytes: MAX_ARCHIVE as u64, + // The Penpot budget also charges partial reads (embedded font signatures) and + // remembers an overflow that an optional-member caller might otherwise swallow. + max_total_bytes: u64::MAX, + }; + let z = SeekableArchive::open(Cursor::new(bytes), limits).map_err(|e| match e { + craft_zip::Error::TooManyEntries { .. } => corrupt("too many ZIP members"), + _ => corrupt(format!("invalid ZIP: {e}")), + })?; + if let Some(name) = z.duplicate_names().next() { + return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::()))); + } + Ok(z) +} + /// Read one exported `.penpot` archive without touching the filesystem or running a converter. /// Returns native, editable FigCraft nodes plus notes about unsupported features. pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { if bytes.len() > MAX_ARCHIVE { return Err(corrupt("archive exceeds 512 MiB")); } - let mut z = ZipArchive::new(Cursor::new(bytes)).map_err(|e| corrupt(format!("invalid ZIP: {e}")))?; - if z.len() > MAX_ENTRIES { - return Err(corrupt("too many ZIP members")); - } - // Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs - // whose compressed size is innocuous but whose advertised uncompressed size is enormous. + let mut z = open_archive(bytes)?; + // Check declared totals and member paths before decoding any JSON. let mut expanded = 0_u64; - let mut names = BTreeSet::new(); for index in 0..z.len() { - let member = z.by_index(index).map_err(|e| corrupt(e.to_string()))?; - // An importer never extracts members to disk, but ambiguous ZIP names can - // cause one member to be inspected and another member to be read by name. - // Reject duplicates and traversal instead of guessing which version is real. - let name = member.name(); - if !names.insert(name.to_owned()) { - return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::()))); - } + let name = z.entry_name(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; if name.starts_with('/') || name.contains('\\') || name.split('/').any(|part| part == "." || part == "..") @@ -390,10 +399,14 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { { return Err(corrupt("unsafe ZIP member path")); } - expanded = expanded.saturating_add(member.size()); + let (size, _) = z.entry_sizes(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; + expanded = expanded.saturating_add(size); if expanded > MAX_DECOMPRESSED { return Err(corrupt("ZIP contents exceed 1 GiB")); } + // The old indexing pass also rejected entries the decoder could not open, + // even when mapping the document would never request those members. + z.open_entry_index(index, MAX_DECOMPRESSED).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; } let mut inflate_budget = InflateBudget::new(); let manifest = json(&mut z, "manifest.json", &mut inflate_budget)?; @@ -447,12 +460,12 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { // The page index files are peers of the directories containing their layers. let prefix = format!("{base}/pages/"); let page_names: Vec = z - .file_names() + .names() .filter(|name| { name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)) }) .take(501) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if page_names.len() > 500 { return Err(corrupt("too many pages")); @@ -508,13 +521,13 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { } let page_prefix = format!("{prefix}{page_id}/"); let paths: Vec = z - .file_names() + .names() .filter(|name| { name.strip_prefix(&page_prefix) .is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)) }) .take(MAX_LAYERS + 1) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if paths.len() > MAX_LAYERS { return Err(corrupt("too many layers on a page")); @@ -1439,13 +1452,13 @@ fn bind_applied_tokens(doc: &mut Document, active_modes: &BTreeMap>, base: &str, doc: &mut Document, warnings: &mut Vec, budget: &mut InflateBudget) { +fn import_document_colors(z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec, budget: &mut InflateBudget) { let prefix = format!("{base}/colors/"); let paths = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(2049) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect::>(); if paths.len() > 2048 { warn(warnings, "Penpot color library exceeds 2048 swatches; truncated".into()); @@ -1483,7 +1496,7 @@ fn import_document_colors(z: &mut ZipArchive>, base: &str, doc: &m /// Keep original values on the text nodes: attaching a shared style automatically /// would override local formatting unless the source explicitly links it. fn import_typography_styles( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec, @@ -1492,10 +1505,10 @@ fn import_typography_styles( let mut custom_refs = Vec::new(); let prefix = format!("{base}/typographies/"); let paths: Vec = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(2049) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if paths.len() > 2048 { warn(warnings, "Penpot typography library exceeds 2048 entries; truncated".into()); @@ -2359,7 +2372,7 @@ fn import_themed_tokens( /// Import supported scalar tokens and retain their original source. fn import_token_variables( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, active_modes: &mut BTreeMap, @@ -2367,7 +2380,9 @@ fn import_token_variables( budget: &mut InflateBudget, ) -> Option { let path = format!("{base}/tokens.json"); - z.index_for_name(&path)?; + if !z.contains(&path) { + return None; + } let value = match json(z, &path, budget) { Ok(v) => v, Err(_) => { @@ -2501,16 +2516,16 @@ fn report_design_system_limits(doc: &Document, warnings: &mut Vec) { /// that original into a native FigCraft component. Copies are still independent layers until the /// Penpot override/source graph can be translated safely (see docs). fn component_masters( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, budget: &mut InflateBudget, ) -> (BTreeMap, BTreeMap, BTreeMap) { let prefix = format!("{base}/components/"); let paths = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(10001) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect::>(); let mut result = BTreeMap::new(); let mut variant_names = BTreeMap::new(); @@ -2971,7 +2986,7 @@ fn svg_paint_ref(text: &str) -> Option<&str> { /// What importing a page's layers shares from layer to layer: the archive and the page's shapes, /// and the document, budgets and warnings they add to. struct LayerImport<'a, 'b> { - z: &'a mut ZipArchive>, + z: &'a mut PenpotArchive<'b>, base: &'a str, shapes: &'a BTreeMap, children_by_parent: &'a BTreeMap>, @@ -4135,7 +4150,7 @@ fn effects(v: &Value, warnings: &mut Vec) -> Vec { /// Resolve a Penpot image fill through `media/.json` -> `objects/.png|jpg`. fn paints( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, shape: &Value, key: &str, @@ -4170,10 +4185,7 @@ fn paints( }; if let Some(obj) = object_id { let p = format!("objects/{obj}.{extension}"); - let data = z.by_name(&p).ok().and_then(|f| { - if f.size() > MAX_IMAGE { - return None; - } + let data = z.open_entry(&p, MAX_IMAGE).ok().flatten().and_then(|f| { let mut bytes = Vec::new(); BudgetReader { inner: f, budget: &mut *budget }.take(MAX_IMAGE + 1).read_to_end(&mut bytes).ok()?; if bytes.len() as u64 > MAX_IMAGE || bytes.len() > MAX_TOTAL_IMAGES.saturating_sub(*image_bytes) { @@ -4385,7 +4397,7 @@ mod tests { writer.write_all(b"[0,0]").unwrap(); } let bytes = writer.finish().unwrap().into_inner(); - let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive = open_archive(&bytes).unwrap(); let mut budget = InflateBudget { json_values: 6, ..InflateBudget::new() }; let mut page_bytes = MAX_PAGE_SHAPES_BYTES; assert_eq!(json(&mut archive, "tokens.json", &mut budget).unwrap(), serde_json::json!([0, 0])); @@ -4493,14 +4505,14 @@ mod tests { z.start_file("shape.json", SimpleFileOptions::default()).unwrap(); z.write_all(br#"{"id":"00000000-0000-0000-0000-000000000001","type":"rect"}"#).unwrap(); let bytes = z.finish().unwrap().into_inner(); - let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive = open_archive(&bytes).unwrap(); let mut inflate_budget = InflateBudget::new(); let mut page_budget = 10u64; // Too small for the shape JSON (~60 bytes) let res = shape_json(&mut archive, "shape.json", &mut inflate_budget, &mut page_budget); assert!(res.is_err()); - let mut archive2 = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive2 = open_archive(&bytes).unwrap(); let mut inflate_budget2 = InflateBudget::new(); let mut page_budget2 = 1000u64; let res2 = shape_json(&mut archive2, "shape.json", &mut inflate_budget2, &mut page_budget2); @@ -4508,7 +4520,7 @@ mod tests { assert!(page_budget2 < 1000); } use std::io::Write; - use zip::write::SimpleFileOptions; + use zip::{ZipArchive, write::SimpleFileOptions}; fn archive_with_shapes(shapes: &[(&str, Value)]) -> Vec { archive_with_components(shapes, &[]) diff --git a/crates/format/src/penpot/embedded_fonts.rs b/crates/format/src/penpot/embedded_fonts.rs index d09896804..bba87462b 100644 --- a/crates/format/src/penpot/embedded_fonts.rs +++ b/crates/format/src/penpot/embedded_fonts.rs @@ -1,20 +1,19 @@ //! Embedded font detection without decoding or retaining unsupported binaries. -use super::{BudgetReader, InflateBudget, MAX_ENTRIES, warn}; -use std::io::{Cursor, Read}; -use zip::ZipArchive; +use super::{BudgetReader, InflateBudget, MAX_ENTRIES, PenpotArchive, warn}; +use std::io::Read; /// Identify unsupported fonts from signatures without decoding their payloads. -pub(super) fn report(z: &mut ZipArchive>, warnings: &mut Vec, budget: &mut InflateBudget) { +pub(super) fn report(z: &mut PenpotArchive<'_>, warnings: &mut Vec, budget: &mut InflateBudget) { let names: Vec = z - .file_names() + .names() .filter(|n| n.starts_with("objects/") || n.starts_with("fonts/") || n.starts_with("assets/fonts/")) .take(MAX_ENTRIES) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); let mut count = 0; for name in names { - let Ok(member) = z.by_name(&name) else { continue }; + let Ok(Some(member)) = z.open_entry(&name, u64::MAX) else { continue }; let mut header = [0; 4]; if (BudgetReader { inner: member, budget }).read_exact(&mut header).is_ok() && (matches!(&header, b"OTTO" | b"true" | b"ttcf" | b"wOFF" | b"wOF2") || header == [0, 1, 0, 0]) @@ -35,7 +34,7 @@ pub(super) fn report(z: &mut ZipArchive>, warnings: &mut Vec Date: Mon, 23 Nov 2026 20:06:52 -0500 Subject: [PATCH 04/38] Use ZIP 9.8.2 for FigCraft test fixtures Covers the dependency bump from #1602 using current fixture APIs and adds a normal CP437 ancillary-member regression. --- Cargo.lock | 89 ++++++++------------- Cargo.toml | 2 +- apps/figcraft-server/src/hardening_tests.rs | 2 +- crates/engine/src/jam_open_tests.rs | 4 +- crates/format/src/fig/export_tests.rs | 3 +- crates/format/src/fig/interop_tests.rs | 2 +- crates/format/src/image_budget_tests.rs | 2 +- crates/format/src/image_tests.rs | 18 +++-- crates/format/src/library_tests.rs | 2 +- crates/format/src/penpot.rs | 25 +++++- crates/format/src/penpot/export_tests.rs | 6 +- 11 files changed, 80 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b56684fec..633b613d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,15 +249,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.7.0" @@ -935,6 +926,15 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1106,7 +1106,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -1448,7 +1448,7 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip 9.1.1", + "zip", ] [[package]] @@ -1504,7 +1504,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab5 dependencies = [ "flate2", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -1641,17 +1641,6 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "deunicode" version = "1.6.2" @@ -2265,7 +2254,7 @@ dependencies = [ "thiserror 2.0.21", "wat", "web-time", - "zip 2.6.1", + "zip", ] [[package]] @@ -2290,7 +2279,7 @@ dependencies = [ "serde_json", "sha1", "sha2", - "zip 2.6.1", + "zip", ] [[package]] @@ -2408,7 +2397,7 @@ dependencies = [ "toml", "tungstenite", "wat", - "zip 2.6.1", + "zip", ] [[package]] @@ -7466,6 +7455,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -7506,33 +7509,21 @@ dependencies = [ [[package]] name = "zip" -version = "2.6.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "flate2", - "indexmap", - "memchr", - "zopfli", -] - -[[package]] -name = "zip" -version = "9.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ + "constant_time_eq", "crc32fast", "flate2", "getrandom 0.4.3", "indexmap", + "libc", "memchr", "nix", "typed-path", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -7547,18 +7538,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index c891c0ef4..af4f7c060 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -110,7 +110,7 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil # dependencies, BSD-3-Clause, no_std so the web build keeps it too). deunicode = "1.6" linesweeper = "0.4" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] } # `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe). flate2 = { version = "1", default-features = false, features = ["rust_backend"] } ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } diff --git a/apps/figcraft-server/src/hardening_tests.rs b/apps/figcraft-server/src/hardening_tests.rs index 186b8d9c0..119a8dc4b 100644 --- a/apps/figcraft-server/src/hardening_tests.rs +++ b/apps/figcraft-server/src/hardening_tests.rs @@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec { let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); for i in 0..src.len() { let f = src.by_index_raw(i).unwrap(); - if bomb > 0 && f.name() == "library/document.json" { + if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" { continue; } out.raw_copy_file(f).unwrap(); diff --git a/crates/engine/src/jam_open_tests.rs b/crates/engine/src/jam_open_tests.rs index 682bc2346..cdad20bfb 100644 --- a/crates/engine/src/jam_open_tests.rs +++ b/crates/engine/src/jam_open_tests.rs @@ -20,11 +20,11 @@ fn jam_file(tag: &str) -> std::path::PathBuf { let mut member = from.by_index(i).unwrap(); let mut bytes = Vec::new(); member.read_to_end(&mut bytes).unwrap(); - if member.name() == "canvas.fig" { + if member.name().expect("ZIP member name") == "canvas.fig" { assert!(bytes.starts_with(b"fig-kiwi")); bytes.splice(..8, *b"fig-jam."); } - to.start_file(member.name(), zip::write::SimpleFileOptions::default()).unwrap(); + to.start_file(member.name().expect("ZIP member name"), zip::write::SimpleFileOptions::default()).unwrap(); to.write_all(&bytes).unwrap(); } let path = std::env::temp_dir().join(format!("figcraft-jam-{tag}-{}.jam", std::process::id())); diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9cb417078..306a82e49 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -1380,7 +1380,8 @@ fn images_are_named_by_the_sha1_of_their_bytes() { assert_eq!(export::sha1_hex(&vec![b'a'; 1_000_000]), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); let (bytes, _) = export(&generate(3), None).unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap(); - let names: Vec = z.file_names().filter(|n| n.starts_with("images/")).map(str::to_string).collect(); + let names: Vec = + z.file_names().map(|name| name.expect("ZIP member name")).filter(|n| n.starts_with("images/")).map(std::borrow::Cow::into_owned).collect(); assert!(!names.is_empty()); for name in names { let data = crate::read_member(&mut z, &name, 1 << 26).unwrap(); diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index 4ad81cebc..c43b61c21 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -364,7 +364,7 @@ fn mask_types_round_trip() { fn the_archive_lists_its_members_and_describes_the_file() { let (bytes, _) = export(&sample(), Some(&super::tests::png())).unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap(); - let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().expect("ZIP member name").into_owned()).collect(); assert_eq!(names, ["canvas.fig", "thumbnail.png", "meta.json"]); let meta: serde_json::Value = serde_json::from_slice(&crate::read_member(&mut z, "meta.json", 1 << 20).unwrap()).unwrap(); assert_eq!(meta["file_name"], "Interop"); diff --git a/crates/format/src/image_budget_tests.rs b/crates/format/src/image_budget_tests.rs index 8e10cd714..51aee7609 100644 --- a/crates/format/src/image_budget_tests.rs +++ b/crates/format/src/image_budget_tests.rs @@ -31,7 +31,7 @@ fn file_with_images(n: u8) -> (Vec, Vec, u64) { /// `bytes` with one more member, `name` holding `data`. fn with_member(bytes: &[u8], name: &str, data: &[u8]) -> Vec { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let names: Vec = z.file_names().map(str::to_string).collect(); + let names: Vec = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect(); let mut buf = std::io::Cursor::new(Vec::new()); let mut w = zip::ZipWriter::new(&mut buf); let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); diff --git a/crates/format/src/image_tests.rs b/crates/format/src/image_tests.rs index b885fc20c..6a8b72477 100644 --- a/crates/format/src/image_tests.rs +++ b/crates/format/src/image_tests.rs @@ -25,7 +25,7 @@ fn doc_with_image() -> (Document, String) { /// The archive of `d` rebuilt with `edit` applied to each member (None drops it). fn rebuild(bytes: &[u8], edit: impl Fn(&str, Vec) -> Option>) -> Vec { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let names: Vec = z.file_names().map(str::to_string).collect(); + let names: Vec = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect(); let mut buf = std::io::Cursor::new(Vec::new()); let mut w = zip::ZipWriter::new(&mut buf); for n in names { @@ -109,7 +109,11 @@ fn image_members_with_path_like_names_are_dropped_and_not_saved_back() { assert!(!loaded.issues.is_empty()); let saved = save_bytes_with_history(&loaded.doc, None, &loaded.versions, &loaded.branches).unwrap(); let z = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap(); - assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::>()); + assert!( + z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1), + "{:?}", + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() + ); let _ = hash; } @@ -128,11 +132,15 @@ fn a_path_like_rest_image_ref_never_names_an_archive_member() { assert!(doc.images.contains_key("rest-image-missing"), "the shared placeholder stores it instead: {:?}", doc.images.keys().collect::>()); let bytes = save_bytes(&doc, None).unwrap(); let z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); - assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::>()); assert!( - z.file_names().any(|n| n == "images/rest-image-missing"), + z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1), + "{:?}", + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() + ); + assert!( + z.file_names().map(|name| name.expect("ZIP member name")).any(|n| n == "images/rest-image-missing"), "the placeholder is saved under its own name: {:?}", - z.file_names().collect::>() + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() ); } diff --git a/crates/format/src/library_tests.rs b/crates/format/src/library_tests.rs index b1f26b0c5..1a43014bb 100644 --- a/crates/format/src/library_tests.rs +++ b/crates/format/src/library_tests.rs @@ -81,7 +81,7 @@ fn replace_member(zip_bytes: &[u8], name: &str, bytes: Option<&[u8]>) -> Vec let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for i in 0..src.len() { let mut f = src.by_index(i).unwrap(); - let n = f.name().to_string(); + let n = f.name().expect("ZIP member name").to_string(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); let data = if n == name { bytes.map(<[u8]>::to_vec) } else { Some(data) }; diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index 16a873d6a..40238ffb0 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -4446,8 +4446,8 @@ mod tests { assert!(dense.len() < MAX_JSON as usize); for index in 0..source.len() { let mut member = source.by_index(index).unwrap(); - writer.start_file(member.name(), crate::json_options()).unwrap(); - if member.name().ends_with(&format!("/{id}.json")) { + writer.start_file(member.name().expect("ZIP member name"), crate::json_options()).unwrap(); + if member.name().expect("ZIP member name").ends_with(&format!("/{id}.json")) { writer.write_all(dense.as_bytes()).unwrap(); } else { io::copy(&mut member, &mut writer).unwrap(); @@ -4558,6 +4558,23 @@ mod tests { z.finish().unwrap().into_inner() } + #[test] + fn import_allows_a_legacy_encoded_ancillary_zip_member() { + let id = "cccccccc-cccc-cccc-cccc-cccccccccccc"; + let bytes = archive_with_shapes(&[(id, serde_json::json!({"id":id,"type":"rect","name":"Imported rectangle","width":40,"height":25}))]); + let mut writer = zip::ZipWriter::new_append(Cursor::new(bytes)).unwrap(); + // Unflagged CP437, as written by legacy ZIP tools: 0x82 is é. + writer.start_file_with_options(SimpleFileOptions::default().name(b"caf\x82.txt")).unwrap(); + writer.write_all(b"Ancillary archive note").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + let mut archive = open_archive(&bytes).unwrap(); + assert!((0..archive.len()).any(|i| archive.entry_name(i).unwrap().as_deref() == Some("café.txt"))); + let (doc, warnings) = import(&bytes).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(doc.nodes().any(|node| node.name == "Imported rectangle")); + } + #[test] fn raw_svg_from_export_is_preserved_for_native_svg_expansion() { let id = "cccccccc-cccc-cccc-cccc-cccccccccccc"; @@ -4941,12 +4958,12 @@ mod tests { let mut e = z.by_index(i).unwrap(); let mut content = Vec::new(); e.read_to_end(&mut content).unwrap(); - if e.name().ends_with(&format!("/{ROOT_ID}.json")) { + if e.name().expect("ZIP member name").ends_with(&format!("/{ROOT_ID}.json")) { let mut v: Value = serde_json::from_slice(&content).unwrap(); v["shapes"] = serde_json::json!([one]); content = serde_json::to_vec(&v).unwrap(); } - members.push((e.name().to_string(), content)); + members.push((e.name().expect("ZIP member name").to_string(), content)); } drop(z); let cursor = Cursor::new(Vec::new()); diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index e3ad744ef..c16f43e82 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -18,7 +18,7 @@ fn entries(bytes: &[u8]) -> BTreeMap { let mut out = BTreeMap::new(); for i in 0..z.len() { let mut f = z.by_index(i).unwrap(); - let name = f.name().to_owned(); + let name = f.name().expect("ZIP member name").into_owned(); if name.ends_with(".json") { let mut text = String::new(); f.read_to_string(&mut text).unwrap(); @@ -684,7 +684,7 @@ fn imported_penpot_tokens_are_written_back_verbatim() { doc.node_mut(p).unwrap().plugin_data.insert("penpot.fp.tokens".into(), fp); let (bytes, warnings) = export(&doc).unwrap(); let mut z = zip::ZipArchive::new(Cursor::new(&bytes[..])).unwrap(); - let path = z.file_names().find(|n| n.ends_with("tokens.json")).unwrap().to_owned(); + let path = z.file_names().map(|name| name.expect("ZIP member name")).find(|n| n.ends_with("tokens.json")).unwrap().into_owned(); let mut text = String::new(); z.by_name(&path).unwrap().read_to_string(&mut text).unwrap(); assert_eq!(text, source); @@ -1033,7 +1033,7 @@ fn shared_writer_keeps_manifest_first_and_deflated_members() { let doc = Document::new("Shared container"); let (bytes, _) = export(&doc).unwrap(); let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); - assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json"); + assert_eq!(zip.by_index(0).unwrap().name().expect("ZIP member name"), "manifest.json"); for index in 0..zip.len() { assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated); } From 95b2fc41f972e378005e4281fa40a578e38545ef Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 14:57:14 +0700 Subject: [PATCH 05/38] Build the export test's corners from the default so the new style field is set --- crates/format/src/fig/export_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9cb417078..c28deb5c4 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -819,7 +819,7 @@ fn a_boolean_groups_corner_radius_round_trips() { doc.create(g, NodeKind::Rectangle, "A", 0.0, 0.0, 200.0, 100.0).unwrap(); doc.create(g, NodeKind::Rectangle, "B", 150.0, 0.0, 100.0, 200.0).unwrap(); doc.fit_to_children(g).unwrap(); - doc.get_mut(g).unwrap().corners = Corners { radii: [20.0; 4], smoothing: 0.6 }; + doc.get_mut(g).unwrap().corners = Corners { radii: [20.0; 4], smoothing: 0.6, ..Corners::default() }; let (back, _) = round_trip(&doc, "boolean radius"); let n = back.nodes().find(|n| matches!(n.kind, NodeKind::BooleanOp { .. })).unwrap(); assert!(n.corners.radii.iter().all(|r| (r - 20.0).abs() < 1e-4), "{:?}", n.corners); From b20d43321e8548e02cd80d707b3658a199c03280 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Sat, 28 Nov 2026 08:59:22 +0100 Subject: [PATCH 06/38] M8: a test checks the tools and fields the prompts name exist A prompt is a workflow an agent follows by name. The existing check covers the command ids the instructions and prompts give, but not the MCP tools or the result fields: a renamed tool or field would leave a prompt pointing at nothing, with no test failing. Every snake_case name in the server instructions and the prompt templates must now be a tool, a prompt or that prompt's own argument, and every backticked field must appear in some tool's or command's documentation. --- crates/mcp/src/prompts.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index e0971da01..50a1440b4 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -196,6 +196,41 @@ mod tests { assert!(out.len() < 3 * bomb.len(), "{}", out.len()); } + /// Every tool and result field the instructions and prompts name exists: an agent told to call a + /// renamed tool, or to read a field that was renamed, follows a workflow that points at nothing. + #[test] + fn the_tools_and_fields_the_instructions_and_prompts_name_exist() { + let tools = crate::tool_definitions(); + // Every name a tool's or command's documentation gives: its fields and arguments. + let documented: String = tools + .iter() + .map(Value::to_string) + .chain(figcraft_engine::all_commands().iter().map(|c| format!("{} {}", c.id, c.params))) + .collect::>() + .join(" "); + let words: std::collections::HashSet<&str> = + documented.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')).map(|w| w.trim_matches('.')).collect(); + let tool_names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect(); + let prompt_names: Vec<&str> = PROMPTS.iter().map(|p| p.name).collect(); + let texts = std::iter::once((crate::INSTRUCTIONS, &[][..])).chain(PROMPTS.iter().map(|p| (p.template, p.args))); + let (mut tools_named, mut fields_named) = (0, 0); + for (text, args) in texts { + for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| w.contains('_')) { + tools_named += 1; + let known = tool_names.contains(&word) || prompt_names.contains(&word) || args.iter().any(|a| a.name == word); + assert!(known, "`{word}` is neither a tool, a prompt nor one of the prompt's arguments"); + } + for quoted in text.split('`').skip(1).step_by(2) { + if quoted.is_empty() || !quoted.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') { + continue; + } + fields_named += 1; + assert!(words.contains(quoted), "`{quoted}` is in no tool's or command's documentation"); + } + } + assert!(tools_named > 10 && fields_named > 3, "the check found the names ({tools_named}, {fields_named})"); + } + /// Every command the server's instructions and the prompts name exists: an agent told to run a /// renamed or misspelt one gets an error instead of the workflow. #[test] From facf27218f8871d63045ad6e25e46150b5af506b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:26:42 +0000 Subject: [PATCH 07/38] mcp: create_node and set_properties take fields and outline The layers these two tools return can now be cut to the keys an agent needs, with the same `fields` and `outline` options get_node and inspect_document take. The options are checked before the edit runs, so a bad one changes nothing, and without them the result is unchanged. Closes #2535. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KudydNWQDXESHDpVmpiqZh --- crates/mcp/src/tools.rs | 21 +++++++--- crates/mcp/tests/it/inspect_fields.rs | 57 ++++++++++++++++++++++++++- docs/mcp.md | 4 +- docs/roadmap.md | 1 + 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index bdd8078ed..db56f3863 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -195,7 +195,7 @@ fn tools() -> Vec { tool( "create_node", "Create layer", - "Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face.", + "Create a layer (engine `node.create`) and return its id and inspected properties. Coordinates are page units, y down; x/y are relative to the parent frame (the page when there is none, so then they are page coordinates; groups don't count). Inside an auto-layout frame the position is decided by the layout. The new layer becomes the selection. `warnings` reports a fontStyle that draws in another face. `fields` / `outline` shrink the returned layer as they do for get_node; the layer is created either way.", obj( json!({ "type": {"type": "string", "enum": ["frame", "rectangle", "ellipse", "polygon", "star", "line", "arrow", "text", "vector", "section", "component", "slice"], "description": "Layer type"}, @@ -212,6 +212,8 @@ fn tools() -> Vec { "closed": boolean("For type vector: close the path"), "select": boolean("Select the new layer (default true)"), "props": {"type": "object", "description": "Any set_properties keys applied at creation, e.g. {\"fill\":\"#3366FF\",\"cornerRadius\":12,\"fontSize\":24,\"layout\":\"vertical\",\"gap\":8,\"padding\":16}"}, + "fields": fields_schema(), + "outline": outline_schema(), }), &["type"], ), @@ -220,9 +222,14 @@ fn tools() -> Vec { tool( "set_properties", "Set properties", - "Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.", + "Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers (up to 20); `fields` / `outline` shrink them as they do for get_node.", obj( - json!({"ids": ids_schema("Layer ids (default: the selection)"), "props": {"type": "object", "description": "Property values to set"}}), + json!({ + "ids": ids_schema("Layer ids (default: the selection)"), + "props": {"type": "object", "description": "Property values to set"}, + "fields": fields_schema(), + "outline": outline_schema(), + }), &["props"], ), false, @@ -836,6 +843,8 @@ fn create_node(b: &mut dyn Backend, a: &Map) -> Result) -> Result) -> Result) -> Result = ids.iter().take(20).filter_map(|i| b.call("node.get", json!({"id": i, "depth": 0})).ok()).collect(); + let nodes: Vec = ids.iter().take(20).filter_map(|&i| node_at(b, i, 0, &options).ok().map(|(v, _)| v)).collect(); let mut out = json!({"ok": true, "nodes": nodes}); if let Some(w) = warnings { out["warnings"] = w; diff --git a/crates/mcp/tests/it/inspect_fields.rs b/crates/mcp/tests/it/inspect_fields.rs index 0351cd02c..a8ea22eae 100644 --- a/crates/mcp/tests/it/inspect_fields.rs +++ b/crates/mcp/tests/it/inspect_fields.rs @@ -35,7 +35,7 @@ fn compact_keys(node: &Value, outline: bool) { fn tool_schemas_describe_compact_inspection_options() { let mut c = Client::new(); let tools = c.rpc("tools/list", json!({})); - for name in ["inspect_document", "get_node"] { + for name in ["inspect_document", "get_node", "create_node", "set_properties"] { let tool = tools["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == name).unwrap(); let props = &tool["inputSchema"]["properties"]; assert_eq!(props["fields"]["type"], "array"); @@ -193,6 +193,61 @@ fn compact_examples_run_verbatim_from_the_docs() { } } +/// The mutation tools return the layers they touched; with `fields` or `outline` that echo is cut +/// down to what the agent asked for, and without them it stays complete. +#[test] +fn mutation_results_take_fields_and_outline() { + let mut c = Client::new(); + let card = json!({"type": "frame", "name": "Card", "width": 280, "height": 160, "props": {"fill": "#F0F0F0", "cornerRadius": 12}}); + let full = c.ok("create_node", card.clone()); + let mut args = card.clone(); + args["fields"] = json!(["name"]); + let picked = c.ok("create_node", args); + compact_keys(&picked["node"], false); + assert_eq!(picked["node"]["name"], "Card"); + assert!(picked.to_string().len() < full.to_string().len(), "{picked} vs {full}"); + let mut args = card; + args["outline"] = json!(true); + let outlined = c.ok("create_node", args); + compact_keys(&outlined["node"], true); + assert_eq!(outlined["node"]["type"], full["node"]["type"]); + + let ids = json!([full["id"], picked["id"], outlined["id"]]); + let set = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 0.5}})); + let slim = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 0.4}, "fields": ["opacity"]})); + let (set, slim) = (set["nodes"].as_array().unwrap(), slim["nodes"].as_array().unwrap()); + assert_eq!(slim.len(), set.len(), "every layer is still reported"); + for (whole, cut) in set.iter().zip(slim) { + assert_eq!(cut["id"], whole["id"]); + assert!(cut["opacity"].as_f64().is_some_and(|o| (o - 0.4).abs() < 1e-6), "{cut}"); + assert!(cut.as_object().unwrap().len() < whole.as_object().unwrap().len(), "{cut} vs {whole}"); + } + let outlined = c.ok("set_properties", json!({"ids": ids, "props": {"opacity": 1}, "outline": true})); + for node in outlined["nodes"].as_array().unwrap() { + compact_keys(node, true); + } +} + +/// A bad option is caught before the edit runs: the call fails and the document is as it was. +#[test] +fn a_bad_option_on_a_mutation_changes_nothing() { + let mut c = Client::new(); + let id = c.create(json!({"type": "rectangle", "name": "Keep"})); + let before = c.doc(); + for bad in [json!({"fields": ["Name"]}), json!({"outline": true, "fields": []}), json!({"outline": "yes"})] { + let mut create = json!({"type": "ellipse", "name": "Extra"}); + let mut set = json!({"ids": [id], "props": {"name": "Changed"}}); + for (k, v) in bad.as_object().unwrap() { + create[k] = v.clone(); + set[k] = v.clone(); + } + assert!(!c.err("create_node", create).is_empty()); + assert!(!c.err("set_properties", set).is_empty()); + } + let after = c.doc(); + assert_eq!(after["pages"], before["pages"], "a rejected call left the layers as they were"); +} + #[test] fn invalid_compact_options_fail_in_tools_and_headless_control() { let mut c = Client::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 4d99c752d..d245e437a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -437,8 +437,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `list_commands {filter?}` | Every command: id, label, menu, shortcut, undoable, params doc. | | `run_command {command, params}` | Run any command (e.g. `align.left`, `layout.add`, `component.create`, `instance.place` (drop an instance at a page point into the frame or auto layout slot under it), `component.exposeInstance` / `instance.exposed` (nested instance properties on instances), `component.makeSlot` / `instance.slotInsert` / `instance.resetSlot` (slots, below), `inspect.code` (CSS, HTML + CSS for a whole frame, React, Leptos, Vue, SwiftUI, Jetpack Compose, ArkUI or Flutter for a layer; components take their properties as parameters and instances are calls, see Developer Mode below), `inspect.properties` (layout, auto layout, typography, fills, strokes and effects with their style and variable names; `colorFormat`: hex, rgb, css, hsl or hsb), `inspect.assets` (layers under the selection with export settings, icons and images, each with its `kind`), `inspect.code` takes `unit: rem` and `rootFontSize` for CSS, HTML, React, Leptos and Vue, `style.create`, `variable.bind`, `variable.update` (rename, describe, scope), `variable.set` with `{alias}` or a colour calculation (`{alpha}`, `{mix}`), `variable.renameMode` / `variable.removeMode`, `variable.deleteCollection`, `proto.interaction.add`, `codeConnect.set` (components linked to real code, see Developer Mode below)). | | `batch {commands: [{command, params}], label?}` | Several commands as one undo step (`command.batch`), which keeps one copy of the document however many steps there are (an `edit.undo` step undoes the batch's edits so far together); all-or-nothing for open documents and their document state. Failed inner commands are removed from the journal; preferences, clipboard, tool state and UI requests are not rolled back. A step can use what an earlier step returned: name it with `"as": "card"` and `{"$ref": "card"}` anywhere in a later step's params becomes the `id` in its result (`{"$step": n}` does the same by zero-based position); `"field"` takes another key or a slash path such as `ids/0` (see Step references below). | -| `create_node {type, x, y, width, height, parent, index, name, text, path, props}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. | -| `set_properties {ids, props}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers. | +| `create_node {type, x, y, width, height, parent, index, name, text, path, props, fields?, outline?}` | Create a frame, rectangle, ellipse, polygon, star, line, arrow, text, vector, section, component or slice; returns `{id, node}`. `warnings` reports a fontStyle that draws in another face. `fields` / `outline` shrink `node` as they do for `get_node`; a bad option is an error and creates nothing. | +| `set_properties {ids, props, fields?, outline?}` | `node.set` on layers (geometry, fills, strokes, effects, corner radius, auto layout, sizing, constraints, masks (`isMask`, `maskType: alpha\|vector\|luminance`), handoff status (`devStatus: none\|readyForDev\|completed`; marking again clears "Changed"), a section's `sectionContentsHidden`, text…); returns the updated layers (up to 20), which `fields` / `outline` shrink as they do for `get_node`; a bad option is an error and sets nothing. | | `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). | | `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. | | `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). | diff --git a/docs/roadmap.md b/docs/roadmap.md index 389ef400f..060b4d3c4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | Smaller mutation results (M0.9, #2535): `create_node` and `set_properties` take the same `fields` and `outline` options as `get_node`, so the layers they return can be cut to the keys an agent needs. A bad option is rejected before the edit runs, and without either option the result is unchanged. | | 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | | 2026-11-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. | | 2026-11-19 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. `board.codeBlock` places a dark panel of monospace text as tall as its lines, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it; the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. Numbers unchanged. | From 406e71f1823bec2e57fa4889f1eb7f13b476533f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 15:45:43 +0700 Subject: [PATCH 08/38] Copied properties keep a corner style: it isn't a link to a shared style --- crates/engine/src/cmd/edit/clipboard.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index da31dded7..ee96cb8df 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -580,7 +580,8 @@ pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, prop // values it gave are pasted without a link, so the layer's own link goes too. let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some()); for (k, v) in m.iter_mut() { - if k.ends_with("Style") && !k.starts_with("font") && !here(v) { + // `cornerStyle` is a value (round, chamfer, concave), not a link to a shared style. + if k.ends_with("Style") && !k.starts_with("font") && k != "cornerStyle" && !here(v) { *v = Value::Null; } } From 031d726da145860a6bdf4d224daa491fef43d17e Mon Sep 17 00:00:00 2001 From: B-uchi Date: Sat, 28 Nov 2026 09:17:52 +0100 Subject: [PATCH 09/38] M8: an MCP prompt takes an agent through building the selected design The developer tools were all there, but nothing said how they fit together: an agent had to find out from each description that design_context reads the whole page when nothing is selected, that export_assets needs a dir, that annotations come from annotation.list, and that a variable's codeSyntax is under variables. implement_design {destination?} gives the order: read the design (and ask which frame when nothing was selected), reuse connected components (asking before importing mappings, which changes the design), tokens and shared styles before literal values, explicit values as the specification and the platform's layout behind the derived ones, the files export_assets writes (again for what it left out), unsupported values approximated, missing and the tree's own annotations read, the other sizes' frames read, and the result checked with compare_design, one frame at a time, when a browser tool is available. Every step that can come up short says to ask or to report it, never to present it as done. The server instructions name it beside fix_comments and design_review. --- crates/mcp/src/prompts.rs | 26 ++++++++++++++++++++++++++ crates/mcp/src/server.rs | 2 +- crates/mcp/tests/it/protocol.rs | 5 ++++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 50a1440b4..3108dcc13 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -117,6 +117,32 @@ pub const PROMPTS: &[PromptDef] = &[ 4. Stop after {minutes} minutes; summarize the threads you fixed and the ones still open (and why)."#, defaults: &[("minutes", "5")], }, + PromptDef { + name: "implement_design", + title: "Implement the selected design", + description: "Build the design selected in FigCraft in this codebase from its stated values, real assets and connected components, then check the result against the design.", + args: &[PromptArg { + name: "destination", + description: "Where it goes in the code, e.g. a route or a component (default: ask if it isn't clear)", + required: false, + }], + template: r#"Implement the design selected in FigCraft in this codebase. Destination: {destination}. + +Paths you pass are absolute, or relative to where the FigCraft MCP server runs, which may not be this project; they must be inside its automation roots when it has them. + +1. Read the design with design_context {}. Check `target` first: if its `source` is `page`, nothing was selected and you have the whole page, so ask the designer which frame to build unless the whole page is meant. Where the tree stops, a layer has `childCount` instead of `children`; if the result has `truncated`, call design_context again with the `ids` of the parts you need. +2. Learn the project before writing code: its components, styling, tokens and where files go. +3. Reuse code that exists. A layer with `code` is connected to a code component: write its `code` snippet with its `importPath`, follow its `notes`, and don't build its children. component_mappings {"unmapped": true} lists the design's components with no code component yet: search the project for each before creating one. If the project has a figcraft.connect.json with mappings component_mappings doesn't show, ask the designer before running sync_mappings {"direction": "import"}: it changes the design (one undo step). +4. Use tokens over literal values. A layer's `tokens` name the variables and shared styles it uses: for a variable, use its `codeSyntax` from `variables` when it has one, else the project's matching token; for a style, the project's style of that `name`. Fall back to the resolved value only when the project has neither. +5. Treat `explicit` values as the specification. `derived` values are what layout worked out at this size: build the layout that produces them with the platform's own layout (flex or grid on the web, stacks natively), filling and hugging as the design does, instead of hard-coding them. +6. Bring in the real assets: export_assets {"ids": , "dir": ""} writes them as files and lists each one. Use those files, never screenshots or redrawn stand-ins. An asset whose `source` is `rendered` isn't the original image, each entry in its `adjustments` still has to be applied in code, and `skipped` says what couldn't be handed over. If the result has `truncated`, call export_assets again with the `ids` of the parts it left out. Fonts aren't exported: `fonts` lists them, and the project has to provide each one and check its licence. +7. For each `unsupported` entry, get as close as the platform allows and list it in your report. Never drop one silently. +8. Read what the design leaves open: `missing`, and the designer's annotations from run_command {"command": "annotation.list", "params": {"page": }}, keeping those whose `id` is a layer in the tree: the rest belong to other designs. Don't invent behaviour the design doesn't state: ask, or report what you assumed. +9. For other screen sizes, follow `responsive`: its `versions` group the designs of one screen at each size, and its `rules` are the designer's instructions. Read the other sizes' `frames` with design_context {"ids": [...]} before building them. When its `explicit` is false the file states no breakpoints: keep to what constraints, sizing and annotations say, and say so instead of inventing breakpoints. +10. If a browser tool is available and the app runs, check the result. Size the browser to the frame's width and height in CSS pixels, capture the page to a file inside the project, and call compare_design {"id": , "image": ""}, one frame at a time; each result repeats the size as `viewport`. Fix the layers in `differences` and repeat. An empty list means no layer differs on 2% or more of its pixels, not that every pixel matches. Delete the captures afterwards. Without a browser tool, say the result wasn't checked against the design. +11. Finish with a report: the files you changed, the components you reused and created, what you approximated, what you assumed, what the design left missing, and whether the result was compared with the design."#, + defaults: &[("destination", "ask if it isn't clear")], + }, ]; pub fn list() -> Value { diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 931dfb1fe..08c4e9d08 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -56,7 +56,7 @@ with severities; design.fix repairs the fixable ones as one undo step; design.ru presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \ design.assert {failOn, minScore} is a read-only CI gate. \ Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \ -prompts/list has workflows, including fix_comments and design_review."; +prompts/list has workflows, including fix_comments, design_review and implement_design (build the selected design in a codebase)."; /// An MCP server bound to one backend. pub struct Server { diff --git a/crates/mcp/tests/it/protocol.rs b/crates/mcp/tests/it/protocol.rs index e6acd7cb1..35dac8490 100644 --- a/crates/mcp/tests/it/protocol.rs +++ b/crates/mcp/tests/it/protocol.rs @@ -219,7 +219,10 @@ fn prompts_list_and_get() { let mut c = Client::new(); let r = c.rpc("prompts/list", json!({})); let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]); + assert_eq!( + names, + ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments", "implement_design"] + ); let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}})); let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}")); From 6e121726675bad17e32041aa9f2d1393504e3576 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Sat, 28 Nov 2026 09:17:52 +0100 Subject: [PATCH 10/38] docs: implement_design in the MCP guide and the ROADMAP A row in the Prompts table, a short "Building from a design" section after visual verification saying which tools the prompt uses, and the ROADMAP row. --- ROADMAP.md | 1 + docs/mcp.md | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index f581f7313..08827c069 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | M8: the MCP prompt `implement_design` takes an agent through building the selected design in a codebase: `design_context` for what the designer set, connected components reused through `component_mappings` and `sync_mappings`, tokens before literal values, real files from `export_assets`, the annotations and `responsive` for what the design states beyond its size, and `compare_design` to check the result. With nothing selected it asks which frame to build, and it reports what it approximated, assumed or couldn't check. A test now checks that every tool and result field the server instructions and prompts name exists, as one already did for command ids. Numbers unchanged | | 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. | | 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | | 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 1f78433a1..35358f49d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -525,6 +525,15 @@ Images are compared at up to 2,000 pixels a side, the larger of the frame and th the scale. Each layer claims the pixels it draws on, so a see-through part of a shape leaves a difference to the layer under it. +### Building from a design + +The `implement_design` prompt takes an agent through building the selected design in a codebase with +these tools: `design_context` for what the designer set, `component_mappings` and `sync_mappings` to +reuse connected components, `export_assets` for the files, the annotations and `responsive` for what +the design states beyond its size, and `compare_design` to check the result. It tells the agent to +ask when nothing is selected and before changing the design, and to report what it approximated, +assumed or couldn't check instead of presenting it as done. + ### Compact layer trees `inspect_document` and `get_node` accept `fields`, an array of exact, case-sensitive top-level node @@ -2309,6 +2318,7 @@ A name a tool or command doesn't take (`run_command {args}` for `params`, a step | `prototype_flow` | `screens` (comma-separated), `transition` | | `fix_comments` | `page` (default "all"), `auto_resolve` (default "yes"), `author` (default "AI") | | `watch_comments` | `minutes` (default 5) | +| `implement_design` | `destination`: where it goes in the code (default: ask if it isn't clear) | Each returns a step-by-step plan naming the exact tools and commands to use and how to verify. From 7b2bb13b363fb7d1564a7f4f4d8c04d133b006e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:20:58 +0000 Subject: [PATCH 11/38] mcp: mutation results skip the unused wire-size pass create_node and set_properties fetched their layers through node_at, which also serializes each one to measure it for the read tools' budgets. The mutation tools threw that size away, so they now fetch through node_get, which only reads the layer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KudydNWQDXESHDpVmpiqZh --- crates/mcp/src/tools.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index db56f3863..8ecb1559d 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -857,7 +857,7 @@ fn create_node(b: &mut dyn Backend, a: &Map) -> Result) -> Result = ids.iter().take(20).filter_map(|&i| node_at(b, i, 0, &options).ok().map(|(v, _)| v)).collect(); + let nodes: Vec = ids.iter().take(20).filter_map(|&i| node_get(b, i, 0, &options).ok()).collect(); let mut out = json!({"ok": true, "nodes": nodes}); if let Some(w) = warnings { out["warnings"] = w; @@ -952,12 +952,17 @@ fn inspect_at(b: &mut dyn Backend, depth: u64, all: bool, options: &Value) -> Re Ok((value, wire)) } -/// One layer's subtree at `depth`, and what its text block would take on the wire. -fn node_at(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result<(Value, usize), String> { +/// One layer's subtree at `depth`, with the `fields` / `outline` options applied. +fn node_get(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result { let mut params = options.clone(); params["id"] = json!(id); params["depth"] = json!(depth); - let value = b.call("node.get", params)?; + b.call("node.get", params) +} + +/// One layer's subtree at `depth`, and what its text block would take on the wire. +fn node_at(b: &mut dyn Backend, id: u64, depth: u64, options: &Value) -> Result<(Value, usize), String> { + let value = node_get(b, id, depth, options)?; let wire = wire_size(&value); Ok((value, wire)) } From 6a14526181efb28c8d719e4df1d9980a46c849d6 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Sat, 28 Nov 2026 10:27:21 +0100 Subject: [PATCH 12/38] docs: the Prompts table lists design_review The design_review prompt came with the design review commands (#2194), but the Prompts table in docs/mcp.md never listed it, so the table showed six of the seven prompts. It now has a row, in prompts/list order, with its one argument. --- docs/mcp.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/mcp.md b/docs/mcp.md index 1f78433a1..aabcb8767 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2306,6 +2306,7 @@ A name a tool or command doesn't take (`run_command {args}` for `params`, a step | `mobile_screen` | `screen` (required), `device` (default "iPhone 16"), `brand_color` | | `design_system` | `name`, `primary` | | `landing_page` | `product` (required), `width` (default 1440), `accent` | +| `design_review` | `target`: selection, page or document (default "page") | | `prototype_flow` | `screens` (comma-separated), `transition` | | `fix_comments` | `page` (default "all"), `auto_resolve` (default "yes"), `author` (default "AI") | | `watch_comments` | `minutes` (default 5) | From 71d9f20c31cedd03c28d4a6639134d6cd0711324 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:28:33 -0700 Subject: [PATCH 13/38] M1, #2264: Windows doesn't start OpenGL beside Direct3D 12 Switching the input language on Windows (Alt+Shift or Win+Space to a Russian layout) or typing in it hung the app. A Windows start offered wgpu Direct3D 12 and OpenGL together, and wgpu's OpenGL backend makes a hidden window on a thread that handles no window messages as soon as its instance exists, even when Direct3D 12 draws. Windows hands the language change to every thread with a window, so the main window waited on that hidden one. The reporter confirmed WGPU_BACKEND=dx12 avoids it. A Windows start now offers Direct3D 12 alone. Vulkan and OpenGL stay as restarts after a failed start, each on its own, and OpenGL with lower limits is added last so the old lowered Direct3D 12 + OpenGL attempt's reach is kept. A GPU with no Direct3D 12 driver (Intel Haswell, which wgpu leaves out of Direct3D 12, and older GPUs) now draws on Direct3D 12's software adapter instead of its OpenGL driver. Not run on Windows; the attempt list is tested. Co-Authored-By: Claude Opus 5.5 --- apps/figcraft/src/graphics.rs | 29 ++++++++++++++++++++++------- apps/figcraft/src/graphics_tests.rs | 20 +++++++++++++++----- docs/hardware-parity.md | 3 ++- 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/apps/figcraft/src/graphics.rs b/apps/figcraft/src/graphics.rs index ec727acc1..c658409cb 100644 --- a/apps/figcraft/src/graphics.rs +++ b/apps/figcraft/src/graphics.rs @@ -4,7 +4,15 @@ //! first, on Windows too. A Vulkan driver that faults there takes the app down as the window opens: //! an access violation inside the vendor's driver, which no guard of ours can catch (seen on a laptop //! with two AMD GPUs whose drivers were years apart). Direct3D 12 is part of Windows, so on Windows -//! wgpu is offered Direct3D 12, and OpenGL for hardware without a Direct3D 12 driver. +//! wgpu is offered Direct3D 12 alone at first. +//! +//! Not OpenGL beside it: wgpu's OpenGL backend on Windows makes a hidden window on a thread of its +//! own that handles no window messages, as soon as the instance is created, whichever backend then +//! draws. Windows hands an input language change (Alt+Shift or Win+Space to a Russian layout, +//! #2264) to every thread of the app with a window, so the main window waited on that hidden one +//! and the app hung. Direct3D 12 always lists its software adapter (WARP), so a GPU with no +//! Direct3D 12 driver (Intel Haswell, which wgpu leaves out of Direct3D 12, and older ones) now +//! draws on WARP rather than on its OpenGL driver. //! //! Two shader compilers lost the device before the window opened ("Parent device is lost", #965, //! #1438), both on wgpu's indirect-call validation shaders, which wgpu compiles with every device: @@ -14,10 +22,12 @@ //! out: FigCraft draws nothing indirectly, so they would check nothing. //! //! When the graphics still fail before the window's first frame, the app starts again with the -//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; and last the first +//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; then the first //! backends again with lower requirements on the power-saving GPU (macOS has no OpenGL in wgpu, so -//! that is its only other try). The attempts are a fixed list, so this ends; the message the last -//! one shows names what was tried. +//! that is its only other try); and on Windows last OpenGL with lower requirements, each on its own +//! so that OpenGL starts only when Direct3D 12 failed. An OpenGL start on Windows can still hang on +//! an input language change. The attempts are a fixed list, so this ends; the message the last one +//! shows names what was tried. //! //! `WGPU_BACKEND` (`dx12`, `vulkan`, `gl`, `metal`) still names the backend on every system, and //! is then the one attempt. `WGPU_DX12_COMPILER` and `WGPU_VALIDATION_INDIRECT_CALL` still choose @@ -36,8 +46,9 @@ pub const ATTEMPT_ENV: &str = "FIGCRAFT_GRAPHICS_ATTEMPT"; /// begins once the first was presented. pub const STARTUP_FRAMES: u64 = 2; -/// Direct3D 12, then OpenGL: wgpu ranks a hardware GPU on either ahead of Direct3D's software one. -const WINDOWS: Backends = Backends::DX12.union(Backends::GL); +/// Direct3D 12 alone: an OpenGL instance beside it hangs the window on an input language change +/// (see the module docs). +const WINDOWS: Backends = Backends::DX12; /// The graphics APIs by name, in the order the startup message lists them. const NAMES: [(Backends, &str); 4] = @@ -54,7 +65,8 @@ pub struct Attempt { /// The ways to start, in order: only `WGPU_BACKEND`'s backends (`requested`) when it is set; /// otherwise [`WINDOWS`] on Windows, else eframe's `defaults`, then Vulkan on Windows, OpenGL -/// except on macOS, and those first backends again with lower requirements. +/// except on macOS, those first backends again with lower requirements, and on Windows OpenGL with +/// lower requirements. pub fn attempts(requested: Option, windows: bool, macos: bool, defaults: Backends) -> Vec { let normal = |backends| Attempt { backends, lower: false }; if let Some(requested) = requested { @@ -69,6 +81,9 @@ pub fn attempts(requested: Option, windows: bool, macos: bool, default list.push(normal(Backends::GL)); } list.push(Attempt { backends: first, lower: true }); + if windows { + list.push(Attempt { backends: Backends::GL, lower: true }); + } list } diff --git a/apps/figcraft/src/graphics_tests.rs b/apps/figcraft/src/graphics_tests.rs index 62d79de90..8c93e02b0 100644 --- a/apps/figcraft/src/graphics_tests.rs +++ b/apps/figcraft/src/graphics_tests.rs @@ -1,6 +1,7 @@ //! The graphics attempts: no Vulkan on Windows at first (a faulting Vulkan driver crashed the app -//! as its window opened), another backend and then lower requirements when the graphics fail -//! before the first frame (#965, #1438), and never more starts than attempts. +//! as its window opened), never OpenGL beside Direct3D 12 there (its hidden window hung the app on +//! an input language change, #2264), another backend and then lower requirements when the graphics +//! fail before the first frame (#965, #1438), and never more starts than attempts. use std::time::Duration; @@ -13,8 +14,6 @@ use crate::graphics::{ATTEMPT_ENV, Attempt, Plan, STARTUP_FRAMES, apply, attempt /// What eframe offers when `WGPU_BACKEND` isn't set. const DEFAULTS: Backends = Backends::PRIMARY.union(Backends::GL); -const DX12_GL: Backends = Backends::DX12.union(Backends::GL); - const fn normal(backends: Backends) -> Attempt { Attempt { backends, lower: false } } @@ -26,10 +25,21 @@ const fn lower(backends: Backends) -> Attempt { #[test] fn windows_starts_on_direct3d_then_vulkan_then_opengl_then_lower_requirements() { let list = attempts(None, true, false, DEFAULTS); - assert_eq!(list, [normal(DX12_GL), normal(Backends::VULKAN), normal(Backends::GL), lower(DX12_GL)]); + assert_eq!(list, [normal(Backends::DX12), normal(Backends::VULKAN), normal(Backends::GL), lower(Backends::DX12), lower(Backends::GL)]); assert!(!list[0].backends.contains(Backends::VULKAN), "a Vulkan driver that faults can't be picked at first"); } +#[test] +fn windows_never_starts_opengl_beside_direct3d_but_still_falls_back_to_it() { + let list = attempts(None, true, false, DEFAULTS); + for attempt in &list { + assert!(!attempt.backends.contains(Backends::DX12 | Backends::GL), "OpenGL's hidden window hangs a Direct3D 12 start: {attempt:?}"); + } + assert!(list.iter().any(|a| a.backends.contains(Backends::VULKAN)), "Vulkan is still tried"); + assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && !a.lower), "OpenGL is still tried"); + assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && a.lower), "and with lower requirements"); +} + #[test] fn linux_falls_back_to_opengl_then_lower_requirements() { assert_eq!(attempts(None, false, false, DEFAULTS), [normal(DEFAULTS), normal(Backends::GL), lower(DEFAULTS)]); diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 674ee0350..1dea3b03b 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -40,7 +40,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Platform | Figma | FigCraft | Notes | |---|---|---|---| | macOS | desktop app (Intel and Apple silicon) | universal `.dmg`, signed and notarized (v0.2.0) | where nearly all QA happens. Quitting ends the process once the preferences, recovery copies and live sessions are taken care of: the window's teardown crashed on Macs with a Touch Bar (#781); the Quit menu and ⌘Q ask about unsaved changes like the main window's close button (#857), and like it close the main window only: with several windows open, each quit closes one; a quit that never asked — killed or crashed — still leaves recovery copies for the next start | -| Windows x64 / arm64 | desktop app | `.msi` and portable zip for x64, x86 and arm64 | built in CI; Windows: QA pass done 2026-10-11, findings in PR. The portable zip keeps its settings in `config\` beside `figcraft.exe` (a `portable` file there), taking an installed copy's preferences on its first start (#1320). Draws with Direct3D 12 (FXC shaders) or OpenGL; when the graphics fail before the first frame it starts again on Vulkan, then OpenGL, then the power-saving GPU with lower limits (#965) | +| Windows x64 / arm64 | desktop app | `.msi` and portable zip for x64, x86 and arm64 | built in CI; Windows: QA pass done 2026-10-11, findings in PR. The portable zip keeps its settings in `config\` beside `figcraft.exe` (a `portable` file there), taking an installed copy's preferences on its first start (#1320). Draws with Direct3D 12 (FXC shaders), on its software adapter (WARP) where the GPU has no Direct3D 12 driver; when the graphics fail before the first frame it starts again on Vulkan, then OpenGL, then the power-saving GPU with lower limits, then OpenGL with lower limits (#965). OpenGL is not started beside Direct3D 12: its hidden window hung the app on an input language change (#2264) | | Linux | none (browser only) | AppImage, `.deb`, `.rpm`, Flatpak, tarball, x86_64 and aarch64; riscv64 tarball | CI tests run here. Clipboard (also the BSDs): reads run on a helper thread that gives up after 2 s, and images copied in other apps paste under Wayland through the data-control protocol (#693). Under Wayland the app can't tell its window is minimised: a window that draws nothing for 0.2 s while a control request waits for it answers the request as a hidden window does (about half a second each, #1906), and only requests that need a drawn frame (screenshots, input) wait there (#720). None of this run on a Linux desktop here. On a Wayland compositor without server-side decorations (GNOME) the window gets winit's Adwaita controls (#592: checked by its author in a GNOME Wayland session; KDE not run) | | FreeBSD | none | tarball | | | Web | primary (figma.com) | `figcraft-web` (WASM, WebGPU/WebGL2), web zip | no accessibility tree; file access through the browser; copy and paste through the system clipboard (copies written from the copy event, pastes read from the paste event, its text or an image copied in another app); an internal error stops the page (a panic can't be caught there), but its unsaved files are kept in the page's local storage (about 5 MB) and open again on reload (#1123) | @@ -50,6 +50,7 @@ Nothing has been timed against Figma on the same document (needs `.fig` import). | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M1, #2264: Windows: switching the input language (Alt+Shift or Win+Space to a Russian layout) or typing in it hung the app. A Windows start offered wgpu Direct3D 12 and OpenGL together, and wgpu's OpenGL backend makes a hidden window on a thread that handles no window messages as soon as its instance exists, even when Direct3D 12 draws; Windows hands the language change to every thread with a window, so the main window waited on it. A Windows start now offers Direct3D 12 alone; Vulkan, OpenGL and OpenGL with lower limits stay as restarts after a failed start (`apps/figcraft/src/graphics.rs`). A GPU with no Direct3D 12 driver (Intel Haswell, older GPUs) now draws on Direct3D 12's software adapter instead of its OpenGL driver. `WGPU_BACKEND=gl` still has the hang. Not run on Windows: the attempt list is tested (`graphics_tests`), the hang itself needs a live check. Numbers unchanged | | 2026-11-10 | minor | Zoom in without coarse previews (#312 follow-up): a zoom in to at most 4× the image on screen, inside the area it covers, shows that image enlarged until the refined one comes, measured from what the screen shows, a preview included; it is at least as sharp as a preview with a quarter of the pixels each way. During a pinch or a held zoom each step used to get a preview and drop its refined image for the next step's, so the canvas stayed coarse until the zoom stopped. Zoom outs, other pages and larger zoom ins still get previews. | | 2026-11-24 | minor | M8: drop shadows of opaque shapes and frames are cast from their outline, drawn where they show and blurred at the resolution their radius needs: a card with a 16 px shadow at 1,933% on a 2× display renders in 152 ms (8 bands, one thread) where it took 4,576 ms. Tests: `outline_shadow_tests`; timings: `zoomed_card_timings`. Numbers unchanged | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | From b33b75275cbd232cbc3f876e0d265efb6e95cd8f Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:44:20 -0700 Subject: [PATCH 14/38] M9: open a full snapshot without copying it first (#2041) Replica::from_snapshot borrowed the changes and cloned the whole Vec before applying it, because the review-settings clamp rewrites some of them in place. Every caller already owns the snapshot (Client::join, the rejoin path, Server::restore), so it now takes the Vec by value: a large file's snapshot is no longer copied and then dropped twice on the way in. The server's publish path still borrows and copies explicitly. In a wasm32 build joining a 120k-layer file through the full-snapshot catch-up (what an older server sends), this cut peak memory from 722 MiB to 455 MiB. Co-Authored-By: Claude Opus 5.5 --- apps/figcraft-server/src/store/files.rs | 2 +- crates/collab-net/src/loopback_tests.rs | 2 +- crates/collab/src/board_sync_tests.rs | 2 +- crates/collab/src/client.rs | 4 ++-- crates/collab/src/delta_snapshot_tests.rs | 4 ++-- crates/collab/src/diff_tests.rs | 8 ++++---- crates/collab/src/image_tests.rs | 4 ++-- crates/collab/src/packed_welcome_tests.rs | 2 +- crates/collab/src/replica.rs | 9 +++++---- crates/collab/src/server.rs | 2 +- crates/engine/src/collab_tests.rs | 2 +- 11 files changed, 21 insertions(+), 20 deletions(-) diff --git a/apps/figcraft-server/src/store/files.rs b/apps/figcraft-server/src/store/files.rs index fcc0fd109..8db73d063 100644 --- a/apps/figcraft-server/src/store/files.rs +++ b/apps/figcraft-server/src/store/files.rs @@ -90,7 +90,7 @@ impl Store { if let Some(why) = self.low_disk() { return Err(why); } - let replica = Replica::from_snapshot(snapshot).map_err(|e| format!("the file couldn't be read: {e}"))?; + let replica = Replica::from_snapshot(snapshot.to_vec()).map_err(|e| format!("the file couldn't be read: {e}"))?; if replica.document().node_count() > self.cfg.core.max_nodes { return Err(format!("the file has more than {} layers", self.cfg.core.max_nodes)); } diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs index 48b19549d..aa4a8776d 100644 --- a/crates/collab-net/src/loopback_tests.rs +++ b/crates/collab-net/src/loopback_tests.rs @@ -687,7 +687,7 @@ fn welcomes_are_packed_only_for_clients_that_read_them() { }; message::unpack(&mut delta_welcome, 64 << 20).unwrap(); let delta_doc = Client::join(delta_welcome).unwrap().document().clone(); - let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone(); + let plain_doc = figcraft_collab::Replica::from_snapshot(plain).unwrap().document().clone(); assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document"); host.stop(); } diff --git a/crates/collab/src/board_sync_tests.rs b/crates/collab/src/board_sync_tests.rs index 442388477..5f0d09c37 100644 --- a/crates/collab/src/board_sync_tests.rs +++ b/crates/collab/src/board_sync_tests.rs @@ -18,7 +18,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() { // A joiner's copy, built from the snapshot, is a board with the sticky's metadata. let snap = host.snapshot().unwrap(); assert!(snap.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Kind, .. }))); - let joiner = Replica::from_snapshot(&snap).unwrap(); + let joiner = Replica::from_snapshot(snap).unwrap(); assert_eq!(joiner.document().kind, FileKind::Board); assert_eq!(joiner.document().node(a).unwrap().board, host.document().node(a).unwrap().board); // Re-attaching a connector's end is one property write, the same after the wire. diff --git a/crates/collab/src/client.rs b/crates/collab/src/client.rs index ba1c3b44c..2124a131e 100644 --- a/crates/collab/src/client.rs +++ b/crates/collab/src/client.rs @@ -90,7 +90,7 @@ impl Client { return Err(Error::Protocol("expected a welcome with the document".into())); }; let mut confirmed = match catch_up { - CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?, + CatchUp::Snapshot(snapshot) => Replica::from_snapshot(snapshot)?, CatchUp::DeltaSnapshot(bytes) => { let limits = crate::Limits::default(); crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)? @@ -604,7 +604,7 @@ impl Client { } } CatchUp::Snapshot(snapshot) => { - let mut confirmed = Replica::from_snapshot(&snapshot)?; + let mut confirmed = Replica::from_snapshot(snapshot)?; confirmed.document_mut().set_client_id(self.id); self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?; } diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index b6f96da99..81e4d2280 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -163,7 +163,7 @@ fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() { let replica = Replica::new(doc); let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap(); - let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap(); + let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap(); assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality"); assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity"); } @@ -311,7 +311,7 @@ fn full_metadata_and_design_review_roundtrip_matches_legacy_json() { doc.take_dirty(); let replica = Replica::new(doc); - let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap(); + let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap(); let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap(); assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII); assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity"); diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 32edaba7c..481a53153 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -77,7 +77,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: // the preset, grid and disabled rules exactly as saved, the lists to the limit. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap(); assert!(clamped, "the settings needed clamping, and the caller is told"); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; @@ -99,7 +99,7 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); // A snapshot with a longer list opens with the ones that fit, not without the settings. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap(); assert!(clamped); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; @@ -232,9 +232,9 @@ fn snapshots_rebuild_the_same_state() { b.styles.push(style("s")); let r = diff(&a, &b).unwrap().replica; let snap = r.snapshot().unwrap(); - let back = Replica::from_snapshot(&snap).unwrap(); + let back = Replica::from_snapshot(snap).unwrap(); assert_eq!(back, r); - assert!(Replica::from_snapshot(&[]).is_err(), "a snapshot needs a page"); + assert!(Replica::from_snapshot(Vec::new()).is_err(), "a snapshot needs a page"); } #[test] diff --git a/crates/collab/src/image_tests.rs b/crates/collab/src/image_tests.rs index 9588a68c6..262ed7ab7 100644 --- a/crates/collab/src/image_tests.rs +++ b/crates/collab/src/image_tests.rs @@ -169,7 +169,7 @@ fn a_snapshot_holding_an_image_the_checks_refuse_still_opens_without_it() { let mut snapshot = crate::Replica::new(crate::sim_tests::base()).snapshot().unwrap(); let (key, bytes) = forged(); snapshot.push(put(&key, 2, 1, bytes)); - let r = crate::Replica::from_snapshot(&snapshot).expect("the snapshot opens"); + let r = crate::Replica::from_snapshot(snapshot).expect("the snapshot opens"); assert!(!r.document().images.contains_key(&key)); } @@ -254,5 +254,5 @@ fn a_snapshot_with_a_broken_layer_change_still_fails_to_open() { // A property of a layer that isn't there: an error when applied (unlike deleting it). let missing = figcraft_doc::NodeId(u64::MAX); snapshot.push(Change::Set { id: missing, prop: crate::change::Prop::Name, value: Json(json!("x")) }); - assert!(crate::Replica::from_snapshot(&snapshot).is_err()); + assert!(crate::Replica::from_snapshot(snapshot).is_err()); } diff --git a/crates/collab/src/packed_welcome_tests.rs b/crates/collab/src/packed_welcome_tests.rs index d8c48bcc7..2859ea757 100644 --- a/crates/collab/src/packed_welcome_tests.rs +++ b/crates/collab/src/packed_welcome_tests.rs @@ -57,7 +57,7 @@ fn a_packed_welcome_is_much_smaller_and_reads_back_the_same() { assert_eq!(back, plain); // The client opens the same document from it. let ServerMsg::Welcome { catch_up: CatchUp::Snapshot(changes), .. } = &plain else { panic!("not a snapshot") }; - assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes).unwrap().document()); + assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes.clone()).unwrap().document()); } #[test] diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 2c49fb0e8..1e3f0a4a3 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -70,8 +70,10 @@ impl Replica { Replica { doc, positions } } - /// Rebuild a replica from a [`snapshot`](Self::snapshot). - pub fn from_snapshot(changes: &[Change]) -> Result { + /// Rebuild a replica from a [`snapshot`](Self::snapshot). It takes the changes, so a large + /// file's snapshot isn't copied on the way in (#2041): the few that need it (review settings + /// past the limits) are rewritten in place. + pub fn from_snapshot(changes: Vec) -> Result { Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r) } @@ -81,9 +83,8 @@ impl Replica { /// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened, /// because a session whose settings had to be clamped can no longer replay its saved batches /// for clients that resume (they hold the value past the limits). - pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> { + pub(crate) fn from_snapshot_leaving_out(mut changes: Vec) -> Result<(Replica, usize, bool), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; - let mut changes = changes.to_vec(); let clamped = docprops::clamp_snapshot_design_review(&mut changes); let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 0f2a648c8..628cfe27c 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -214,7 +214,7 @@ impl Server { /// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped /// (clients then catch up with a snapshot). pub fn restore(state: SessionState, token: impl Into, limits: Limits) -> Result { - let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?; + let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(state.snapshot)?; let mut server = Server::new(replica.document().clone(), token, limits); server.state = replica; server.session = state.session; diff --git a/crates/engine/src/collab_tests.rs b/crates/engine/src/collab_tests.rs index c4fa4f9d6..4ea5a28d6 100644 --- a/crates/engine/src/collab_tests.rs +++ b/crates/engine/src/collab_tests.rs @@ -114,7 +114,7 @@ fn every_command_edit_round_trips_through_its_changes() { replica = d.replica; } assert!(edits > 50, "seed {seed}: only {edits} edits"); - let back = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap(); + let back = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap(); assert_eq!(back, replica, "seed {seed}: snapshot"); } } From d1b4bc1023552fd2f28930f634b599382c5ce573 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:51:36 -0700 Subject: [PATCH 15/38] M9: grow the web heap in large steps while a snapshot is read (#2041) On wasm32-unknown-unknown, Rust's allocator (dlmalloc) grows the memory one 64 KiB page at a time whenever it runs out, and the browser changes the protection of the whole memory at each grow. The reporter's 121k-layer join made about 20,400 grows and spent 176 s of a 3-minute freeze in them on Windows. Memory dlmalloc got is reused once freed and never given back, so allocating one large block and freeing it at once leaves that much free room, for one grow. heap::keep_ahead does this whenever the memory grew since its last call: half the heap again, at most 256 MiB at a time. It acts only while a snapshot is read: a heap::reading() guard is held by the delta snapshot decode, by unpacking a packed welcome and by Replica::from_snapshot, and dropped on every exit path. Inside that window it runs between delta records and vectors, between changes in Replica::apply, and for each JSON value read from a full snapshot. The same hooks run for live batches, where they return at once. Off wasm32 they always return at once. All of it is safe code: a fallible reservation, then black_box so the optimizer keeps the allocation. Measured with Client::join on an encoded 120k-layer welcome, in a standalone wasm32 module under Node on macOS (three runs each, same window). The shipped figcraft-web build, Chrome and Windows were not measured: - delta catch-up: 607-616 ms -> 433-449 ms; the memory grew twice between hook calls, each followed by one reservation (the baseline grew by 3,800 pages, at most one grow each); peak memory 241 -> 308 MiB - full-snapshot catch-up (an older server): 3.6-3.9 s before the previous commit, 1.27 s after it, 407-417 ms with this one; 4 reservations; peak memory 455 -> 674 MiB against the previous commit (722 MiB before both) The extra peak memory is the room reserved ahead and not used. This covers the allocations inside the decode and apply. Opening the tab, the first layout and the first paint run outside every hook and were not measured. --initial-memory doesn't help: with the std that Rust 1.96 links, a probe still grew page by page above a 256 MiB initial memory. Co-Authored-By: Claude Opus 5.5 --- crates/collab/src/change.rs | 3 + crates/collab/src/delta_snapshot/decode.rs | 3 + crates/collab/src/heap.rs | 146 +++++++++++++++++++++ crates/collab/src/lib.rs | 1 + crates/collab/src/message.rs | 1 + crates/collab/src/replica.rs | 4 + 6 files changed, 158 insertions(+) create mode 100644 crates/collab/src/heap.rs diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 555ed3e33..3485629f3 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -45,6 +45,9 @@ impl<'de> Deserialize<'de> for Json { f.write_str("JSON text") } fn visit_str(self, v: &str) -> Result { + // A full snapshot holds one of these per property: while one is read, on the web + // the heap grows in large steps ([`crate::heap`]). + crate::heap::keep_ahead(); // serde_json caps nesting depth, so hostile input can't overflow the stack. serde_json::from_str(v).map(Json).map_err(E::custom) } diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index 512cde16e..39e88a8e3 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -40,6 +40,7 @@ pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) - /// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated /// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`. pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result { + let _reading = crate::heap::reading(); let declared = parse_header(bytes)?; if declared > max_bytes { return Err(Error::TooLarge(max_bytes)); @@ -280,6 +281,7 @@ impl<'de> Visitor<'de> for VectorsSeed<'_> { } self.0.vector_sizes.push(size); self.0.vectors.push(figcraft_doc::Shared::new(net)); + crate::heap::keep_ahead(); } Ok(()) } @@ -313,6 +315,7 @@ impl<'de> Visitor<'de> for RecordsSeed<'_> { if let Err(err) = self.0.ingest_record(rec) { return Err(self.0.fail(err)); } + crate::heap::keep_ahead(); } Ok(()) } diff --git a/crates/collab/src/heap.rs b/crates/collab/src/heap.rs new file mode 100644 index 000000000..5490ecf78 --- /dev/null +++ b/crates/collab/src/heap.rs @@ -0,0 +1,146 @@ +//! Room kept ahead in a web page's heap while a large file is read (#2041). +//! +//! The allocator Rust links on `wasm32-unknown-unknown` (dlmalloc) asks the page for more memory +//! one 64 KiB page at a time whenever it runs out, and the browser changes the protection of the +//! whole memory at every grow. Joining a 121k-layer file grew the heap by about 1.5 GB in about +//! 20,000 grows; their total cost rises with the square of the heap size and took minutes on +//! Windows. Memory the allocator got is reused once freed and never handed back, so allocating one +//! large block and freeing it at once leaves that much room for what follows, for one grow. +//! [`keep_ahead`] does that whenever the memory grew since its last call: half the heap again, at +//! most [`MAX_STEP`], so the heap grows in a few dozen steps. +//! +//! It acts only while a snapshot is read ([`reading`]): the hooks sit in code every live edit runs +//! too (applying a batch, reading a property value), and an edit never reserves memory. Off the web +//! it does nothing. Between the steps of a read it only reads the memory size unless the memory +//! grew. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A WebAssembly memory page. +const PAGE: usize = 64 * 1024; + +/// The most room reserved at once: past a heap of twice this, the heap grows by this much a step +/// rather than by half, so a page close to the browser's limit doesn't ask for more than it needs. +const MAX_STEP: usize = 256 << 20; + +/// How many bytes of room to reserve when the memory is `now` pages and was `seen` pages at the +/// last look (0: never looked, so only the size is noted). +fn room(seen: usize, now: usize) -> Option { + (seen != 0 && now > seen).then(|| (now.saturating_mul(PAGE) / 2).min(MAX_STEP)) +} + +/// How many snapshot reads are under way (a full snapshot is applied inside a welcome's read). +static READING: AtomicUsize = AtomicUsize::new(0); + +/// The memory size at the last look, in pages. +static SEEN: AtomicUsize = AtomicUsize::new(0); + +/// A snapshot read under way: [`keep_ahead`] acts until it is dropped, on error paths too. +pub(crate) struct Reading(()); + +impl Drop for Reading { + fn drop(&mut self) { + READING.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Start a snapshot read: growth from here on gets room kept ahead. +pub(crate) fn reading() -> Reading { + if READING.fetch_add(1, Ordering::Relaxed) == 0 { + SEEN.store(memory_pages().unwrap_or(0), Ordering::Relaxed); + } + Reading(()) +} + +/// Reserve room ahead in the heap if a snapshot is being read and the memory grew since the last +/// call (see the module docs). +pub(crate) fn keep_ahead() { + if READING.load(Ordering::Relaxed) == 0 { + return; + } + let Some(now) = memory_pages() else { return }; + if let Some(bytes) = room(SEEN.load(Ordering::Relaxed), now) { + let mut block: Vec = Vec::new(); + // Near the browser's memory limit this fails and nothing changes: the heap then grows as + // it needs, as before. + if block.try_reserve_exact(bytes).is_ok() { + // Opaque to the optimizer, which could otherwise drop an allocation nothing reads. + drop(std::hint::black_box(block)); + } + } + SEEN.store(memory_pages().unwrap_or(now), Ordering::Relaxed); +} + +/// The size of the page's memory in pages (`None` off the web: the system allocator there maps +/// large blocks on its own). +fn memory_pages() -> Option { + #[cfg(target_arch = "wasm32")] + { + Some(core::arch::wasm32::memory_size(0)) + } + #[cfg(not(target_arch = "wasm32"))] + { + None + } +} + +#[cfg(test)] +mod tests { + use super::{PAGE, room}; + + /// A heap that grows by whole pages when an allocation doesn't fit, as the web allocator's. + struct Heap { + pages: usize, + free: usize, + grows: usize, + seen: usize, + } + + impl Heap { + fn alloc(&mut self, n: usize) { + if self.free < n { + let pages = (n - self.free).div_ceil(PAGE); + self.pages += pages; + self.free += pages * PAGE; + self.grows += 1; + } + self.free -= n; + } + + fn keep_ahead(&mut self) { + if let Some(bytes) = room(self.seen, self.pages) { + self.alloc(bytes); + self.free += bytes; + } + self.seen = self.pages; + } + } + + /// Reading a file the size of #2041's (46 MB to 1.66 GB in small allocations) grows the heap + /// in a few dozen steps with room kept ahead between allocations, not in one step per page. + #[test] + fn room_kept_ahead_turns_page_by_page_growth_into_a_few_steps() { + let run = |ahead: bool| { + let mut h = Heap { pages: (46 << 20) / PAGE, free: 0, grows: 0, seen: 0 }; + while h.pages * PAGE < 1660 << 20 { + h.alloc(400); + if ahead { + h.keep_ahead(); + } + } + h.grows + }; + let (plain, ahead) = (run(false), run(true)); + assert!(plain > 20_000, "page by page: {plain} grows"); + assert!(ahead * 200 < plain, "{ahead} grows with room kept ahead, {plain} without"); + } + + /// The first look only notes the size, and an unchanged or smaller memory reserves nothing. + #[test] + fn room_is_reserved_only_after_the_memory_grew() { + assert_eq!(room(0, 1000), None); + assert_eq!(room(1000, 1000), None); + assert!(room(1000, 1001).is_some()); + assert!(room(1000, 1001) <= room(5000, 5001), "more room for a larger heap"); + } +} diff --git a/crates/collab/src/lib.rs b/crates/collab/src/lib.rs index 912af370f..94f0aad64 100644 --- a/crates/collab/src/lib.rs +++ b/crates/collab/src/lib.rs @@ -28,6 +28,7 @@ pub mod delta_snapshot; mod diff; mod docprops; pub mod frac; +mod heap; mod history; pub mod merge; pub mod message; diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 36c691b85..0e4386cf6 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -1192,6 +1192,7 @@ pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> { if let ServerMsg::Welcome { catch_up, .. } = msg { match catch_up { CatchUp::Packed(packed) => { + let _reading = crate::heap::reading(); let mut raw = Vec::new(); let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1); flate2::read::DeflateDecoder::new(packed.as_slice()) diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 1e3f0a4a3..51beae9bc 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -84,6 +84,7 @@ impl Replica { /// because a session whose settings had to be clamped can no longer replay its saved batches /// for clients that resume (they hold the value past the limits). pub(crate) fn from_snapshot_leaving_out(mut changes: Vec) -> Result<(Replica, usize, bool), Error> { + let _reading = crate::heap::reading(); let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let clamped = docprops::clamp_snapshot_design_review(&mut changes); let left_out = r.apply_kept(&mut changes, Change::is_image)?; @@ -200,6 +201,9 @@ impl Replica { let (mut relist, mut relist_all) = (BTreeSet::new(), false); let mut index = docprops::Index::default(); for c in changes { + // While a snapshot is applied, on the web the heap grows in large steps instead of + // page by page ([`crate::heap`]); a live batch doesn't reserve anything. + crate::heap::keep_ahead(); match self.apply_one(c, &mut out, &mut index) { Ok(Relist::No) => {} Ok(Relist::Page(p)) => { From 6c638908c98cccc5c0166426217add0e57ad92dd Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:51:36 -0700 Subject: [PATCH 16/38] M9: time joining a large shared file (#2041) An ignored release test that builds a 120k-layer file over 15 pages and times the server's welcome, Client::join and the engine opening it through live_poll, for the delta catch-up and the full snapshot: cargo test --release -p figcraft-engine --lib join_timings -- --ignored --nocapture It runs natively, where the web heap's page-by-page growth doesn't happen, so it times decode and apply work only. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/join_bench_tests.rs | 96 +++++++++++++++++++++++++++ crates/engine/src/lib.rs | 2 + 2 files changed, 98 insertions(+) create mode 100644 crates/engine/src/join_bench_tests.rs diff --git a/crates/engine/src/join_bench_tests.rs b/crates/engine/src/join_bench_tests.rs new file mode 100644 index 000000000..08498026a --- /dev/null +++ b/crates/engine/src/join_bench_tests.rs @@ -0,0 +1,96 @@ +//! Join timings for a large shared file (#2041): the server's welcome, the sync client built from +//! it and the engine opening it as a tab, for the current catch-up and the older full snapshot. +//! Run in release: +//! `cargo test --release -p figcraft-engine --lib join_timings -- --ignored --nocapture`. +//! +//! `FIGCRAFT_JOIN_BENCH_LAYERS` sets the layer count (default 120000) and +//! `FIGCRAFT_JOIN_BENCH_CATCH_UP` which catch-ups to time (`delta,legacy` by default). + +use std::time::Instant; + +use figcraft_collab::message::{ClientMsg, ServerMsg}; +use figcraft_collab::{Client, Limits, Outgoing, Server}; +use figcraft_doc::color::{Color, Paint}; +use figcraft_doc::{Document, NodeKind, TextData}; +use serde_json::json; + +use crate::live::{Event, Role}; +use crate::live_tests::{info, push, session}; + +/// What a current client announces, minus the delta snapshot: a server sends it the full snapshot. +const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches"; + +/// A document of about `layers` layers over 15 pages: frames of eight children (text, rectangles +/// and ellipses with fills), like a large product file. +fn big_doc(layers: usize) -> Document { + let mut doc = Document::new("Big file"); + let mut pages = vec![doc.first_page().unwrap()]; + for p in 1..15 { + pages.push(doc.add_page(&format!("Page {p}"))); + } + let per_page = layers / pages.len(); + for (pi, page) in pages.into_iter().enumerate() { + let mut made = 0; + let mut f = 0; + while made < per_page { + let x = (f % 40) as f64 * 400.0; + let y = (f / 40) as f64 * 300.0; + let frame = doc.create(page, NodeKind::Frame, &format!("Card {pi}.{f}"), x, y, 360.0, 260.0).unwrap(); + for c in 0..8 { + let kind = match c % 3 { + 0 => NodeKind::Text(TextData::new(format!("Label {f} {c}"))), + 1 => NodeKind::Rectangle, + _ => NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, + }; + let id = doc.create(frame, kind, &format!("Layer {c}"), 8.0 + c as f64 * 40.0, 8.0, 32.0, 32.0).unwrap(); + doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::new(0.2, 0.4, c as f32 / 8.0, 1.0))]; + } + made += 9; + f += 1; + } + } + doc.repair(); + doc +} + +/// The welcome `server` gives a newcomer announcing `client_version`, and its id. +fn welcome(server: &mut Server, client_version: &str) -> (u32, ServerMsg) { + let ClientMsg::Hello(mut h) = Client::hello("f", "", "Ada", "") else { panic!("no hello") }; + h.client_version = client_version.to_string(); + let (id, outs) = server.join(h).unwrap(); + let w = outs.into_iter().find_map(|o| if let Outgoing::To(_, w @ ServerMsg::Welcome { .. }) = o { Some(w) } else { None }).unwrap(); + (id, w) +} + +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +#[test] +#[ignore = "timing: run in release with --ignored --nocapture"] +fn join_timings() { + let layers: usize = std::env::var("FIGCRAFT_JOIN_BENCH_LAYERS").ok().and_then(|v| v.parse().ok()).unwrap_or(120_000); + let which = std::env::var("FIGCRAFT_JOIN_BENCH_CATCH_UP").unwrap_or_else(|_| "delta,legacy".into()); + let doc = big_doc(layers); + println!("{} layers", doc.node_count()); + let mut server = Server::new(doc, "", Limits::default()); + for name in which.split(',').map(str::trim) { + let version = if name == "legacy" { LEGACY_CLIENT_VERSION.to_string() } else { figcraft_collab::message::client_version() }; + let t = Instant::now(); + let (id, w) = welcome(&mut server, &version); + let welcome_ms = ms(t); + let bytes = figcraft_collab::message::encode(&w).unwrap().len(); + let t = Instant::now(); + let client = Client::join(w.clone()).unwrap(); + let client_ms = ms(t); + drop(client); + let (mut s, script) = session(); + s.execute("collab.join", &json!({"link": "figcraft://join?host=a:1&file=f&token=t"})).unwrap(); + push(&script, vec![Event::Welcome { info: info(Role::Guest, id), peers: vec![] }, Event::Sync(w)]); + let t = Instant::now(); + s.live_poll(); + let engine_ms = ms(t); + assert_eq!(s.doc().unwrap().name, "Big file"); + println!("{name}: welcome {bytes} bytes in {welcome_ms:.0} ms; Client::join {client_ms:.0} ms; engine join (live_poll) {engine_ms:.0} ms"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ced6a49c4..abaf28e9b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -416,6 +416,8 @@ mod invite_links_tests; #[cfg(test)] mod jam_open_tests; #[cfg(test)] +mod join_bench_tests; +#[cfg(test)] mod jpg_export_tests; #[cfg(test)] mod keymap_tests; From 866fe84f9cb25cdec387bd49bff8a6fed74c092b Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:54:43 -0700 Subject: [PATCH 17/38] fix(collab): stop retrying large heap reservations after OOM in current read (#2041) --- crates/collab/src/heap.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/collab/src/heap.rs b/crates/collab/src/heap.rs index 5490ecf78..b8f54f3eb 100644 --- a/crates/collab/src/heap.rs +++ b/crates/collab/src/heap.rs @@ -14,7 +14,7 @@ //! it does nothing. Between the steps of a read it only reads the memory size unless the memory //! grew. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// A WebAssembly memory page. const PAGE: usize = 64 * 1024; @@ -35,6 +35,10 @@ static READING: AtomicUsize = AtomicUsize::new(0); /// The memory size at the last look, in pages. static SEEN: AtomicUsize = AtomicUsize::new(0); +/// Set when a reservation fails near the browser's memory limit so the rest of this read does not +/// retry failing large reservations on every subsequent growth. +static EXHAUSTED: AtomicBool = AtomicBool::new(false); + /// A snapshot read under way: [`keep_ahead`] acts until it is dropped, on error paths too. pub(crate) struct Reading(()); @@ -47,6 +51,7 @@ impl Drop for Reading { /// Start a snapshot read: growth from here on gets room kept ahead. pub(crate) fn reading() -> Reading { if READING.fetch_add(1, Ordering::Relaxed) == 0 { + EXHAUSTED.store(false, Ordering::Relaxed); SEEN.store(memory_pages().unwrap_or(0), Ordering::Relaxed); } Reading(()) @@ -55,17 +60,19 @@ pub(crate) fn reading() -> Reading { /// Reserve room ahead in the heap if a snapshot is being read and the memory grew since the last /// call (see the module docs). pub(crate) fn keep_ahead() { - if READING.load(Ordering::Relaxed) == 0 { + if READING.load(Ordering::Relaxed) == 0 || EXHAUSTED.load(Ordering::Relaxed) { return; } let Some(now) = memory_pages() else { return }; if let Some(bytes) = room(SEEN.load(Ordering::Relaxed), now) { let mut block: Vec = Vec::new(); - // Near the browser's memory limit this fails and nothing changes: the heap then grows as - // it needs, as before. + // Near the browser's memory limit this fails and nothing changes: stop trying large + // reservations for the rest of this read and let the heap grow as needed. if block.try_reserve_exact(bytes).is_ok() { // Opaque to the optimizer, which could otherwise drop an allocation nothing reads. drop(std::hint::black_box(block)); + } else { + EXHAUSTED.store(true, Ordering::Relaxed); } } SEEN.store(memory_pages().unwrap_or(now), Ordering::Relaxed); From 46ff7d9595323005f46c9dfa804937c339088b26 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 02:57:36 -0700 Subject: [PATCH 18/38] fix(engine): wrap TextData with Shared::from in join_bench_tests after #2679 --- crates/engine/src/join_bench_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/join_bench_tests.rs b/crates/engine/src/join_bench_tests.rs index 08498026a..0cd30a3dd 100644 --- a/crates/engine/src/join_bench_tests.rs +++ b/crates/engine/src/join_bench_tests.rs @@ -38,7 +38,7 @@ fn big_doc(layers: usize) -> Document { let frame = doc.create(page, NodeKind::Frame, &format!("Card {pi}.{f}"), x, y, 360.0, 260.0).unwrap(); for c in 0..8 { let kind = match c % 3 { - 0 => NodeKind::Text(TextData::new(format!("Label {f} {c}"))), + 0 => NodeKind::Text(TextData::new(format!("Label {f} {c}")).into()), 1 => NodeKind::Rectangle, _ => NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, }; From 4d3d4e4e5b2bf708dda55beb62895f28dec64c9a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 04:08:59 +0700 Subject: [PATCH 19/38] M3: a selected variant shows its Current variant, the set its property editor (#2346) --- crates/ui-egui/locales/en.toml | 3 +- crates/ui-egui/src/panels/component_panel.rs | 66 +++++++++++++------ crates/ui-egui/src/variant_own_value_tests.rs | 28 ++++++++ docs/components-parity.md | 3 +- 4 files changed, 77 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 77bdca3b2..c0c3fe871 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -461,7 +461,8 @@ name = "English" "Default" = "Default" "Default content" = "Default content" "Default value (the top-left variant)" = "Default value (the top-left variant)" -"This variant's value" = "This variant's value" +"Current variant" = "Current variant" +"Select component set" = "Select component set" "Delay" = "Delay" "Delete" = "Delete" "Delete category (its annotations stay)" = "Delete category (its annotations stay)" diff --git a/crates/ui-egui/src/panels/component_panel.rs b/crates/ui-egui/src/panels/component_panel.rs index 4dd042b9c..2ef05c016 100644 --- a/crates/ui-egui/src/panels/component_panel.rs +++ b/crates/ui-egui/src/panels/component_panel.rs @@ -38,12 +38,14 @@ pub fn instance_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[No match &n.kind { NodeKind::Instance { .. } => instance_ui(app, ui, doc, n), NodeKind::ComponentSet { description } => { - properties_ui(app, ui, doc, n.id, None); + properties_ui(app, ui, doc, n.id); description_ui(app, ui, n.id, description); } NodeKind::Component { description, .. } => { - let set = variant_set(doc, n.id); - properties_ui(app, ui, doc, set.unwrap_or(n.id), set.map(|_| n.id)); + match variant_set(doc, n.id) { + Some(set) => current_variant_ui(app, ui, doc, n, set), + None => properties_ui(app, ui, doc, n.id), + } description_ui(app, ui, n.id, description); } _ => {} @@ -226,8 +228,43 @@ fn name_width(ui: &Ui, default_w: f32, max: f32) -> f32 { (ui.available_width() - default_w - BUTTON - 2.0 * widgets::GUTTER).clamp(48.0, max) } -/// Properties of a component or component set (`variant`: the set's variant that is selected). -fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, variant: Option) { +/// One variant of a set selected: a Current variant section, a dropdown of each variant property +/// set to this variant's value; choosing another renames this variant only, so nothing moves +/// (#2349). The set's properties are edited on the set, which the section's button selects (#2346). +fn current_variant_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, variant: &Node, set: NodeId) { + let t = Tokens::get(ui.ctx()); + widgets::separator(ui); + if widgets::section_header(ui, tr("Current variant"), &[(Icon::ComponentSet, tr("Select component set"))], false) == Some(0) { + app.run("select.set", json!({"ids": [set]})); + } + let pairs = variant_props(&variant.name); + let options = variant_options(doc, set); + let order: Vec = options.iter().map(|(k, _)| k.clone()).collect(); + for (k, vals) in &options { + let cur = pairs.get(k).cloned().unwrap_or_default(); + row(ui, 32.0, |ui| { + prop_label(ui, k, Icon::ComponentSet); + let w = ui.available_width().max(60.0); + let resp = widgets::dropdown(ui, &cur, w, None); + menu_popup(&resp).show(|ui| { + for v in vals { + if menu_item(ui, v, "") { + let mut pairs = pairs.clone(); + pairs.insert(k.clone(), v.clone()); + app.run("node.set", json!({"ids": [variant.id], "props": {"name": variant_name(&pairs, &order)}})); + ui.close(); + } + } + }); + }); + } + if variant_conflicts(doc, set).iter().any(|g| g.contains(&variant.id)) { + widgets::note(ui, tr("Some variants have the same property values: give each one a unique combination"), t.warning); + } +} + +/// Properties of a component or component set. +fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId) { let t = Tokens::get(ui.ctx()); let is_set = matches!(doc.node(owner).map(|n| &n.kind), Some(NodeKind::ComponentSet { .. })); // Shared (non-variant) properties live on every variant; read them from the first. @@ -273,9 +310,6 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, v } else { Default::default() }; - // A selected variant's dropdowns show and set its own values (#2349); the set's, its default. - let own = variant.and_then(|v| doc.node(v)).map(|n| (n.id, variant_props(&n.name))); - let order: Vec = variants.iter().map(|(k, _)| k.clone()).collect(); // Variant properties: name, values (the matrix), add value, delete. Dragged by their left // margin to reorder them (only among themselves: the shared ones keep the engine's order). let mut drag = ListDrag::in_order(ui, ("variant_props", owner)); @@ -291,22 +325,12 @@ fn properties_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, v if let Some(nn) = widgets::text_field(ui, Id::unique(("vprop_name", owner, k.as_str())), k, name_w, tr("Name")) { app.run("component.editProperty", json!({"id": owner, "name": k, "newName": nn})); } - let def = own.as_ref().map_or(&defaults, |(_, pairs)| pairs).get(k).or(vals.first()).cloned().unwrap_or_default(); - let hint = if own.is_some() { tr("This variant's value") } else { tr("Default value (the top-left variant)") }; - let resp = widgets::dropdown(ui, &def, DEFAULT_W, None).on_hover_text(hint); + let def = defaults.get(k).or(vals.first()).cloned().unwrap_or_default(); + let resp = widgets::dropdown(ui, &def, DEFAULT_W, None).on_hover_text(tr("Default value (the top-left variant)")); menu_popup(&resp).show(|ui| { for v in vals { if menu_item(ui, v, "") { - match &own { - Some((id, pairs)) => { - let mut pairs = pairs.clone(); - pairs.insert(k.clone(), v.clone()); - app.run("node.set", json!({"ids": [id], "props": {"name": variant_name(&pairs, &order)}})); - } - None => { - app.run("component.editProperty", json!({"id": owner, "name": k, "default": v})); - } - } + app.run("component.editProperty", json!({"id": owner, "name": k, "default": v})); ui.close(); } } diff --git a/crates/ui-egui/src/variant_own_value_tests.rs b/crates/ui-egui/src/variant_own_value_tests.rs index 198ae3bed..281a051d2 100644 --- a/crates/ui-egui/src/variant_own_value_tests.rs +++ b/crates/ui-egui/src/variant_own_value_tests.rs @@ -121,3 +121,31 @@ fn a_long_variant_dropdown_scrolls_within_the_viewport() { }; assert_eq!(*component, variants[49], "picking the last variant from the scrolled menu switches the instance"); } + +#[test] +fn a_selected_variant_shows_its_current_values_and_the_set_edits_the_properties() { + // #2346: one variant shows a Current variant section, not the set's property editor; its + // button selects the set, which has the editor. + let mut s = Session::new(); + let mut variants = Vec::new(); + for (k, name) in ["Looking=Top right", "Looking=Down left"].iter().enumerate() { + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 20 + k * 44, "width": 80, "height": 30, "name": name})).unwrap()); + variants.push(id(s.execute("component.create", &json!({"ids": [f]})).unwrap())); + } + let set = id(s.execute("component.combineVariants", &json!({"ids": variants})).unwrap()); + s.execute("select.set", &json!({"ids": [variants[1]]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + let labels = |nodes: &[Node]| nodes.iter().filter_map(|n| n.label().map(str::to_string)).collect::>(); + let nodes = tree(&mut u); + let shown = labels(&nodes); + assert!(!shown.iter().any(|l| l == "Delete property" || l == "Add variant with a new value"), "no set editor: {shown:?}"); + let values = combos(&nodes); + assert!(values.contains(&"Down left".to_string()) && !values.contains(&"Top right".to_string()), "this variant's value: {values:?}"); + let to_set = nodes.iter().find(|n| n.label() == Some("Select component set") && n.bounds().is_some()).expect("the button"); + click(&mut u, centre(to_set)); + u.frame(vec![]); + assert_eq!(u.app.session.selection(), [set]); + let shown = labels(&tree(&mut u)); + assert!(shown.iter().any(|l| l == "Delete property"), "the set has the editor: {shown:?}"); +} diff --git a/docs/components-parity.md b/docs/components-parity.md index 0dd64a248..4639142d9 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (one variant selected shows a Current variant section, a dropdown of each variant property at its value, and a button that selects the set, which has the property editor (#2346); a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -84,6 +84,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M3, #2346: one variant of a set selected showed the set's whole property editor (names, every value as a field, Add variant), so it wasn't clear which variant was selected and edits there changed the set. It now shows a Current variant section: one dropdown per variant property at this variant's value (choosing another renames this variant, #2349) and a button that selects the set, where the properties are edited. Test: `variant_own_value_tests::a_selected_variant_shows_its_current_values_and_the_set_edits_the_properties`. | | 2026-11-23 | minor | M3: a main component copied from a library file and pasted into another file is an instance of it from that library, which gets enabled in that file, as pasting an instance of it already was and as Figma does with a published component. It used to paste a copy of the main, a new component of that file unlinked from the library. A variant pastes as an instance of that variant. A component the library doesn't offer (hidden from publishing, or added since the last publish) and a main from a file that publishes no library still paste as a copy. Test: `library::tests::a_main_pasted_from_its_library_file_is_an_instance_of_it`. Numbers unchanged | | 2026-11-19 | patch | M3: copying a variant and pasting with that variant, a layer in it or its set selected pasted an instance on the page. Copied variants of one set now paste into that set as new variants (deep copies, as Duplicate makes), under the copied variants where they are now, below the lowest variant with the gap of 20 that Add variant leaves, and the set grows to hold them. Every other paste of a copied main still makes an instance: with nothing selected, into another set, a main that isn't a variant pasted with a set selected, Paste over and Paste to replace on a variant, and an explicit `parent` (even the variant's own set). Tests: `pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others`, `a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant`, `a_variant_pasted_with_another_set_selected_is_an_instance`, `a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance`, `a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance`, `pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant` | | 2026-11-22 | patch | M3: switching an instance to another variant put back the variant's own text in place of the text typed into it when the two variants nest that text layer in different frames (`text › Label` in one, `div › text › Label` in the other), because the typed layer was matched to the new variant's by name path only. Now a text layer of the new variant nothing else matched takes the old text layer of the same name, when exactly one layer on each side has that name; layers inside nested instances still go by their own mains. Two layers of one name stay unmatched, since either could be the one typed into. Test: `typed_text_stays_across_variants_that_nest_it_differently`. Grade unchanged. | From 086594604c541243ccf73c5e45fd8d4fe1905b5c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 13:28:47 +0700 Subject: [PATCH 20/38] M8: a wobbly Bend click on a point or segment is a click, not a drag (#2166) --- .../engine/src/canvas/vectoredit/pointer.rs | 25 +++++++----- crates/engine/src/canvas/vectoredit/tests.rs | 40 +++++++++++++++++++ docs/ui-parity.md | 1 + 3 files changed, 56 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/canvas/vectoredit/pointer.rs b/crates/engine/src/canvas/vectoredit/pointer.rs index 2f32f5aef..3e38c7594 100644 --- a/crates/engine/src/canvas/vectoredit/pointer.rs +++ b/crates/engine/src/canvas/vectoredit/pointer.rs @@ -56,14 +56,20 @@ pub(crate) enum VGesture { start_angle: f64, angle: f64, }, + /// Bend tool on a segment: a drag past the click slop from `start` (the press, on the page) + /// bends it. BendSegment { seg: usize, t: f64, + start: Point, + moved: bool, }, - /// Bend tool on a point: drag pulls out handles, a click on a smooth point sharpens it. + /// Bend tool on a point: a drag past the click slop from `start` (the press, on the page) + /// pulls out handles; a click (wobble included) on a smooth point sharpens it. BendVertex { v: usize, origin: Point, + start: Point, moved: bool, smooth: bool, }, @@ -748,11 +754,11 @@ impl Session { e.vertices = vec![index]; })?; self.begin_interaction("Bend")?; - self.vgesture(VGesture::BendVertex { v: index, origin, moved: false, smooth }); + self.vgesture(VGesture::BendVertex { v: index, origin, start: ev.p(), moved: false, smooth }); } Some(VHit::Segment { seg, t }) => { self.begin_interaction("Bend")?; - self.vgesture(VGesture::BendSegment { seg, t }); + self.vgesture(VGesture::BendSegment { seg, t, start: ev.p(), moved: false }); } None => self.vgesture(VGesture::Marquee { start: ev.p(), base: Self::select_base(ve, ev.shift), leave: None }), }, @@ -956,17 +962,16 @@ impl Session { self.tool.overlay.cursor = Cursor::Rotate((ev.p() - c).atan2().to_degrees()); self.vgesture(VGesture::BoxRotate { b, start_angle, angle }); } - VGesture::BendSegment { seg, t } => { + // A hand's wobble during a click is not a drag (#2166): the same slop as other clicks. + VGesture::BendSegment { start, moved: false, .. } | VGesture::BendVertex { start, moved: false, .. } if within_slop(ev, start) => {} + VGesture::BendSegment { seg, t, start, .. } => { self.preview(|doc, _| edit(doc, id, |net| ops::bend(net, seg, t, lp)))?; + self.vgesture(VGesture::BendSegment { seg, t, start, moved: true }); } - VGesture::BendVertex { v, origin, moved, smooth } => { + VGesture::BendVertex { v, origin, start, smooth, .. } => { let d = lp - origin; - let page_d = (w * lp - w * origin).hypot() * ev.zoom; - if !moved && page_d < 2.0 { - return Ok(()); - } self.preview(|doc, _| edit(doc, id, |net| ops::make_smooth(net, v, d)))?; - self.vgesture(VGesture::BendVertex { v, origin, moved: true, smooth }); + self.vgesture(VGesture::BendVertex { v, origin, start, moved: true, smooth }); } VGesture::Marquee { start, base, .. } => { let r = Rect::from_points(start, ev.p()); diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index 636368ee7..14bc48ea8 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -173,6 +173,46 @@ fn a_bend_click_curves_a_sharp_point_between_its_neighbours() { assert!(n.incident(v).iter().all(|(sg, st)| n.handle(*sg, *st) == Some((0.0, 0.0)))); } +/// #2166: with the Bend tool, or Cmd/Ctrl with Move, a press that wobbles a pixel or two before +/// it lets go is a click: a sharp point curves between its neighbours as a still click does, and a +/// segment stays as it is. Past the click slop the drag pulls the point's handles towards it. +#[test] +fn a_bend_click_that_wobbles_is_still_a_click() { + for cmd in [false, true] { + let mut s = Session::new(); + let r = ex(&mut s, "vector.create", json!({"points": [[0, 0], [50, 30], [100, 0]], "closed": false})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(&mut s, "vector.edit.begin", json!({"id": id})); + if !cmd { + ex(&mut s, "vector.edit.tool", json!({"tool": "bend"})); + } + let v = vertex_at(&net(&s, id), 50.0, 30.0); + let gesture = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Move, to), (PointerKind::Up, to)] { + let mut e = ev(kind, x, y); + e.cmd = cmd; + s.pointer(&e).unwrap(); + } + }; + let handles = |s: &Session| { + let n = net(s, id); + n.incident(v).iter().map(|(sg, st)| n.handle(*sg, *st).unwrap()).collect::>() + }; + // A segment pressed and wobbled is not bent. + let before = net(&s, id); + gesture(&mut s, (25.0, 15.0), (26.0, 16.0)); + assert_eq!(net(&s, id).segments, before.segments, "cmd={cmd}: a wobble doesn't bend the segment"); + // Pressed beside the point and wobbled: the click's curve, along the neighbours' line. + gesture(&mut s, (51.0, 30.0), (52.0, 31.0)); + let hs = handles(&s); + assert!(hs.iter().all(|h| h.0.abs() > 1.0 && h.1.abs() < 1e-6), "cmd={cmd}: the automatic curve, not a handle drag: {hs:?}"); + // Dragged down past the slop: the handles follow the pointer. + gesture(&mut s, (50.0, 30.0), (50.0, 60.0)); + let hs = handles(&s); + assert!(hs.iter().all(|h| h.1.abs() > h.0.abs()), "cmd={cmd}: pulled towards the pointer: {hs:?}"); + } +} + /// Between a handle's end and a point both within reach, the nearer on the page wins, also under a /// non-uniform scale (10× wide here), where local distances would pick the point. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b114ceecf..d5b3d1f1b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -212,6 +212,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M8, #2166: with the Bend tool, or Cmd/Ctrl in vector edit mode, a click on a point that moved the pointer 2 px from the point (pressing beside it counted) pulled out tiny handles in a random direction instead of curving it, and a click on a segment bent it at the first pixel. Both now take the click slop other clicks use (3 px from the press, on screen): a wobbly click on a sharp point gives the automatic curve, on a curved point sharpens it, and on a segment changes nothing; past the slop the drag pulls handles or bends as before. Test: `vectoredit::tests::a_bend_click_that_wobbles_is_still_a_click` | | 2026-11-28 | patch | M3, #2507: Cmd/Ctrl+L with nothing selected copied nothing. It now copies the link of the page shown (`figcraft://node/`, what the pages list's Copy link to page copies), with the same "Link copied" toast; with a selection it still copies the selected layer's link. Test: `context_menu_tests::cmd_l_with_nothing_selected_copies_the_pages_link` | | 2026-11-28 | patch | M12, #2641: the Pencil (and the board's Marker, Highlighter and Eraser) showed a crosshair. Its cursor is now the ink's tip: a dot in the colour its stroke takes there, as wide on screen as the stroke, ringed white and dark; the Eraser's is a ring of its reach. Tests: `cursor_tests::each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer`, `cursors_tests::the_ink_tools_show_a_dot_in_the_inks_colour_and_width`. | | 2026-11-28 | patch | M12, #2237: the code block tool takes the `` ` `` key on boards (`tool.codeBlock`), pinned like the other board tool keys (60 undocumented bindings). Test: `shortcut_parity_tests::counts_match_the_docs`. | From e57f9a385d30647070cb4f5ff1fb61ad8c471321 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 13:33:35 +0700 Subject: [PATCH 21/38] M6: pasted layers drop bindings to variables the file doesn't have and keep their values (#2524, part 3) --- crates/engine/src/cmd/edit/clipboard.rs | 14 ++++++++++++++ crates/engine/src/design_paste_tests.rs | 21 +++++++++++++++++++++ docs/file-format-parity.md | 5 +++-- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 3fd5d11d2..0c7da7fda 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -294,10 +294,24 @@ fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_vari if let Some(src) = foreign { crate::library::adopt_pasted(doc, src, clip.source_path.as_deref(), &all)?; } + drop_dangling_bindings(doc, all.values().copied()); crate::library::count_inserted(doc, &out); Ok(out) } +/// Pasted layers bound to variables this file doesn't have (copied from another file or app that +/// brought no variables along, or deleted since the copy) keep the values they showed, unbound: a +/// binding that names no variable here would dangle (#2524). +fn drop_dangling_bindings(doc: &mut Document, pasted: impl Iterator) { + for id in pasted { + let Some(n) = doc.node(id).filter(|n| n.bound.values().any(|v| doc.variables.get_by_id(v).is_none())) else { continue }; + let kept = n.bound.iter().filter(|(_, v)| doc.variables.get_by_id(v).is_some()).map(|(f, v)| (f.clone(), v.clone())).collect(); + if let Ok(n) = doc.get_mut(id) { + n.bound = kept; + } + } +} + /// Lock the aspect ratio of a layer pasted into an auto layout frame when it shows an image cropped /// to it and fills one axis while fixed on the other, so layout can't squash the image. fn keep_a_cropped_images_proportions(doc: &mut Document, pasted: NodeId, parent: NodeId) { diff --git a/crates/engine/src/design_paste_tests.rs b/crates/engine/src/design_paste_tests.rs index 6823645ed..03ec11e12 100644 --- a/crates/engine/src/design_paste_tests.rs +++ b/crates/engine/src/design_paste_tests.rs @@ -73,6 +73,27 @@ fn layers_paste_into_the_page_and_undo() { assert!(ids.iter().all(|i| !s.doc().unwrap().contains(*i))); } +/// Layers copied with a fill bound to a variable the copy doesn't bring along paste unbound, in +/// the colour they showed (#2524), rather than bound to a variable that isn't in the file. +#[test] +fn bindings_to_variables_the_file_lacks_paste_as_their_values() { + let mut src = Session::new(); + let r = id(&src.execute("node.create", &json!({"type": "rectangle", "x": 0, "y": 0, "width": 40, "height": 20, "name": "Swatch"})).unwrap()); + src.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap(); + src.execute("variable.create", &json!({"collection": "Tokens", "name": "Brand", "type": "color", "value": "#3366FF"})).unwrap(); + src.execute("variable.bind", &json!({"ids": [r], "field": "fill", "variable": "Brand"})).unwrap(); + let file = B64.decode(src.execute("file.export", &json!({"format": "fig"})).unwrap()["data"].as_str().unwrap()).unwrap(); + let mut s = Session::new(); + let out = s.execute("edit.pasteDesignLayers", &json!({"html": clipboard_html(&file)})).unwrap(); + let copied = s.clipboard.nodes[0].1[0].clone(); + assert!(!copied.bound.is_empty(), "the copy is bound"); + let doc = s.doc().unwrap(); + let pasted = doc.node(params::id_of(&out["ids"][0]).unwrap()).unwrap(); + assert!(copied.bound.values().all(|v| doc.variables.get_by_id(v).is_none()), "the file hasn't the variable"); + assert!(pasted.bound.is_empty(), "no binding to a variable the file hasn't: {:?}", pasted.bound); + assert_eq!(pasted.fills, copied.fills, "the colour it showed"); +} + #[test] fn a_second_paste_repeats_the_copied_layers() { let mut s = Session::new(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 32bc84481..57b8ac22e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (`.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (layers pasted from another app drop bindings to variables the file lacks and keep the values they showed (#2524); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -40,7 +40,7 @@ and prototype interactions are still unchecked there. | Camera raw (RW2, CR2, CR3, NEF, ARW, RAF, ORF, DNG and the other containers craft-raw reads) | no | **yes**, developed | open, import, place, drop, image fills: the raw is developed once as it comes in (craft-raw decode; craft-develop demosaic, as-shot white balance, colour matrices, highlight rebuild and neutral tone curve) and the document keeps the picture as a JPEG at quality 95 with full chroma, not the raw file; a raw variant craft-raw doesn't decode is refused with its reason. Not applied: DNG camera-profile looks, lens corrections kept only as metadata, noise reduction, sharpening | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). On macOS, pasting a single supported raster file copied in Finder places the file’s image on the canvas. Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). On macOS, pasting a single supported raster file copied in Finder places the file’s image on the canvas. Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A binding to a variable the file doesn't have (the clipboard brought no variables along) is dropped and the layer keeps the value it showed (#2524). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -203,6 +203,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M6, part of #2524: layers pasted from another design app kept their bindings to variables the paste didn't bring along, so `boundVariables` named variables the file doesn't have. A pasted layer bound to a variable that isn't in the file (from another app or file, or deleted since the copy) now keeps the value it showed, unbound; bindings to variables the file has stay. Test: `design_paste_tests::bindings_to_variables_the_file_lacks_paste_as_their_values` | | 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged | | 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. | | 2026-11-20 | patch | M6, #2501 follow-up: JPG export inherited 4:2:0 chroma subsampling from the `craft-image-codecs` defaults when #2501 moved it to the shared encoder, so fine colour detail blurred. It asks for 4:4:4 again, as before the cutover (#2521). Tests: `render::tests::jpeg_export_keeps_full_chroma`, and `export_formats_and_what_each_keeps` checks an 8 × 8 corner block clear of the ellipse. Numbers unchanged. | From 681b8180ac1101c6d2fa0ddcb6edface68bbd4a9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:25:04 +0700 Subject: [PATCH 22/38] M1: scrubbing a field hides the selection's frame until it is let go (#1319) Changing a stroke weight, corner radius or any other value by scrubbing its field left the selection's frame and handles over the layer, so the result couldn't be judged without deselecting. While a field is scrubbed (the shared widgets::scrub gesture, used by every number field and the typography icons) the canvas now hides the selection's frame, handles and size label, as it already did while the colour picker is used, and draws them again once the drag is let go. A press without a drag leaves them. --- crates/ui-egui/src/app/frame.rs | 8 +++++++ crates/ui-egui/src/canvas/overlays.rs | 16 ++++++------- .../src/colorpicker_selection_tests.rs | 24 +++++++++++++++++++ crates/ui-egui/src/field_tests.rs | 2 +- crates/ui-egui/src/widgets.rs | 13 ++++++++++ docs/ui-parity.md | 5 ++-- 6 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 510ad84e7..bf252f541 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -72,6 +72,14 @@ impl FigApp { } } + /// Whether the canvas hides the selection's frame and a text's coloured selection right now: + /// while a field is scrubbed ([`crate::widgets::scrubbing`]) or the colour picker is used on + /// the selection ([`Self::picker_hides_selection`]), so the value being changed shows on the + /// layer itself. + pub(crate) fn hides_selection(&self, ctx: &egui::Context) -> bool { + crate::widgets::scrubbing(ctx) || self.picker_hides_selection(ctx) + } + /// Whether the colour picker is being used right now for the selected layers' own look (a /// paint, an effect, a text range or Selection colors): a drag on its value controls (the /// palette, the hue and alpha sliders, a number field, the gradient bar and its stops), the diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index e854a1630..b44022ebd 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -124,10 +124,10 @@ pub(super) fn overlays(app: &FigApp, painter: &egui::Painter, t: &Tokens) -> Vec } // Selection. let editing = ds.text_edit.clone(); - // While the colour picker is being used on the selection, hide its frame and handles so the - // colour being picked shows on the layer itself (a text's coloured selection would hide it - // too). - if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.picker_hides_selection(painter.ctx()) { + // While a field is scrubbed or the colour picker is used on the selection, hide its frame and + // handles so the value being changed shows on the layer itself (a text's coloured selection + // would hide it too). + if !sel.is_empty() && editing.is_none() && ds.vector_edit.is_none() && !app.hides_selection(painter.ctx()) { size_label = selection_overlay(app, painter, ds, &doc, &sel, zoom); } if app.session.tool.tool == ToolId::ShapeBuilder @@ -276,10 +276,10 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do let preedit = app.preedit_view(); let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc); let Some(text) = TextOnScreen::of(edoc, te.id) else { return }; - // While the colour picker is being used on this text, its frame and coloured selection hide - // too: the selection colour tinted the very characters whose colour is being chosen. The - // caret stays. - let picking = app.picker_hides_selection(painter.ctx()); + // While a field is scrubbed or the colour picker is used on this text, its frame and coloured + // selection hide too: the selection colour tinted the very characters being changed. The caret + // stays. + let picking = app.hides_selection(painter.ctx()); let layout = &text.layout; if !picking && let Some(q) = node_quad(app, edoc, te.id) { quad(painter, q, stroke(accent(painter), 1.0)); diff --git a/crates/ui-egui/src/colorpicker_selection_tests.rs b/crates/ui-egui/src/colorpicker_selection_tests.rs index e1adf380f..649496658 100644 --- a/crates/ui-egui/src/colorpicker_selection_tests.rs +++ b/crates/ui-egui/src/colorpicker_selection_tests.rs @@ -541,3 +541,27 @@ fn a_focused_palette_square_does_not_hide_the_selection() { } assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "focus on a palette square leaves the frame in view"); } + +// Scrubbing a field changes the layer live (#1319): its frame and handles step aside meanwhile, as +// they do for the colour picker, so the new value shows on the layer itself. +#[test] +fn scrubbing_a_field_hides_the_selections_frame_until_let_go() { + let mut s = Session::new(); + let text = selected_text(&mut s); + let mut u = Ui::new(s); + let area = text_area(&u, text); + let accent = crate::theme::canvas_accent(&u.ctx); + u.ctx.enable_accesskit(); + assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "the selected text's frame shows"); + let from = crate::field_tests::label(&mut u, "Rotation"); + u.button(from, true); + assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "a press on the label alone leaves the frame"); + let mut to = from; + for _ in 0..4 { + to += egui::vec2(6.0, 0.0); + u.frame(vec![egui::Event::PointerMoved(to)]); + } + assert_eq!(painted_around(&u.frame_output(vec![]), area, accent), 0, "scrubbing hides the frame"); + u.button(to, false); + assert!(painted_around(&u.frame_output(vec![]), area, accent) > 0, "letting go brings the frame back"); +} diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 1c575cac9..ea462399e 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -204,7 +204,7 @@ pub(crate) fn field(u: &mut Ui, name: &str) -> (Pos2, String) { } /// The middle of field `name`'s label (what scrubs): just left of its value. -fn label(u: &mut Ui, name: &str) -> Pos2 { +pub(crate) fn label(u: &mut Ui, name: &str) -> Pos2 { u.frame(vec![]); let out = u.frame_output(vec![]); let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d5c3a2f1e..da0c46e7d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -154,6 +154,17 @@ pub fn scrub_notice_id() -> Id { Id::unique("scrub_speed_notice") } +/// Where a scrub notes the last frame it moved a value in ([`scrubbing`]). +fn scrubbing_id() -> Id { + Id::unique("scrubbing_frame") +} + +/// Whether a field is being scrubbed, this frame or the last (the panels may draw before or after +/// the canvas): the canvas hides the selection's frame meanwhile, so the value shows on the layer. +pub(crate) fn scrubbing(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(scrubbing_id())).is_some_and(|f| f + 1 >= ctx.cumulative_frame_nr()) +} + /// The value a scrub that began at `from` and has moved `amount` (see [`scrub_amount`]) shows: /// whole steps of `quantum` away from where it began. pub fn scrubbed(from: f64, amount: f64, quantum: f64) -> f64 { @@ -193,6 +204,8 @@ pub(crate) fn scrub(ui: &Ui, id: Id, response: &Response, value: Option, st let (speed, notice) = scrub_speed(rise); // The frame the button goes up moves nothing: the scrub ends where the last one left it. if response.dragged() { + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|d| d.insert_temp(scrubbing_id(), frame)); amount += scrub_amount(dx, step, shift, alt) * speed; // A change of speed is said once (not the usual speed a scrub starts at). if notice != last_speed && !(last_speed.is_empty() && speed == 1.0) { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b114ceecf..f1e68f043 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (the Pencil, Marker, Highlighter and Eraser show a round tip in the ink's colour and width instead of a crosshair (#2641); the `` ` `` key chooses the code block tool on boards (#2237); Cmd/Ctrl+L copies a link to the selected layer, as in Figma; M4: the eyedropper colours the stroke of a layer that has only a stroke, samples for an open colour picker from the shortcut too, and shows the colour under it beside the pointer; Shift with a double-click goes a level deeper and keeps the rest of the selection, so layers nested in neighbouring artboards can be selected together; M1: Frame selection makes a frame without a fill; M1: centred auto-width text keeps its middle as it grows and shrinks; M1: a drag on a section's background, or on the background of a frame in it, draws a marquee; the Layers panel's eye and padlock stay at the list's right edge, and a name takes at most 400 pt; in vector edit mode, deleting a point selects the next one on its path, so Delete pressed again goes on along it; the hover and selection outline of a curved layer bends smoothly instead of showing straight pieces; text copied while editing, or a whole text layer copied, pastes into a text edit with its formatting and its layer's colour, and Shift+Cmd/Ctrl+V (also Alt+Cmd/Ctrl+V) pastes it in the style at the caret; crop mode: the layer's sides and corners crop its image in an auto layout frame too, up to the image's edges, change a locked ratio (Shift keeps it), the image's own corners scale freely with Shift proportional as a resize does, and crop mode and vector edit mode end each other; after a click on a layer row the arrow keys nudge the selection, or move a layer in an auto layout flow one place, as in Figma; the rows take the arrows once they have the keyboard (F6); Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen: next in an auto layout frame's flow, else below the lowest or right of the rightmost, at the selection's own gap; Tab and Shift+Tab while editing a text layer go on to the next or previous text layer of its frame, in reading order, with all of its text selected; a file opens again on the page and at the view it was left at; the desktop app reopens the files open when it quit, in their tabs' order with the same one in front, and with nothing to reopen starts on the Home screen instead of in a new file; a dropdown, button menu or context menu in the panels that is taller than the window scrolls, so its last rows can be picked; frames, sections, components and instances move, resize and draw on whole pixels whatever Snap to pixel grid says and whatever they snap to, as Figma's help says; the pixel grid shows on a dark canvas and dark fills as well as on white, its lines one screen pixel wide in a light grey at a fifth of its strength, as measured in Figma; Shift+Cmd/Ctrl+' says at the bottom of the window whether snapping to the pixel grid is now on or off; Paste properties links the copied layer's colour, effect, grid and text styles and binds the variables it follows, and a frame's layout grids come along; links another file lacks paste as values; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); a dragged layer is drawn from a sprite that moves with its outline (#2033); the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); Type settings ▸ Details ▸ Position sets the selected text layers, or the selected characters while editing, to superscript or subscript, or neither (#2338); Shift with the Pencil, Marker or Highlighter draws one straight segment from where the stroke started, at the nearest 45° step, as the Line tool and the Pen do (#2447); the Design panel's header names a selected component or component set, after its icon, instead of only its type (#2347); dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (while a field is scrubbed the selection's frame and handles hide, so the value shows on the layer, as they already did while the colour picker is used (#1319); the Pencil, Marker, Highlighter and Eraser show a round tip in the ink's colour and width instead of a crosshair (#2641); the `` ` `` key chooses the code block tool on boards (#2237); Cmd/Ctrl+L copies a link to the selected layer, as in Figma; M4: the eyedropper colours the stroke of a layer that has only a stroke, samples for an open colour picker from the shortcut too, and shows the colour under it beside the pointer; Shift with a double-click goes a level deeper and keeps the rest of the selection, so layers nested in neighbouring artboards can be selected together; M1: Frame selection makes a frame without a fill; M1: centred auto-width text keeps its middle as it grows and shrinks; M1: a drag on a section's background, or on the background of a frame in it, draws a marquee; the Layers panel's eye and padlock stay at the list's right edge, and a name takes at most 400 pt; in vector edit mode, deleting a point selects the next one on its path, so Delete pressed again goes on along it; the hover and selection outline of a curved layer bends smoothly instead of showing straight pieces; text copied while editing, or a whole text layer copied, pastes into a text edit with its formatting and its layer's colour, and Shift+Cmd/Ctrl+V (also Alt+Cmd/Ctrl+V) pastes it in the style at the caret; crop mode: the layer's sides and corners crop its image in an auto layout frame too, up to the image's edges, change a locked ratio (Shift keeps it), the image's own corners scale freely with Shift proportional as a resize does, and crop mode and vector edit mode end each other; after a click on a layer row the arrow keys nudge the selection, or move a layer in an auto layout flow one place, as in Figma; the rows take the arrows once they have the keyboard (F6); Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen: next in an auto layout frame's flow, else below the lowest or right of the rightmost, at the selection's own gap; Tab and Shift+Tab while editing a text layer go on to the next or previous text layer of its frame, in reading order, with all of its text selected; a file opens again on the page and at the view it was left at; the desktop app reopens the files open when it quit, in their tabs' order with the same one in front, and with nothing to reopen starts on the Home screen instead of in a new file; a dropdown, button menu or context menu in the panels that is taller than the window scrolls, so its last rows can be picked; frames, sections, components and instances move, resize and draw on whole pixels whatever Snap to pixel grid says and whatever they snap to, as Figma's help says; the pixel grid shows on a dark canvas and dark fills as well as on white, its lines one screen pixel wide in a light grey at a fifth of its strength, as measured in Figma; Shift+Cmd/Ctrl+' says at the bottom of the window whether snapping to the pixel grid is now on or off; Paste properties links the copied layer's colour, effect, grid and text styles and binds the variables it follows, and a frame's layout grids come along; links another file lacks paste as values; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); a dragged layer is drawn from a sprite that moves with its outline (#2033); the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); Type settings ▸ Details ▸ Position sets the selected text layers, or the selected characters while editing, to superscript or subscript, or neither (#2338); Shift with the Pencil, Marker or Highlighter draws one straight segment from where the stroke started, at the nearest 45° step, as the Line tool and the Pen do (#2447); the Design panel's header names a selected component or component set, after its icon, instead of only its type (#2347); dragging near the canvas edge pans the view toward it, as measured in Figma: 40 px/s for each px within about 15 px of the edge, 600 px/s at it, for moving layers, the selection box, drawing and prototype connections (#2015); M8: a Shift-click range in the Layers panel across parents keeps a frame and not its covered children, measured in Figma's web app on 2026-11-12; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -77,7 +77,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; frames, sections and components always do, also with snapping off or next to a layer off the grid, as the help says (`frames_land_on_whole_pixels_whatever_they_snap_to`); the pixel grid shows from 400% (`view_behaviour_tests`) | -| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px), ten times that with Shift (5 steps a point) and a tenth of that with Alt (0.05 steps a point; neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837) | +| Numeric fields: arithmetic, scrubbing by dragging the label (or the field itself with Alt held), mixed values | done | Numeric panels use `widgets::number_field`; Corner smoothing has an original code-drawn icon, a 24 pt drag target and an accessible name, with live changes, fractional values preserved across consecutive drags, Shift/Alt rates, 0–100% clamping and one-step undo/redo (`corner_individual_tests`); Typography line height, letter spacing and paragraph spacing share its leading-icon scrub logic (#373), retaining their existing unit parsing, Auto/Mixed values, variable chips and selected-character targeting (`typography_scrub_tests`). Scrubbing the label: half a step a point (0.5 px; 0.5% of opacity, 0.5° of rotation), as measured in Figma on 2026-11-08 (a 12.2 px drag moved X by 6, a 61.2 px drag by 31; rotation by 6° and opacity by 5% for 12.2 px), ten times that with Shift (5 steps a point) and a tenth of that with Alt (0.05 steps a point; neither measured), each stretch at the rate held while it was dragged, one undo step when let go; past the edge of the screen it goes on where the platform reports the mouse's own motion (desktop), otherwise it stops there. Arrow keys: Up/Down step a pixel field by the small nudge and Shift by the big nudge (the preferences), other fields by their own step and ten of it; they work while typing (from what is typed) and with the keyboard on the field. Typing: `+ - * /`, brackets, units (`px`, `°`, `%`, `x`, `ms`), a decimal comma; `+10`, `*2`, `/4` are relative to the value, and `50%`, `+10%`, `-10%` too in a field that isn't a percentage. Enter, Tab or a click elsewhere commits (Tab and Shift+Tab move to the next and previous control), Escape restores; a field left as it was commits nothing (no undo step, and a rounded display isn't written back). Mixed values show "Mixed": a number sets them all, a relative edit or an arrow key goes to each layer from its own value in one undo step, for X, Y, W, H, rotation, opacity, corner radius and stroke weight (elsewhere `+10` on Mixed sets 10 and `*2` does nothing) (`field_tests`). Left: scrubbing a Mixed field (nothing happens), `x2`-style suffix edits, the pointer isn't wrapped to the other side of the screen; the Shift and Alt rates and the speed by height are not compared with Figma's, and the rotation scrub's direction is not confirmed; while scrubbing, the pointer's height sets the speed (more than 100 points above where the scrub began: 2x; that far below: 1/2; twice as far: 1/4), a toast names the speed when it changes, and Shift and Alt multiply as before ("Change the speed that you scrub the field by moving the cursor towards the top of the screen to increase the scrubbing speed, or towards the bottom of the screen to reduce it", Scrub fields; #1837). While a field is scrubbed, the canvas hides the selection's frame, handles and size label (and a text's coloured selection), so the value being changed shows on the layer, and brings them back when it is let go (#1319, `colorpicker_selection_tests::scrubbing_a_field_hides_the_selections_frame_until_let_go`) | | Transform box at small sizes | done | a press inside a layer smaller than its handles moves it, the nearest handle wins, handles answer just outside and are hidden under 16 px on screen; cursors follow each handle and the box's rotation | | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | @@ -212,6 +212,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M1, #1319: changing a value by scrubbing its field left the selection's frame and handles over the layer, so a stroke weight or corner radius couldn't be judged without deselecting. While a field is scrubbed (`widgets::scrub`, every number field and the typography icons) the canvas now hides the selection's frame, handles and size label, as it already did while the colour picker is used, and brings them back when the drag is let go. A press on a label without a drag leaves them. Test: `colorpicker_selection_tests::scrubbing_a_field_hides_the_selections_frame_until_let_go`. Numbers unchanged | | 2026-11-28 | patch | M3, #2507: Cmd/Ctrl+L with nothing selected copied nothing. It now copies the link of the page shown (`figcraft://node/`, what the pages list's Copy link to page copies), with the same "Link copied" toast; with a selection it still copies the selected layer's link. Test: `context_menu_tests::cmd_l_with_nothing_selected_copies_the_pages_link` | | 2026-11-28 | patch | M12, #2641: the Pencil (and the board's Marker, Highlighter and Eraser) showed a crosshair. Its cursor is now the ink's tip: a dot in the colour its stroke takes there, as wide on screen as the stroke, ringed white and dark; the Eraser's is a ring of its reach. Tests: `cursor_tests::each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer`, `cursors_tests::the_ink_tools_show_a_dot_in_the_inks_colour_and_width`. | | 2026-11-28 | patch | M12, #2237: the code block tool takes the `` ` `` key on boards (`tool.codeBlock`), pinned like the other board tool keys (60 undocumented bindings). Test: `shortcut_parity_tests::counts_match_the_docs`. | From 22fe0ceda15732fe31cff41eac6af9d421a38b31 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:33:14 +0700 Subject: [PATCH 23/38] M2: node.set reports the sizing it changes on other layers and variants its set clips (#2178, #2182) An edit that turned another layer Fixed (a child set to Fill turning its hugging parent Fixed, a frame set to Hug turning the children that filled it Fixed) only showed the canvas notice, so a script got no hint why a frame stopped growing. node.set now lists each such layer in `warnings` with its id, name, key and old sizing. A variant grown or moved past a component set that clips and has no auto layout keeps being cut off (the set is sized only when variants are combined or added). node.set now names such a variant in `warnings` and points at layout.add on the set. --- crates/engine/src/al_behaviour_tests.rs | 28 +++++++++++++ crates/engine/src/cmd/edit/props.rs | 40 +++++++++++++++++-- crates/engine/src/cmd/props.rs | 29 +++++++++----- crates/engine/src/variants_discovery_tests.rs | 27 ++++++++++++- docs/auto-layout-parity.md | 5 ++- docs/components-parity.md | 3 +- docs/mcp.md | 6 ++- 7 files changed, 119 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index e07fc3db7..5569ae7f7 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -125,6 +125,34 @@ fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() { assert_eq!(s.message, None); } +/// #2178: through the API, the sizing an edit changes on another layer comes back in `warnings` +/// (the canvas shows it as a notice), naming that layer; an edit that changes no other layer's +/// sizing has none. +#[test] +fn node_set_warns_about_the_other_layers_it_turns_fixed() { + let mut s = Session::new(); + let root = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"})); + let menu = rect(&mut s, root, 200.0, 100.0, "#222222"); + let content = rect(&mut s, root, 600.0, 900.0, "#FFFFFF"); + let warnings = |v: Value| v["warnings"].as_array().cloned().unwrap_or_default(); + let names = |w: &[Value], n: NodeId, key: &str| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with(&format!("{n} ")) && w.contains(key))); + + let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingV": "fill"}})).unwrap()); + assert!(w.is_empty(), "a non-Fill sibling is left, the root keeps hugging: {w:?}"); + let w = warnings(s.execute("node.set", &json!({"id": content, "props": {"sizingV": "fill"}})).unwrap()); + assert_eq!(sizing(&s, root).1, Sizing::Fixed); + assert!(names(&w, root, "sizingV"), "the root turned Fixed: {w:?}"); + assert!(!names(&w, content, "sizingV"), "not the layer edited: {w:?}"); + + // Along the row: the menu filling its width turns the root's width Fixed; hugging it again + // turns the menu's width Fixed. + let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingH": "fill"}})).unwrap()); + assert!(names(&w, root, "sizingH"), "{w:?}"); + let w = warnings(s.execute("node.set", &json!({"id": root, "props": {"sizingH": "hug"}})).unwrap()); + assert_eq!(sizing(&s, menu).0, Sizing::Fixed); + assert!(names(&w, menu, "sizingH") && !names(&w, root, "sizingH"), "the child that filled it: {w:?}"); +} + #[test] fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index 107717384..eb29898dd 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -163,7 +163,7 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { names.join(", ") )); } - let mut hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props); + let hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props); let filling = crate::cmd::props::filling_children(&s.ds()?.doc, &ids, &props); let targets = ids.clone(); let doc = s.doc_mut()?; @@ -194,14 +194,48 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { for f in &targets { figcraft_layout::coherent_sizing(doc, *f); } - hugging.extend(filling); } - if let Some(notice) = crate::cmd::props::fixed_notice(&s.ds()?.doc, &hugging) { + // The canvas shows the notice; a script reads the same side effects in `warnings` (#2178). + let doc = &s.ds()?.doc; + let parents = crate::cmd::props::turned_fixed(doc, &hugging); + let children = crate::cmd::props::turned_fixed(doc, &filling); + for ((n, horizontal), (was, why)) in parents + .iter() + .map(|f| (f, ("Hug", "a layer in it now fills it"))) + .chain(children.iter().map(|f| (f, ("Fill", "the frame it is in now hugs it")))) + { + let key = if *horizontal { "sizingH" } else { "sizingV" }; + warnings.push(format!("{} “{}” ({}): `{key}` {was} → Fixed, because {why}", n.id, n.name, n.kind.type_name())); + } + warnings.extend(clipped_variants(doc, &targets)); + let notice = crate::cmd::props::fixed_notice(&[parents, children].concat()); + if let Some(notice) = notice { s.message = Some(notice); } if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) } } +/// Variants among `ids` that reach past their component set while it clips them and has no auto +/// layout to grow with them: the set keeps its size, as it does on the canvas, so the cut-off part +/// is hidden (#2182). +fn clipped_variants(doc: &figcraft_doc::Document, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|i| { + let n = doc.node(*i)?; + let set = doc.node(n.parent?).filter(|p| matches!(p.kind, NodeKind::ComponentSet { .. }) && p.clip && p.layout.is_none())?; + // The variant's box in the set's space, as `fit_set` measures it. + let b = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect()); + let outside = b.x0 < -0.01 || b.y0 < -0.01 || b.x1 > set.width + 0.01 || b.y1 > set.height + 0.01; + outside.then(|| { + format!( + "{} “{}” reaches past its component set {} “{}”, which clips it: the part outside is hidden (`layout.add` on the set makes it grow with its variants)", + n.id, n.name, set.id, set.name + ) + }) + }) + .collect() +} + /// A `fontStyle` draws in the family's face nearest to it, as a text layer resolves it. When that /// face has another weight or slant than the name asks for ("Black" on a family whose heaviest is /// Bold), say which face it is. Families that aren't installed, and names that match a style or a diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 10291c20a..593da4b4f 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1548,7 +1548,7 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal: } /// The hugging parents that `props` setting Fill on `ids` may turn Fixed, as (parent, horizontal): -/// taken before the edit, for [`fixed_notice`]. +/// taken before the edit, for [`turned_fixed`]. pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map) -> Vec<(NodeId, bool)> { let mut out = Vec::new(); for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] { @@ -1568,7 +1568,7 @@ pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map) -> Vec<(NodeId, bool)> { let mut out = Vec::new(); for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] { @@ -1587,17 +1587,24 @@ pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map Option { - let notes: Vec = before +/// The layers of [`hugging_parents`] or [`filling_children`] that the edit turned Fixed, as +/// (layer, horizontal). +pub(crate) fn turned_fixed<'a>(doc: &'a Document, before: &[(NodeId, bool)]) -> Vec<(&'a Node, bool)> { + before .iter() - .filter_map(|(p, horizontal)| { - let p = doc.node(*p)?; - let now = if *horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v }; - (now == Sizing::Fixed).then(|| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, p.name)) + .filter_map(|(id, horizontal)| { + let n = doc.node(*id)?; + let now = if *horizontal { n.child_layout.sizing_h } else { n.child_layout.sizing_v }; + (now == Sizing::Fixed).then_some((n, *horizontal)) }) - .collect(); + .collect() +} + +/// The notice for the layers the edit turned Fixed ([`turned_fixed`]): "Height set to Fixed for +/// Frame 1", `None` when every one kept its sizing. +pub(crate) fn fixed_notice(fixed: &[(&Node, bool)]) -> Option { + let notes: Vec = + fixed.iter().map(|(n, horizontal)| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, n.name)).collect(); (!notes.is_empty()).then(|| notes.join("; ")) } diff --git a/crates/engine/src/variants_discovery_tests.rs b/crates/engine/src/variants_discovery_tests.rs index b792e727c..17e48ea02 100644 --- a/crates/engine/src/variants_discovery_tests.rs +++ b/crates/engine/src/variants_discovery_tests.rs @@ -3,7 +3,7 @@ //! variants already (it used to put a set inside a set), and Add variant on a main component that //! isn't in a set yet making it one. -use serde_json::json; +use serde_json::{Value, json}; use crate::Session; use crate::cmd::component::{can_add_variant, can_combine_variants}; @@ -177,3 +177,28 @@ fn add_variant_on_a_lone_component_in_auto_layout_keeps_its_place() { assert_eq!(kids(&s, set).len(), 2); healthy(&s); } + +/// #2182: a set without auto layout keeps its size when a variant grows past it (it is sized only +/// when variants are combined or added) and clips it. `node.set` says so in `warnings`; with auto +/// layout on the set, it grows and there is nothing to say. +#[test] +fn a_variant_grown_past_its_clipping_set_is_warned_about() { + let mut s = Session::new(); + let a = component(&mut s, "State=Default", 0.0); + let b = component(&mut s, "State=Hover", 200.0); + let set = idv(&ex(&mut s, "component.combineVariants", json!({"ids": [a, b]}))); + let warns = |v: Value, id: NodeId| { + v["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with(&format!("{id} "))))) + }; + let height = |s: &Session| node(s, set).height; + let before = height(&s); + let grown = s.execute("node.set", &json!({"id": a, "props": {"height": before * 3.0}})).unwrap(); + assert_eq!(height(&s), before, "the set keeps its size"); + assert!(warns(grown, a), "the clipped variant is named"); + // Inside the set: nothing to say. + assert!(!warns(s.execute("node.set", &json!({"id": a, "props": {"height": 40}})).unwrap(), a)); + // With auto layout the set grows with it. + ex(&mut s, "layout.add", json!({"ids": [set], "direction": "horizontal"})); + let grown = s.execute("node.set", &json!({"id": a, "props": {"height": before * 3.0}})).unwrap(); + assert!(height(&s) > before && !warns(grown, a)); +} diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 3a8011bb9..524deed2b 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-27 · **Change:** patch (Shift-dragging a padding grip or gap band snaps to multiples of the big nudge; Alt links the opposite side; a child with its aspect ratio locked that fills one axis and is fixed on the other keeps its proportions: the fixed side follows the filled one; Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size, as measured in Figma (#2091, #2034); padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; Add auto layout picks the sizing, gap and padding Figma does, measured with synthetic rectangles: height hugs, width fixed in a vertical flow or with an Auto gap, Space between for two far-apart layers, padding from the converted frame's left and top offsets, 10 around a single wrapped layer; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-28 · **Change:** patch (`node.set` lists the other layers an edit turned Fixed (a hugging parent, a filling child) in `warnings` (#2178); Shift-dragging a padding grip or gap band snaps to multiples of the big nudge; Alt links the opposite side; a child with its aspect ratio locked that fills one axis and is fixed on the other keeps its proportions: the fixed side follows the filled one; Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size, as measured in Figma (#2091, #2034); padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; Add auto layout picks the sizing, gap and padding Figma does, measured with synthetic rectangles: height hugs, width fixed in a vertical flow or with an Auto gap, Space between for two far-apart layers, padding from the converted frame's left and top offsets, 10 around a single wrapped layer; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -54,7 +54,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Fixed: the frame keeps its size whatever its children need | pass | `sizing_rules` | | Fill: children share the space left after padding, gaps and fixed siblings; across the flow they stretch | pass | `sizing_rules` | | Fill children share by their content area (border-box): a child with more padding or a thicker included inside stroke takes a little more, so the content areas come out the same | **fixed** | "Figma distributes space amongst fill container children by the children's content area instead of by their size, matching the CSS border-box model. A layer with a thicker stroke will take up slightly more of the available width or height, so that its inner content area matches its sibling's" (Use auto layout with CSS Flexbox in mind); the split went by outer size before. Min and max still clamp the outer size; a child's own insets are its padding and its included inside stroke (`nested_tests::fill_children_share_by_content_area`; #1824) | -| Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size (the largest non-Fill sibling, a Fill child's min counted, padding outside); the parent turns Fixed when no non-Fill child is left (toast); Fill across a wrapping row that hugs that axis is not offered | **fixed** | Measured in Figma web (2026-11-08): A 4×20 Fill height beside B 50×40 in a hugging row: A 40, parent height 40 Hug, no notice; B 60: A 60, parent 60 Hug; min height 50 on A: A 50, parent 50 Hug, B 40; both Fill: parent Fixed 40 with the notice "Height set to Fixed for Frame 1"; along the flow (A's width Fill): parent Fixed, "Width set to Fixed for Frame 1"; in a wrapping row hugging its height Fill height is greyed out. FigCraft turned the parent Fixed on both axes, so a `.fig` STRETCH bar beside a two-line text kept its own height (#2091) and a Fill bar froze its row at the text's height of that moment (#2034). `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed`, `fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line`, `fill_along_a_hugging_parent_notes_that_the_width_is_fixed`, `a_fill_childs_min_counts_toward_the_hugging_size`, `a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it`, `fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered`; `behaviour_tests::fill_across_a_hugging_axis_rules`; `nested_tests::coherent_sizing_keeps_fill_across_a_hugging_flow`; `auto_layout_sizing_tests::stretch_children_take_the_row_height_after_a_layout_pass`. Unmeasured: a grid keeps the old rule on both axes; deleting or hiding the last non-Fill child changes no sizing (the children keep their own sizes and the parent hugs the largest) | +| Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size (the largest non-Fill sibling, a Fill child's min counted, padding outside); the parent turns Fixed when no non-Fill child is left (toast; `node.set` lists the layers it turned Fixed in `warnings`, #2178); Fill across a wrapping row that hugs that axis is not offered | **fixed** | Measured in Figma web (2026-11-08): A 4×20 Fill height beside B 50×40 in a hugging row: A 40, parent height 40 Hug, no notice; B 60: A 60, parent 60 Hug; min height 50 on A: A 50, parent 50 Hug, B 40; both Fill: parent Fixed 40 with the notice "Height set to Fixed for Frame 1"; along the flow (A's width Fill): parent Fixed, "Width set to Fixed for Frame 1"; in a wrapping row hugging its height Fill height is greyed out. FigCraft turned the parent Fixed on both axes, so a `.fig` STRETCH bar beside a two-line text kept its own height (#2091) and a Fill bar froze its row at the text's height of that moment (#2034). `al_behaviour_tests::fill_on_a_child_turns_the_hugging_parent_fixed`, `node_set_warns_about_the_other_layers_it_turns_fixed`, `fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line`, `fill_along_a_hugging_parent_notes_that_the_width_is_fixed`, `a_fill_childs_min_counts_toward_the_hugging_size`, `a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it`, `fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered`; `behaviour_tests::fill_across_a_hugging_axis_rules`; `nested_tests::coherent_sizing_keeps_fill_across_a_hugging_flow`; `auto_layout_sizing_tests::stretch_children_take_the_row_height_after_a_layout_pass`. Unmeasured: a grid keeps the old rule on both axes; deleting or hiding the last non-Fill child changes no sizing (the children keep their own sizes and the parent hugs the largest) | | A child resized to the full available space becomes Fill container on that axis | **fixed** | "Child objects of an auto layout frame will also be set to Fill container if they are manually resized to the full available space of the parent frame": a width or height given by a resize, the W/H fields or a canvas handle that equals the frame's size less its padding sets Fill there: across the flow for any child, along the flow for a lone child (beside siblings what is left depends on the gaps, the alignment and overflow, so it is left alone); not in a hugging or wrapping frame or a grid. It stayed Fixed before (`al_behaviour_tests::a_child_resized_to_the_full_available_space_becomes_fill`) | | Hug only on auto layout frames (and text); Fill only in an auto layout flow, never on a top-level frame | pass | `al_behaviour_tests::hug_and_fill_only_where_they_apply` | | Double-click an edge of an auto layout frame's box: Hug contents on that axis; Alt+double-click an edge of a child's box: Fill container | **fixed** | "Tip: Double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Hug contents."; "Hold ⌥ Option or Alt and double-click the vertical or horizontal edge of an auto layout object's bounding box to set it to Fill container." A vertical edge sizes the width, a horizontal one the height; any other layer keeps the double-click's old meaning (#1838). `double_click_tests::a_double_click_on_an_auto_layout_edge_hugs_and_with_alt_fills` | @@ -117,6 +117,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M2, #2178: an edit that turned another layer Fixed (a child set to Fill turning its hugging parent Fixed, a frame set to Hug turning the children that filled it Fixed) showed the notice on the canvas only, so a script driving `node.set` got no hint why a frame stopped growing. `node.set` now lists each such layer in `warnings`, with its id, name, key and old sizing. The rules are unchanged. Test: `al_behaviour_tests::node_set_warns_about_the_other_layers_it_turns_fixed`. Numbers unchanged. | | 2026-11-27 | patch | M2, #2523: Shift-dragging a padding grip or gap band snaps the value to multiples of the big nudge amount (Preferences, 10 by default), so layouts land on an 8 or 10 px grid. Shift no longer links the opposite padding side; Alt does that, and Alt+Shift still links all four without snapping. A headless test drags with a big nudge of 8 and checks padding and gap land on its multiples. | | 2026-11-18 | patch | M2: a child with its aspect ratio locked (`constrainProportions`) that fills one axis of an auto layout frame and is fixed on the other kept the fixed size while the filled side changed, so a photo filling the rest of a row was squashed when it moved into a wider or narrower row (pasted into another artboard, 804 × 969.15 became 1092 × 969.15) and its image, cropped to the layer, stretched with it. The fixed side now follows the filled one at the locked ratio, in a single-line flow along or across it, for a layer that isn't rotated (min and max still apply); without the lock the fixed side stays fixed. A layer whose image is cropped to it, pasted into an auto layout frame where it fills one axis and is fixed on the other, gets its aspect ratio locked, so a pasted image is never squashed. Tests: `locked_ratio_layout_tests` | | 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. | diff --git a/docs/components-parity.md b/docs/components-parity.md index 0dd64a248..c50ed88e9 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (`node.set` warns when a variant reaches past a component set that clips it and has no auto layout (#2182); a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -84,6 +84,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M3, #2182: a variant grown or moved past its component set's edge, in a set without auto layout, is cut off by the set's clipping; the set keeps its size, as it is sized only when variants are combined or added, matching the usual design-tool behaviour. Through the API that was silent. `node.set` now names such a variant in `warnings` and points at `layout.add` on the set, which makes the set grow with its variants. Test: `variants_discovery_tests::a_variant_grown_past_its_clipping_set_is_warned_about`. Numbers unchanged. | | 2026-11-23 | minor | M3: a main component copied from a library file and pasted into another file is an instance of it from that library, which gets enabled in that file, as pasting an instance of it already was and as Figma does with a published component. It used to paste a copy of the main, a new component of that file unlinked from the library. A variant pastes as an instance of that variant. A component the library doesn't offer (hidden from publishing, or added since the last publish) and a main from a file that publishes no library still paste as a copy. Test: `library::tests::a_main_pasted_from_its_library_file_is_an_instance_of_it`. Numbers unchanged | | 2026-11-19 | patch | M3: copying a variant and pasting with that variant, a layer in it or its set selected pasted an instance on the page. Copied variants of one set now paste into that set as new variants (deep copies, as Duplicate makes), under the copied variants where they are now, below the lowest variant with the gap of 20 that Add variant leaves, and the set grows to hold them. Every other paste of a copied main still makes an instance: with nothing selected, into another set, a main that isn't a variant pasted with a set selected, Paste over and Paste to replace on a variant, and an explicit `parent` (even the variant's own set). Tests: `pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others`, `a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant`, `a_variant_pasted_with_another_set_selected_is_an_instance`, `a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance`, `a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance`, `pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant` | | 2026-11-22 | patch | M3: switching an instance to another variant put back the variant's own text in place of the text typed into it when the two variants nest that text layer in different frames (`text › Label` in one, `div › text › Label` in the other), because the typed layer was matched to the new variant's by name path only. Now a text layer of the new variant nothing else matched takes the old text layer of the same name, when exactly one layer on each side has that name; layers inside nested instances still go by their own mains. Two layers of one name stay unmatched, since either could be the one typed into. Test: `typed_text_stays_across_variants_that_nest_it_differently`. Grade unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 4d99c752d..bd1a40def 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -237,7 +237,11 @@ Or in a project's `.mcp.json`: and a parent set to `hug` turns the children that filled it `fixed`. Across the flow the parent keeps hugging and the child takes the line's cross size (the largest sibling that doesn't fill, its min counted, padding outside); the parent turns `fixed` ("Height set to Fixed for ") only when no - such sibling is left, and `fill` across a wrapping row that hugs that axis is refused. A + such sibling is left, and `fill` across a wrapping row that hugs that axis is refused. `node.set` + lists each layer it turned `fixed` this way in `warnings` (such as `2 “Root” (frame): sizingV Hug → Fixed, + because a layer in it now fills it`), and names a variant it leaves reaching past its + component set when the set clips and has no auto layout (the set keeps its size, so the part + outside is hidden; `layout.add` on the set makes it grow with its variants). A layer moved out of auto layout (or whose frame loses it) keeps its size as `fixed`. Fill children share the space like CSS flexbox, within their min/max. - `minWidth` / `maxWidth` / `minHeight` / `maxHeight` (px, `null` removes) bound Hug, Fill and From d5033c9f10b27a9e7fbd81974057f57deee2f189 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:37:50 +0700 Subject: [PATCH 24/38] Pasting into another file keeps the copied corner style Unlinking the copied styles for a paste into another file cleared cornerStyle too, which then failed as a bad value: it is a value (round, chamfer, concave), not a link. Both paths now share one check. --- crates/engine/src/cmd/edit/clipboard.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index ee96cb8df..b83691323 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -547,13 +547,19 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Whether copied property `k` links to a shared style: `fontStyle` and `cornerStyle` are values +/// (a font's style name; round, chamfer, concave). +fn is_style_link(k: &str) -> bool { + k.ends_with("Style") && !k.starts_with("font") && k != "cornerStyle" +} + /// Copied properties `props` without their style and variable links, for a paste into another /// file: the copied ids name the source file's styles and variables, and the same ids here can /// name unrelated ones. The values paste unlinked, and the layer's own links on them go. fn without_links(mut props: Value) -> Value { if let Some(m) = props.as_object_mut() { for (k, v) in m.iter_mut() { - if k.ends_with("Style") && !k.starts_with("font") { + if is_style_link(k) { *v = Value::Null; } else if k == "boundVariables" { *v = json!({}); @@ -580,8 +586,7 @@ pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, prop // values it gave are pasted without a link, so the layer's own link goes too. let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some()); for (k, v) in m.iter_mut() { - // `cornerStyle` is a value (round, chamfer, concave), not a link to a shared style. - if k.ends_with("Style") && !k.starts_with("font") && k != "cornerStyle" && !here(v) { + if is_style_link(k) && !here(v) { *v = Value::Null; } } From 81b507a052b2cca55e2898f6184d187e5ef8b764 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:52:08 +0700 Subject: [PATCH 25/38] M4: a missing well-known UI or code font draws in a close stand-in in its own style (#1237) Text in a family that isn't installed drew in the default face (Inter, Helvetica... in Regular) whatever the family and style, so code set in Menlo came out proportional and SF Pro Bold came out regular. A small table now picks an installed stand-in of similar design and width for the common UI and code families, in the style asked. The family stays reported as missing. --- crates/text/src/fontdb.rs | 30 ++++++++++++++++++++++++++- crates/text/src/fontdb_names_tests.rs | 19 +++++++++++++++++ crates/text/src/layout.rs | 2 +- docs/cli.md | 3 ++- docs/file-format-parity.md | 5 +++-- 5 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index c236f74fb..9dd1078d1 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -1084,6 +1084,14 @@ impl FontDb { faces.into_iter().min_by_key(|f| cost(f)).cloned() } + /// The face to draw `family` + `style` with: the family's own, else for a well-known family + /// that isn't installed a close stand-in in the same style ([`stand_ins`]), else the default. + pub fn find_or_stand_in(&mut self, family: &str, style: &str) -> Option> { + self.find(family, style) + .or_else(|| stand_ins(&family.trim().to_lowercase()).iter().find_map(|f| self.find(f, style))) + .or_else(|| self.default_face()) + } + /// The default face (Inter Regular if embedded, else any system sans). pub fn default_face(&mut self) -> Option> { for fam in ["Inter", "Helvetica Neue", "Helvetica", "Arial", "Segoe UI", "Roboto", "DejaVu Sans", "Liberation Sans", "Noto Sans"] { @@ -1534,6 +1542,26 @@ pub fn apple_alias(key: &str) -> Option<&'static str> { }) } +/// Installed families of similar design and width to draw a well-known UI family with when it +/// isn't installed (`key` lowercase), best first (#1237): the platform UI and code families that +/// designs use most and other systems lack. Text still names the family it asked for, which stays +/// reported as missing. +fn stand_ins(key: &str) -> &'static [&'static str] { + const MONO: &[&str] = &["Cascadia Mono", "Consolas", "SF Mono", "Menlo", "DejaVu Sans Mono", "Liberation Mono", "Courier New"]; + let key = key.trim_start_matches('.'); + if ["sf mono", "menlo", "monaco"].iter().any(|m| key.starts_with(m)) { + MONO + } else if key.starts_with("sf pro") || key.starts_with("sf compact") || apple_alias(key).is_some() { + &["Inter", "Pretendard"] + } else if key.starts_with("google sans") { + &["Roboto", "Inter"] + } else if key.starts_with("euclid") { + &["DM Sans", "Inter"] + } else { + &[] + } +} + /// Convenience: find a face with the global db. /// The family and style of the installed face whose PostScript name is `ps`. pub fn postscript_face(ps: &str) -> Option<(String, String)> { @@ -1545,7 +1573,7 @@ pub fn postscript_face(ps: &str) -> Option<(String, String)> { pub fn find_face(family: &str, style: &str) -> Option> { let mut db = db().write().unwrap_or_else(std::sync::PoisonError::into_inner); - db.find(family, style).or_else(|| db.default_face()) + db.find_or_stand_in(family, style) } /// All family names known to the global db. diff --git a/crates/text/src/fontdb_names_tests.rs b/crates/text/src/fontdb_names_tests.rs index 62bd27be3..25edafa27 100644 --- a/crates/text/src/fontdb_names_tests.rs +++ b/crates/text/src/fontdb_names_tests.rs @@ -145,3 +145,22 @@ fn a_family_per_weight_offers_its_italics_too() { db.add(face("Synthetic Slab Semi Light", "Italic", 350, true)); assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)])); } + +#[test] +fn a_well_known_family_that_isnt_installed_draws_with_a_close_stand_in_in_its_style() { + // #1237: the default face (the first of Inter, Helvetica…, in Regular) stood in for every + // missing family, so code set in Menlo came out proportional and SF Pro Bold came out regular. + let Some(f) = CRAFT_FONTS.first() else { return }; + let face = |family: &str, style: &str| Face::from_bytes(FontBytes::Static(f.bytes), 0, Some(family), Some(style)).unwrap(); + let mut db = FontDb::default(); + let inter = db.add(face("Inter", "Regular")); + let inter_bold = db.add(face("Inter", "Bold")); + let roboto = db.add(face("Roboto", "Regular")); + let consolas = db.add(face("Consolas", "Regular")); + assert!(Arc::ptr_eq(&db.find_or_stand_in("Menlo", "Regular").unwrap(), &consolas), "a code font for a code font"); + assert!(Arc::ptr_eq(&db.find_or_stand_in("Google Sans", "Regular").unwrap(), &roboto), "ahead of the default"); + assert!(Arc::ptr_eq(&db.find_or_stand_in("SF Pro Display", "Bold").unwrap(), &inter_bold), "the style asked for"); + assert!(Arc::ptr_eq(&db.find_or_stand_in("Synthetic Unknown", "Bold").unwrap(), &inter), "others keep the default"); + // The stand-in only draws: the family itself is still missing. + assert!(!db.has_family("Menlo") && !db.has_family("Google Sans")); +} diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 30b5baba2..073bebe90 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -510,7 +510,7 @@ fn shape_text(text: &TextData) -> ShapedText { let mut faces: Vec>> = Vec::with_capacity(styles.len()); let mut style_fallbacks: Vec>> = Vec::with_capacity(styles.len()); for s in &styles { - faces.push(dbw.find(&s.font_family, &s.font_style).or_else(|| dbw.default_face())); + faces.push(dbw.find_or_stand_in(&s.font_family, &s.font_style)); style_fallbacks.push(dbw.fallbacks_for(&s.font_style)); } // Colour emoji are their own, large faces (Apple Color Emoji is ~180 MB): they are read only diff --git a/docs/cli.md b/docs/cli.md index 28facebab..9451a9d2f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -107,7 +107,8 @@ be open to the public: [server.md](server.md#running-a-public-server)). See [ser Pages, node counts, top-level frames (id, type, name, size), style/variable/image counts. Repairs of a damaged file and import warnings go to stderr as `note:` lines (`notes` with `--json`). Fonts the file names that aren't installed are listed as `missing font` lines (`missingFonts: [{family, -layers}]` with `--json`); their text renders in a fallback font. +layers}]` with `--json`); their text renders in a fallback font (a close stand-in for well-known UI +and code families such as SF Pro or Menlo, see `docs/file-format-parity.md`). Every subcommand that reads a file also takes the public REST API file JSON (the response of `GET /v1/files/:key` or of its nodes endpoint, written to a `.json` file): it is imported on the fly. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 32bc84481..a67ded0c4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (`.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (text in a well-known UI or code family that isn't installed draws in a close stand-in in its own style instead of the default sans (#1237); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -197,12 +197,13 @@ scales and empty-style clears; they have not been checked in other software. | Conflicting fonts | an uploaded organization font comes first, then fonts installed on the device, then Figma's web fonts (help center, "Manage conflicting fonts") | a font loaded with `text.loadFont` wins over the built-in and installed faces of the same family and style, the latest load over earlier ones (#2092); installed versus built-in order is unchanged, and browser local fonts count as installed | | Bundled/shared fonts | Google Fonts in the cloud | optional `CRAFT_FONTS_DIR` build input (storytold/craft-fonts) | | Variable fonts | yes | yes (axes, named instances, per-range axis values) | -| Missing-font replacement on open | yes | listed, not replaced: in the desktop app the Missing fonts window opens after a file that uses them opens and from Text ▸ Missing fonts (`text.missingFonts`; `figcraft-cli info` prints `missing font` lines), and their text draws in a fallback font. A family the font store has (Google Fonts, Noto) downloads from the window once the user allows downloading fonts (`font.download`, #754): pinned, checksum-verified files into the Craft apps' shared font folder, after which the text draws in it. A family is found however a file names it: by the legacy name of one of its weights ("Family Medium") or by the typographic name of a family installed one family per weight, and spelt with other case, spaces or hyphens (#1292). No substitute picker | +| Missing-font replacement on open | yes | listed, not replaced: in the desktop app the Missing fonts window opens after a file that uses them opens and from Text ▸ Missing fonts (`text.missingFonts`; `figcraft-cli info` prints `missing font` lines), and their text draws in a fallback font: for a well-known UI or code family a close installed stand-in in the same style (SF Pro and SF Compact: Inter, then Pretendard; Google Sans: Roboto; Menlo, Monaco and SF Mono: Cascadia Mono, Consolas or another monospaced font; Euclid: DM Sans), else the default sans; the family stays listed as missing (#1237). A family the font store has (Google Fonts, Noto) downloads from the window once the user allows downloading fonts (`font.download`, #754): pinned, checksum-verified files into the Craft apps' shared font folder, after which the text draws in it. A family is found however a file names it: by the legacy name of one of its weights ("Family Medium") or by the typographic name of a family installed one family per weight, and spelt with other case, spaces or hyphens (#1292). No substitute picker | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M4, #1237: text set in a family that isn't installed drew in the default face, the first of Inter, Helvetica, Arial… in Regular, whatever the family and style, so code set in Menlo came out proportional and SF Pro Bold came out regular. A well-known UI or code family now draws in the first installed stand-in of similar design and width, in the style asked: SF Pro and SF Compact in Inter (then Pretendard), Google Sans in Roboto, Menlo, Monaco and SF Mono in Cascadia Mono, Consolas or another monospaced font, Euclid in DM Sans; other families keep the default. The stand-in only draws: the family stays listed as missing (Missing fonts, `figcraft-cli info`) and the layer keeps its name. Not built: overriding the table (an environment variable or a command) and naming the stand-in in the missing-fonts list. Test: `fontdb_names_tests::a_well_known_family_that_isnt_installed_draws_with_a_close_stand_in_in_its_style` | | 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged | | 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. | | 2026-11-20 | patch | M6, #2501 follow-up: JPG export inherited 4:2:0 chroma subsampling from the `craft-image-codecs` defaults when #2501 moved it to the shared encoder, so fine colour detail blurred. It asks for 4:4:4 again, as before the cutover (#2521). Tests: `render::tests::jpeg_export_keeps_full_chroma`, and `export_formats_and_what_each_keeps` checks an 8 × 8 corner block clear of the ellipse. Numbers unchanged. | From 15fa211bb4cda88df6224c55b8ea822c361027b6 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 03:53:18 -0700 Subject: [PATCH 26/38] Contributors: add Bryton Cooper --- contributors/people.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 8db486ad1..ac927b5a1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -145,3 +145,8 @@ display_name = "Terra854" [people.andrejskvorc] real_name = "Andrej Skvorc" sync_github_name = true + +[people.brytoncooper] +real_name = "Bryton Cooper" +display_name = "Bryton Cooper" +sync_github_name = true From 51a2125118cc87b99b7c87c27ef9af5ab9e25c4c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 18:01:32 +0700 Subject: [PATCH 27/38] M3: Current variant dropdowns keep the "This variant's value" hint, so its translations stay in use (#2346) --- crates/ui-egui/locales/en.toml | 1 + crates/ui-egui/src/panels/component_panel.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index c0c3fe871..5b092ddb8 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -461,6 +461,7 @@ name = "English" "Default" = "Default" "Default content" = "Default content" "Default value (the top-left variant)" = "Default value (the top-left variant)" +"This variant's value" = "This variant's value" "Current variant" = "Current variant" "Select component set" = "Select component set" "Delay" = "Delay" diff --git a/crates/ui-egui/src/panels/component_panel.rs b/crates/ui-egui/src/panels/component_panel.rs index 2ef05c016..b041e5c7c 100644 --- a/crates/ui-egui/src/panels/component_panel.rs +++ b/crates/ui-egui/src/panels/component_panel.rs @@ -245,7 +245,7 @@ fn current_variant_ui(app: &mut FigApp, ui: &mut Ui, doc: &Document, variant: &N row(ui, 32.0, |ui| { prop_label(ui, k, Icon::ComponentSet); let w = ui.available_width().max(60.0); - let resp = widgets::dropdown(ui, &cur, w, None); + let resp = widgets::dropdown(ui, &cur, w, None).on_hover_text(tr("This variant's value")); menu_popup(&resp).show(|ui| { for v in vals { if menu_item(ui, v, "") { From 8750ba81bb76f1eb5f3630d163a27a45e9c41301 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 18:16:03 +0700 Subject: [PATCH 28/38] M9: .jam import: connectors on the page come in as board connectors attached to what they join (#1808) A whiteboard file's connectors came in as loose vectors, so moving a shape left them behind. On a whiteboard the mapper's adapter now writes a board connector on each connector drawn as one line on the page: its ends name the layers it joins (a named magnet is that side, an automatic one the side facing the other end, an end without a magnet keeps its point on the layer) or a free page point, with its routing. The REST importer makes the vector a native board connector once every layer is in, so the board routes it again when what it joins moves. The import report counts only the connectors that stayed vectors. Labelled connectors, connectors inside frames and connectors in design files are unchanged. --- crates/format/src/fig/board_import_tests.rs | 71 ++++++++++++ crates/format/src/fig/map.rs | 119 ++++++++++++++++++++ crates/format/src/rest.rs | 39 ++++++- docs/boards-parity.md | 5 +- docs/file-format-parity.md | 5 +- 5 files changed, 231 insertions(+), 8 deletions(-) diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index bff5ad32f..c0a148ce3 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -720,3 +720,74 @@ fn a_jam_shape_whose_text_only_the_outer_node_carries_keeps_it() { assert!(frame.board.is_none(), "the generated layers keep the outer text"); assert!(frame.children.iter().filter_map(|id| doc.node(*id)?.kind.text()).any(|t| t.characters == "Outer saved text")); } + +/// A synthetic whiteboard of two boxes and connectors: one joining them by named and automatic +/// magnets, one from a box to a free point, and one inside a frame. +fn connected_board() -> Vec { + let box_at = |id, name: &str, x| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, 600.0))]); + let joined = |id, name: &str, parent: u64, start: Kv<'static>, finish: Kv<'static>| { + node( + id, + Some((parent, "+")), + "CONNECTOR", + name, + vec![ + ("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])), + ("connectorStart", start), + ("connectorEnd", finish), + ("connectorLineStyle", e("ELBOWED")), + ], + ) + }; + let on = |node, magnet: &'static str| o(vec![("endpointNodeID", g(node)), ("magnet", e(magnet))]); + let message = o(vec![ + ( + "nodeChanges", + arr(vec![ + node(0, None, "DOCUMENT", "Synthetic board", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + box_at(60, "A", 0.0), + box_at(61, "B", 300.0), + joined(62, "Joined", 1, on(60, "BOTTOM"), on(61, "AUTO")), + joined(63, "Loose", 1, on(60, "NONE"), o(vec![("position", xy(50.0, 900.0))])), + node(64, Some((1, "-")), "FRAME", "Frame", vec![("size", xy(400.0, 400.0)), ("transform", at(0.0, 0.0))]), + joined(65, "Framed", 64, on(60, "AUTO"), on(61, "AUTO")), + ]), + ), + ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(triangle_blob()))])])), + ]); + let mut bytes = canvas(&board_schema(), &message); + bytes.splice(..8, *b"fig-jam."); + bytes +} + +/// #1808: on a whiteboard a connector is a native board connector attached to the layers it joins, +/// so it follows them when they move; a free end keeps its point. +#[test] +fn a_jam_connector_is_attached_to_the_layers_it_joins() { + use figcraft_doc::{BoardItem, End, Routing, Side}; + let (doc, warnings) = import(&connected_board(), "Synthetic board").unwrap(); + let (a, b) = (named(&doc, "A").id, named(&doc, "B").id); + let Some(BoardItem::Connector(c)) = &named(&doc, "Joined").board else { panic!("{:?}", named(&doc, "Joined").board) }; + assert!(matches!(c.from, End::Node { node, side: Side::Bottom, .. } if node == a), "{c:?}"); + assert!(matches!(c.to, End::Node { node, side: Side::Auto, .. } if node == b), "{c:?}"); + assert_eq!(c.routing, Routing::Elbow); + assert!(matches!(named(&doc, "Joined").kind, figcraft_doc::NodeKind::Vector { .. }), "it keeps the line it was drawn with"); + + let Some(BoardItem::Connector(loose)) = &named(&doc, "Loose").board else { panic!("the loose connector is attached too") }; + assert!(matches!(loose.from, End::Node { node, .. } if node == a)); + assert_eq!(loose.to, End::Point { x: 50.0, y: 900.0 }, "a free end keeps its point on the page"); + + assert!(named(&doc, "Framed").board.is_none(), "one inside a frame stays a plain line"); + let note: Vec<_> = warnings.iter().filter(|w| w.starts_with("connector layers import as vectors")).collect(); + assert_eq!(note, ["connector layers import as vectors"], "only the one left a line is reported: {warnings:?}"); +} + +/// In a `.fig` design file connectors stay plain lines. +#[test] +fn a_fig_connector_stays_a_line() { + let mut bytes = connected_board(); + bytes.splice(..8, *b"fig-kiwi"); + let (doc, _) = import(&bytes, "Synthetic design").unwrap(); + assert!(doc.nodes().all(|n| n.board.is_none())); +} diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index f075c1526..8fff15bd2 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -78,6 +78,8 @@ pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) - mapped.networks.into_iter().map(|n| serde_json::to_value(n?).ok().and_then(|v| crate::rest::network(&v))).collect(); if board { native_board_shapes(msg, &mut mapped.json, &mut mapped.warnings); + let native = native_board_connectors(msg, &mut mapped.json); + uncount(&mut mapped.warnings, "connector layers import as vectors", native); } (mapped.json, mapped.warnings, networks) } @@ -199,6 +201,123 @@ fn apply_native_board_shape(rest_node: &mut Value, origin: &str, shape: BoardSha } } +/// A record's `guid` as the `session:local` origin the mapped layers carry. +fn origin(guid: &Kv) -> Option { + let (session, local) = guid.get("sessionID").and_then(Kv::f64).zip(guid.get("localID").and_then(Kv::f64))?; + Some(format!("{}:{}", session as u64, local as u64)) +} + +/// Every mapped layer of `json` (bounded by `max_nodes` already), depth first. +fn each_layer(json: &mut Value, f: &mut impl FnMut(&mut Value)) { + if json.get(craft_fig::rest::FIG_SOURCE_FIELD).is_some() { + f(json); + } + match json { + Value::Object(fields) => fields.values_mut().for_each(|child| each_layer(child, f)), + Value::Array(items) => items.iter_mut().for_each(|child| each_layer(child, f)), + _ => {} + } +} + +/// A mapped layer's source origin. +fn layer_origin(layer: &Value) -> Option<&str> { + layer.get(craft_fig::rest::FIG_SOURCE_FIELD)?.get("origin")?.as_str() +} + +/// A whiteboard file's connectors are native board connectors: the line the shared mapper drew +/// stays, and the connector is attached to the layers it joins, so FigCraft routes it again when +/// they move. Only a connector drawn as one line on the page itself is adapted: a free end's +/// point is in its parent's space, the page's only there, and one with a label is a frame holding +/// its line and label, which stays as it is. +/// Returns how many it attached. +fn native_board_connectors(msg: &Kv, json: &mut Value) -> usize { + let Some(changes) = msg.get("nodeChanges") else { return 0 }; + let ty = |n: &Kv| n.get("type").and_then(Kv::str).map(str::to_owned); + let pages: std::collections::HashSet = + changes.list().iter().filter(|n| ty(n).as_deref() == Some("CANVAS")).filter_map(|n| origin(n.get("guid")?)).collect(); + let mut connectors = std::collections::HashMap::new(); + for node in changes.list() { + if ty(node).as_deref() != Some("CONNECTOR") + || node.get("parentIndex").and_then(|p| p.get("guid")).and_then(origin).is_none_or(|p| !pages.contains(&p)) + { + continue; + } + let Some(id) = node.get("guid").and_then(origin) else { continue }; + let end = |key: &str| -> Option { + let e = node.get(key)?; + let Some(target) = e.get("endpointNodeID").and_then(origin) else { + let p = e.get("position")?; + return Some(serde_json::json!({"x": p.get("x").and_then(Kv::f64)?, "y": p.get("y").and_then(Kv::f64)?})); + }; + let magnet = e.get("magnet").and_then(Kv::str); + let side = match magnet { + Some("TOP") => "top", + Some("RIGHT") => "right", + Some("BOTTOM") => "bottom", + Some("LEFT") => "left", + _ => "auto", + }; + let mut out = serde_json::json!({"node": target, "side": side}); + // Without a magnet the end sits where it was put on the layer. + if matches!(magnet, None | Some("NONE")) + && let Some(r) = e.get("relativePosition") + && let Some((x, y)) = r.get("x").and_then(Kv::f64).zip(r.get("y").and_then(Kv::f64)) + { + out["at"] = serde_json::json!([x, y]); + } + Some(out) + }; + let routing = match node.get("connectorLineStyle").and_then(Kv::str) { + Some("ELBOWED") => "elbow", + Some("CURVED") => "curved", + _ => "straight", + }; + if let Some((from, to)) = end("connectorStart").zip(end("connectorEnd")) { + connectors.insert(id, serde_json::json!({"type": "connector", "from": from, "to": to, "routing": routing})); + } + } + if connectors.is_empty() { + return 0; + } + // The mapped layers' REST ids by origin: a connector's ends name the layers it joins by them. + let mut ids = std::collections::HashMap::new(); + let mut attached = 0; + each_layer(json, &mut |layer| { + if let (Some(origin), Some(id)) = (layer_origin(layer), layer.get("id").and_then(Value::as_str)) { + ids.entry(origin.to_owned()).or_insert_with(|| id.to_owned()); + } + }); + each_layer(json, &mut |layer| { + if layer["type"] != "VECTOR" { + return; + } + let Some(mut board) = layer_origin(layer).and_then(|o| connectors.get(o)).cloned() else { return }; + for key in ["from", "to"] { + if let Some(node) = board[key].get("node").and_then(Value::as_str) { + match ids.get(node) { + Some(id) => board[key]["node"] = Value::String(id.clone()), + // A layer left out (or not a layer here) leaves the connector a plain line. + None => return, + } + } + } + layer["board"] = board; + attached += 1; + }); + attached +} + +/// Take `n` off the count of warning `what` (`what (×count)`, or `what` once), dropping it at none. +fn uncount(warnings: &mut Vec, what: &str, n: usize) { + let Some(i) = warnings.iter().position(|w| w.starts_with(what)) else { return }; + let count = warnings[i].strip_prefix(what).and_then(|r| r.trim().strip_prefix("(×")?.strip_suffix(')')?.parse::().ok()).unwrap_or(1); + match count.saturating_sub(n) { + 0 => _ = warnings.remove(i), + 1 => warnings[i] = what.to_string(), + left => warnings[i] = format!("{what} (×{left})"), + } +} + /// The shared snapshot mapper omits a generated text child whose characters are empty. FigCraft /// still keeps that empty child on a native shape, matching its prior mapper behavior. fn generated_empty_body(node: &Kv) -> bool { diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 7e7c80422..c024661d3 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -767,10 +767,15 @@ impl<'a> Ctx<'a> { } /// The `board` field (a FigCraft extension): what the object is on a board. A sticky or shape - /// is set at once; anything else, or junk, is ignored with a warning. + /// is set at once, a connector (a vector) once every layer is in and its ends can be found; + /// anything else, or junk, is ignored with a warning. fn board_item(&mut self, n: &mut Node, b: &'a Value) { // A sticky or shape is a frame holding its layers: on anything else it is ignored. let frame = n.kind.is_frame_like(); + if text(b, "type") == Some("connector") && matches!(n.kind, NodeKind::Vector { .. }) { + self.pending_boards.push((n.id, b)); + return; + } let item = match text(b, "type") { Some("sticky") if frame => { let author = text(b, "author").unwrap_or("").trim(); @@ -789,10 +794,36 @@ impl<'a> Ctx<'a> { /// Board items that name other layers (connector ends, a label's connector), once every /// layer is imported and `ids` can resolve them. + /// A connector's `from` and `to` are each `{node: , side?, at?: [x, y]}` (`at`: where + /// on the layer, as fractions of its box) or a page point `{x, y}`; `routing` is straight, + /// elbow or curved. One whose ends don't resolve is ignored with a warning (it stays a vector). fn resolve_boards(&mut self) { - for (id, _) in std::mem::take(&mut self.pending_boards) { - let name = self.doc.node(id).map(|n| n.name.clone()).unwrap_or_default(); - self.warn(format!("unknown board item on {name} was ignored")); + for (id, b) in std::mem::take(&mut self.pending_boards) { + let end = |e: &Value| -> Option { + let Some(rest_id) = text(e, "node") else { + let (x, y) = (num(e, "x")?, num(e, "y")?); + let c = |v: f64| v.clamp(-MAX_COORD, MAX_COORD); + return (x.is_finite() && y.is_finite()).then(|| figcraft_doc::End::Point { x: c(x), y: c(y) }); + }; + let node = *self.ids.get(rest_id).filter(|node| **node != id)?; + let side = text(e, "side").and_then(figcraft_doc::Side::from_id).unwrap_or_default(); + let at = list(e, "at").iter().map(Value::as_f64).collect::>>().and_then(|v| match v.as_slice() { + [x, y] if x.is_finite() && y.is_finite() => Some([x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]), + _ => None, + }); + Some(figcraft_doc::End::Node { node, side, at }) + }; + let ends = b.get("from").and_then(end).zip(b.get("to").and_then(end)); + let routing = text(b, "routing").and_then(figcraft_doc::Routing::from_id).unwrap_or_default(); + match (ends, self.doc.node_mut(id)) { + (Some((from, to)), Some(n)) => { + n.board = Some(figcraft_doc::BoardItem::Connector(figcraft_doc::Connector { from, to, routing, path: None, branch: false })); + } + (_, n) => { + let name = n.map(|n| n.name.clone()).unwrap_or_default(); + self.warn(format!("unknown board item on {name} was ignored")); + } + } } } diff --git a/docs/boards-parity.md b/docs/boards-parity.md index b7739e6c2..fe4f35cb9 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-28 · **Change:** minor (the Pencil, Marker, Highlighter and Eraser show a round tip at the pointer, in the ink's colour and as wide as the stroke (#2641); code blocks from the toolbar's Text tools flyout or the `` ` `` key, a language menu in the bar over a selected block, and handles on a block's left and right edges only (#2237); a mind map node dropped on another node becomes its child, with everything under it (#2226); code blocks colour keywords, strings, numbers and comments by their language (#2237); the ink colour and stroke weight of the Marker, Highlighter and Pencil are chosen before drawing, in a bar above the toolbar (#2395); mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-28 · **Change:** minor (a `.jam` file's connectors come in as native board connectors attached to the layers they join (#1808); the Pencil, Marker, Highlighter and Eraser show a round tip at the pointer, in the ink's colour and as wide as the stroke (#2641); code blocks from the toolbar's Text tools flyout or the `` ` `` key, a language menu in the bar over a selected block, and handles on a block's left and right edges only (#2237); a mind map node dropped on another node becomes its child, with everything under it (#2226); code blocks colour keywords, strings, numbers and comments by their language (#2237); the ink colour and stroke weight of the Marker, Highlighter and Pencil are chosen before drawing, in a bar above the toolbar (#2395); mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); a `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~48%, ready ~30% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -63,12 +63,13 @@ all end with the same geometry. | Audio and huddles | missing | | | AI features (summaries, sorting stickies, generating boards) | missing | | | Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none | -| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as native shapes for the 23 kinds FigCraft draws (the file's paints and weight kept, the outline FigCraft's own; the 7 others stay frames with their generated layers) and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) | +| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as native shapes for the 23 kinds FigCraft draws (the file's paints and weight kept, the outline FigCraft's own; the 7 others stay frames with their generated layers) and its connectors on the page as native board connectors attached to the layers they join, so they follow them when moved (#1808; the line drawn on import stays until then, and an elbowed one keeps the path it was saved with, #1910); a connector with a label or inside a frame still comes in as a vector or a frame; no export | see [`file-format-parity.md`](file-format-parity.md) | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | M9, #1808 (step 3): a `.jam` connector came in as a loose vector, so moving a shape it joined left it behind. On a whiteboard the `.fig` mapper's adapter now writes a `board` connector (a FigCraft extension of the REST JSON: `{type: "connector", from, to, routing}`, each end `{node, side, at?}` or a page point `{x, y}`) on a connector drawn as one line on the page: its ends name the layers it joins (a named magnet is that side, `AUTO`, `CENTER` or none the side facing the other end, and an end without a magnet keeps its point on the layer as `at`), and the REST importer, once every layer is in, makes the vector a native board connector (`BoardItem::Connector`) with them, so it is routed again when they move. The line it was drawn with stays until then. A connector with a label (a frame holding its line and label), one inside a frame or section, and every connector in a `.fig` design file stay as they were, and the import report counts only those as vectors. Tests: `board_import_tests::a_jam_connector_is_attached_to_the_layers_it_joins`, `a_fig_connector_stays_a_line`. Numbers unchanged | | 2026-11-28 | minor | M12, #2641 (part 1): the Pencil, Marker, Highlighter and Eraser showed the shape tools' crosshair, so the ink's colour and width were seen only once a stroke landed. They now ask for an ink cursor (`Cursor::Ink`): a dot at the pointer in the colour a stroke started there takes (the Pencil's automatic ink as it resolves over that page or frame) and as wide on screen as the stroke will be (`Session::ink_tip`), ringed white then dark so it shows on light and dark pages; the Eraser's is a ring as wide as it reaches. `ui.inspect` names it `ink`. The eraser's two modes and lasso selection are still to come. Tests: `cursor_tests::the_ink_tools_tip_takes_the_inks_colour_and_width`, `cursors_tests::the_ink_tools_show_a_dot_in_the_inks_colour_and_width`. Numbers unchanged. | | 2026-11-28 | minor | M12, #2237 (step 2 of 4): code blocks could only be made by command, their language changed only by command, and their four corner handles resized a block whose height then snapped back. The toolbar's Text tools flyout now ends in Code block (`tool.codeBlock`, also on the `` ` `` key, boards only; the board's text group remembers its own last tool, apart from a design file's): a click places a block centred there and starts typing in it, as Code block from the Actions palette now does too. The bar over a selected block ends in a language menu of the 16 languages (`board.setLanguage`), the block's own checked and its name on the button. A selected block draws a handle on the middle of its left and right edges instead of its corner squares, and only those two edges resize it (`tools::handle_at`); a press on a corner or on the top or bottom edge moves it. The key is pinned with the other board tool keys. Tests: `board_code_tests::a_block_has_handles_on_its_left_and_right_edges_only` and `the_tool_places_a_block_centred_on_the_click_and_types_in_it` (engine), `board_ui_tests::the_text_flyout_and_the_backtick_key_choose_the_code_block_tool_a_click_places_and_types_in` and `a_selected_code_block_has_a_language_menu`. Numbers unchanged (line numbers and `.jam` import still to come). | | 2026-11-28 | patch | M12, #2226 (part of step 3): a mind map node dragged onto another node went back to its place, so the only way to give it another parent was to delete it and add it again. The normalize pass now hangs a node that moved by itself and whose middle is on another node of the page from that node, with everything under it: its branch leaves the new parent, on that node's side, and the map lays itself out again. The first node (which has no branch) carries its map as before, and a drop on a node under the moved one changes nothing; dropped on its own parent it keeps it, taking its place among its siblings by its middle as any child moved by hand does. It works the same for a drag, a nudge, `transform.move` and a live session's edit. Detaching a node by dragging it away is not in this change: a child moved by hand still goes back or swaps with a sibling. Test: `board_mindmap_tests::a_node_dropped_on_another_node_becomes_its_child_with_its_own`. | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 32bc84481..37b94ded0 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (`.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (`.jam` import: connectors on the page come in as native board connectors attached to the layers they join (#1808); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -20,7 +20,7 @@ and prototype interactions are still unchecked there. | `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations (with their corner radius and smoothing, #2222), components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers (Figma writes a list's start on every line; import keeps it only on the item where the list starts counting, so a list split later restarts at 1, #2273), vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | -| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | +| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (see [boards-parity](boards-parity.md)); connectors drawn on the page as native board connectors attached to the layers they join, so they follow them when moved (#1808; one with a label or inside a frame stays a frame or vector; an elbowed connector keeps the path it was saved with, #1910); tables, stamps, code blocks and the like come in as frames with their text, with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | | REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | @@ -203,6 +203,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | M9, #1808 (step 3): a `.jam` connector came in as a loose vector, so moving a shape it joined left it behind. On a whiteboard the `.fig` mapper's adapter now writes a `board` connector (a FigCraft extension of the REST JSON: `{type: "connector", from, to, routing}`, each end `{node, side, at?}` or a page point `{x, y}`) on a connector drawn as one line on the page: its ends name the layers it joins (a named magnet is that side, `AUTO`, `CENTER` or none the side facing the other end, and an end without a magnet keeps its point on the layer as `at`), and the REST importer, once every layer is in, makes the vector a native board connector (`BoardItem::Connector`) with them, so it is routed again when they move. The line it was drawn with stays until then. A connector with a label (a frame holding its line and label), one inside a frame or section, and every connector in a `.fig` design file stay as they were, and the import report counts only those as vectors. Tests: `board_import_tests::a_jam_connector_is_attached_to_the_layers_it_joins`, `a_fig_connector_stays_a_line`. Numbers unchanged | | 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged | | 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. | | 2026-11-20 | patch | M6, #2501 follow-up: JPG export inherited 4:2:0 chroma subsampling from the `craft-image-codecs` defaults when #2501 moved it to the shared encoder, so fine colour detail blurred. It asks for 4:4:4 again, as before the cutover (#2521). Tests: `render::tests::jpeg_export_keeps_full_chroma`, and `export_formats_and_what_each_keeps` checks an 8 × 8 corner block clear of the ellipse. Numbers unchanged. | From 6b3c4c2bf4e0332614ad2ad5d99946e0391d02a1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:52:49 +0700 Subject: [PATCH 29/38] Control channel: idle connections give up their slot; request lines share one memory budget (#1110, #1111) With all 8 connection slots taken, a new client now takes the slot of the connection that has waited longest for its client; a connection whose request the app is running keeps its slot. Request lines are counted as they arrive against 64 MiB shared by all connections until they are answered, so eight clients can no longer make the app hold eight 32 MiB lines and their parsed trees. --- apps/figcraft/src/control_server.rs | 122 +++++++++++++++++++--- apps/figcraft/src/control_server_tests.rs | 88 +++++++++++----- docs/control-protocol.md | 11 +- 3 files changed, 174 insertions(+), 47 deletions(-) diff --git a/apps/figcraft/src/control_server.rs b/apps/figcraft/src/control_server.rs index a1da75f3f..97d9f60bd 100644 --- a/apps/figcraft/src/control_server.rs +++ b/apps/figcraft/src/control_server.rs @@ -1,10 +1,11 @@ //! Localhost JSON-lines control server: each line `{"id", "method", "params"}` is queued for the UI //! thread; the reply line `{"id", "ok", "result" | "error"}` is written when the frame handled it. -use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::io::{BufRead, BufReader, Write}; +use std::net::{Shutdown, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; use figcraft_engine::events::{self, EventLog}; use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate, RequestState}; @@ -14,6 +15,9 @@ type Queue = Arc>>; type CtxSlot = Arc>>; const MAX_LINE: usize = 32 * 1024 * 1024; +/// Bytes of request lines all connections hold at once (#1111): a line is counted as it is read +/// and until its reply is written, so eight clients can't make the app hold eight full lines. +const MAX_IN_FLIGHT: usize = 64 * 1024 * 1024; const MAX_CONNECTIONS: usize = 8; const MAX_QUEUED_REQUESTS: usize = 8; const TIMEOUT: Duration = Duration::from_secs(60); @@ -115,8 +119,9 @@ pub fn start(port: u16, busy: Duration, queue: Queue, ctx: CtxSlot, events: Arc< eprintln!("FigCraft control server listening on 127.0.0.1:{port}"); let spawned = std::thread::Builder::new().name("figcraft-control".into()).spawn(move || { let mut workers = Vec::new(); + let budget = Arc::new(AtomicUsize::new(0)); for stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) { - spawn_connection(stream, queue.clone(), ctx.clone(), events.clone(), &mut workers, TIMEOUT); + spawn_connection(stream, queue.clone(), ctx.clone(), events.clone(), &budget, &mut workers, TIMEOUT); } }); if let Err(e) = spawned { @@ -129,45 +134,129 @@ fn accepted(incoming: impl Iterator>, mut wait: imp incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok()) } +/// Since when a connection has been waiting for its client (`None` while the UI runs one of its +/// requests). +type Idle = Arc>>; + +/// One connection's thread, a handle on its socket and since when it has been idle. +struct Worker { + thread: std::thread::JoinHandle<()>, + stream: TcpStream, + idle: Idle, +} + fn spawn_connection( stream: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc, - workers: &mut Vec>, + budget: &Arc, + workers: &mut Vec, timeout: Duration, ) { - workers.retain(|worker| !worker.is_finished()); + workers.retain(|worker| !worker.thread.is_finished()); if workers.len() >= MAX_CONNECTIONS { - return; + // A client keeping slots it doesn't use can't lock others out (#1110): the connection idle + // longest (between requests or in `events.poll`; clients reconnect) gives its slot up. One + // whose request the UI is running keeps it. + let idle = |w: &Worker| *w.idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let longest = workers.iter().enumerate().filter_map(|(i, w)| Some((i, idle(w)?))).min_by_key(|(_, since)| *since); + let Some((i, _)) = longest else { return }; + let _ = workers.swap_remove(i).stream.shutdown(Shutdown::Both); } + let Ok(handle) = stream.try_clone() else { return }; + let idle: Idle = Arc::new(Mutex::new(Some(Instant::now()))); + let (budget, mine) = (budget.clone(), idle.clone()); match std::thread::Builder::new().name("figcraft-control-conn".into()).spawn(move || { - let _ = serve_with_events(stream, queue, ctx, events, timeout); + let _ = serve_with_events(stream, queue, ctx, events, &budget, &mine, timeout); }) { - Ok(worker) => workers.push(worker), + Ok(thread) => workers.push(Worker { thread, stream: handle, idle }), Err(e) => log::error!("control connection thread: {e}"), } } +/// Bytes of a line reserved from the shared budget, given back when dropped. +struct Held<'a> { + budget: &'a AtomicUsize, + bytes: usize, +} + +impl Drop for Held<'_> { + fn drop(&mut self) { + self.budget.fetch_sub(self.bytes, Ordering::SeqCst); + } +} + +/// What [`read_line`] read. +enum Line<'a> { + End, + /// A line, its newline included if it had one; longer than [`MAX_LINE`] when it was too long. + Read(Held<'a>), + /// The connections hold [`MAX_IN_FLIGHT`] bytes already. + Busy, +} + +/// Read a line of at most [`MAX_LINE`] bytes plus its newline into `line`, taking its bytes from +/// `budget` as they arrive. +fn read_line<'a>(reader: &mut impl BufRead, line: &mut Vec, budget: &'a AtomicUsize) -> std::io::Result> { + let mut held = Held { budget, bytes: 0 }; + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(if line.is_empty() { Line::End } else { Line::Read(held) }); + } + let room = MAX_LINE + 1 - line.len(); + let (take, done) = match buf.iter().position(|b| *b == b'\n') { + Some(i) if i < room => (i + 1, true), + _ => (buf.len().min(room), false), + }; + if budget.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| used.checked_add(take).filter(|t| *t <= MAX_IN_FLIGHT)).is_err() { + return Ok(Line::Busy); + } + held.bytes += take; + line.extend_from_slice(&buf[..take]); + reader.consume(take); + if done || line.len() > MAX_LINE { + return Ok(Line::Read(held)); + } + } +} + /// Serve one control connection: read bounded JSON lines, reject oversized frames and a /// full queue, queue one request, wait under its gate, and write one reply. Non-JSON input /// answers with an error and closes the connection so HTTP body lines cannot become commands. /// Serve a connection with a private event log (the tests; the app shares its session's log). #[cfg(test)] fn serve(out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> std::io::Result<()> { - serve_with_events(out, queue, ctx, Arc::new(EventLog::default()), timeout) + serve_with_events(out, queue, ctx, Arc::new(EventLog::default()), &AtomicUsize::new(0), &Mutex::new(None), timeout) } -fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc, timeout: Duration) -> std::io::Result<()> { +fn serve_with_events( + mut out: TcpStream, + queue: Queue, + ctx: CtxSlot, + events: Arc, + budget: &AtomicUsize, + idle: &Mutex>, + timeout: Duration, +) -> std::io::Result<()> { out.set_read_timeout(Some(timeout))?; out.set_write_timeout(Some(timeout))?; let mut reader = BufReader::new(out.try_clone()?); - let mut line = Vec::new(); + let set_idle = |since: Option| *idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = since; loop { - line.clear(); - if (&mut reader).take((MAX_LINE + 1) as u64).read_until(b'\n', &mut line)? == 0 { - break; - } + set_idle(Some(Instant::now())); + // A new buffer each time: an idle connection keeps no large line's capacity. + let mut line = Vec::new(); + let _held = match read_line(&mut reader, &mut line, budget)? { + Line::End => break, + Line::Read(held) => held, + Line::Busy => { + let error = "the control server holds too many large requests: retry when they are answered"; + writeln!(out, "{}", json!({"id": null, "ok": false, "error": error}))?; + break; + } + }; if line.last() == Some(&b'\n') { line.pop(); } @@ -205,6 +294,7 @@ fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc continue; } let needs_frame = matches!(method.as_str(), "ui.screenshot" | "ui.input"); + set_idle(None); pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, state: gate.clone() }); drop(pending); if let Some(c) = ctx.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() { diff --git a/apps/figcraft/src/control_server_tests.rs b/apps/figcraft/src/control_server_tests.rs index a497942e1..1658d0e20 100644 --- a/apps/figcraft/src/control_server_tests.rs +++ b/apps/figcraft/src/control_server_tests.rs @@ -277,46 +277,54 @@ fn a_failed_accept_waits_before_the_next() { assert_eq!(waits, 3, "one wait per failed accept"); } +/// With every slot taken, a new client gets the slot of the connection idle longest, never one +/// whose request the UI is running (#1110), and finished slots are reused. #[test] -fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() { +fn connection_limit_frees_the_longest_idle_slot_and_reuses_finished_ones() { let pending = queue(); let ctx = context(); + let budget = Arc::new(AtomicUsize::new(0)); let mut workers = Vec::new(); let mut clients = Vec::new(); + let spawn = |server, workers: &mut Vec| { + let events = Arc::new(figcraft_engine::events::EventLog::default()); + spawn_connection(server, pending.clone(), ctx.clone(), events, &budget, workers, Duration::from_secs(5)); + }; for _ in 0..MAX_CONNECTIONS { let (client, server) = pair(); - spawn_connection( - server, - pending.clone(), - ctx.clone(), - Arc::new(figcraft_engine::events::EventLog::default()), - &mut workers, - Duration::from_secs(5), - ); + spawn(server, &mut workers); clients.push(client); + // Each idle from its own moment. + std::thread::sleep(Duration::from_millis(2)); } assert_eq!(workers.len(), MAX_CONNECTIONS); - let (mut extra, server) = pair(); - spawn_connection( - server, - pending.clone(), - ctx.clone(), - Arc::new(figcraft_engine::events::EventLog::default()), - &mut workers, - Duration::from_secs(5), - ); - assert_eq!(extra.read(&mut [0]).unwrap(), 0); - assert_eq!(workers.len(), MAX_CONNECTIONS); - for client in clients { - client.shutdown(Shutdown::Both).unwrap(); - } + // The oldest connection waits for the UI: it is busy, not idle. + clients[0].write_all(b"{\"id\":1,\"method\":\"ui.inspect\"}\n").unwrap(); let start = Instant::now(); - while workers.iter().any(|worker| !worker.is_finished()) { + while pending.lock().unwrap().is_empty() { assert!(start.elapsed() < Duration::from_secs(5)); std::thread::sleep(Duration::from_millis(1)); } + let (mut extra, server) = pair(); + spawn(server, &mut workers); + assert_eq!(workers.len(), MAX_CONNECTIONS); + assert_eq!(clients[1].read(&mut [0]).unwrap(), 0, "the connection idle longest was closed"); + extra.write_all(b"invalid\n").unwrap(); + assert_eq!(reply(&mut BufReader::new(extra.try_clone().unwrap()))["ok"], false, "the new client is served"); + assert!(pending.lock().unwrap().len() == 1, "the busy request is still queued"); + pending.lock().unwrap().clear(); + for client in clients.iter().skip(2) { + client.shutdown(Shutdown::Both).unwrap(); + } + let _ = clients[0].shutdown(Shutdown::Both); + // The busy worker waits out its request's 5 s timeout before it sees the shutdown. + let start = Instant::now(); + while workers.iter().any(|worker| !worker.thread.is_finished()) { + assert!(start.elapsed() < Duration::from_secs(15)); + std::thread::sleep(Duration::from_millis(5)); + } let (mut client, server) = pair(); - spawn_connection(server, pending, ctx, Arc::new(figcraft_engine::events::EventLog::default()), &mut workers, Duration::from_secs(5)); + spawn(server, &mut workers); assert_eq!(workers.len(), 1); client.write_all(b"invalid\n").unwrap(); assert_eq!(reply(&mut BufReader::new(client.try_clone().unwrap()))["ok"], false); @@ -325,7 +333,26 @@ fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() { // returns Ok. Closing the client is what the worker is waiting for, so the result is moot: // the other shutdowns in this file run while the peer is still open and stay checked. let _ = client.shutdown(Shutdown::Both); - workers.pop().unwrap().join().unwrap(); + workers.pop().unwrap().thread.join().unwrap(); +} + +/// Lines are counted against one budget shared by every connection while they are held (#1111): +/// a line past it is refused before it is read whole, and a line answered gives its bytes back. +#[test] +fn lines_past_the_shared_budget_are_refused_and_given_back_when_done() { + let frame = b"{\"id\":1,\"method\":\"ui.inspect\"}\n".to_vec(); + let nearly_full = AtomicUsize::new(MAX_IN_FLIGHT - 4); + let mut line = Vec::new(); + assert!(matches!(read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &nearly_full).unwrap(), Line::Busy)); + assert_eq!(nearly_full.load(Ordering::SeqCst), MAX_IN_FLIGHT - 4, "nothing kept from the refused line"); + let budget = AtomicUsize::new(0); + let mut line = Vec::new(); + { + let Line::Read(_held) = read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &budget).unwrap() else { panic!("read") }; + assert_eq!(line, frame); + assert!(budget.load(Ordering::SeqCst) >= frame.len(), "held while it is served"); + } + assert_eq!(budget.load(Ordering::SeqCst), 0, "given back"); } #[test] @@ -358,7 +385,8 @@ fn events_poll_is_answered_without_the_ui_queue() { let log = Arc::new(figcraft_engine::events::EventLog::default()); log.push("comment.added", "Doc", None, json!({"commentId": 7})); let l = log.clone(); - let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5))); + let worker = + std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))); client.write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":0,\"timeoutMs\":0}}\n").unwrap(); let mut reader = BufReader::new(client); let r = reply(&mut reader); @@ -484,7 +512,8 @@ fn events_poll_rejects_an_unknown_topic_without_the_ui_queue() { let q = pending.clone(); let log = Arc::new(figcraft_engine::events::EventLog::default()); let l = log.clone(); - let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5))); + let worker = + std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))); let mut reader = BufReader::new(client); reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"topics\":[\"nope\"],\"timeoutMs\":0}}\n").unwrap(); let r = reply(&mut reader); @@ -503,7 +532,8 @@ fn events_poll_reports_reset_for_a_cursor_ahead_of_the_log() { log.push("comment.added", "Doc", None, json!({"commentId": 1})); let q = queue(); let l = log.clone(); - let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5))); + let worker = + std::thread::spawn(move || serve_with_events(server, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))); let mut reader = BufReader::new(client); reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":2,\"timeoutMs\":0}}\n").unwrap(); let r = reply(&mut reader); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c34fbdf94..b66771a20 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -32,8 +32,15 @@ HTTP request a web page makes the browser send here never runs). The implementat A request line is limited to **32 MiB before the newline**, including whitespace. The reader stops at the first excess byte, replies `{"id": null, "ok": false, "error": "message too large"}`, then -closes the connection without consuming the rest of the frame. The server accepts at most **8 -active connections**; additional connections are closed immediately. Socket reads and writes each +closes the connection without consuming the rest of the frame. All connections together hold at +most **64 MiB of request lines** (counted as they arrive, until each is answered): a line past +that gets `{"id": null, "ok": false, "error": "the control server holds too many large requests: +retry when they are answered"}` and its connection is closed. The server keeps at most **8 +connections**. With all 8 open, a new client takes the slot of the connection that has waited +longest for its client (between requests, or in `events.poll`), which is closed; a connection +whose request the app is running keeps its slot, and with all 8 running one the new client is +closed at once. Clients that keep a connection reconnect when it closes (the attached MCP +backend does). Socket reads and writes each have a **60 s inactivity timeout**, so idle clients and clients that stop reading release their worker. This bounds blocked socket operations, not the total duration of a frame arriving slowly. Clients can reconnect after an idle timeout (the attached MCP backend already does). From 0b97d092114b5a48040bd53e0d61c2f3d553b44c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 17:52:30 +0700 Subject: [PATCH 30/38] M9: wss:// connections also trust the operating system's certificate store (#2342) The desktop app and figcraft-cli trusted only the compiled-in public roots and FIGCRAFT_CA_FILE, so a server behind a proxy with a private authority needed that variable on every computer. They now also add the authorities in the operating system's certificate store, unless FIGCRAFT_NO_SYSTEM_ROOTS is set. Certificates are still always verified. --- Cargo.lock | 1 + crates/collab-net/Cargo.toml | 7 ++++--- crates/collab-net/src/tls.rs | 21 +++++++++++++++++---- docs/collab-protocol.md | 3 ++- docs/collaboration-parity.md | 3 ++- docs/server.md | 15 +++++++++------ 6 files changed, 35 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 35d34b470..399be9e64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2716,6 +2716,7 @@ dependencies = [ "log", "proptest", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde_json", "tungstenite", diff --git a/crates/collab-net/Cargo.toml b/crates/collab-net/Cargo.toml index 67c4d8499..e7fc92200 100644 --- a/crates/collab-net/Cargo.toml +++ b/crates/collab-net/Cargo.toml @@ -19,12 +19,13 @@ web-time = "1" # Native transport: blocking tungstenite with a reader and a writer thread per connection. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tungstenite = { version = "0.30", default-features = false, features = ["handshake"] } -# `wss://`: TLS with ring as the crypto provider and Mozilla's root certificates compiled in (no -# OS certificate store, no OpenSSL). Over our own split reader/writer stream (`tls.rs`), so not -# tungstenite's single-owner TLS stream. +# `wss://`: TLS with ring as the crypto provider, the public root certificates of webpki-roots +# compiled in and the operating system's certificate store read (no OpenSSL). Over our own split +# reader/writer stream (`tls.rs`), so not tungstenite's single-owner TLS stream. rustls = { version = "0.23", default-features = false, features = ["std", "ring", "tls12", "logging"] } rustls-pki-types = { version = "1", features = ["std"] } webpki-roots = "1" +rustls-native-certs = "0.8" getrandom = "0.4" base64 = { workspace = true } diff --git a/crates/collab-net/src/tls.rs b/crates/collab-net/src/tls.rs index 7e39a5ced..c86a5b03f 100644 --- a/crates/collab-net/src/tls.rs +++ b/crates/collab-net/src/tls.rs @@ -1,6 +1,7 @@ -//! TLS for `wss://` addresses (native): rustls with ring, trusting Mozilla's root certificates -//! (compiled in) plus any in the PEM file `FIGCRAFT_CA_FILE` names (a private authority or a -//! self-signed server). Certificates are always verified. +//! TLS for `wss://` addresses (native): rustls with ring, trusting the public root certificates of +//! webpki-roots (compiled in), the authorities this computer trusts (its certificate store, unless +//! `FIGCRAFT_NO_SYSTEM_ROOTS` is set) and any in the PEM file `FIGCRAFT_CA_FILE` names (a private +//! authority or a self-signed server). Certificates are always verified. //! //! A connection's reader and writer threads share one TLS session ([`Tls`]), each holding it only //! to decrypt or encrypt: the reader waits for bytes on its own socket handle without it, and a @@ -20,6 +21,9 @@ use rustls::{CertificateError, ClientConfig, ClientConnection, RootCertStore}; /// The variable naming a PEM file of extra certificate authorities to trust. pub const CA_FILE: &str = "FIGCRAFT_CA_FILE"; +/// The variable that, set, leaves the operating system's certificate store out. +pub const NO_SYSTEM_ROOTS: &str = "FIGCRAFT_NO_SYSTEM_ROOTS"; + /// One connection's TLS session, shared by its reader and writer. pub type Tls = Arc>; @@ -44,7 +48,7 @@ pub fn handshake(stream: &TcpStream, host: &str) -> Result { fn explain(host: &str, e: &io::Error) -> String { let why = |c: &CertificateError| match c { CertificateError::UnknownIssuer => format!( - "isn't signed by an authority this app trusts (for a private or self-signed certificate, set {CA_FILE} to its authority's PEM file)" + "isn't signed by an authority this app trusts (for a private or self-signed certificate, add its authority to this computer's trusted certificates, or set {CA_FILE} to its authority's PEM file)" ), CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => "is for another name".into(), CertificateError::Expired | CertificateError::ExpiredContext { .. } => "has expired".into(), @@ -67,6 +71,15 @@ fn config() -> Result, String> { fn make_config() -> Result, String> { let mut roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + // A private authority an administrator installed (a company's, a proxy's) is trusted as the + // computer's other apps trust it (#2342). An unreadable store adds nothing. + if std::env::var_os(NO_SYSTEM_ROOTS).is_none() { + let system = rustls_native_certs::load_native_certs(); + for e in &system.errors { + log::warn!("system certificate store: {e}"); + } + roots.add_parsable_certificates(system.certs); + } if let Some(path) = std::env::var_os(CA_FILE) { let shown = std::path::Path::new(&path).display().to_string(); let certs: Vec = CertificateDer::pem_file_iter(&path) diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 2cc15c005..d3b76a654 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -799,7 +799,8 @@ resuming with its offline edits, and leaving the session going back to snapshot plain `ws://` endpoint at `/`, `figcraft://join?server=&file=…&token=…` for any endpoint (TLS, a path behind a proxy), or `ws(s)://…?file=…&token=…`. The desktop app, `figcraft-cli` and the browser all open `wss://`: natively through rustls (ring, Mozilla's root - certificates compiled in, plus any authority in the PEM file `FIGCRAFT_CA_FILE` names), always + certificates compiled in, the operating system's certificate store unless + `FIGCRAFT_NO_SYSTEM_ROOTS` is set, plus any authority in the PEM file `FIGCRAFT_CA_FILE` names), always verifying the certificate; the browser through its own WebSocket. - **Managing files.** A connection that opens with `Manage {key}` instead of `Hello` sends `Admin` requests: publish a document (its snapshot) as a new file, which returns an edit link diff --git a/docs/collaboration-parity.md b/docs/collaboration-parity.md index 0998cde7f..0cc5b37e6 100644 --- a/docs/collaboration-parity.md +++ b/docs/collaboration-parity.md @@ -1,6 +1,6 @@ # Collaboration parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-26 · **Change:** minor (legacy welcomes without a reconnect secret are accepted with their explicit access level, and reconnects re-authenticate with the share link (#2365); a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); shared branches sync across live sessions and survive `figcraft-server` restarts, capability-gated on `branches`; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (`wss://` connections also trust the authorities in the operating system's certificate store, so a private authority added there works without `FIGCRAFT_CA_FILE` (#2342); legacy welcomes without a reconnect secret are accepted with their explicit access level, and reconnects re-authenticate with the share link (#2365); a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); shared branches sync across live sessions and survive `figcraft-server` restarts, capability-gated on `branches`; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing) Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model, @@ -27,6 +27,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | #2342: the desktop app and `figcraft-cli` checked a `wss://` server's certificate against the compiled-in public roots and `FIGCRAFT_CA_FILE` only, so a server behind a proxy with a private authority needed that variable on every computer, which a signed desktop app started from the dock or the start menu doesn't see. They now also trust the authorities in the operating system's certificate store, read once per process, so adding the private authority to the computer's trusted certificates is enough. `FIGCRAFT_NO_SYSTEM_ROOTS=1` leaves the store out. Certificates are still always verified; an unknown authority's error names both ways to trust it. Not tested against a real private authority in the store here. | | 2026-11-28 | patch | M9, #2495: Stop sharing failed on a private server for a file shared with the server key typed under Advanced ("that owner token doesn't manage a file of that id here"). Such a file has no owner token, and the key went only with the publish. `collab.share {key}` now keeps the key with the share in this session, in the address as `collab.share {server: "…?key=…"}` would give it, so Stop sharing and sharing again ask as the server's operator. The key is never in a command result. Test: `live_share_tests::stopping_a_file_shared_with_a_separate_key_asks_with_that_key`. Numbers unchanged | | 2026-11-26 | minor | M10, gap 17: shared branches sync across live sessions. Capability-gated on `branches` in `Hello::client_version` (`ServerMsg::Branches` / `Branch`, `ClientMsg::Branch` with `Create`, `Edit`, `UpdateFromMain`, `SetState`), persisted in `SessionState::branches` and the server journal (with fallback decoding for pre-branch `figcraft-server` snapshots). Any editor can open, co-edit, update from main, review, archive and merge another peer's branch (remote merges/archives close open branch tabs on peers and switch back to main); view and comment links are refused; node/entry id spaces, geometry and image entries are validated on every branch mutation; older clients and servers stay compatible (local-only branches). Tests: `collab::branch_tests`, `engine::branch_live_tests`, `figcraft-server::server_tests::shared_branches_sync_and_survive_a_server_restart`, `figcraft-server::disk::tests::decode_snapshot_reads_pre_branch_v1_snapshots`. Numbers unchanged. | | 2026-11-16 | patch | M9, #2365: a server predating reconnect secrets sends a complete `Welcome` ending at `access`; postcard does not honor a missing trailing field through `serde(default)`. The client reads that exact legacy layout, preserves access, and keeps strict size, version and message-boundary checks. Native and browser transports use this reader; reconnects without a secret send a fresh authenticated hello. Covered by codec and connection-driver regressions. A patched 0.15.1 desktop build was also checked against the public service with separate view-only access and annotation reads; writes remained denied. The public server still needs upgrading. Numbers unchanged. | diff --git a/docs/server.md b/docs/server.md index c7cbe3093..8e97c2174 100644 --- a/docs/server.md +++ b/docs/server.md @@ -454,12 +454,15 @@ gives people `wss://` links (and browsers the `wss://` they need on an `https:// so the proxy's access logs don't record them. The desktop app, `figcraft-cli` (and so agents through MCP) and the browser build all open -`wss://` links. The desktop app and the CLI check the certificate against Mozilla's list of root -authorities built into them (not the operating system's store), so a certificate from a public -authority such as Let's Encrypt just works. For a certificate from a private authority (or a -self-signed one, such as Caddy's `tls internal`), set the environment variable `FIGCRAFT_CA_FILE` -to that authority's certificate (a PEM file) before starting the app: it is trusted in addition -to the built-in list. There is no way to skip the check: a certificate that has expired, is for +`wss://` links. The desktop app and the CLI check the certificate against a list of public root +authorities built into them and the authorities the operating system trusts (its certificate +store), so a +certificate from a public authority such as Let's Encrypt just works, and so does one from a +private authority once it is added to the computer's trusted certificates. Without that (or for a +self-signed certificate, such as Caddy's `tls internal`), set the environment variable +`FIGCRAFT_CA_FILE` to that authority's certificate (a PEM file) before starting the app: it is +trusted in addition to the others. `FIGCRAFT_NO_SYSTEM_ROOTS=1` leaves the operating system's +store out. There is no way to skip the check: a certificate that has expired, is for another name or comes from an unknown authority is refused, and the app says which. ## Running a public server From b6540e2cab323f6f09ac9ab91280a99d4f125c94 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 28 Nov 2026 18:22:36 +0700 Subject: [PATCH 31/38] M5: the presenter's sharp detail waits until a zoom or resize has settled (#2187) The device-scale detail drawn over a tall frame's capped texture waited out only a fling, a drag and the wheel. A zoom, a window resize, a move to a display of another scale or any other change of the view rendered a new detail, up to 16.8 million pixels on the UI thread, on every frame it changed. Any change of the page area in view or of its pixel scale from one frame to the next now counts as motion: the capped texture shows alone meanwhile, and a frame is asked for so the detail for the still view is rendered next. --- crates/ui-egui/src/present.rs | 4 ++++ crates/ui-egui/src/present/draw.rs | 15 ++++++++++++++- crates/ui-egui/src/present/tests.rs | 14 ++++++++++++++ docs/prototyping-parity.md | 3 ++- 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 05a997a66..488f2c435 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -295,6 +295,9 @@ pub struct Presenter { /// The part of the presented frame in view, drawn at device scale over the (capped) whole-frame /// texture; `bounds` is the page area it covers. detail: Option<(NodeId, FrameTex)>, + /// The page area in view and the pixel scale it was drawn at last frame: a change is motion, + /// which the detail waits out. + last_view: Option<(figcraft_geom::Rect, f64)>, /// Small current-screen preview in the full-window bar, cached until its content changes. bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>, arrived: f64, @@ -382,6 +385,7 @@ impl Presenter { temp: None, textures: HashMap::new(), detail: None, + last_view: None, bar_thumb: None, arrived: -1.0, delays_fired: HashSet::new(), diff --git a/crates/ui-egui/src/present/draw.rs b/crates/ui-egui/src/present/draw.rs index 0afe7cd86..952b51816 100644 --- a/crates/ui-egui/src/present/draw.rs +++ b/crates/ui-egui/src/present/draw.rs @@ -84,7 +84,13 @@ pub(super) fn draw(p: &mut Presenter, painter: &egui::Painter, ctx: &egui::Conte if shown.is_positive() { let (a, b) = (l.place.page(shown.min), l.place.page(shown.max)); let visible = figcraft_geom::Rect::new(a.x, a.y, b.x, b.y); - let moving = p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); + // A zoom, a resize or any other change of the view moves it too: the detail is rendered + // once it is still (a frame is asked for then, as nothing else may draw one). + let changed = p.last_view.replace((visible, px)).is_some_and(|(v, s)| !same_view(v, visible) || s != px); + if changed { + ctx.request_repaint(); + } + let moving = changed || p.fling.is_some() || p.drag_scroll.is_some() || p.wheel.is_some(); detail = p.detail_texture(ctx, &l.disp, p.current, px, to.bounds, visible, moving, now); } let hole = detail.as_ref().map(|d| l.clip.intersect(l.place.rect(d.bounds))); @@ -160,3 +166,10 @@ pub(super) fn base_parts(clip: Rect, hole: Option) -> Vec { .filter(|r| r.is_positive()) .collect() } + +/// Whether two views of the page are the same up to the rounding of converting them back from the +/// screen. +fn same_view(a: figcraft_geom::Rect, b: figcraft_geom::Rect) -> bool { + const EPS: f64 = 1e-3; + (a.x0 - b.x0).abs() < EPS && (a.y0 - b.y0).abs() < EPS && (a.x1 - b.x1).abs() < EPS && (a.y1 - b.y1).abs() < EPS +} diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index fb8cdc773..04d2c76bd 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -527,6 +527,20 @@ fn a_view_a_rounding_error_past_the_frame_keeps_its_detail() { assert_eq!(again, first, "the same view reuses its detail instead of rendering a new one"); } +/// A change of scale (a zoom, a resize, a move to another display) is motion too (#2187): the frame +/// it happens in renders no detail, and once the view is still a detail for it is rendered. +#[test] +fn a_change_of_scale_renders_the_detail_once_the_view_is_still() { + let mut ui = tall_hidpi(16_384); + let tex_id = |ui: &Ui| ui.app.ui.present.as_ref().and_then(|p| p.detail.as_ref().map(|(_, d)| d.tex.id())); + let first = tex_id(&ui).expect("a detail is drawn"); + ui.hidpi = Some((3.0, 16_384)); + ui.frames(1, Vec::new); + assert_eq!(tex_id(&ui), Some(first), "the frame the scale changes renders no detail"); + ui.frames(2, Vec::new); + assert_ne!(tex_id(&ui), Some(first), "once still, a detail at the new scale"); +} + /// While the view moves, the detail is drawn only while it covers the whole view: past its edge /// the capped whole-frame texture shows alone, so no sharp/soft boundary crosses the view, and /// once the view settles a detail for it is rendered. diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 86c427508..493419167 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -1,6 +1,6 @@ # Prototyping parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** patch (platform arrow-key aliases and document-scoped player controls, with failed batch UI requests rolled back; at 100% a presented frame reaches the window's edges, the padding kept for Fit; without a device, a frame taller than the window with fixed or sticky layers scrolls in the window as on a device's screen, so a fixed header stays at the window's top to the end of the page instead of panning away with the frame (#2430); dragging a prototype connection near the canvas edge pans the view toward it, so a link can reach a frame off screen (#2015); in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-19 · **Change:** patch (a zoom, resize or other change of the presenter's scale or view waits until the view is still before the sharp detail of a tall frame is drawn again (#2187); platform arrow-key aliases and document-scoped player controls, with failed batch UI requests rolled back; at 100% a presented frame reaches the window's edges, the padding kept for Fit; without a device, a frame taller than the window with fixed or sticky layers scrolls in the window as on a device's screen, so a fixed header stays at the window's top to the end of the page instead of panning away with the frame (#2430); dragging a prototype connection near the canvas edge pans the view toward it, so a link can reach a frame off screen (#2015); in the presenter's comment mode (C) a click on the presented frame starts a comment there and the mode stays on for the next one, Escape closes the draft and then the mode, measured in Figma's web app 2026-11-10 (#2209); presenting a tall frame is sharp on a HiDPI display: a frame too big for one texture at device scale (a 1440 by 9701 frame at 2 pixels a unit) is still drawn from the capped whole-frame texture, with the part in view drawn again over it from a texture at device scale (#2127); a connection dragged from a variant, or a layer in it, onto a sibling variant makes Change to, On click, Instant, with the sibling outlined (#2158); `proto.settings` refuses an unknown device with the list of devices instead of saving it, takes a known one in any case, and answers the page's settings, so `proto.settings {}` reads them (#2027); Hide UI in the presenter's Options menu, and Cmd/Ctrl+\ as in the editor: the bar above the prototype and the navigation bar under it go away, a toast names the key that brings them back, `proto.presentOptions {hideUi}` (#1820); the Controller menu names each button as PlayStation and Switch controllers do; "Open in new tab" on Open link: off, the web build's own tab goes to the link; a manual overlay's position can be dragged on the canvas (#405); Open link notices now cover mail links, and skipping them covers only links the viewer fired (#1096); overlay positions relative to the layer that opens them; the Triggers row no longer lists delays on mouse triggers as missing; top-level frames bigger than the device's screen scroll in the player; Change to, set variable and set variable mode lay out what they change in the player, as the canvas does; presentation tabs, one per page of a file; a Present tab with device and scale controls (#537); core editor leftovers: delays on mouse triggers and manual overlay offsets; controller buttons on key/gamepad triggers, widgets that react in prototypes, `proto.evaluate` and the mode lookup rules pinned) · **Target:** Figma Design (desktop app 126.10.7) **Breadth ~92%, ready ~74% (estimated).** Every Figma trigger except media, every action except media control, every transition and easing exist; key/gamepad triggers take controller buttons, @@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M5, #2187 (part): the sharp detail drawn over a tall frame's capped texture on a HiDPI display waited out only a fling, a drag and the wheel, so a zoom, a window resize, a move to a display of another scale or any other change of the view rendered a new detail (up to 16.8 million pixels, on the UI thread) on every frame it changed. Any change of the page area in view or of its pixel scale from one frame to the next now counts as motion: the capped texture shows alone meanwhile, and a frame is asked for so the detail for the still view is rendered next. Rendering it off the UI thread, edits outside the detail, peak memory and the animated GIF test from the issue are still open. Test: `present::tests::a_change_of_scale_renders_the_detail_once_the_view_is_still`. Numbers unchanged | | 2026-11-18 | patch | M5: at Actual size (100%) the presenter kept the 32 pt padding it has at Fit, so a frame the size of the window panned 64 pt both ways; in Figma a frame shown at 100% reaches the window's edges and only what is bigger pans. Actual size now takes the whole area, and Fit keeps the padding and still never goes above 100%. Test: `a_frame_the_size_of_the_window_shows_at_100_percent_without_panning` | | 2026-11-15 | patch | M5: `ArrowRight` and the platform name `Right` match the same trigger without bypassing modifiers. Explicit file/tab/player commands keep the requested document; nested batches use only successful selections, and aborted groups discard their UI requests. Ordinary background reads and edits keep the front tab. Tests: `control::document_tests`, `headless::document_tests`, `arrow_key_triggers_override_default_frame_navigation`; estimates unchanged. | | 2026-11-07 | patch | M8, #2015: dragging a prototype connection near the canvas edge pans the view, as measured in Figma: while a drag holds the pointer within about 15 px of the edge (or past it) the view pans toward it at 40 px/s for each px closer, up to 600 px/s at the edge, steadily while the pointer stays still; moving layers, the selection box, drawing a shape and dragging a prototype connection (a link can now reach a frame off screen). Resizing, rotating and other drags don't pan. Tests: `view_autopan_tests`, `canvas_autopan_tests`, `proto_canvas::tests`. | From 0b5f079c0dd3c7b32f55f0d5de28bcf761c5bf2c Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 04:27:25 -0700 Subject: [PATCH 32/38] M8: navigation timings in a 100,000-layer file Five pages of 20,000 layers: cards, cards with a background blur and a glass pane on the page shown or on another page, and a flat page. Rows time the retained renderer's scan after an edit, an edit, a zoom at 100% and 400% and a 60 px pan. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/large_doc_bench_tests.rs | 197 +++++++++++++++++++++ crates/render/src/lib.rs | 2 + crates/render/src/retained.rs | 6 + 3 files changed, 205 insertions(+) create mode 100644 crates/render/src/large_doc_bench_tests.rs diff --git a/crates/render/src/large_doc_bench_tests.rs b/crates/render/src/large_doc_bench_tests.rs new file mode 100644 index 000000000..bd81d6b35 --- /dev/null +++ b/crates/render/src/large_doc_bench_tests.rs @@ -0,0 +1,197 @@ +//! Navigation timings in a large file: five pages of 20,000 layers each (100,000 in the file), seen +//! through a 1600 × 1100 device-pixel view. Run in release: +//! `cargo test --release -p figcraft-render --lib large_doc_timings -- --ignored --nocapture`. +//! +//! Columns, by what the pages hold: +//! - "cards": 400 cards a page (frames with a drop shadow), each holding 49 rectangles; +//! - "blur here": the cards, and a background blur and a glass pane on the page shown; +//! - "blur elsewhere": the cards, and a background blur and a glass pane on another page; +//! - "flat": 20,000 rectangles straight on each page. +//! +//! Rows go through `Retained` as the canvas does: "scan" is what the retained renderer works out +//! about a page after an edit (the layers to redraw whole, the largest backdrop blur); "edit" +//! moves one rectangle each frame; "zoom" renders a new scale each frame; "pan" moves the view by +//! 60 device pixels each frame. + +use std::sync::Arc; +use std::time::Instant; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Blur, Document, Effect, EffectKind, Glass, NodeId, NodeKind, Shadow}; +use figcraft_geom::Affine; + +use crate::{Options, Retained, View, Work}; + +const PAGES: u32 = 5; +const RUNS: u32 = 12; + +#[derive(Clone, Copy, PartialEq)] +enum Scene { + Cards, + BlurHere, + BlurElsewhere, + Flat, +} + +/// The file, the page shown and a rectangle on it. +struct File { + doc: Document, + page: NodeId, + target: NodeId, +} + +/// A background blur and a glass pane on `page`. +fn backdrops(d: &mut Document, page: NodeId) { + let pane = d.create(page, NodeKind::Rectangle, "Frosted", 1100.0, 1100.0, 500.0, 300.0).unwrap(); + let n = d.get_mut(pane).unwrap(); + n.fills = vec![Paint::solid(Color { a: 0.2, ..Color::WHITE })]; + n.effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur { radius: 24.0, ..Blur::default() }), visible: true }]; + let glass = d.create(page, NodeKind::Rectangle, "Glass", 1700.0, 1300.0, 400.0, 260.0).unwrap(); + let n = d.get_mut(glass).unwrap(); + n.corners.radii = [32.0; 4]; + n.fills = vec![Paint::solid(Color { a: 0.1, ..Color::WHITE })]; + n.effects = vec![Effect { kind: EffectKind::Glass(Glass::default()), visible: true }]; +} + +fn file(scene: Scene) -> File { + let mut d = Document::new("large file"); + let first = d.first_page().unwrap(); + let pages: Vec = std::iter::once(first).chain((1..PAGES).map(|i| d.add_page(&format!("Page {}", i + 1)))).collect(); + let mut target = None; + let colour = |x: u32, y: u32, n: u32| Paint::solid(Color::new(x as f32 / n as f32, y as f32 / n as f32, 0.6, 1.0)); + for &p in &pages { + if scene == Scene::Flat { + for y in 0..100u32 { + for x in 0..200u32 { + let r = d.create(p, NodeKind::Rectangle, "Cell", f64::from(x) * 30.0, f64::from(y) * 30.0, 26.0, 26.0).unwrap(); + d.get_mut(r).unwrap().fills = vec![colour(x, y, 200)]; + if p == first && x == 50 && y == 50 { + target = Some(r); + } + } + } + continue; + } + for cy in 0..20u32 { + for cx in 0..20u32 { + let card = d.create(p, NodeKind::Frame, "Card", f64::from(cx) * 400.0, f64::from(cy) * 400.0, 360.0, 360.0).unwrap(); + let n = d.get_mut(card).unwrap(); + n.fills = vec![Paint::solid(Color::WHITE)]; + n.effects = + vec![Effect { kind: EffectKind::DropShadow(Shadow { radius: 12.0, offset: (0.0, 4.0), ..Shadow::default() }), visible: true }]; + for y in 0..7u32 { + for x in 0..7u32 { + let r = + d.create(card, NodeKind::Rectangle, "Cell", 8.0 + f64::from(x) * 50.0, 8.0 + f64::from(y) * 50.0, 44.0, 44.0).unwrap(); + d.get_mut(r).unwrap().fills = vec![colour(x, y, 7)]; + if p == first && cx == 3 && cy == 3 && x == 3 && y == 3 { + target = Some(r); + } + } + } + } + } + } + match scene { + Scene::BlurHere => backdrops(&mut d, first), + Scene::BlurElsewhere => backdrops(&mut d, pages[2]), + Scene::Cards | Scene::Flat => {} + } + File { doc: d, page: first, target: target.unwrap() } +} + +fn view(origin: (f64, f64), scale: f64) -> View { + View { origin, scale, width: 1600, height: 1100 } +} + +fn opts() -> Options { + Options { lod: true, ..Options::default() } +} + +fn mean_ms(t: Instant, runs: u32) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs) +} + +/// Move the target a unit right. +fn nudge(d: &mut Document, target: NodeId) { + let n = d.get_mut(target).unwrap(); + let c = n.transform.as_coeffs(); + n.transform = Affine::translate((c[4] + 1.0, c[5])); +} + +/// Mean milliseconds of the retained renderer's look at the page after an edit. +fn scan(f: &File) -> f64 { + let mut doc = f.doc.clone(); + let t = Instant::now(); + for _ in 0..RUNS { + nudge(&mut doc, f.target); + std::hint::black_box(crate::retained::bench_scan(&doc, f.page)); + } + mean_ms(t, RUNS) +} + +/// Mean milliseconds of a canvas frame after moving the target a unit. +fn edits(f: &File) -> f64 { + let v = view((1000.0, 1000.0), 1.0); + let mut r = Retained::default(); + let mut doc = Arc::new(f.doc.clone()); + r.render(&doc, f.page, &v, &opts()).unwrap(); + let t = Instant::now(); + for _ in 0..RUNS { + let mut next = (*doc).clone(); + nudge(&mut next, f.target); + doc = Arc::new(next); + let (_, _, work) = r.render(&doc, f.page, &v, &opts()).unwrap(); + assert!(matches!(work, Work::Partial { .. }), "{work:?}"); + } + mean_ms(t, RUNS) +} + +/// Mean milliseconds of a canvas frame at a new zoom around `scale`. +fn zooms(f: &File, scale: f64) -> f64 { + let doc = Arc::new(f.doc.clone()); + let mut r = Retained::default(); + r.render(&doc, f.page, &view((1000.0, 1000.0), scale), &opts()).unwrap(); + let t = Instant::now(); + for i in 1..=RUNS { + let (_, _, work) = r.render(&doc, f.page, &view((1000.0, 1000.0), scale * (1.0 + 0.02 * f64::from(i))), &opts()).unwrap(); + assert_eq!(work, Work::Full); + } + mean_ms(t, RUNS) +} + +/// Mean milliseconds of a canvas frame after a pan of 60 device pixels. +fn pans(f: &File) -> f64 { + let doc = Arc::new(f.doc.clone()); + let mut r = Retained::default(); + let mut at = (1000.0, 1000.0); + r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap(); + let t = Instant::now(); + for _ in 0..RUNS { + at.0 += 60.0; + let (_, _, work) = r.render(&doc, f.page, &view(at, 1.0), &opts()).unwrap(); + assert!(matches!(work, Work::Partial { .. }), "{work:?}"); + } + mean_ms(t, RUNS) +} + +#[test] +#[ignore = "timing: run in release with --ignored --nocapture"] +fn large_doc_timings() { + let scenes = [Scene::Cards, Scene::BlurHere, Scene::BlurElsewhere, Scene::Flat].map(file); + println!( + "large file timings ({} build, {} layers, 1600 × 1100 px, mean of {RUNS}, ms)", + if cfg!(debug_assertions) { "debug" } else { "release" }, + scenes[0].doc.node_count() + ); + println!("| frame | cards | blur here | blur elsewhere | flat |\n|---|---:|---:|---:|---:|"); + let row = |name: &str, f: &dyn Fn(&File) -> f64| { + let cells: Vec = scenes.iter().map(|s| format!("{:.2}", f(s))).collect(); + println!("| {name} | {} |", cells.join(" | ")); + }; + row("scan after an edit", &scan); + row("edit one layer", &edits); + row("zoom (100%)", &|f| zooms(f, 1.0)); + row("zoom (400%)", &|f| zooms(f, 4.0)); + row("pan 60 px", &pans); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index fb635509d..71259923a 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -705,6 +705,8 @@ mod join_tests; #[cfg(test)] mod jpeg_sampling_tests; #[cfg(test)] +mod large_doc_bench_tests; +#[cfg(test)] mod large_image_tests; #[cfg(test)] mod lod_tests; diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index 2d8bbdce3..977995b33 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -83,6 +83,12 @@ fn sensitive(doc: &Document) -> Sensitive { Sensitive { areas: noisy.filter_map(|n| draw::paint_bounds(doc, n.id)).collect(), backdrop_blur: crate::max_backdrop_blur(doc), pattern_sources } } +/// [`sensitive`] for the large-file timings: how many areas it found. +#[cfg(test)] +pub(crate) fn bench_scan(doc: &Document, _page: NodeId) -> usize { + sensitive(doc).areas.len() +} + /// Whether `id` is a pattern source or inside one in `doc`. fn in_pattern_source(doc: &Document, s: &Sensitive, id: NodeId) -> bool { s.pattern_sources.iter().any(|src| *src == id || doc.is_ancestor(*src, id)) From 6529c9240bd4d8f5c1da33cf883b595ccbd7d815 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 04:41:02 -0700 Subject: [PATCH 33/38] M8: the retained canvas looks only at the page it draws (#1250) What the retained renderer works out about a page (grainy layers to redraw whole, pattern sources whose edits show, the largest backdrop blur) came from passes over every layer of the file, after every edit and before every zoom. It now comes from one walk down the page shown, following the pattern sources it fills with wherever they are (and the sources those fill with). A zoom reuses what the last render found for the same document, page and fonts. Partial renders, the canvas's full renders and the browser's banded renders take the page's backdrop radius, so a blur on another page no longer widens pan strips and patch margins, and no longer stops a full render from drawing in parallel bands. render_view keeps the file's radius. Release timings on an Apple M5 Pro, 100,000 layers on five pages, 1600 x 1100 px, minimum of 8 runs alternating the two builds (ms, before -> after; the machine was shared with other builds): | frame | cards | blur here | blur elsewhere | flat | |---|---:|---:|---:|---:| | scan after an edit | 3.11 -> 0.80 | 3.09 -> 0.79 | 3.27 -> 0.79 | 3.07 -> 0.82 | | edit one layer | 5.31 -> 2.77 | 10.57 -> 7.95 | 7.43 -> 2.79 | 7.06 -> 3.30 | | zoom (100%) | 9.60 -> 6.67 | 20.62 -> 17.85 | 13.53 -> 6.71 | 6.72 -> 3.61 | | zoom (400%) | 5.78 -> 2.75 | 32.62 -> 29.42 | 18.04 -> 2.77 | 5.86 -> 3.03 | | pan 60 px | 0.69 -> 0.70 | 3.05 -> 3.10 | 2.16 -> 0.69 | 2.84 -> 2.95 | large_doc_digests hashes 65 frames of pans, edits and zooms over five scenes (pattern fill with an off-page source, noise, background blur, glass included); both builds print the same digests. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/large_doc_bench_tests.rs | 74 +++++++++ crates/render/src/lib.rs | 53 +++++- crates/render/src/retained.rs | 118 ++++++++----- crates/render/src/retained_page_tests.rs | 182 +++++++++++++++++++++ 4 files changed, 377 insertions(+), 50 deletions(-) create mode 100644 crates/render/src/retained_page_tests.rs diff --git a/crates/render/src/large_doc_bench_tests.rs b/crates/render/src/large_doc_bench_tests.rs index bd81d6b35..50b2bb7ac 100644 --- a/crates/render/src/large_doc_bench_tests.rs +++ b/crates/render/src/large_doc_bench_tests.rs @@ -195,3 +195,77 @@ fn large_doc_timings() { row("zoom (400%)", &|f| zooms(f, 4.0)); row("pan 60 px", &pans); } + +/// The cards with, on the page shown, a grainy card, a layer filled with a pattern whose source +/// lies on another page, a background blur and a glass pane. +fn mixed() -> File { + let mut f = file(Scene::BlurHere); + let d = &mut f.doc; + let other = d.pages[3]; + let source = d.create(other, NodeKind::Frame, "Source", 0.0, 0.0, 30.0, 30.0).unwrap(); + d.get_mut(source).unwrap().fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())]; + let dot = d.create(source, NodeKind::Rectangle, "Dot", 8.0, 8.0, 12.0, 12.0).unwrap(); + d.get_mut(dot).unwrap().fills = vec![Paint::solid(Color::from_hex("2040E0").unwrap())]; + let filled = d.create(f.page, NodeKind::Rectangle, "Filled", 1300.0, 1500.0, 300.0, 200.0).unwrap(); + let pt = figcraft_color::PatternPaint::new(source.0); + d.get_mut(filled).unwrap().fills = vec![Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }]; + let grainy = d.create(f.page, NodeKind::Rectangle, "Grain", 1500.0, 1150.0, 200.0, 120.0).unwrap(); + let n = d.get_mut(grainy).unwrap(); + n.fills = vec![Paint::solid(Color::from_hex("20C060").unwrap())]; + n.effects = vec![Effect { + kind: EffectKind::Noise(figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() }), + visible: true, + }]; + f +} + +/// Prints a digest of every frame of a run of pans, edits and zooms through `Retained`, to tell +/// that two builds draw the same pixels: run in release on each and compare. +#[test] +#[ignore = "digests: run in release with --ignored --nocapture on two builds and compare"] +fn large_doc_digests() { + use std::hash::{DefaultHasher, Hash, Hasher}; + let scenes = [ + ("cards", file(Scene::Cards)), + ("blur here", file(Scene::BlurHere)), + ("blur elsewhere", file(Scene::BlurElsewhere)), + ("flat", file(Scene::Flat)), + ("mixed", mixed()), + ]; + let mut all = DefaultHasher::new(); + for (name, f) in &scenes { + let mut r = Retained::default(); + let mut doc = Arc::new(f.doc.clone()); + let mut frames = Vec::new(); + let mut at = (1000.0, 1000.0); + let mut scale = 1.0; + let steps = ["pan", "pan", "edit", "edit", "zoom 1.37", "pan", "edit", "zoom 4", "pan", "edit", "zoom 0.5", "pan"]; + let mut draw = |r: &mut Retained, doc: &Arc, at: (f64, f64), scale: f64, frames: &mut Vec| { + let (_, pix, work) = r.render(doc, f.page, &view(at, scale), &opts()).unwrap(); + let mut h = DefaultHasher::new(); + pix.data().hash(&mut h); + let w = match work { + Work::Full => "F", + Work::Partial { .. } => "P", + Work::Reused => "R", + }; + frames.push(format!("{w}{:04x}", h.finish() & 0xffff)); + pix.data().hash(&mut all); + }; + draw(&mut r, &doc, at, scale, &mut frames); + for s in steps { + match s { + "pan" => at = (at.0 + 60.0 / scale, at.1 + 24.0 / scale), + "edit" => { + let mut next = (*doc).clone(); + nudge(&mut next, f.target); + doc = Arc::new(next); + } + z => scale = z.trim_start_matches("zoom ").parse().unwrap(), + } + draw(&mut r, &doc, at, scale, &mut frames); + } + println!("{name}: {}", frames.join(" ")); + } + println!("all: {:016x}", all.finish()); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 71259923a..cad02d3e3 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -123,6 +123,13 @@ pub(crate) fn render_number() -> u64 { /// Render a page region, splitting it into horizontal bands rendered in parallel (desktop). pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option { + render_view_with(doc, page, view, opts, max_backdrop_blur(doc)) +} + +/// [`render_view`], where `backdrop` is at least the largest backdrop radius of what it draws (a +/// retained render works it out for the page: a blur on another page then widens no band's +/// overlap). +pub(crate) fn render_view_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option { start_render(); #[cfg(not(target_arch = "wasm32"))] if let Some(pool) = band_pool() { @@ -130,11 +137,13 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> let bands = threads.min(view.height / 96).max(1); if bands > 1 && view.width.saturating_mul(view.height) > 300_000 - && let Some(p) = pool.install(|| render_bands(doc, page, view, opts, bands)) + && let Some(p) = pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop)) { return Some(p); } } + #[cfg(target_arch = "wasm32")] + let _ = backdrop; render_one(doc, page, view, opts) } @@ -142,31 +151,45 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> /// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a /// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is /// drawn whole for a sliver of it), not its pixels. +#[cfg(test)] pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option { + render_part_with(doc, page, view, opts, max_backdrop_blur(doc)) +} + +/// [`render_part`], where `backdrop` is at least the largest backdrop radius of what it draws. +pub(crate) fn render_part_with(doc: &Document, page: NodeId, view: &View, opts: &Options, backdrop: f64) -> Option { start_render(); #[cfg(not(target_arch = "wasm32"))] if let Some(pool) = band_pool() { let threads = pool.current_num_threads().clamp(1, 16) as u32; let rendered = if view.height >= view.width { let bands = threads.min(view.height / 96); - (bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten() + (bands > 1).then(|| pool.install(|| render_bands_with(doc, page, view, opts, bands, backdrop))).flatten() } else { let bands = threads.min(view.width / 96); - (bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten() + (bands > 1).then(|| pool.install(|| render_columns_with(doc, page, view, opts, bands, backdrop))).flatten() }; if rendered.is_some() { return rendered; } } + #[cfg(target_arch = "wasm32")] + let _ = backdrop; render_one(doc, page, view, opts) } /// [`render_bands`] across: `bands` columns, overlapping by what background blurs read. -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(test, not(target_arch = "wasm32")))] fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option { + render_columns_with(doc, page, view, opts, bands, max_backdrop_blur(doc)) +} + +/// [`render_columns`], where `backdrop` is at least the largest backdrop radius of what it draws. +#[cfg(not(target_arch = "wasm32"))] +fn render_columns_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option { use rayon::prelude::*; let band_w = view.width.div_ceil(bands.max(1)); - let overlap = band_overlap(doc, view, band_w)?; + let overlap = overlap_for(backdrop, view, band_w)?; let s = view.scale.max(1e-9); let parts: Vec<(u32, Option)> = (0..bands) .into_par_iter() @@ -209,11 +232,17 @@ fn band_pool() -> Option<&'static rayon::ThreadPool> { /// read and each keeps only its own rows, so a backdrop never ends at a band's edge. `None` when a /// blur reaches past a whole band (every band would render most of the view: render it in one /// piece instead). -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(test, not(target_arch = "wasm32")))] fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option { + render_bands_with(doc, page, view, opts, bands, max_backdrop_blur(doc)) +} + +/// [`render_bands`], where `backdrop` is at least the largest backdrop radius of what it draws. +#[cfg(not(target_arch = "wasm32"))] +fn render_bands_with(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32, backdrop: f64) -> Option { use rayon::prelude::*; let band_h = view.height.div_ceil(bands.max(1)); - let overlap = band_overlap(doc, view, band_h)?; + let overlap = overlap_for(backdrop, view, band_h)?; let parts: Vec<(u32, Option)> = (0..bands) .into_par_iter() .map(|i| { @@ -232,8 +261,14 @@ fn render_bands(doc: &Document, page: NodeId, view: &View, opts: &Options, bands /// How many rows bands of `band_h` rows of `view` overlap (what background blurs read); `None` /// when that is more than a band. +#[cfg(test)] pub(crate) fn band_overlap(doc: &Document, view: &View, band_h: u32) -> Option { - let overlap = backdrop_reach(max_backdrop_blur(doc), view.scale).ceil(); + overlap_for(max_backdrop_blur(doc), view, band_h) +} + +/// [`band_overlap`] for backdrop radii up to `backdrop`. +pub(crate) fn overlap_for(backdrop: f64, view: &View, band_h: u32) -> Option { + let overlap = backdrop_reach(backdrop, view.scale).ceil(); (overlap.is_finite() && overlap <= f64::from(band_h)).then_some(overlap as u32) } @@ -727,6 +762,8 @@ mod render_depth_tests; #[cfg(test)] mod retained_edit_tests; #[cfg(test)] +mod retained_page_tests; +#[cfg(test)] mod retained_tests; #[cfg(test)] mod rtl_list_tests; diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index 977995b33..1a83ccf61 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -8,11 +8,11 @@ use std::sync::Arc; -use figcraft_doc::{Document, EffectKind, NodeId, NodeKind}; +use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind}; use figcraft_geom::Rect; use tiny_skia::Pixmap; -use crate::{Options, View, draw, render_view}; +use crate::{Options, View, draw}; /// What a render had to do. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -70,23 +70,58 @@ struct Sensitive { /// Grain effects (noise, texture) work on their layer's pixels, which end where a render cuts the /// layer (texture scatters pixels from across the cut): grainy layers are redrawn whole. -fn sensitive(doc: &Document) -> Sensitive { - let noisy = doc.nodes().filter(|n| n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_)))); - let pattern_sources = doc - .nodes() - .flat_map(|n| n.fills.iter().chain(&n.strokes)) - .filter_map(|p| match &p.kind { - figcraft_color::PaintKind::Pattern(pt) => Some(NodeId(pt.source)), - _ => None, - }) - .collect(); - Sensitive { areas: noisy.filter_map(|n| draw::paint_bounds(doc, n.id)).collect(), backdrop_blur: crate::max_backdrop_blur(doc), pattern_sources } +/// +/// Only what `page` draws counts: its layers, and the pattern sources they fill with wherever those +/// are (and the sources those fill with in turn), whose edits show on the page and whose backdrop +/// blurs count too. A source's grain is drawn in its cells, not where the source lies, so only the +/// page's own grainy layers give areas. One walk down the page rather than passes over every page +/// of the file: in a large file those passes took most of an edit's frame, and a blur on another +/// page widened every pan's strips and every band's overlap. +fn sensitive(doc: &Document, page: NodeId) -> Sensitive { + let mut noisy: Vec<(NodeId, Rect)> = Vec::new(); + let mut backdrop_blur = 0.0f64; + let mut pattern_sources = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + // A tree visits each node once (a source on the page twice); child lists repeated in a + // hostile file are cut off rather than walked in full. + let mut left = doc.node_count().saturating_mul(2).saturating_add(8); + // Each node with whether it is drawn where it lies on the page (a source's layers are drawn + // in its cells). + let mut stack = vec![(page, true)]; + while let Some((id, on_page)) = stack.pop() { + let Some(budget) = left.checked_sub(1) else { break }; + left = budget; + let Some(n) = doc.node(id) else { continue }; + if on_page + && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::Noise(_) | EffectKind::Texture(_))) + && let Some(r) = draw::paint_bounds(doc, id) + { + noisy.push((id, r)); + } + backdrop_blur = n.effects.iter().map(Effect::backdrop_radius).fold(backdrop_blur, f64::max); + for p in n.fills.iter().chain(&n.strokes) { + if let figcraft_color::PaintKind::Pattern(pt) = &p.kind { + let src = NodeId(pt.source); + if seen.insert(src) { + pattern_sources.push(src); + // A page as a source draws nothing. + if doc.node(src).is_some_and(|s| !s.is_page()) { + stack.push((src, false)); + } + } + } + } + stack.extend(n.children.iter().map(|c| (*c, on_page))); + } + // In id order, as a pass over the file found them. + noisy.sort_by_key(|(id, _)| *id); + Sensitive { areas: noisy.into_iter().map(|(_, r)| r).collect(), backdrop_blur, pattern_sources } } /// [`sensitive`] for the large-file timings: how many areas it found. #[cfg(test)] -pub(crate) fn bench_scan(doc: &Document, _page: NodeId) -> usize { - sensitive(doc).areas.len() +pub(crate) fn bench_scan(doc: &Document, page: NodeId) -> usize { + sensitive(doc, page).areas.len() } /// Whether `id` is a pattern source or inside one in `doc`. @@ -138,8 +173,8 @@ enum Prepared { /// The previous render patched (or reused as is), now kept. Patched(View, Work), /// Only a full render will do: the snapped view, its top-left device pixel, the font - /// generation and what [`sensitive`] found when the previous render's document was checked. - Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Option> }, + /// generation and what [`sensitive`] finds on the page. + Full { snapped: View, px: (i64, i64), fonts: u64, sensitive: Arc }, } /// What [`Retained::begin`] did. @@ -159,7 +194,7 @@ pub struct Steps { px: (i64, i64), fonts: u64, opts: Options, - sensitive: Option>, + sensitive: Arc, pix: Pixmap, /// The first row not drawn yet. next: u32, @@ -231,9 +266,8 @@ impl Retained { match self.prepare(doc, page, view, opts)? { Prepared::Patched(snapped, work) => Some((snapped, &self.last.as_ref()?.pix, work)), Prepared::Full { snapped, px, fonts, sensitive } => { - let pix = render_view(doc, page, &snapped, opts)?; - let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc))); - let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); + let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?; + let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive); Some((snapped, &frame.pix, Work::Full)) } } @@ -248,13 +282,12 @@ impl Retained { Prepared::Full { snapped, px, fonts, sensitive } => { // Bands at least twice what they overlap (each draws its overlap again both ways), // so a background blur reaching past `band_h` makes the bands taller. - let overlap = crate::band_overlap(doc, &snapped, u32::MAX).map(|o| o.min(snapped.height)); + let overlap = crate::overlap_for(sensitive.backdrop_blur, &snapped, u32::MAX).map(|o| o.min(snapped.height)); let band_h = band_h.max(1).max(overlap.unwrap_or(0).saturating_mul(2)); // A blur that can't be measured: one piece. let Some(overlap) = overlap else { - let pix = render_view(doc, page, &snapped, opts)?; - let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(doc))); - let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); + let pix = crate::render_view_with(doc, page, &snapped, opts, sensitive.backdrop_blur)?; + let frame = self.keep(doc, page, (&snapped, px, fonts), opts, pix, sensitive); return Some(Begun::Done(snapped, &frame.pix, Work::Full)); }; let pix = crate::new_pixmap(snapped.width, snapped.height)?; @@ -281,8 +314,7 @@ impl Retained { /// Keep the image `steps` drew (all its bands: see [`Steps::step`]) as a full render. pub fn finish(&mut self, steps: Steps) -> (View, &Pixmap) { let Steps { doc, page, view, px, fonts, opts, sensitive, pix, .. } = steps; - let s = sensitive.unwrap_or_else(|| Arc::new(self::sensitive(&doc))); - let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, s); + let frame = self.keep(&doc, page, (&view, px, fonts), &opts, pix, sensitive); (view, &frame.pix) } @@ -296,8 +328,12 @@ impl Retained { return None; }; let fonts = figcraft_text::layout_generation(); - let mut sens = None; - if let Some(last) = self.last.take() + let last = self.last.take(); + // What the previous render found on the page holds while the document, the page and the + // fonts (text's ink bounds) stay the same: a zoom works none of it out again. + let kept = last.as_ref().filter(|l| Arc::ptr_eq(&l.doc, doc) && l.page == page && l.fonts == fonts).map(|l| l.sensitive.clone()); + let s = kept.unwrap_or_else(|| Arc::new(sensitive(doc, page))); + if let Some(last) = last && last.page == page && last.outline == opts.outline_mode && last.outline_extras == opts.outline @@ -316,18 +352,14 @@ impl Retained { && last.fonts == fonts // Images are decoded into the file's colour space: a new profile redraws everything. && last.doc.color_profile == doc.color_profile + && let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) { - let same_doc = Arc::ptr_eq(&last.doc, doc); - let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) }; - if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) { - let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } }; - self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); - self.patched = areas; - return Some(Prepared::Patched(snapped, work)); - } - sens = Some(s); + let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } }; + self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); + self.patched = areas; + return Some(Prepared::Patched(snapped, work)); } - Some(Prepared::Full { snapped, px, fonts, sensitive: sens }) + Some(Prepared::Full { snapped, px, fonts, sensitive: s }) } /// Keep `pix`, the render of `at`: the snapped view, its top-left device pixel and the font @@ -648,7 +680,7 @@ fn patch( let mut pix = last.pix; shift(&mut pix, dx, dy)?; for d in &damage { - render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?; + render_into(FrameRender { doc, page, view, px, opts, backdrop: s.backdrop_blur }, d, margin, &mut pix)?; } let area = |d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]); @@ -712,13 +744,15 @@ struct FrameRender<'a> { view: &'a View, px: (i64, i64), opts: &'a Options, + /// The largest backdrop radius on the page. + backdrop: f64, } /// Render the frame pixels `d` (with `margin` more around, discarded) into `pix`. The margin stops /// at the frame's edge: background blurs and glass read what is drawn under them, and a full /// render's backdrops end where the frame does. fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> Option<()> { - let FrameRender { doc, page, view, px, opts } = frame; + let FrameRender { doc, page, view, px, opts, backdrop } = frame; let s = view.scale; let (w, h) = (i64::from(pix.width()), i64::from(pix.height())); let (ox, oy) = ((d.x0 - margin).max(0), (d.y0 - margin).max(0)); @@ -726,7 +760,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?); // The same pixel grid as the frame: origin (px + offset) / scale. let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh }; - let part = crate::render_part(doc, page, &sub, opts)?; + let part = crate::render_part_with(doc, page, &sub, opts, backdrop)?; // The rows of `d` in `part`, straight into their place (a copy of the part and a draw of the // copy took longer than rendering a simple part). let (skip_x, skip_y) = (usize::try_from(d.x0 - ox).ok()?, usize::try_from(d.y0 - oy).ok()?); diff --git a/crates/render/src/retained_page_tests.rs b/crates/render/src/retained_page_tests.rs new file mode 100644 index 000000000..40b586ea4 --- /dev/null +++ b/crates/render/src/retained_page_tests.rs @@ -0,0 +1,182 @@ +//! What the retained renderer works out about a page (grainy layers, pattern sources, the largest +//! backdrop blur) comes from that page and the pattern sources it draws, not from the whole file. + +use std::sync::Arc; + +use figcraft_color::{Color, Paint, PaintKind, PatternPaint}; +use figcraft_doc::{Blur, Document, Effect, EffectKind, NodeId, NodeKind}; +use figcraft_geom::Affine; + +use crate::retained_tests::assert_same; +use crate::{Options, Pixmap, Retained, View, Work, render_view}; + +fn solid(d: &mut Document, id: NodeId, hex: &str) { + d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex(hex).unwrap())]; +} + +fn pattern(d: &mut Document, id: NodeId, source: NodeId) { + let pt = PatternPaint::new(source.0); + d.get_mut(id).unwrap().fills = vec![Paint { kind: PaintKind::Pattern(pt), ..Paint::solid(Color::BLACK) }]; +} + +fn edit(doc: &Arc, f: impl FnOnce(&mut Document)) -> Arc { + let mut d = (**doc).clone(); + f(&mut d); + Arc::new(d) +} + +/// Render through `r`; the image, the view drawn and what it took. +fn render(r: &mut Retained, doc: &Arc, page: NodeId, v: &View) -> (Pixmap, View, Work) { + let (shown, pix, work) = r.render(doc, page, v, &Options::default()).unwrap(); + (pix.clone(), shown, work) +} + +/// Render through `r` and check the image against a full render of the same view: the same +/// pixels for a full render, the same up to anti-aliasing for a patched one. +fn check(r: &mut Retained, doc: &Arc, page: NodeId, v: &View) -> Work { + let (pix, shown, work) = render(r, doc, page, v); + let full = render_view(doc, page, &shown, &Options::default()).unwrap(); + if work == Work::Full { + assert!(pix.data() == full.data(), "a full retained render differs from render_view"); + } else { + assert_same(&pix, &full, &format!("{work:?}")); + } + work +} + +/// Shapes on the first page, and a background blur reaching far past any patch's margin on the +/// second: (document, first page, a shape on it). +fn blur_elsewhere() -> (Arc, NodeId, NodeId) { + let mut d = Document::new("blur elsewhere"); + let p = d.first_page().unwrap(); + let mut shape = None; + for i in 0..12u32 { + let r = d.create(p, NodeKind::Rectangle, "R", f64::from(i % 4) * 160.0 + 20.0, f64::from(i / 4) * 150.0 + 20.0, 120.0, 100.0).unwrap(); + solid(&mut d, r, ["E03030", "2040E0", "20C060", "F0C830"][i as usize % 4]); + shape.get_or_insert(r); + } + let other = d.add_page("Other"); + let frosted = d.create(other, NodeKind::Rectangle, "Frosted", 0.0, 0.0, 400.0, 300.0).unwrap(); + d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }]; + (Arc::new(d), p, shape.unwrap()) +} + +#[test] +fn a_blur_on_another_page_leaves_pans_and_edits_partial() { + let (doc, p, shape) = blur_elsewhere(); + let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 700, height: 500 }; + let mut r = Retained::default(); + assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full); + assert!(matches!(check(&mut r, &doc, p, &v(30.0)), Work::Partial { .. }), "a pan"); + let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0))); + assert!(matches!(check(&mut r, &moved, p, &v(30.0)), Work::Partial { .. }), "an edit"); + // A new zoom renders in bands as wide apart as the page's own blurs need (none here). + assert_eq!(check(&mut r, &moved, p, &View { scale: 1.5, ..v(30.0) }), Work::Full); +} + +#[test] +fn a_blur_on_the_page_still_renders_full_when_it_reaches_past_a_patch() { + let (doc, p, shape) = blur_elsewhere(); + // The same blur on the page shown. + let doc = edit(&doc, |d| { + let frosted = d.create(p, NodeKind::Rectangle, "Frosted", 300.0, 200.0, 200.0, 150.0).unwrap(); + d.get_mut(frosted).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(Blur::uniform(1000.0)), visible: true }]; + }); + let v = View { origin: (0.0, 0.0), scale: 1.0, width: 700, height: 500 }; + let mut r = Retained::default(); + check(&mut r, &doc, p, &v); + let moved = edit(&doc, |d| d.get_mut(shape).unwrap().transform = Affine::translate((60.0, 40.0))); + assert_eq!(check(&mut r, &moved, p, &v), Work::Full); +} + +/// A rectangle on the first page filled with a pattern whose source is a frame on the second +/// page; inside the source, a child and a layer filled with a second pattern, whose source is on +/// a third page. (document, first page, filled rectangle, source, child, nested source) +fn patterns() -> (Arc, NodeId, [NodeId; 4]) { + let mut d = Document::new("patterns"); + let p = d.first_page().unwrap(); + let filled = d.create(p, NodeKind::Rectangle, "Filled", 20.0, 20.0, 260.0, 200.0).unwrap(); + let plain = d.create(p, NodeKind::Rectangle, "Plain", 300.0, 40.0, 60.0, 60.0).unwrap(); + solid(&mut d, plain, "202020"); + let second = d.add_page("Sources"); + let source = d.create(second, NodeKind::Frame, "Source", 0.0, 0.0, 40.0, 40.0).unwrap(); + solid(&mut d, source, "E03030"); + let child = d.create(source, NodeKind::Rectangle, "Child", 4.0, 4.0, 14.0, 14.0).unwrap(); + solid(&mut d, child, "2040E0"); + let inner = d.create(source, NodeKind::Rectangle, "Inner", 20.0, 20.0, 18.0, 18.0).unwrap(); + let third = d.add_page("More sources"); + let nested = d.create(third, NodeKind::Rectangle, "Nested", 0.0, 0.0, 6.0, 6.0).unwrap(); + solid(&mut d, nested, "20C060"); + pattern(&mut d, inner, nested); + pattern(&mut d, filled, source); + (Arc::new(d), p, [filled, source, child, nested]) +} + +#[test] +fn edits_to_pattern_sources_on_other_pages_show_on_the_page() { + let (doc, p, [_, source, child, nested]) = patterns(); + let v = View { origin: (0.0, 0.0), scale: 1.0, width: 400, height: 260 }; + let mut r = Retained::default(); + check(&mut r, &doc, p, &v); + let mut doc = doc; + for (what, id, hex) in + [("the source", source, "F0C830"), ("a layer in the source", child, "FFFFFF"), ("a source the source fills with", nested, "000000")] + { + doc = edit(&doc, |d| solid(d, id, hex)); + assert_ne!(check(&mut r, &doc, p, &v), Work::Reused, "{what}"); + } +} + +#[test] +fn a_grainy_layer_patches_as_it_renders_after_a_zoom() { + let mut d = Document::new("grain"); + let p = d.first_page().unwrap(); + let grainy = d.create(p, NodeKind::Rectangle, "Grain", 60.0, 50.0, 120.0, 90.0).unwrap(); + solid(&mut d, grainy, "E03030"); + let noise = figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() }; + d.get_mut(grainy).unwrap().effects = vec![Effect { kind: EffectKind::Noise(noise), visible: true }]; + let other = d.add_page("Other"); + let far = d.create(other, NodeKind::Rectangle, "Far", 0.0, 0.0, 10.0, 10.0).unwrap(); + solid(&mut d, far, "2040E0"); + let doc = Arc::new(d); + let v = |x: f64, scale: f64| View { origin: (x, 0.0), scale, width: 400, height: 300 }; + let mut r = Retained::default(); + check(&mut r, &doc, p, &v(0.0, 1.0)); + assert_eq!(check(&mut r, &doc, p, &v(0.0, 1.7)), Work::Full); + // Pans across the grainy layer at the new zoom: it is redrawn whole each time. + for i in 1..=4 { + let (pix, shown, work) = render(&mut r, &doc, p, &v(f64::from(i) * 13.0, 1.7)); + let full = render_view(&doc, p, &shown, &Options::default()).unwrap(); + let worst = pix.data().iter().zip(full.data()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(matches!(work, Work::Partial { .. }), "{work:?}"); + assert!(worst <= 2, "pan {i}: {worst} levels off a full render"); + } +} + +#[test] +fn a_page_shown_again_after_another_matches() { + let (doc, p, [filled, ..]) = patterns(); + let other = doc.pages[1]; + let v = |x: f64| View { origin: (x, 0.0), scale: 1.0, width: 400, height: 260 }; + let mut r = Retained::default(); + check(&mut r, &doc, p, &v(0.0)); + assert_eq!(check(&mut r, &doc, other, &v(0.0)), Work::Full); + assert_eq!(check(&mut r, &doc, p, &v(0.0)), Work::Full); + assert!(matches!(check(&mut r, &doc, p, &v(24.0)), Work::Partial { .. })); + let moved = edit(&doc, |d| d.get_mut(filled).unwrap().transform = Affine::translate((40.0, 30.0))); + assert!(matches!(check(&mut r, &moved, p, &v(24.0)), Work::Partial { .. })); +} + +#[test] +fn a_layer_listed_as_its_own_child_ends_the_page_walk() { + let mut d = Document::new("loop"); + let p = d.first_page().unwrap(); + let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 50.0, 50.0).unwrap(); + solid(&mut d, f, "E03030"); + d.get_mut(f).unwrap().children.push(f); + let doc = Arc::new(d); + let mut r = Retained::default(); + let v = View { origin: (0.0, 0.0), scale: 1.0, width: 100, height: 100 }; + assert!(r.render(&doc, p, &v, &Options::default()).is_some()); + assert!(r.render(&doc, p, &View { origin: (5.0, 0.0), ..v }, &Options::default()).is_some()); +} From 927408fe160abfb429a0faa1d9ea23f93b27d209 Mon Sep 17 00:00:00 2001 From: Bryton Cooper Date: Sat, 28 Nov 2026 04:47:53 -0700 Subject: [PATCH 34/38] figcraft-web: confirmed saves for hosts that opt in (#2366) A host page that opts in with `?save=managed` (or `data-save="managed"` on the canvas) now gets each Save and Save As of the document with an `id` (`save-1`, `save-2`, ...), and the document keeps its unsaved changes until the host answers `figcraft:saved` with that `id`. Hosts that don't opt in see no change: a file still counts as saved once it is posted. - `host_saves.rs`: the bookkeeping, apart from the browser so it is tested natively. One save waits at a time; a newer one replaces it; answers for any other `id` are ignored; a file the host opens forgets the waiting save; a save unanswered after 30 s counts as not stored (the clock is passed in). A Save As becomes the document's file only once confirmed, so a retry after a failure is still `saveAs: true`. - `host.rs`: the listener only queues what the host sent; the shell handles it in order each frame. Exports and copies carry no `id` and `saveAs: false`. A timeout tells the user and posts `figcraft:failed` with the `id`, and the app wakes itself for it. - ui-egui: `Services::deliver_document` hands the document's own file over (its default is `download`, so desktop and plain browser saves are unchanged). `Delivery::Pending` skips `file.markSaved`; `FigApp::document_stored` and `document_not_stored` finish the save. - engine: `FileSnapshot::delivered` marks the snapshot's tab saved as of the snapshot, so edits made while the save was in flight stay unsaved, and a tab closed or saved since is left alone. It shares its tail with `FileSnapshot::save`. `craft-web-host` at the pinned rev has no host-to-app refusal message and no `host {confirmsSaves}` handshake (storytold/craft-libs#1338), so a host's refusal shows as the timeout until the crate adds them. Co-Authored-By: Claude Opus 5.5 --- apps/figcraft-web/src/host.rs | 169 +++++++++++--- apps/figcraft-web/src/host_saves.rs | 262 ++++++++++++++++++++++ apps/figcraft-web/src/main.rs | 7 +- apps/figcraft-web/src/query.rs | 8 + apps/figcraft-web/src/query_tests.rs | 16 +- apps/figcraft-web/src/web.rs | 58 +++-- crates/engine/src/cmd/file/save.rs | 25 ++- crates/engine/src/delivered_save_tests.rs | 46 ++++ crates/engine/src/lib.rs | 2 + crates/ui-egui/locales/en.toml | 4 + crates/ui-egui/src/app/files.rs | 50 ++++- crates/ui-egui/src/host_save_tests.rs | 85 ++++++- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/services.rs | 33 +++ packaging/web/README.md | 29 ++- 15 files changed, 723 insertions(+), 75 deletions(-) create mode 100644 apps/figcraft-web/src/host_saves.rs create mode 100644 crates/engine/src/delivered_save_tests.rs diff --git a/apps/figcraft-web/src/host.rs b/apps/figcraft-web/src/host.rs index 57b67ca85..1e5687124 100644 --- a/apps/figcraft-web/src/host.rs +++ b/apps/figcraft-web/src/host.rs @@ -24,6 +24,17 @@ //! - Everything else is a copy or export that never becomes the document: `false` — rendered //! images, SVG and PDF, `.fig` copies, and the variables exports (a `.variables.json` //! sidecar's `.json` extension doesn't make it a document). +//! - Confirmed saves, opt-in: with `?save=managed` in the URL, or `data-save="managed"` on the +//! canvas ([`crate::query::confirms_saves`]), each Save and Save As of the document carries an +//! `id` (`save-1`, `save-2`, …) and the document keeps its unsaved changes until the host answers +//! `figcraft:saved` with that `id` ([`crate::host_saves`]). Then it is saved as of the file the +//! host stored, so edits made meanwhile stay unsaved, and a Save As becomes the document's file +//! only then. Answers for any other `id` are ignored; a newer save replaces the one waiting; a +//! file the host opens forgets it (the user is told). Without an answer within 30 seconds the save counts as not +//! stored: the user is told and the host gets `figcraft:failed` with the `id`. Copies and exports +//! carry no `id` and `saveAs: false`. A host that doesn't opt in sees no change: every file +//! counts as saved once it is posted. `craft-web-host` has no message yet for a host to refuse a +//! save, so a refusal shows as the timeout. //! - `figcraft:dirty` whenever unsaved changes appear or go away, `figcraft:failed` when the app //! couldn't start. //! @@ -31,10 +42,14 @@ //! edit; `?author=` names the user for comments and board notes. use std::cell::RefCell; +use std::collections::VecDeque; use std::rc::Rc; use craft_web_host::web::{FileData, Host, Message}; -use figcraft_ui_egui::FigApp; +use figcraft_engine::cmd::file::FileSnapshot; +use figcraft_ui_egui::{Delivery, FigApp}; + +use crate::host_saves::HostSaves; /// The app id in the host messages (`figcraft:ready`). const APP: &str = "figcraft"; @@ -42,38 +57,87 @@ const APP: &str = "figcraft"; /// The longest user name taken from `?author=`. const MAX_AUTHOR_CHARS: usize = 200; -/// Files the host sent, on their way to the app's own open queue ([`figcraft_ui_egui::pending_open`]): -/// `(name, bytes)`. -pub type OpenQueue = Rc)>>>; +/// What the host sent, in the order it came, for the shell's next frame ([`Bridge::frame`]). +enum FromHost { + /// A file to open: `(name, bytes)`. + Open(String, Vec), + /// The save with this `id` is stored. + Saved(String), +} #[derive(Clone)] pub struct Bridge { host: Rc, - /// The file the host opened, and after a `saveAs` hand-over the document's file: the name a - /// Save under (`saveAs: false`) is decided against. - host_file: Rc>>, + /// The host confirms saves (`?save=managed`): document saves wait for its `saved`. + confirms_saves: bool, + /// The document's file and the save waiting for the host ([`crate::host_saves`]). + saves: Rc>>, + /// Messages heard and not yet handled. The listener only queues them: a page host can answer + /// while a post is still running, so nothing else is borrowed there. + inbox: Rc>>, } impl Bridge { /// The bridge for this page, or `None` when FigCraft isn't hosted: no `?host=parent` and no /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app - /// with downloads), or a parent on another origin. - pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option { - Some(Self { host: Rc::new(Host::connect(APP, canvas)?), host_file: Rc::default() }) + /// with downloads), or a parent on another origin. `confirms_saves`: the host opted in to + /// confirmed saves. + pub fn connect(canvas: &web_sys::HtmlCanvasElement, confirms_saves: bool) -> Option { + Some(Self { host: Rc::new(Host::connect(APP, canvas)?), confirms_saves, saves: Rc::default(), inbox: Rc::default() }) } - /// Hear the files the host sends, and queue each one on `opens` for the app's own open path - /// (the shell drains it into [`figcraft_ui_egui::pending_open`] every frame, so a host file - /// opens like a dropped one). - pub fn listen(&self, opens: OpenQueue, ctx: egui::Context) { - let host_file = self.host_file.clone(); + /// Hear the host's messages. They are handled in the shell's next frame ([`Bridge::frame`]), + /// in the order they came. + pub fn listen(&self, ctx: egui::Context) { + let inbox = self.inbox.clone(); self.host.listen(move |message| { - if let Message::Open { name, data } = message { - deliver_open(&opens, &ctx, &host_file, &name, &data); + let heard = match message { + Message::Open { name, data } => open_bytes(&name, &data), + Message::Saved { id } => Some(FromHost::Saved(id)), + _ => None, + }; + if let Some(heard) = heard { + inbox.borrow_mut().push_back(heard); + ctx.request_repaint(); } }); } + /// Every frame: handle what the host sent, in order (a file opens on the app's own open path, + /// as a dropped one does; a `saved` marks its document saved), and end a save that waited too + /// long. `now_ms`: the app's clock, which also wakes the app when the waiting save times out. + pub fn frame(&self, fig: &mut FigApp, ctx: &egui::Context, now_ms: u64) { + let heard = std::mem::take(&mut *self.inbox.borrow_mut()); + for message in heard { + match message { + FromHost::Open(name, bytes) => { + let forgotten = self.saves.borrow_mut().opened(&name); + if let Some(save) = forgotten { + fig.document_not_stored(&save.name, &figcraft_ui_egui::save_forgotten_on_open()); + } + queue_open(fig, name, bytes); + } + FromHost::Saved(id) => { + let confirmed = self.saves.borrow_mut().saved(&id); + match confirmed { + Some(save) => fig.document_stored(&save.name, save.file), + None => log::info!("host confirmed save {id:?}, which isn't the one waiting; ignored"), + } + } + } + } + let expired = self.saves.borrow_mut().expire(now_ms); + if let Some(save) = expired { + let secs = self.saves.borrow().timeout_ms() / 1000; + let _ = self.host.post_failed(&format!("save {} was not confirmed within {secs} seconds", save.id), Some(&save.id)); + fig.document_not_stored(&save.name, &figcraft_ui_egui::save_unconfirmed(usize::try_from(secs).unwrap_or(usize::MAX))); + } + let wait = self.saves.borrow().wait_ms(now_ms); + if let Some(wait) = wait { + ctx.request_repaint_after(std::time::Duration::from_millis(wait)); + } + } + /// `?author=`: the host's name for the user signs comments and board notes. pub fn set_author(app: &mut FigApp, author: &str) { let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect(); @@ -93,24 +157,53 @@ impl Bridge { /// The document file the host opened or the last Save As made, if any. pub fn host_file(&self) -> Option { - self.host_file.borrow().clone() + self.saves.borrow().host_file().map(str::to_string) } - /// Hand a file the app would otherwise download to the host; `false` when nothing was - /// delivered. The `saveAs` rule is this module's documentation's. + /// Hand a file the app would otherwise download to the host, without an `id`; `false` when + /// nothing was delivered. To a host that confirms saves only copies and exports come this way + /// (the document's own file goes through [`post_document`](Self::post_document)), so they are + /// `saveAs: false`; to one that doesn't, the `saveAs` rule is this module's documentation's. pub fn post_save(&self, path: &str, bytes: &[u8]) -> bool { let name = file_name(path); - let host_file = self.host_file.borrow().clone(); - let save_as = crate::hostmode::save_as(&name, host_file.as_deref()); + let save_as = !self.confirms_saves && self.saves.borrow().save_as(&name); let sent = self.host.post_save(&name, bytes, None, save_as).is_ok(); // After a Save As hand-over the host has the new file: the next Save of it sends its name // with `saveAs: false`. A failed send changes nothing, so a retry is still a Save As. if sent && save_as { - *self.host_file.borrow_mut() = Some(name); + self.saves.borrow_mut().adopt(&name); } sent } + /// Hand the host the document's own file (Save, Save As) as `file`. To a host that confirms + /// saves it goes with an `id` and stays unsaved until the host answers ([`Delivery::Pending`]); + /// otherwise as [`post_save`](Self::post_save). + pub fn post_document(&self, path: &str, bytes: &[u8], file: FileSnapshot, now_ms: u64, ctx: &egui::Context) -> Delivery { + if !self.confirms_saves { + return if self.post_save(path, bytes) { Delivery::Saved } else { Delivery::Refused }; + } + let name = file_name(path); + // Recorded before the post: a page host can answer while it is still dispatching. + let (started, timeout_ms) = { + let mut saves = self.saves.borrow_mut(); + (saves.start(&name, file, now_ms), saves.timeout_ms()) + }; + match self.host.post_save(&name, bytes, Some(&started.id), started.save_as) { + Ok(()) => { + // Schedule the timeout wakeup immediately so an idle tab still times out if the + // host never answers after this frame. + ctx.request_repaint_after(std::time::Duration::from_millis(timeout_ms)); + Delivery::Pending + } + Err(e) => { + log::error!("couldn't hand {name} to the host: {e}"); + self.saves.borrow_mut().failed(&started.id); + Delivery::Refused + } + } + } + /// Report unsaved changes when they appear or go away, not every frame (the crate does not /// repeat a state it already reported). pub fn set_dirty(&self, dirty: bool) { @@ -118,23 +211,33 @@ impl Bridge { } } -/// The file an open message carries, queued for the app's own open path, or nothing when the -/// payload isn't one (a `File` the app doesn't read, or over the open limit). -fn deliver_open(opens: &OpenQueue, ctx: &egui::Context, host_file: &RefCell>, name: &str, data: &FileData) { +/// The app's own open queue gets a file the host sent: the same "Opening as a new file" card as a +/// dropped file, and `file.open` with the contents once read. +fn queue_open(fig: &mut FigApp, name: String, bytes: Vec) { + let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes))); + fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen { + label: name.clone(), + params: serde_json::json!({ "name": name }), + command: "file.open", + target: None, + read: Some(read), + }); +} + +/// The file an open message carries, copied out for the next frame, or nothing when the payload +/// isn't one (a `File` the app doesn't read, or over the open limit). Once handled it is the +/// document's file: a Save of it under this name is `saveAs: false`. +fn open_bytes(name: &str, data: &FileData) -> Option { let name = crate::hostmode::open_name(name); let FileData::Bytes(array) = data else { log::warn!("host file {name} came as a File; FigCraft reads bytes only; not opened"); - return; + return None; }; if figcraft_ui_egui::browser_can_read(&name, data.size()).is_err() { log::warn!("host file {name} is too large to open in the browser; not opened"); - return; + return None; } - // The document's file is now the one the host sent: a Save of it under this name is - // `saveAs: false`. - *host_file.borrow_mut() = Some(name.clone()); - opens.borrow_mut().push((name, array.to_vec())); - ctx.request_repaint(); + Some(FromHost::Open(name, array.to_vec())) } /// The last component of `path`, or the whole of it when there is none. diff --git a/apps/figcraft-web/src/host_saves.rs b/apps/figcraft-web/src/host_saves.rs new file mode 100644 index 000000000..5c2f7e58c --- /dev/null +++ b/apps/figcraft-web/src/host_saves.rs @@ -0,0 +1,262 @@ +//! Confirmed saves: what the bridge ([`crate::host`]) knows about the files it handed a host page, +//! kept apart from the browser so every step is testable without one (like [`crate::hostmode`]). +//! +//! A host that confirms saves (`?save=managed`, [`crate::query::confirms_saves`]) gets each +//! Save and Save As of the document with an `id` and answers `saved` with that `id` once it stored +//! the file. Until then the document keeps its unsaved changes. Only one document save waits at a +//! time: a newer one replaces it, and an answer for any other `id` (an older save, a repeat, one +//! the host made up) is ignored. A save the host doesn't answer within the timeout counts as not +//! stored. A file the host opens forgets the save still waiting, so a late answer can't touch +//! the file opened since. +//! +//! The file the host opened, or the one the last Save As made, is kept here too: a Save As becomes +//! the document's file only once the host confirms it, so after a failed one the next Save is +//! still a Save As. + +/// How long a document save waits for the host's answer before it counts as not stored. +pub const DEFAULT_TIMEOUT_MS: u64 = 30_000; + +/// A document save handed to the host and not answered yet. +#[derive(Debug)] +pub struct PendingSave { + /// The `id` the save carried; the host's `saved` names it. + pub id: String, + /// The file name it went out under. + pub name: String, + /// It went out as `saveAs: true`: confirmed, it becomes the document's file. + pub save_as: bool, + /// When it was handed over, in the caller's clock (milliseconds). + pub started_at_ms: u64, + /// The document as handed over. In the app this is its `FileSnapshot` (the tab's uid, its + /// revision and contents), which marks the document saved as of the snapshot once confirmed. + pub file: F, +} + +/// A document save just handed to [`HostSaves::start`]: what to post with it. +#[derive(Debug, PartialEq, Eq)] +pub struct Started { + pub id: String, + pub save_as: bool, +} + +/// The bridge's record of the document's file and the save waiting for the host. +#[derive(Debug)] +pub struct HostSaves { + host_file: Option, + /// The number in the next save's `id`. Never reset, so an `id` is never used twice on a page. + next_id: u64, + pending: Option>, + timeout_ms: u64, +} + +impl Default for HostSaves { + fn default() -> Self { + Self::new(DEFAULT_TIMEOUT_MS) + } +} + +impl HostSaves { + pub fn new(timeout_ms: u64) -> Self { + Self { host_file: None, next_id: 1, pending: None, timeout_ms } + } + + /// How long a save waits for its answer, in milliseconds. + pub fn timeout_ms(&self) -> u64 { + self.timeout_ms + } + + /// The file the host opened, or the one the last confirmed (or, without confirmation, posted) + /// Save As made. + pub fn host_file(&self) -> Option<&str> { + self.host_file.as_deref() + } + + /// Whether a file named `name` goes out as `saveAs: true` now ([`crate::hostmode::save_as`]). + pub fn save_as(&self, name: &str) -> bool { + crate::hostmode::save_as(name, self.host_file.as_deref()) + } + + /// A Save As went to a host that doesn't confirm saves: `name` is the document's file now. + pub fn adopt(&mut self, name: &str) { + self.host_file = Some(name.to_string()); + } + + /// The host sent the file `name` to open: it is the document's file now. A save still waiting + /// was for the document open before, so it is forgotten and returned; its answer, if one + /// comes, is ignored, and that document keeps its unsaved changes. + pub fn opened(&mut self, name: &str) -> Option> { + self.host_file = Some(name.to_string()); + self.pending.take() + } + + /// A Save or Save As of the document as `file`, under `name`, handed over at `now_ms`: the `id` + /// and `saveAs` to post it with. A save still waiting is replaced, so its answer is ignored. + pub fn start(&mut self, name: &str, file: F, now_ms: u64) -> Started { + let id = format!("save-{}", self.next_id); + self.next_id += 1; + let save_as = self.save_as(name); + self.pending = Some(PendingSave { id: id.clone(), name: name.to_string(), save_as, started_at_ms: now_ms, file }); + Started { id, save_as } + } + + /// The host's `saved` for `id`: the save it confirms, when that is the one waiting. A Save As + /// becomes the document's file now. Any other `id` changes nothing. + pub fn saved(&mut self, id: &str) -> Option> { + let save = self.take(id)?; + if save.save_as { + self.host_file = Some(save.name.clone()); + } + Some(save) + } + + /// The save `id` could not be stored (the post failed, or the host refused it): the save, + /// when that is the one waiting. The document's file stays as it was. Any other `id` changes + /// nothing. + pub fn failed(&mut self, id: &str) -> Option> { + self.take(id) + } + + /// The save waiting since longer than the timeout at `now_ms`, which then counts as failed. + pub fn expire(&mut self, now_ms: u64) -> Option> { + let waiting = self.pending.as_ref()?; + if now_ms.saturating_sub(waiting.started_at_ms) < self.timeout_ms { + return None; + } + self.pending.take() + } + + /// How long from `now_ms` until the waiting save times out (so the app wakes then), or + /// `None` when none waits. + pub fn wait_ms(&self, now_ms: u64) -> Option { + let waiting = self.pending.as_ref()?; + Some((waiting.started_at_ms.saturating_add(self.timeout_ms)).saturating_sub(now_ms)) + } + + fn take(&mut self, id: &str) -> Option> { + if self.pending.as_ref().is_some_and(|p| p.id == id) { self.pending.take() } else { None } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The document as handed over: in these tests, a label for the revision saved. + type Saves = HostSaves<&'static str>; + + fn opened(name: &str) -> Saves { + let mut saves = Saves::default(); + assert!(saves.opened(name).is_none()); + saves + } + + #[test] + fn each_save_gets_an_id_of_its_own() { + let mut saves = opened("Poster.figcraft"); + let first = saves.start("Poster.figcraft", "r1", 0).id; + let second = saves.start("Poster.figcraft", "r2", 0).id; + assert_ne!(first, second); + saves.opened("Other.figcraft"); + let third = saves.start("Other.figcraft", "r3", 0).id; + assert!(third != first && third != second, "opening a file doesn't start the ids over"); + } + + #[test] + fn a_confirmed_save_hands_back_what_was_saved() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster.figcraft", "r1", 5); + assert!(!started.save_as, "a Save of the host's own file"); + let save = saves.saved(&started.id).expect("the waiting save"); + assert_eq!((save.file, save.name.as_str(), save.started_at_ms), ("r1", "Poster.figcraft", 5)); + assert!(saves.wait_ms(5).is_none(), "nothing waits any more"); + assert!(saves.saved(&started.id).is_none(), "a repeated answer changes nothing"); + } + + #[test] + fn a_save_as_becomes_the_document_s_file_only_once_confirmed() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + assert!(started.save_as); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "not before the host stored it"); + saves.saved(&started.id); + assert_eq!(saves.host_file(), Some("Poster 2.figcraft")); + assert!(!saves.start("Poster 2.figcraft", "r2", 0).save_as, "the next Save is of that file"); + } + + #[test] + fn a_failed_save_as_leaves_the_document_s_file_so_a_retry_is_still_a_save_as() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + let save = saves.failed(&started.id).expect("the waiting save"); + assert_eq!(save.file, "r1"); + assert_eq!(saves.host_file(), Some("Poster.figcraft")); + assert!(saves.start("Poster 2.figcraft", "r1", 0).save_as); + } + + #[test] + fn answers_for_other_ids_change_nothing() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + for id in ["", "save-0", "save-99", "Save-1 ", "nonsense"] { + assert!(saves.saved(id).is_none(), "{id:?}"); + assert!(saves.failed(id).is_none(), "{id:?}"); + } + assert_eq!(saves.host_file(), Some("Poster.figcraft")); + assert!(saves.saved(&started.id).is_some(), "the real answer still counts"); + } + + #[test] + fn a_newer_save_replaces_the_one_waiting() { + let mut saves = opened("Poster.figcraft"); + let older = saves.start("Poster 2.figcraft", "r1", 0); + let newer = saves.start("Poster.figcraft", "r2", 10); + assert!(saves.saved(&older.id).is_none(), "a late answer for the older save is ignored"); + assert!(saves.failed(&older.id).is_none()); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "the older Save As never became the file"); + assert_eq!(saves.saved(&newer.id).map(|s| s.file), Some("r2")); + } + + #[test] + fn a_save_left_unanswered_times_out() { + let mut saves = Saves::new(1_000); + saves.opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 100); + assert!(saves.expire(100).is_none()); + assert!(saves.expire(1_099).is_none(), "still inside the timeout"); + let remaining = saves.wait_ms(600).expect("a save waits"); + assert!(remaining > 0 && remaining < saves.timeout_ms(), "{remaining}"); + let save = saves.expire(1_100).expect("timed out"); + assert_eq!(save.file, "r1"); + assert_eq!(saves.host_file(), Some("Poster.figcraft"), "a timed-out Save As isn't the file"); + assert!(saves.saved(&started.id).is_none(), "an answer after the timeout is ignored"); + assert!(saves.expire(5_000).is_none() && saves.wait_ms(5_000).is_none()); + } + + #[test] + fn a_clock_that_goes_back_does_not_end_the_wait_early() { + let mut saves = Saves::new(1_000); + saves.start("Untitled.figcraft", "r1", 500); + assert!(saves.expire(0).is_none()); + assert!(saves.wait_ms(0).is_some_and(|w| w >= saves.timeout_ms())); + } + + #[test] + fn opening_a_file_forgets_the_save_still_waiting() { + let mut saves = opened("Poster.figcraft"); + let started = saves.start("Poster 2.figcraft", "r1", 0); + let dropped = saves.opened("Other.figcraft").expect("the save that waited"); + assert_eq!(dropped.file, "r1"); + assert!(saves.saved(&started.id).is_none(), "its late answer is ignored"); + assert_eq!(saves.host_file(), Some("Other.figcraft"), "and can't rename the file opened since"); + assert!(saves.expire(u64::MAX).is_none()); + } + + #[test] + fn without_confirmation_a_save_as_is_the_document_s_file_once_posted() { + let mut saves = Saves::default(); + assert!(saves.save_as("Untitled.figcraft"), "the host never sent a file"); + saves.adopt("Untitled.figcraft"); + assert!(!saves.save_as("Untitled.figcraft")); + assert!(!saves.save_as("Untitled.png"), "an export is never the document's file"); + } +} diff --git a/apps/figcraft-web/src/main.rs b/apps/figcraft-web/src/main.rs index 36d37ed39..59d2e008f 100644 --- a/apps/figcraft-web/src/main.rs +++ b/apps/figcraft-web/src/main.rs @@ -21,13 +21,14 @@ //! `http://` on a trusted network to reach plain `ws://` hosts on other machines. //! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `