From 0244230e1a82f2a69374aa07cf04753985531bb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 16:02:00 +0100 Subject: [PATCH 01/14] M6: .fig import sets a variable font's optical size to the text size Figma sets a variable font's optical size to the text size (within the axis), also for a named style; FigCraft keeps the named instance's (SF Pro's is 28, its display cut), so imported SF Pro text at text sizes came out about 14% narrower than in Figma. The .fig, paste and REST imports now carry the size as the text's opsz value, as the .sketch import already did (shared pass optical_size_follows_text_size). Rule from the glyph advances Figma saves in derivedTextData, in a real-world file and in a synthetic one saved from Figma's web app; Figma's Inter has no optical size axis and keeps its advances at every size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/engine/src/cmd/file/load.rs | 59 +++++++++++++++------ crates/engine/src/fig_optical_size_tests.rs | 39 ++++++++++++++ crates/engine/src/lib.rs | 2 + docs/file-format-parity.md | 5 +- 4 files changed, 86 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/fig_optical_size_tests.rs diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index d204931ac..c81f202d8 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -143,6 +143,7 @@ fn load_any( let (mut doc, warnings) = r.map_err(|e| EngineError::Other(e.to_string()))?; link_instances(&mut doc); installed_fonts_first(); + optical_size_follows_text_size(&mut doc); return Ok((figcraft_format::Loaded { issues: warnings, ..doc.into() }, true)); } let mut loaded = figcraft_format::load_bytes_with_versions(bytes).map_err(|e| EngineError::Other(e.to_string()))?; @@ -261,11 +262,40 @@ fn match_font_families(doc: &mut Document) { /// Sketch draws text with the tracking a font's `trak` table gives at its size (Apple's text engine /// adds it; FigCraft's, like Figma's, doesn't): the imported text keeps it as letter spacing, so /// lines measure and break as they did there. A named style's optical size follows the text size -/// there too (FigCraft keeps the instance's), so the imported text carries it as an `opsz` value. +/// there too ([`optical_size_follows_text_size`]). fn platform_tracking(doc: &mut Document) { + let mut face = face_cache(); + each_text_style(doc, &mut |style| { + let Some(f) = face(style) else { return }; + let t = f.tracking(style.font_size); + if t != 0.0 && t.is_finite() { + let px = style.letter_spacing.resolve(style.font_size); + style.letter_spacing = figcraft_doc::LetterSpacing::Pixels(px + t); + } + }); + optical_size_follows_text_size(doc); +} + +/// Figma and Sketch set a variable font's optical size to the text size (within the axis), also +/// for a named style; FigCraft keeps the named instance's (so existing documents render as +/// before). The imported text carries its size as an `opsz` value instead, unless it sets one. +/// Seen in the glyph advances `.fig` files save with their text: SF Pro Regular at 12–17 px is the +/// 17 cut, at 18, 20, 22 and 24 px that size's, at 30 px the 28 cut (the axis's top). +fn optical_size_follows_text_size(doc: &mut Document) { + let mut face = face_cache(); + each_text_style(doc, &mut |style| { + let Some(f) = face(style) else { return }; + if f.axis("opsz").is_some() && f.instance(&style.font_style).is_some() && style.font_size.is_finite() { + style.variations.entry("opsz".into()).or_insert(style.font_size); + } + }); +} + +/// A lookup of the installed face for a text style, cached per family and style. +fn face_cache() -> impl FnMut(&figcraft_doc::TextStyle) -> Option> { let mut cache: std::collections::BTreeMap<(String, String), Option>> = std::collections::BTreeMap::new(); - let mut face = |style: &figcraft_doc::TextStyle| { + move |style: &figcraft_doc::TextStyle| { cache .entry((style.font_family.clone(), style.font_style.clone())) .or_insert_with(|| { @@ -274,30 +304,24 @@ fn platform_tracking(doc: &mut Document) { .flatten() }) .clone() - }; - let mut track = |style: &mut figcraft_doc::TextStyle| { - let Some(f) = face(style) else { return }; - let t = f.tracking(style.font_size); - if t != 0.0 && t.is_finite() { - let px = style.letter_spacing.resolve(style.font_size); - style.letter_spacing = figcraft_doc::LetterSpacing::Pixels(px + t); - } - if f.axis("opsz").is_some() && f.instance(&style.font_style).is_some() && style.font_size.is_finite() { - style.variations.entry("opsz".into()).or_insert(style.font_size); - } - }; + } +} + +/// Calls `f` on every text style of the document: each text layer's, its runs' and the shared +/// text styles'. +fn each_text_style(doc: &mut Document, f: &mut dyn FnMut(&mut figcraft_doc::TextStyle)) { let ids: Vec = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id).collect(); for id in ids { if let Some(NodeKind::Text(td)) = doc.node_mut(id).map(|n| &mut n.kind) { - track(&mut td.style); + f(&mut td.style); for r in &mut td.runs { - track(&mut r.style); + f(&mut r.style); } } } for st in &mut doc.styles { if let StyleKind::Text { style, .. } = &mut st.kind { - track(style); + f(style); } } } @@ -397,6 +421,7 @@ pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option Option { + let NodeKind::Text(td) = &doc.nodes().find(|n| n.name == name)?.kind else { return None }; + td.style.variations.get("opsz").copied() +} + +/// macOS only: needs the system's variable SF font (an optical size axis and named instances). +#[test] +fn a_fig_import_sets_the_optical_size_to_the_text_size() { + if !std::path::Path::new("/System/Library/Fonts/SFNS.ttf").exists() { + return; + } + figcraft_text::fontdb::scan_system_fonts(); + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for (name, size, y) in [("Body", 17.0, 0.0), ("Title", 34.0, 40.0)] { + let props = json!({"fontFamily": "SF Pro", "fontStyle": "Regular", "fontSize": size}); + s.execute("text.create", &json!({"text": "Handgloves", "x": 0, "y": y, "name": name, "props": props})).unwrap(); + } + assert_eq!(opsz(s.doc().unwrap(), "Body"), None, "FigCraft's own text keeps the named instance's"); + let (bytes, _) = figcraft_format::fig::export(s.doc().unwrap(), None).unwrap(); + let back = crate::cmd::file::load_fig(&bytes, "x").unwrap().unwrap().doc; + let f = figcraft_text::fontdb::find_face("SF Pro", "Regular").unwrap(); + if f.axis("opsz").is_none() || f.instance("Regular").is_none() { + return; + } + assert_eq!(opsz(&back, "Body"), Some(17.0)); + assert_eq!(opsz(&back, "Title"), Some(34.0)); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ad6bb085e..c9ef71f6a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -345,6 +345,8 @@ mod fig_font_names_tests; #[cfg(test)] mod fig_import_tests; #[cfg(test)] +mod fig_optical_size_tests; +#[cfg(test)] mod fill_none_tests; #[cfg(test)] mod finite_geometry_tests; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8eac69eee..900ef0525 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-20 · **Change:** minor (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); `.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-20 · **Change:** minor (`.fig` and REST import: a variable font's optical size follows the text size, as in Figma, so SF Pro text is no longer set with its display cut at text sizes; 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); `.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 @@ -17,7 +17,7 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.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 | +| `.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). Since 2026-11-20, a variable font's optical size follows the text size (within the axis), also for a named style, as the glyph advances a `.fig` file saves with its text show for SF Pro (12–17 px set with the 17 cut, 18–24 px with their own size's, 30 px with the 28 cut); the text carries the size as its `opsz` value. A font without that axis is unaffected: Figma's own Inter has none, so its advances stay the same at every size, while a locally installed Inter 4 has one and can set large text narrower than Figma. Optical sizes a `.fig` text sets itself (`fontVariations`) are not read yet. 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 | — | @@ -195,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | M6: `.fig` and REST import set a variable font's optical size to the text size (within the axis), also for a named style, as the `.sketch` import already did: FigCraft keeps a named instance's optical size (SF Pro's is 28, its display cut), so imported SF Pro text at text sizes was set about 14% narrower than in Figma. Rule from the glyph advances `.fig` files saved by Figma carry (`derivedTextData.glyphs`): in a real-world file SF Pro Regular, Medium and Semibold at 12–17 px match the 17 cut and at 18–24 px their own size's, and a synthetic file saved from Figma's web app gives SF Pro Regular the 17 cut at 11–17 px, the 20 cut at 20 px and the 28 cut at 28–64 px; Figma's Inter (no optical size axis) keeps the same advances from 11 to 64 px. Checked against renders from Figma's REST images endpoint: on 24 screens of that file the share of differing pixels fell on every screen (median 3.2% → 1.7%). Test: `crates/engine/src/fig_optical_size_tests.rs`. Numbers unchanged | | 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. | | 2026-11-19 | patch | M6, #2468 follow-up: SVG import checks its input with craft-svg (`tree::parse`, `tree::image_resolver`), so FigCraft's own byte scanners (`too_wide`, `too_deep`, `nesting`) and `import/budget.rs` were dead code, and `main` failed `cargo fmt` and clippy. They are removed; the budget and hostile-input tests now run against craft-svg's `tree::Limits` (documents nest at most 256 levels deep, references followed, where FigCraft's scanner allowed 512). No behaviour change beyond #2468. | | 2026-11-19 | patch | M6, #2441: REST import warned "variables bound to `fills` (`effects`, `textRangeFills`) are not supported and were skipped" for layers that lost nothing: those node-level lists repeat the variables each gradient stop, effect and paint binds itself, which are read. The warning now names such a list only when it holds a variable none of them bound, so the warnings left mean a real loss. Test: `rest::proto_variable_tests::node_level_lists_the_paints_and_effects_bind_are_not_reported`. Numbers unchanged. | From aad01c0f6795628edb7391bade3651435e610030 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 16:57:27 +0100 Subject: [PATCH 02/14] M3: paint and shadow blend modes as the reference tool draws them Checked against renders of a synthetic file (9 scenes, each now under 0.2% differing pixels): - a layer in a blend mode of its own (Normal included) blends its fills among themselves only, then lays them over the canvas as one, with or without effects; - a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it drew as an isolated layer); - drop shadows blend among themselves, then lie under the layer as one; - inner shadows blend with the fills under them by their own mode; - plus lighter adds premultiplied colours, alpha as source-over. Found on iOS kit buttons imported from a .fig, which drew mid grey instead of near white. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/render/src/draw.rs | 123 +++++++++++++++++++++++--- crates/render/src/fill_blend_tests.rs | 106 ++++++++++++++++++++++ crates/render/src/fx.rs | 21 ++++- crates/render/src/lib.rs | 2 + crates/render/src/paint.rs | 10 ++- docs/target-app-parity.md | 5 +- 6 files changed, 252 insertions(+), 15 deletions(-) create mode 100644 crates/render/src/fill_blend_tests.rs diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index a5010006b..c2d781f9c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -151,13 +151,62 @@ fn pixels_when_magnified(prep: Prepared, device_scale: f64) -> Prepared { Prepared::Pattern { pixmap, mode, quality, opacity, transform } } -fn fill_with(pix: &mut Pixmap, path: &tiny_skia::Path, paints: &[Paint], w: f64, h: f64, xf: Affine, rule: FillRule, ctx: &Ctx, mask: Option<&Mask>) { +/// Paint `paints` over `path`, bottom first. Each blends by its own mode with what lies under it: +/// within a layer that isn't pass-through (`isolate`), only with the paints below it in the list, +/// the list then laid over the canvas as one (the reference tool's: a shape's fills on a +/// coloured backdrop, a plus-lighter or luminosity fill over a translucent one, come out the +/// same with or without effects on the shape); a pass-through frame's paints blend with the +/// backdrop too. +#[allow(clippy::too_many_arguments)] +fn fill_with( + pix: &mut Pixmap, + path: &tiny_skia::Path, + paints: &[Paint], + w: f64, + h: f64, + xf: Affine, + rule: FillRule, + ctx: &Ctx, + mask: Option<&Mask>, + isolate: bool, +) { + let blended = |p: &Paint| p.visible && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); + if isolate && paints.iter().any(blended) { + let area = path + .bounds() + .transform(ts_transform(xf)) + .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), (pix.width(), pix.height()))); + let Some(r) = area else { return }; + let Some(_held) = crate::layer_budget::Held::take(r.width(), r.height(), 1) else { return }; + let Some(mut alone) = Pixmap::new(r.width(), r.height()) else { return }; + let at = Affine::translate((-f64::from(r.x()), -f64::from(r.y()))) * xf; + paint_each(&mut alone, path, paints, w, h, at, rule, ctx, None); + let pp = PixmapPaint::default(); + pix.draw_pixmap(r.x(), r.y(), alone.as_ref(), &pp, Transform::identity(), mask); + return; + } + paint_each(pix, path, paints, w, h, xf, rule, ctx, mask); +} + +/// Paint `paints` over `path` onto `pix`, each by its own blend mode. +#[allow(clippy::too_many_arguments)] +fn paint_each( + pix: &mut Pixmap, + path: &tiny_skia::Path, + paints: &[Paint], + w: f64, + h: f64, + xf: Affine, + rule: FillRule, + ctx: &Ctx, + mask: Option<&Mask>, +) { let scale = xf.determinant().abs().sqrt(); for p in paints { let Some(prep) = prepare_at(p, w, h, scale, ctx.doc, ctx.time, ctx.preview) else { continue }; let prep = if ctx.magnified_image_pixels && matches!(p.kind, PaintKind::Image(_)) { pixels_when_magnified(prep, scale) } else { prep }; let paint = tiny_skia::Paint { shader: prep.shader(), anti_alias: true, blend_mode: ts_blend(p.blend), ..Default::default() }; - if p.blend == BlendMode::PlusDarker { + if crate::paint::own_blend(p.blend) { // No tiny-skia mode: the paint alone over its pixels, then blended in. let area = path .bounds() @@ -753,7 +802,8 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u None => shape.as_ref().and_then(|sh| shadow::inner_shadow(sh, lw, lh, lxf, ctx.scale, s)), } { - l.draw_pixmap(0, 0, inner.as_ref(), &PixmapPaint::default(), Transform::identity(), None); + // Blended by its own mode with the fills under it (a linear burn darkens them). + composite(l, (0, 0), &inner, 1.0, s.blend); } } }; @@ -773,7 +823,7 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u if let EffectKind::InnerShadow(s) = &e.kind && let Some(sh) = shadow::inner_shadow_of(&cover, ctx.scale, s) { - layer.draw_pixmap(0, 0, sh.as_ref(), &PixmapPaint::default(), Transform::identity(), None); + composite(&mut layer, (0, 0), &sh, 1.0, s.blend); } } } @@ -793,13 +843,23 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u c }); let caster = shadow::Caster::new(ctx.doc, n, content.as_ref().unwrap_or(&layer), lxf, ctx.scale); + // The shadows blend by their own modes among themselves, then lie under the layer as one + // (two linear-burn shadows darken where they overlap, not the backdrop under them). + let blended = n.effects.iter().any(|e| e.visible && matches!(&e.kind, EffectKind::DropShadow(s) if s.blend != BlendMode::Normal)); + let mut group = if blended { Pixmap::new(lw, lh) } else { None }; for e in n.effects.iter().filter(|e| e.visible) { if let EffectKind::DropShadow(s) = &e.kind && let Some(sh) = shadow::drop_shadow(&caster, s) { - composite(pix, (lx, ly), &sh, op, s.blend); + match group.as_mut() { + Some(g) => composite(g, (0, 0), &sh, 1.0, s.blend), + None => composite(pix, (lx, ly), &sh, op, s.blend), + } } } + if let Some(g) = &group { + composite(pix, (lx, ly), g, op, BlendMode::Normal); + } } if casts { // The backdrop with the shadows under it, the content over it, then the layer effects. @@ -809,9 +869,46 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u } layer_effects(ctx, &mut layer, n, id, lxf); } + if blends_through(ctx.doc, n, casts || first_back.is_some()) { + // A pass-through layer whose only effects are shadows isn't a group: once its shadows lie + // under it, what it paints blends by its own modes with the backdrop, as without them + // (the layer above was what the shadows were cast from). + let inner = |p: &mut Pixmap| { + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::InnerShadow(s) = &e.kind + && let Some(inner) = shape.as_ref().and_then(|sh| shadow::inner_shadow(sh, lw, lh, lxf, ctx.scale, s)) + { + composite(p, (lx, ly), &inner, 1.0, s.blend); + } + } + }; + let has_inner = shape.is_some() && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::InnerShadow(_))); + draw_content(ctx, pix, n, xf, depth, has_inner.then_some(&inner as &dyn Fn(&mut Pixmap))); + return; + } composite(pix, (lx, ly), &layer, op, n.blend); } +/// Whether pass-through layer `n` draws straight onto the canvas after its shadows instead of as +/// a layer: fully opaque, with no effect but drop and inner shadows (`backdrop`: it has background +/// blur or glass) and with paints or layers inside in a blend mode of their own, which would +/// otherwise blend only with the layer's other content. +fn blends_through(doc: &Document, n: &Node, backdrop: bool) -> bool { + if n.blend != BlendMode::PassThrough || n.opacity < 0.999 || backdrop { + return false; + } + if !n.effects.iter().filter(|e| e.visible).all(|e| matches!(e.kind, EffectKind::DropShadow(_) | EffectKind::InnerShadow(_))) { + return false; + } + if shadow::inner_from_pixels(doc, n) && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::InnerShadow(_))) { + return false; + } + let own = |p: &Paint| p.visible && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); + n.fills.iter().any(own) + || n.strokes.iter().any(own) + || doc.subtree(n.id).iter().skip(1).filter_map(|c| doc.node(*c)).any(|c| !matches!(c.blend, BlendMode::Normal | BlendMode::PassThrough)) +} + /// Node `n`'s backdrop effects through its backdrop outline `sh`, for its `size` layer at `at` on /// `pix` (local → layer pixels through `lxf`): what `pix` holds there now, over what lies under it. fn backdrop_layer(ctx: &Ctx, pix: &Pixmap, n: &Node, sh: &shadow::Outline, at: (i32, i32), size: (u32, u32), lxf: Affine) -> Option { @@ -859,6 +956,12 @@ fn draw_outline(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize) } } +/// Whether `n`'s own paints blend only among themselves: every layer but a pass-through one (a +/// layer in a blend mode of its own, Normal included, is a group of its own). +fn isolates_paints(n: &Node) -> bool { + n.blend != BlendMode::PassThrough +} + /// What paints over a node's fills, under its children and strokes (its inner shadows). type OverFills<'a> = Option<&'a dyn Fn(&mut Pixmap)>; @@ -882,7 +985,7 @@ fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft path.apply_affine(frame.inverse()); let Some(tp) = ts_path(&path) else { continue }; let rule = if region.winding == figcraft_doc::WindingRule::EvenOdd { FillRule::EvenOdd } else { FillRule::Winding }; - fill_with(pix, &tp, paints, pw, ph, xf * frame, rule, ctx, None); + fill_with(pix, &tp, paints, pw, ph, xf * frame, rule, ctx, None, isolates_paints(n)); } } } @@ -934,7 +1037,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, for k in &keys { let fills = layout.styles.get(*k).and_then(|s| s.fills.as_ref()).unwrap_or(&n.fills); if let Some(tp) = by_style.get(k).and_then(ts_path) { - fill_with(pix, &tp, fills, w, h, gxf, FillRule::Winding, ctx, None); + fill_with(pix, &tp, fills, w, h, gxf, FillRule::Winding, ctx, None, isolates_paints(n)); } for (_, item) in ink.iter().filter(|(style, _)| style == k) { match item { @@ -958,7 +1061,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, for path in keys.iter().filter_map(|k| by_style.get(k)) { let s = stroke_area(n, path, true); if let Some(ts) = ts_path(&s) { - fill_with(pix, &ts, &n.strokes, w, h, gxf, stroke_rule(n, true), ctx, None); + fill_with(pix, &ts, &n.strokes, w, h, gxf, stroke_rule(n, true), ctx, None, isolates_paints(n)); } } } @@ -978,7 +1081,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, } else if let Some((path, rule)) = &outline && let Some(tp) = ts_path(path) { - fill_with(pix, &tp, &n.fills, w, h, xf, *rule, ctx, None); + fill_with(pix, &tp, &n.fills, w, h, xf, *rule, ctx, None, isolates_paints(n)); } } if let Some(f) = over_fills { @@ -999,7 +1102,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, if let Some(g) = geom { let area = stroke_area(n, &g, closed); if let Some(tp) = ts_path(&area) { - fill_with(pix, &tp, &n.strokes, w, h, xf, stroke_rule(n, closed), ctx, None); + fill_with(pix, &tp, &n.strokes, w, h, xf, stroke_rule(n, closed), ctx, None, isolates_paints(n)); } } } diff --git a/crates/render/src/fill_blend_tests.rs b/crates/render/src/fill_blend_tests.rs new file mode 100644 index 000000000..e4b2b8ee1 --- /dev/null +++ b/crates/render/src/fill_blend_tests.rs @@ -0,0 +1,106 @@ +//! Blend modes of a layer's paints and shadows, against renders of the same synthetic scenes by +//! the reference tool (the expected values are its pixels, within a few levels): a layer in a +//! blend mode of its own (Normal included) is a group, so its fills blend with each other only and +//! then lie over the canvas as one, with or without effects; a pass-through frame's fills blend +//! with what lies under it, shadows or not. Drop shadows blend among themselves, inner shadows +//! with the fills under them. Plus lighter adds the premultiplied colours and combines the alphas +//! as source-over does. + +use figcraft_color::{BlendMode, Color, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow}; + +use super::paint_behaviour_tests::{hex, near, page, px, rect, render, solid_at}; +use super::*; + +const BACK: &str = "F7F8FC"; + +fn blended(c: &str, opacity: f32, blend: BlendMode) -> Paint { + Paint { blend, ..solid_at(c, opacity) } +} + +/// The fill stack of the reference tool's glass buttons: black and white at 25%, `#444` at 60% +/// plus lighter, `#F8F8F8` at 20% luminosity. +fn stack() -> Vec { + vec![ + solid_at("000000", 0.25), + solid_at("FFFFFF", 0.25), + blended("444444", 0.6, BlendMode::PlusLighter), + blended("F8F8F8", 0.2, BlendMode::Luminosity), + ] +} + +fn shadow(kind: fn(Shadow) -> EffectKind, c: &str, a: f32, offset: (f64, f64), radius: f64, spread: f64, blend: BlendMode) -> Effect { + let color = Color { a, ..hex(c) }; + Effect { kind: kind(Shadow { color, offset, radius, spread, blend, ..Shadow::default() }), visible: true } +} + +/// A faint drop shadow that only makes the layer carry an effect. +fn faint() -> Effect { + shadow(EffectKind::DropShadow, "000000", 0.02, (0.0, 8.0), 15.0, 0.0, BlendMode::Normal) +} + +/// The backdrop: the page filled `BACK` with a blue stripe on the left. +fn backdrop() -> (Document, NodeId) { + let (mut d, p) = page(); + rect(&mut d, p, (0.0, 0.0, 200.0, 200.0), vec![Paint::solid(hex(BACK))]); + rect(&mut d, p, (0.0, 0.0, 40.0, 200.0), vec![Paint::solid(hex("2A7FFF"))]); + (d, p) +} + +/// A 160 × 120 layer at (20, 40) of `kind` with `fills` and `effects` over [`backdrop`]. +fn scene(kind: NodeKind, blend: BlendMode, fills: Vec, effects: Vec) -> Pixmap { + let (mut d, p) = backdrop(); + let id = d.create(p, kind, "L", 20.0, 40.0, 160.0, 120.0).unwrap(); + let n = d.get_mut(id).unwrap(); + (n.fills, n.effects, n.blend) = (fills, effects, blend); + render(&d) +} + +fn shape(fills: Vec, effects: Vec) -> Pixmap { + scene(NodeKind::Rectangle, BlendMode::Normal, fills, effects) +} + +#[test] +fn a_shapes_fills_blend_among_themselves_with_or_without_effects() { + for effects in [vec![], vec![faint()]] { + let pix = shape(stack(), effects.clone()); + assert!(near(px(&pix, 100, 100), [179, 179, 179], 3), "{:?} with {} effects", px(&pix, 100, 100), effects.len()); + assert!(near(px(&pix, 30, 100), [142, 157, 180], 3), "{:?} over blue", px(&pix, 30, 100)); + } +} + +#[test] +fn one_plus_lighter_fill_on_a_shape_is_a_plain_fill() { + for effects in [vec![], vec![faint()]] { + let pix = shape(vec![blended("444444", 0.6, BlendMode::PlusLighter)], effects); + assert!(near(px(&pix, 100, 100), [140, 140, 142], 3), "{:?}", px(&pix, 100, 100)); + } +} + +#[test] +fn a_pass_through_frames_fills_blend_with_the_backdrop_under_its_shadows() { + for effects in [vec![], vec![faint()]] { + let pix = scene(NodeKind::Frame, BlendMode::PassThrough, stack(), effects.clone()); + assert!(near(px(&pix, 100, 100), [245, 245, 247], 3), "{:?} with {} effects", px(&pix, 100, 100), effects.len()); + assert!(near(px(&pix, 30, 100), [153, 191, 249], 3), "{:?} over blue", px(&pix, 30, 100)); + } +} + +#[test] +fn drop_shadows_blend_among_themselves_not_with_the_backdrop() { + let burn = |c, x: f64, spread| shadow(EffectKind::DropShadow, c, 1.0, (x, 0.0), 0.0, spread, BlendMode::PlusDarker); + let pix = shape(vec![Paint::solid(Color::WHITE)], vec![burn("E8E8E8", 0.0, 4.0), burn("D0D0D0", -6.0, -2.0)]); + // Both shadows over the blue stripe: `D0 + E8 - FF`, grey; the first alone: its own colour. + assert!(near(px(&pix, 17, 100), [185, 185, 185], 3), "{:?}", px(&pix, 17, 100)); + assert!(near(px(&pix, 100, 37), [232, 232, 232], 3), "{:?}", px(&pix, 100, 37)); +} + +#[test] +fn inner_shadows_blend_with_the_fills_under_them() { + let burn = shadow(EffectKind::InnerShadow, "E6E6E6", 1.0, (0.0, 40.0), 30.0, -10.0, BlendMode::PlusDarker); + let dodge = shadow(EffectKind::InnerShadow, "282828", 1.0, (0.0, -40.0), 10.0, -10.0, BlendMode::PlusLighter); + let pix = shape(vec![Paint::solid(hex("808080"))], vec![dodge, burn]); + // Near the top the burn darkens the grey (`80 + E6 - FF`), near the bottom the dodge lightens it. + assert!(near(px(&pix, 100, 45), [103, 103, 103], 4), "{:?}", px(&pix, 100, 45)); + assert!(near(px(&pix, 100, 155), [168, 168, 168], 4), "{:?}", px(&pix, 100, 155)); +} diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index fd5f3764c..98e52ee86 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -288,6 +288,22 @@ pub(crate) fn overlap_rows(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, mut f /// `max(0, backdrop + source - 1)`, through the W3C general compositing formula), which /// tiny-skia lacks. pub fn plus_darker(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, opacity: f32) { + plus(dst, at, src, opacity, false); +} + +/// Composite `src` at `opacity` onto `dst` (top-left at `at`) with plus-lighter as the reference +/// tool draws it: the premultiplied colours add up (`min(1, cb + cs)` on an opaque backdrop, the +/// source counted at its opacity) and the alphas combine as source-over does. tiny-skia's `Plus` +/// adds the alphas too, so a fill stack over a translucent one came out opaque; the W3C general +/// formula comes out darker where the sum saturates (a 60% `#444` over 80% grey: 0.92 instead of +/// 0.96). Both checked on renders of synthetic files. +pub fn plus_lighter(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, opacity: f32) { + plus(dst, at, src, opacity, true); +} + +/// Linear dodge (`lighter`, see [`plus_lighter`]) or burn (the general formula, premultiplied: +/// `cs (1 - ab) + cb (1 - as) + as ab B(Cb, Cs)`). +fn plus(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, opacity: f32, lighter: bool) { let o = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 0.0 }; overlap_rows(dst, at, src, |dp, sp, _, _| { for (d, s) in dp.chunks_exact_mut(4).zip(sp.chunks_exact(4)) { @@ -297,12 +313,13 @@ pub fn plus_darker(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, opacity: f32) continue; } let da = f(d[3]); + let alpha = (sa + da - sa * da).clamp(0.0, 1.0); for c in 0..3 { let (sc, dc) = (f(s[c]) * o, f(d[c])); - let v = sc * (1.0 - da) + dc * (1.0 - sa) + (sa * dc + da * sc - sa * da).max(0.0); + let v = if lighter { (sc + dc).min(alpha) } else { sc * (1.0 - da) + dc * (1.0 - sa) + (sa * dc + da * sc - sa * da).max(0.0) }; d[c] = (v.clamp(0.0, 1.0) * 255.0).round() as u8; } - d[3] = ((sa + da - sa * da).clamp(0.0, 1.0) * 255.0).round() as u8; + d[3] = (alpha * 255.0).round() as u8; } }); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4a2ccc0fb..000396254 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -643,6 +643,8 @@ mod effect_order_tests; #[cfg(test)] mod effects_behaviour_tests; #[cfg(test)] +mod fill_blend_tests; +#[cfg(test)] mod gif_tests; #[cfg(test)] mod glass_bench_tests; diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 56de03464..22ca71d7f 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -16,7 +16,8 @@ pub fn ts_blend(b: BlendMode) -> tiny_skia::BlendMode { BlendMode::PassThrough | BlendMode::Normal => T::SourceOver, BlendMode::Darken => T::Darken, BlendMode::Multiply => T::Multiply, - // Plus darker has no tiny-skia mode: `composite` draws it; elsewhere the nearest one. + // Plus darker has no tiny-skia mode and plus lighter's (`Plus`) adds the alphas too: + // `composite` draws both (see [`own_blend`]); elsewhere the nearest one. BlendMode::PlusDarker => T::Multiply, BlendMode::ColorBurn => T::ColorBurn, BlendMode::Lighten => T::Lighten, @@ -35,10 +36,17 @@ pub fn ts_blend(b: BlendMode) -> tiny_skia::BlendMode { } } +/// The blend modes [`composite`] draws itself rather than through a tiny-skia mode. +pub fn own_blend(b: BlendMode) -> bool { + matches!(b, BlendMode::PlusDarker | BlendMode::PlusLighter) +} + /// Draw `src` (top-left at `at`) onto `dst` at `opacity`, blended by `blend`. pub fn composite(dst: &mut Pixmap, at: (i32, i32), src: &Pixmap, opacity: f32, blend: BlendMode) { if blend == BlendMode::PlusDarker { crate::fx::plus_darker(dst, at, src, opacity); + } else if blend == BlendMode::PlusLighter { + crate::fx::plus_lighter(dst, at, src, opacity); } else { let paint = tiny_skia::PixmapPaint { opacity, blend_mode: ts_blend(blend), ..Default::default() }; dst.draw_pixmap(at.0, at.1, src.as_ref(), &paint, Transform::identity(), None); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 409efe1d7..a583ee32b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -102,7 +102,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 2 | Selection & transform | 8 | 97% | 72% | Handles, measuring and snapping checked tool by tool against Figma and real files (snap distance, handle reach, cursors); children turned off a right angle scale without skew, approximately (behaviour suite from the documentation, rotated groups and mixed selections, equal spacing snapping, Cmd/Ctrl to ignore constraints and marquees inside frames landed) | 3–5 | | 3 | Layers panel | 5 | 99% | 85% | QA with long real files (behaviour suite from the documentation, Rename layers dialog, sweeping eyes and padlocks, page dragging and dividers, several layers dropped together, keyboard box selection, F2 rename, Shift+F10 context menu and 10k-layer timings landed) | 1–2 | | 4 | Shapes & vector | 8 | 99% | 73% | per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons, stars and closed vectors, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation, a boolean group's corner radius and the miter angle landed) | 1–3 | -| 5 | Paint | 7 | 90% | 71% | Video fills, wide-gamut canvas, HEIC images; plus darker in PDF (behaviour suite from the documentation, pass-through and isolating groups, clipping frames that don't isolate, plus darker, animated GIF fills, TIFF images and embedded image colour profiles landed) | 2–5 | +| 5 | Paint | 7 | 90% | 71% | Video fills, wide-gamut canvas, HEIC images; plus darker in PDF (behaviour suite from the documentation, pass-through and isolating groups, clipping frames that don't isolate, plus darker, animated GIF fills, TIFF images and embedded image colour profiles landed; paint and shadow blend modes checked against the reference tool's renders of synthetic files, 2026-11-20) | 2–5 | | 6 | Strokes | 3 | 95% | 75% | Stroke QA with real files (colour styles on strokes, stroke weight and per-side weight variables, brush strokes landed, see 20) | 1–2 | | 7 | Effects | 4 | 100% | 75% | Glass and progressive blur tuned side by side (behaviour suite from the documentation, inner shadows and background blur on groups, shadows hidden behind translucent layers on the canvas and in every export landed; a background blur or glass exported on its own keeps the content behind it within its bounds, measured 2026-11-10, #2213) | 2–5 | | 8 | Frames, groups, sections, masks | 5 | 97% | 80% | Visual QA with real files (a one-step frame/group convert, and a behaviour suite from the documentation landed: masked-out areas don't take clicks, mask group bounds and exports follow the mask, sections kept out of frames and groups, frames and sections drawn around layers take them, section resizing leaves contents in place, X/Y measured in the frame) | 1–3 | @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Paint blend modes checked against renders of a synthetic file by the reference tool (9 scenes; differing pixels before → after: up to 39% → under 0.2% each) and fixed on the canvas and in PNG exports: a layer in a blend mode of its own (Normal included) blends its fills with each other only, then lays them over the canvas as one, with or without effects (they blended with the backdrop until a layer had an effect, then not); a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it was drawn as an isolated layer); drop shadows blend by their modes among themselves, then lie under the layer as one (two linear-burn shadows darkened the backdrop); inner shadows blend with the fills under them by their own mode (they were drawn normally); plus lighter adds the premultiplied colours and combines the alphas as source-over does (tiny-skia's sum made a translucent stack opaque). Found on iOS kit buttons and alerts imported from a `.fig`: their fill stacks (plus lighter, luminosity) drew mid grey instead of near white. Tests: `crates/render/src/fill_blend_tests.rs`. SVG and PDF exports unchanged. Percentages and hours unchanged at this rounding | | 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | | 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`. | | 2026-11-09 | patch | M5, #2127: presenting a frame taller than about 2900 units at 1440 wide on a 2x display (Fit width, or 100%) drew it blurry: the whole frame is rasterised once, capped at 16.8 million pixels (a 1440 by 9701 frame at 1.1 pixels a unit, 1579 by 10632), and stretched up 1.8 times with linear filtering, while the canvas, which renders only what is in view, stayed sharp. Now the part in view plus a quarter of its size each way is drawn again over that texture from one more at the full pixel scale (never past the GPU's side or the same pixel cap), rendered when it stops covering the view and not while a fling, drag or the wheel moves it (while the view moves, a detail is drawn only while it covers the whole view: past it the capped texture shows alone, with no sharp edge across the view, until the view settles); transitions, smart animate, overlays and thumbnails keep the capped texture. Tests: `present::tests::tall_frame_detail_plan_renders_the_view_at_device_scale`, `presenting_a_tall_frame_on_a_hidpi_display_draws_the_view_at_device_scale`. Numbers unchanged | From d5a0d7169056d362f3c1b96185614c6a45af8425 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 17:58:21 +0100 Subject: [PATCH 03/14] M6: imported variant properties bound to a mode variable pick their variant A design kit's Light/Dark components switch variant through a `Mode` string variable bound to the variant property. Imports dropped that: dark screens showed the light variants. - REST import reads boundVariables.componentProperties (variant, text and boolean properties) as componentProperties/ bindings. - An opened REST or .fig file settles them: each bound instance shows the variant the variable names in its mode, outer instances first, keeping its own overrides and the ones the mains around it make. - A text reads a property its instance sets even when the variant set lists it under another id (imported library copies do). .fig needs craft-libs craft-fig with the RESOLVE_VARIANT mapping (local commit edcc9d6d3). On a real-world iOS kit file: dark alerts 28%/20% and the dark keyboard 38% differing pixels -> 2%, 1.4%, 1.7%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/engine/src/assets/components.rs | 1 + crates/engine/src/assets/components/diff.rs | 36 ++++ crates/engine/src/assets/components/sync.rs | 9 +- crates/engine/src/cmd/file/load.rs | 1 + crates/engine/src/cmd/styles.rs | 51 +++++ crates/engine/src/lib.rs | 4 + .../src/variant_binding_import_tests.rs | 183 ++++++++++++++++++ .../engine/src/variant_mode_switch_tests.rs | 108 +++++++++++ crates/format/src/rest.rs | 10 + crates/format/src/rest/variables.rs | 17 +- docs/file-format-parity.md | 7 +- 11 files changed, 419 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/variant_binding_import_tests.rs create mode 100644 crates/engine/src/variant_mode_switch_tests.rs diff --git a/crates/engine/src/assets/components.rs b/crates/engine/src/assets/components.rs index 06c82563a..54eee67e0 100644 --- a/crates/engine/src/assets/components.rs +++ b/crates/engine/src/assets/components.rs @@ -51,6 +51,7 @@ mod variants; pub use cycles::{ break_component_cycles, check_component_cycles, component_cycle, contains_itself_error, cycle_text, new_cycle, would_contain_itself, }; +pub(crate) use diff::keep_inherited_overrides; pub use diff::{diff_groups, property_owners, set_boolean_default, variable_groups}; pub use guard::{check_override_edit, check_structure_edit, refused_override, unlink_layers}; pub(crate) use instances::copy_group; diff --git a/crates/engine/src/assets/components/diff.rs b/crates/engine/src/assets/components/diff.rs index 5c6b7e4c5..e70ad072c 100644 --- a/crates/engine/src/assets/components/diff.rs +++ b/crates/engine/src/assets/components/diff.rs @@ -217,3 +217,39 @@ pub(super) fn follow_boolean_defaults(doc: &mut Document, before: &Document, cha } out } + +/// Before instance `inst` switches from main `old` to another variant: the overrides its layers +/// inherit from the mains around it (a destructive button's main binding its background +/// instance's tint to red) become the layers' own, so the rebuild carries them onto the new +/// variant by name, as the reference tool applies an enclosing main's overrides over whichever +/// variant a nested instance shows. The layers already hold those values. +pub(crate) fn keep_inherited_overrides(doc: &mut Document, inst: NodeId, old: NodeId) { + const MAX_HOPS: usize = 64; + let mut found: Vec<(NodeId, Vec)> = Vec::new(); + for d in doc.subtree(inst).into_iter().skip(1) { + let Some(n) = doc.node(d) else { continue }; + let mut inherited: Vec = Vec::new(); + let mut src = n.source; + for _ in 0..MAX_HOPS { + let Some(s) = src.and_then(|s| doc.node(s)) else { break }; + // The main being left: its own values are what the new variant replaces. + if s.id == old || doc.ancestors(s.id).contains(&old) { + break; + } + for g in &s.overrides { + if !n.overrides.contains(g) && !inherited.contains(g) { + inherited.push(g.clone()); + } + } + src = s.source; + } + if !inherited.is_empty() { + found.push((d, inherited)); + } + } + for (d, groups) in found { + if let Some(n) = doc.node_mut(d) { + n.overrides.extend(groups); + } + } +} diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index b8c9bdf8d..e49286e12 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -300,13 +300,14 @@ fn remeasure_text(doc: &mut Document, remeasure: Vec) { } } -/// The component's property defaults with the instance's values for the ones it has. +/// The component's property defaults with the instance's values, also for a property the +/// component doesn't list that a layer inside reads: an imported kit's text can read a property +/// the variant set lists under another id, which the instance sets (the reference tool goes by +/// the property a layer reads, not by the list). fn effective_props(comp: &Node, root_props: &BTreeMap) -> BTreeMap { let mut eff_props = default_props(comp); for (k, v) in root_props { - if eff_props.contains_key(k) { - eff_props.insert(k.clone(), v.clone()); - } + eff_props.insert(k.clone(), v.clone()); } eff_props } diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index c81f202d8..4964c9c35 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -730,6 +730,7 @@ fn link_instances(doc: &mut Document) { for (_, i) in insts { crate::components::rebase_instance_with(doc, i, &mut mains); } + crate::cmd::styles::apply_prop_bindings_on_load(doc); } /// Largest image file read for a REST API file JSON import. diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index f5a0dd6a0..918b59016 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -1262,6 +1262,57 @@ pub(crate) fn apply_paint_bindings_on_load(doc: &mut Document) { /// Re-apply the variable bindings whose field passes `include`, on the `only` nodes (every bound /// node when `None`). Auto layout fields wait while their node has no auto layout. +/// Settle imported instances whose component properties are bound to variables before the +/// document is first shown: a variant property bound to a string variable (a kit's Light/Dark +/// `Mode`) switches each instance to the variant the variable names in its mode, and the instance +/// follows that variant, keeping what the mains around it override. Again for the instances the +/// new content brings, until nothing switches (a few rounds at most). +pub(crate) fn apply_prop_bindings_on_load(doc: &mut Document) { + const MAX_ROUNDS: usize = 8; + let prop_bound = |n: &Node| matches!(n.kind, NodeKind::Instance { .. }) && n.bound.keys().any(|k| k.starts_with(crate::components::PROP_BINDING)); + let pending = doc.take_dirty(); + for _ in 0..MAX_ROUNDS { + let before: Vec<(NodeId, NodeId)> = doc + .nodes() + .filter(|n| prop_bound(n)) + .filter_map(|n| match n.kind { + NodeKind::Instance { component, .. } => Some((n.id, component)), + _ => None, + }) + .collect(); + if before.is_empty() { + break; + } + let ids: std::collections::BTreeSet = before.iter().map(|(i, _)| *i).collect(); + apply_bindings_matching(doc, Some(&ids), |f| f.starts_with(crate::components::PROP_BINDING)); + let switched: Vec<(usize, NodeId)> = before + .iter() + .filter(|(i, c)| matches!(doc.node(*i).map(|n| &n.kind), Some(NodeKind::Instance { component, .. }) if component != c)) + .map(|(i, _)| (doc.ancestors(*i).len(), *i)) + .collect(); + if switched.is_empty() { + break; + } + // Outer instances first. What a switching instance's layers inherit from the mains around + // it becomes their own first, so the rebuild carries it onto the new variant (rebuilding + // the outer instance instead would put the main's variant back: the switch is no override). + let mut switched = switched; + switched.sort_unstable(); + let m = crate::measure::TextMeasure; + for (_, id) in switched { + if doc.contains(id) { + if let Some((_, old)) = before.iter().find(|(i, _)| *i == id) { + crate::components::keep_inherited_overrides(doc, id, *old); + } + crate::components::sync_instance(doc, id); + figcraft_layout::layout_up(doc, id, &m); + } + } + } + doc.take_dirty(); + doc.mark_dirty(pending); +} + fn apply_bindings_matching(doc: &mut Document, only: Option<&std::collections::BTreeSet>, include: impl Fn(&str) -> bool) { use super::lists::{BoundList, list_binding}; if doc.variables.variables.is_empty() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c9ef71f6a..425eac87a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -649,6 +649,10 @@ mod variables_import_shapes_tests; #[cfg(test)] mod variables_io_tests; #[cfg(test)] +mod variant_binding_import_tests; +#[cfg(test)] +mod variant_mode_switch_tests; +#[cfg(test)] mod variant_shared_props_tests; #[cfg(test)] mod variants_discovery_tests; diff --git a/crates/engine/src/variant_binding_import_tests.rs b/crates/engine/src/variant_binding_import_tests.rs new file mode 100644 index 000000000..fd2884955 --- /dev/null +++ b/crates/engine/src/variant_binding_import_tests.rs @@ -0,0 +1,183 @@ +//! A variant property bound to a string variable (REST `boundVariables.componentProperties`, the +//! form a design kit's Light/Dark `Mode` takes) picks the variant the variable names in the +//! instance's mode as soon as the file opens: an instance in a frame set to Dark shows the Dark +//! variant, one in a Light frame the Light one. + +use base64::Engine as _; +use serde_json::{Value, json}; + +use crate::Session; +use figcraft_doc::{NodeId, NodeKind}; + +fn at(x: f64, y: f64) -> Value { + json!([[1.0, 0.0, x], [0.0, 1.0, y]]) +} + +fn solid(v: f64) -> Value { + json!({"type": "SOLID", "color": {"r": v, "g": v, "b": v, "a": 1.0}}) +} + +/// The local variables: a `Scheme` collection with Light and Dark modes and a string variable +/// `Mode` that holds each mode's name. +fn variables() -> Value { + json!({"meta": { + "variableCollections": {"VC:1": {"id": "VC:1", "name": "Scheme", "modes": [{"modeId": "1:0", "name": "Light"}, {"modeId": "1:1", "name": "Dark"}], + "defaultModeId": "1:0", "variableIds": ["VariableID:1"]}}, + "variables": {"VariableID:1": {"id": "VariableID:1", "name": "Mode", "variableCollectionId": "VC:1", "resolvedType": "STRING", + "valuesByMode": {"1:0": "Light", "1:1": "Dark"}}} + }}) +} + +/// An instance of the Light variant called `name` at `x`, its `Mode` bound to the variable. +fn instance(id: &str, name: &str) -> Value { + json!({"id": id, "name": name, "type": "INSTANCE", "componentId": "1:2", "relativeTransform": at(10.0, 10.0), "size": {"x": 40, "y": 20}, + "componentProperties": {"Mode": {"type": "VARIANT", "value": "Light"}}, + "boundVariables": {"componentProperties": {"Mode": {"type": "VARIABLE_ALIAS", "id": "VariableID:1"}}}, + "fills": [solid(1.0)]}) +} + +fn frame(id: &str, name: &str, x: f64, mode: &str, child: Value) -> Value { + json!({"id": id, "name": name, "type": "FRAME", "relativeTransform": at(x, 200.0), "size": {"x": 60, "y": 40}, + "explicitVariableModes": {"VC:1": mode}, "children": [child]}) +} + +fn file() -> Value { + json!({ + "name": "Modes", "schemaVersion": 0, + "document": {"id": "0:0", "type": "DOCUMENT", "children": [{"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ + {"id": "1:1", "name": "Chip", "type": "COMPONENT_SET", "relativeTransform": at(0.0, 0.0), "size": {"x": 120, "y": 40}, + "componentPropertyDefinitions": {"Mode": {"type": "VARIANT", "defaultValue": "Light", "variantOptions": ["Light", "Dark"]}}, + "children": [ + {"id": "1:2", "name": "Mode=Light", "type": "COMPONENT", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, "fills": [solid(1.0)]}, + {"id": "1:3", "name": "Mode=Dark", "type": "COMPONENT", "relativeTransform": at(60.0, 0.0), "size": {"x": 40, "y": 20}, "fills": [solid(0.0)]} + ]}, + frame("2:1", "Light screen", 0.0, "1:0", instance("3:1", "In light")), + frame("2:2", "Dark screen", 100.0, "1:1", instance("3:2", "In dark")) + ]}]}, + "components": {"1:2": {"key": "k2", "name": "Mode=Light", "componentSetId": "1:1"}, "1:3": {"key": "k3", "name": "Mode=Dark", "componentSetId": "1:1"}}, + "componentSets": {"1:1": {"key": "s1", "name": "Chip"}}, + "styles": {} + }) +} + +/// A rectangle called `name` filled `fill` (grey level). +fn rect(id: &str, name: &str, fill: f64) -> Value { + json!({"id": id, "name": name, "type": "RECTANGLE", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, "fills": [solid(fill)]}) +} + +/// A kit: a Light/Dark `Chip` set whose variants hold a `Base` (light or dark grey), a `Tint` +/// (white or black) and a `Label` text reading property `Label#9:9`, which the set lists under +/// another id (as an imported library's can); a `Button` main holding a Chip whose `Tint` it +/// makes red (an override of the main's), the Chip's `Mode` bound to the variable; and a Button +/// instance in a Dark frame that sets the label to "Stop" (`expanded`: the file lists the +/// instance's layers, as a file read through the API does). +fn kit_file(expanded: bool) -> Value { + let label = |id: &str| { + json!({"id": id, "name": "Label", "type": "TEXT", "relativeTransform": at(0.0, 0.0), "size": {"x": 30, "y": 16}, + "characters": "Label", "style": {"fontSize": 12}, "componentPropertyReferences": {"characters": "Label#9:9"}}) + }; + let variant = |id: &str, mode: &str, base: f64, tint: f64, ids: [&str; 3]| { + json!({"id": id, "name": format!("Mode={mode}"), "type": "COMPONENT", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, + "children": [rect(ids[0], "Base", base), rect(ids[1], "Tint", tint), label(ids[2])]}) + }; + let chip = |id: &str, tint: f64, inner: [&str; 3], label_text: &str| { + let mut t = label(inner[2]); + t["characters"] = json!(label_text); + json!({"id": id, "name": "Chip", "type": "INSTANCE", "componentId": "1:2", "relativeTransform": at(0.0, 0.0), "size": {"x": 40, "y": 20}, + "componentProperties": {"Mode": {"type": "VARIANT", "value": "Light"}, "Label#9:9": {"type": "TEXT", "value": label_text}}, + "boundVariables": {"componentProperties": {"Mode": {"type": "VARIABLE_ALIAS", "id": "VariableID:1"}}}, + "children": [rect(inner[0], "Base", 0.8), rect(inner[1], "Tint", tint), t]}) + }; + let red = json!([{"type": "SOLID", "color": {"r": 1.0, "g": 0.0, "b": 0.0, "a": 1.0}}]); + let mut main_chip = chip("4:2", 1.0, ["I4:2;1:4", "I4:2;1:5", "I4:2;1:6"], "Label"); + main_chip["children"][1]["fills"] = red.clone(); + let mut used_chip = chip("I5:1;4:2", 1.0, ["I5:1;4:2;1:4", "I5:1;4:2;1:5", "I5:1;4:2;1:6"], "Stop"); + used_chip["children"][1]["fills"] = red; + json!({ + "name": "Kit", "schemaVersion": 0, + "document": {"id": "0:0", "type": "DOCUMENT", "children": [{"id": "0:1", "name": "Page", "type": "CANVAS", "children": [ + {"id": "1:1", "name": "Chip", "type": "COMPONENT_SET", "relativeTransform": at(0.0, 0.0), "size": {"x": 120, "y": 40}, + "componentPropertyDefinitions": {"Mode": {"type": "VARIANT", "defaultValue": "Light", "variantOptions": ["Light", "Dark"]}, + "Label#1:5": {"type": "TEXT", "defaultValue": "Label"}}, + "children": [variant("1:2", "Light", 0.8, 1.0, ["1:4", "1:5", "1:6"]), variant("1:3", "Dark", 0.2, 0.0, ["1:7", "1:8", "1:9"])]}, + {"id": "4:1", "name": "Button", "type": "COMPONENT", "relativeTransform": at(200.0, 0.0), "size": {"x": 40, "y": 20}, "children": [main_chip]}, + {"id": "2:2", "name": "Dark screen", "type": "FRAME", "relativeTransform": at(0.0, 200.0), "size": {"x": 60, "y": 40}, + "explicitVariableModes": {"VC:1": "1:1"}, + "children": [{"id": "5:1", "name": "Stop", "type": "INSTANCE", "componentId": "4:1", "relativeTransform": at(10.0, 10.0), + "size": {"x": 40, "y": 20}, "children": if expanded { json!([used_chip]) } else { json!([]) }}]} + ]}]}, + "components": {"1:2": {"key": "k2", "name": "Mode=Light", "componentSetId": "1:1"}, "1:3": {"key": "k3", "name": "Mode=Dark", "componentSetId": "1:1"}, + "4:1": {"key": "k4", "name": "Button"}}, + "componentSets": {"1:1": {"key": "s1", "name": "Chip"}}, + "styles": {} + }) +} + +/// The name of the variant the instance called `name` shows. +fn variant_of(s: &Session, name: &str) -> String { + let doc = s.doc().unwrap(); + let n = doc.nodes().find(|n| n.name == name).unwrap(); + let NodeKind::Instance { component, .. } = &n.kind else { panic!("{name} is not an instance") }; + doc.node(*component).unwrap().name.clone() +} + +#[test] +fn a_variant_bound_to_a_mode_variable_follows_the_frames_mode_on_open() { + let data = base64::engine::general_purpose::STANDARD.encode(file().to_string()); + let mut s = Session::new(); + let r = s.execute("file.open", &json!({"data": data, "name": "modes.json", "variables": variables()})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{r}"); + assert_eq!(variant_of(&s, "In light"), "Mode=Light"); + assert_eq!(variant_of(&s, "In dark"), "Mode=Dark"); + // The binding stays, so a later change of the frame's mode switches the variant again. + let doc = s.doc().unwrap(); + let dark = doc.nodes().find(|n| n.name == "In dark").unwrap(); + assert!(dark.bound.contains_key("componentProperties/Mode"), "{:?}", dark.bound); +} + +/// The fill (grey level, red as 1.0 + 10) of the layer called `name` inside the layer called `inside`. +fn fill_in(s: &Session, inside: &str, name: &str) -> f32 { + let doc = s.doc().unwrap(); + let outer = + doc.nodes().find(|n| n.name == inside && doc.ancestors(n.id).iter().any(|a| doc.node(*a).is_some_and(|p| p.name == "Dark screen"))).unwrap(); + let id = doc.subtree(outer.id).into_iter().find(|i| doc.node(*i).is_some_and(|n| n.name == name)).unwrap(); + let c = doc.node(id).unwrap().fills[0].solid_color().unwrap(); + if c.r > 0.9 && c.g < 0.1 { 11.0 } else { c.r } +} + +fn open_kit(expanded: bool) -> Session { + let data = base64::engine::general_purpose::STANDARD.encode(kit_file(expanded).to_string()); + let mut s = Session::new(); + s.execute("file.open", &json!({"data": data, "name": "kit.json", "variables": variables()})).unwrap(); + s +} + +/// The Chip instance inside the Dark frame. +fn dark_chip(s: &Session) -> NodeId { + let doc = s.doc().unwrap(); + let in_dark = |n: &figcraft_doc::Node| doc.ancestors(n.id).iter().any(|a| doc.node(*a).is_some_and(|p| p.name == "Dark screen")); + doc.nodes().find(|n| n.name == "Chip" && matches!(n.kind, NodeKind::Instance { .. }) && in_dark(n)).unwrap().id +} + +#[test] +fn a_nested_instance_switching_variant_keeps_its_enclosing_mains_overrides() { + { + let expanded = true; + let s = open_kit(expanded); + let doc = s.doc().unwrap(); + let NodeKind::Instance { component, .. } = &doc.node(dark_chip(&s)).unwrap().kind else { panic!("not an instance") }; + assert_eq!(doc.node(*component).unwrap().name, "Mode=Dark", "expanded: {expanded}"); + // The Dark variant's own base, the enclosing Button main's red tint over it. + assert!((fill_in(&s, "Stop", "Base") - 0.2).abs() < 0.01, "expanded: {expanded}: {}", fill_in(&s, "Stop", "Base")); + assert_eq!(fill_in(&s, "Stop", "Tint"), 11.0, "expanded: {expanded}: the Button main's red tint stays"); + } +} + +#[test] +fn a_text_reads_the_property_the_instance_sets_though_the_set_lists_it_under_another_id() { + let s = open_kit(true); + let doc = s.doc().unwrap(); + let label = doc.subtree(dark_chip(&s)).into_iter().filter_map(|i| doc.node(i)).find(|n| n.name == "Label").unwrap(); + let NodeKind::Text(t) = &label.kind else { panic!("not text") }; + assert_eq!(t.characters, "Stop"); +} diff --git a/crates/engine/src/variant_mode_switch_tests.rs b/crates/engine/src/variant_mode_switch_tests.rs new file mode 100644 index 000000000..f2d3163d7 --- /dev/null +++ b/crates/engine/src/variant_mode_switch_tests.rs @@ -0,0 +1,108 @@ +//! A nested instance whose variant property is bound to a string variable switches variant when +//! the mode around it changes, and keeps what the main around it overrides: a Button main makes +//! its Chip's tint red, and a Button instance in a frame set to Dark shows the Dark Chip with that +//! red tint (the reference tool applies an enclosing main's overrides over whichever variant). + +use serde_json::{Value, json}; + +use crate::Session; +use figcraft_doc::{NodeId, NodeKind}; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + match s.execute(cmd, &p) { + Ok(v) => v, + Err(e) => panic!("{cmd}: {e}"), + } +} + +fn id_of(v: &Value) -> u64 { + v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}")) +} + +/// A `name` frame holding a `Tint` rectangle filled `fill`; returns (frame, tint). +fn variant(s: &mut Session, name: &str, x: f64, fill: &str) -> (u64, u64) { + let f = id_of(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 40, "height": 20, "name": name}))); + let t = + id_of(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20, "parent": f, "name": "Tint", "props": {"fill": fill}}))); + (f, t) +} + +fn fill_hex(s: &Session, id: NodeId) -> String { + s.doc().unwrap().node(id).unwrap().fills[0].solid_color().unwrap().to_hex() +} + +/// The scene: Light and Dark Chip variants (a white or black `Tint`), a Button main holding a +/// Chip whose tint it makes red and whose Mode it binds to the variable, and a Button instance in +/// a `Screen` frame. Returns the session, the screen and the Button instance. +fn scene() -> (Session, u64, u64) { + let mut s = Session::new(); + ex(&mut s, "file.new", json!({})); + ex(&mut s, "variable.createCollection", json!({"name": "Scheme", "modes": ["Light", "Dark"]})); + ex(&mut s, "variable.create", json!({"collection": "Scheme", "name": "Mode", "type": "string", "values": {"Light": "Light", "Dark": "Dark"}})); + let (light, _) = variant(&mut s, "Mode=Light", 0.0, "#FFFFFF"); + let (dark, _) = variant(&mut s, "Mode=Dark", 60.0, "#000000"); + for f in [light, dark] { + ex(&mut s, "component.create", json!({"ids": [f]})); + } + let comps: Vec = [light, dark] + .iter() + .map(|f| { + let doc = s.doc().unwrap(); + let n = doc.node(NodeId(*f)).unwrap(); + if matches!(n.kind, NodeKind::Component { .. }) { *f } else { n.children[0].0 } + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": comps})); + // A Button main holding a Chip (Light) whose tint it makes red, its Mode bound to the variable. + let button = id_of(&ex(&mut s, "frame.create", json!({"x": 200, "y": 0, "width": 40, "height": 20, "name": "Button"}))); + let chip = id_of(&ex(&mut s, "instance.create", json!({"component": comps[0], "x": 0, "y": 0, "parent": button}))); + ex(&mut s, "component.create", json!({"ids": [button]})); + let tint_in_main = { + let doc = s.doc().unwrap(); + doc.subtree(NodeId(chip)).into_iter().find(|i| doc.node(*i).is_some_and(|n| n.name == "Tint")).unwrap() + }; + ex(&mut s, "node.set", json!({"ids": [tint_in_main.0], "props": {"fill": "#FF0000"}})); + ex(&mut s, "variable.bind", json!({"ids": [chip], "field": "componentProperties/Mode", "variable": "Mode"})); + // A screen with a Button, switched to Dark. + let screen = id_of(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 60, "name": "Screen"}))); + let main_button = { + let doc = s.doc().unwrap(); + doc.nodes().find(|n| n.name == "Button" && matches!(n.kind, NodeKind::Component { .. })).unwrap().id + }; + let used = id_of(&ex(&mut s, "instance.create", json!({"component": main_button.0, "x": 10, "y": 10, "parent": screen}))); + (s, screen, used) +} + +/// The Button instance's Chip shows the Dark variant with the Button main's red tint. +fn assert_dark_with_red_tint(s: &Session, used: u64) { + let doc = s.doc().unwrap(); + let used_chip = doc + .subtree(NodeId(used)) + .into_iter() + .find(|i| doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Instance { .. }) && n.id.0 != used)) + .unwrap(); + let NodeKind::Instance { component, .. } = &doc.node(used_chip).unwrap().kind else { panic!("not an instance") }; + assert_eq!(doc.node(*component).unwrap().name, "Mode=Dark"); + let tint = doc.subtree(used_chip).into_iter().find(|i| doc.node(*i).is_some_and(|n| n.name == "Tint")).unwrap(); + assert_eq!(fill_hex(s, tint), "FF0000", "the Button main's red tint stays on the Dark variant"); +} + +#[test] +fn a_nested_variant_bound_to_a_mode_keeps_its_mains_overrides_when_the_mode_switches() { + let (mut s, screen, used) = scene(); + ex(&mut s, "variable.setMode", json!({"ids": [screen], "collection": "Scheme", "mode": "Dark"})); + assert_dark_with_red_tint(&s, used); +} + +/// An opened file settles the same way: its layers inherit the main's overrides (as a `.fig` +/// file's instances do) when the variant switches on load. +#[test] +fn an_opened_files_nested_variant_keeps_its_mains_overrides() { + let (mut s, screen, used) = scene(); + let doc = s.doc_mut().unwrap(); + let coll = doc.variables.collections.iter().find(|c| c.name == "Scheme").unwrap().clone(); + let dark = coll.modes.iter().find(|m| m.name == "Dark").unwrap().id.clone(); + doc.get_mut(NodeId(screen)).unwrap().var_modes.insert(coll.id.clone(), dark); + crate::cmd::styles::apply_prop_bindings_on_load(doc); + assert_dark_with_red_tint(&s, used); +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 0b9426ef6..020da3fbf 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -1314,7 +1314,9 @@ impl<'a> Ctx<'a> { let re = |k: &String| rename.get(k).cloned().unwrap_or_else(|| k.clone()); for id in ids { let Some(n) = self.doc.node(id) else { continue }; + let bound_prop = |k: &String| k.strip_prefix(variables::PROP_BINDING).is_some_and(|p| rename.contains_key(p)); let touches = n.prop_refs.values().any(|v| rename.contains_key(v)) + || n.bound.keys().any(bound_prop) || match &n.kind { NodeKind::Component { props, .. } => props.keys().any(|k| rename.contains_key(k)), NodeKind::Instance { props, .. } => props.keys().any(|k| rename.contains_key(k)), @@ -1327,6 +1329,14 @@ impl<'a> Ctx<'a> { for v in n.prop_refs.values_mut() { *v = re(v); } + // Component property bindings follow their property's name. + n.bound = std::mem::take(&mut n.bound) + .into_iter() + .map(|(k, v)| match k.strip_prefix(variables::PROP_BINDING) { + Some(p) => (format!("{}{}", variables::PROP_BINDING, re(&p.to_string())), v), + None => (k, v), + }) + .collect(); match &mut n.kind { NodeKind::Component { props, .. } => *props = std::mem::take(props).into_iter().map(|(k, d)| (re(&k), d)).collect(), NodeKind::Instance { props, .. } => *props = std::mem::take(props).into_iter().map(|(k, d)| (re(&k), d)).collect(), diff --git a/crates/format/src/rest/variables.rs b/crates/format/src/rest/variables.rs index 75f4bbddb..212377b31 100644 --- a/crates/format/src/rest/variables.rs +++ b/crates/format/src/rest/variables.rs @@ -386,8 +386,11 @@ impl Ctx<'_> { self.warn("variable bindings to properties the layer doesn't have were skipped"); continue; } + // A component property takes a string variable (variant and text) or a boolean one; + // the engine checks which when it applies the binding. + let prop = field.starts_with(PROP_BINDING); match self.var_kinds.get(var) { - Some(kind) if *kind == field_type(&field) => { + Some(kind) if *kind == field_type(&field) || (prop && matches!(kind, VariableType::String | VariableType::Boolean)) => { n.bound.insert(field, var.to_string()); } Some(_) => self.warn("variable bindings whose variable type doesn't fit the property were skipped"), @@ -401,6 +404,9 @@ impl Ctx<'_> { } } +/// The binding key prefix of an instance's component property (the engine's `PROP_BINDING`). +pub(crate) const PROP_BINDING: &str = "componentProperties/"; + /// Map one `boundVariables` entry onto our field names; false when the property isn't bindable. fn node_binding<'v>(k: &str, v: &'v Value, n: &Node, out: &mut Vec<(String, &'v str)>) -> bool { let mut push = |f: &str, a: Option<&'v str>| { @@ -414,6 +420,15 @@ fn node_binding<'v>(k: &str, v: &'v Value, n: &Node, out: &mut Vec<(String, &'v push("height", v.get("y").and_then(alias)); } "itemSpacing" => push("gap", alias(v)), + // An instance's component properties, variant ones included (`Mode` bound to a string + // variable picks the variant it names): `componentProperties/`, the engine's + // `PROP_BINDING` key that `variable.bind` writes. + "componentProperties" => { + let Some(props) = v.as_object() else { return false }; + for (name, a) in props.iter().take(256) { + push(&format!("{PROP_BINDING}{name}"), alias(a)); + } + } "counterAxisSpacing" => push("crossGap", alias(v)), "characters" | "visible" | "opacity" | "strokeWeight" | "strokeTopWeight" | "strokeRightWeight" | "strokeBottomWeight" | "strokeLeftWeight" | "paddingLeft" | "paddingRight" | "paddingTop" | "paddingBottom" | "topLeftRadius" | "topRightRadius" diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 900ef0525..89e45fa56 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-20 · **Change:** minor (`.fig` and REST import: a variable font's optical size follows the text size, as in Figma, so SF Pro text is no longer set with its display cut at text sizes; 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); `.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-20 · **Change:** minor (REST import reads instances' component property bindings, variant ones included, and an opened file shows the variant a bound `Mode`-style variable names in each instance's mode; `.fig` and REST import: a variable font's optical size follows the text size, as in Figma, so SF Pro text is no longer set with its display cut at text sizes; 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); `.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 @@ -17,12 +17,12 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.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). Since 2026-11-20, a variable font's optical size follows the text size (within the axis), also for a named style, as the glyph advances a `.fig` file saves with its text show for SF Pro (12–17 px set with the 17 cut, 18–24 px with their own size's, 30 px with the 28 cut); the text carries the size as its `opsz` value. A font without that axis is unaffected: Figma's own Inter has none, so its advances stay the same at every size, while a locally installed Inter 4 has one and can set large text narrower than Figma. Optical sizes a `.fig` text sets itself (`fontVariations`) are not read yet. 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 | +| `.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). Since 2026-11-20, a variable font's optical size follows the text size (within the axis), also for a named style, as the glyph advances a `.fig` file saves with its text show for SF Pro (12–17 px set with the 17 cut, 18–24 px with their own size's, 30 px with the 28 cut); the text carries the size as its `opsz` value. A font without that axis is unaffected: Figma's own Inter has none, so its advances stay the same at every size, while a locally installed Inter 4 has one and can set large text narrower than Figma. Optical sizes a `.fig` text sets itself (`fontVariations`) are not read yet. A variant property bound to a variable (a kit's Light/Dark `Mode`, a `RESOLVE_VARIANT` expression in the file) comes across with craft-libs' `craft-fig` from local commit `edcc9d6d3` on (not yet in the pinned revision): it then switches each instance to the variant the variable names in its mode, as the REST import does, and the whole variant set is kept. 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 | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, 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` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints, 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 (an instance's component properties too, `boundVariables.componentProperties`: a variant property bound to a string variable shows, once the file opens, the variant the variable names in the instance's mode, keeping what the instance and the mains around it override, since 2026-11-20), 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) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | @@ -195,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | M6: instances' component property bindings import from REST JSON (`boundVariables.componentProperties`, variant properties included), and an opened REST or `.fig` file settles them: an instance whose variant property is bound to a string variable shows the variant the variable names in its mode (a kit's Dark variants in frames set to Dark), keeping its own overrides and those the mains around it make (a destructive button's red tint), and a text reads a property its instance sets even when the variant set lists it under another id. `.fig` needs craft-libs' `craft-fig` from local commit `edcc9d6d3` (maps the file's `RESOLVE_VARIANT` binding and keeps the whole variant set). Checked against renders of a real-world iOS kit file: its dark screens drew the light variants (dark alerts 28% and 20% of pixels differing, the dark keyboard 38%); now 2%, 1.4% and 1.7%; frames under 1% difference 108 → 126 of 162. Tests: `crates/engine/src/variant_binding_import_tests.rs`, `variant_mode_switch_tests.rs`. Numbers unchanged | | 2026-11-20 | minor | M6: `.fig` and REST import set a variable font's optical size to the text size (within the axis), also for a named style, as the `.sketch` import already did: FigCraft keeps a named instance's optical size (SF Pro's is 28, its display cut), so imported SF Pro text at text sizes was set about 14% narrower than in Figma. Rule from the glyph advances `.fig` files saved by Figma carry (`derivedTextData.glyphs`): in a real-world file SF Pro Regular, Medium and Semibold at 12–17 px match the 17 cut and at 18–24 px their own size's, and a synthetic file saved from Figma's web app gives SF Pro Regular the 17 cut at 11–17 px, the 20 cut at 20 px and the 28 cut at 28–64 px; Figma's Inter (no optical size axis) keeps the same advances from 11 to 64 px. Checked against renders from Figma's REST images endpoint: on 24 screens of that file the share of differing pixels fell on every screen (median 3.2% → 1.7%). Test: `crates/engine/src/fig_optical_size_tests.rs`. Numbers unchanged | | 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. | | 2026-11-19 | patch | M6, #2468 follow-up: SVG import checks its input with craft-svg (`tree::parse`, `tree::image_resolver`), so FigCraft's own byte scanners (`too_wide`, `too_deep`, `nesting`) and `import/budget.rs` were dead code, and `main` failed `cargo fmt` and clippy. They are removed; the budget and hostile-input tests now run against craft-svg's `tree::Limits` (documents nest at most 256 levels deep, references followed, where FigCraft's scanner allowed 512). No behaviour change beyond #2468. | From 64d81e57e0f420e8712d636172dca159a186bd25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 23:27:54 +0100 Subject: [PATCH 04/14] M3: a line height in pixels keeps its fraction The reference tool's saved layouts (derivedTextData) keep a pixel line height's pitch exactly (22.5, 18.4) and round the self-sizing box's total up to a whole pixel; only Auto and percentage line heights come out whole. FigCraft rounded every line height, so a 22.5 px paragraph drifted half a pixel per line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/text/src/layout.rs | 22 +++++++++++++++------- crates/text/src/metrics_tests.rs | 25 ++++++++++++++++++++++--- docs/target-app-parity.md | 3 ++- 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index ebe35c722..fc84c12cc 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -221,10 +221,18 @@ fn natural_ratio(face: &Face) -> f64 { ((face.ascent + face.descent + face.line_gap.max(0.0)) / face.upem).max(0.5) } -/// A line's height: whole pixels (halves round up), whatever unit it was given in. Heights under a -/// pixel stay as they are, so tiny text keeps its lines apart. -fn whole_px(line_height: f64) -> f64 { - if line_height >= 1.0 { (line_height + 0.5).floor() } else { line_height } +/// A line's height: one given in pixels as it is (22.5 px lines stay 22.5 apart, as the reference +/// tool lays them out), one worked out from the font (Auto or a percentage) in whole pixels, halves +/// rounding up. Heights under a pixel stay as they are, so tiny text keeps its lines apart. +fn line_px(line_height: LineHeight, size: f64, natural: f64) -> f64 { + let h = line_height.resolve(size, natural); + if matches!(line_height, LineHeight::Pixels(_)) || h < 1.0 { h } else { (h + 0.5).floor() } +} + +/// A text box's height: the lines' height rounded up to a whole pixel (lines a fraction of a pixel +/// tall add up to that), as the reference tool sizes it. Under a pixel it stays as it is. +fn box_px(h: f64) -> f64 { + if h >= 1.0 { (h - 1e-6).ceil() } else { h } } /// Advances sit on a grid of this many steps per em, then scale with the font size. @@ -1105,7 +1113,7 @@ fn finish_layout(out: &mut TextLayout, finish: LayoutFinish<'_>) { g.y -= shift; } } - let bottom = |l: &Line| if trim { l.baseline } else { l.top + l.height }; + let bottom = |l: &Line| if trim { l.baseline } else { box_px(l.top + l.height) }; out.height = out.lines.last().map_or(flow_height, bottom).max(0.0); truncate_layout(out, &finish); @@ -1270,9 +1278,9 @@ pub fn layout(text: &TextData, box_width: Option, box_height: Option) match faces.get(st_idx).and_then(Option::as_ref).or(default_face.as_ref()) { Some(f) => { let k = size / f.upem; - [f.ascent * k, f.descent * k, whole_px(st.line_height.resolve(size, natural_ratio(f))), f.cap_height * k] + [f.ascent * k, f.descent * k, line_px(st.line_height, size, natural_ratio(f)), f.cap_height * k] } - None => [size * 0.8, size * 0.2, whole_px(st.line_height.resolve(size, 1.2)), size * 0.7], + None => [size * 0.8, size * 0.2, line_px(st.line_height, size, 1.2), size * 0.7], } }; let mut first_cap = 0.0; diff --git a/crates/text/src/metrics_tests.rs b/crates/text/src/metrics_tests.rs index f3fe4e342..213b122bf 100644 --- a/crates/text/src/metrics_tests.rs +++ b/crates/text/src/metrics_tests.rs @@ -1,5 +1,5 @@ -//! Text metric rules measured against documents re-saved by other software: line heights are whole -//! pixels, advances sit on a grid of 1024 steps per em, and letter spacing goes between glyphs +//! Text metric rules measured against documents re-saved by other software: line heights worked +//! out from the font are whole pixels (ones given in pixels keep their fraction), advances sit on a grid of 1024 steps per em, and letter spacing goes between glyphs //! only. Each case derives its numbers from the face in use (skipped on a machine without fonts); //! the last test pins sizes that were measured, for the one font build they were measured with. @@ -32,7 +32,6 @@ fn line_heights_are_whole_pixels() { (22.0, LineHeight::Percent(125.0), 28.0, "27.5: halves round up"), (48.0, LineHeight::Percent(110.0), 53.0, "52.8 rounds up"), (14.0, LineHeight::Pixels(20.0), 20.0, "whole pixels stay"), - (14.0, LineHeight::Pixels(20.4), 20.0, "pixel values round too (not measured: pins today's behaviour)"), (14.0, LineHeight::Auto, (own(14.0) + 0.5).floor(), "Auto: the font's own line height, rounded"), (20.0, LineHeight::Auto, (own(20.0) + 0.5).floor(), "Auto at 20 px"), (24.0, LineHeight::Auto, (own(24.0) + 0.5).floor(), "Auto at 24 px"), @@ -54,6 +53,26 @@ fn line_heights_are_whole_pixels() { } } +/// A line height given in pixels keeps its fraction: lines 22.5 px apart stay 22.5 apart, the +/// glyphs centred in each, and the box rounds the lines' total up to a whole pixel (three lines of +/// 22.5 are 68 tall, three of 18.4 are 56), as the reference tool lays them out. +#[test] +fn pixel_line_heights_keep_their_fraction() { + let Some(f) = face() else { return }; + for (size, px, lines, want_box) in [(17.0, 22.5, 3, 68.0), (17.0, 22.5, 4, 90.0), (16.0, 18.4, 3, 56.0), (14.0, 20.4, 2, 41.0)] { + let mut t = text(&vec!["Ag"; lines].join("\n"), &f, size); + t.style.line_height = LineHeight::Pixels(px); + let l = layout(&t, None, None); + assert_eq!(l.lines.len(), lines); + assert_eq!(l.height, want_box, "{lines} lines of {px} px"); + let (asc, desc) = (f.ascent * size / f.upem, f.descent * size / f.upem); + for (i, line) in l.lines.iter().enumerate() { + let baseline = i as f64 * px + (px - asc - desc) / 2.0 + asc; + assert!((line.height - px).abs() < 1e-9 && (line.baseline - baseline).abs() < 1e-9, "{px} px: line {i} baseline {}", line.baseline); + } + } +} + #[test] fn advances_sit_on_a_grid_of_1024_per_em() { let Some(f) = face() else { return }; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a583ee32b..d53254864 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Text line heights given in pixels keep their fraction (M3, text metrics): lines 22.5 px apart stay 22.5 apart, the glyphs centred in each, and a self-sizing box rounds the lines' total up to a whole pixel (three lines of 22.5 make a 68 px box, three of 18.4 a 56 px one), as the reference tool's own saved layouts show (`derivedTextData` of 1 486 text layers in one `.fig`, 470 of them with pixel line heights from 15 to 38.5: those keep their pitch; Auto and percentages round, as before). They were rounded to whole pixels (22.5 → 23), so every paragraph drifted half a pixel a line. Found on an iOS kit: four-line paragraphs ended 1.5 px low; differing pixels on those screens 3% → 1.7%. Test: `metrics_tests::pixel_line_heights_keep_their_fraction` (the pinned "pixel values round too, not measured" case is replaced). Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Paint blend modes checked against renders of a synthetic file by the reference tool (9 scenes; differing pixels before → after: up to 39% → under 0.2% each) and fixed on the canvas and in PNG exports: a layer in a blend mode of its own (Normal included) blends its fills with each other only, then lays them over the canvas as one, with or without effects (they blended with the backdrop until a layer had an effect, then not); a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it was drawn as an isolated layer); drop shadows blend by their modes among themselves, then lie under the layer as one (two linear-burn shadows darkened the backdrop); inner shadows blend with the fills under them by their own mode (they were drawn normally); plus lighter adds the premultiplied colours and combines the alphas as source-over does (tiny-skia's sum made a translucent stack opaque). Found on iOS kit buttons and alerts imported from a `.fig`: their fill stacks (plus lighter, luminosity) drew mid grey instead of near white. Tests: `crates/render/src/fill_blend_tests.rs`. SVG and PDF exports unchanged. Percentages and hours unchanged at this rounding | | 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | | 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 604174424727994b93498a941b0b239c8273c98a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 23:29:40 +0100 Subject: [PATCH 05/14] M3: exports frame a shadow to its blur radius and skip layers that draw nothing The reference tool's exports (and absoluteRenderBounds) take a drop shadow as far as its blur radius, and leave out a layer without any visible paint, effect or children. FigCraft framed shadows at three standard deviations (1.5 x radius) and counted empty placeholders, so a glass button exported 92 px instead of 76 and an illustration with an empty 1448 px box exported at that size. Canvas culling keeps the full reach; only Document::world_export_bounds frames this way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/doc/src/lib.rs | 49 +++++++++++++++------ crates/doc/src/node.rs | 38 ++++++++++++++-- crates/engine/src/export_behaviour_tests.rs | 7 +-- crates/render/src/export_framing_tests.rs | 41 +++++++++++++++++ crates/render/src/lib.rs | 6 ++- docs/target-app-parity.md | 3 +- 6 files changed, 121 insertions(+), 23 deletions(-) create mode 100644 crates/render/src/export_framing_tests.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 170da1a25..91c6eb9c7 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -52,6 +52,13 @@ use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::sync::Arc; +/// A walk for [`Document::world_render_bounds`]: how many more nodes it may visit, and whether it +/// frames an export ([`Document::world_export_bounds`]). +struct Walk { + left: std::cell::Cell, + export: bool, +} + /// Deepest descendant [`Document::world_render_bounds`] follows: as deep as the renderer draws /// (`figcraft_render::MAX_EXPORT_DEPTH`), so a crafted chain can't overflow the stack (#1062). const MAX_RENDER_DEPTH: usize = 256; @@ -776,37 +783,51 @@ impl Document { /// children only within their mask). A group, or an unclipped frame past its box, is what its /// children show grown by its effects, which apply to all of it. pub fn world_render_bounds(&self, id: NodeId) -> Option { - // A tree visits each node once; a child list deserialized with repeats (a graph) is cut off - // after twice the document's node count rather than walked in full. - self.render_bounds_at(id, 0, &std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8))) + self.render_bounds_from(id, false) } - fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell) -> Option { + /// [`Document::world_render_bounds`] as an export frames it: drop shadows reach as far as + /// their blur radius (see [`Node::own_export_bounds`]) and layers inside that draw nothing (no + /// visible paint, effect or children) don't count, as in the reference tool's exports. + pub fn world_export_bounds(&self, id: NodeId) -> Option { + self.render_bounds_from(id, true) + } + + fn render_bounds_from(&self, id: NodeId, export: bool) -> Option { + // A tree visits each node once; a child list deserialized with repeats (a graph) is cut off + // after twice the document's node count rather than walked in full. + let left = std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8)); + self.render_bounds_at(id, 0, &Walk { left, export }) + } + + fn render_bounds_at(&self, id: NodeId, depth: usize, walk: &Walk) -> Option { let n = self.node(id)?; - let own = n.own_paint_bounds(self.world_transform(id)); - let visit = left.get(); - left.set(visit.saturating_sub(1)); + let world = self.world_transform(id); + let own = if walk.export { n.own_export_bounds(world) } else { n.own_paint_bounds(world) }; + let grow = |r: Rect| if walk.export { n.grow_by_export_effects(r) } else { n.grow_by_effects(r) }; + let visit = walk.left.get(); + walk.left.set(visit.saturating_sub(1)); if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH || visit == 0 { return Some(own); } - Some(match (self.children_render_bounds(n, depth + 1, left), &n.kind) { - (Some(kids), NodeKind::Group) => n.grow_by_effects(kids), + Some(match (self.children_render_bounds(n, depth + 1, walk), &n.kind) { + (Some(kids), NodeKind::Group) => grow(kids), // An unclipped frame's effects apply to its children too, past its box included. - (Some(kids), _) => own.union(n.grow_by_effects(kids)), + (Some(kids), _) => own.union(grow(kids)), (None, _) => own, }) } /// What `n`'s visible children show, together: each mask's run within the mask's bounds. - fn children_render_bounds(&self, n: &Node, depth: usize, left: &std::cell::Cell) -> Option { - let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask); + fn children_render_bounds(&self, n: &Node, depth: usize, walk: &Walk) -> Option { + let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask && !(walk.export && c.draws_nothing())); let mut out: Option = None; for run in self.paint_runs(n) { let ids = n.children.get(run).unwrap_or(&[]); let mask = ids.first().copied().filter(|m| self.node(*m).is_some_and(|c| c.is_mask && c.visible)); - let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, left)).reduce(|a, b| a.union(b)); + let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, walk)).reduce(|a, b| a.union(b)); let r = match mask { - Some(m) => r.zip(self.render_bounds_at(m, depth, left)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0), + Some(m) => r.zip(self.render_bounds_at(m, depth, walk)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0), None => r, }; out = match (out, r) { diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index bea172277..cca1136b0 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -784,6 +784,12 @@ impl Node { self.board.as_ref().is_some_and(crate::BoardItem::is_atom) } + /// Whether this layer puts nothing on the canvas: no visible fill, stroke or effect and no + /// children (a placeholder box whose image was taken out, an empty frame). + pub fn draws_nothing(&self) -> bool { + self.children.is_empty() && !self.fills.iter().any(|f| f.visible) && !self.has_visible_stroke() && !self.effects.iter().any(|e| e.visible) + } + /// A section whose contents are hidden: only its name and outline show; its children are /// skipped when rendering and hit testing. pub fn hides_contents(&self) -> bool { @@ -890,9 +896,21 @@ impl Node { /// The page-space area this node paints itself under `world` (its children aside): its box /// grown by its strokes and glyphs, then by its effects (see [`Node::grow_by_effects`]). pub fn own_paint_bounds(&self, world: Affine) -> figcraft_geom::Rect { + self.own_bounds_with(world, SHADOW_BLUR_REACH) + } + + /// [`Node::own_paint_bounds`] as an export frames it: drop shadows count as far as their blur + /// radius (what the reference tool's exports and render bounds take in; the faint tail of the + /// blur past it stays out). + pub fn own_export_bounds(&self, world: Affine) -> figcraft_geom::Rect { + self.own_bounds_with(world, 1.0) + } + + /// [`Node::own_paint_bounds`] with drop shadows' blur reaching `blur` times their radius. + fn own_bounds_with(&self, world: Affine, blur: f64) -> figcraft_geom::Rect { let o = self.outline_reach(); let base = self.local_rect().inflate(o, o); - let grown = self.grow_by_effects(figcraft_geom::transform_rect_bbox(world, base)); + let grown = self.grow_by_effects_with(figcraft_geom::transform_rect_bbox(world, base), blur); // A filled outline's spread grows in local units (see [`Node::outline_spreads`]): a box by // its spread all round, sharp corners' mitres anywhere within a circle of it. let [a, b, c, d, _, _] = world.as_coeffs(); @@ -906,7 +924,7 @@ impl Node { let m = spread * SPREAD_MITER_LIMIT; figcraft_geom::transform_rect_bbox(world, base).inflate(m * a.hypot(c), m * b.hypot(d)) }; - let (g, (dx, dy)) = (layer + s.radius.abs() * 1.5, s.offset); + let (g, (dx, dy)) = (layer + s.radius.abs() * blur, s.offset); if g.is_finite() && dx.is_finite() && dy.is_finite() && outline.is_finite() { r.union(outline.inflate(g, g) + figcraft_geom::kurbo::Vec2::new(dx, dy)) } else { @@ -923,12 +941,22 @@ impl Node { /// Layer blurs and texture grow it by what they reach together, and drop shadows are cast from /// that (see [`Node::layer_effects_reach`]). pub fn grow_by_effects(&self, b: figcraft_geom::Rect) -> figcraft_geom::Rect { + self.grow_by_effects_with(b, SHADOW_BLUR_REACH) + } + + /// [`Node::grow_by_effects`] as an export frames it (see [`Node::own_export_bounds`]). + pub fn grow_by_export_effects(&self, b: figcraft_geom::Rect) -> figcraft_geom::Rect { + self.grow_by_effects_with(b, 1.0) + } + + /// [`Node::grow_by_effects`] with drop shadows' blur reaching `blur` times their radius. + fn grow_by_effects_with(&self, b: figcraft_geom::Rect, blur: f64) -> figcraft_geom::Rect { let miter = self.spread_miter_reach(); let layer = self.layer_effects_reach(); let moved = if layer > 0.0 { b.inflate(layer, layer) } else { b }; self.effects.iter().filter(|e| e.visible).fold(moved, |r, e| match &e.kind { EffectKind::DropShadow(s) => { - let g = s.radius.abs() * 1.5 + s.spread.max(0.0) + miter; + let g = s.radius.abs() * blur + s.spread.max(0.0) + miter; let (dx, dy) = s.offset; if g.is_finite() && dx.is_finite() && dy.is_finite() { r.union(moved.inflate(g, g) + figcraft_geom::kurbo::Vec2::new(dx, dy)) @@ -1020,6 +1048,10 @@ impl Node { /// canvas, and a sum of any number of them (or of their squares) stays finite. const MAX_EFFECT_REACH: f64 = 1e100; +/// How many times its radius a drop shadow's blur reaches past the shape when everything it paints +/// counts: three standard deviations of a blur whose deviation is half the radius. +const SHADOW_BLUR_REACH: f64 = 1.5; + /// An effect's reach made safe to add: finite, in 0..[`MAX_EFFECT_REACH`]. fn effect_reach(r: f64) -> f64 { if r.is_finite() { r.clamp(0.0, MAX_EFFECT_REACH) } else { 0.0 } diff --git a/crates/engine/src/export_behaviour_tests.rs b/crates/engine/src/export_behaviour_tests.rs index 4d6c2a244..f558cb493 100644 --- a/crates/engine/src/export_behaviour_tests.rs +++ b/crates/engine/src/export_behaviour_tests.rs @@ -227,11 +227,12 @@ fn what_an_export_covers() { set(&mut s, &[r], json!({"strokes": ["#000000"], "strokeWeight": w, "strokeAlign": align})); assert_eq!(size(&mut s, r), want, "{why}"); } - // A shadow extends the export towards its offset: blur 4 reaches 6 (1.5 × blur, docs silent on - // the exact reach), moved 10 down, so 6 more on the left and right, 16 more below, none above. + // A shadow extends the export towards its offset: blur 4 reaches 4 (its radius, as the + // reference tool's exports measure), moved 10 down, so 4 more on the left and right, 14 more + // below, none above. let r = rect(&mut s, 400.0, 0.0, 100.0, 100.0, "#FF0000", None); shadow(&mut s, r, (0.0, 10.0), 4.0, 0.0); - assert_eq!(size(&mut s, r), (112, 116), "effects extend the bounds, in the direction the shadow falls"); + assert_eq!(size(&mut s, r), (108, 114), "effects extend the bounds, in the direction the shadow falls"); assert_eq!(pixels(&export(&mut s, json!({"ids": [r]}))).get_pixel(6, 0).0, [255, 0, 0, 255], "the layer's top edge is the image's top edge"); // Include bounding box: the layer's box, whatever it paints outside it. let b = export(&mut s, json!({"ids": [r], "includeBoundingBox": true})); diff --git a/crates/render/src/export_framing_tests.rs b/crates/render/src/export_framing_tests.rs new file mode 100644 index 000000000..6edecf023 --- /dev/null +++ b/crates/render/src/export_framing_tests.rs @@ -0,0 +1,41 @@ +//! How an export frames a layer, as the reference tool's exports do (measured on its renders of the +//! same scenes): a drop shadow counts as far as its blur radius (its faint tail past that stays +//! out), and a layer inside that draws nothing doesn't count. + +use figcraft_color::{BlendMode, Color, Paint}; +use figcraft_doc::{Effect, EffectKind, NodeKind, Shadow}; + +use super::paint_behaviour_tests::page; +use crate::export_bounds; + +fn shadow(radius: f64, offset: (f64, f64)) -> Effect { + let color = Color { a: 0.3, ..Color::BLACK }; + Effect { kind: EffectKind::DropShadow(Shadow { color, offset, radius, blend: BlendMode::Normal, ..Shadow::default() }), visible: true } +} + +#[test] +fn a_shadow_reaches_into_the_export_as_far_as_its_blur_radius() { + let (mut d, p) = page(); + let b = d.create(p, NodeKind::Frame, "Button", 100.0, 100.0, 44.0, 44.0).unwrap(); + let n = d.get_mut(b).unwrap(); + (n.fills, n.effects) = (vec![Paint::solid(Color::WHITE)], vec![shadow(16.0, (0.0, 4.0))]); + let r = export_bounds(&d, b).unwrap(); + // 44 + 2 × 16 square, moved down by the offset: 76 × 76, as the reference tool exports it. + assert_eq!((r.x0, r.y0, r.x1, r.y1), (84.0, 88.0, 160.0, 164.0)); +} + +#[test] +fn a_layer_that_draws_nothing_stays_out_of_the_export() { + let (mut d, p) = page(); + let f = d.create(p, NodeKind::Frame, "Illustration", 0.0, 0.0, 300.0, 225.0).unwrap(); + let n = d.get_mut(f).unwrap(); + (n.fills, n.clip) = (vec![Paint::solid(Color::WHITE)], false); + // A placeholder far larger than the frame, its image taken out (no fills). + let ph = d.create(f, NodeKind::Rectangle, "image 15", -445.0, -438.0, 1448.0, 1086.0).unwrap(); + d.get_mut(ph).unwrap().fills.clear(); + let r = export_bounds(&d, f).unwrap(); + assert_eq!((r.x0, r.y0, r.x1, r.y1), (0.0, 0.0, 300.0, 225.0)); + // Given a fill, it counts. + d.get_mut(ph).unwrap().fills = vec![Paint::solid(Color::BLACK)]; + assert!(export_bounds(&d, f).unwrap().width() > 1000.0); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 000396254..df1a2e04e 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -393,9 +393,9 @@ pub fn raster_bounds(doc: &Document, id: NodeId) -> Option { } /// The page-space rectangle a node exports: a clipping frame's box (plus its own effects), else -/// everything it paints. +/// everything it paints, framed as [`Document::world_export_bounds`] frames it. pub fn export_bounds(doc: &Document, id: NodeId) -> Option { - doc.world_render_bounds(id) + doc.world_export_bounds(id) } /// Rasterise one node at `scale` (export). Transparent background. @@ -643,6 +643,8 @@ mod effect_order_tests; #[cfg(test)] mod effects_behaviour_tests; #[cfg(test)] +mod export_framing_tests; +#[cfg(test)] mod fill_blend_tests; #[cfg(test)] mod gif_tests; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d53254864..2753e7cea 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (an export frames a drop shadow to its blur radius and leaves out layers that draw nothing; a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Export area as the reference tool frames it (M3, export): a drop shadow reaches into a PNG/JPG/SVG/PDF export's area as far as its blur radius (plus spread, toward its offset), as the tool's exports and render bounds take it (a 44 px button with a 16 px shadow exports 76 × 76; it was 92 × 92, three standard deviations), and a layer that draws nothing (no visible fill, stroke, effect or children: a placeholder whose image was taken out) no longer widens its parent's export (a 300 × 225 illustration holding an empty 1 448 × 1 086 box exported at that size). The canvas's culling and redraw areas keep the whole blur. Found on an iOS kit's glass buttons, switches and illustrations: differing pixels 20–42% → under 1% each. Tests: `crates/render/src/export_framing_tests.rs`. Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Text line heights given in pixels keep their fraction (M3, text metrics): lines 22.5 px apart stay 22.5 apart, the glyphs centred in each, and a self-sizing box rounds the lines' total up to a whole pixel (three lines of 22.5 make a 68 px box, three of 18.4 a 56 px one), as the reference tool's own saved layouts show (`derivedTextData` of 1 486 text layers in one `.fig`, 470 of them with pixel line heights from 15 to 38.5: those keep their pitch; Auto and percentages round, as before). They were rounded to whole pixels (22.5 → 23), so every paragraph drifted half a pixel a line. Found on an iOS kit: four-line paragraphs ended 1.5 px low; differing pixels on those screens 3% → 1.7%. Test: `metrics_tests::pixel_line_heights_keep_their_fraction` (the pinned "pixel values round too, not measured" case is replaced). Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Paint blend modes checked against renders of a synthetic file by the reference tool (9 scenes; differing pixels before → after: up to 39% → under 0.2% each) and fixed on the canvas and in PNG exports: a layer in a blend mode of its own (Normal included) blends its fills with each other only, then lays them over the canvas as one, with or without effects (they blended with the backdrop until a layer had an effect, then not); a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it was drawn as an isolated layer); drop shadows blend by their modes among themselves, then lie under the layer as one (two linear-burn shadows darkened the backdrop); inner shadows blend with the fills under them by their own mode (they were drawn normally); plus lighter adds the premultiplied colours and combines the alphas as source-over does (tiny-skia's sum made a translucent stack opaque). Found on iOS kit buttons and alerts imported from a `.fig`: their fill stacks (plus lighter, luminosity) drew mid grey instead of near white. Tests: `crates/render/src/fill_blend_tests.rs`. SVG and PDF exports unchanged. Percentages and hours unchanged at this rounding | | 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | From 69d146243ede1467e17a05eccf6fa8e2bfc3c5c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 23:29:53 +0100 Subject: [PATCH 06/14] M3: images shown smaller average what each pixel covers The reference tool's exports draw an image shown smaller than its pixels as the area average under each device pixel, at its exact (fractional) position: a 1254 px illustration at 265 px now matches pixel for pixel. FigCraft sampled it bicubically at pixel centres, aliasing edges and thin lines. Straight images scaled down along both axes are resampled onto the device grid (crate::resample) on the canvas and in exports, so both still agree; others keep the pattern sampling. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/render/src/draw.rs | 22 +++++ crates/render/src/export_framing_tests.rs | 46 ++++++++-- crates/render/src/lib.rs | 1 + crates/render/src/resample.rs | 107 ++++++++++++++++++++++ docs/target-app-parity.md | 3 +- 5 files changed, 172 insertions(+), 7 deletions(-) create mode 100644 crates/render/src/resample.rs diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index c2d781f9c..77063befe 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -151,6 +151,27 @@ fn pixels_when_magnified(prep: Prepared, device_scale: f64) -> Prepared { Prepared::Pattern { pixmap, mode, quality, opacity, transform } } +/// An image pattern shown smaller than its pixels, straight, drawn into `path` under `xf` (local +/// → device) on a `limit`-sized pixmap: replaced by the device pixels it covers, each the average +/// of the image under it (see [`crate::resample`]), laid on the pixel grid. Others as they are. +fn averaged_when_shrunk(prep: Prepared, path: &tiny_skia::Path, xf: Affine, limit: (u32, u32)) -> Prepared { + let Prepared::Pattern { pixmap, mode: tiny_skia::SpreadMode::Pad, opacity, transform, .. } = &prep else { return prep }; + let device = ts_transform(xf); + let area = path + .bounds() + .transform(device) + .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), limit)); + let (Some(area), Some(back)) = (area, device.invert()) else { return prep }; + let Some(avg) = crate::resample::area_averaged(pixmap, device.pre_concat(*transform), area) else { return prep }; + Prepared::Pattern { + pixmap: std::sync::Arc::new(avg), + mode: tiny_skia::SpreadMode::Pad, + quality: FilterQuality::Nearest, + opacity: *opacity, + transform: back.pre_translate(area.x() as f32, area.y() as f32), + } +} + /// Paint `paints` over `path`, bottom first. Each blends by its own mode with what lies under it: /// within a layer that isn't pass-through (`isolate`), only with the paints below it in the list, /// the list then laid over the canvas as one (the reference tool's: a shape's fills on a @@ -205,6 +226,7 @@ fn paint_each( for p in paints { let Some(prep) = prepare_at(p, w, h, scale, ctx.doc, ctx.time, ctx.preview) else { continue }; let prep = if ctx.magnified_image_pixels && matches!(p.kind, PaintKind::Image(_)) { pixels_when_magnified(prep, scale) } else { prep }; + let prep = if matches!(p.kind, PaintKind::Image(_)) { averaged_when_shrunk(prep, path, xf, (pix.width(), pix.height())) } else { prep }; let paint = tiny_skia::Paint { shader: prep.shader(), anti_alias: true, blend_mode: ts_blend(p.blend), ..Default::default() }; if crate::paint::own_blend(p.blend) { // No tiny-skia mode: the paint alone over its pixels, then blended in. diff --git a/crates/render/src/export_framing_tests.rs b/crates/render/src/export_framing_tests.rs index 6edecf023..31336db69 100644 --- a/crates/render/src/export_framing_tests.rs +++ b/crates/render/src/export_framing_tests.rs @@ -1,12 +1,16 @@ -//! How an export frames a layer, as the reference tool's exports do (measured on its renders of the -//! same scenes): a drop shadow counts as far as its blur radius (its faint tail past that stays -//! out), and a layer inside that draws nothing doesn't count. +//! How an export frames and samples a layer, as the reference tool's exports do (measured on its +//! renders of the same scenes): a drop shadow counts as far as its blur radius (its faint tail past +//! that stays out), a layer inside that draws nothing doesn't count, and an image shown smaller +//! than its pixels comes out as the average of the image under each pixel, wherever it falls +//! between pixels. -use figcraft_color::{BlendMode, Color, Paint}; -use figcraft_doc::{Effect, EffectKind, NodeKind, Shadow}; +use std::sync::Arc; + +use figcraft_color::{BlendMode, Color, ImageScaleMode, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, ImageData, NodeKind, Shadow}; use super::paint_behaviour_tests::page; -use crate::export_bounds; +use crate::{Pixmap, encode_png, export_bounds, render_node}; fn shadow(radius: f64, offset: (f64, f64)) -> Effect { let color = Color { a: 0.3, ..Color::BLACK }; @@ -39,3 +43,33 @@ fn a_layer_that_draws_nothing_stays_out_of_the_export() { d.get_mut(ph).unwrap().fills = vec![Paint::solid(Color::BLACK)]; assert!(export_bounds(&d, f).unwrap().width() > 1000.0); } + +/// A 400 × 400 white image with one black column of pixels (x = 201), on a 100 × 100 layer at +/// `(x, 0)`. +fn line_at(x: f64) -> (Document, figcraft_doc::NodeId) { + let mut img = Pixmap::new(400, 400).unwrap(); + for (i, c) in img.data_mut().chunks_exact_mut(4).enumerate() { + let v = if i % 400 == 201 { 0 } else { 255 }; + c.copy_from_slice(&[v, v, v, 255]); + } + let (mut d, p) = page(); + d.images.insert("line".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: 400, height: 400 }); + let r = d.create(p, NodeKind::Rectangle, "Image", x, 0.0, 100.0, 100.0).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image("line", ImageScaleMode::Fill)]; + (d, r) +} + +#[test] +fn an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers() { + // Shown at a quarter of its size, the line is a quarter of a pixel wide: wherever it falls, + // the pixels it crosses hold a quarter pixel's worth of black between them (sampled at pixel + // centres instead, it vanishes or comes out a whole pixel dark). + for at in [0.0, 10.5, 7.3, 3.9] { + let (d, r) = line_at(at); + let pix = render_node(&d, r, 1.0).unwrap(); + let w = pix.width() as usize; + let y = 50; + let ink: f64 = (0..w).map(|x| 255.0 - f64::from(pix.data()[(y * w + x) * 4])).sum(); + assert!((ink - 255.0 / 4.0).abs() < 6.0, "layer at x {at}: {ink} of black in the row"); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index df1a2e04e..7d8e3a314 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -20,6 +20,7 @@ mod layer_budget; pub mod lod; pub mod paint; pub mod pattern; +mod resample; pub mod retained; pub mod shadow; diff --git a/crates/render/src/resample.rs b/crates/render/src/resample.rs new file mode 100644 index 000000000..9a194a14d --- /dev/null +++ b/crates/render/src/resample.rs @@ -0,0 +1,107 @@ +//! Images drawn smaller than their pixels, on the canvas and in exports: each device pixel is the +//! average of the image area it covers, wherever the image falls between pixels (the reference +//! tool's exports; sampling the image at pixel centres instead keeps every edge and fine line +//! aliased, and a copy scaled down first then shifted a fraction of a pixel comes out blurred). +//! Past its edges the image extends its edge pixels, as the pattern it replaces does. + +use tiny_skia::{IntRect, Pixmap, Transform}; + +/// The most weights the two passes may work through (device pixels times the image pixels each +/// averages), so one huge image shown small doesn't hold up an export: past it the image is +/// sampled as before. +const MAX_WORK: u64 = 1 << 28; + +/// `src` (premultiplied) as it shows over device area `area` under `m` (image pixels → device), +/// averaged per device pixel; its pixel (0, 0) lies at the area's top-left. `None` unless `m` is +/// axis-aligned and makes the image smaller along both axes. +pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect) -> Option { + let (sx, sy) = (f64::from(m.sx), f64::from(m.sy)); + let (tx, ty) = (f64::from(m.tx), f64::from(m.ty)); + let straight = m.kx.abs() < 1e-6 && m.ky.abs() < 1e-6; + if !straight || !(sx.abs() < 1.0 && sy.abs() < 1.0 && sx.abs() > 1e-6 && sy.abs() > 1e-6) || !tx.is_finite() || !ty.is_finite() { + return None; + } + let (sw, sh) = (src.width() as usize, src.height() as usize); + let (dw, dh) = (area.width() as usize, area.height() as usize); + let cols = spans(area.x(), dw, tx, sx, sw); + let rows = spans(area.y(), dh, ty, sy, sh); + // Only the image rows some device row reads are averaged across. + let (r0, r1) = rows.iter().fold((usize::MAX, 0), |(a, b), s| (a.min(s.first), b.max(s.first + s.weights.len()))); + let r1 = r1.min(sh); + if r0 >= r1 { + return None; + } + let work = |s: &[Span]| s.iter().map(|s| s.weights.len() as u64).sum::(); + if work(&cols).saturating_mul((r1 - r0) as u64).saturating_add(work(&rows).saturating_mul(dw as u64)) > MAX_WORK { + return None; + } + let data = src.data(); + // Across: each image row in use, averaged into the device columns. + let mut across = vec![[0.0_f32; 4]; (r1 - r0) * dw]; + for (r, out) in (r0..r1).zip(across.chunks_mut(dw)) { + let row = data.get(r * sw * 4..(r + 1) * sw * 4)?; + for (c, o) in cols.iter().zip(out.iter_mut()) { + for (k, w) in c.weights.iter().enumerate() { + let px = row.get((c.first + k) * 4..(c.first + k) * 4 + 4)?; + for (acc, v) in o.iter_mut().zip(px) { + *acc += w * f32::from(*v); + } + } + } + } + // Down: the device rows from those. + let mut out = Pixmap::new(area.width(), area.height())?; + for (y, s) in rows.iter().enumerate() { + for x in 0..dw { + let mut acc = [0.0_f32; 4]; + for (k, w) in s.weights.iter().enumerate() { + let px = across.get((s.first + k - r0) * dw + x)?; + for (a, v) in acc.iter_mut().zip(px) { + *a += w * v; + } + } + let to = |v: f32| v.round().clamp(0.0, 255.0) as u8; + let alpha = to(acc[3]); + let dst = out.data_mut().get_mut((y * dw + x) * 4..(y * dw + x) * 4 + 4)?; + // Premultiplied: no channel above the alpha, whatever rounding did. + dst.copy_from_slice(&[to(acc[0]).min(alpha), to(acc[1]).min(alpha), to(acc[2]).min(alpha), alpha]); + } + } + Some(out) +} + +/// The image pixels one device column (or row) averages: the first, and each one's weight. +struct Span { + first: usize, + weights: Vec, +} + +/// For `n` device pixels from `start`, the image pixels each covers along an axis where image +/// pixel `u` lies at `t + u * s` (device): the overlap of each with the pixel, as a share of the +/// pixel's width in image pixels. What lies past the image's `len` pixels counts as its edge +/// pixel. +fn spans(start: i32, n: usize, t: f64, s: f64, len: usize) -> Vec { + let last = len.saturating_sub(1); + (0..n) + .map(|i| { + let d = f64::from(start) + i as f64; + let (a, b) = ((d - t) / s, (d + 1.0 - t) / s); + let (a, b) = (a.min(b), a.max(b)); + let total = b - a; + let clamp = |u: f64| u.clamp(0.0, last as f64) as usize; + let (first, end) = (clamp(a.floor()), clamp(b.ceil() - 1.0)); + let mut weights = vec![0.0_f32; end - first + 1]; + // Each image pixel's own overlap; what lies before the image goes to the first and + // past it to the last. + let mut u = a.floor(); + while u < b { + let w = (b.min(u + 1.0) - a.max(u)) / total; + if let Some(slot) = weights.get_mut(clamp(u) - first) { + *slot += w as f32; + } + u += 1.0; + } + Span { first, weights } + }) + .collect() +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2753e7cea..81f0139d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (an export frames a drop shadow to its blur radius and leaves out layers that draw nothing; a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-20 · **Change:** minor (an image shown smaller than its pixels is drawn as the average of what each pixel covers; an export frames a drop shadow to its blur radius and leaves out layers that draw nothing; a line height in pixels keeps its fraction, as the reference tool lays text out; paint blend modes checked against the reference tool's renders: a layer that isn't pass-through blends its fills among themselves only, a pass-through frame's fills blend with the backdrop under its shadows, drop shadows blend among themselves, inner shadows with the fills, plus lighter adds colours with source-over alpha; M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; 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); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -651,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Images shown smaller than their pixels (M3, paint): on the canvas and in exports each device pixel is now the average of the image area it covers, wherever the image falls between pixels, as the reference tool's exports come out (a 1 254 px illustration shown at 265 px matches its export pixel for pixel). It was sampled bicubically at pixel centres from the full image (exports) or from a copy at the next of 256…8192 px (canvas), which kept edges and fine lines aliased and, an image at a fractional position, dropped that fraction. Straight (unrotated) images scaled down along both axes; rotated or skewed ones and tiles are sampled as before, and the work is capped (a huge image shown small falls back too). Found on an iOS kit's illustrations: differing pixels 1–2% → 0–0.4%. Test: `export_framing_tests::an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers`. Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Export area as the reference tool frames it (M3, export): a drop shadow reaches into a PNG/JPG/SVG/PDF export's area as far as its blur radius (plus spread, toward its offset), as the tool's exports and render bounds take it (a 44 px button with a 16 px shadow exports 76 × 76; it was 92 × 92, three standard deviations), and a layer that draws nothing (no visible fill, stroke, effect or children: a placeholder whose image was taken out) no longer widens its parent's export (a 300 × 225 illustration holding an empty 1 448 × 1 086 box exported at that size). The canvas's culling and redraw areas keep the whole blur. Found on an iOS kit's glass buttons, switches and illustrations: differing pixels 20–42% → under 1% each. Tests: `crates/render/src/export_framing_tests.rs`. Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Text line heights given in pixels keep their fraction (M3, text metrics): lines 22.5 px apart stay 22.5 apart, the glyphs centred in each, and a self-sizing box rounds the lines' total up to a whole pixel (three lines of 22.5 make a 68 px box, three of 18.4 a 56 px one), as the reference tool's own saved layouts show (`derivedTextData` of 1 486 text layers in one `.fig`, 470 of them with pixel line heights from 15 to 38.5: those keep their pitch; Auto and percentages round, as before). They were rounded to whole pixels (22.5 → 23), so every paragraph drifted half a pixel a line. Found on an iOS kit: four-line paragraphs ended 1.5 px low; differing pixels on those screens 3% → 1.7%. Test: `metrics_tests::pixel_line_heights_keep_their_fraction` (the pinned "pixel values round too, not measured" case is replaced). Percentages and hours unchanged at this rounding | | 2026-11-20 | minor | Paint blend modes checked against renders of a synthetic file by the reference tool (9 scenes; differing pixels before → after: up to 39% → under 0.2% each) and fixed on the canvas and in PNG exports: a layer in a blend mode of its own (Normal included) blends its fills with each other only, then lays them over the canvas as one, with or without effects (they blended with the backdrop until a layer had an effect, then not); a pass-through frame's fills blend with the backdrop also when it has drop or inner shadows (it was drawn as an isolated layer); drop shadows blend by their modes among themselves, then lie under the layer as one (two linear-burn shadows darkened the backdrop); inner shadows blend with the fills under them by their own mode (they were drawn normally); plus lighter adds the premultiplied colours and combines the alphas as source-over does (tiny-skia's sum made a translucent stack opaque). Found on iOS kit buttons and alerts imported from a `.fig`: their fill stacks (plus lighter, luminosity) drew mid grey instead of near white. Tests: `crates/render/src/fill_blend_tests.rs`. SVG and PDF exports unchanged. Percentages and hours unchanged at this rounding | From bb2ecfb1706ff8f57d88d096f2fe100b2d2b3f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Fri, 20 Nov 2026 23:30:02 +0100 Subject: [PATCH 07/14] M6: REST import reads opentypeFlags as the API writes it Figma's REST API names a text's feature toggles style.opentypeFlags; the importer looked for openTypeFlags, so features in real files (SF Pro's SS16 large symbols on an iOS kit's back chevron) were dropped. The old spelling is still read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/format/src/rest/tests.rs | 2 +- crates/format/src/rest/text.rs | 3 ++- docs/file-format-parity.md | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/format/src/rest/tests.rs b/crates/format/src/rest/tests.rs index 6630ee406..d61d61edb 100644 --- a/crates/format/src/rest/tests.rs +++ b/crates/format/src/rest/tests.rs @@ -326,7 +326,7 @@ fn text_styles_and_runs() { "style": {"fontFamily": "Inter", "fontPostScriptName": "Inter-Regular", "fontStyle": "Regular", "fontWeight": 400, "fontSize": 24, "lineHeightPx": 29, "lineHeightUnit": "INTRINSIC_%", "letterSpacing": 0, "textAlignHorizontal": "CENTER", "textAlignVertical": "CENTER", "textAutoResize": "HEIGHT", "textCase": "UPPER", "textDecoration": "UNDERLINE", - "paragraphSpacing": 8, "paragraphIndent": 4, "leadingTrim": "CAP_HEIGHT", "openTypeFlags": {"LIGA": 0, "ss01": 1}}, + "paragraphSpacing": 8, "paragraphIndent": 4, "leadingTrim": "CAP_HEIGHT", "opentypeFlags": {"LIGA": 0, "ss01": 1}}, // UTF-16 code units: the emoji takes two. "characterStyleOverrides": [0, 1, 1, 2], "styleOverrideTable": {"1": {"fontWeight": 700}, "2": {"fills": [solid(1.0, 0.0, 0.0)], "hyperlink": {"type": "URL", "url": "https://example.com"}}}, diff --git a/crates/format/src/rest/text.rs b/crates/format/src/rest/text.rs index 971e2fb8f..b58c33af8 100644 --- a/crates/format/src/rest/text.rs +++ b/crates/format/src/rest/text.rs @@ -95,7 +95,8 @@ fn paragraph(s: &Value, td: &mut TextData) { if text(s, "leadingTrim") == Some("CAP_HEIGHT") { td.leading_trim = figcraft_doc::LeadingTrim::CapHeight; } - if let Some(flags) = s.get("openTypeFlags").and_then(Value::as_object) { + // `opentypeFlags` as the reference tool's API writes it; `openTypeFlags` as earlier files had it. + if let Some(flags) = s.get("opentypeFlags").or_else(|| s.get("openTypeFlags")).and_then(Value::as_object) { for (tag, on) in flags.iter().take(64) { if figcraft_doc::valid_feature_tag(&tag.to_ascii_lowercase()) { td.features.insert(tag.to_ascii_lowercase(), on.as_f64().is_some_and(|x| x != 0.0) || on.as_bool() == Some(true)); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 89e45fa56..793da9fe9 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-20 · **Change:** minor (REST import reads instances' component property bindings, variant ones included, and an opened file shows the variant a bound `Mode`-style variable names in each instance's mode; `.fig` and REST import: a variable font's optical size follows the text size, as in Figma, so SF Pro text is no longer set with its display cut at text sizes; 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); `.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-20 · **Change:** minor (REST import reads OpenType feature toggles under the key the API writes, `opentypeFlags`; REST import reads instances' component property bindings, variant ones included, and an opened file shows the variant a bound `Mode`-style variable names in each instance's mode; `.fig` and REST import: a variable font's optical size follows the text size, as in Figma, so SF Pro text is no longer set with its display cut at text sizes; 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); `.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 @@ -195,6 +195,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | M6: REST import reads a text's OpenType feature toggles from `style.opentypeFlags`, the key the reference tool's API writes (it looked for `openTypeFlags`, so real files lost them; that spelling is still read). Found on an iOS kit whose back chevron turns on `SS16` (SF Pro's large symbols): it drew the medium symbol, a quarter smaller. `.fig` files need craft-fig to pass `toggledOnOTFeatures` / `toggledOffOTFeatures` on as `opentypeFlags` (craft-libs change, not yet merged). Test: `rest::tests::text_styles_and_runs` | | 2026-11-20 | minor | M6: instances' component property bindings import from REST JSON (`boundVariables.componentProperties`, variant properties included), and an opened REST or `.fig` file settles them: an instance whose variant property is bound to a string variable shows the variant the variable names in its mode (a kit's Dark variants in frames set to Dark), keeping its own overrides and those the mains around it make (a destructive button's red tint), and a text reads a property its instance sets even when the variant set lists it under another id. `.fig` needs craft-libs' `craft-fig` from local commit `edcc9d6d3` (maps the file's `RESOLVE_VARIANT` binding and keeps the whole variant set). Checked against renders of a real-world iOS kit file: its dark screens drew the light variants (dark alerts 28% and 20% of pixels differing, the dark keyboard 38%); now 2%, 1.4% and 1.7%; frames under 1% difference 108 → 126 of 162. Tests: `crates/engine/src/variant_binding_import_tests.rs`, `variant_mode_switch_tests.rs`. Numbers unchanged | | 2026-11-20 | minor | M6: `.fig` and REST import set a variable font's optical size to the text size (within the axis), also for a named style, as the `.sketch` import already did: FigCraft keeps a named instance's optical size (SF Pro's is 28, its display cut), so imported SF Pro text at text sizes was set about 14% narrower than in Figma. Rule from the glyph advances `.fig` files saved by Figma carry (`derivedTextData.glyphs`): in a real-world file SF Pro Regular, Medium and Semibold at 12–17 px match the 17 cut and at 18–24 px their own size's, and a synthetic file saved from Figma's web app gives SF Pro Regular the 17 cut at 11–17 px, the 20 cut at 20 px and the 28 cut at 28–64 px; Figma's Inter (no optical size axis) keeps the same advances from 11 to 64 px. Checked against renders from Figma's REST images endpoint: on 24 screens of that file the share of differing pixels fell on every screen (median 3.2% → 1.7%). Test: `crates/engine/src/fig_optical_size_tests.rs`. Numbers unchanged | | 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 37131ec1c2a6574539f29389ebe203f9142e8fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Sat, 21 Nov 2026 00:09:44 +0100 Subject: [PATCH 08/14] docs: point the .fig rows at storytold/craft-libs#2714 The .fig side of the variant bindings and OpenType features is in that pull request; the rows named a local commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- docs/file-format-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 793da9fe9..dc08a7f4d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -17,7 +17,7 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.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). Since 2026-11-20, a variable font's optical size follows the text size (within the axis), also for a named style, as the glyph advances a `.fig` file saves with its text show for SF Pro (12–17 px set with the 17 cut, 18–24 px with their own size's, 30 px with the 28 cut); the text carries the size as its `opsz` value. A font without that axis is unaffected: Figma's own Inter has none, so its advances stay the same at every size, while a locally installed Inter 4 has one and can set large text narrower than Figma. Optical sizes a `.fig` text sets itself (`fontVariations`) are not read yet. A variant property bound to a variable (a kit's Light/Dark `Mode`, a `RESOLVE_VARIANT` expression in the file) comes across with craft-libs' `craft-fig` from local commit `edcc9d6d3` on (not yet in the pinned revision): it then switches each instance to the variant the variable names in its mode, as the REST import does, and the whole variant set is kept. 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 | +| `.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). Since 2026-11-20, a variable font's optical size follows the text size (within the axis), also for a named style, as the glyph advances a `.fig` file saves with its text show for SF Pro (12–17 px set with the 17 cut, 18–24 px with their own size's, 30 px with the 28 cut); the text carries the size as its `opsz` value. A font without that axis is unaffected: Figma's own Inter has none, so its advances stay the same at every size, while a locally installed Inter 4 has one and can set large text narrower than Figma. Optical sizes a `.fig` text sets itself (`fontVariations`) are not read yet. A variant property bound to a variable (a kit's Light/Dark `Mode`, a `RESOLVE_VARIANT` expression in the file) comes across with craft-libs' `craft-fig` from storytold/craft-libs#2714 on (not yet in the pinned revision): it then switches each instance to the variant the variable names in its mode, as the REST import does, and the whole variant set is kept. 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 | — | @@ -195,8 +195,8 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| -| 2026-11-20 | minor | M6: REST import reads a text's OpenType feature toggles from `style.opentypeFlags`, the key the reference tool's API writes (it looked for `openTypeFlags`, so real files lost them; that spelling is still read). Found on an iOS kit whose back chevron turns on `SS16` (SF Pro's large symbols): it drew the medium symbol, a quarter smaller. `.fig` files need craft-fig to pass `toggledOnOTFeatures` / `toggledOffOTFeatures` on as `opentypeFlags` (craft-libs change, not yet merged). Test: `rest::tests::text_styles_and_runs` | -| 2026-11-20 | minor | M6: instances' component property bindings import from REST JSON (`boundVariables.componentProperties`, variant properties included), and an opened REST or `.fig` file settles them: an instance whose variant property is bound to a string variable shows the variant the variable names in its mode (a kit's Dark variants in frames set to Dark), keeping its own overrides and those the mains around it make (a destructive button's red tint), and a text reads a property its instance sets even when the variant set lists it under another id. `.fig` needs craft-libs' `craft-fig` from local commit `edcc9d6d3` (maps the file's `RESOLVE_VARIANT` binding and keeps the whole variant set). Checked against renders of a real-world iOS kit file: its dark screens drew the light variants (dark alerts 28% and 20% of pixels differing, the dark keyboard 38%); now 2%, 1.4% and 1.7%; frames under 1% difference 108 → 126 of 162. Tests: `crates/engine/src/variant_binding_import_tests.rs`, `variant_mode_switch_tests.rs`. Numbers unchanged | +| 2026-11-20 | minor | M6: REST import reads a text's OpenType feature toggles from `style.opentypeFlags`, the key the reference tool's API writes (it looked for `openTypeFlags`, so real files lost them; that spelling is still read). Found on an iOS kit whose back chevron turns on `SS16` (SF Pro's large symbols): it drew the medium symbol, a quarter smaller. `.fig` files need craft-fig to pass `toggledOnOTFeatures` / `toggledOffOTFeatures` on as `opentypeFlags` (storytold/craft-libs#2714, not yet merged). Test: `rest::tests::text_styles_and_runs` | +| 2026-11-20 | minor | M6: instances' component property bindings import from REST JSON (`boundVariables.componentProperties`, variant properties included), and an opened REST or `.fig` file settles them: an instance whose variant property is bound to a string variable shows the variant the variable names in its mode (a kit's Dark variants in frames set to Dark), keeping its own overrides and those the mains around it make (a destructive button's red tint), and a text reads a property its instance sets even when the variant set lists it under another id. `.fig` needs craft-libs' `craft-fig` from storytold/craft-libs#2714 (maps the file's `RESOLVE_VARIANT` binding and keeps the whole variant set). Checked against renders of a real-world iOS kit file: its dark screens drew the light variants (dark alerts 28% and 20% of pixels differing, the dark keyboard 38%); now 2%, 1.4% and 1.7%; frames under 1% difference 108 → 126 of 162. Tests: `crates/engine/src/variant_binding_import_tests.rs`, `variant_mode_switch_tests.rs`. Numbers unchanged | | 2026-11-20 | minor | M6: `.fig` and REST import set a variable font's optical size to the text size (within the axis), also for a named style, as the `.sketch` import already did: FigCraft keeps a named instance's optical size (SF Pro's is 28, its display cut), so imported SF Pro text at text sizes was set about 14% narrower than in Figma. Rule from the glyph advances `.fig` files saved by Figma carry (`derivedTextData.glyphs`): in a real-world file SF Pro Regular, Medium and Semibold at 12–17 px match the 17 cut and at 18–24 px their own size's, and a synthetic file saved from Figma's web app gives SF Pro Regular the 17 cut at 11–17 px, the 20 cut at 20 px and the 28 cut at 28–64 px; Figma's Inter (no optical size axis) keeps the same advances from 11 to 64 px. Checked against renders from Figma's REST images endpoint: on 24 screens of that file the share of differing pixels fell on every screen (median 3.2% → 1.7%). Test: `crates/engine/src/fig_optical_size_tests.rs`. Numbers unchanged | | 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. | | 2026-11-19 | patch | M6, #2468 follow-up: SVG import checks its input with craft-svg (`tree::parse`, `tree::image_resolver`), so FigCraft's own byte scanners (`too_wide`, `too_deep`, `nesting`) and `import/budget.rs` were dead code, and `main` failed `cargo fmt` and clippy. They are removed; the budget and hostile-input tests now run against craft-svg's `tree::Limits` (documents nest at most 256 levels deep, references followed, where FigCraft's scanner allowed 512). No behaviour change beyond #2468. | From ff3cd3f9fec8d7e1338a03ce204781ad4fb79cc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Sat, 21 Nov 2026 11:14:30 +0100 Subject: [PATCH 09/14] M3: review fixes for blend modes, export framing, image averaging, text cut - A pass-through frame drawn onto the canvas after its shadows draws what it casts them from without letting the layers inside draw twice as well, so nested shadowed frames no longer double the work at each level. - That decision also looks at vector region fills and at the paints of pass-through layers inside. - A paint at zero opacity or a fully transparent shadow no longer changes how the others composite; the shadow group takes its pixmap from the layer budget, and paints past the budget still draw. - A vector that paints only through its regions counts for export framing. - Averaging an image shown smaller keeps one row of scratch instead of the whole pass, takes its pixmap from the layer budget, walks only the image's own pixels, and averages only the part of each pixel inside the shape, so a fitted image's edge fades once. - Text cut to its box height keeps a whole-pixel height. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/doc/src/node.rs | 15 ++- crates/render/src/draw.rs | 57 ++++++++--- crates/render/src/export_framing_tests.rs | 49 +++++++--- crates/render/src/fill_blend_tests.rs | 18 ++++ crates/render/src/lib.rs | 2 + crates/render/src/lod_tests.rs | 1 + crates/render/src/pattern.rs | 1 + crates/render/src/resample.rs | 113 +++++++++++----------- crates/text/src/layout.rs | 3 +- crates/text/src/metrics_tests.rs | 13 +++ 10 files changed, 185 insertions(+), 87 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index cca1136b0..144ca4101 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -784,10 +784,19 @@ impl Node { self.board.as_ref().is_some_and(crate::BoardItem::is_atom) } - /// Whether this layer puts nothing on the canvas: no visible fill, stroke or effect and no - /// children (a placeholder box whose image was taken out, an empty frame). + /// Whether this layer puts nothing on the canvas: no visible fill (its own or a vector + /// region's), stroke or effect and no children (a placeholder box whose image was taken out, + /// an empty frame). pub fn draws_nothing(&self) -> bool { - self.children.is_empty() && !self.fills.iter().any(|f| f.visible) && !self.has_visible_stroke() && !self.effects.iter().any(|e| e.visible) + let region_fill = match &self.kind { + NodeKind::Vector { network } => network.regions.iter().any(|r| r.fills.as_deref().is_some_and(|f| f.iter().any(|p| p.visible))), + _ => false, + }; + self.children.is_empty() + && !self.fills.iter().any(|f| f.visible) + && !region_fill + && !self.has_visible_stroke() + && !self.effects.iter().any(|e| e.visible) } /// A section whose contents are hidden: only its name and outline show; its children are diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 77063befe..1bdf7f2fd 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -40,6 +40,10 @@ pub struct Ctx<'a, 'd> { pub time: f64, /// Paint bounds already worked out in this render. pub bounds: &'a Bounds<'d>, + /// Drawing only what a pass-through layer casts its shadows from, before it draws again onto + /// the canvas: layers inside don't draw twice themselves (nested, the draws would double at + /// each level). + pub casting: bool, } /// What one render works out about layers with children, which a walk down their subtree finds: @@ -162,7 +166,8 @@ fn averaged_when_shrunk(prep: Prepared, path: &tiny_skia::Path, xf: Affine, limi .transform(device) .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), limit)); let (Some(area), Some(back)) = (area, device.invert()) else { return prep }; - let Some(avg) = crate::resample::area_averaged(pixmap, device.pre_concat(*transform), area) else { return prep }; + let Some(clip) = path.bounds().transform(device) else { return prep }; + let Some(avg) = crate::resample::area_averaged(pixmap, device.pre_concat(*transform), area, clip) else { return prep }; Prepared::Pattern { pixmap: std::sync::Arc::new(avg), mode: tiny_skia::SpreadMode::Pad, @@ -191,20 +196,23 @@ fn fill_with( mask: Option<&Mask>, isolate: bool, ) { - let blended = |p: &Paint| p.visible && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); + let blended = |p: &Paint| p.visible && p.opacity > 0.0 && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); if isolate && paints.iter().any(blended) { let area = path .bounds() .transform(ts_transform(xf)) .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), (pix.width(), pix.height()))); - let Some(r) = area else { return }; - let Some(_held) = crate::layer_budget::Held::take(r.width(), r.height(), 1) else { return }; - let Some(mut alone) = Pixmap::new(r.width(), r.height()) else { return }; - let at = Affine::translate((-f64::from(r.x()), -f64::from(r.y()))) * xf; - paint_each(&mut alone, path, paints, w, h, at, rule, ctx, None); - let pp = PixmapPaint::default(); - pix.draw_pixmap(r.x(), r.y(), alone.as_ref(), &pp, Transform::identity(), mask); - return; + // Past the layer budget, the paints blend with the canvas too rather than not draw. + if let Some(r) = area + && let Some(_held) = crate::layer_budget::Held::take(r.width(), r.height(), 1) + && let Some(mut alone) = Pixmap::new(r.width(), r.height()) + { + let at = Affine::translate((-f64::from(r.x()), -f64::from(r.y()))) * xf; + paint_each(&mut alone, path, paints, w, h, at, rule, ctx, None); + let pp = PixmapPaint::default(); + pix.draw_pixmap(r.x(), r.y(), alone.as_ref(), &pp, Transform::identity(), mask); + return; + } } paint_each(pix, path, paints, w, h, xf, rule, ctx, mask); } @@ -812,6 +820,8 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u layer.draw_pixmap(0, 0, b.as_ref(), &PixmapPaint::default(), Transform::identity(), None); } let op = n.opacity.clamp(0.0, 1.0); + // Drawn onto the canvas after its shadows, the layer below is only what they are cast from. + let through = !ctx.casting && blends_through(ctx.doc, n, casts || first_back.is_some()); { // Inner shadows paint over the fills, under the children and strokes: cast from around the // outline, or around the fills' pixels where images paint their own alpha. @@ -835,7 +845,8 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u let under = Under { opacity: op, blend: n.blend, ..Under::new(pix, (lx, ly), ctx.under) }; let over_back = first_back.as_ref().filter(|_| casts).map(|b| Under::new(b, (0, 0), Some(&under))); let content_under = over_back.as_ref().unwrap_or(&under); - draw_content(&Ctx { under: Some(content_under), ..*ctx }, &mut layer, n, lxf, depth, has_inner.then_some(&inner as &dyn Fn(&mut Pixmap))); + let sub = Ctx { under: Some(content_under), casting: ctx.casting || through, ..*ctx }; + draw_content(&sub, &mut layer, n, lxf, depth, has_inner.then_some(&inner as &dyn Fn(&mut Pixmap))); } // A group is no outline of its own: its inner shadows are cast from around what its layers // draw together, over them. @@ -867,8 +878,12 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u let caster = shadow::Caster::new(ctx.doc, n, content.as_ref().unwrap_or(&layer), lxf, ctx.scale); // The shadows blend by their own modes among themselves, then lie under the layer as one // (two linear-burn shadows darken where they overlap, not the backdrop under them). - let blended = n.effects.iter().any(|e| e.visible && matches!(&e.kind, EffectKind::DropShadow(s) if s.blend != BlendMode::Normal)); - let mut group = if blended { Pixmap::new(lw, lh) } else { None }; + // A shadow that adds nothing (fully transparent) doesn't make the others a group. Past the + // layer budget they lie under the layer one by one. + let blended = + n.effects.iter().any(|e| e.visible && matches!(&e.kind, EffectKind::DropShadow(s) if s.blend != BlendMode::Normal && s.color.a > 0.0)); + let held = if blended { crate::layer_budget::Held::take(lw, lh, 1) } else { None }; + let mut group = held.as_ref().and_then(|_| Pixmap::new(lw, lh)); for e in n.effects.iter().filter(|e| e.visible) { if let EffectKind::DropShadow(s) = &e.kind && let Some(sh) = shadow::drop_shadow(&caster, s) @@ -891,7 +906,7 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u } layer_effects(ctx, &mut layer, n, id, lxf); } - if blends_through(ctx.doc, n, casts || first_back.is_some()) { + if through { // A pass-through layer whose only effects are shadows isn't a group: once its shadows lie // under it, what it paints blends by its own modes with the backdrop, as without them // (the layer above was what the shadows were cast from). @@ -925,10 +940,22 @@ fn blends_through(doc: &Document, n: &Node, backdrop: bool) -> bool { if shadow::inner_from_pixels(doc, n) && n.effects.iter().any(|e| e.visible && matches!(e.kind, EffectKind::InnerShadow(_))) { return false; } + paints_blend(n) + || doc.subtree(n.id).iter().skip(1).filter_map(|c| doc.node(*c)).any(|c| match c.blend { + BlendMode::Normal => false, + // Its paints blend with what lies under it too. + BlendMode::PassThrough => paints_blend(c), + _ => true, + }) +} + +/// Whether one of `n`'s own paints (fills, strokes, a vector region's fills) is in a blend mode +/// of its own. +fn paints_blend(n: &Node) -> bool { let own = |p: &Paint| p.visible && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); n.fills.iter().any(own) || n.strokes.iter().any(own) - || doc.subtree(n.id).iter().skip(1).filter_map(|c| doc.node(*c)).any(|c| !matches!(c.blend, BlendMode::Normal | BlendMode::PassThrough)) + || region_painted(n).is_some_and(|net| net.regions.iter().any(|r| r.fills.as_deref().is_some_and(|f| f.iter().any(own)))) } /// Node `n`'s backdrop effects through its backdrop outline `sh`, for its `size` layer at `at` on diff --git a/crates/render/src/export_framing_tests.rs b/crates/render/src/export_framing_tests.rs index 31336db69..bf0c3e63d 100644 --- a/crates/render/src/export_framing_tests.rs +++ b/crates/render/src/export_framing_tests.rs @@ -45,7 +45,7 @@ fn a_layer_that_draws_nothing_stays_out_of_the_export() { } /// A 400 × 400 white image with one black column of pixels (x = 201), on a 100 × 100 layer at -/// `(x, 0)`. +/// `(x, 0)` in a white 120 × 100 frame; returns the frame. fn line_at(x: f64) -> (Document, figcraft_doc::NodeId) { let mut img = Pixmap::new(400, 400).unwrap(); for (i, c) in img.data_mut().chunks_exact_mut(4).enumerate() { @@ -54,22 +54,47 @@ fn line_at(x: f64) -> (Document, figcraft_doc::NodeId) { } let (mut d, p) = page(); d.images.insert("line".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: 400, height: 400 }); - let r = d.create(p, NodeKind::Rectangle, "Image", x, 0.0, 100.0, 100.0).unwrap(); + let f = d.create(p, NodeKind::Frame, "Frame", 0.0, 0.0, 120.0, 100.0).unwrap(); + d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::WHITE)]; + let r = d.create(f, NodeKind::Rectangle, "Image", x, 0.0, 100.0, 100.0).unwrap(); d.get_mut(r).unwrap().fills = vec![Paint::image("line", ImageScaleMode::Fill)]; - (d, r) + (d, f) } #[test] fn an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers() { - // Shown at a quarter of its size, the line is a quarter of a pixel wide: wherever it falls, - // the pixels it crosses hold a quarter pixel's worth of black between them (sampled at pixel - // centres instead, it vanishes or comes out a whole pixel dark). - for at in [0.0, 10.5, 7.3, 3.9] { - let (d, r) = line_at(at); - let pix = render_node(&d, r, 1.0).unwrap(); + // Shown at a quarter of its size, the line is a quarter of a pixel wide, at x + 50.25. The + // pixels it crosses share its quarter pixel of black by how much of it each covers (sampled at + // pixel centres instead, it vanishes or comes out a whole pixel dark). + for at in [0.0, 10.5, 7.3, 3.9, 0.6] { + let (d, f) = line_at(at); + let pix = render_node(&d, f, 1.0).unwrap(); let w = pix.width() as usize; - let y = 50; - let ink: f64 = (0..w).map(|x| 255.0 - f64::from(pix.data()[(y * w + x) * 4])).sum(); - assert!((ink - 255.0 / 4.0).abs() < 6.0, "layer at x {at}: {ink} of black in the row"); + let ink = |x: usize| 255.0 - f64::from(pix.data()[(50 * w + x) * 4]); + let (l, r) = (at + 50.25, at + 50.5); + for x in 0..w { + let covered = (r.min(x as f64 + 1.0) - l.max(x as f64)).max(0.0); + assert!((ink(x) - 255.0 * covered).abs() < 3.0, "layer at x {at}: pixel {x} holds {} of black", ink(x)); + } } } + +/// Where a shape's edge cuts a pixel, an image fitted to that edge fades it once (by the shape's +/// coverage), not again for the image area past the edge. +#[test] +fn a_fitted_image_shown_smaller_fades_the_shapes_edge_once() { + let mut img = Pixmap::new(8, 8).unwrap(); + img.fill(tiny_skia::Color::from_rgba8(0, 0, 0, 255)); + let (mut d, p) = page(); + d.images.insert("black".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: 8, height: 8 }); + let f = d.create(p, NodeKind::Frame, "Frame", 0.0, 0.0, 8.0, 8.0).unwrap(); + d.get_mut(f).unwrap().fills = vec![Paint::solid(Color::WHITE)]; + // 4 wide, so the image shows at half its size, fitted edge to edge across. + let r = d.create(f, NodeKind::Rectangle, "Image", 0.25, 0.0, 4.0, 6.0).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image("black", ImageScaleMode::Fit)]; + let pix = render_node(&d, f, 1.0).unwrap(); + let w = pix.width() as usize; + let ink = |x: usize| 255.0 - f64::from(pix.data()[(3 * w + x) * 4]); + assert!((ink(0) - 255.0 * 0.75).abs() < 4.0, "the first pixel, three quarters covered, holds {}", ink(0)); + assert!(ink(1) > 250.0, "the next, inside, holds {}", ink(1)); +} diff --git a/crates/render/src/fill_blend_tests.rs b/crates/render/src/fill_blend_tests.rs index e4b2b8ee1..bc3b4a49e 100644 --- a/crates/render/src/fill_blend_tests.rs +++ b/crates/render/src/fill_blend_tests.rs @@ -104,3 +104,21 @@ fn inner_shadows_blend_with_the_fills_under_them() { assert!(near(px(&pix, 100, 45), [103, 103, 103], 4), "{:?}", px(&pix, 100, 45)); assert!(near(px(&pix, 100, 155), [168, 168, 168], 4), "{:?}", px(&pix, 100, 155)); } + +/// A pass-through frame inside a pass-through frame: its Multiply fill blends with the backdrop +/// whether or not the frame around it casts shadows (yellow over the light backdrop comes out +/// its yellow, not pure yellow). +#[test] +fn a_nested_pass_through_frames_fills_blend_with_the_backdrop_under_shadows() { + for effects in [vec![], vec![faint()]] { + let (mut d, p) = backdrop(); + let outer = d.create(p, NodeKind::Frame, "Outer", 20.0, 40.0, 160.0, 120.0).unwrap(); + let n = d.get_mut(outer).unwrap(); + (n.fills, n.effects, n.blend) = (vec![], effects.clone(), BlendMode::PassThrough); + let inner = d.create(outer, NodeKind::Frame, "Inner", 0.0, 0.0, 160.0, 120.0).unwrap(); + let n = d.get_mut(inner).unwrap(); + (n.fills, n.blend) = (vec![blended("FFFF00", 1.0, BlendMode::Multiply)], BlendMode::PassThrough); + let pix = render(&d); + assert!(near(px(&pix, 100, 100), [247, 248, 0], 3), "{:?} with {} effects", px(&pix, 100, 100), effects.len()); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7d8e3a314..ce4a3ac8c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -302,6 +302,7 @@ fn render_one(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Opti magnified_image_pixels: opts.magnified_image_pixels, under: None, time: 0.0, + casting: false, bounds: &bounds, }; let xf = view.transform(); @@ -337,6 +338,7 @@ fn nodes_into(doc: &Document, ids: &[NodeId], view: &View, pix: &mut Pixmap, tim magnified_image_pixels: false, under, time, + casting: false, bounds: &bounds, }; // 0, but inside an exporter's [`at_layer_depth`] its depth: one cap for both (#1082). diff --git a/crates/render/src/lod_tests.rs b/crates/render/src/lod_tests.rs index d7cd983c9..fad6e5b02 100644 --- a/crates/render/src/lod_tests.rs +++ b/crates/render/src/lod_tests.rs @@ -180,6 +180,7 @@ fn exports_never_use_lod() { magnified_image_pixels: false, under: None, time: 0.0, + casting: false, bounds: &bounds, }; let parent = d.world_transform(p); diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index f86f9e774..a5669eb00 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -63,6 +63,7 @@ pub fn cell_pixmap(doc: &Document, pt: &PatternPaint, w: f64, h: f64, scale: f64 magnified_image_pixels: false, under: None, time, + casting: false, bounds: &bounds, }; let unrotated = src.transform.inverse(); diff --git a/crates/render/src/resample.rs b/crates/render/src/resample.rs index 9a194a14d..ab34a29f9 100644 --- a/crates/render/src/resample.rs +++ b/crates/render/src/resample.rs @@ -4,17 +4,19 @@ //! aliased, and a copy scaled down first then shifted a fraction of a pixel comes out blurred). //! Past its edges the image extends its edge pixels, as the pattern it replaces does. -use tiny_skia::{IntRect, Pixmap, Transform}; +use tiny_skia::{IntRect, Pixmap, Rect, Transform}; -/// The most weights the two passes may work through (device pixels times the image pixels each -/// averages), so one huge image shown small doesn't hold up an export: past it the image is -/// sampled as before. +/// The most weights the two passes may work through (the image pixels each device column averages +/// times those each device row does), so one huge image shown small doesn't hold up an export: +/// past it the image is sampled as before. const MAX_WORK: u64 = 1 << 28; /// `src` (premultiplied) as it shows over device area `area` under `m` (image pixels → device), -/// averaged per device pixel; its pixel (0, 0) lies at the area's top-left. `None` unless `m` is -/// axis-aligned and makes the image smaller along both axes. -pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect) -> Option { +/// averaged per device pixel; its pixel (0, 0) lies at the area's top-left. Each pixel averages +/// only the part of it inside `clip` (the shape the image fills, in device pixels), so where the +/// shape's edge cuts a pixel, its antialiasing alone fades it (once, not again for the image). +/// `None` unless `m` is axis-aligned and makes the image smaller along both axes. +pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect, clip: Rect) -> Option { let (sx, sy) = (f64::from(m.sx), f64::from(m.sy)); let (tx, ty) = (f64::from(m.tx), f64::from(m.ty)); let straight = m.kx.abs() < 1e-6 && m.ky.abs() < 1e-6; @@ -23,48 +25,39 @@ pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect) -> Option } let (sw, sh) = (src.width() as usize, src.height() as usize); let (dw, dh) = (area.width() as usize, area.height() as usize); - let cols = spans(area.x(), dw, tx, sx, sw); - let rows = spans(area.y(), dh, ty, sy, sh); - // Only the image rows some device row reads are averaged across. - let (r0, r1) = rows.iter().fold((usize::MAX, 0), |(a, b), s| (a.min(s.first), b.max(s.first + s.weights.len()))); - let r1 = r1.min(sh); - if r0 >= r1 { - return None; - } + let cols = spans(area.x(), dw, (clip.left().into(), clip.right().into()), tx, sx, sw)?; + let rows = spans(area.y(), dh, (clip.top().into(), clip.bottom().into()), ty, sy, sh)?; let work = |s: &[Span]| s.iter().map(|s| s.weights.len() as u64).sum::(); - if work(&cols).saturating_mul((r1 - r0) as u64).saturating_add(work(&rows).saturating_mul(dw as u64)) > MAX_WORK { + if work(&cols).saturating_mul(work(&rows)) > MAX_WORK { return None; } + let _held = crate::layer_budget::Held::take(area.width(), area.height(), 1)?; + let mut out = Pixmap::new(area.width(), area.height())?; let data = src.data(); - // Across: each image row in use, averaged into the device columns. - let mut across = vec![[0.0_f32; 4]; (r1 - r0) * dw]; - for (r, out) in (r0..r1).zip(across.chunks_mut(dw)) { - let row = data.get(r * sw * 4..(r + 1) * sw * 4)?; - for (c, o) in cols.iter().zip(out.iter_mut()) { - for (k, w) in c.weights.iter().enumerate() { - let px = row.get((c.first + k) * 4..(c.first + k) * 4 + 4)?; - for (acc, v) in o.iter_mut().zip(px) { - *acc += w * f32::from(*v); + // Each device row: the image rows it covers, each averaged across into the device columns + // and weighted in (only one device row of scratch, whatever the image's size). + let mut acc = vec![[0.0_f32; 4]; dw]; + for (y, s) in rows.iter().enumerate() { + acc.iter_mut().for_each(|a| *a = [0.0; 4]); + for (k, wy) in s.weights.iter().enumerate() { + let r = s.first + k; + let row = data.get(r * sw * 4..(r + 1) * sw * 4)?; + for (c, o) in cols.iter().zip(acc.iter_mut()) { + for (j, wx) in c.weights.iter().enumerate() { + let px = row.get((c.first + j) * 4..(c.first + j) * 4 + 4)?; + let w = wx * wy; + for (a, v) in o.iter_mut().zip(px) { + *a += w * f32::from(*v); + } } } } - } - // Down: the device rows from those. - let mut out = Pixmap::new(area.width(), area.height())?; - for (y, s) in rows.iter().enumerate() { - for x in 0..dw { - let mut acc = [0.0_f32; 4]; - for (k, w) in s.weights.iter().enumerate() { - let px = across.get((s.first + k - r0) * dw + x)?; - for (a, v) in acc.iter_mut().zip(px) { - *a += w * v; - } - } - let to = |v: f32| v.round().clamp(0.0, 255.0) as u8; - let alpha = to(acc[3]); - let dst = out.data_mut().get_mut((y * dw + x) * 4..(y * dw + x) * 4 + 4)?; + let to = |v: f32| v.round().clamp(0.0, 255.0) as u8; + let line = out.data_mut().get_mut(y * dw * 4..(y + 1) * dw * 4)?; + for (dst, a) in line.chunks_exact_mut(4).zip(&acc) { + let alpha = to(a[3]); // Premultiplied: no channel above the alpha, whatever rounding did. - dst.copy_from_slice(&[to(acc[0]).min(alpha), to(acc[1]).min(alpha), to(acc[2]).min(alpha), alpha]); + dst.copy_from_slice(&[to(a[0]).min(alpha), to(a[1]).min(alpha), to(a[2]).min(alpha), alpha]); } } Some(out) @@ -77,31 +70,39 @@ struct Span { } /// For `n` device pixels from `start`, the image pixels each covers along an axis where image -/// pixel `u` lies at `t + u * s` (device): the overlap of each with the pixel, as a share of the -/// pixel's width in image pixels. What lies past the image's `len` pixels counts as its edge -/// pixel. -fn spans(start: i32, n: usize, t: f64, s: f64, len: usize) -> Vec { - let last = len.saturating_sub(1); - (0..n) +/// pixel `u` lies at `t + u * s` (device): the overlap of each with the part of the pixel inside +/// `clip` (device; all of it when none is), as a share of that part. What lies past the image's +/// `len` pixels counts as its edge pixel. `None` for an empty image. +fn spans(start: i32, n: usize, clip: (f64, f64), t: f64, s: f64, len: usize) -> Option> { + let last = len.checked_sub(1)?; + let spans = (0..n) .map(|i| { let d = f64::from(start) + i as f64; - let (a, b) = ((d - t) / s, (d + 1.0 - t) / s); + let (d0, d1) = (d.max(clip.0), (d + 1.0).min(clip.1)); + let (d0, d1) = if d1 > d0 { (d0, d1) } else { (d, d + 1.0) }; + let (a, b) = ((d0 - t) / s, (d1 - t) / s); let (a, b) = (a.min(b), a.max(b)); let total = b - a; let clamp = |u: f64| u.clamp(0.0, last as f64) as usize; let (first, end) = (clamp(a.floor()), clamp(b.ceil() - 1.0)); let mut weights = vec![0.0_f32; end - first + 1]; - // Each image pixel's own overlap; what lies before the image goes to the first and - // past it to the last. - let mut u = a.floor(); - while u < b { - let w = (b.min(u + 1.0) - a.max(u)) / total; - if let Some(slot) = weights.get_mut(clamp(u) - first) { - *slot += w as f32; + // What lies before the image goes to its first pixel and past it to its last, each + // in one share; each image pixel in between takes its own overlap. + let mut add = |at: usize, w: f64| { + if let Some(slot) = at.checked_sub(first).and_then(|k| weights.get_mut(k)) { + *slot += (w.max(0.0) / total) as f32; } + }; + add(first, b.min(0.0) - a); + add(end, b - a.max(len as f64)); + let (lo, hi) = (a.max(0.0), b.min(len as f64)); + let mut u = lo.floor(); + while u < hi { + add(u as usize, hi.min(u + 1.0) - lo.max(u)); u += 1.0; } Span { first, weights } }) - .collect() + .collect(); + Some(spans) } diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index fc84c12cc..1503698be 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1056,7 +1056,8 @@ fn truncate_layout(out: &mut TextLayout, finish: &LayoutFinish<'_>) { let gend = out.lines.last().map(|l| l.glyph_end).unwrap_or(0); out.glyphs.truncate(gend); out.truncated = true; - out.height = out.lines.last().map_or(0.0, bottom); + // Rounded up as the self-sizing box is (cap-height trimmed text ends at its baseline). + out.height = out.lines.last().map_or(0.0, |l| if trim { l.baseline } else { box_px(l.top + l.height) }); } } if out.truncated { diff --git a/crates/text/src/metrics_tests.rs b/crates/text/src/metrics_tests.rs index 213b122bf..4f01d2411 100644 --- a/crates/text/src/metrics_tests.rs +++ b/crates/text/src/metrics_tests.rs @@ -73,6 +73,19 @@ fn pixel_line_heights_keep_their_fraction() { } } +/// Cut to its box's height, the text keeps a whole-pixel height too (one line of 22.5 is 23). +#[test] +fn text_cut_to_its_height_keeps_a_whole_pixel_height() { + let Some(f) = face() else { return }; + let mut t = text("Ag\nAg", &f, 17.0); + t.style.line_height = LineHeight::Pixels(22.5); + t.auto_resize = figcraft_doc::TextAutoResize::Truncate; + let l = layout(&t, Some(200.0), Some(30.0)); + assert_eq!(l.lines.len(), 1); + assert_eq!(l.height, l.height.ceil(), "one line of 22.5 px"); + assert!(l.height > 22.5); +} + #[test] fn advances_sit_on_a_grid_of_1024_per_em() { let Some(f) = face() else { return }; From e26b0aa2238dfa97bcaa5d4f4ebaf20a04ebc9ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Sun, 22 Nov 2026 10:40:18 +0100 Subject: [PATCH 10/14] M3: second review round for export framing, blend-through and budgets - Text painted only through its runs' fills counts for export framing. - A hidden layer inside a pass-through frame no longer makes it draw straight onto the canvas. - The scratch surface for plus lighter and plus darker comes from the layer budget; refused, the paint draws in tiny-skia's nearest mode. - Averaging an image shown smaller bounds the weight setup before working it out, and reserves its output first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/doc/src/node.rs | 8 +++++--- crates/render/src/draw.rs | 9 ++++++++- crates/render/src/export_framing_tests.rs | 19 +++++++++++++++++++ crates/render/src/resample.rs | 8 +++++++- 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 144ca4101..6a0ba7517 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -784,12 +784,14 @@ impl Node { self.board.as_ref().is_some_and(crate::BoardItem::is_atom) } - /// Whether this layer puts nothing on the canvas: no visible fill (its own or a vector - /// region's), stroke or effect and no children (a placeholder box whose image was taken out, + /// Whether this layer puts nothing on the canvas: no visible fill (its own, a vector + /// region's or a text run's), stroke or effect and no children (a placeholder box whose image was taken out, /// an empty frame). pub fn draws_nothing(&self) -> bool { + let shows = |f: &Option>| f.as_deref().is_some_and(|f| f.iter().any(|p| p.visible)); let region_fill = match &self.kind { - NodeKind::Vector { network } => network.regions.iter().any(|r| r.fills.as_deref().is_some_and(|f| f.iter().any(|p| p.visible))), + NodeKind::Vector { network } => network.regions.iter().any(|r| shows(&r.fills)), + NodeKind::Text(t) => shows(&t.style.fills) || t.runs.iter().any(|r| shows(&r.style.fills)), _ => false, }; self.children.is_empty() diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 1bdf7f2fd..07c162b4c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -242,8 +242,13 @@ fn paint_each( .bounds() .transform(ts_transform(xf)) .and_then(|b| int_rect(Rect::new(b.left().into(), b.top().into(), b.right().into(), b.bottom().into()), (pix.width(), pix.height()))); - let Some(mut alone) = area.and_then(|r| Pixmap::new(r.width(), r.height())) else { continue }; let Some(r) = area else { continue }; + // Past the layer budget, the paint draws in the nearest mode tiny-skia has instead. + let held = crate::layer_budget::Held::take(r.width(), r.height(), 1); + let Some(mut alone) = held.as_ref().and_then(|_| Pixmap::new(r.width(), r.height())) else { + pix.fill_path(path, &paint, rule, ts_transform(xf), mask); + continue; + }; let t = ts_transform(Affine::translate((-f64::from(r.x()), -f64::from(r.y()))) * xf); alone.fill_path(path, &tiny_skia::Paint { blend_mode: tiny_skia::BlendMode::SourceOver, ..paint }, rule, t, None); crate::paint::composite(pix, (r.x(), r.y()), &alone, 1.0, p.blend); @@ -942,6 +947,8 @@ fn blends_through(doc: &Document, n: &Node, backdrop: bool) -> bool { } paints_blend(n) || doc.subtree(n.id).iter().skip(1).filter_map(|c| doc.node(*c)).any(|c| match c.blend { + // A hidden layer draws nothing (nor do the layers inside it). + _ if !c.visible => false, BlendMode::Normal => false, // Its paints blend with what lies under it too. BlendMode::PassThrough => paints_blend(c), diff --git a/crates/render/src/export_framing_tests.rs b/crates/render/src/export_framing_tests.rs index bf0c3e63d..c1b19a416 100644 --- a/crates/render/src/export_framing_tests.rs +++ b/crates/render/src/export_framing_tests.rs @@ -98,3 +98,22 @@ fn a_fitted_image_shown_smaller_fades_the_shapes_edge_once() { assert!((ink(0) - 255.0 * 0.75).abs() < 4.0, "the first pixel, three quarters covered, holds {}", ink(0)); assert!(ink(1) > 250.0, "the next, inside, holds {}", ink(1)); } + +/// Text painted only through its runs' fills draws something, so it counts for the export. +#[test] +fn text_painted_by_its_runs_counts_for_the_export() { + let (mut d, p) = page(); + let mut td = figcraft_doc::TextData::new("Hi"); + td.runs = vec![figcraft_doc::StyleRun { + start: 0, + end: 2, + style: figcraft_doc::TextStyle { fills: Some(vec![Paint::solid(Color::BLACK)]), ..td.style.clone() }, + }]; + let t = d.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 40.0, 20.0).unwrap(); + let n = d.get_mut(t).unwrap(); + n.fills.clear(); + assert!(!n.draws_nothing()); + let NodeKind::Text(td) = &mut n.kind else { panic!("not text") }; + td.runs.clear(); + assert!(n.draws_nothing(), "without the runs' fills, nothing"); +} diff --git a/crates/render/src/resample.rs b/crates/render/src/resample.rs index ab34a29f9..481b8e7e8 100644 --- a/crates/render/src/resample.rs +++ b/crates/render/src/resample.rs @@ -25,13 +25,19 @@ pub(crate) fn area_averaged(src: &Pixmap, m: Transform, area: IntRect, clip: Rec } let (sw, sh) = (src.width() as usize, src.height() as usize); let (dw, dh) = (area.width() as usize, area.height() as usize); + // Bounded before any weight is worked out: each device pixel covers at most 1 / s + 2 image + // pixels along an axis, however wide the area a caller asks for. + let setup = |n: usize, s: f64| (n as f64) * (1.0 / s.abs() + 2.0); + if setup(dw, sx) + setup(dh, sy) > MAX_WORK as f64 { + return None; + } + let _held = crate::layer_budget::Held::take(area.width(), area.height(), 1)?; let cols = spans(area.x(), dw, (clip.left().into(), clip.right().into()), tx, sx, sw)?; let rows = spans(area.y(), dh, (clip.top().into(), clip.bottom().into()), ty, sy, sh)?; let work = |s: &[Span]| s.iter().map(|s| s.weights.len() as u64).sum::(); if work(&cols).saturating_mul(work(&rows)) > MAX_WORK { return None; } - let _held = crate::layer_budget::Held::take(area.width(), area.height(), 1)?; let mut out = Pixmap::new(area.width(), area.height())?; let data = src.data(); // Each device row: the image rows it covers, each averaged across into the device columns From 0a6d3220bb2d82a48d3fb3dcba293f89d14da41d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jind=C5=99ich=20=C5=A0ar=C5=A1on?= Date: Sun, 29 Nov 2026 10:45:42 +0100 Subject: [PATCH 11/14] M3: fill_with without the mask no caller passes, and without lint allows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012eBDgsvRwsSRpWeWrzabVY --- crates/render/src/draw.rs | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 29ea4dcdd..1a13dd496 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -183,19 +183,7 @@ fn averaged_when_shrunk(prep: Prepared, path: &tiny_skia::Path, xf: Affine, limi /// coloured backdrop, a plus-lighter or luminosity fill over a translucent one, come out the /// same with or without effects on the shape); a pass-through frame's paints blend with the /// backdrop too. -#[allow(clippy::too_many_arguments)] -fn fill_with( - pix: &mut Pixmap, - path: &tiny_skia::Path, - paints: &[Paint], - w: f64, - h: f64, - xf: Affine, - rule: FillRule, - ctx: &Ctx, - mask: Option<&Mask>, - isolate: bool, -) { +fn fill_with(pix: &mut Pixmap, path: &tiny_skia::Path, paints: &[Paint], w: f64, h: f64, xf: Affine, rule: FillRule, ctx: &Ctx, isolate: bool) { let blended = |p: &Paint| p.visible && p.opacity > 0.0 && !matches!(p.blend, BlendMode::Normal | BlendMode::PassThrough); if isolate && paints.iter().any(blended) { let area = path @@ -210,15 +198,14 @@ fn fill_with( let at = Affine::translate((-f64::from(r.x()), -f64::from(r.y()))) * xf; paint_each(&mut alone, path, paints, w, h, at, rule, ctx, None); let pp = PixmapPaint::default(); - pix.draw_pixmap(r.x(), r.y(), alone.as_ref(), &pp, Transform::identity(), mask); + pix.draw_pixmap(r.x(), r.y(), alone.as_ref(), &pp, Transform::identity(), None); return; } } - paint_each(pix, path, paints, w, h, xf, rule, ctx, mask); + paint_each(pix, path, paints, w, h, xf, rule, ctx, None); } /// Paint `paints` over `path` onto `pix`, each by its own blend mode. -#[allow(clippy::too_many_arguments)] fn paint_each( pix: &mut Pixmap, path: &tiny_skia::Path, @@ -1191,7 +1178,7 @@ fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft path.apply_affine(frame.inverse()); let Some(tp) = ts_path(&path) else { continue }; let rule = if region.winding == figcraft_doc::WindingRule::EvenOdd { FillRule::EvenOdd } else { FillRule::Winding }; - fill_with(pix, &tp, paints, pw, ph, xf * frame, rule, ctx, None, isolates_paints(n)); + fill_with(pix, &tp, paints, pw, ph, xf * frame, rule, ctx, isolates_paints(n)); } } } @@ -1202,7 +1189,7 @@ fn fill_outline(ctx: &Ctx, pix: &mut Pixmap, n: &Node, paints: &[Paint], path: & let under = fill_to_stroke_middle(n, path, rule); let (path, rule) = under.as_ref().map_or((path, rule), |(p, r)| (&**p, *r)); if let Some(tp) = ts_path(path) { - fill_with(pix, &tp, paints, n.width, n.height, xf, rule, ctx, None, isolates_paints(n)); + fill_with(pix, &tp, paints, n.width, n.height, xf, rule, ctx, isolates_paints(n)); } } @@ -1277,7 +1264,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, for path in keys.iter().filter_map(|k| by_style.get(k)) { let s = stroke_area(n, path, true); if let Some(ts) = ts_path(&s) { - fill_with(pix, &ts, &n.strokes, w, h, gxf, stroke_rule(n, true), ctx, None, isolates_paints(n)); + fill_with(pix, &ts, &n.strokes, w, h, gxf, stroke_rule(n, true), ctx, isolates_paints(n)); } } } @@ -1316,7 +1303,7 @@ fn draw_content(ctx: &Ctx, pix: &mut Pixmap, n: &Node, xf: Affine, depth: usize, if let Some(g) = geom { let area = stroke_area(n, &g, closed); if let Some(tp) = ts_path(&area) { - fill_with(pix, &tp, &n.strokes, w, h, xf, stroke_rule(n, closed), ctx, None, isolates_paints(n)); + fill_with(pix, &tp, &n.strokes, w, h, xf, stroke_rule(n, closed), ctx, isolates_paints(n)); } } } From ff3bcfd2a63773061fba8c246ec1edcab9d3779d Mon Sep 17 00:00:00 2001 From: Livio Sidler <94077193+LS254@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:23:05 +0100 Subject: [PATCH 12/14] M8, #2736: a soft shadow under an opaque gradient is cast from the outline, as under an opaque colour --- crates/render/src/outline_shadow_tests.rs | 32 +++++++++++++++++++++++ crates/render/src/shadow.rs | 15 ++++++++--- docs/gaps.md | 4 +++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/render/src/outline_shadow_tests.rs b/crates/render/src/outline_shadow_tests.rs index d803c636f..75b5f2bb9 100644 --- a/crates/render/src/outline_shadow_tests.rs +++ b/crates/render/src/outline_shadow_tests.rs @@ -88,6 +88,20 @@ fn a_shadow_blurred_widely_looks_as_the_one_cast_from_the_layers_pixels() { } } +/// A card filled with a gradient of opaque colours casts the shadow its pixels would. +#[test] +fn a_shadow_under_an_opaque_gradient_looks_as_the_one_cast_from_the_layers_pixels() { + let mut c = card(true); + shadow_of(&mut c, |s| s.color = Color { a: 0.8, ..Color::BLACK }); + c.doc.get_mut(c.card).unwrap().fills = fade(1.0); + for scale in [1.0, 4.0, 9.3] { + let (new, old) = both(&c, &corner(scale)); + assert!(darkest(&new) < 200, "a shadow shows at {scale}"); + let d = furthest(&corner(scale), &new, &old); + assert!(d <= 4, "at {scale}: {d} apart"); + } +} + #[test] fn bands_and_one_piece_draw_the_same_wide_shadow() { let mut c = card(true); @@ -132,6 +146,15 @@ fn layers_that_are_not_their_outline_cast_from_their_pixels() { c.doc.get_mut(c.card).unwrap().fills = vec![Paint::solid(Color { a: 0.5, ..Color::WHITE })]; c.card })); + // A gradient of opaque colours fills its outline as a colour does; one that fades doesn't. + assert!(caster(|c| { + c.doc.get_mut(c.card).unwrap().fills = fade(1.0); + c.card + })); + assert!(!caster(|c| { + c.doc.get_mut(c.card).unwrap().fills = fade(0.0); + c.card + })); // A child past the card's edge, or in the corner its rounding cuts off, casts a shadow too. assert!(!caster(|c| { let picture = c.doc.node(c.shape).unwrap().parent.unwrap(); @@ -163,6 +186,15 @@ fn layers_that_are_not_their_outline_cast_from_their_pixels() { })); } +/// A linear gradient from opaque black to black at alpha `to`. +fn fade(to: f32) -> Vec { + let mut g = figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK); + for (s, a) in g.stops.iter_mut().zip([1.0, to]) { + s.color.a = a; + } + vec![Paint::gradient(g)] +} + /// A rectangle with a dark shadow of `radius` and `spread`, drawn through `transform`. fn slab(transform: figcraft_geom::Affine, size: (f64, f64), radius: f64, spread: f64) -> (figcraft_doc::Document, NodeId) { let mut d = figcraft_doc::Document::new("slab"); diff --git a/crates/render/src/shadow.rs b/crates/render/src/shadow.rs index cd37cc681..5ff9d320b 100644 --- a/crates/render/src/shadow.rs +++ b/crates/render/src/shadow.rs @@ -299,13 +299,22 @@ fn inner_from(mut big: Pixmap, pad: u32, cover: &Pixmap, scale: f64, s: &Shadow) Some(out) } -/// Whether `p` paints every pixel it covers at full alpha: a visible, opaque solid colour. +/// Whether `p` paints every pixel it covers at full alpha: a visible, opaque solid colour or a +/// gradient of opaque colours. fn opaque(p: &Paint) -> bool { - p.visible && p.opacity >= 1.0 && p.blend == figcraft_color::BlendMode::Normal && matches!(&p.kind, PaintKind::Solid { color } if color.a >= 1.0) + p.visible + && p.opacity >= 1.0 + && p.blend == figcraft_color::BlendMode::Normal + && match &p.kind { + PaintKind::Solid { color } => color.a >= 1.0, + PaintKind::Gradient(g) => !g.stops.is_empty() && g.stops.iter().all(|s| s.color.a >= 1.0), + _ => false, + } } /// The outlines node `n`'s drop shadows are cast from when its pixels are those outlines, filled: -/// a shape or a clipping frame whose paints are opaque colours and that has no effect that moves +/// a shape or a clipping frame whose paints are opaque colours or gradients of them and that has no +/// effect that moves /// its pixels. Such a shadow needs none of the layer's pixels, so it is drawn only where it /// shows and blurred at the resolution its radius needs ([`outline_drop_shadow`]), not from a /// copy of the layer reaching past the view. `None`: the shadows come from the layer's pixels. diff --git a/docs/gaps.md b/docs/gaps.md index c7d995a60..635059418 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -317,6 +317,10 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe all in or all out are copied or kept in one piece. A view inside four nested clipping frames at 1,933% on a 2× display (4112 × 2292 device pixels, release, one thread): 119 → 87 ms, a band of it 18 → 12 ms. +- **Landed (2026-11-29):** a gradient whose stops are all opaque counts as an opaque paint for + the entry below (#2736), so a soft shadow under a gradient-filled frame is cast from its + outline too. `zoomed_card_timings` with the card filled with such a gradient (release, one + thread, 4112 × 2292): 8 bands 3,950 → 130 ms, the slowest band 516 → 17 ms. - **Landed (2026-11-24):** a drop shadow of a shape or frame with opaque paints is cast from its outline: drawn only where it shows on the pixmap, and a blur of 8 device pixels or more is drawn smaller, blurred and scaled back up, on a grid that follows the shape (bands, patches and whole From 1cffe6e254d264167873917899f787932dde8d75 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 29 Nov 2026 18:30:29 +0700 Subject: [PATCH 13/14] render: a gradient whose handles collapse onto one line casts from its pixels Such a gradient prepares no shader and paints nothing, so its layer is not its outline: an outline-cast shadow would show under an invisible fill. --- crates/render/src/outline_shadow_tests.rs | 9 +++++++++ crates/render/src/shadow.rs | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/render/src/outline_shadow_tests.rs b/crates/render/src/outline_shadow_tests.rs index 75b5f2bb9..0968af5b2 100644 --- a/crates/render/src/outline_shadow_tests.rs +++ b/crates/render/src/outline_shadow_tests.rs @@ -155,6 +155,15 @@ fn layers_that_are_not_their_outline_cast_from_their_pixels() { c.doc.get_mut(c.card).unwrap().fills = fade(0.0); c.card })); + // Handles collapsed onto one line: the gradient draws nothing, so there's no outline to cast. + assert!(!caster(|c| { + let mut fills = fade(1.0); + if let figcraft_color::PaintKind::Gradient(g) = &mut fills[0].kind { + g.width = g.to; + } + c.doc.get_mut(c.card).unwrap().fills = fills; + c.card + })); // A child past the card's edge, or in the corner its rounding cuts off, casts a shadow too. assert!(!caster(|c| { let picture = c.doc.node(c.shape).unwrap().parent.unwrap(); diff --git a/crates/render/src/shadow.rs b/crates/render/src/shadow.rs index 5ff9d320b..7ba1e16ac 100644 --- a/crates/render/src/shadow.rs +++ b/crates/render/src/shadow.rs @@ -307,11 +307,18 @@ fn opaque(p: &Paint) -> bool { && p.blend == figcraft_color::BlendMode::Normal && match &p.kind { PaintKind::Solid { color } => color.a >= 1.0, - PaintKind::Gradient(g) => !g.stops.is_empty() && g.stops.iter().all(|s| s.color.a >= 1.0), + PaintKind::Gradient(g) => !g.stops.is_empty() && g.stops.iter().all(|s| s.color.a >= 1.0) && spans(g), _ => false, } } +/// Whether gradient `g`'s handles span an area: with all three on one line it draws nothing +/// ([`crate::paint::prepare`] gets no shader), so its layer isn't its outline. +fn spans(g: &figcraft_color::Gradient) -> bool { + let (a, b) = ((g.to.0 - g.from.0, g.to.1 - g.from.1), (g.width.0 - g.from.0, g.width.1 - g.from.1)); + (a.0 * b.1 - a.1 * b.0).abs() > 1e-9 +} + /// The outlines node `n`'s drop shadows are cast from when its pixels are those outlines, filled: /// a shape or a clipping frame whose paints are opaque colours or gradients of them and that has no /// effect that moves From a6920f0c5d43b64215b0c063603713ba4aa66c92 Mon Sep 17 00:00:00 2001 From: Livio Sidler <94077193+LS254@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:42:23 +0100 Subject: [PATCH 14/14] M8, #2736: the gradient card's test looks for the shadow under the card, not on it From the review of #2737: the card is black, so the darkest pixel of the view said nothing about a shadow. --- crates/render/src/outline_shadow_tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/render/src/outline_shadow_tests.rs b/crates/render/src/outline_shadow_tests.rs index 0968af5b2..56d600beb 100644 --- a/crates/render/src/outline_shadow_tests.rs +++ b/crates/render/src/outline_shadow_tests.rs @@ -95,9 +95,13 @@ fn a_shadow_under_an_opaque_gradient_looks_as_the_one_cast_from_the_layers_pixel shadow_of(&mut c, |s| s.color = Color { a: 0.8, ..Color::BLACK }); c.doc.get_mut(c.card).unwrap().fills = fade(1.0); for scale in [1.0, 4.0, 9.3] { - let (new, old) = both(&c, &corner(scale)); - assert!(darkest(&new) < 200, "a shadow shows at {scale}"); - let d = furthest(&corner(scale), &new, &old); + let v = corner(scale); + let (new, old) = both(&c, &v); + // Under the card, where only the shadow paints: the card itself is dark. + let from = (((CARD_BOTTOM - v.origin.1) * v.scale).ceil() as usize + 2) * v.width as usize * 4; + let under = new.data().get(from..).unwrap_or_default().as_chunks::<4>().0.iter().map(|c| c[0]).min().unwrap_or(255); + assert!(under < 200, "a shadow shows at {scale}"); + let d = furthest(&v, &new, &old); assert!(d <= 4, "at {scale}: {d} apart"); } }