Merge branch 'main' of https://github.com/storytold/figcraft into codex/fig-import-confirmation

# Conflicts:
#	crates/engine/src/cmd/file/load.rs
#	docs/file-format-parity.md
This commit is contained in:
Timo Klerx committed 2026-11-29 13:33:22 +01:00
commit 41ee2d7e92
32 files changed
+1318 -102

No files matched your search

+37 -27
View File
@@ -56,6 +56,14 @@ use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
/// A walk for [`Document::world_render_bounds_with`]: how many more nodes it may visit, and how it
/// measures each.
struct Walk<'a> {
left: std::cell::Cell<usize>,
own: &'a dyn Fn(&Node, Affine) -> Option<Rect>,
grow: &'a dyn Fn(&Node, Rect) -> Rect,
}
/// 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;
@@ -784,53 +792,55 @@ 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<Rect> {
self.world_render_bounds_with(id, &|n, world| n.own_paint_bounds(world))
self.world_render_bounds_with(id, &|n, world| Some(n.own_paint_bounds(world)), &|n, kids| n.grow_by_effects(kids))
}
/// [`Document::world_render_bounds`] with what each node paints itself (its children aside)
/// measured by `own` from the node and its world transform, for a caller that measures it more
/// closely than [`Node::own_paint_bounds`] (an export measures the stroke itself).
pub fn world_render_bounds_with(&self, id: NodeId, own: &dyn Fn(&Node, Affine) -> Rect) -> Option<Rect> {
/// [`Document::world_render_bounds`] measured by the caller, for one that measures more
/// closely than [`Node::own_paint_bounds`] (an export measures the stroke itself and frames
/// shadows by their blur radius): `own` gives the page area a node paints itself under its
/// world transform (its children aside), `None` for one that doesn't count, and `grow` what a
/// group's or an unclipped frame's effects add round its children's area.
pub fn world_render_bounds_with(
&self,
id: NodeId,
own: &dyn Fn(&Node, Affine) -> Option<Rect>,
grow: &dyn Fn(&Node, Rect) -> Rect,
) -> Option<Rect> {
// 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)), own)
let left = std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8));
self.render_bounds_at(id, 0, &Walk { left, own, grow })
}
fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell<usize>, own_paint: &dyn Fn(&Node, Affine) -> Rect) -> Option<Rect> {
fn render_bounds_at(&self, id: NodeId, depth: usize, walk: &Walk) -> Option<Rect> {
let n = self.node(id)?;
let own = own_paint(n, self.world_transform(id));
let visit = left.get();
left.set(visit.saturating_sub(1));
let own = (walk.own)(n, self.world_transform(id));
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);
return own;
}
Some(match (self.children_render_bounds(n, depth + 1, left, own_paint), &n.kind) {
(Some(kids), NodeKind::Group) => n.grow_by_effects(kids),
match (self.children_render_bounds(n, depth + 1, walk), &n.kind) {
(Some(kids), NodeKind::Group) => Some((walk.grow)(n, 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), _) => {
let kids = (walk.grow)(n, kids);
Some(own.map_or(kids, |o| o.union(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<usize>,
own_paint: &dyn Fn(&Node, Affine) -> Rect,
) -> Option<Rect> {
fn children_render_bounds(&self, n: &Node, depth: usize, walk: &Walk) -> Option<Rect> {
let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask);
let mut out: Option<Rect> = 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, own_paint)).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, own_paint))
.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) {
+46 -3
View File
@@ -802,6 +802,23 @@ 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, 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<Vec<Paint>>| 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| shows(&r.fills)),
NodeKind::Text(t) => shows(&t.style.fills) || t.runs.iter().any(|r| shows(&r.style.fills)),
_ => 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
/// skipped when rendering and hit testing.
pub fn hides_contents(&self) -> bool {
@@ -908,9 +925,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();
@@ -924,7 +953,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 {
@@ -941,12 +970,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))
@@ -1038,6 +1077,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 }
+1
View File
@@ -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;
@@ -249,3 +249,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<String>)> = Vec::new();
for d in doc.subtree(inst).into_iter().skip(1) {
let Some(n) = doc.node(d) else { continue };
let mut inherited: Vec<String> = 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);
}
}
}
+5 -4
View File
@@ -356,13 +356,14 @@ fn remeasure_text(doc: &mut Document, remeasure: Vec<NodeId>) {
}
}
/// 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<String, Value>) -> BTreeMap<String, Value> {
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
}
+43 -17
View File
@@ -150,6 +150,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, false));
}
let mut loaded = figcraft_format::load_bytes_with_versions(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
@@ -268,11 +269,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<std::sync::Arc<figcraft_text::fontdb::Face>> {
let mut cache: std::collections::BTreeMap<(String, String), Option<std::sync::Arc<figcraft_text::fontdb::Face>>> =
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(|| {
@@ -281,30 +311,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<NodeId> = 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);
}
}
}
@@ -412,6 +436,7 @@ fn load_fig_with_budget(bytes: &[u8], name: &str, higher: bool) -> Option<Result
|mut imported| {
link_instances(&mut imported.doc);
installed_fonts_first();
optical_size_follows_text_size(&mut imported.doc);
(figcraft_format::Loaded { issues: imported.warnings, ..imported.doc.into() }, imported.retryable)
},
))
@@ -721,6 +746,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.
+51
View File
@@ -1412,6 +1412,57 @@ pub(crate) fn bake_stale_scales(doc: &mut Document, root: NodeId) {
/// 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<NodeId> = 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<NodeId>>, include: impl Fn(&str) -> bool) {
use super::lists::{BoundList, list_binding};
if doc.variables.variables.is_empty() {
+4 -3
View File
@@ -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}));
@@ -0,0 +1,39 @@
//! A variable font's optical size follows the text size in Figma, also for a named style (the
//! glyph advances `.fig` files save show it: SF Pro Regular at 17 px is the 17 cut, at 20 px the
//! 20 cut). A `.fig` import carries the size as the text's `opsz` value, so FigCraft draws the
//! same cut instead of the named instance's.
use serde_json::json;
use crate::Session;
use figcraft_doc::NodeKind;
/// The `opsz` value of the text layer called `name`.
fn opsz(doc: &figcraft_doc::Document, name: &str) -> Option<f64> {
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));
}
+6
View File
@@ -360,6 +360,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;
@@ -690,6 +692,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;
@@ -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");
}
@@ -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<u64> = [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);
}
+10
View File
@@ -1408,7 +1408,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)),
@@ -1421,6 +1423,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(),
+1 -1
View File
@@ -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"}}},
+2 -1
View File
@@ -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));
+16 -1
View File
@@ -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/<name>`, 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"
+190 -17
View File
@@ -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:
@@ -151,7 +155,68 @@ 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>) {
/// 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(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,
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
/// 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.
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
.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())));
// 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(), None);
return;
}
}
paint_each(pix, path, paints, w, h, xf, rule, ctx, None);
}
/// Paint `paints` over `path` onto `pix`, each by its own blend mode.
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();
// An image picks its copy by the direction shown the most device pixels (a layer can be squeezed).
let [a, b, c, d, ..] = xf.as_coeffs();
@@ -160,15 +225,21 @@ fn fill_with(pix: &mut Pixmap, path: &tiny_skia::Path, paints: &[Paint], w: f64,
let k = if matches!(p.kind, PaintKind::Image(_)) { stretch } else { scale };
let Some(prep) = prepare_at(p, w, h, k, 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 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()
.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);
@@ -855,6 +926,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.
@@ -867,7 +940,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);
}
}
};
@@ -877,7 +951,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.
@@ -887,7 +962,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);
}
}
}
@@ -895,14 +970,47 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
if !casts {
layer_effects(ctx, &mut layer, n, id, lxf);
}
// Drop shadows go under the layer, in effect-list order.
// Drop shadows go under the layer, in effect-list order. They 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). 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));
if let Some(outlines) = &cast_outline {
let cover = shadow::hiding_cover(ctx.doc, n);
for e in n.effects.iter().filter(|e| e.visible) {
if let EffectKind::DropShadow(s) = &e.kind
&& let Some((sh, at)) = shadow::outline_drop_shadow(outlines, cover.as_deref().unwrap_or(outlines), s, xf, ctx.scale, (pw, ph), op)
{
composite(pix, at, &sh, op, s.blend);
let shadows: Vec<_> = n
.effects
.iter()
.filter(|e| e.visible)
.filter_map(|e| match &e.kind {
EffectKind::DropShadow(s) => {
shadow::outline_drop_shadow(outlines, cover.as_deref().unwrap_or(outlines), s, xf, ctx.scale, (pw, ph), op)
.map(|sh| (sh, s.blend))
}
_ => None,
})
.collect();
// Blended, they go into a group as large as the area they cover.
let area = shadows
.iter()
.map(|((sh, (x, y)), _)| (*x, *y, *x + sh.width() as i32, *y + sh.height() as i32))
.reduce(|a, b| (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)));
let grouped = area.filter(|_| blended).and_then(|(x0, y0, x1, y1)| {
let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
let held = crate::layer_budget::Held::take(w, h, 1)?;
Some((held, Pixmap::new(w, h)?, (x0, y0)))
});
match grouped {
Some((_held, mut g, (x0, y0))) => {
for ((sh, (x, y)), blend) in &shadows {
composite(&mut g, (x - x0, y - y0), sh, 1.0, *blend);
}
composite(pix, (x0, y0), &g, op, BlendMode::Normal);
}
None => {
for ((sh, at), blend) in &shadows {
composite(pix, *at, sh, op, *blend);
}
}
}
} else {
@@ -916,13 +1024,21 @@ 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);
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)
{
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.
@@ -932,9 +1048,60 @@ fn draw_layer(ctx: &Ctx, pix: &mut Pixmap, n: &Node, parent_xf: Affine, depth: u
}
layer_effects(ctx, &mut layer, n, id, lxf);
}
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).
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;
}
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),
_ => 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)
|| 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
/// `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<Pixmap> {
@@ -982,6 +1149,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)>;
@@ -1005,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);
fill_with(pix, &tp, paints, pw, ph, xf * frame, rule, ctx, isolates_paints(n));
}
}
}
@@ -1016,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);
fill_with(pix, &tp, paints, n.width, n.height, xf, rule, ctx, isolates_paints(n));
}
}
@@ -1091,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);
fill_with(pix, &ts, &n.strokes, w, h, gxf, stroke_rule(n, true), ctx, isolates_paints(n));
}
}
}
@@ -1130,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);
fill_with(pix, &tp, &n.strokes, w, h, xf, stroke_rule(n, closed), ctx, isolates_paints(n));
}
}
}
+120
View File
@@ -0,0 +1,120 @@
//! 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 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::{Pixmap, encode_png, export_bounds, render_node};
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);
}
/// A 160 × 160 white image with one black column of pixels (x = 81), on a 100 × 100 layer at
/// `(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(160, 160).unwrap();
for (i, c) in img.data_mut().chunks_exact_mut(4).enumerate() {
let v = if i % 160 == 81 { 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: 160, height: 160 });
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, f)
}
#[test]
fn an_image_shown_smaller_exports_the_average_of_what_each_pixel_covers() {
// Shown at 0.625 of its size, the line is 0.625 of a pixel wide, at x + 50.625. The pixels it
// crosses share its black by how much of it each covers (sampled at pixel centres instead, it
// comes out a whole pixel dark or too faint). Above half its size: the image itself is
// averaged, not a smaller copy (see `downscaled_image_tests`).
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 ink = |x: usize| 255.0 - f64::from(pix.data()[(50 * w + x) * 4]);
let (l, r) = (at + 50.625, at + 51.25);
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));
}
/// 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.into()), "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");
}
+124
View File
@@ -0,0 +1,124 @@
//! 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<Paint> {
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<Paint>, effects: Vec<Effect>) -> 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<Paint>, effects: Vec<Effect>) -> 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));
}
/// 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());
}
}
+19 -2
View File
@@ -422,6 +422,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)) {
@@ -431,12 +447,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;
}
});
}
+20 -6
View File
@@ -20,6 +20,7 @@ mod layer_budget;
pub mod lod;
pub mod paint;
pub mod pattern;
mod resample;
pub mod retained;
pub mod shadow;
@@ -337,6 +338,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();
@@ -372,6 +374,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).
@@ -429,16 +432,23 @@ pub fn raster_bounds(doc: &Document, id: NodeId) -> Option<Rect> {
}
/// The page-space rectangle a node exports: a clipping frame's box (plus its own effects), else
/// everything it paints. Each layer counts the fill and stroke outlines it draws (see
/// [`drawn_bounds`]), so a stroke inside its frame leaves the export the frame's size; the
/// renderer's own bounds ([`Document::world_render_bounds`]) only bound how far a stroke can reach.
/// everything it paints, as the reference tool's exports frame it. Each layer counts the fill
/// and stroke outlines it draws (see [`drawn_bounds`]), so a stroke inside its frame leaves the
/// export the frame's size; the renderer's own bounds ([`Document::world_render_bounds`]) only
/// bound how far a stroke can reach. Drop shadows count as far as their blur radius (see
/// [`figcraft_doc::Node::own_export_bounds`]), and a layer inside that draws nothing (no visible
/// paint, effect or children) doesn't count.
pub fn export_bounds(doc: &Document, id: NodeId) -> Option<Rect> {
doc.world_render_bounds_with(id, &|n, world| drawn_bounds(doc, n, world).unwrap_or_else(|| n.own_paint_bounds(world)))
let own = |n: &figcraft_doc::Node, world: Affine| {
(!n.draws_nothing()).then(|| drawn_bounds(doc, n, world).unwrap_or_else(|| n.own_export_bounds(world)))
};
// A layer that draws nothing at all exports at its box.
doc.world_render_bounds_with(id, &own, &|n, kids| n.grow_by_export_effects(kids)).or_else(|| doc.world_render_bounds(id))
}
/// The page area `n` paints itself under `world` (its children aside), measured on the outlines
/// it draws: its fill's and its stroke's (joins, caps and alignment as drawn), grown by its
/// effects. A dashed stroke counts as a solid one too, so where the dashes fall doesn't change the
/// effects (as an export frames them). A dashed stroke counts as a solid one too, so where the dashes fall doesn't change the
/// size, and as its dashes, whose square ends can stand out past it round a curve. `None` where
/// those outlines don't cover what it paints: text (glyphs and their
/// strokes), a layer without an outline of its own, and drop shadows whose spread grows the
@@ -469,7 +479,7 @@ fn drawn_bounds(doc: &Document, n: &figcraft_doc::Node, world: Affine) -> Option
.into_iter()
.flatten()
.reduce(|a, b| a.union(b))?;
Some(n.grow_by_effects(drawn))
Some(n.grow_by_export_effects(drawn))
}
/// Rasterise one node at `scale` (export). Transparent background.
@@ -721,8 +731,12 @@ mod effect_order_tests;
#[cfg(test)]
mod effects_behaviour_tests;
#[cfg(test)]
mod export_framing_tests;
#[cfg(test)]
mod fig_round_trip_tests;
#[cfg(test)]
mod fill_blend_tests;
#[cfg(test)]
mod gif_tests;
#[cfg(test)]
mod glass_bench_tests;
+1
View File
@@ -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);
+45
View File
@@ -88,6 +88,24 @@ 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 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");
}
}
#[test]
fn bands_and_one_piece_draw_the_same_wide_shadow() {
let mut c = card(true);
@@ -132,6 +150,24 @@ 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
}));
// 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();
@@ -163,6 +199,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<Paint> {
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");
+9 -1
View File
@@ -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);
+1
View File
@@ -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();
+114
View File
@@ -0,0 +1,114 @@
//! 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, Rect, Transform};
/// 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. 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<Pixmap> {
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);
// 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::<u64>();
if work(&cols).saturating_mul(work(&rows)) > MAX_WORK {
return None;
}
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
// 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);
}
}
}
}
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(a[0]).min(alpha), to(a[1]).min(alpha), to(a[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<f32>,
}
/// 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 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<Vec<Span>> {
let last = len.checked_sub(1)?;
let spans = (0..n)
.map(|i| {
let d = f64::from(start) + i as f64;
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];
// 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();
Some(spans)
}
+19 -3
View File
@@ -299,13 +299,29 @@ 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) && 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 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.
+17 -8
View File
@@ -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.
@@ -1048,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 {
@@ -1105,7 +1114,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 +1279,9 @@ pub fn layout(text: &TextData, box_width: Option<f64>, box_height: Option<f64>)
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;
+35 -3
View File
@@ -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,39 @@ 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);
}
}
}
/// 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 };
+6 -3
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (`figcraft-cli export`, `convert` and `run --out` take `--strict`, which writes nothing when the `.fig`, `.penpot` or Android Vector Drawable writer would leave content out (#2384); `.fig` export writes one fill outline per winding rule for vectors whose areas use both; `.jam` import: connectors on the page come in as native board connectors attached to the layers they join (#1808); text in a well-known UI or code family that isn't installed draws in a close stand-in in its own style instead of the default sans (#1237); layers pasted from another app drop bindings to variables the file lacks and keep the values they showed (#2524); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB inLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **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; `figcraft-cli export`, `convert` and `run --out` take `--strict`, which writes nothing when the `.fig`, `.penpot` or Android Vector Drawable writer would leave content out (#2384); `.fig` export writes one fill outline per winding rule for vectors whose areas use both; `.jam` import: connectors on the page come in as native board connectors attached to the layers they join (#1808); text in a well-known UI or code family that isn't installed draws in a close stand-in in its own style instead of the default sans (#1237); layers pasted from another app drop bindings to variables the file lacks and keep the values they showed (#2524); `.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regLine truncated
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). 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. On 64-bit builds, a decoded-value limit or a truncated layer tree can offer a one-time retry with higher budgets within the existing caps (#574). This can use significantly more memory. A retry after a partial import opens a new tab and keeps thLine truncated
| `.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 filLine truncated
| `.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 showcaseLine truncated
| `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (see [boards-parity](boards-parity.md)); connectors drawn on the page as native board connectors attached to the layers they join, so they follow them when moved (#1808; one with a label or inside a frame stays a frame or vector; an elbowed connector keeps the path it was saved with, #1910); tables, stamps, code blocks and the like come in as frames with their text, with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — |
| `.deck` (Slides) | native to other Figma products | no | no | out of scope | — |
| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — |
| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings (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/<key>`, 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) |
@@ -211,6 +211,9 @@ scales and empty-style clears; they have not been checked in other software.
| 2026-11-28 | minor | #2384: `figcraft-cli export --strict` (also `convert` and `run --out`) refuses to write a `.fig`, `.penpot` or Android Vector Drawable file when the writer reports anything left out or changed: exit 1, the reasons on the error line, no file written or replaced (a folder of drawables only once none of its files leaves anything out). `--strict` with a format that reports nothing, or on a drawable with `--vd-compat ignore`, is a usage error. `.fig` export writes a vector whose filled areas use both winding rules as one fill outline per rule, so other readers fill each area as the network does; the warning about using the first area's rule is gone. Image adjustments, list spacing, hanging punctuation and lists, and vertical trim were already written. OpenType features, variables' publishing, code syntax and inheritance settings, prototype device settings and text styles on part of a text stay left out with their warnings: the `.fig` import (`craft_fig`'s mapping) doesn't read them back yet. |
| 2026-11-24 | minor | M8: SVG, PNG, PDF and Android Vector Drawable exports were bigger than what they show around strokes on lines, vectors and polygons. The export took its size from the renderer's bounds, which leave room for a stroke's mitre at the miter limit (4 × the weight on a vector) whatever its corners, so a 24 × 24 icon frame whose outlined strokes stay inside it exported at 26 × 26 to 30 × 25, its content moved off the frame's origin. The export now measures each layer's fill and stroke outlines as drawn (joins, caps and alignment included, a mitre only where a corner keeps one; a dashed stroke as a solid one too, so where the dashes fall doesn't change the size), and grows that by the layer's effects; text and drop shadows with a spread keep the renderer's bounds. The renderer's own bounds are unchanged. Tests: `export_bounds_tests` (3). Numbers unchanged |
| 2026-11-23 | patch | M7: Save as to another file left the tab showing the old name unless that name was Untitled or the old file's own name (#935). So a file opened from an import (`.fig`, `.penpot`, `.sketch`), which carries its source's name and has no file yet, kept that name after being saved as `Other.figcraft`, and so did a file renamed here. Now saving to another file always names the document, its tab and the saved file's stored name after the new file, as a desktop app's document window does. Saving to the same file keeps a name given here, so a name with characters a file name can't hold (`aa: design system`) stays until Save as. Test: `save_format_tests::saving_to_another_file_names_the_document_after_it`. |
| 2026-11-20 | 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. |
| 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. |
+4
View File
@@ -338,6 +338,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
+6 -2
View File
@@ -1,6 +1,6 @@
# FigCraft parity with Figma
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-28 · **Change:** minor (M8, #2664: an image shown at half its pixels or fewer, on the canvas and in exports, blends its fine detail instead of showing moiré; M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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-28 · **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; M8, #2664: an image shown at half its pixels or fewer, on the canvas and in exports, blends its fine detail instead of showing moiré; M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); 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 |
@@ -656,6 +656,10 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
| 2026-11-28 | patch | M8, #2664: an image fill shown at half its pixels or fewer (a 0.5x export, the canvas zoomed out) turned fine detail, a knitted sweater, into strong moiré bands: the image was sampled straight at the small size, a few source pixels per output pixel, with nothing averaging the rest. Wherever an image shows at half its size or less, it is now drawn from a copy averaged down to under twice the size it shows at (the image halved, or the canvas's smaller copy halved, cached with the decoded images), so each output pixel blends every pixel it covers. Every smaller copy now averages the finished pixels, premultiplied and after the image's adjustments: averaging first darkened the edges of transparent areas and changed the colours of adjusted images (exposure and the rest clamp), which the canvas's smaller copies did before. A copy is placed where the image itself would be, so a thin image keeps its box (each side of a copy rounds apart), and an image squeezed on one axis (by its crop or its layer) keeps the pixels its other axis shows. Images shown larger draw as before (magnified pixels too). Canvas, PNG, JPG and WebP exports and the paints PDF export rasterises (images PDF and SVG embed are scaled by the viewer); tiled images still draw from the image itself. Tests: `downscaled_image_tests::an_image_shown_at_half_its_size_or_less_blends_its_fine_detail_evenly` (fails on main), `an_adjusted_image_shown_smaller_averages_its_adjusted_pixels`, `a_transparent_image_shown_smaller_keeps_its_colour`, `a_thin_image_shown_smaller_still_fills_its_box`, `a_crop_stretching_one_axis_keeps_the_pixels_that_axis_shows` and `a_layer_squeezed_on_one_axis_keeps_the_pixels_its_other_axis_shows`. |
| 2026-11-27 | patch | M8, #2631: a drop shadow under a layer with an outside stroke (text especially, a black stroke over a black shadow) showed a light outline along the layer's edge wherever that edge lay over the shadow, in a letter's counters too. Hiding the shadow behind the layer cut the layer's share of each anti-aliased edge pixel out of the shadow, then the layer's own edge pixel drew that share again over what was left, counting the edge twice. The shadow now keeps, at each pixel, its part outside the layer, scaled by what the layer lets through there, so an opaque edge sits on a full shadow and a translucent fill still hides it. What the shadow is cast from and hidden behind follows what the layer fills (the fill out to the middle of an opaque inside or outside stroke, #2635), and stroked text casts and hides its shadows by its glyph outlines and stroke too (it fell back to its pixels). Canvas, PNG and PDF; SVG text with a stroke now cuts its shadow out behind it as other layers do. Test: `shadow_silhouette_tests::a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge` (fails on main). |
| 2026-11-27 | patch | M8, #2635: a stroked layer showed a thin light line along the outer edge of an inside stroke (the fill under the stroke's anti-aliased edge showed through it), and what lies behind showed between an outside stroke and the fill. Where the stroke hides what is under it (its top paint an opaque solid colour, normal blend, one weight all round, no dashes, width profile or brush), the fill now reaches the middle of the stroke, so neither edge has the fill or the background showing through: rectangles, frames and ellipses by their inset or grown outline, other shapes and text by their outline less or plus the centred stroke. Translucent, gradient and image strokes and even-odd outlines fill as before. Test: `stroke_fringe_tests::an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge` (fails on main). |
| 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). Since #2673, an image shown at half its size or less is averaged from its filtered copy, not the image itself. 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 |
| 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 |