mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 22:09:28 +00:00
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:
+37
-27
@@ -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
@@ -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 }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
@@ -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"}}},
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
@@ -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 +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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
Reference in New Issue
Block a user