M6: Merge main into prototype action export

This commit is contained in:
Timo Klerx committed 2026-11-15 23:50:18 +01:00
commit 659f7a176c
103 files changed
+3590 -6773

No files matched your search

+2 -2
View File
@@ -16,8 +16,8 @@ concurrency:
jobs:
sonarcloud:
# Pin the coverage setup that checks out this repo's pinned craft-i18n data.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@ea24c9c24e1997238334182160f60e602e5bce32
# Pin the coverage setup that provisions test data and fetches locked dependencies before offline metadata tests.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@5008f8cd1b011b35eed223a7d058d7a8e9075ef6
with:
# The shared coverage archive's shards omit the CLI executable used by integration tests.
# Run this repository's suite in one instrumented job and provide its pinned test data.
Generated
+74 -9
View File
@@ -253,7 +253,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -1011,6 +1011,43 @@ name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
[[package]]
name = "craft-fig"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
dependencies = [
"craft-figma-rest",
"craft-kiwi",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)",
"flate2",
"kurbo",
"ruzstd",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-figcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee"
dependencies = [
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee)",
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "craft-figma-rest"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -1076,6 +1113,11 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-kiwi"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
[[package]]
name = "craft-menu"
version = "0.1.0"
@@ -1186,6 +1228,26 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -1376,7 +1438,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1718,7 +1780,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -1935,6 +1997,9 @@ dependencies = [
name = "figcraft-format"
version = "0.18.1"
dependencies = [
"craft-fig",
"craft-figcraft-format",
"craft-figma-rest",
"figcraft-doc",
"figcraft-layout",
"figcraft-pathops",
@@ -3885,7 +3950,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4581,7 +4646,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4638,7 +4703,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5207,10 +5272,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6334,7 +6399,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
+7
View File
@@ -56,6 +56,13 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae
# Where the settings live: the suite's folder rules, portable mode included (craft-libs).
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
# The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of
# a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share
# types, so they stay on one rev; they share none with the crates above.
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" }
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
thiserror = "2"
+1 -1
View File
@@ -112,7 +112,7 @@ fn pages_can_be_inserted_onto_a_page_less_base() {
assert!(d.pages.is_empty() && d.node_count() == 0);
let p = Node::new(
NodeId(C3 | 1),
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default() },
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default(), opening: false },
"P",
0.0,
0.0,
+39 -16
View File
@@ -152,7 +152,7 @@ fn near_path(path: &BezPath, p: Point, dist: f64) -> bool {
/// boolean groups are hit where their `result` is.
pub fn hit_leaf(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
let p = doc.node(page)?;
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None).filter(|_| !masked_out(doc, p, *c, pt)))
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, HitOpts::default()).filter(|_| !masked_out(doc, p, *c, pt)))
}
/// Whether child `c` of `parent` is masked at `pt`: a visible mask below it (the nearest mask
@@ -175,7 +175,7 @@ fn covers(doc: &Document, id: NodeId, n: &Node, pt: Point, depth: usize) -> bool
/// Like [`hit_leaf`], but only within layer `root` (it included).
pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
hit_rec(doc, root, pt, tol, 0, result, None)
hit_rec(doc, root, pt, tol, 0, result, None, HitOpts::default())
}
/// [`hit_leaf`] (or [`hit_in`] for a `root` that isn't a page) in outline mode: shapes are hit
@@ -185,8 +185,8 @@ pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolRes
/// when it shows them, and every layer on the edge of its box when it shows object bounds.
pub fn hit_outlines(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, also: OutlineHits) -> Option<NodeId> {
match doc.node(root) {
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also))),
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also)),
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also), HitOpts::default())),
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also), HitOpts::default()),
}
}
@@ -204,13 +204,30 @@ fn on_box_edge(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64) -> boo
r.inflate(tol, tol).contains(lp) && !(r.width() > 2.0 * tol && r.height() > 2.0 * tol && r.inflate(-tol, -tol).contains(lp))
}
fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, also: Option<OutlineHits>) -> Option<NodeId> {
/// Options for the hit tests that the plain pick never sets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HitOpts {
/// Reach locked layers (and what a locked frame holds) too. A click, hover or marquee never
/// does; the Select layer list does.
pub locked: bool,
}
fn hit_rec(
doc: &Document,
id: NodeId,
pt: Point,
tol: f64,
depth: usize,
result: BoolResult,
also: Option<OutlineHits>,
opts: HitOpts,
) -> Option<NodeId> {
if depth > 512 {
return None;
}
let n = doc.node(id)?;
let outline = also.is_some();
if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked {
if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked && !opts.locked {
return None;
}
if let NodeKind::Section { contents_hidden: true } = n.kind {
@@ -228,7 +245,7 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result
return None;
}
for c in n.paint_order().rev() {
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also).filter(|_| !masked_out(doc, n, c, pt)) {
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also, opts).filter(|_| !masked_out(doc, n, c, pt)) {
return Some(h);
}
}
@@ -239,14 +256,20 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result
None
}
/// Every visible, unlocked layer under `pt` (page coordinates) with its depth below the page, in
/// layer-tree order (each layer before what it contains, the front-most first): what
/// "Select layer" in the context menu lists. Clip content is honoured; boolean groups (hit where
/// their `result` is) and sections with hidden contents count as one layer.
/// Every visible, unlocked layer under `pt`: [`layers_at_opts`] with the default options.
pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Vec<(NodeId, usize)> {
fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, out: &mut Vec<(NodeId, usize)>) {
layers_at_opts(doc, page, pt, tol, result, HitOpts::default())
}
/// Every visible layer under `pt` (page coordinates) with its depth below the page, in
/// layer-tree order (each layer before what it contains, the front-most first): what
/// "Select layer" in the context menu lists. Locked layers are left out unless `opts.locked`.
/// Clip content is honoured; boolean groups (hit where their `result` is) and sections with
/// hidden contents count as one layer.
pub fn layers_at_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Vec<(NodeId, usize)> {
fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, opts: HitOpts, out: &mut Vec<(NodeId, usize)>) {
let Some(n) = doc.node(id) else { return };
if !n.visible || n.locked || depth > 512 {
if !n.visible || n.locked && !opts.locked || depth > 512 {
return;
}
let clips = n.clip && n.kind.is_frame_like();
@@ -256,14 +279,14 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool
let at = out.len();
let whole = matches!(n.kind, NodeKind::BooleanOp { .. } | NodeKind::Section { contents_hidden: true });
if whole {
if hit_rec(doc, id, pt, tol, depth, result, None).is_some() {
if hit_rec(doc, id, pt, tol, depth, result, None, opts).is_some() {
out.push((id, depth));
}
return;
}
for c in n.paint_order().rev() {
let before = out.len();
rec(doc, c, pt, tol, depth + 1, result, out);
rec(doc, c, pt, tol, depth + 1, result, opts, out);
if out.len() > before && masked_out(doc, n, c, pt) {
out.truncate(before);
}
@@ -276,7 +299,7 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool
if let Some(p) = doc.node(page) {
for c in p.children.iter().rev() {
let before = out.len();
rec(doc, *c, pt, tol, 0, result, &mut out);
rec(doc, *c, pt, tol, 0, result, opts, &mut out);
if out.len() > before && masked_out(doc, p, *c, pt) {
out.truncate(before);
}
+7 -2
View File
@@ -439,8 +439,13 @@ impl Document {
/// Add a page at the end.
pub fn add_page(&mut self, name: &str) -> NodeId {
let id = self.alloc_id();
let node =
Node::new(id, NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() }, name, 0.0, 0.0);
let node = Node::new(
id,
NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false },
name,
0.0,
0.0,
);
self.nodes.insert(id, Arc::new(node));
self.dirty.touch(id);
self.pages.push(id);
+1 -1
View File
@@ -312,7 +312,7 @@ impl Document {
let id = self.alloc_id();
let node = Node::new(
id,
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() },
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false },
STORE_NAME,
0.0,
0.0,
+4
View File
@@ -91,6 +91,10 @@ pub enum NodeKind {
flows: Vec<crate::proto::Flow>,
#[serde(default)]
prototype: crate::proto::PrototypeSettings,
/// The page chosen to open the file on for everyone (`page.setOpening`; at most one page):
/// saving writes it as the document's `current_page` instead of the page the saver was viewing.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
opening: bool,
},
Frame,
Group,
+33
View File
@@ -336,3 +336,36 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() {
set(&mut s, f, json!({"layout": null, "name": "Plain"}));
assert!(s.doc().unwrap().node(f).unwrap().layout.is_none());
}
#[test]
fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() {
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
let mut s = Session::new();
let f = al_frame(&mut s, json!({"gap": 10}));
let a = rect(&mut s, f, 20.0, 20.0, "#ff0000");
let b = rect(&mut s, f, 20.0, 20.0, "#00ff00");
let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
let (before_a, before_b) = (at(&s, a), at(&s, b));
assert_eq!(before_b.x0, 30.0, "the layout placed the second one after the first");
let doc = s.doc().unwrap();
assert!(!can_align(doc, &[b]), "Align is greyed out for one child of the frame");
assert!(align_blocked_by_auto_layout(doc, &[b]), "because its frame places it");
for cmd in ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"] {
s.execute(cmd, &json!({"ids": [b]})).unwrap();
assert_eq!((at(&s, a), at(&s, b)), (before_a, before_b), "{cmd} leaves the layout alone");
}
}
#[test]
fn an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it() {
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
let mut s = Session::new();
let f = al_frame(&mut s, json!({}));
let kid = rect(&mut s, f, 20.0, 20.0, "#ff0000");
set(&mut s, kid, json!({"absolute": true}));
let doc = s.doc().unwrap();
assert!(can_align(doc, &[kid]));
assert!(!align_blocked_by_auto_layout(doc, &[kid]));
s.execute("align.right", &json!({"ids": [kid]})).unwrap();
assert_eq!(s.doc().unwrap().world_bounds(kid).unwrap().x1, 200.0);
}
+47 -3
View File
@@ -6,12 +6,16 @@
//! [`INSET_PX`] in, so it can be grabbed at radius 0). Dragging it along the bisector sets the
//! radius of every corner; with Alt, only that corner of a rectangle or frame (the documentation
//! is silent on Alt).
//! - **Count**: a polygon's or star's sits on its first point clockwise from the top; dragging it
//! sets the count from the pointer's angle about the centre, measured clockwise from the top
//! point: `round(360 / angle)`, clamped to 3 to 60 (measured in Figma's web app, 2026-11-12; a
//! polygon's maximum wasn't read).
//! - **Ratio**: a star's sits on its first inner point; dragging it towards or away from the
//! centre sets the inner radius as a share of the outer one.
//!
//! Positions are in page coordinates and work for rotated and flipped layers at any zoom; the
//! handles hide on layers smaller than [`MIN_PX`] on screen. The Move tool's gesture (`tools.rs`)
//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`), one
//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`, `pointCount`), one
//! undo step per drag.
use figcraft_doc::{Document, Node, NodeId, NodeKind};
@@ -20,18 +24,22 @@ use serde::Serialize;
use serde_json::{Map, Value, json};
/// One shape handle: a corner's radius (corner index: tl, tr, br, bl; 0 for a polygon's or
/// star's top point) or a star's ratio.
/// star's top point), a star's ratio or a polygon's or star's point count.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum ShapeHandle {
Radius { corner: usize },
Ratio,
Count,
}
/// Layers smaller than this on screen (either side, in pixels) show no shape handles.
pub const MIN_PX: f64 = 48.0;
/// How far in from its corner a handle sits at least (screen pixels).
pub const INSET_PX: f64 = 10.0;
/// The fewest and most points the Count handle sets (a star's range in the help center).
const COUNT_MIN: f64 = 3.0;
const COUNT_MAX: f64 = 60.0;
/// How near the pointer must be to pick a handle (screen pixels).
const HIT_PX: f64 = 6.0;
@@ -113,6 +121,34 @@ fn ratio_point(n: &Node, count: u32, ratio: f64) -> Option<Point> {
figcraft_geom::star_points(n.width, n.height, count, ratio).get(1).copied()
}
/// The Count handle (local): a polygon's vertex 1 or a star's outer point 1, the first clockwise
/// from the top.
fn count_point(n: &Node) -> Option<Point> {
match n.kind {
NodeKind::Polygon { count } => figcraft_geom::polygon_points(n.width, n.height, count).get(1).copied(),
NodeKind::Star { count, inner_ratio } => figcraft_geom::star_points(n.width, n.height, count, inner_ratio).get(2).copied(),
_ => None,
}
}
/// The count a pointer at local point `q` sets: `round(360 / angle)` for its clockwise angle from
/// the top about the centre, on the unit circle the shape's box maps from; finite for any `q`.
fn count_at(n: &Node, q: Point) -> Option<f64> {
let (rx, ry) = (n.width / 2.0, n.height / 2.0);
if rx.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || ry.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
return None;
}
let (x, y) = (q.x / rx - 1.0, q.y / ry - 1.0);
// On the centre there is no direction (atan2 of two zeros would read as 180 degrees): treat it
// as no angle, the most points.
if x.hypot(y) < 1e-9 {
return Some(COUNT_MAX);
}
let angle = x.atan2(-y).rem_euclid(std::f64::consts::TAU).to_degrees();
let count = (360.0 / angle.max(1e-9)).round();
count.is_finite().then(|| count.clamp(COUNT_MIN, COUNT_MAX))
}
/// The shape handles of the selection at `zoom` (screen pixels per page unit): each handle and
/// where it is (page coordinates).
pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [f64; 2])> {
@@ -128,6 +164,9 @@ pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [
{
out.push((ShapeHandle::Ratio, pt(p)));
}
if let Some(p) = count_point(n) {
out.push((ShapeHandle::Count, pt(p)));
}
out
}
@@ -160,6 +199,10 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) ->
};
Some(Map::from_iter([(key.to_string(), json!(r))]))
}
ShapeHandle::Count => {
count_point(n)?;
Some(Map::from_iter([("pointCount".to_string(), json!(count_at(n, q)?))]))
}
ShapeHandle::Ratio => {
let NodeKind::Star { count, .. } = n.kind else { return None };
// Along the inner point's ray, measured on the unit circle the star's box maps from.
@@ -172,11 +215,12 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) ->
}
}
/// The live readout while dragging `h` of `id`: the corner's radius, or the star's ratio in percent.
/// The live readout while dragging `h` of `id`: the corner's radius, the star's ratio in percent or the point count.
pub fn value(doc: &Document, id: NodeId, h: ShapeHandle) -> Option<f64> {
let n = doc.node(id)?;
let v = match (h, &n.kind) {
(ShapeHandle::Ratio, NodeKind::Star { inner_ratio, .. }) => inner_ratio * 100.0,
(ShapeHandle::Count, NodeKind::Polygon { count }) | (ShapeHandle::Count, NodeKind::Star { count, .. }) => f64::from(*count),
(ShapeHandle::Radius { corner }, _) => corners(n).into_iter().nth(corner).map(|(c, r)| r.clamp(0.0, c.max_r))?,
_ => return None,
};
+3 -2
View File
@@ -586,8 +586,9 @@ pub struct ToolState {
/// Vector edit mode's pen: where the last press that started something new (no path being
/// drawn) was, and the undo depth before it, so a double-click there takes that edit back.
pub(crate) pen_press: Option<(Point, usize)>,
/// The Scale tool's anchor: column and row (0 start, 1 middle, 2 end) of the point of the
/// selection box that stays put (`tool.scaleAnchor`).
/// The Scale tool's origin: column and row (0 start, 1 middle, 2 end) of the point of the
/// selection box that stays put when the Scale field sets a factor (`tool.scaleAnchor`; the
/// centre, `(1, 1)`, until set). Handle drags ignore it and pivot on the opposite handle.
pub scale_anchor: (u8, u8),
/// The last drag move handled (a held button repeats it every frame).
pub(crate) last_move: Option<PointerEvent>,
+1 -1
View File
@@ -640,7 +640,7 @@ impl Session {
/// text included, children by the same factor whatever their constraints.
fn scale_drag(&mut self, ev: &PointerEvent, r: &ResizeStart, q: Point, guides: Vec<Guide>) -> Result<()> {
let (frame, w0, h0) = r.frame;
let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, self.tool.scale_anchor, ev.alt) else { return Ok(()) };
let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, ev.alt) else { return Ok(()) };
let nodes = r.nodes.clone();
let inv = frame.inverse();
// A layer's place in the box scales about the pivot; a negative factor turns it over.
+5 -13
View File
@@ -392,30 +392,22 @@ fn opposite(h: Handle) -> Handle {
}
/// The Scale tool's factor and pivot (in the box's axes) for dragging `handle` of a `w0`×`h0` box
/// to `q`. The pivot is the anchor point (`anchor`: column, row), or the opposite handle when the
/// anchor lies on the side being dragged, or the centre (`from_center`). Corners follow the axis
/// that moved the most; a negative factor flips. None when the box has no size to scale by.
pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, anchor: (u8, u8), from_center: bool) -> Option<(f64, Point)> {
/// to `q`. The pivot is the opposite handle's point, or the centre (`from_center`); the origin grid
/// never decides it (measured in Figma's web app, 2026-11-09). Corners follow the axis that moved
/// the most; a negative factor flips. None when the box has no size to scale by.
pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, from_center: bool) -> Option<(f64, Point)> {
const EPS: f64 = 1e-9;
if !(q.x.is_finite() && q.y.is_finite() && w0.is_finite() && h0.is_finite()) || matches!(handle, Handle::Rotate(_)) {
return None;
}
let h = handle_point(handle, w0, h0);
let anchor_pt = anchor_in_box(anchor, w0, h0);
// The axes the handle moves along.
let (ax_x, ax_y) = match handle {
Handle::Edge(0) | Handle::Edge(2) => (false, true),
Handle::Edge(_) => (true, false),
_ => (true, true),
};
let on_side = (ax_x && (anchor_pt.x - h.x).abs() < EPS) || (ax_y && (anchor_pt.y - h.y).abs() < EPS);
let pivot = if from_center {
Point::new(w0 / 2.0, h0 / 2.0)
} else if on_side {
handle_point(opposite(handle), w0, h0)
} else {
anchor_pt
};
let pivot = if from_center { Point::new(w0 / 2.0, h0 / 2.0) } else { handle_point(opposite(handle), w0, h0) };
let ratio = |on: bool, to: f64, from: f64, p: f64| (on && (from - p).abs() > EPS).then(|| (to - p) / (from - p));
let kx = ratio(ax_x, q.x, h.x, pivot.x);
let ky = ratio(ax_y, q.y, h.y, pivot.y);
+31 -44
View File
@@ -164,12 +164,27 @@ pub fn can_align(doc: &Document, ids: &[NodeId]) -> bool {
align_target(doc, &roots(doc, ids)).is_some()
}
/// Whether `ids` is one layer that its auto layout frame places: Figma greys out Align for it,
/// since the frame decides where it goes (measured in Figma's web app, 2026-11-12).
pub fn align_blocked_by_auto_layout(doc: &Document, ids: &[NodeId]) -> bool {
matches!(roots(doc, ids).as_slice(), [id] if in_auto_layout_flow(doc, *id))
}
/// Whether the layer sits in an auto layout frame and takes part in its flow (not absolutely positioned).
fn in_auto_layout_flow(doc: &Document, id: NodeId) -> bool {
let Some(n) = doc.node(id) else { return false };
!n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
}
/// What `roots` align to: one layer to its parent frame, several to their combined bounds.
fn align_target(doc: &Document, roots: &[NodeId]) -> Option<Rect> {
match roots {
[] => None,
[id] => {
let parent = doc.node(*id)?.parent.filter(|pp| !doc.node(*pp).is_some_and(Node::is_page))?;
if in_auto_layout_flow(doc, *id) {
return None;
}
Some(doc.world_bounds(parent).unwrap_or_default())
}
_ => Some(doc.bounds_of(roots).unwrap_or_default()),
@@ -223,53 +238,25 @@ fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
ok()
}
/// Tidy up: snap the selection into a grid of rows/columns with even spacing.
/// Tidy up: even the gaps of a row, a column or a grid, keeping the order and sizes (see
/// `selection::tidy`). Nothing moves, and no undo step is added, when it is unavailable.
fn tidy(s: &mut Session, p: &Value) -> Result<Value> {
let ids = req_targets("arrange.tidy", s, p)?;
let spacing = num(p, "spacing");
if spacing.is_some_and(|v| !v.is_finite() || v.abs() > 1_000_000.0) {
return Err(bad("arrange.tidy", "spacing out of range"));
}
let snap = s.ds()?.view.snap_pixel;
let moves = crate::tidy::tidy_moves(s.doc()?, &ids, spacing, snap);
if moves.is_empty() {
return ok();
}
if moves.iter().any(|(_, dx, dy)| !dx.is_finite() || !dy.is_finite()) {
return Err(bad("arrange.tidy", "non-finite result"));
}
let doc = s.doc_mut()?;
let ids = roots(doc, &ids);
let mut items: Vec<(NodeId, Rect)> = ids.iter().filter_map(|i| doc.world_bounds(*i).map(|b| (*i, b))).collect();
if items.len() < 2 {
return ok();
}
// Group into rows by vertical centre overlap.
items.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0));
let mut rows: Vec<Vec<(NodeId, Rect)>> = Vec::new();
for it in items {
match rows.last_mut() {
Some(row) if row.iter().any(|(_, b)| it.1.center().y < b.y1 && it.1.center().y > b.y0) => row.push(it),
_ => rows.push(vec![it]),
}
}
let all: Vec<Rect> = rows.iter().flatten().map(|(_, b)| *b).collect();
let (Some(origin), maxw, maxh) = (
all.iter().copied().reduce(|a, b| a.union(b)),
all.iter().map(Rect::width).fold(0.0, f64::max),
all.iter().map(Rect::height).fold(0.0, f64::max),
) else {
return ok();
};
let gap = num(p, "spacing").unwrap_or_else(|| {
// Keep the average existing horizontal gap (min 10).
10f64.max(
rows.iter()
.filter(|r| r.len() > 1)
.map(|r| {
(r.iter().map(|(_, b)| b.x1).fold(f64::MIN, f64::max)
- r.iter().map(|(_, b)| b.x0).fold(f64::MAX, f64::min)
- r.iter().map(|(_, b)| b.width()).sum::<f64>())
/ (r.len() - 1) as f64
})
.fold(0.0, f64::max),
)
});
for (ri, row) in rows.iter_mut().enumerate() {
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0));
for (ci, (id, b)) in row.iter().enumerate() {
let x = origin.x0 + ci as f64 * (maxw + gap);
let y = origin.y0 + ri as f64 * (maxh + gap);
move_world(doc, *id, x - b.x0, y - b.y0)?;
}
for (id, dx, dy) in moves {
move_world(doc, id, dx, dy)?;
}
ok()
}
+113 -11
View File
@@ -3,7 +3,7 @@
use std::collections::{BTreeMap, BTreeSet};
use figcraft_doc::{Document, Effect, ExportSetting, ImageData, LayoutGrid, Node, NodeId, NodeKind};
use figcraft_geom::Affine;
use figcraft_geom::{Affine, Point};
use serde_json::{Map, Value, json};
use super::{CommandSpec, ok};
@@ -207,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"select.layersAt",
"Layers at a point",
"{x, y (page coordinates)} → {layers: [{id, name, type, depth}]} (every layer under the point, front-most first; what the context menu's Select layer lists)",
"{x, y (page coordinates)} → {layers: [{id, name, type, depth, locked}]} (every layer under the point, locked ones too, front-most first; locked is true when the layer or an ancestor is locked; what the context menu's Select layer lists)",
false,
layers_at
),
@@ -616,7 +616,8 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
/// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the
/// copies are the selection, Duplicate places the next copies as far from them as they are from
/// their sources, measured then: so moving the copies first sets the step.
/// their sources, measured then (their move and turn, not their size): so moving or turning the
/// copies first sets the step.
#[derive(Clone, Debug)]
pub struct Duplicated {
pub sources: Vec<NodeId>,
@@ -629,9 +630,12 @@ impl Duplicated {
!self.copies.is_empty() && set(&self.copies) == set(sel)
}
/// The page offset from the sources to the copies, if both are still there and the copies move
/// freely (an auto layout places its own).
fn offset(&self, doc: &Document) -> Option<(f64, f64)> {
/// The step from the sources to the copies, if both are still there and the copies move freely
/// (an auto layout places its own): the mean move of the copies' own centres in the page frame
/// (less what a size change shifts them by), and the turn every copy has over its source (zero
/// unless they all agree, or when a flip differs). A turn is not counted as a move, whether each
/// copy turned about its own centre or the copies turned together about their shared centre.
fn step(&self, doc: &Document) -> Option<Step> {
let free = self
.copies
.iter()
@@ -639,19 +643,109 @@ impl Duplicated {
if !free || self.sources.iter().chain(&self.copies).any(|i| !doc.contains(*i)) {
return None;
}
let (a, b) = (doc.bounds_of(&self.sources)?, doc.bounds_of(&self.copies)?);
let d = (b.x0 - a.x0, b.y0 - a.y0);
(d.0.is_finite() && d.1.is_finite() && (d.0 != 0.0 || d.1 != 0.0)).then_some(d)
// A flip reads as a half turn and was not measured: never repeat a turn across one.
let flips_differ = self
.sources
.iter()
.zip(&self.copies)
.any(|(s, c)| figcraft_geom::is_flipped(doc.world_transform(*s)) != figcraft_geom::is_flipped(doc.world_transform(*c)));
let turns: Vec<f64> = self
.sources
.iter()
.zip(&self.copies)
.map(|(s, c)| {
let d = figcraft_geom::rotation_degrees(doc.world_transform(*c)) - figcraft_geom::rotation_degrees(doc.world_transform(*s));
let d = d.rem_euclid(360.0);
if d > 180.0 { d - 360.0 } else { d }
})
.collect();
let angle = match turns.first() {
Some(first) if !flips_differ && turns.iter().all(|t| (t - first).abs() < 1e-6) => *first,
_ => 0.0,
};
// Per pair, where the copy's own centre is, less what its size change moved that centre by
// (a growing edge shifts it, in the source's frame), and where the source's centre is.
let mut pairs = Vec::new();
for (s, c) in self.sources.iter().zip(&self.copies) {
let (sn, cn) = (doc.node(*s)?, doc.node(*c)?);
let (sw, cw) = (doc.world_transform(*s), doc.world_transform(*c));
let (ps, pc) = (sw * Point::new(sn.width / 2.0, sn.height / 2.0), cw * Point::new(cn.width / 2.0, cn.height / 2.0));
let grow = Point::new((cn.width - sn.width) / 2.0, (cn.height - sn.height) / 2.0);
let shift_in = |x: Affine| x * grow - x * Point::ORIGIN;
// The order of a turn and a resize isn't recorded. A resize then a turn shifts the centre
// along the source's axes; a turn then a resize, along the copy's. Take the copy's only
// when it alone makes this pair's own move zero: a pure resize plus turn, either order,
// with no move must give no move. Otherwise keep the source's.
let (by_source, by_copy) = (pc - shift_in(sw), pc - shift_in(cw));
let still = |q: Point| (q.x - ps.x).hypot(q.y - ps.y) < 1e-6;
let corrected = if still(by_copy) && !still(by_source) { by_copy } else { by_source };
pairs.push((ps, corrected));
}
// The mean of the residuals, and whether they all agree (the copies fit that reading).
let fit = |res: &[(f64, f64)]| {
let n = res.len() as f64;
let mean = (res.iter().map(|m| m.0).sum::<f64>() / n, res.iter().map(|m| m.1).sum::<f64>() / n);
let agree = res.iter().all(|m| (m.0 - mean.0).hypot(m.1 - mean.1) < 1e-6);
(mean, agree)
};
// Reading A, each copy turned about its own centre: the residual is the move of its centre.
let each: Vec<(f64, f64)> = pairs.iter().map(|(ps, pc)| (pc.x - ps.x, pc.y - ps.y)).collect();
let (mut mv, each_fits) = fit(&each);
// Reading B, the copies turned together about the sources' centre (as a Rotate on several
// layers does): the residual is what is left once each source's centre is turned that way.
// The centre is `turn_centre`, never read from the copies: a turn about another point shifts
// every residual by the same vector, so where the copies are can't say which point they
// turned about. Such a turn reads as this one plus a move.
if angle != 0.0
&& pairs.len() > 1
&& !each_fits
&& let Some(c) = turn_centre(doc, &self.sources)
{
let together: Vec<(f64, f64)> = pairs
.iter()
.map(|(ps, pc)| {
let q = figcraft_geom::translation(figcraft_geom::rotate_about(Affine::translate(ps.to_vec2()), c, angle));
(pc.x - q.x, pc.y - q.y)
})
.collect();
let (m, together_fits) = fit(&together);
if together_fits {
mv = m;
}
}
let (dx, dy) = mv;
let step = Step { dx, dy, angle };
(step.dx.is_finite() && step.dy.is_finite() && step.angle.is_finite() && (dx != 0.0 || dy != 0.0 || angle != 0.0)).then_some(step)
}
}
/// What Duplicate repeats: a move of the copies' centre in the page frame, then a turn about the
/// centre of the new copies. Size is not part of it.
#[derive(Clone, Copy, Debug)]
struct Step {
dx: f64,
dy: f64,
angle: f64,
}
/// Where several layers turn, for the step and for its repeat: the centre of their handle box
/// (`selection_box`), the point the Rotate handle and the rotate keys turn a selection about.
/// One layer: its own centre. Several: their bounds centre, or the centre of the box turned
/// with them when they share a rotation. `transform.rotate` without a pivot turns about the
/// bounds centre instead, so its turn of layers that share a rotation repeats as a turn plus
/// a move.
fn turn_centre(doc: &Document, ids: &[NodeId]) -> Option<Point> {
let q = crate::tools::selection_box(doc, ids)?;
Some(Point::new(q.iter().map(|c| c.x).sum::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 4.0))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let ids = req_targets("edit.duplicate", s, p)?;
let rename = s.prefs.rename_duplicates;
let explicit = num(p, "dx").is_some() || num(p, "dy").is_some();
let ds = s.ds()?;
let roots_now = z_sorted(&ds.doc, &roots(&ds.doc, &ids));
let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.offset(&ds.doc));
let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.step(&ds.doc));
let doc = s.doc_mut()?;
let ids = roots_now;
let mut out = Vec::new();
@@ -670,7 +764,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
_ => (0.0, 0.0),
};
match repeat {
Some((rx, ry)) => super::arrange::move_world(doc, nid, rx, ry)?,
Some(st) => super::arrange::move_world(doc, nid, st.dx, st.dy)?,
None => {
let nn = doc.get_mut(nid)?;
nn.transform = Affine::translate((dx, dy)) * nn.transform;
@@ -683,6 +777,14 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
}
out.push(nid);
}
// A repeated turn is about the new copies' centre: one layer's own, several layers' shared one.
if let Some(st) = repeat.filter(|st| st.angle != 0.0)
&& let Some(c) = turn_centre(doc, &out)
{
for nid in out.iter().copied() {
super::arrange::rotate_world(doc, nid, c, st.angle)?;
}
}
crate::library::count_inserted(doc, &out);
// Board connectors copied with what they join join the copies.
let map = crate::board::copy_map(doc, &ids, &out);
+6 -2
View File
@@ -8,9 +8,13 @@ pub(super) fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
let zoom = s.ds()?.view.zoom.max(1e-6);
let sel = s.selection();
let result = crate::booleans::result_outline(doc, &sel);
let layers: Vec<Value> = figcraft_doc::geometry::layers_at(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result))
let opts = figcraft_doc::geometry::HitOpts { locked: true };
let layers: Vec<Value> = figcraft_doc::geometry::layers_at_opts(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result), opts)
.into_iter()
.filter_map(|(id, depth)| doc.node(id).map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth})))
.filter_map(|(id, depth)| {
doc.node(id)
.map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth, "locked": crate::tools::locked_in(doc, id)}))
})
.collect();
Ok(json!({"layers": layers}))
}
+2 -1
View File
@@ -85,7 +85,8 @@ impl FileSnapshot {
/// files are from its folder.
fn encode_at(&self, path: Option<&str>) -> Result<Vec<u8>> {
let mut doc = (*self.doc).clone();
doc.current_page = Some(self.page);
let opening = doc.pages.iter().copied().find(|&p| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. })));
doc.current_page = Some(opening.unwrap_or(self.page));
if let Some(path) = path {
crate::library::relate_links(&mut doc, path);
}
+35 -3
View File
@@ -1,7 +1,7 @@
//! Pages.
use figcraft_doc::proto::Flow;
use figcraft_doc::{Guide, NodeId, NodeKind};
use figcraft_doc::{Document, Guide, NodeId, NodeKind};
use serde_json::{Value, json};
use super::{CommandSpec, ok};
@@ -109,8 +109,8 @@ pub fn specs() -> Vec<CommandSpec> {
// The copy keeps the page's colour, flows (pointing at the copied frames), prototype settings and guides.
let guides = doc.get(src)?.guides.clone();
doc.get_mut(np)?.guides = guides;
if let NodeKind::Page { background, flows, prototype } = doc.get(src)?.kind.clone()
&& let NodeKind::Page { background: b, flows: f, prototype: pr } = &mut doc.get_mut(np)?.kind
if let NodeKind::Page { background, flows, prototype, .. } = doc.get(src)?.kind.clone()
&& let NodeKind::Page { background: b, flows: f, prototype: pr, .. } = &mut doc.get_mut(np)?.kind
{
*b = background;
*f = flows
@@ -147,6 +147,38 @@ pub fn specs() -> Vec<CommandSpec> {
}
ok()
}),
spec!(
"page.setOpening",
"Set as opening page",
"{id?} (the page the file opens on, for everyone who opens or joins it; the current page when none is named)",
true,
|s, p| {
// A document property (#1817), so it syncs in a live session and undoes; nobody's
// own page moves (`page.select` is each viewer's).
let id = page_target(s, "page.setOpening", p)?;
if s.doc()?.is_divider(id) {
return Err(bad("page.setOpening", "a divider isn't a page to open on"));
}
let is_opening = |doc: &Document, p: NodeId| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. }));
if s.doc()?.current_page == Some(id) && is_opening(s.doc()?, id) {
// Already the opening page: nothing changes, so no undo step.
return ok();
}
let doc = s.doc_mut()?;
doc.current_page = Some(id);
// The flag lives on the page node (so it syncs with the node's kind): one page has it.
for page in doc.pages.clone() {
let want = page == id;
if is_opening(doc, page) != want
&& let NodeKind::Page { opening, .. } = &mut doc.get_mut(page)?.kind
{
*opening = want;
}
}
settle(s, "page.setOpening")?;
ok()
}
),
spec!("page.list", "List pages", "{}", false, |s, _| {
let doc = s.doc()?;
let cur = s.page()?;
+1 -1
View File
@@ -650,7 +650,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"tool.scaleAnchor",
"Scale anchor",
"{anchor?: tl|t|tr|l|c|r|bl|b|br} (the point of the selection that stays put when the Scale tool scales; omit to read it)",
"{anchor?: tl|t|tr|l|c|r|bl|b|br} (the origin of the Scale tool's factor field: the point of the selection that stays put; defaults to c, handle drags pivot on the opposite handle whatever it is; omit to read it)",
false,
|s, p| {
if let Some(a) = string(p, "anchor") {
+28
View File
@@ -552,3 +552,31 @@ fn leaving_the_session_goes_back_to_snapshot_undo() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().node(r).unwrap().name, "Live");
}
/// #1817: the page a file opens on is a document property: setting it syncs to the server, so
/// everyone who joins afterwards lands on it, and moves nobody's own view.
#[test]
fn the_opening_page_syncs_and_moves_no_ones_view() {
let mut room = Room::new(base(), 2, 7);
let first = room.server.document().first_page().unwrap();
let cover = NodeId(room.s(0).execute("page.add", &json!({"name": "Cover"})).unwrap()["id"].as_u64().unwrap());
room.settle();
room.check();
assert_eq!(room.s(1).page().unwrap(), first, "another person's page is their own");
room.s(0).execute("page.setOpening", &json!({"id": cover})).unwrap();
room.settle();
room.check();
assert_eq!(room.server.document().current_page, Some(cover), "the server's file opens on it now");
assert_eq!(room.s(1).page().unwrap(), first, "nobody's view moved");
assert_eq!(Session::with_document(room.server.document().clone()).page().unwrap(), cover, "whoever joins next lands on it");
// One undo step, the setter's.
assert_eq!(room.s(0).execute("edit.undo", &json!({})).unwrap()["undone"], true);
room.settle();
room.check();
assert_ne!(room.server.document().current_page, Some(cover), "undone for everyone");
assert_eq!(
Session::with_document(room.server.document().clone()).page().unwrap(),
first,
"whoever joins after the undo lands on the restored page"
);
}
+214 -1
View File
@@ -6,7 +6,7 @@
//! their iOS and Android code syntax in SwiftUI and Compose. The output is a starting point, not a
//! pixel-exact translation.
use figcraft_color::{Color, PaintKind};
use figcraft_color::{Color, Gradient, GradientKind, Paint, PaintKind};
use figcraft_doc::{
ContentAlign, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Shadow, Sizing,
TextAlignH, TextCase, TextDecoration, Variable,
@@ -345,6 +345,35 @@ fn first_fill(n: &Node) -> Option<Color> {
})
}
/// A layer's visible fills with their place in the document. Document order is bottom first, as
/// the renderer paints them; the index tells a target which paint is the bottom one.
fn visible_fills(n: &Node) -> impl DoubleEndedIterator<Item = (usize, &Paint)> {
n.fills.iter().enumerate().filter(|(_, p)| p.visible)
}
/// A gradient's sorted stops as (position, colour), the paint's opacity folded into each colour.
/// A lone stop is written twice (at 1 as well), since Android and Flutter need two colours.
fn gradient_stops(g: &Gradient, opacity: f32) -> Vec<(f64, Color)> {
let mut stops: Vec<(f64, Color)> = g.sorted_stops().iter().map(|s| (f64::from(s.position), s.color.with_alpha(s.color.a * opacity))).collect();
if let [(_, only)] = stops[..] {
stops.push((1.0, only));
}
stops
}
/// A gradient's main axis in pixels on a `w` x `h` box.
fn gradient_axis(g: &Gradient, w: f64, h: f64) -> (f64, f64) {
((g.to.0 - g.from.0) * w, (g.to.1 - g.from.1) * h)
}
/// The kind a native target writes: a diamond reads as a radial gradient.
fn native_gradient_kind(g: &Gradient) -> GradientKind {
match g.kind {
GradientKind::Diamond => GradientKind::Radial,
k => k,
}
}
fn stroke_color(n: &Node) -> Option<Color> {
if !n.has_visible_stroke() {
return None;
@@ -824,4 +853,188 @@ mod tests {
}
}
}
/// White, a 20% default linear gradient of black, then 50% black: bottom to top.
fn three_fills() -> Vec<figcraft_color::Paint> {
let mut gradient = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK));
gradient.opacity = 0.2;
let mut top = figcraft_color::Paint::solid(Color::BLACK);
top.opacity = 0.5;
vec![figcraft_color::Paint::solid(Color::WHITE), gradient, top]
}
/// A 200 x `h` layer of `kind` (`frame`, `rectangle` or `ellipse`, a rectangle with corner
/// radius 8) with exactly `fills`.
fn fill_layer(s: &mut Session, kind: &str, h: f64, fills: Vec<figcraft_color::Paint>) -> NodeId {
let id = match kind {
"frame" => id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(),
_ => id_of(&s.execute(&format!("shape.{kind}"), &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(),
};
if kind == "rectangle" {
s.execute("node.set", &json!({"id": id, "props": {"cornerRadius": 8}})).unwrap();
}
s.doc_mut().unwrap().get_mut(id).unwrap().fills = fills;
id
}
fn one_gradient(s: &mut Session, g: figcraft_color::Gradient) -> NodeId {
fill_layer(s, "frame", 120.0, vec![figcraft_color::Paint::gradient(g)])
}
const SWIFT_WHITE: &str = "Color(red: 1, green: 1, blue: 1, opacity: 1)";
const SWIFT_HALF: &str = "Color(red: 0, green: 0, blue: 0, opacity: 0.5)";
const SWIFT_GRADIENT: &str = "LinearGradient(stops: [Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0.2), location: 0), Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0), location: 1)], startPoint: UnitPoint(x: 0.5, y: 0), endPoint: UnitPoint(x: 0.5, y: 1))";
#[test]
fn swiftui_writes_every_fill_top_first() {
let mut s = Session::new();
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), f, CodeLang::SwiftUi);
let backgrounds: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect();
let want = [format!(".background({SWIFT_HALF})"), format!(".background({SWIFT_GRADIENT})"), format!(".background({SWIFT_WHITE})")];
assert_eq!(backgrounds, want.iter().map(String::as_str).collect::<Vec<_>>(), "{code}");
}
#[test]
fn swiftui_shapes_fill_with_the_bottom_paint_and_overlay_the_rest() {
let mut s = Session::new();
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), r, CodeLang::SwiftUi);
let mods: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with('.')).collect();
let want = [
format!(".fill({SWIFT_WHITE})"),
format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_GRADIENT}))"),
format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_HALF}))"),
".frame(width: 200, height: 120)".to_string(),
];
assert_eq!(mods, want.iter().map(String::as_str).collect::<Vec<_>>(), "{code}");
assert!(!code.contains(".background("), "{code}");
let mut half = figcraft_color::Paint::solid(Color::BLACK);
half.opacity = 0.5;
let e = fill_layer(&mut s, "ellipse", 120.0, vec![figcraft_color::Paint::solid(Color::WHITE), half]);
let code = code_for(s.doc().unwrap(), e, CodeLang::SwiftUi);
assert!(code.contains(&format!(".overlay(Ellipse().fill({SWIFT_HALF}))")), "{code}");
}
#[test]
fn compose_writes_every_fill_bottom_first() {
let mut s = Session::new();
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), f, CodeLang::Compose);
let want = "Modifier.size(200.dp, 120.dp).background(Color(0xFFFFFFFF), RectangleShape).background(Brush.linearGradient(0f to Color(0x33000000), 1f to Color(0x00000000), start = Offset(0f, 0f), end = Offset(0f, Float.POSITIVE_INFINITY)), RectangleShape).background(Color(0x80000000), RectangleShape)";
assert!(code.contains(want), "{code}");
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), r, CodeLang::Compose);
assert_eq!(code.matches(".background(").count(), 3, "{code}");
assert_eq!(code.matches(", RoundedCornerShape(8.dp))").count(), 3, "{code}");
assert!(code.contains(".background(Color(0xFFFFFFFF), RoundedCornerShape(8.dp)).background(Brush."), "{code}");
}
#[test]
fn flutter_nests_a_box_per_fill_bottom_outermost() {
let mut s = Session::new();
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter);
let want = "DecoratedBox(
decoration: BoxDecoration(
color: Color(0xFFFFFFFF),
),
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment(0, -1), end: Alignment(0, 1), colors: [Color(0x33000000), Color(0x00000000)], stops: [0, 1]),
),
child: Container(
width: 200,
height: 120,
decoration: BoxDecoration(
color: Color(0x80000000),
),
)
)
)";
assert_eq!(code, want);
}
#[test]
fn flutter_keeps_the_shadow_under_every_fill() {
let mut s = Session::new();
let f = fill_layer(&mut s, "frame", 120.0, three_fills());
s.execute("effect.add", &json!({"ids": [f], "type": "dropShadow"})).unwrap();
let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter);
assert_eq!(code.matches("boxShadow:").count(), 1, "{code}");
let (shadow, gradient) = (code.find("boxShadow:").unwrap(), code.find("gradient:").unwrap());
assert!(shadow < gradient, "the shadow is on the outermost box: {code}");
let r = fill_layer(&mut s, "rectangle", 120.0, three_fills());
let code = code_for(s.doc().unwrap(), r, CodeLang::Flutter);
assert_eq!(code.matches("borderRadius: BorderRadius.circular(8)").count(), 3, "{code}");
}
#[test]
fn native_gradients_are_written_as_gradients() {
use figcraft_color::{Gradient, GradientKind};
let mut s = Session::new();
let radial = one_gradient(&mut s, Gradient::default_for(GradientKind::Radial, Color::BLACK));
let doc = s.doc().unwrap();
let sw = code_for(doc, radial, CodeLang::SwiftUi);
assert!(sw.contains("RadialGradient(stops: ["), "{sw}");
assert!(sw.contains("center: UnitPoint(x: 0.5, y: 0.5), startRadius: 0, endRadius: 60)"), "{sw}");
let kt = code_for(doc, radial, CodeLang::Compose);
assert!(kt.contains(".background(Brush.radialGradient(0f to Color(0xFF000000), 1f to Color(0x00000000)), RectangleShape)"), "{kt}");
let dart = code_for(doc, radial, CodeLang::Flutter);
assert!(
dart.contains(
"gradient: RadialGradient(center: Alignment(0, 0), radius: 0.5, colors: [Color(0xFF000000), Color(0x00000000)], stops: [0, 1])"
),
"{dart}"
);
let angular = one_gradient(&mut s, Gradient::default_for(GradientKind::Angular, Color::BLACK));
let doc = s.doc().unwrap();
assert!(code_for(doc, angular, CodeLang::SwiftUi).contains("angle: .degrees(90))"));
assert!(code_for(doc, angular, CodeLang::Compose).contains("Brush.sweepGradient("));
assert!(code_for(doc, angular, CodeLang::Flutter).contains("transform: GradientRotation(1.57))"));
// Compose snaps a linear gradient to one of eight directions.
let mut directed = |from: (f64, f64), to: (f64, f64)| {
let mut g = Gradient::default_for(GradientKind::Linear, Color::BLACK);
(g.from, g.to) = (from, to);
let id = one_gradient(&mut s, g);
code_for(s.doc().unwrap(), id, CodeLang::Compose)
};
let up = directed((0.5, 1.0), (0.5, 0.0));
assert!(up.contains("start = Offset(0f, Float.POSITIVE_INFINITY), end = Offset(0f, 0f)"), "{up}");
let right = directed((0.0, 0.5), (1.0, 0.5));
assert!(right.contains("end = Offset(Float.POSITIVE_INFINITY, 0f)"), "{right}");
let corner = directed((0.0, 0.0), (1.0, 1.0));
assert!(corner.contains("end = Offset(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)"), "{corner}");
// A single stop is written twice, since a brush needs two colours.
let mut one = Gradient::default_for(GradientKind::Linear, Color::BLACK);
one.stops.truncate(1);
let id = one_gradient(&mut s, one);
let kt = code_for(s.doc().unwrap(), id, CodeLang::Compose);
assert_eq!(kt.matches(" to Color(").count(), 2, "{kt}");
}
#[test]
fn one_solid_fill_is_unchanged_in_native_code() {
let mut hidden = figcraft_color::Paint::solid(Color::BLACK);
hidden.visible = false;
let mut s = Session::new();
for fills in [vec![figcraft_color::Paint::solid(Color::WHITE)], vec![figcraft_color::Paint::solid(Color::WHITE), hidden]] {
let f = fill_layer(&mut s, "frame", 100.0, fills);
let doc = s.doc().unwrap();
let sw = code_for(doc, f, CodeLang::SwiftUi);
let backgrounds: Vec<&str> = sw.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect();
assert_eq!(backgrounds, [format!(".background({SWIFT_WHITE})")], "{sw}");
assert!(!sw.contains("Gradient"), "{sw}");
let kt = code_for(doc, f, CodeLang::Compose);
assert!(kt.contains("Modifier.size(200.dp, 100.dp).background(Color(0xFFFFFFFF), RectangleShape))"), "{kt}");
assert!(!kt.contains("Brush"), "{kt}");
let dart = code_for(doc, f, CodeLang::Flutter);
assert!(
dart.starts_with("Container(\n width: 200,\n height: 100,\n decoration: BoxDecoration(\n color: Color(0xFFFFFFFF),\n ),\n)"),
"{dart}"
);
assert!(!dart.contains("DecoratedBox"), "{dart}");
assert!(code_for(doc, f, CodeLang::ArkUi).contains(".backgroundColor('#FFFFFF')"));
}
}
}
+56 -3
View File
@@ -1,6 +1,7 @@
use super::swift::one_line;
use super::{
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
CodeLang, Color, Ctx, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill, gradient_axis,
gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
};
use figcraft_doc::Document;
@@ -22,14 +23,66 @@ fn bound_dp(doc: &Document, n: &Node, fields: &[&str], value: f64) -> String {
bound(doc, n, fields, format!("{}.dp", num(value)))
}
/// One end of a linear brush's axis along one direction: `sign` is 0 for none, 1 for with the
/// axis and -1 against it. `Float.POSITIVE_INFINITY` stands for the far edge, which a modifier
/// can't know in pixels.
fn compose_edge(sign: i8) -> (&'static str, &'static str) {
match sign {
0 => ("0f", "0f"),
s if s > 0 => ("0f", "Float.POSITIVE_INFINITY"),
_ => ("Float.POSITIVE_INFINITY", "0f"),
}
}
/// A direction's sign: its component counts as none when it is at most tan 22.5 degrees of the other.
fn compose_sign(v: f64, other: f64) -> i8 {
if v.abs() <= 0.4142 * other.abs() {
0
} else if v > 0.0 {
1
} else {
-1
}
}
/// A gradient fill as a Compose `Brush` for a `w` x `h` layer. A linear gradient snaps to the
/// nearest of eight directions; radial and angular ones sit at the box's centre.
fn compose_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let stops = gradient_stops(g, opacity).into_iter().map(|(at, c)| format!("{}f to {}", num(at), kotlin_color(c))).collect::<Vec<_>>().join(", ");
match native_gradient_kind(g) {
GradientKind::Linear => {
let (dx, dy) = gradient_axis(g, w, h);
let (sx, sy) = if dx == 0.0 && dy == 0.0 { (0, 1) } else { (compose_sign(dx, dy), compose_sign(dy, dx)) };
let ((x0, x1), (y0, y1)) = (compose_edge(sx), compose_edge(sy));
format!("Brush.linearGradient({stops}, start = Offset({x0}, {y0}), end = Offset({x1}, {y1}))")
}
GradientKind::Angular => format!("Brush.sweepGradient({stops})"),
_ => format!("Brush.radialGradient({stops})"),
}
}
/// One paint (the one at document index `i`) as the first argument of `background`; `None` for an
/// image or pattern. Only a solid at index 0 takes the `fill` variable's name.
fn compose_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => {
let c = kotlin_color(p.solid_color()?);
Some(if i == 0 { bound(doc, n, &["fill"], c) } else { c })
}
PaintKind::Gradient(g) => Some(compose_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// The Modifier chain for a layer (size, shadow, background, border, alpha, padding).
fn modifier(doc: &Document, n: &Node, shape: &str, padding: bool) -> String {
let mut m = format!("Modifier.size({}, {})", bound_dp(doc, n, &["width"], n.width), bound_dp(doc, n, &["height"], n.height));
if let Some(s) = drop_shadow(n) {
m.push_str(&format!(".shadow({}.dp, {shape})", num(s.radius / 2.0)));
}
if let Some(c) = first_fill(n) {
m.push_str(&format!(".background({}, {shape})", bound(doc, n, &["fill"], kotlin_color(c))));
// Each background draws and lets the rest of the chain draw over it: bottom fill first.
for b in visible_fills(n).filter_map(|(i, p)| compose_paint(doc, n, i, p)) {
m.push_str(&format!(".background({b}, {shape})"));
}
if let Some(c) = stroke_color(n) {
m.push_str(&format!(
+103 -17
View File
@@ -2,8 +2,9 @@ use figcraft_doc::AutoLayout;
use super::swift::one_line;
use super::{
CodeLang, CrossAlign, Ctx, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Param, Sizing, TextAlignH, TextDecoration,
drop_shadow, first_fill, kotlin_color, literal, num, radius, stroke_color,
CodeLang, CrossAlign, Ctx, GradientKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Paint, PaintKind, Param,
Sizing, TextAlignH, TextDecoration, drop_shadow, first_fill, gradient_axis, gradient_stops, kotlin_color, literal, native_gradient_kind, num,
radius, stroke_color, visible_fills,
};
// ------------------------------------------------------------------ Flutter (Dart)
@@ -74,22 +75,72 @@ fn flutter_padding(n: &Node) -> Option<String> {
})
}
/// A gradient's colours and stops, the tail of every Flutter gradient constructor.
fn flutter_colors(g: &figcraft_color::Gradient, opacity: f32) -> String {
let stops = gradient_stops(g, opacity);
let colors = stops.iter().map(|(_, c)| kotlin_color(*c)).collect::<Vec<_>>().join(", ");
let at = stops.iter().map(|(at, _)| num(*at)).collect::<Vec<_>>().join(", ");
format!("colors: [{colors}], stops: [{at}]")
}
/// A point of the unit box as Flutter's `Alignment`, which runs from -1 to 1.
fn flutter_alignment(p: (f64, f64)) -> String {
format!("Alignment({}, {})", num(2.0 * p.0 - 1.0), num(2.0 * p.1 - 1.0))
}
/// A gradient fill on a layer of `w` x `h` as a Flutter gradient.
fn flutter_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let (dx, dy) = gradient_axis(g, w, h);
let (tail, from) = (flutter_colors(g, opacity), flutter_alignment(g.from));
match native_gradient_kind(g) {
GradientKind::Linear => format!("LinearGradient(begin: {from}, end: {}, {tail})", flutter_alignment(g.to)),
GradientKind::Angular => format!("SweepGradient(center: {from}, {tail}, transform: GradientRotation({}))", num(dy.atan2(dx))),
_ => {
// Flutter's radius is a fraction of the box's shorter side.
let (reach, side) = (dx.hypot(dy), w.min(h));
let radius = if reach > 0.0 && side > 0.0 { reach / side } else { 0.5 };
format!("RadialGradient(center: {from}, radius: {}, {tail})", num(radius))
}
}
}
/// One paint as a `BoxDecoration` part (`color: ...` or `gradient: ...`); `None` for an image or
/// pattern, which no native target writes yet.
fn flutter_paint(n: &Node, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => Some(format!("color: {}", kotlin_color(p.solid_color()?))),
PaintKind::Gradient(g) => Some(format!("gradient: {}", flutter_gradient(g, n.width, n.height, p.opacity))),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// Whether a layer is written as a `Container`: the layers with a box to paint.
fn paints_a_box(n: &Node) -> bool {
matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Rectangle | NodeKind::Group) || n.kind.is_frame_like()
}
/// A layer's fills as `BoxDecoration` parts, bottom first.
fn flutter_fill_parts(n: &Node) -> Vec<String> {
visible_fills(n).filter_map(|(_, p)| flutter_paint(n, p)).collect()
}
/// A layer's fill, shape, corner radius, stroke and shadow as a `BoxDecoration`; `None` when it has
/// none of them. `pad` is the indentation of the constructor itself.
fn box_decoration(n: &Node, pad: &str) -> Option<String> {
/// none of them. `pad` is the indentation of the constructor itself; `fill` is the one fill part
/// this decoration paints, and `stroke` and `shadow` say whether it carries those.
fn box_decoration(n: &Node, pad: &str, fill: Option<&str>, stroke: bool, shadow: bool) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
if let Some(c) = first_fill(n) {
parts.push(format!("color: {}", kotlin_color(c)));
if let Some(f) = fill {
parts.push(f.to_string());
}
if matches!(n.kind, NodeKind::Ellipse { .. }) {
parts.push("shape: BoxShape.circle".into());
} else if radius(n) > 0.0 {
parts.push(format!("borderRadius: BorderRadius.circular({})", num(radius(n))));
}
if let Some(c) = stroke_color(n) {
if let Some(c) = stroke_color(n).filter(|_| stroke) {
parts.push(format!("border: Border.all(color: {}, width: {})", kotlin_color(c), num(n.stroke.weight)));
}
if let Some(s) = drop_shadow(n) {
if let Some(s) = drop_shadow(n).filter(|_| shadow) {
parts.push(format!(
"boxShadow: [BoxShadow(color: {}, blurRadius: {}, offset: Offset({}, {}))]",
kotlin_color(s.color),
@@ -105,6 +156,42 @@ fn box_decoration(n: &Node, pad: &str) -> Option<String> {
Some(format!("BoxDecoration(\n{}{pad})", parts.iter().map(|p| format!("{inner}{p},\n")).collect::<String>()))
}
/// What a `Container` paints itself: its own fill (the top one), and whether it carries the shadow
/// (only when no `DecoratedBox` does).
struct Painted {
fill: Option<String>,
shadow: bool,
}
/// Opens a `DecoratedBox` for each fill under the top one, the bottom fill outermost, and returns
/// what is left for the `Container`. The outermost box carries the drop shadow: a decoration paints
/// its shadow first, so on the `Container` it would lie over the lower fills.
fn flutter_fill_boxes(n: &Node, depth: &mut usize, close: &mut Vec<String>, out: &mut String) -> Painted {
let mut parts = flutter_fill_parts(n);
let top = parts.pop();
let shadow = parts.is_empty();
for (at, part) in parts.iter().enumerate() {
let (pad, inner) = (flutter_indent(*depth), flutter_indent(*depth + 1));
if close.is_empty() {
out.push_str(&pad);
}
let deco = box_decoration(n, &inner, Some(part), false, at == 0).unwrap_or_default();
out.push_str(&format!("DecoratedBox(\n{inner}decoration: {deco},\n{inner}child: "));
close.push(format!("\n{pad})"));
*depth += 1;
}
Painted { fill: top, shadow }
}
/// The call an instance below the root is (an instance swap parameter is a widget); `None` for
/// every other layer.
fn flutter_call(ctx: &Ctx, n: &Node, depth: usize) -> Option<String> {
match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
Some(p) => Some(p.ident.clone()),
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
}
}
/// Flutter for a layer and its subtree at `depth`. A layer a boolean parameter shows sits behind an
/// `if (…)`: Dart's lists take conditions, so the element itself carries it.
pub(crate) fn flutter(ctx: &Ctx, id: NodeId, depth: usize, out: &mut String, place: Place) {
@@ -150,9 +237,13 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
close.push(format!("\n{pad})"));
depth += 1;
}
// An instance is a call, made once: it gets no fill boxes, so this is its final depth.
let call = flutter_call(ctx, n, depth);
let painted =
if call.is_none() && paints_a_box(n) { flutter_fill_boxes(n, &mut depth, &mut close, out) } else { Painted { fill: None, shadow: true } };
// A wrapper leaves its line open ("child: "), so the widget carries no indentation of its own.
let mut body = String::new();
flutter_widget(ctx, n, depth, &mut body);
flutter_widget(ctx, n, depth, call, &painted, &mut body);
out.push_str(if close.is_empty() { body.as_str() } else { body.trim_start() });
for c in close.iter().rev() {
out.push_str(c);
@@ -161,13 +252,8 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl
/// A layer's own look and its subtree as a Flutter widget at `depth`: a complete expression whose
/// closing parenthesis sits at `depth`.
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, call: Option<String>, painted: &Painted, out: &mut String) {
let (pad, inner) = (flutter_indent(depth), flutter_indent(depth + 1));
// Nested instances are calls; an instance swap parameter is a widget.
let call = match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) {
Some(p) => Some(p.ident.clone()),
None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code),
};
if let Some(call) = call {
out.push_str(call.trim_end_matches('\n'));
return;
@@ -216,7 +302,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
}
NodeKind::Ellipse { .. } | NodeKind::Rectangle => {
out.push_str(&format!("{pad}Container(\n{inner}width: {},\n{inner}height: {},\n", num(n.width), num(n.height)));
if let Some(d) = box_decoration(n, &inner) {
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
out.push_str(&format!("{inner}decoration: {d},\n"));
}
out.push_str(&format!("{pad})"));
@@ -232,7 +318,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) {
if !padded_inside && let Some(p) = flutter_padding(n) {
out.push_str(&format!("{inner}padding: {p},\n"));
}
if let Some(d) = box_decoration(n, &inner) {
if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) {
out.push_str(&format!("{inner}decoration: {d},\n"));
}
if children.is_empty() && slot.is_none() {
+47 -10
View File
@@ -1,5 +1,6 @@
use super::{
CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color,
CodeLang, Color, Ctx, Document, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill,
gradient_axis, gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills,
};
// ------------------------------------------------------------------ SwiftUI
@@ -8,6 +9,47 @@ fn swift_color(c: Color) -> String {
format!("Color(red: {}, green: {}, blue: {}, opacity: {})", num(f64::from(c.r)), num(f64::from(c.g)), num(f64::from(c.b)), num(f64::from(c.a)))
}
fn swift_point(p: (f64, f64)) -> String {
format!("UnitPoint(x: {}, y: {})", num(p.0), num(p.1))
}
/// A gradient fill on a layer of `w` x `h` as a SwiftUI gradient.
fn swift_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String {
let stops = gradient_stops(g, opacity)
.into_iter()
.map(|(at, c)| format!("Gradient.Stop(color: {}, location: {})", swift_color(c), num(at)))
.collect::<Vec<_>>()
.join(", ");
let (dx, dy) = gradient_axis(g, w, h);
match native_gradient_kind(g) {
GradientKind::Linear => format!("LinearGradient(stops: [{stops}], startPoint: {}, endPoint: {})", swift_point(g.from), swift_point(g.to)),
GradientKind::Angular => {
format!("AngularGradient(stops: [{stops}], center: {}, angle: .degrees({}))", swift_point(g.from), num(dy.atan2(dx).to_degrees()))
}
_ => format!("RadialGradient(stops: [{stops}], center: {}, startRadius: 0, endRadius: {})", swift_point(g.from), num(dx.hypot(dy))),
}
}
/// One paint (the one at document index `i`) as SwiftUI; `None` for an image or pattern, which no
/// native target writes yet. Only a solid at index 0 takes the `fill` variable's name.
fn swift_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option<String> {
match &p.kind {
PaintKind::Solid { .. } => {
let c = swift_color(p.solid_color()?);
Some(if i == 0 { named(doc, n, "iOS", &["fill"], c) } else { c })
}
PaintKind::Gradient(g) => Some(swift_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Image(_) | PaintKind::Pattern(_) => None,
}
}
/// The modifiers filling a rectangle or ellipse: the bottom paint fills the `shape`, and each paint
/// above it is a copy of the shape laid over it.
fn swift_shape_fills(doc: &Document, n: &Node, shape: &str) -> Vec<String> {
let paints = visible_fills(n).filter_map(|(i, p)| swift_paint(doc, n, i, p));
paints.enumerate().map(|(at, c)| if at == 0 { format!(".fill({c})") } else { format!(".overlay({shape}.fill({c}))") }).collect()
}
fn swift_weight(w: u16) -> &'static str {
match w {
0..=150 => ".thin",
@@ -84,16 +126,12 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
}
NodeKind::Ellipse { .. } => {
out.push_str(&format!("{pad}Ellipse()\n"));
if let Some(c) = &fill {
mods.push(format!(".fill({c})"));
}
mods.extend(swift_shape_fills(doc, n, "Ellipse()"));
mods.push(format!(".frame(width: {w}, height: {h})"));
}
NodeKind::Rectangle => {
out.push_str(&format!("{pad}RoundedRectangle(cornerRadius: {corner})\n"));
if let Some(c) = &fill {
mods.push(format!(".fill({c})"));
}
mods.extend(swift_shape_fills(doc, n, &format!("RoundedRectangle(cornerRadius: {corner})")));
mods.push(format!(".frame(width: {w}, height: {h})"));
}
k if k.is_frame_like() || matches!(k, NodeKind::Group) => {
@@ -142,9 +180,8 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str
}
}
mods.push(format!(".frame(width: {w}, height: {h}, alignment: .topLeading)"));
if let Some(c) = &fill {
mods.push(format!(".background({c})"));
}
// Each background goes behind the ones before it, so the top fill is written first.
mods.extend(visible_fills(n).rev().filter_map(|(i, p)| swift_paint(doc, n, i, p)).map(|c| format!(".background({c})")));
if radius(n) > 0.0 {
mods.push(format!(".clipShape(RoundedRectangle(cornerRadius: {corner}))"));
}
@@ -255,3 +255,277 @@ fn duplicate_repeats_a_nudged_step() {
let c2 = cmd_d(&mut s);
assert_eq!(at(&s, c2), (80.0, 0.0), "the nudge is the step");
}
fn centre(s: &Session, id: NodeId) -> (f64, f64) {
let c = s.doc().unwrap().world_bounds(id).unwrap().center();
(c.x, c.y)
}
fn turn(s: &Session, id: NodeId) -> f64 {
figcraft_geom::rotation_degrees(s.doc().unwrap().world_transform(id))
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
#[test]
fn duplicate_repeats_the_copys_move_and_rotation() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -15}}));
assert!(near(centre(&s, c1).0, 200.0) && near(centre(&s, c1).1, 50.0));
for k in 1..=3 {
let c = cmd_d(&mut s);
let (x, y) = centre(&s, c);
let want = 200.0 + 150.0 * f64::from(k);
assert!(near(x, want) && near(y, 50.0), "repeat {k}: centre ({x}, {y})");
assert!(near(turn(&s, c), -15.0 - 15.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c));
}
}
#[test]
fn duplicate_repeats_a_rotation_in_place() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": 30}}));
for k in 1..=3 {
let c = cmd_d(&mut s);
let (x, y) = centre(&s, c);
assert!(near(x, 50.0) && near(y, 50.0), "repeat {k}: centre ({x}, {y})");
assert!(near(turn(&s, c), 30.0 + 30.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c));
}
}
#[test]
fn duplicate_does_not_step_the_size() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
let c1_centre = centre(&s, c1);
for k in 1..=2 {
let c = cmd_d(&mut s);
let w = s.doc().unwrap().get(c).unwrap().width;
assert!(near(w, 120.0), "repeat {k}: width {w}");
assert!(near(centre(&s, c).0, c1_centre.0 + 150.0 * f64::from(k)), "repeat {k}: centre {:?}", centre(&s, c));
}
}
#[test]
fn duplicate_turns_several_layers_about_their_selection_centre() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
let b = rect(&mut s, 150.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a, b]}));
let out = ex(&mut s, "edit.duplicate", json!({}));
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0}));
// Turn the pair -15 about its combined centre.
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15}));
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let pair_before = s.doc().unwrap().bounds_of(&copies).unwrap().center();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
assert_eq!(next.len(), 2);
let after = s.doc().unwrap().bounds_of(&next).unwrap().center();
assert!(near(after.x, pair_before.x + 150.0) && near(after.y, pair_before.y), "pair centre {after:?}");
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c));
// Expected: the layer's centre moved +150, then turned -15 about the moved pair's centre.
let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1));
let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, after, -15.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
}
}
#[test]
fn a_deselect_forgets_the_duplicate_step() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
ex(&mut s, "select.none", json!({}));
ex(&mut s, "select.set", json!({"ids": [c1]}));
let c2 = cmd_d(&mut s);
assert_eq!(at(&s, c2), (150.0, 0.0), "no step after a deselect: the copy lands in place");
}
#[test]
fn several_uneven_layers_turned_in_place_repeat_the_turn_without_a_move() {
let mut s = Session::new();
let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
let ids = [rect(&mut s, 0.0, 200.0), wide];
ex(&mut s, "select.set", json!({"ids": ids}));
let out = ex(&mut s, "edit.duplicate", json!({}));
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
for c in &copies {
ex(&mut s, "node.set", json!({"ids": [*c], "props": {"rotation": -45}}));
}
let pivot = handle_box_centre(&s, &copies);
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c), -90.0), "layer {i}: rotation {}", turn(&s, *c));
// No move: each layer's centre only turned -45 about the copies' shared centre.
let want =
figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, -45.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
}
}
/// The uneven pair the collective-turn tests share: a square and a wide one, selected and duplicated.
fn uneven_pair_and_copies(s: &mut Session) -> Vec<NodeId> {
let wide = id_of(&ex(s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
let ids = [rect(s, 0.0, 200.0), wide];
ex(s, "select.set", json!({"ids": ids}));
let out = ex(s, "edit.duplicate", json!({}));
out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect()
}
#[test]
fn several_uneven_layers_turned_together_repeat_the_turn_without_a_move() {
let mut s = Session::new();
let copies = uneven_pair_and_copies(&mut s);
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 90}));
let pivot = s.doc().unwrap().bounds_of(&copies).unwrap().center();
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
assert_eq!(next.len(), 2);
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c).abs(), 180.0), "layer {i}: rotation {}", turn(&s, *c));
let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 90.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
}
}
#[test]
fn several_uneven_layers_moved_and_turned_together_repeat_both() {
let mut s = Session::new();
let copies = uneven_pair_and_copies(&mut s);
ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0}));
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15}));
let pivot = handle_box_centre(&s, &copies);
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
assert_eq!(next.len(), 2);
let moved_pivot = figcraft_geom::Point::new(pivot.x + 150.0, pivot.y);
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c));
let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1));
let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, moved_pivot, -15.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
}
}
#[test]
fn a_widened_copy_turned_in_place_repeats_the_turn_without_a_move() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}}));
let c1_centre = centre(&s, c1);
let c2 = cmd_d(&mut s);
let got = centre(&s, c2);
assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}");
assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2));
assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0));
}
#[test]
fn a_copy_turned_then_widened_repeats_the_turn_without_a_move() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}}));
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
let c1_centre = centre(&s, c1);
let c2 = cmd_d(&mut s);
let got = centre(&s, c2);
assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}");
assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2));
assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0));
}
/// The centre of the selection's handle box, which is what the Rotate handle turns about.
fn handle_box_centre(s: &Session, ids: &[NodeId]) -> figcraft_geom::Point {
let q = crate::tools::selection_box(s.doc().unwrap(), ids).unwrap();
figcraft_geom::Point::new(q.iter().map(|c| c.x).sum::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 4.0)
}
#[test]
fn a_turned_pair_turned_again_about_its_handle_box_repeats_without_a_move() {
let mut s = Session::new();
let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
let ids = [rect(&mut s, 0.0, 200.0), wide];
ex(&mut s, "transform.rotate", json!({"ids": ids, "degrees": 60}));
ex(&mut s, "select.set", json!({"ids": ids}));
let out = ex(&mut s, "edit.duplicate", json!({}));
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
let p = handle_box_centre(&s, &copies);
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30, "cx": p.x, "cy": p.y}));
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
assert_eq!(next.len(), 2);
let pivot = handle_box_centre(&s, &next);
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c), 120.0), "layer {i}: rotation {}", turn(&s, *c));
let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
}
}
#[test]
fn several_uneven_layers_turned_together_repeat_about_one_centre_each_time() {
let mut s = Session::new();
let mut copies = uneven_pair_and_copies(&mut s);
// Upright, the pair's handle box is its bounds: both centres are (250, 150), so this is also
// the Rotate handle's turn. Turned, the box keeps that centre; the bounds don't.
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30}));
let pivot = figcraft_geom::Point::new(250.0, 150.0);
for k in 1..=3 {
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
let again = ex(&mut s, "edit.duplicate", json!({}));
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
assert_eq!(next.len(), 2);
for (i, c) in next.iter().enumerate() {
assert!(near(turn(&s, *c), 30.0 + 30.0 * f64::from(k)), "repeat {k}, layer {i}: rotation {}", turn(&s, *c));
let want =
figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0));
let got = centre(&s, *c);
assert!(near(got.0, want.x) && near(got.1, want.y), "repeat {k}, layer {i}: {got:?} vs {want:?}");
}
copies = next;
}
}
#[test]
fn a_flipped_copy_does_not_repeat_a_half_turn() {
let mut s = Session::new();
let a = rect(&mut s, 0.0, 0.0);
ex(&mut s, "select.set", json!({"ids": [a]}));
let c1 = cmd_d(&mut s);
ex(&mut s, "object.flipH", json!({"ids": [c1]}));
let c2 = cmd_d(&mut s);
assert!(near(turn(&s, c2), turn(&s, c1)), "rotation {} vs {}", turn(&s, c2), turn(&s, c1));
}
+4
View File
@@ -14,6 +14,10 @@ pub enum EngineError {
NoNode(NodeId),
#[error("{0}")]
Other(String),
/// A preview was asked for with no gesture open (something committed it under a held button).
/// Not for the user: the canvas drops it, as the drag it belonged to is over.
#[error("no gesture in progress")]
NoGesture,
/// A command run in the background sent a request to a server and runs again with the answer
/// ([`background`]); never returned to other callers.
#[error("waiting for the server")]
+5
View File
@@ -77,6 +77,7 @@ pub use selection::rename;
pub use selection::selection_colors;
pub use selection::selection_reorder;
pub use selection::selection_spacing;
pub use selection::tidy;
pub use sharing::agent;
pub use sharing::background;
pub use sharing::branches;
@@ -459,6 +460,8 @@ mod page_clipboard_tests;
#[cfg(test)]
mod page_copy_navigation_tests;
#[cfg(test)]
mod page_opening_tests;
#[cfg(test)]
mod page_target_tests;
#[cfg(test)]
mod paint_index_tests;
@@ -609,6 +612,8 @@ mod textfit_tests;
#[cfg(test)]
mod theme_pages_tests;
#[cfg(test)]
mod tidy_tests;
#[cfg(test)]
mod tiff_tests;
#[cfg(test)]
mod transform_behaviour_tests;
+175
View File
@@ -0,0 +1,175 @@
//! `page.setOpening` (#1817): the page a file opens on, for everyone who opens or joins it, written
//! as a document change (so it syncs and undoes) without moving anyone's own view.
use figcraft_doc::NodeId;
use serde_json::{Value, json};
use crate::Session;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
/// Setting the opening page writes the document, leaves this viewer where they are, is one undo
/// step, and a file opened from that document lands on it.
#[test]
fn the_opening_page_is_written_without_moving_the_view_and_a_reopened_file_lands_on_it() {
let mut s = Session::new();
let first = s.page().unwrap();
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
ex(&mut s, "page.select", json!({"id": first}));
let depth = s.undo_depth().0;
ex(&mut s, "page.setOpening", json!({"id": cover}));
assert_eq!(s.doc().unwrap().current_page, Some(cover), "written to the document");
assert_eq!(s.page().unwrap(), first, "the view stays where it was");
assert_eq!(s.undo_depth().0, depth + 1, "one undo step");
let reopened = Session::with_document(s.doc().unwrap().clone());
assert_eq!(reopened.page().unwrap(), cover, "a file opened from this document lands on it");
ex(&mut s, "edit.undo", json!({}));
assert_ne!(s.doc().unwrap().current_page, Some(cover), "undone");
assert_eq!(Session::with_document(s.doc().unwrap().clone()).page().unwrap(), first);
}
/// Without an id the current page is meant; a divider and a layer are refused and change nothing.
#[test]
fn the_current_page_is_the_default_and_dividers_and_layers_are_refused() {
let mut s = Session::new();
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
assert_eq!(s.page().unwrap(), two, "page.add goes to the new page");
ex(&mut s, "page.setOpening", json!({}));
assert_eq!(s.doc().unwrap().current_page, Some(two), "the current page when none is named");
let divider = id_of(&ex(&mut s, "page.add", json!({"name": "-"})));
let r = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})));
let (view, depth) = (s.page().unwrap(), s.undo_depth());
assert!(s.execute("page.setOpening", &json!({"id": divider})).is_err(), "a divider isn't a page to open on");
assert!(s.execute("page.setOpening", &json!({"id": r})).is_err(), "a layer isn't a page");
assert_eq!(s.doc().unwrap().current_page, Some(two), "refusals change nothing");
assert_eq!(s.page().unwrap(), view, "the viewer's page is where it was");
assert_eq!(s.undo_depth(), depth, "and no undo step was added");
}
/// An id that is no node at all errors and changes nothing.
#[test]
fn an_unknown_id_is_refused_and_changes_nothing() {
let mut s = Session::new();
let first = s.page().unwrap();
let depth = s.undo_depth();
assert!(s.execute("page.setOpening", &json!({"id": 987_654_321u64})).is_err(), "no such node");
assert_eq!(s.doc().unwrap().current_page, Some(first));
assert_eq!(s.undo_depth(), depth);
}
/// Setting the page that already is the opening page changes nothing and adds no undo step.
#[test]
fn setting_the_page_that_already_opens_the_file_adds_no_undo_step() {
let mut s = Session::new();
let first = s.page().unwrap();
assert_eq!(s.doc().unwrap().current_page, Some(first));
ex(&mut s, "page.setOpening", json!({"id": first}));
let depth = s.undo_depth();
ex(&mut s, "page.setOpening", json!({"id": first}));
assert_eq!(s.undo_depth(), depth, "already the opening page: no step");
assert_eq!(s.doc().unwrap().current_page, Some(first));
}
/// Deleting the opening page leaves the file opening on a page that exists.
#[test]
fn deleting_the_opening_page_falls_back_to_a_page_that_exists() {
let mut s = Session::new();
let first = s.page().unwrap();
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
ex(&mut s, "page.setOpening", json!({"id": cover}));
ex(&mut s, "page.delete", json!({"id": cover}));
let doc = s.doc().unwrap().clone();
let now = doc.current_page.expect("an opening page remains");
assert!(doc.pages.contains(&now) && now != cover, "a page that exists");
assert_eq!(now, first);
assert_eq!(Session::with_document(doc).page().unwrap(), first, "a reopened file lands on it");
}
/// The file written by a real save (the serializer, not a cloned document), opened again.
fn saved_and_reopened(s: &Session) -> Session {
let bytes = crate::cmd::file::file_bytes(s.ds().unwrap()).unwrap();
let (doc, _) = figcraft_format::load_bytes(&bytes).unwrap();
Session::with_document(doc)
}
/// Saving writes the chosen opening page, not the page the saver was viewing.
#[test]
fn the_opening_page_survives_a_save_and_reopen_from_another_page() {
let mut s = Session::new();
let first = s.page().unwrap();
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
ex(&mut s, "page.select", json!({"id": first}));
ex(&mut s, "page.setOpening", json!({"id": cover}));
assert_eq!(s.page().unwrap(), first, "the saver stays on Page 1");
assert_eq!(saved_and_reopened(&s).page().unwrap(), cover);
}
/// With no opening page chosen, a file opens on the page it was saved on, as before.
#[test]
fn without_an_opening_page_a_file_reopens_on_the_page_it_was_saved_on() {
let mut s = Session::new();
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
assert_eq!(s.page().unwrap(), two);
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
}
/// A deleted opening page no longer decides: the file opens where it was saved.
#[test]
fn deleting_the_opening_page_falls_back_to_the_saver_s_page() {
let mut s = Session::new();
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
ex(&mut s, "page.setOpening", json!({"id": cover}));
ex(&mut s, "page.delete", json!({"id": cover}));
ex(&mut s, "page.select", json!({"id": two}));
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
}
/// Undoing the choice puts the saver's page back in charge.
#[test]
fn undoing_the_opening_page_then_saving_reopens_on_the_saver_s_page() {
let mut s = Session::new();
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
ex(&mut s, "page.setOpening", json!({"id": cover}));
ex(&mut s, "edit.undo", json!({}));
ex(&mut s, "page.select", json!({"id": two}));
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
}
/// Choosing another opening page takes the choice off the first.
#[test]
fn setting_another_opening_page_clears_the_first() {
let mut s = Session::new();
let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"})));
let b = id_of(&ex(&mut s, "page.add", json!({"name": "B"})));
let c = id_of(&ex(&mut s, "page.add", json!({"name": "C"})));
ex(&mut s, "page.setOpening", json!({"id": a}));
ex(&mut s, "page.setOpening", json!({"id": b}));
let flagged: Vec<NodeId> = s.doc().unwrap().pages.iter().copied().filter(|&p| opening(&s, p)).collect();
assert_eq!(flagged, vec![b]);
ex(&mut s, "page.select", json!({"id": c}));
assert_eq!(saved_and_reopened(&s).page().unwrap(), b);
}
/// A copy of the opening page is just a page.
#[test]
fn a_duplicated_opening_page_is_not_an_opening_page() {
let mut s = Session::new();
let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"})));
ex(&mut s, "page.setOpening", json!({"id": a}));
let copy = id_of(&ex(&mut s, "page.duplicate", json!({"id": a})));
assert_ne!(copy, a);
assert!(opening(&s, a));
assert!(!opening(&s, copy));
}
fn opening(s: &Session, p: NodeId) -> bool {
matches!(s.doc().unwrap().get(p).map(|n| &n.kind), Ok(figcraft_doc::NodeKind::Page { opening: true, .. }))
}
+47 -21
View File
@@ -57,29 +57,54 @@ fn anchors_round_trip() {
}
#[test]
fn the_pivot_is_the_anchor_unless_it_is_on_the_dragged_side() {
fn the_pivot_is_the_opposite_handle_or_the_centre_with_alt() {
let (w, h) = (100.0, 50.0);
let tl = (0, 0);
// Bottom-right corner from the top-left anchor: classic, by the axis that moved the most.
assert_eq!(scale_factor(Handle::Corner(2), Point::new(200.0, 60.0), w, h, tl, false), Some((2.0, Point::new(0.0, 0.0))));
// Top-right corner: the anchor is on its top side, so the opposite corner stays put.
assert_eq!(scale_factor(Handle::Corner(1), Point::new(150.0, -25.0), w, h, tl, false), Some((1.5, Point::new(0.0, 50.0))));
// Right edge: from the anchor; left edge: the anchor is on it, so from the right edge.
assert_eq!(scale_factor(Handle::Edge(1), Point::new(50.0, 999.0), w, h, tl, false), Some((0.5, Point::new(0.0, 0.0))));
assert_eq!(scale_factor(Handle::Edge(3), Point::new(-100.0, 0.0), w, h, tl, false), Some((2.0, Point::new(100.0, 25.0))));
// A centre anchor, or Alt, scales about the centre.
assert_eq!(scale_factor(Handle::Corner(2), Point::new(150.0, 75.0), w, h, (1, 1), false), Some((2.0, Point::new(50.0, 25.0))));
assert_eq!(scale_factor(Handle::Edge(2), Point::new(0.0, 75.0), w, h, tl, true), Some((2.0, Point::new(50.0, 25.0))));
// Bottom-right corner: the top-left corner stays put, by the axis that moved the most.
assert_eq!(scale_factor(Handle::Corner(2), Point::new(200.0, 60.0), w, h, false), Some((2.0, Point::new(0.0, 0.0))));
// Top-right corner: the bottom-left corner stays put.
assert_eq!(scale_factor(Handle::Corner(1), Point::new(150.0, -25.0), w, h, false), Some((1.5, Point::new(0.0, 50.0))));
// Right edge: the left edge's middle; left edge: the right edge's middle.
assert_eq!(scale_factor(Handle::Edge(1), Point::new(50.0, 999.0), w, h, false), Some((0.5, Point::new(0.0, 25.0))));
assert_eq!(scale_factor(Handle::Edge(3), Point::new(-100.0, 0.0), w, h, false), Some((2.0, Point::new(100.0, 25.0))));
// Alt scales about the centre.
assert_eq!(scale_factor(Handle::Edge(2), Point::new(0.0, 75.0), w, h, true), Some((2.0, Point::new(50.0, 25.0))));
// Past the pivot flips; it never collapses to nothing.
assert_eq!(scale_factor(Handle::Corner(2), Point::new(-100.0, -50.0), w, h, tl, false).map(|k| k.0), Some(-1.0));
assert_eq!(scale_factor(Handle::Corner(2), Point::new(0.0, 0.0), w, h, tl, false).map(|k| k.0), Some(0.01));
assert_eq!(scale_factor(Handle::Corner(2), Point::new(-100.0, -50.0), w, h, false).map(|k| k.0), Some(-1.0));
assert_eq!(scale_factor(Handle::Corner(2), Point::new(0.0, 0.0), w, h, false).map(|k| k.0), Some(0.01));
// Lines (no height) scale along their length.
assert_eq!(scale_factor(Handle::Corner(1), Point::new(300.0, 7.0), 100.0, 0.0, tl, false).map(|k| k.0), Some(3.0));
assert_eq!(scale_factor(Handle::Corner(1), Point::new(300.0, 7.0), 100.0, 0.0, false).map(|k| k.0), Some(3.0));
for bad in [f64::NAN, f64::INFINITY] {
assert_eq!(scale_factor(Handle::Corner(2), Point::new(bad, 0.0), w, h, tl, false), None);
assert_eq!(scale_factor(Handle::Corner(2), Point::new(bad, 0.0), w, h, false), None);
}
assert_eq!(scale_factor(Handle::Rotate(0), Point::new(1.0, 1.0), w, h, tl, false), None);
assert_eq!(scale_factor(Handle::Corner(2), Point::new(5.0, 5.0), 0.0, 0.0, tl, false), None);
assert_eq!(scale_factor(Handle::Rotate(0), Point::new(1.0, 1.0), w, h, false), None);
assert_eq!(scale_factor(Handle::Corner(2), Point::new(5.0, 5.0), 0.0, 0.0, false), None);
}
/// Measured in Figma's web app, 2026-11-09: a drag ignores the origin grid and pivots on the
/// opposite handle (a 100 x 100 layer at 9000, 5000: the bottom-right corner keeps the top left;
/// the right edge keeps the left edge's middle and scales both ways).
#[test]
fn a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin() {
for origin in ["c", "tl"] {
let mut s = Session::new();
let r = rect(&mut s, 9000.0, 5000.0, 100.0, 100.0);
ex(&mut s, "select.set", json!({"ids": [r]}));
ex(&mut s, "tool.scale", json!({}));
ex(&mut s, "tool.scaleAnchor", json!({"anchor": origin}));
drag(&mut s, (9100.0, 5100.0), (9144.0, 5144.0), false);
assert_rect(bounds(&s, r), [9000.0, 5000.0, 9144.0, 5144.0]);
s.undo().unwrap();
// The right edge's middle: the left edge's middle stays, the layer scales evenly.
drag(&mut s, (9100.0, 5050.0), (9150.0, 5050.0), false);
assert_rect(bounds(&s, r), [9000.0, 4975.0, 9150.0, 5125.0]);
}
}
#[test]
fn the_scale_origin_starts_at_the_centre() {
let mut s = Session::new();
assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({}))["anchor"], json!("c"));
assert_eq!(s.tool.scale_anchor, (1, 1));
}
#[test]
@@ -118,7 +143,7 @@ fn the_live_readout_shows_the_factor_and_pivot() {
}
#[test]
fn the_anchor_and_alt_choose_what_stays_put() {
fn the_anchor_is_read_back_and_alt_scales_from_the_centre() {
let mut s = Session::new();
let r = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
ex(&mut s, "select.set", json!({"ids": [r]}));
@@ -126,12 +151,13 @@ fn the_anchor_and_alt_choose_what_stays_put() {
assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({"anchor": "c"}))["anchor"], json!("c"));
assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({}))["anchor"], json!("c"), "reads it back");
assert!(s.execute("tool.scaleAnchor", &json!({"anchor": "nowhere"})).is_err());
// A drag pivots on the opposite corner whatever the anchor.
drag(&mut s, (100.0, 50.0), (150.0, 75.0), false);
assert_rect(bounds(&s, r), [-50.0, -25.0, 150.0, 75.0]);
assert_rect(bounds(&s, r), [0.0, 0.0, 150.0, 75.0]);
// Alt scales from the centre whatever the anchor.
ex(&mut s, "tool.scaleAnchor", json!({"anchor": "tl"}));
drag(&mut s, (150.0, 75.0), (125.0, 62.5), true);
assert_rect(bounds(&s, r), [-25.0, -12.5, 125.0, 62.5]);
assert_rect(bounds(&s, r), [25.0, 12.5, 125.0, 62.5]);
}
#[test]
+1
View File
@@ -2,3 +2,4 @@ pub mod rename;
pub mod selection_colors;
pub mod selection_reorder;
pub mod selection_spacing;
pub mod tidy;
+271
View File
@@ -0,0 +1,271 @@
//! Tidy up: the moves that even a selection's gaps the way Figma's web app does.
//!
//! Measured in Figma's web app on 2026-11-12 (top-level rectangles): a row, a column, a 2 x 3 grid
//! and its transpose, and many runs on the gap. Figma keeps the order and the sizes of every layer
//! and keeps the first layer where it is. Rows are the groups of layers whose Y ranges overlap
//! (transitively), columns the groups whose X ranges overlap. A row is one row group of layers
//! side by side: its horizontal gaps are evened and every Y kept; a column is the mirror image.
//! Layers of a row may overlap along X, also in a chain: a negative gap counts in the mean. The one gap is the most
//! common existing gap (the smaller of two equally common ones), else the mean rounded to a whole
//! number, half up. A grid (two or more rows and two or more columns, one layer in every cell) is
//! packed along the axis that has more groups: for 2 rows by 3 columns each column is as wide as
//! its widest layer, centred where its layers were, the columns are evened, every layer is
//! centred in its column and every column is stacked from the selection's top; 3 rows by 2
//! columns is the mirror image. Tidy up is unavailable for fewer than three layers, for layers all
//! in one row and one column (overlapping each other), for a diagonal and for an irregular layout.
//!
//! Not measured, FigCraft's choices: a 2 x 2 grid packed as columns; layers in an auto layout flow
//! making it unavailable (the frame places them, and the measurement could not tell this from an
//! irregular layout); the 2,000 layer cap; rotated layers counting by their box; gaps a pixel
//! apart being different gaps; an explicit `spacing` taking two layers; no rounding in a grid with
//! Snap to pixel grid off.
use std::collections::BTreeSet;
use figcraft_doc::{Document, NodeId};
use figcraft_geom::Rect;
use crate::cmd::edit::roots;
const EPS: f64 = 0.01;
const MAX_LAYERS: usize = 2000;
type Item = (NodeId, Rect);
type Move = (NodeId, f64, f64);
/// What a selection is: a row or a column (`vertical`), or a grid packed in units along an axis
/// (`vertical`: the units are rows).
#[derive(Clone, Copy)]
enum Shape {
Line { vertical: bool },
Grid { vertical: bool },
}
/// Whether Tidy up is offered for `ids`: three to 2,000 layers with boxes, none in an auto layout
/// flow, forming a row, a column or a grid.
pub fn can_tidy(doc: &Document, ids: &[NodeId]) -> bool {
available(doc, ids, 3).is_some()
}
/// The page-space moves that tidy `ids` (empty when unavailable or when nothing would move).
/// `spacing` sets the gap and lets two layers through; `snap` rounds a grid's positions across its
/// packing axis to whole pixels.
pub(crate) fn tidy_moves(doc: &Document, ids: &[NodeId], spacing: Option<f64>, snap: bool) -> Vec<Move> {
let min = if spacing.is_some() { 2 } else { 3 };
let Some((items, shape)) = available(doc, ids, min) else { return Vec::new() };
let moves = match shape {
Shape::Line { vertical } => line_moves(&items, vertical, spacing),
Shape::Grid { vertical } => grid_moves(&groups(&items, vertical), vertical, spacing, snap),
};
moves.into_iter().filter(|(_, dx, dy)| !(dx.is_finite() && dy.is_finite()) || dx.abs() > 1e-9 || dy.abs() > 1e-9).collect()
}
fn available(doc: &Document, ids: &[NodeId], min: usize) -> Option<(Vec<Item>, Shape)> {
let mut seen = BTreeSet::new();
let ids: Vec<NodeId> = roots(doc, ids).into_iter().filter(|i| seen.insert(*i)).collect();
if ids.len() < min || ids.len() > MAX_LAYERS {
return None;
}
let mut items = Vec::with_capacity(ids.len());
for id in ids {
let n = doc.node(id)?;
if n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some() && !n.child_layout.absolute) {
return None;
}
let b = doc.world_bounds(id)?;
if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) {
return None;
}
items.push((id, b));
}
let shape = classify(&items)?;
Some((items, shape))
}
/// A row: one row group over two or more column groups (layers sharing a column group overlap).
/// A column: the mirror image. A grid: two or
/// more of each, one layer in every cell, packed along the axis with more groups (columns on a tie).
fn classify(items: &[Item]) -> Option<Shape> {
let cols = groups(items, false);
let rows = groups(items, true);
match (cols.len(), rows.len()) {
(c, 1) if c >= 2 && cols.iter().all(|g| overlapping(g, false)) => Some(Shape::Line { vertical: false }),
(1, r) if r >= 2 && rows.iter().all(|g| overlapping(g, true)) => Some(Shape::Line { vertical: true }),
(c, r) if c >= 2 && r >= 2 && one_per_cell(&cols, &rows) => Some(Shape::Grid { vertical: r > c }),
_ => None,
}
}
/// Layers that share a group along a row's (`vertical` false) or column's own axis must overlap
/// each other pairwise on the OTHER axis, not merely sit in the same band: a header above two
/// layers side by side is irregular (a row's column group of the header and one of the pair has Y
/// ranges that don't overlap for the pair). The own axis is already covered by `groups`, which
/// chains transitively, so 50 px squares at X 0, 40, 80, 150 are a row although the first and
/// third don't touch.
fn overlapping(group: &[Item], vertical: bool) -> bool {
let across = |a: Rect, b: Rect| {
let (a, b) = (span(a, !vertical), span(b, !vertical));
a.1.min(b.1) - a.0.max(b.0) > EPS
};
group.iter().enumerate().all(|(i, a)| group.iter().skip(i + 1).all(|b| across(a.1, b.1)))
}
fn span(b: Rect, vertical: bool) -> (f64, f64) {
if vertical { (b.y0, b.y1) } else { (b.x0, b.x1) }
}
/// Columns (`vertical` false) or rows: the layers whose ranges on the axis overlap, transitively,
/// in order along the axis.
fn groups(items: &[Item], vertical: bool) -> Vec<Vec<Item>> {
let mut sorted = items.to_vec();
sorted.sort_by(|a, b| span(a.1, vertical).0.total_cmp(&span(b.1, vertical).0));
let mut out: Vec<Vec<Item>> = Vec::new();
let mut end = f64::MIN;
for it in sorted {
let (lo, hi) = span(it.1, vertical);
match out.last_mut() {
Some(group) if lo < end - EPS => {
group.push(it);
end = end.max(hi);
}
_ => {
out.push(vec![it]);
end = hi;
}
}
}
out
}
/// Every (column, row) cell holds exactly one layer.
fn one_per_cell(cols: &[Vec<Item>], rows: &[Vec<Item>]) -> bool {
cols.iter().all(|c| rows.iter().all(|r| c.iter().filter(|a| r.iter().any(|b| b.0 == a.0)).count() == 1))
}
/// The one gap an axis is evened to: `spacing`, a single gap, the most common gap (the smaller of
/// two equally common ones), else the mean rounded to a whole number, half up.
fn even_gap(gaps: &[f64], spacing: Option<f64>) -> f64 {
if let Some(s) = spacing {
return s;
}
if let [only] = gaps {
return *only;
}
let count = |g: f64| gaps.iter().filter(|o| (**o - g).abs() <= EPS).count();
let best = gaps.iter().copied().map(|g| (count(g), g)).reduce(|a, b| if b.0 > a.0 || (b.0 == a.0 && b.1 < a.1) { b } else { a });
match best {
Some((n, g)) if n >= 2 => g,
_ if gaps.is_empty() => 0.0,
_ => (gaps.iter().sum::<f64>() / gaps.len() as f64 + 0.5 + 1e-9).floor(),
}
}
/// The even gap of a line of three or more layers, from its derived gap `gap`: raised so that
/// every layer starts strictly after the end of the layer two places before it. With one gap `g`,
/// layer `i + 2` starts at `end(i) + w(i + 1) + 2g`, so `g > -w(i + 1) / 2` for every interior
/// layer, in whole pixels `floor(-w_min / 2) + 1` for the narrowest interior size `w_min`. Measured
/// in Figma's web app on 2026-11-13: interior widths of 10, 20 and 30 among 100s gave -4, -9 and
/// -14, and widths of 100 left the most common gap, -40, alone. Only those three widths were
/// measured; other widths follow the same formula.
///
/// The first layer has no layer two places before it, but the second must still start after it:
/// `g > -w(0)`, in whole pixels `floor(-w(0)) + 1`. Figma kept the order in every run; a narrow
/// first layer was not measured, so this bound keeps that order rather than following a reading.
fn raise_negative_gap(gap: f64, widths: &[f64]) -> f64 {
let interior = widths.get(1..widths.len().saturating_sub(1)).unwrap_or(&[]);
let w_min = interior.iter().copied().fold(f64::INFINITY, f64::min);
let Some(first) = widths.first().copied() else { return gap };
if widths.len() < 3 || !w_min.is_finite() || !first.is_finite() {
return gap;
}
gap.max((-w_min / 2.0).floor() + 1.0).max((-first).floor() + 1.0)
}
/// A row (`vertical` false) or a column: the first layer stays, each next one follows the last at
/// the even gap, the other axis is untouched.
fn line_moves(items: &[Item], vertical: bool, spacing: Option<f64>) -> Vec<Move> {
let mut line = items.to_vec();
line.sort_by(|a, b| span(a.1, vertical).0.total_cmp(&span(b.1, vertical).0));
let gaps: Vec<f64> = line
.windows(2)
.filter_map(|w| match w {
[a, b] => Some(span(b.1, vertical).0 - span(a.1, vertical).1),
_ => None,
})
.collect();
let widths: Vec<f64> = line.iter().map(|i| span(i.1, vertical).1 - span(i.1, vertical).0).collect();
let gap = match spacing {
Some(s) => s,
None => raise_negative_gap(even_gap(&gaps, None), &widths),
};
let mut pos = line.first().map_or(0.0, |i| span(i.1, vertical).0);
let mut out = Vec::with_capacity(line.len());
for (id, b) in line {
let (lo, hi) = span(b, vertical);
let d = pos - lo;
pos += (hi - lo) + gap;
out.push(if vertical { (id, 0.0, d) } else { (id, d, 0.0) });
}
out
}
fn snap_to(v: f64, snap: bool) -> f64 {
if snap { (v + 0.5).floor() } else { v }
}
/// A unit's box on the packing axis: where it starts and how wide it is (its widest layer, around
/// the middle of the unit's range).
fn unit_box(unit: &[Item], vertical: bool) -> (f64, f64) {
let lo = unit.iter().map(|i| span(i.1, vertical).0).fold(f64::MAX, f64::min);
let hi = unit.iter().map(|i| span(i.1, vertical).1).fold(f64::MIN, f64::max);
let w = unit.iter().map(|i| span(i.1, vertical).1 - span(i.1, vertical).0).fold(0.0, f64::max);
((lo + hi) / 2.0 - w / 2.0, w)
}
/// The gaps inside every unit along the other axis, pooled.
fn unit_gaps(units: &[Vec<Item>], vertical: bool) -> Vec<f64> {
let mut out = Vec::new();
for unit in units {
let mut u = unit.clone();
u.sort_by(|a, b| span(a.1, !vertical).0.total_cmp(&span(b.1, !vertical).0));
out.extend(u.windows(2).filter_map(|w| match w {
[a, b] => Some(span(b.1, !vertical).0 - span(a.1, !vertical).1),
_ => None,
}));
}
out
}
/// A grid packed in `units` (columns, or rows when `vertical`): the units are evened around where
/// they were, every layer is centred in its unit and each unit is laid out from the selection's
/// start on the other axis.
fn grid_moves(units: &[Vec<Item>], vertical: bool, spacing: Option<f64>, snap: bool) -> Vec<Move> {
let boxes: Vec<(f64, f64)> = units.iter().map(|u| unit_box(u, vertical)).collect();
let across: Vec<f64> = boxes
.windows(2)
.filter_map(|w| match w {
[a, b] => Some(b.0 - (a.0 + a.1)),
_ => None,
})
.collect();
let g_units = even_gap(&across, spacing);
let g_within = even_gap(&unit_gaps(units, vertical), spacing);
let start = units.iter().flatten().map(|i| span(i.1, !vertical).0).fold(f64::MAX, f64::min);
let mut at = boxes.first().map_or(0.0, |b| snap_to(b.0, snap));
let mut out = Vec::new();
for (unit, (_, w)) in units.iter().zip(&boxes) {
let mut u = unit.clone();
u.sort_by(|a, b| span(a.1, !vertical).0.total_cmp(&span(b.1, !vertical).0));
let mut pos = start;
for (id, b) in u {
let (lo, hi) = span(b, vertical);
let (lo2, hi2) = span(b, !vertical);
let d_main = snap_to(at + (w - (hi - lo)) / 2.0, snap) - lo;
let d_cross = pos - lo2;
pos += (hi2 - lo2) + g_within;
out.push(if vertical { (id, d_cross, d_main) } else { (id, d_main, d_cross) });
}
at += w + g_units;
}
out
}
@@ -118,8 +118,33 @@ fn layers_at_a_point_list_the_stack_front_most_first() {
let got: Vec<(NodeId, u64)> =
out["layers"].as_array().unwrap().iter().map(|l| (id_of(&l["id"]).unwrap(), l["depth"].as_u64().unwrap())).collect();
assert_eq!(got, vec![(f, 0), (over, 1), (g, 1), (a, 2)]);
assert!(out["layers"].as_array().unwrap().iter().all(|l| l["locked"] == json!(false)), "none is locked");
assert_eq!(out["layers"][0]["type"], json!("FRAME"));
// Nothing under empty canvas; junk is refused.
assert_eq!(ex(&mut s, "select.layersAt", json!({"x": 2000, "y": 2000}))["layers"], json!([]));
assert!(s.execute("select.layersAt", &json!({"x": "left"})).is_err());
}
/// Measured in Figma's web app, 2026-11-10 (Select layer lists a locked layer, and picking it selects it).
#[test]
fn layers_at_a_point_list_locked_layers_with_a_flag_and_select_set_takes_them() {
let mut s = Session::new();
let (f, g, [a, ..], _) = scene(&mut s);
let over = rect_in(&mut s, 10.0, 10.0, Some(f));
let lk = rect_in(&mut s, 10.0, 10.0, Some(f));
ex(&mut s, "object.toggleLock", json!({"ids": [lk], "locked": true}));
let out = ex(&mut s, "select.layersAt", json!({"x": 30, "y": 30}));
let got: Vec<(NodeId, u64, bool)> = out["layers"]
.as_array()
.unwrap()
.iter()
.map(|l| (id_of(&l["id"]).unwrap(), l["depth"].as_u64().unwrap(), l["locked"].as_bool().unwrap()))
.collect();
assert_eq!(got, vec![(f, 0, false), (lk, 1, true), (over, 1, false), (g, 1, false), (a, 2, false)]);
ex(&mut s, "select.set", json!({"ids": [lk]}));
assert_eq!(s.selection(), vec![lk]);
ex(&mut s, "select.none", json!({}));
s.pointer(&ev(PointerKind::Down, 30.0, 30.0, false, false)).unwrap();
s.pointer(&ev(PointerKind::Up, 30.0, 30.0, false, false)).unwrap();
assert_eq!(s.selection(), vec![over], "a click still skips the locked layer");
}
+1 -1
View File
@@ -17,7 +17,7 @@ impl Session {
default_props: Default::default(),
prefs: Prefs::default(),
prefs_unsaved: false,
tool: tools::ToolState::default(),
tool: tools::ToolState { scale_anchor: (1, 1), ..tools::ToolState::default() },
ui_requests: Vec::new(),
ui_dark: None,
journal: Vec::new(),
+1 -1
View File
@@ -65,7 +65,7 @@ impl Session {
/// Replace the document with `f(snapshot)` for a live preview during a gesture.
pub fn preview(&mut self, f: impl FnOnce(&mut Document, &mut Vec<NodeId>) -> Result<()>) -> Result<()> {
let ds = self.ds_mut()?;
let Some(it) = ds.interaction.clone() else { return Err(EngineError::Other("no gesture in progress".into())) };
let Some(it) = ds.interaction.clone() else { return Err(EngineError::NoGesture) };
let mut doc = (*it.doc).clone();
let mut sel = it.selection.clone();
// What the gesture changes on the selected layers is an explicit edit.
+104 -2
View File
@@ -3,6 +3,7 @@
use figcraft_doc::{NodeId, NodeKind};
use figcraft_geom::Point;
use serde_json::{Value, json};
use std::f64::consts::TAU;
use crate::Session;
use crate::params::id_of;
@@ -63,7 +64,11 @@ fn polygon_and_star_handles() {
let doc = s.doc().unwrap().clone();
let hs = handles(&doc, &[star], 1.0);
let kinds: Vec<ShapeHandle> = hs.iter().map(|h| h.0).collect();
assert_eq!(kinds, vec![ShapeHandle::Radius { corner: 0 }, ShapeHandle::Ratio], "a star has a radius and a ratio handle");
assert_eq!(
kinds,
vec![ShapeHandle::Radius { corner: 0 }, ShapeHandle::Ratio, ShapeHandle::Count],
"a star has a radius, a ratio and a count handle"
);
// The ratio handle sits on the first inner point; dragging it to the centre's side shrinks it.
let ratio_at = hs[1].1;
let inner = figcraft_geom::star_points(200.0, 200.0, 5, 0.38)[1];
@@ -78,7 +83,7 @@ fn polygon_and_star_handles() {
assert!(radii(&s, star)[0] > 1.0, "the star's points round");
let mut s = Session::new();
let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
assert_eq!(handles(s.doc().unwrap(), &[poly], 1.0).len(), 1, "a polygon has one radius handle");
assert_eq!(handles(s.doc().unwrap(), &[poly], 1.0).len(), 2, "a polygon has a radius and a count handle");
}
#[test]
@@ -100,3 +105,100 @@ fn handles_show_only_where_they_can_be_used() {
s.execute("vector.edit.begin", &json!({"id": r})).unwrap();
assert!(s.shape_handles().is_empty(), "none while editing points");
}
fn count_of(s: &Session, id: NodeId) -> u32 {
match s.doc().unwrap().node(id).unwrap().kind {
NodeKind::Polygon { count } | NodeKind::Star { count, .. } => count,
_ => panic!("a polygon or star"),
}
}
fn count_handle(s: &Session, id: NodeId) -> [f64; 2] {
handles(s.doc().unwrap(), &[id], 1.0).into_iter().find(|h| h.0 == ShapeHandle::Count).expect("a count handle").1
}
/// The page point at `deg` degrees clockwise from the shape's own top, `r` from its centre (200 x 200 box).
fn at_angle(s: &Session, id: NodeId, deg: f64, r: f64) -> (f64, f64) {
let a = deg.to_radians();
let p = s.doc().unwrap().world_transform(id) * Point::new(100.0 + r * a.sin(), 100.0 - r * a.cos());
(p.x, p.y)
}
fn count_drag(s: &mut Session, id: NodeId, deg: f64) {
let h = count_handle(s, id);
let to = at_angle(s, id, deg, 80.0);
drag(s, (h[0], h[1]), to, false);
}
#[test]
fn a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top() {
let mut s = Session::new();
let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap();
let h = count_handle(&s, poly);
let v1 = figcraft_geom::polygon_points(200.0, 200.0, 5)[1];
assert!((Point::new(h[0], h[1]) - v1).hypot() < 1e-6, "on vertex 1, not inset: {h:?} vs {v1:?}");
assert!((h[0] - (100.0 + 100.0 * (TAU / 5.0).sin())).abs() < 1e-6, "72 degrees from the top");
// Hovering it finds it, not the radius handle.
assert_eq!(hit(s.doc().unwrap(), &[poly], Point::new(h[0], h[1]), 1.0).map(|x| x.1), Some(ShapeHandle::Count));
}
#[test]
fn dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre() {
let mut s = Session::new();
let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap();
for (deg, want) in [(90.0, 4), (45.0, 8), (120.0, 3), (0.5, 60), (0.0, 60), (200.0, 3)] {
count_drag(&mut s, poly, deg);
assert_eq!(count_of(&s, poly), want, "{deg} degrees");
}
// The radius from the centre doesn't matter.
let h = count_handle(&s, poly);
let to = at_angle(&s, poly, 90.0, 30.0);
drag(&mut s, (h[0], h[1]), to, false);
assert_eq!(count_of(&s, poly), 4, "90 degrees near the centre");
// The readout is the count.
let doc = s.doc().unwrap();
assert_eq!(crate::shape_handles::value(doc, poly, ShapeHandle::Count), Some(4.0));
// A pointer on the centre has no direction: it gives the most points.
let h = count_handle(&s, poly);
drag(&mut s, (h[0], h[1]), (100.0, 100.0), false);
assert_eq!(count_of(&s, poly), 60, "a pointer on the centre");
}
#[test]
fn dragging_a_stars_count_handle_sets_its_points() {
let mut s = Session::new();
let star = create(&mut s, "shape.star", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
let h = count_handle(&s, star);
let outer = figcraft_geom::star_points(200.0, 200.0, 5, 0.38)[2];
assert!((Point::new(h[0], h[1]) - outer).hypot() < 1e-6, "on its first outer point clockwise from the top");
for (deg, want) in [(90.0, 4), (45.0, 8), (130.0, 3), (1.0, 60)] {
count_drag(&mut s, star, deg);
assert_eq!(count_of(&s, star), want, "{deg} degrees");
}
let NodeKind::Star { inner_ratio, .. } = s.doc().unwrap().node(star).unwrap().kind else { panic!("star") };
assert!((inner_ratio - 0.38).abs() < 0.02, "the ratio stays through count drags: {inner_ratio}");
}
#[test]
fn a_count_drag_is_one_undo_step() {
let mut s = Session::new();
let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap();
count_drag(&mut s, poly, 45.0);
assert_eq!(count_of(&s, poly), 8);
s.undo().unwrap();
assert_eq!(count_of(&s, poly), 5, "one Ctrl+Z takes the drag back");
}
#[test]
fn a_rotated_polygons_count_angle_is_measured_in_its_own_frame() {
let mut s = Session::new();
let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200}));
s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5, "rotation": 30}})).unwrap();
for (deg, want) in [(90.0, 4), (45.0, 8)] {
count_drag(&mut s, poly, deg);
assert_eq!(count_of(&s, poly), want, "{deg} degrees in the shape's frame");
}
}
+373
View File
@@ -0,0 +1,373 @@
//! Tidy up (`arrange.tidy`) against what was measured in Figma's web app on 2026-11-12: a row, a
//! column and a 2 x 3 grid of unequal sizes, eight runs on the gap, and the cases where the menu
//! row is greyed out. Figma keeps the order and sizes, evens one gap per axis and keeps the first
//! layer where it is. Tests whose message says "not measured in Figma" pin FigCraft's own choice.
use crate::Session;
use figcraft_doc::NodeId;
use serde_json::json;
fn make(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn xy(s: &Session, id: NodeId) -> (f64, f64) {
let b = s.doc().unwrap().world_bounds(id).unwrap();
(b.x0, b.y0)
}
fn size(s: &Session, id: NodeId) -> (f64, f64) {
let n = s.doc().unwrap().node(id).unwrap();
(n.width, n.height)
}
fn tidy(s: &mut Session, ids: &[NodeId]) {
s.execute("arrange.tidy", &json!({"ids": ids})).unwrap();
}
fn can(s: &Session, ids: &[NodeId]) -> bool {
crate::tidy::can_tidy(s.doc().unwrap(), ids)
}
fn all_xy(s: &Session, ids: &[NodeId]) -> Vec<(f64, f64)> {
ids.iter().map(|i| xy(s, *i)).collect()
}
/// Squares of 50 at Y 0 with the given X values.
fn squares(s: &mut Session, xs: &[f64]) -> Vec<NodeId> {
xs.iter().map(|x| make(s, *x, 0.0, 50.0, 50.0)).collect()
}
fn xs_of(s: &Session, ids: &[NodeId]) -> Vec<f64> {
ids.iter().map(|i| xy(s, *i).0).collect()
}
fn row(s: &mut Session, xs: [f64; 4]) -> Vec<NodeId> {
vec![make(s, xs[0], 0., 50., 30.), make(s, xs[1], 10., 70., 50.), make(s, xs[2], -5., 40., 40.), make(s, xs[3], 8., 60., 20.)]
}
fn grid(s: &mut Session) -> Vec<NodeId> {
vec![
make(s, 0., 0., 50., 30.),
make(s, 80., 5., 70., 50.),
make(s, 190., -3., 40., 40.),
make(s, 2., 90., 60., 20.),
make(s, 85., 95., 40., 50.),
make(s, 200., 92., 55., 35.),
]
}
#[test]
fn a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps() {
let mut s = Session::new();
let ids = row(&mut s, [0., 80., 190., 260.]);
let before = s.undo_depth();
tidy(&mut s, &ids);
assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (80., 10.), (180., -5.), (250., 8.)]);
assert_eq!(size(&s, ids[1]), (70., 50.));
assert_eq!(size(&s, ids[3]), (60., 20.));
assert_eq!(s.undo_depth().0, before.0 + 1);
s.undo().unwrap();
assert_eq!(xy(&s, ids[3]), (260., 8.));
}
#[test]
fn gaps_that_all_differ_take_their_mean_taken_down() {
let mut s = Session::new();
let ids = row(&mut s, [0., 130., 220., 305.]);
tidy(&mut s, &ids);
assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (98., 10.), (216., -5.), (304., 8.)]);
// Gaps 30, 40, 21 (the third layer 49 wide, 50 tall).
let mut s = Session::new();
let ids =
vec![make(&mut s, 0., 0., 50., 30.), make(&mut s, 80., 10., 70., 50.), make(&mut s, 190., -5., 49., 50.), make(&mut s, 260., 8., 60., 20.)];
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 80., 180., 259.]);
}
#[test]
fn a_column_keeps_x_and_evens_the_vertical_gaps() {
let mut s = Session::new();
let ids =
vec![make(&mut s, 0., 0., 50., 30.), make(&mut s, 8., 60., 70., 50.), make(&mut s, -5., 150., 40., 40.), make(&mut s, 6., 220., 60., 20.)];
tidy(&mut s, &ids);
assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (8., 60.), (-5., 140.), (6., 210.)]);
}
#[test]
fn the_gap_is_the_most_common_one_else_the_mean() {
// (X before, widths, X after): cases 1, 2, 3, 4, 5, 7 and 8 of the second run.
let cases: [(&[f64], &[f64], &[f64]); 7] = [
(&[0., 60., 160.], &[50., 50., 50.], &[0., 80., 160.]),
(&[0., 100., 160.], &[50., 50., 50.], &[0., 80., 160.]),
(&[0., 70., 140.], &[50., 50., 50.], &[0., 70., 140.]),
(&[0., 50., 160.], &[50., 50., 50.], &[0., 80., 160.]),
(&[0., 60., 120., 240.], &[50., 50., 50., 50.], &[0., 60., 120., 180.]),
(&[0., 70., 210.], &[50., 100., 30.], &[0., 80., 210.]),
(&[0., 60., 120., 220., 360.], &[50., 50., 50., 50., 50.], &[0., 60., 120., 180., 240.]),
];
for (n, (before, widths, after)) in cases.iter().enumerate() {
let mut s = Session::new();
let ids: Vec<NodeId> = before.iter().zip(widths.iter()).map(|(x, w)| make(&mut s, *x, 0., *w, 50.)).collect();
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), after.to_vec(), "case {n}");
assert!(xy(&s, ids[0]).1 == 0.0 && xy(&s, ids[1]).1 == 0.0, "case {n}: Y kept");
}
}
/// Within a pixel: Figma read 52 for the vertical gap in one column and 51 in two (the mean of 60,
/// 40, 55 is 51.67), probably from pixel snapping, so a layer's place along a stack may differ by one.
fn near(got: &[(f64, f64)], want: &[(f64, f64)]) {
assert_eq!(got.len(), want.len());
for (g, w) in got.iter().zip(want) {
assert!((g.0 - w.0).abs() <= 1.0 && (g.1 - w.1).abs() <= 1.0, "{got:?} vs {want:?}");
}
}
#[test]
fn a_grid_is_tidied_by_columns() {
let mut s = Session::new();
let ids = grid(&mut s);
tidy(&mut s, &ids);
near(&all_xy(&s, &ids), &[(6., -3.), (93., -3.), (203., -3.), (1., 79.), (108., 98.), (195., 88.)]);
assert_eq!(size(&s, ids[4]), (40., 50.));
}
#[test]
fn a_transposed_grid_is_tidied_by_rows() {
let mut s = Session::new();
let ids = vec![
make(&mut s, 0., 0., 30., 50.),
make(&mut s, 5., 80., 50., 70.),
make(&mut s, -3., 190., 40., 40.),
make(&mut s, 90., 2., 20., 60.),
make(&mut s, 95., 85., 50., 40.),
make(&mut s, 92., 200., 35., 55.),
];
tidy(&mut s, &ids);
near(&all_xy(&s, &ids), &[(-3., 6.), (-3., 93.), (-3., 203.), (78., 1.), (98., 108.), (88., 195.)]);
}
#[test]
fn two_layers_and_a_selection_in_one_cell_are_left_alone() {
let mut s = Session::new();
let two = squares(&mut s, &[0., 87.]);
let before = (all_xy(&s, &two), s.undo_depth());
tidy(&mut s, &two);
assert_eq!((all_xy(&s, &two), s.undo_depth()), before, "two layers");
assert!(!can(&s, &two));
let mut s = Session::new();
let tri = vec![make(&mut s, 100., 460., 50., 30.), make(&mut s, 140., 430., 80., 60.), make(&mut s, 130., 400., 30., 90.)];
let before = (all_xy(&s, &tri), s.undo_depth());
tidy(&mut s, &tri);
assert_eq!((all_xy(&s, &tri), s.undo_depth()), before, "overlapping triple");
assert!(!can(&s, &tri));
}
#[test]
fn a_tidy_that_moves_nothing_adds_no_undo_step() {
let mut s = Session::new();
let ids = squares(&mut s, &[0., 70., 140.]);
let before = s.undo_depth();
tidy(&mut s, &ids);
assert_eq!(s.undo_depth(), before);
assert_eq!(xs_of(&s, &ids), vec![0., 70., 140.]);
assert!(can(&s, &ids));
}
#[test]
fn two_equally_common_gaps_give_the_smaller() {
let mut s = Session::new();
let ids = squares(&mut s, &[0., 60., 120., 220., 320.]);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 60., 120., 180., 240.]);
}
#[test]
fn a_mean_is_rounded_half_up() {
let mut s = Session::new();
let ids = squares(&mut s, &[0., 60., 135.]);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 68., 136.], "a mean of 17.5 goes up");
let mut s = Session::new();
let ids = squares(&mut s, &[0., 60., 135., 215.]);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 72., 144., 216.], "a mean of 21.67 goes to 22");
}
#[test]
fn layers_on_a_diagonal_are_unavailable() {
let mut s = Session::new();
let ids = vec![make(&mut s, 0., 0., 50., 50.), make(&mut s, 60., 70., 50., 50.), make(&mut s, 140., 150., 50., 50.)];
let before = (all_xy(&s, &ids), s.undo_depth());
tidy(&mut s, &ids);
assert_eq!((all_xy(&s, &ids), s.undo_depth()), before);
assert!(!can(&s, &ids));
}
#[test]
fn a_grid_with_an_empty_place_is_unavailable() {
let mut s = Session::new();
let ids = vec![
make(&mut s, 0., 0., 50., 50.),
make(&mut s, 70., 0., 50., 50.),
make(&mut s, 150., 0., 50., 50.),
make(&mut s, 0., 80., 50., 50.),
make(&mut s, 72., 90., 50., 50.),
];
let before = (all_xy(&s, &ids), s.undo_depth());
tidy(&mut s, &ids);
assert_eq!((all_xy(&s, &ids), s.undo_depth()), before, "not measured in Figma: an empty place in a grid");
assert!(!can(&s, &ids), "not measured in Figma: an empty place in a grid");
}
#[test]
fn an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts() {
let mut s = Session::new();
let ids = squares(&mut s, &[0., 60., 105., 170.]);
assert!(can(&s, &ids));
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 57., 114., 171.], "gaps 10, -5, 15 have the mean 6.67, which gives 7");
}
#[test]
fn layers_in_an_auto_layout_flow_are_left_alone() {
let mut s = Session::new();
let f = NodeId(
s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 400, "height": 100, "props": {"layout": "horizontal"}})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let ids: Vec<NodeId> = (0..3)
.map(|_| NodeId(s.execute("shape.rectangle", &json!({"width": 50, "height": 50, "parent": f})).unwrap()["id"].as_u64().unwrap()))
.collect();
let before = (all_xy(&s, &ids), s.undo_depth());
tidy(&mut s, &ids);
assert_eq!((all_xy(&s, &ids), s.undo_depth()), before, "not measured in Figma: auto layout flow children");
assert!(!can(&s, &ids), "not measured in Figma: auto layout flow children");
for id in &ids {
s.execute("node.set", &json!({"id": id, "props": {"absolute": true}})).unwrap();
}
for (id, x) in ids.iter().zip([0., 60., 160.]) {
s.execute("node.set", &json!({"id": id, "props": {"x": x, "y": 0}})).unwrap();
}
assert_eq!(xs_of(&s, &ids), vec![0., 60., 160.]);
assert!(can(&s, &ids));
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 80., 160.]);
}
#[test]
fn an_irregular_selection_is_unavailable() {
let mut s = Session::new();
let ids = vec![make(&mut s, 0., 0., 200., 30.), make(&mut s, 0., 50., 90., 50.), make(&mut s, 110., 50., 90., 50.)];
let before = (all_xy(&s, &ids), s.undo_depth());
tidy(&mut s, &ids);
assert_eq!((all_xy(&s, &ids), s.undo_depth()), before);
assert!(!can(&s, &ids));
}
#[test]
fn spacing_sets_the_gap_and_takes_two_layers() {
let mut s = Session::new();
let ids = squares(&mut s, &[0., 60., 160.]);
s.execute("arrange.tidy", &json!({"ids": ids, "spacing": 12})).unwrap();
assert_eq!(xs_of(&s, &ids), vec![0., 62., 124.]);
let mut s = Session::new();
let two = squares(&mut s, &[0., 87.]);
s.execute("arrange.tidy", &json!({"ids": two, "spacing": 12})).unwrap();
assert_eq!(xs_of(&s, &two), vec![0., 62.]);
assert!(!can(&s, &two));
}
#[test]
fn without_pixel_snapping_a_centred_layer_keeps_its_half_pixel() {
let mut s = Session::new();
s.execute("view.snapPixel", &json!({"on": false})).unwrap();
let ids = grid(&mut s);
tidy(&mut s, &ids);
let got = all_xy(&s, &ids);
assert_eq!(got.get(2).map(|p| p.0), Some(202.5), "not measured in Figma: no rounding with Snap to pixel grid off");
near(&got, &[(6., -3.), (93., -3.), (202.5, -3.), (1., 79.), (108., 98.), (195., 88.)]);
}
#[test]
fn a_rotated_layer_is_tidied_by_its_box() {
let mut s = Session::new();
let a = make(&mut s, 0., 0., 50., 50.);
let m = make(&mut s, 80., 0., 40., 40.);
let c = make(&mut s, 200., 0., 50., 50.);
s.execute("node.set", &json!({"id": m, "props": {"rotation": 30}})).unwrap();
let boxes = |s: &Session| -> Vec<figcraft_geom::Rect> { [a, m, c].iter().map(|i| s.doc().unwrap().world_bounds(*i).unwrap()).collect() };
let b = boxes(&s);
let (g1, g2) = (b[1].x0 - b[0].x1, b[2].x0 - b[1].x1);
let want = ((g1 + g2) / 2.0 + 0.5).floor();
let rot = figcraft_geom::rotation_degrees(s.doc().unwrap().node(m).unwrap().transform);
tidy(&mut s, &[a, m, c]);
let b = boxes(&s);
assert_eq!(b[0].x0, 0.0);
assert!(((b[1].x0 - b[0].x1) - want).abs() < 1e-6);
assert!(((b[2].x0 - b[1].x1) - want).abs() < 1e-6);
let after = figcraft_geom::rotation_degrees(s.doc().unwrap().node(m).unwrap().transform);
assert!((rot - after).abs() < 1e-9, "rotation unchanged");
}
/// Rectangles at Y 0, H 50 with the given (X, W) pairs.
fn bars(s: &mut Session, xw: &[(f64, f64)]) -> Vec<NodeId> {
xw.iter().map(|(x, w)| make(s, *x, 0.0, *w, 50.0)).collect()
}
#[test]
fn a_row_whose_layers_overlap_in_a_chain_is_tidied_at_its_most_common_gap() {
// Measured in Figma's web app on 2026-11-13: gaps -10, -10, 20 give X 0, 40, 80, 120.
let mut s = Session::new();
let ids = squares(&mut s, &[0., 40., 80., 150.]);
assert!(can(&s, &ids), "the first and third layers don't overlap, the chain still counts as a row");
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 40., 80., 120.]);
}
#[test]
fn a_negative_gap_is_raised_so_no_layer_reaches_the_one_two_before() {
// Measured in Figma's web app on 2026-11-13, X before 0, 80, 200, 260, 400, 460.
let cases: [([f64; 6], [f64; 6]); 4] = [
([100., 10., 100., 100., 100., 100.], [0., 96., 102., 198., 294., 390.]),
([100., 20., 100., 100., 100., 100.], [0., 91., 102., 193., 284., 375.]),
([100., 30., 100., 100., 100., 100.], [0., 86., 102., 188., 274., 360.]),
([100., 100., 100., 10., 100., 100.], [0., 96., 192., 288., 294., 390.]),
];
for (widths, want) in cases {
let mut s = Session::new();
let xs = [0., 80., 200., 260., 400., 460.];
let pairs: Vec<(f64, f64)> = xs.iter().copied().zip(widths).collect();
let ids = bars(&mut s, &pairs);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), want.to_vec(), "widths {widths:?}");
}
}
#[test]
fn a_narrow_first_layer_still_keeps_the_second_after_it() {
// Not measured in Figma (it kept the order in every run): the modal gap -40 would start the
// second layer at -30, before a 10 wide first layer, so the gap is raised to -9.
let mut s = Session::new();
let xs = [0., 80., 200., 260., 400., 460.];
let widths = [10., 100., 100., 100., 100., 100.];
let pairs: Vec<(f64, f64)> = xs.iter().copied().zip(widths).collect();
let ids = bars(&mut s, &pairs);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 1., 92., 183., 274., 365.]);
}
#[test]
fn a_negative_gap_between_equal_widths_is_the_most_common_gap() {
let mut s = Session::new();
let xs = [0., 80., 200., 260., 400., 460.];
let pairs: Vec<(f64, f64)> = xs.iter().map(|x| (*x, 100.)).collect();
let ids = bars(&mut s, &pairs);
tidy(&mut s, &ids);
assert_eq!(xs_of(&s, &ids), vec![0., 60., 120., 180., 240., 300.]);
}
#[test]
fn an_explicit_spacing_is_not_raised() {
// Not measured in Figma: the Spacing field stays as typed.
let mut s = Session::new();
let pairs: Vec<(f64, f64)> = [(0., 100.), (80., 10.), (200., 100.)].to_vec();
let ids = bars(&mut s, &pairs);
s.execute("arrange.tidy", &json!({"ids": ids, "spacing": -40})).unwrap();
assert_eq!(xs_of(&s, &ids), vec![0., 60., 30.]);
}
+3
View File
@@ -20,3 +20,6 @@ ruzstd = { workspace = true }
sha1 = { workspace = true }
sha2 = { workspace = true }
image = { workspace = true }
craft-fig = { workspace = true }
craft-figcraft-format = { workspace = true }
craft-figma-rest = { workspace = true }
+19 -276
View File
@@ -26,13 +26,11 @@ mod export;
mod export_tests;
#[cfg(test)]
mod interop_tests;
pub mod kiwi;
#[cfg(test)]
mod layer_cap_tests;
mod map;
#[cfg(test)]
mod missing_image_tests;
mod network;
#[cfg(test)]
mod paste_style_tests;
#[cfg(test)]
@@ -49,7 +47,6 @@ mod source_identity_tests;
mod tests;
#[cfg(test)]
mod text_paragraph_tests;
mod text_path;
#[cfg(test)]
mod text_path_tests;
#[cfg(test)]
@@ -63,27 +60,22 @@ mod value_budget_tests;
#[cfg(test)]
mod vector_scale_tests;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::io::Read;
use std::sync::Arc;
use figcraft_doc::{Document, FileKind};
pub use export::export;
use crate::FormatError;
use kiwi::{Kv, Schema};
#[cfg(test)]
use craft_fig::rest::MAX_FIG_NODES;
pub(crate) use craft_fig::rest::layer_budget;
use craft_fig::{Archive, Limits, decode_canvas, embedded_aliases, embedded_copies, kiwi};
pub use craft_fig::{JAM_HEADER, is_fig};
#[cfg(test)]
use craft_fig::{MAX_CANVAS, chunks, network};
pub(crate) use craft_figma_rest::style_name;
/// Largest `canvas.fig` member read, and largest decompressed chunk.
const MAX_CANVAS: u64 = 256 * 1024 * 1024;
const MAX_CHUNK: u64 = 512 * 1024 * 1024;
/// Largest decompressed schema chunk: Figma's schema unpacks to well under 1 MB, so a schema that
/// inflates past this is refused before its definitions are decoded.
const MAX_SCHEMA: u64 = 16 * 1024 * 1024;
/// Longest image hash (bytes) an image is found by: `images/` names and embedded images both
/// stop at 64 bytes (128 hex digits).
pub(crate) const MAX_IMAGE_HASH: usize = 64;
/// Largest image member read.
const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES;
/// Total decompressed ZIP image bytes read per import: the native image budget (`IMAGE_BUDGET`) on
@@ -93,35 +85,6 @@ const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES;
const MAX_IMAGE_BYTES: u64 = crate::IMAGE_BUDGET.bytes;
#[cfg(target_pointer_width = "32")]
const MAX_IMAGE_BYTES: u64 = 1024 * 1024 * 1024;
/// Most chunks read from `canvas.fig`.
const MAX_CHUNKS: usize = 16;
/// Most layers imported from a `.fig` file: one per [`PACKED_BYTES_PER_LAYER`] bytes of its
/// compressed canvas, at least the REST import's cap and at most [`MAX_FIG_NODES`]. Instances
/// expand into a layer per layer of their component, and chunks inflate up to [`MAX_CHUNK`], so the
/// budget follows what the file takes, not what it unpacks to: a small file can't claim a large
/// count, however it's built; a large one gets room. Design systems are mostly instances, which
/// pack tightly: a 7.8 MB canvas stopped at 244 248 layers at 32 bytes a layer (#981). At 8, files
/// under about 1.6 MB keep the floor and the ceiling comes at a 16 MB canvas (about 11 GB and 40 s
/// to import 2 million synthetic layers; memory grows with the count, about 5.4 KB a layer).
const PACKED_BYTES_PER_LAYER: usize = 8;
const MAX_FIG_NODES: usize = 2_000_000;
/// Most layers imported from a `.fig` file whose compressed canvas is `packed` bytes.
pub(crate) fn layer_budget(packed: usize) -> usize {
(packed / PACKED_BYTES_PER_LAYER).clamp(crate::rest::MAX_NODES, MAX_FIG_NODES)
}
/// The canvas header of a FigJam whiteboard (a `.jam`); a `.fig` has `fig-kiwi`.
pub const JAM_HEADER: &[u8] = b"fig-jam.";
/// Whether `bytes` look like a `.fig` file: a zip holding `canvas.fig`, or a bare canvas.
pub fn is_fig(bytes: &[u8]) -> bool {
bytes.starts_with(b"fig-") || (bytes.starts_with(b"PK") && zip_has_canvas(bytes))
}
fn zip_has_canvas(bytes: &[u8]) -> bool {
zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| z.file_names().any(|n| n == "canvas.fig"))
}
/// Import `bytes` when they are a `.fig` file; `None` when they are something else.
pub fn try_import(bytes: &[u8], name: &str) -> Option<Result<(Document, Vec<String>), FormatError>> {
@@ -135,24 +98,23 @@ pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec<String>), Forma
}
fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result<(Document, Vec<String>), FormatError> {
let mut archive = Archive::open(bytes)?;
archive.image_budget.remaining.set(image_limit);
let mut archive = Archive::open_with(bytes, Limits { max_image: MAX_IMAGE, max_image_total: image_limit }).map_err(fig_err)?;
// The budgets follow the compressed canvas, which the file itself bounds (its zip member may
// inflate too).
let packed = archive.canvas.len().min(bytes.len());
// FigJam writes its whiteboards with this header: they open as boards.
let board = archive.canvas.starts_with(JAM_HEADER);
let board = archive.is_board();
// Each stage's input is dropped as soon as the next one is built: in a large file every one
// of them takes gigabytes, and holding them all at once runs out of memory.
let (schema, message) = decode_canvas(&std::mem::take(&mut archive.canvas))?;
let (schema, message) = decode_canvas(&std::mem::take(&mut archive.canvas)).map_err(fig_err)?;
let root = schema.find("Message").ok_or_else(|| corrupt("the schema has no Message definition"))?;
let msg = schema.decode_message_within(root, &message, kiwi::value_budget(packed)).map_err(|e| corrupt(e.to_string()))?;
let msg = schema.decode_message_within(root, &message, craft_fig::value_budget(packed)).map_err(|e| corrupt(e.to_string()))?;
let max_nodes = layer_budget(packed);
drop(message);
let file_name = archive.file_name.as_deref().filter(|n| !n.trim().is_empty()).unwrap_or(name);
let (mut json, mut warnings, networks) = map::to_rest_for(&msg, file_name, max_nodes, board);
// The message goes before the layers are built, so the images it carries are copied out first.
let embedded = embedded_copies(&msg);
let embedded = embedded_copies(&msg, MAX_IMAGE);
drop(msg);
let aliases = embedded_aliases(&embedded, |hash| archive.has_image(hash));
if !aliases.is_empty() {
@@ -160,7 +122,7 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result
}
let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec()));
let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?;
let skipped = archive.image_budget.skipped.get();
let skipped = archive.images_skipped();
if skipped > 0 {
warnings.push(format!("{skipped} ZIP image(s) skipped by the total ZIP image byte budget ({image_limit} bytes)"));
}
@@ -177,87 +139,16 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result
Ok((doc, warnings))
}
/// A font style under the name the format uses: the standard weight names as words ("SemiBold"
/// → "Semi Bold", "ExtraBoldItalic" → "Extra Bold Italic", "Regular Italic" → "Italic"). Other
/// names stay as they are.
pub(crate) fn style_name(style: &str) -> String {
const WEIGHTS: [&str; 12] =
["Thin", "Extra Light", "Ultra Light", "Light", "Regular", "Medium", "Semi Bold", "Demi Bold", "Bold", "Extra Bold", "Ultra Bold", "Black"];
let compact = |s: &str| s.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).flat_map(char::to_lowercase).collect::<String>();
let key = compact(style);
let (base, italic) = match key.strip_suffix("italic") {
Some(b) => (b, true),
None => (key.as_str(), false),
};
let weight = if base.is_empty() && italic { Some("Regular") } else { WEIGHTS.into_iter().find(|w| compact(w) == base) };
match (weight, italic) {
(None, _) => style.to_string(),
(Some("Regular"), true) => "Italic".into(),
(Some(w), true) => format!("{w} Italic"),
(Some(w), false) => w.into(),
}
}
fn corrupt(msg: impl Into<String>) -> FormatError {
FormatError::Corrupt(format!(".fig file: {}", msg.into()))
}
/// Image bytes that travel inside the message, by image hash (lowercase hex): a paint's
/// `image.dataBlob` indexes the message's `blobs`. Copies written by plugins and other tools embed
/// their images this way, and a bare canvas (what the clipboard carries) has no `images/`. The
/// walk is iterative (no recursion on nested data) and skips blobs larger than [`MAX_IMAGE`].
/// Returns the index of each hash's blob.
fn embedded_images(msg: &Kv) -> BTreeMap<String, usize> {
let blobs = msg.get("blobs").map(Kv::list).unwrap_or_default();
let mut found = BTreeMap::new();
let mut pending = vec![msg];
while let Some(value) = pending.pop() {
match value {
Kv::Object(fields) => {
if let Some((hash, index)) = value.get("image").and_then(|image| embedded_image(image, blobs)) {
found.entry(hash).or_insert(index);
}
pending.extend(fields.iter().filter(|(name, _)| *name != "blobs").map(|(_, field)| field));
}
Kv::Array(items) => pending.extend(items),
_ => {}
}
/// A `.fig` read or write failure as the app reports it (`Corrupt` already says `.fig file:`).
pub(crate) fn fig_err(e: craft_fig::Error) -> FormatError {
match e {
craft_fig::Error::Corrupt(_) => FormatError::Corrupt(e.to_string()),
craft_fig::Error::TooLarge | craft_fig::Error::Io(_) => FormatError::Io(e.to_string()),
}
found
}
/// The images that travel inside the message ([`embedded_images`]), copied out of it once per
/// blob: every hash naming the same blob shares its copy. A file can point any number of hashes
/// at one large blob, and a copy for each would multiply it (#1059).
fn embedded_copies(msg: &Kv) -> BTreeMap<String, Arc<[u8]>> {
let blobs = msg.get("blobs").map(Kv::list).unwrap_or_default();
let mut copies: BTreeMap<usize, Arc<[u8]>> = BTreeMap::new();
let mut out = BTreeMap::new();
for (hash, index) in embedded_images(msg) {
let Some(bytes) = blob(blobs, index) else { continue };
out.insert(hash, Arc::clone(copies.entry(index).or_insert_with(|| Arc::from(bytes))));
}
out
}
/// Embedded images ([`embedded_copies`]) whose blob an earlier hash already names, each with that
/// hash. Hashes that also have an `images/` member keep their own name: the member is read first.
/// Pointing every alias at one name has the import copy and hash each blob once, however many
/// hashes a file points at it.
fn embedded_aliases(embedded: &BTreeMap<String, Arc<[u8]>>, in_zip: impl Fn(&str) -> bool) -> BTreeMap<String, String> {
let mut first: BTreeMap<usize, &String> = BTreeMap::new();
let mut out = BTreeMap::new();
for (hash, bytes) in embedded {
if in_zip(hash) {
continue;
}
// Hashes naming one blob share its copy, so the copy's address tells the blob.
let canonical = *first.entry(bytes.as_ptr() as usize).or_insert(hash);
if canonical != hash {
out.insert(hash.clone(), canonical.clone());
}
}
out
}
/// Rename every `imageRef` in REST `json` found in `aliases` to the name it maps to.
@@ -284,154 +175,6 @@ fn canonical_image_refs(json: &mut serde_json::Value, aliases: &BTreeMap<String,
}
}
/// The hash and blob index of an `Image` value whose `dataBlob` points at a usable blob.
fn embedded_image(image: &Kv, blobs: &[Kv]) -> Option<(String, usize)> {
let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= MAX_IMAGE_HASH)?;
let Some(Kv::Uint(index)) = image.get("dataBlob") else { return None };
let index = usize::try_from(*index).ok()?;
let bytes = blob(blobs, index)?;
if bytes.is_empty() || bytes.len() as u64 > MAX_IMAGE {
return None;
}
Some((hash.iter().map(|b| format!("{b:02x}")).collect(), index))
}
/// The bytes of blob `index`.
fn blob<'k>(blobs: &'k [Kv], index: usize) -> Option<&'k [u8]> {
blobs.get(index)?.get("bytes").and_then(Kv::bytes)
}
/// Bytes left for ZIP image reads, including damaged images. The REST resolver caches references,
/// including failures, so each referenced member is read or counted as skipped only once.
struct ZipImageBudget {
remaining: Cell<u64>,
skipped: Cell<usize>,
}
/// The parts of a `.fig` archive the import reads.
struct Archive<'b> {
canvas: Vec<u8>,
file_name: Option<String>,
/// `images/<hash>` members (or nothing for a bare canvas).
zip: Option<zip::ZipArchive<std::io::Cursor<&'b [u8]>>>,
image_budget: ZipImageBudget,
}
impl<'b> Archive<'b> {
fn open(bytes: &'b [u8]) -> Result<Self, FormatError> {
let image_budget = ZipImageBudget { remaining: Cell::new(MAX_IMAGE_BYTES), skipped: Cell::new(0) };
if bytes.starts_with(b"fig-") {
return Ok(Archive { canvas: bytes.to_vec(), file_name: None, zip: None, image_budget });
}
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| corrupt(e.to_string()))?;
let canvas = crate::read_member(&mut z, "canvas.fig", MAX_CANVAS)?;
let file_name = crate::read_member(&mut z, "meta.json", 1 << 20)
.ok()
.and_then(|m| serde_json::from_slice::<serde_json::Value>(&m).ok())
.and_then(|m| m.get("file_name").and_then(serde_json::Value::as_str).map(str::to_string));
Ok(Archive { canvas, file_name, zip: Some(z), image_budget })
}
/// Whether `images/` has a member for image `hash`.
fn has_image(&self, hash: &str) -> bool {
self.zip.as_ref().is_some_and(|z| z.index_for_name(&format!("images/{hash}")).is_some())
}
/// Bytes of image `hash` (lowercase hex) from `images/`.
fn image(&self, hash: &str) -> Option<Vec<u8>> {
let budget = &self.image_budget;
if hash.is_empty() || hash.len() > 2 * MAX_IMAGE_HASH || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
// A clone shares the parsed directory and the bytes; the resolver only has shared access.
let mut z = self.zip.clone()?;
let f = z.by_name(&format!("images/{hash}")).ok()?;
let size = f.size();
if size > MAX_IMAGE {
return None;
}
let remaining = budget.remaining.get();
if size > remaining {
budget.skipped.set(budget.skipped.get() + 1);
return None;
}
let checksum = f.crc32();
let mut data = Vec::new();
// Probe past the per-image cap only when the total budget has room. Even a dishonest
// size cannot make the read exceed the remaining total; failed reads keep their charge.
let limit = remaining.min(MAX_IMAGE + 1);
let read = f.take(limit).read_to_end(&mut data);
let used = data.len() as u64;
budget.remaining.set(remaining - used);
if used > size && used == remaining {
budget.skipped.set(budget.skipped.get() + 1);
}
if read.is_err() || used != size {
return None;
}
// `take` can stop exactly at the budget without asking ZIP for EOF (where it checks CRC).
// Check it here too, without spending an extra byte on an overflow probe.
if used == limit {
let mut crc = flate2::Crc::new();
crc.update(&data);
if crc.sum() != checksum {
return None;
}
}
Some(data)
}
}
/// The schema and the raw message of a `canvas.fig`.
fn decode_canvas(canvas: &[u8]) -> Result<(Schema, Vec<u8>), FormatError> {
let chunks = chunks(canvas)?;
let mut it = chunks.into_iter();
let (Some(schema), Some(message)) = (it.next(), it.next()) else {
return Err(corrupt("canvas.fig needs a schema and a message chunk"));
};
let schema = Schema::decode(&inflate_within(schema, MAX_SCHEMA)?).map_err(|e| corrupt(e.to_string()))?;
Ok((schema, inflate(message)?))
}
/// The length-prefixed chunks after the 12-byte header.
fn chunks(canvas: &[u8]) -> Result<Vec<&[u8]>, FormatError> {
if canvas.len() < 12 || !canvas.starts_with(b"fig-") {
return Err(corrupt("canvas.fig has no header"));
}
let mut out = Vec::new();
let mut pos = 12usize;
while pos < canvas.len() && out.len() < MAX_CHUNKS {
let len = canvas.get(pos..pos + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| corrupt("truncated chunk"))?;
let start = pos + 4;
let end = start.checked_add(len as usize).filter(|e| *e <= canvas.len()).ok_or_else(|| corrupt("truncated chunk"))?;
out.push(canvas.get(start..end).unwrap_or_default());
pos = end;
}
Ok(out)
}
/// Decompress a chunk: zstd (by its magic number), else raw deflate, else zlib.
fn inflate(data: &[u8]) -> Result<Vec<u8>, FormatError> {
inflate_within(data, MAX_CHUNK)
}
/// [`inflate`] refusing a chunk that unpacks to more than `max` bytes.
fn inflate_within(data: &[u8], max: u64) -> Result<Vec<u8>, FormatError> {
let capped = |r: &mut dyn Read| -> Option<Vec<u8>> {
let mut out = Vec::new();
r.take(max.saturating_add(1)).read_to_end(&mut out).ok()?;
(out.len() as u64 <= max).then_some(out)
};
if data.starts_with(&[0x28, 0xB5, 0x2F, 0xFD]) {
let mut src = data;
let mut dec = ruzstd::decoding::StreamingDecoder::new(&mut src).map_err(|e| corrupt(format!("zstd: {e}")))?;
return capped(&mut dec).ok_or_else(|| corrupt("damaged or oversized zstd chunk"));
}
capped(&mut flate2::read::DeflateDecoder::new(data))
.or_else(|| capped(&mut flate2::read::ZlibDecoder::new(data)))
.ok_or_else(|| corrupt("damaged or oversized deflate chunk"))
}
/// Decoded message `msg` as JSON (byte arrays as their length), for looking at files.
#[cfg(test)]
pub(crate) fn debug_json(v: &kiwi::Kv) -> serde_json::Value {
@@ -249,7 +249,7 @@ fn a_routed_connector_takes_its_line_style_from_the_generated_record() {
assert_eq!(connector["strokeWeight"], 4.0);
assert_eq!(connector["strokeDashes"], serde_json::json!([16.0, 10.0]));
assert_eq!(connector["strokeCapEnd"], "ARROW");
assert!(warnings.iter().any(|warning| warning.contains("follow FigCraft's own routing")), "{warnings:?}");
assert!(warnings.iter().any(|warning| warning.contains("are routed afresh")), "{warnings:?}");
let (native, _) = crate::rest::import_fig(&rest, &|_| None).unwrap();
let node = find_node(&native, "synthetic connector");
+27 -80
View File
@@ -15,7 +15,6 @@
//! (`docs/file-format-parity.md` says what was checked); other apps may not open every file.
use std::collections::BTreeMap;
use std::io::Write;
use std::sync::Arc;
use figcraft_doc::color::{BlendMode, Color, GradientKind, ImageScaleMode, Paint, PaintKind};
@@ -33,9 +32,9 @@ use figcraft_doc::{
use serde_json::Value;
use sha1::Digest;
use super::kiwi::{Kv, Schema, encode};
use super::network;
use crate::FormatError;
use craft_fig::kiwi::{Kv, Schema, encode};
use craft_fig::{network, path};
mod assets;
mod common;
@@ -50,18 +49,18 @@ mod shape;
const MAX_NODES: usize = crate::rest::MAX_NODES;
const MAX_DEPTH: usize = 256;
/// Largest `canvas.fig` and image written (what the import reads).
const MAX_CANVAS: u64 = super::MAX_CANVAS;
const MAX_CANVAS: u64 = craft_fig::MAX_CANVAS;
const MAX_IMAGE: u64 = super::MAX_IMAGE;
/// Largest whole file written.
const MAX_FILE: u64 = 2 * 1024 * 1024 * 1024;
/// Most characters of one text layer, and vertices + segments + loop entries of one vector
/// network (what the import reads).
const MAX_CHARS: usize = 1 << 20;
const MAX_NETWORK: usize = 200_000;
/// Largest magnitude written for a float (the format stores 32-bit floats).
const MAX_FLOAT: f64 = 1e30;
/// The version number in the `canvas.fig` header.
const VERSION: u32 = 101;
/// Grid track values, and the scale factor of a scaled instance, that the import follows.
const MAX_GRID_TRACK_VALUE: f64 = 1e6;
const MIN_SCALE_FACTOR: f64 = 1e-3;
const MAX_SCALE_FACTOR: f64 = 1e3;
/// Session ids of the GUIDs: layers, and grid tracks and component properties.
const LAYERS: u32 = 1;
const AUX: u32 = 2;
@@ -206,11 +205,11 @@ message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4
pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec<u8>, Vec<String>), FormatError> {
let mut x = Exporter::new(doc);
let message = x.message();
let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}"));
let fail = |e: craft_fig::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}"));
let schema = Schema::parse(SCHEMA).map_err(fail)?;
let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?;
let body = encode::message(&schema, root, &message).map_err(fail)?;
let canvas = canvas(&encode::schema(&schema), &body)?;
let canvas = craft_fig::encode_canvas(&encode::schema(&schema), &body).map_err(super::fig_err)?;
let background = doc.pages.first().and_then(|p| doc.node(*p)).and_then(|p| match &p.kind {
NodeKind::Page { background, .. } => Some(*background),
_ => None,
@@ -219,28 +218,6 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec<u8>, Vec<
Ok((bytes, x.warnings))
}
fn too_large() -> FormatError {
FormatError::Io("the document is too large for a .fig file".into())
}
/// `canvas.fig`: the magic, the version and the two deflated chunks, each after its length.
pub(super) fn canvas(schema: &[u8], message: &[u8]) -> Result<Vec<u8>, FormatError> {
let mut out = b"fig-kiwi".to_vec();
out.extend_from_slice(&VERSION.to_le_bytes());
for chunk in [schema, message] {
let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
z.write_all(chunk).map_err(crate::io_err)?;
let c = z.finish().map_err(crate::io_err)?;
let len = u32::try_from(c.len()).map_err(|_| too_large())?;
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(&c);
}
if out.len() as u64 > MAX_CANVAS {
return Err(too_large());
}
Ok(out)
}
/// The zip around `canvas.fig`.
fn archive(
name: &str,
@@ -249,33 +226,9 @@ fn archive(
images: &[(String, Arc<Vec<u8>>)],
thumbnail: Option<&[u8]>,
) -> Result<Vec<u8>, FormatError> {
let mut buf = std::io::Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
crate::put(&mut z, "canvas.fig", stored, canvas)?;
if let Some(t) = thumbnail {
crate::put(&mut z, "thumbnail.png", stored, t)?;
}
let mut client = serde_json::json!({"background_color": {"r": background.r, "g": background.g, "b": background.b, "a": background.a}});
// A PNG says its size right after its signature and header chunk name.
let be = |at: usize| thumbnail.and_then(|t| t.get(at..at + 4)).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes);
if let (Some(w), Some(h)) = (be(16), be(20)) {
client["thumbnail_size"] = serde_json::json!({"width": w, "height": h});
}
let meta = serde_json::to_vec(&serde_json::json!({"client_meta": client, "file_name": name})).map_err(crate::io_err)?;
crate::put(&mut z, "meta.json", crate::json_options(), &meta)?;
let mut total = canvas.len() as u64;
for (hash, bytes) in images {
total += bytes.len() as u64;
if total > MAX_FILE {
return Err(too_large());
}
crate::put(&mut z, &format!("images/{hash}"), stored, bytes)?;
}
z.finish().map_err(crate::io_err)?;
}
Ok(buf.into_inner())
let images: Vec<(&str, &[u8])> = images.iter().map(|(hash, bytes)| (hash.as_str(), bytes.as_slice())).collect();
let background = [background.r, background.g, background.b, background.a].map(f64::from);
craft_fig::write_archive(&craft_fig::Package { file_name: name, background, canvas, images: &images, thumbnail }).map_err(super::fig_err)
}
type Fields = Vec<(&'static str, Kv<'static>)>;
@@ -310,7 +263,7 @@ fn b(x: bool) -> Kv<'static> {
/// importer keeps only those). `None`: the format has no name for it, so an equal track stands in.
fn grid_track_size(track: &GridTrack) -> Option<(&'static str, f64)> {
let value = track.value;
let fits = value.is_finite() && (0.0..=crate::fig::map::MAX_GRID_TRACK_VALUE).contains(&value);
let fits = value.is_finite() && (0.0..=MAX_GRID_TRACK_VALUE).contains(&value);
match track.sizing {
Sizing::Fixed if fits => Some(("FIXED", value)),
Sizing::Fill if fits && value > 0.0 => Some(("FLEX", value)),
@@ -423,27 +376,21 @@ fn join_name(j: StrokeJoin) -> &'static str {
}
}
/// A geometry blob (the import's `svg_path` reads it): commands `0` close, `1` move, `2` line,
/// `3` quadratic, `4` cubic, each followed by its points as little-endian `f32` pairs.
/// A geometry blob (`craft_fig::path`), with every value finite.
fn path_blob(p: &BezPath) -> Vec<u8> {
let mut out = Vec::new();
let mut put = |cmd: u8, pts: &[figcraft_doc::geom::Point]| {
out.push(cmd);
for q in pts {
out.extend_from_slice(&(finite(q.x) as f32).to_le_bytes());
out.extend_from_slice(&(finite(q.y) as f32).to_le_bytes());
}
};
for el in p.elements() {
match *el {
PathEl::MoveTo(a) => put(1, &[a]),
PathEl::LineTo(a) => put(2, &[a]),
PathEl::QuadTo(a, c) => put(3, &[a, c]),
PathEl::CurveTo(a, c, d) => put(4, &[a, c, d]),
PathEl::ClosePath => put(0, &[]),
}
}
out
let pt = |q: figcraft_doc::geom::Point| [finite(q.x) as f32, finite(q.y) as f32];
let commands: Vec<path::Command> = p
.elements()
.iter()
.map(|el| match *el {
PathEl::MoveTo(a) => path::Command::Move(pt(a)),
PathEl::LineTo(a) => path::Command::Line(pt(a)),
PathEl::QuadTo(a, c) => path::Command::Quad(pt(a), pt(c)),
PathEl::CurveTo(a, c, d) => path::Command::Cubic(pt(a), pt(c), pt(d)),
PathEl::ClosePath => path::Command::Close,
})
.collect();
path::encode(&commands)
}
/// Settings an overlay's destination carries.
+1 -1
View File
@@ -1,9 +1,9 @@
use super::super::map::{MAX_SCALE_FACTOR, MIN_SCALE_FACTOR};
use super::common::{
bool_data, changed, layout_grid, prop_type, resolved_alike, scaled, sort_position, symbol_data, text_data, text_value, var_data, variant_pairs,
};
use super::scale::main_equal_lengths;
use super::{AUX, BTreeMap, Bound, Exporter, Fields, Kv, MAX_NODES, Node, NodeId, NodeKind, PropDef, StyleKind, Value, arr, b, e, fl, guid, o, s};
use super::{MAX_SCALE_FACTOR, MIN_SCALE_FACTOR};
/// A changed effect/grid style, and a payload only when it differs from that style's values.
struct ListStyleOverride {
+1 -1
View File
@@ -105,7 +105,7 @@ impl<'d> Exporter<'d> {
// Message → layer → interaction → action uses three Kiwi levels. Each
// conditional adds two, an expression operator adds three, and the deepest
// condition (an alias with a GUID) uses five levels below its action.
let expression_levels = (super::super::kiwi::MAX_DEPTH - 8 - 2 * depth) / 3;
let expression_levels = (craft_fig::kiwi::MAX_DEPTH - 8 - 2 * depth) / 3;
match a {
Action::Navigate { dest, preserve_scroll } => {
let mut act = node(self, dest, "NAVIGATE")?;
+15 -7
View File
@@ -181,8 +181,8 @@ impl<'d> Exporter<'d> {
/// The editable network (with per-point corner radii, handle mirroring and end caps) and,
/// when it has filled areas, their outline.
pub(super) fn vector(&mut self, n: &Node, net: &VectorNetwork, f: &mut Fields) {
if net.regions.iter().any(|region| region.fills.is_some() || region.paint_space.is_some()) {
self.warn("vector region paints were left out of the .fig export");
if net.regions.iter().any(|region| region.paint_space.is_some()) {
self.warn("vector region paint frames were left out (their gradients and images follow the layer's box)");
}
let entries: usize = net.regions.iter().flat_map(|r| &r.loops).map(Vec::len).sum();
if net.vertices.len() + net.segments.len() + entries > MAX_NETWORK {
@@ -260,11 +260,19 @@ impl<'d> Exporter<'d> {
tb: (finite(sg.tb.0), finite(sg.tb.1)),
})
.collect();
let regions = net
.regions
.iter()
.map(|r| network::Region { style: 0, non_zero: r.winding == WindingRule::NonZero, loops: r.loops.clone() })
.collect();
// A region with paints of its own (an empty list included) names a style entry that
// holds them; one without writes style 0 and shows the layer's fills.
let mut regions = Vec::with_capacity(net.regions.len());
for r in &net.regions {
let style = match &r.fills {
Some(paints) => {
let list = self.paints(paints, true, &Bound::default());
style_of(vec![("fillPaints", list)])
}
None => 0,
};
regions.push(network::Region { style, non_zero: r.winding == WindingRule::NonZero, loops: r.loops.clone() });
}
let blob = network::encode(&network::Network { vertices, segments, regions });
let table = styles.into_iter().zip(1u32..).map(|(mut st, id)| {
st.insert(0, ("styleID", u(id)));
+35 -16
View File
@@ -843,21 +843,38 @@ fn round_trip_keeps_the_details() {
}
#[test]
fn fig_export_warns_when_region_paints_are_left_out() {
let mut doc = generate(3);
let Some(id) = doc.nodes().find_map(|node| match &node.kind {
NodeKind::Vector { network } if !network.regions.is_empty() => Some(node.id),
_ => None,
}) else {
panic!("generated document has no filled vector");
};
let node = doc.node_mut(id).unwrap();
let NodeKind::Vector { network } = &mut node.kind else { panic!("expected vector fixture") };
let region = network.regions.first_mut().unwrap();
region.fills = Some(Vec::new());
fn vector_region_paints_round_trip() {
let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y));
let mut doc = Document::new("regions");
let page = doc.first_page().unwrap();
let mut two = VectorNetwork::from_points(&square, true);
let again = two.regions[0].clone();
two.regions.push(again);
let mut half = Paint::solid(Color { r: 0.25, g: 0.5, b: 0.75, a: 1.0 });
half.opacity = 0.5;
let gradient = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }));
two.regions[0].fills = Some(vec![half, gradient]);
two.regions[1].fills = Some(Vec::new());
let id = doc.create(page, NodeKind::Vector { network: two }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)];
let inherit = VectorNetwork::from_points(&square, true);
let id2 = doc.create(page, NodeKind::Vector { network: inherit }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id2).unwrap().fills = vec![Paint::solid(Color::BLACK)];
let (_, warnings) = export(&doc, None).unwrap();
assert!(warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}");
let (back, warnings) = round_trip(&doc, "region paints");
assert!(!warnings.iter().any(|w| w.contains("region")), "{warnings:?}");
let regions_of = |d: &Document, name: &str| match d.nodes().find(|n| n.name == name).map(|n| &n.kind) {
Some(NodeKind::Vector { network }) => network.regions.clone(),
k => panic!("{name}: {k:?}"),
};
let painted = regions_of(&back, "Painted");
assert_eq!(painted.len(), 2);
let fills = painted[0].fills.as_ref().expect("the first region keeps its paints");
assert_eq!(fills.len(), 2);
assert!(matches!(&fills[0].kind, PaintKind::Solid { .. }) && (fills[0].opacity - 0.5).abs() < 1e-6);
assert!(matches!(&fills[1].kind, PaintKind::Gradient(_)));
assert_eq!(painted[1].fills, Some(Vec::new()), "an unfilled region stays unfilled");
assert_eq!(regions_of(&back, "Inherits")[0].fills, None, "a region with no paints of its own still shows the layer's");
}
#[test]
@@ -875,16 +892,18 @@ fn fig_export_warns_when_inherited_region_paints_have_a_paint_frame() {
let region = network.regions.first_mut().unwrap();
region.fills = None;
region.paint_space = Some(RegionPaintSpace { width: 20.0, height: 10.0, transform: Affine::translate((4.0, 8.0)) });
let text = "vector region paint frames were left out (their gradients and images follow the layer's box)";
let (_, warnings) = export(&doc, None).unwrap();
assert!(warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}");
assert!(warnings.iter().any(|warning| warning == text), "{warnings:?}");
let mut plain = doc;
let node = plain.node_mut(id).unwrap();
let NodeKind::Vector { network } = &mut node.kind else { panic!("expected vector fixture") };
network.regions[0].paint_space = None;
network.regions[0].fills = Some(vec![Paint::solid(Color::BLACK)]);
let (_, warnings) = export(&plain, None).unwrap();
assert!(!warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}");
assert!(!warnings.iter().any(|warning| warning.contains("region paint")), "{warnings:?}");
}
#[test]
-690
View File
@@ -1,690 +0,0 @@
//! A generic decoder and encoder for the kiwi binary schema format (an open, MIT-licensed message
//! format with a public specification). A binary schema lists definitions (enums, structs and messages, each
//! with typed fields); a message is then decoded with it into a [`Kv`] tree keyed by field name,
//! and encoded back from one ([`encode`]).
//!
//! Everything here reads untrusted bytes: reads are bounds-checked, nesting is capped, array
//! counts can't exceed the bytes left, and the total number of decoded values is capped.
use std::collections::HashMap;
use std::fmt;
/// Deepest struct/message nesting decoded.
pub(super) const MAX_DEPTH: usize = 64;
/// Most values decoded from one message (every scalar, array element and field counts): at least
/// [`MIN_VALUES`], and [`VALUES_PER_PACKED_BYTE`] per byte of the file's compressed canvas up to
/// [`MAX_VALUES`], so a large real file decodes while a small one can't expand into a huge tree,
/// however far its chunks inflate. 32-bit targets (wasm32) have a 4 GB address space in all, so
/// their ceiling is lower: past it the file is refused cleanly instead of running out of memory.
const MIN_VALUES: usize = 20_000_000;
/// Value budget per compressed canvas byte. The real files measured in
/// `large_files_get_a_larger_value_budget` hold up to 0.75 values per compressed byte without their
/// single scalar fields; counting those too adds 15–43% on the generated files in
/// `value_budget_tests` and up to 3.2 times on a rectangle carrying only geometry and paint, so a
/// dense file may reach about 2.4 per byte. Four leaves two-thirds more room than that. The
/// trade-off: from 32 MiB of canvas (8 MiB on 32-bit targets) a file gets all of [`MAX_VALUES`],
/// and above the floor it may decode four values for every byte it carries; [`MIN_VALUES`] and
/// [`MAX_VALUES`] still bound every file.
const VALUES_PER_PACKED_BYTE: usize = 4;
#[cfg(not(target_pointer_width = "32"))]
const MAX_VALUES: usize = 128 << 20;
#[cfg(target_pointer_width = "32")]
const MAX_VALUES: usize = 32 << 20;
/// Most definitions in a schema, and fields in one definition.
const MAX_DEFS: usize = 10_000;
const MAX_FIELDS: usize = 10_000;
/// Most fields in a schema, every definition together: Figma's own schema has a few thousand, and
/// without a total a schema of [`MAX_DEFS`] wide definitions could hold 100 million field records.
const MAX_SCHEMA_FIELDS: usize = 200_000;
#[derive(Debug, PartialEq, Eq)]
pub struct KiwiError(pub String);
impl fmt::Display for KiwiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
fn err<T>(msg: impl Into<String>) -> Result<T, KiwiError> {
Err(KiwiError(msg.into()))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Enum,
Struct,
Message,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Type {
Bool,
Byte,
Int,
Uint,
Float,
Str,
Int64,
Uint64,
/// Index of a definition in the schema.
Def(usize),
}
/// Built-in types in their schema order (encoded as `!index`).
const BUILTINS: [Type; 8] = [Type::Bool, Type::Byte, Type::Int, Type::Uint, Type::Float, Type::Str, Type::Int64, Type::Uint64];
#[derive(Clone, Debug)]
pub struct Field {
pub name: String,
/// `None` for enum values.
pub ty: Option<Type>,
pub array: bool,
/// The field id (messages) or the value (enums).
pub value: u32,
}
#[derive(Clone, Debug)]
pub struct Def {
pub name: String,
pub kind: Kind,
pub fields: Vec<Field>,
}
#[derive(Clone, Debug, Default)]
pub struct Schema {
pub defs: Vec<Def>,
}
/// A decoded value. Field and enum names borrow from the schema.
#[derive(Clone, Debug, PartialEq)]
pub enum Kv<'s> {
Bool(bool),
Int(i64),
Uint(u64),
Float(f32),
Str(String),
/// A `byte[]` field.
Bytes(Vec<u8>),
Enum(&'s str),
Array(Vec<Kv<'s>>),
/// A struct or message: its fields in the order read.
Object(Vec<(&'s str, Kv<'s>)>),
}
impl<'s> Kv<'s> {
/// Field `name` of an object.
pub fn get(&self, name: &str) -> Option<&Kv<'s>> {
match self {
Kv::Object(f) => f.iter().find(|(n, _)| *n == name).map(|(_, v)| v),
_ => None,
}
}
pub fn f64(&self) -> Option<f64> {
let v = match self {
Kv::Float(f) => f64::from(*f),
Kv::Int(i) => *i as f64,
Kv::Uint(u) => *u as f64,
Kv::Bool(b) => f64::from(u8::from(*b)),
_ => return None,
};
v.is_finite().then_some(v)
}
pub fn bool(&self) -> Option<bool> {
match self {
Kv::Bool(b) => Some(*b),
_ => None,
}
}
pub fn str(&self) -> Option<&str> {
match self {
Kv::Str(s) => Some(s),
Kv::Enum(s) => Some(s),
_ => None,
}
}
pub fn list(&self) -> &[Kv<'s>] {
match self {
Kv::Array(a) => a,
_ => &[],
}
}
pub fn bytes(&self) -> Option<&[u8]> {
match self {
Kv::Bytes(b) => Some(b),
_ => None,
}
}
}
/// A bounds-checked reader over kiwi bytes.
struct Reader<'b> {
data: &'b [u8],
pos: usize,
}
impl<'b> Reader<'b> {
fn left(&self) -> usize {
self.data.len().saturating_sub(self.pos)
}
fn byte(&mut self) -> Result<u8, KiwiError> {
let b = *self.data.get(self.pos).ok_or_else(|| KiwiError("unexpected end of data".into()))?;
self.pos += 1;
Ok(b)
}
fn take(&mut self, n: usize) -> Result<&'b [u8], KiwiError> {
let end = self.pos.checked_add(n).filter(|e| *e <= self.data.len()).ok_or_else(|| KiwiError("unexpected end of data".into()))?;
let s = self.data.get(self.pos..end).ok_or_else(|| KiwiError("unexpected end of data".into()))?;
self.pos = end;
Ok(s)
}
fn var_uint(&mut self) -> Result<u32, KiwiError> {
let mut value = 0u32;
let mut shift = 0;
loop {
let b = self.byte()?;
let part = b & 127;
if shift == 28 && (part > 0x0f || b & 128 != 0) {
return err("u32 varint overflow");
}
value |= u32::from(part) << shift;
shift += 7;
if b & 128 == 0 {
return Ok(value);
}
}
}
fn var_int(&mut self) -> Result<i32, KiwiError> {
let v = self.var_uint()?;
Ok(if v & 1 != 0 { !((v >> 1) as i32) } else { (v >> 1) as i32 })
}
fn var_uint64(&mut self) -> Result<u64, KiwiError> {
let mut value = 0u64;
let mut shift = 0u32;
loop {
let b = self.byte()?;
if shift == 56 {
// The ninth byte carries a full eight bits.
return Ok(value | (u64::from(b) << 56));
}
value |= u64::from(b & 127) << shift;
shift += 7;
if b & 128 == 0 {
return Ok(value);
}
}
}
fn var_int64(&mut self) -> Result<i64, KiwiError> {
let v = self.var_uint64()?;
Ok(if v & 1 != 0 { !((v >> 1) as i64) } else { (v >> 1) as i64 })
}
fn var_float(&mut self) -> Result<f32, KiwiError> {
if self.data.get(self.pos) == Some(&0) {
self.pos += 1;
return Ok(0.0);
}
let b = self.take(4)?;
let bits = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
// The exponent is stored first so zero fits one byte; move it back into place.
Ok(f32::from_bits(bits.rotate_left(23)))
}
fn string(&mut self) -> Result<String, KiwiError> {
let rest = self.data.get(self.pos..).unwrap_or_default();
let len = rest.iter().position(|b| *b == 0).ok_or_else(|| KiwiError("unterminated string".into()))?;
let s = String::from_utf8_lossy(self.take(len)?).into_owned();
self.pos += 1;
Ok(s)
}
}
impl Schema {
/// Decode a binary schema.
pub fn decode(data: &[u8]) -> Result<Schema, KiwiError> {
let mut r = Reader { data, pos: 0 };
let count = r.var_uint()? as usize;
if count > MAX_DEFS || count > r.left() {
return err("schema: too many definitions");
}
let mut defs = Vec::with_capacity(count);
let mut raw_types = Vec::new();
let mut total_fields = 0usize;
for _ in 0..count {
let name = r.string()?;
let kind = match r.byte()? {
0 => Kind::Enum,
1 => Kind::Struct,
2 => Kind::Message,
k => return err(format!("schema: unknown definition kind {k}")),
};
let n = r.var_uint()? as usize;
total_fields = total_fields.saturating_add(n);
if n > MAX_FIELDS || n > r.left() || total_fields > MAX_SCHEMA_FIELDS {
return err("schema: too many fields");
}
let mut fields = Vec::with_capacity(n);
for _ in 0..n {
let fname = r.string()?;
let ty = r.var_int()?;
let array = r.byte()? & 1 != 0;
let value = r.var_uint()?;
if kind == Kind::Message && fields.iter().any(|f: &Field| f.value == value) {
return err(format!("schema: duplicate field id {value} in {name}"));
}
raw_types.push(ty);
fields.push(Field { name: fname, ty: None, array, value });
}
defs.push(Def { name, kind, fields });
}
let total = defs.len();
let mut types = raw_types.into_iter();
for d in &mut defs {
for f in &mut d.fields {
let raw = types.next().unwrap_or(0);
if d.kind == Kind::Enum {
continue;
}
f.ty = Some(if raw < 0 {
*BUILTINS.get((!raw) as usize).ok_or_else(|| KiwiError(format!("schema: unknown type {raw}")))?
} else {
let i = raw as usize;
if i >= total {
return err(format!("schema: field {} names missing definition {i}", f.name));
}
Type::Def(i)
});
}
}
Ok(Schema { defs })
}
pub fn find(&self, name: &str) -> Option<usize> {
self.defs.iter().position(|d| d.name == name)
}
/// Decode a message of definition `root`, within [`MIN_VALUES`] values.
pub fn decode_message<'s>(&'s self, root: usize, data: &[u8]) -> Result<Kv<'s>, KiwiError> {
self.decode_message_within(root, data, MIN_VALUES)
}
/// [`Self::decode_message`] within `budget` values (see [`value_budget`]).
pub fn decode_message_within<'s>(&'s self, root: usize, data: &[u8], budget: usize) -> Result<Kv<'s>, KiwiError> {
let mut d = Decoder { schema: self, r: Reader { data, pos: 0 }, budget, ids: vec![None; self.defs.len()] };
d.def(root, 0)
}
}
/// Most values decoded from a file whose compressed canvas is `packed` bytes.
pub(crate) fn value_budget(packed: usize) -> usize {
packed.saturating_mul(VALUES_PER_PACKED_BYTE).clamp(MIN_VALUES, MAX_VALUES)
}
struct Decoder<'s, 'b> {
schema: &'s Schema,
r: Reader<'b>,
budget: usize,
/// Per definition, the index of the first field with each id (message field ids, enum
/// values), built the first time the definition is decoded: a message can carry many tags
/// against a wide definition, and a scan per tag would multiply the two.
ids: Vec<Option<HashMap<u32, usize>>>,
}
impl<'s> Decoder<'s, '_> {
fn spend(&mut self, n: usize) -> Result<(), KiwiError> {
self.budget = self.budget.checked_sub(n).ok_or_else(|| KiwiError("message: too many values".into()))?;
Ok(())
}
/// The first field of definition `i` with id (or enum value) `id`.
fn field_by_id(&mut self, i: usize, id: u32) -> Option<&'s Field> {
let fields = &self.schema.defs.get(i)?.fields;
let ids = self.ids.get_mut(i)?.get_or_insert_with(|| {
let mut m = HashMap::with_capacity(fields.len());
for (j, f) in fields.iter().enumerate() {
m.entry(f.value).or_insert(j);
}
m
});
fields.get(*ids.get(&id)?)
}
fn def(&mut self, i: usize, depth: usize) -> Result<Kv<'s>, KiwiError> {
if depth > MAX_DEPTH {
return err("message: nested too deeply");
}
self.spend(1)?;
let schema = self.schema;
let d = schema.defs.get(i).ok_or_else(|| KiwiError("message: missing definition".into()))?;
match d.kind {
Kind::Enum => {
let v = self.r.var_uint()?;
Ok(self.field_by_id(i, v).map_or(Kv::Uint(u64::from(v)), |f| Kv::Enum(f.name.as_str())))
}
Kind::Struct => {
let mut out = Vec::with_capacity(d.fields.len());
for f in &d.fields {
out.push((f.name.as_str(), self.field(f, depth)?));
}
Ok(Kv::Object(out))
}
Kind::Message => {
let mut out = Vec::new();
loop {
let id = self.r.var_uint()?;
if id == 0 {
// Grown by doubling: trimmed, a large file's tree takes a good part less.
out.shrink_to_fit();
return Ok(Kv::Object(out));
}
let f = self.field_by_id(i, id).ok_or_else(|| KiwiError(format!("message: {} has no field {id}", d.name)))?;
out.push((f.name.as_str(), self.field(f, depth)?));
}
}
}
}
fn field(&mut self, f: &Field, depth: usize) -> Result<Kv<'s>, KiwiError> {
let ty = f.ty.ok_or_else(|| KiwiError("message: untyped field".into()))?;
if !f.array {
// A nested definition spends its own value in `def`.
if !matches!(ty, Type::Def(_)) {
self.spend(1)?;
}
return self.value(ty, depth);
}
let n = self.r.var_uint()? as usize;
// Every element takes at least one byte.
if n > self.r.left() {
return err("message: array longer than the data");
}
// The field itself counts, so empty arrays can't pile up for free.
self.spend(1)?;
if ty == Type::Byte {
return Ok(Kv::Bytes(self.r.take(n)?.to_vec()));
}
self.spend(n)?;
let mut out = Vec::with_capacity(n);
for _ in 0..n {
out.push(self.value(ty, depth)?);
}
Ok(Kv::Array(out))
}
fn value(&mut self, ty: Type, depth: usize) -> Result<Kv<'s>, KiwiError> {
Ok(match ty {
Type::Bool => Kv::Bool(self.r.byte()? != 0),
Type::Byte => Kv::Uint(u64::from(self.r.byte()?)),
Type::Int => Kv::Int(i64::from(self.r.var_int()?)),
Type::Uint => Kv::Uint(u64::from(self.r.var_uint()?)),
Type::Float => Kv::Float(self.r.var_float()?),
Type::Str => Kv::Str(self.r.string()?),
Type::Int64 => Kv::Int(self.r.var_int64()?),
Type::Uint64 => Kv::Uint(self.r.var_uint64()?),
Type::Def(i) => self.def(i, depth + 1)?,
})
}
}
/// An encoder for the same format: the `.fig` export writes its schema and message with it (and
/// test fixtures are built with it). Values are checked against the schema; it never panics.
pub mod encode {
use super::{BUILTINS, Field, Kind, KiwiError, Kv, MAX_DEPTH, Schema, Type, err};
#[derive(Default)]
pub struct Writer(pub Vec<u8>);
impl Writer {
pub fn byte(&mut self, b: u8) {
self.0.push(b);
}
pub fn var_uint(&mut self, mut v: u32) {
loop {
let b = (v & 127) as u8;
v >>= 7;
if v == 0 {
self.0.push(b);
return;
}
self.0.push(b | 128);
}
}
pub fn var_int(&mut self, v: i32) {
self.var_uint(((v << 1) ^ (v >> 31)) as u32);
}
pub fn var_uint64(&mut self, mut v: u64) {
for _ in 0..8 {
let b = (v & 127) as u8;
v >>= 7;
if v == 0 {
self.0.push(b);
return;
}
self.0.push(b | 128);
}
self.0.push(v as u8);
}
pub fn var_int64(&mut self, v: i64) {
self.var_uint64(((v << 1) ^ (v >> 63)) as u64);
}
pub fn var_float(&mut self, f: f32) {
let bits = f.to_bits().rotate_right(23);
if bits & 255 == 0 {
self.0.push(0);
} else {
self.0.extend_from_slice(&bits.to_le_bytes());
}
}
/// A NUL-terminated string (NULs inside are dropped: they would end it early).
pub fn string(&mut self, s: &str) {
self.0.extend(s.bytes().filter(|b| *b != 0));
self.0.push(0);
}
}
pub fn schema(s: &Schema) -> Vec<u8> {
let mut w = Writer::default();
w.var_uint(s.defs.len() as u32);
for d in &s.defs {
w.string(&d.name);
w.byte(match d.kind {
Kind::Enum => 0,
Kind::Struct => 1,
Kind::Message => 2,
});
w.var_uint(d.fields.len() as u32);
for f in &d.fields {
w.string(&f.name);
w.var_int(match f.ty {
None => 0,
Some(Type::Def(i)) => i32::try_from(i).unwrap_or(i32::MAX),
Some(t) => !(BUILTINS.iter().position(|b| *b == t).unwrap_or(0) as i32),
});
w.byte(u8::from(f.array));
w.var_uint(f.value);
}
}
w.0
}
/// Encode `v` as definition `def` (objects may leave message fields out; struct fields are
/// required, in order). Fails on what doesn't fit the schema: unknown fields or enum names,
/// missing struct fields, wrong types, numbers out of range, non-finite floats.
pub fn message(s: &Schema, def: usize, v: &Kv) -> Result<Vec<u8>, KiwiError> {
let mut w = Writer::default();
encode_def(s, def, v, &mut w, 0)?;
Ok(w.0)
}
fn encode_def(s: &Schema, i: usize, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> {
if depth > MAX_DEPTH {
return err("encode: nested too deeply");
}
let d = s.defs.get(i).ok_or_else(|| KiwiError("encode: missing definition".into()))?;
match d.kind {
Kind::Enum => {
let value = match v {
Kv::Uint(u) => u32::try_from(*u).ok(),
_ => v.str().and_then(|name| d.fields.iter().find(|f| f.name == name)).map(|f| f.value),
};
w.var_uint(value.ok_or_else(|| KiwiError(format!("encode: {v:?} is not a value of {}", d.name)))?);
}
Kind::Struct => {
for f in &d.fields {
let fv = v.get(&f.name).ok_or_else(|| KiwiError(format!("encode: {} needs field {}", d.name, f.name)))?;
encode_field(s, f, fv, w, depth)?;
}
}
Kind::Message => {
let Kv::Object(fields) = v else { return err(format!("encode: {} needs an object", d.name)) };
for (name, fv) in fields {
let f = d.fields.iter().find(|f| f.name == *name).ok_or_else(|| KiwiError(format!("encode: {} has no field {name}", d.name)))?;
w.var_uint(f.value);
encode_field(s, f, fv, w, depth)?;
}
w.var_uint(0);
}
}
Ok(())
}
fn encode_field(s: &Schema, f: &Field, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> {
let ty = f.ty.ok_or_else(|| KiwiError("encode: untyped field".into()))?;
if !f.array {
return encode_value(s, ty, v, w, depth);
}
let len = |n: usize| u32::try_from(n).map_err(|_| KiwiError(format!("encode: {} is too long", f.name)));
if let (Type::Byte, Kv::Bytes(b)) = (ty, v) {
w.var_uint(len(b.len())?);
w.0.extend_from_slice(b);
return Ok(());
}
let Kv::Array(items) = v else { return err(format!("encode: {} needs a list", f.name)) };
w.var_uint(len(items.len())?);
for it in items {
encode_value(s, ty, it, w, depth)?;
}
Ok(())
}
/// An integer value (whole finite floats count).
fn int(v: &Kv) -> Option<i128> {
match v {
Kv::Int(i) => Some(i128::from(*i)),
Kv::Uint(u) => Some(i128::from(*u)),
Kv::Bool(b) => Some(i128::from(*b)),
Kv::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128),
_ => None,
}
}
fn encode_value(s: &Schema, ty: Type, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> {
let bad = || KiwiError(format!("encode: {v:?} is not a {ty:?}"));
let ranged = |lo: i128, hi: i128| int(v).filter(|i| (lo..=hi).contains(i)).ok_or_else(bad);
match ty {
Type::Bool => w.byte(u8::from(v.bool().ok_or_else(bad)?)),
Type::Byte => w.byte(ranged(0, 255)? as u8),
Type::Int => w.var_int(ranged(i32::MIN.into(), i32::MAX.into())? as i32),
Type::Uint => w.var_uint(ranged(0, u32::MAX.into())? as u32),
// Infinity is a value of its own (an axis with no maximum size); NaN is not.
Type::Float => w.var_float(match v {
Kv::Float(f) if f.is_infinite() => *f,
_ => v.f64().map(|x| x as f32).filter(|x| x.is_finite()).ok_or_else(bad)?,
}),
Type::Str => w.string(v.str().ok_or_else(bad)?),
Type::Int64 => w.var_int64(ranged(i64::MIN.into(), i64::MAX.into())? as i64),
Type::Uint64 => w.var_uint64(ranged(0, u64::MAX.into())? as u64),
Type::Def(i) => encode_def(s, i, v, w, depth + 1)?,
}
Ok(())
}
}
/// The built-in type names, in [`BUILTINS`] order.
const BUILTIN_NAMES: [&str; 8] = ["bool", "byte", "int", "uint", "float", "string", "int64", "uint64"];
impl Schema {
/// A schema from a compact text form, one definition per line: `enum Name A B …` (values from
/// 0), `struct Name type field, type field[] …` or `message Name …` (field ids from 1), the
/// types being built-in names or other definitions'. `A=3` or `type field=7` gives a value or
/// a field its own number.
pub fn parse(text: &str) -> Result<Schema, KiwiError> {
let lines: Vec<Vec<&str>> = text.lines().map(|l| l.split_whitespace().collect::<Vec<_>>()).filter(|l| !l.is_empty()).collect();
let index = |name: &str| lines.iter().position(|l| l.get(1) == Some(&name));
let mut defs = Vec::with_capacity(lines.len());
for l in &lines {
let (Some(kind), Some(name)) = (l.first(), l.get(1)) else { return err("schema text: a definition needs a kind and a name") };
let rest = l.get(2..).unwrap_or_default();
let (kind, fields) = match *kind {
"enum" => {
let mut fields = Vec::new();
for (n, i) in rest.iter().zip(0..) {
let (name, value) = numbered(n, i)?;
fields.push(Field { name, ty: None, array: false, value });
}
(Kind::Enum, fields)
}
"struct" | "message" => {
let mut fields = Vec::new();
for (f, id) in rest.join(" ").split(',').zip(1..) {
let Some((t, n)) = f.trim().split_once(' ') else { return err(format!("schema text: bad field `{f}` in {name}")) };
let base = t.trim_end_matches("[]");
let ty = match BUILTIN_NAMES.iter().position(|b| *b == base) {
Some(i) => BUILTINS.get(i).copied(),
None => index(base).map(Type::Def),
}
.ok_or_else(|| KiwiError(format!("schema text: unknown type {base}")))?;
let (name, value) = numbered(n.trim(), id)?;
if *kind == "message" && fields.iter().any(|f: &Field| f.value == value) {
return err(format!("schema text: duplicate field id {value} in {name}"));
}
fields.push(Field { name, ty: Some(ty), array: t.ends_with("[]"), value });
}
(if *kind == "struct" { Kind::Struct } else { Kind::Message }, fields)
}
k => return err(format!("schema text: unknown kind {k}")),
};
defs.push(Def { name: name.to_string(), kind, fields });
}
Ok(Schema { defs })
}
}
/// `name=number` as its parts, or `name` with `default`.
fn numbered(token: &str, default: u32) -> Result<(String, u32), KiwiError> {
match token.split_once('=') {
None => Ok((token.to_string(), default)),
Some((name, n)) => Ok((name.to_string(), n.parse().map_err(|_| KiwiError(format!("schema text: bad number in `{token}`")))?)),
}
}
#[cfg(test)]
mod tests {
use super::Reader;
#[test]
fn overflowing_u32_varint_is_rejected() {
let mut boundary = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x0f], pos: 0 };
assert_eq!(boundary.var_uint(), Ok(u32::MAX));
let mut overflowing = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x7f], pos: 0 };
assert!(overflowing.var_uint().is_err(), "overflowing u32 varint was accepted");
}
}
+234 -619
View File
@@ -1,56 +1,66 @@
//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports.
//!
//! The message lists node changes; each names its id (`guid`), its parent and its position among
//! the siblings (`parentIndex`). Nodes are read by field name, so files written with newer
//! schemas still import what is understood. Instances carry only their overrides: their layers
//! are expanded here from the main component (overrides and derived layout matched by id path,
//! component property values applied) so the import looks as saved.
//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports. The mapping
//! is `craft_fig::rest`; FigCraft gives it its own connector routing and text measure, so an
//! imported connector runs as one drawn here, and takes the networks it hands over.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::rc::Rc;
use figcraft_doc::VectorNetwork;
use figcraft_doc::geom::{Affine, Point};
use figcraft_doc::proto::{MAX_ACTION_DEPTH, MAX_EXPR_DEPTH};
use serde_json::{Map, Value, json};
use craft_fig::rest::{self, Geometry, RouteEnd, Routing, SavedRuns, Side};
use figcraft_doc::geom::{Point, measure};
use figcraft_doc::{BoardShape, ConnectorPath, VectorNetwork};
use serde_json::Value;
use super::kiwi::Kv;
use super::network;
mod board;
mod component;
mod connector;
mod document;
mod layer;
mod layout;
mod paint;
mod proto;
mod text;
mod variables;
/// FigCraft's board routing and text measure, for the mapping.
struct FigGeometry;
#[cfg(test)]
pub(super) use board::board_shape;
fn end(e: RouteEnd) -> figcraft_doc::RouteEnd {
match e {
RouteEnd::Point(p) => figcraft_doc::RouteEnd::Point(p),
RouteEnd::Box(b, s) => figcraft_doc::RouteEnd::Box(b, side(s)),
}
}
use component::OverrideScope;
#[cfg(test)]
use paint::paint;
fn side(s: Side) -> figcraft_doc::Side {
match s {
Side::Auto => figcraft_doc::Side::Auto,
Side::Top => figcraft_doc::Side::Top,
Side::Right => figcraft_doc::Side::Right,
Side::Bottom => figcraft_doc::Side::Bottom,
Side::Left => figcraft_doc::Side::Left,
}
}
type Obj = Map<String, Value>;
fn side_back(s: figcraft_doc::Side) -> Side {
match s {
figcraft_doc::Side::Auto => Side::Auto,
figcraft_doc::Side::Top => Side::Top,
figcraft_doc::Side::Right => Side::Right,
figcraft_doc::Side::Bottom => Side::Bottom,
figcraft_doc::Side::Left => Side::Left,
}
}
/// Deepest nesting followed.
const MAX_DEPTH: usize = 256;
/// Most path commands read from one geometry blob.
const MAX_COMMANDS: usize = 200_000;
const MAX_GRID_TRACKS: usize = 1_000;
pub(super) const MAX_GRID_TRACK_VALUE: f64 = 1e6;
/// Smallest and largest scale factor of a scaled instance (`symbolData.uniformScaleFactor`, times
/// those of the instances around it) that is followed: a junk factor changes nothing.
pub(super) const MIN_SCALE_FACTOR: f64 = 1e-3;
pub(super) const MAX_SCALE_FACTOR: f64 = 1e3;
/// Id of "no style".
const NO_STYLE: &str = "4294967295:4294967295";
/// Longest asset `key` or `version` kept for resolving references given as assets.
const MAX_ASSET_PART: usize = 256;
impl Geometry for FigGeometry {
fn route(&self, from: RouteEnd, to: RouteEnd, routing: Routing, saved: Option<&SavedRuns>) -> Option<Vec<Point>> {
let routing = match routing {
Routing::Straight => figcraft_doc::Routing::Straight,
Routing::Elbow => figcraft_doc::Routing::Elbow,
Routing::Curved => figcraft_doc::Routing::Curved,
};
let path = saved.map(|s| ConnectorPath::Runs { across: s.across, at: s.at.clone() });
figcraft_doc::route_along(end(from), end(to), routing, path.as_ref())
}
fn attach(&self, from: RouteEnd, to: RouteEnd) -> ((Point, Option<Side>), (Point, Option<Side>)) {
let (a, b) = (end(from), end(to));
let ((p0, p1), (s0, s1)) = (figcraft_doc::attach_points(a, b), figcraft_doc::attached_sides(a, b));
((p0, s0.map(side_back)), (p1, s1.map(side_back)))
}
fn text_path_measurable(&self, d: &str) -> bool {
let path = figcraft_doc::geom::svg_path(d).unwrap_or_default();
measure::polylines(&path).and_then(|lines| lines.first().map(|line| line.length() > 1e-9)).unwrap_or(false)
}
}
/// The REST API file JSON for message `msg`, with the warnings about what was skipped and the
/// vector networks its layers name by `vectorNetworkRef` (for [`crate::rest::import_with_networks`]).
@@ -59,49 +69,189 @@ pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec<Str
to_rest_for(msg, name, max_nodes, false)
}
/// The REST JSON (as `to_rest`) for a FigJam whiteboard (`board`) or a design file: a
/// whiteboard's stickies come out as native board items.
/// Map a FigJam whiteboard's stickies as native board items when `board` is true.
pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) -> (Value, Vec<String>, Vec<Option<VectorNetwork>>) {
let mut m = Mapper::new(msg, max_nodes);
m.board = board;
let _canon = VarCanon::install(&m);
let doc = m.document();
// Large values are moved in, never passed through `json!`, which serialises its arguments:
// a deep copy of the whole tree, briefly holding it twice.
let mut out = json!({"name": name});
out["document"] = doc;
if !m.library_contexts.is_empty() {
out[crate::rest::FIG_LIBRARY_CONTEXTS_FIELD] = Value::Array(std::mem::take(&mut m.library_contexts));
let options = rest::Options { max_nodes, geometry: &FigGeometry, outlined_stroke: Some(super::export::STASH), board };
let mut mapped = rest::to_rest(msg, name, &options);
// Each network passes the importer's own checks, as the JSON's `vectorNetwork` does.
let networks: Vec<Option<VectorNetwork>> =
mapped.networks.into_iter().map(|n| serde_json::to_value(n?).ok().and_then(|v| crate::rest::network(&v))).collect();
if board {
native_board_shapes(msg, &mut mapped.json, &mut mapped.warnings);
}
// Mains in the file that the layer cap kept out: their instances are told apart from those of
// components the file doesn't have (#981).
if m.count >= m.max_nodes {
let capped: Vec<Value> = m.referenced_mains.difference(&m.mapped_mains).map(|id| json!(id)).collect();
if !capped.is_empty() {
out[crate::rest::FIG_CAPPED_MAINS_FIELD] = Value::Array(capped);
}
}
if !m.styles.is_empty() {
out["styles"] = Value::Object(std::mem::take(&mut m.styles));
}
if !m.components.is_empty() {
out["components"] = Value::Object(std::mem::take(&mut m.components));
}
if !m.sets.is_empty() {
out["componentSets"] = Value::Object(std::mem::take(&mut m.sets));
}
if let Some(vars) = m.variables() {
out["meta"] = vars;
}
let styles = m.style_definitions();
if !styles.is_empty() {
out["styleDefinitions"] = Value::Array(styles);
}
(out, m.warnings.finish(), m.networks)
(mapped.json, mapped.warnings, networks)
}
#[cfg(test)]
mod image_filter_tests;
/// FigJam shapes whose generated records are complete are native board items in FigCraft. The
/// shared mapper owns the neutral generated layers; this adapter supplies only FigCraft's board
/// shape model, outline, and layout semantics.
fn native_board_shapes(msg: &Kv, json: &mut Value, warnings: &mut Vec<String>) {
let Some(changes) = msg.get("nodeChanges") else { return };
let mut shapes = std::collections::HashMap::new();
for node in changes.list() {
if node.get("type").and_then(Kv::str) != Some("SHAPE_WITH_TEXT") {
continue;
}
let Some(guid) = node.get("guid") else { continue };
let Some(origin) = guid
.get("sessionID")
.and_then(Kv::f64)
.zip(guid.get("localID").and_then(Kv::f64))
.map(|(session, local)| format!("{}:{}", session as u64, local as u64))
else {
continue;
};
let kind = node.get("shapeWithTextType").and_then(Kv::str).unwrap_or("SQUARE");
let Some(shape) = board_shape(kind) else {
warnings.push(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind)));
continue;
};
// An outer text fallback means the generated body was absent or invalid. Keep the shared
// mapper's editable generated layers in that case, matching the older FigJam adapter.
if node.get("textData").and_then(|t| t.get("characters")).and_then(Kv::str).is_some_and(|s| !s.trim().is_empty()) {
continue;
}
shapes.insert(origin, (shape, generated_empty_body(node)));
}
apply_native_board_shapes(json, &shapes);
}
/// Traverse only the mapped REST tree (already bounded by `max_nodes`) and adapt each source
/// origin at most once. The origin index avoids rescanning the tree for every source record.
fn apply_native_board_shapes(json: &mut Value, shapes: &std::collections::HashMap<String, (BoardShape, bool)>) {
fn visit(json: &mut Value, shapes: &std::collections::HashMap<String, (BoardShape, bool)>, visited: &mut std::collections::HashSet<String>) {
if let Some(origin) = json.get(craft_fig::rest::FIG_SOURCE_FIELD).and_then(|s| s.get("origin")).and_then(Value::as_str).map(str::to_owned)
&& visited.insert(origin.clone())
&& let Some((shape, empty_body)) = shapes.get(&origin).copied()
{
apply_native_board_shape(json, &origin, shape, empty_body);
}
match json {
Value::Object(fields) => fields.values_mut().for_each(|child| visit(child, shapes, visited)),
Value::Array(items) => items.iter_mut().for_each(|child| visit(child, shapes, visited)),
_ => {}
}
}
visit(json, shapes, &mut std::collections::HashSet::new());
}
fn apply_native_board_shape(rest_node: &mut Value, origin: &str, shape: BoardShape, empty_body: bool) {
let Some(children) = rest_node.get("children").and_then(Value::as_array) else { return };
let has_generated_outline = !children.is_empty() && children[0]["type"] == "VECTOR";
let has_generated_label = children.len() == 2 && children[1]["type"] == "TEXT";
if !has_generated_outline || !(has_generated_label || (children.len() == 1 && empty_body)) {
return;
}
let (Some(width), Some(height)) = (
rest_node.get("size").and_then(|s| s.get("x")).and_then(Value::as_f64),
rest_node.get("size").and_then(|s| s.get("y")).and_then(Value::as_f64),
) else {
return;
};
if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) {
return;
}
let (width, height) = (width.min(crate::rest::props::MAX_SIZE), height.min(crate::rest::props::MAX_SIZE));
let Some(network) = serde_json::to_value(VectorNetwork::from_path(&shape.path(width, height))).ok() else { return };
rest_node["board"] = serde_json::json!({"type": "shape", "shape": shape.id()});
rest_node["fills"] = serde_json::json!([]);
rest_node["strokes"] = serde_json::json!([]);
rest_node["clipsContent"] = serde_json::json!(false);
rest_node["layoutMode"] = serde_json::json!("VERTICAL");
rest_node["primaryAxisAlignItems"] = serde_json::json!("CENTER");
rest_node["counterAxisAlignItems"] = serde_json::json!("CENTER");
rest_node["primaryAxisSizingMode"] = serde_json::json!("FIXED");
rest_node["counterAxisSizingMode"] = serde_json::json!("FIXED");
let [top, right, bottom, left] = shape.text_insets();
rest_node["paddingTop"] = serde_json::json!(top * height);
rest_node["paddingRight"] = serde_json::json!(right * width);
rest_node["paddingBottom"] = serde_json::json!(bottom * height);
rest_node["paddingLeft"] = serde_json::json!(left * width);
let Some(children) = rest_node.get_mut("children").and_then(Value::as_array_mut) else { return };
if children.len() == 1 {
children.push(serde_json::json!({
"id": format!("{origin};generated1"),
"type": "TEXT",
"name": "",
"characters": "",
"size": {"x": width, "y": height},
"relativeTransform": [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
"style": {"textAutoResize": "HEIGHT", "textAlignHorizontal": "CENTER"},
"layoutSizingHorizontal": "FILL"
}));
}
let outline = &mut children[0];
outline["name"] = serde_json::json!("Outline");
outline["vectorNetwork"] = network;
outline["size"] = serde_json::json!({"x": width, "y": height});
outline["relativeTransform"] = serde_json::json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]);
outline["layoutPositioning"] = serde_json::json!("ABSOLUTE");
outline["constraints"] = serde_json::json!({"horizontal": "SCALE", "vertical": "SCALE"});
outline.as_object_mut().map(|o| o.remove("cornerRadius"));
let label = &mut children[1];
label["layoutSizingHorizontal"] = serde_json::json!("FILL");
if let Some(style) = label.get_mut("style").and_then(Value::as_object_mut) {
style.insert("textAutoResize".into(), serde_json::json!("HEIGHT"));
style.insert("textAlignHorizontal".into(), serde_json::json!("CENTER"));
}
}
/// The shared snapshot mapper omits a generated text child whose characters are empty. FigCraft
/// still keeps that empty child on a native shape, matching its prior mapper behavior.
fn generated_empty_body(node: &Kv) -> bool {
fn record<'a, 's>(node: &'a Kv<'s>, field: &str) -> Option<&'a Kv<'s>> {
node.get(field)?.get("overrides")?.list().iter().find(|record| {
let Some(guids) = record.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list) else { return false };
if guids.len() != 1 {
return false;
}
let session = guids[0].get("sessionID").and_then(Kv::f64);
let local = guids[0].get("localID").and_then(Kv::f64);
session == Some(40_000_000.0) && local == Some(1.0)
})
}
let bounds = node.get("derivedImmutableFrameData");
let version = bounds.and_then(|v| v.get("version")).and_then(Kv::f64);
if version != Some(1.0) {
return false;
}
let Some(style) = record(node, "nodeGenerationData") else { return false };
let Some(_) = record(node, "derivedImmutableFrameData") else { return false };
style.get("textData").and_then(|v| v.get("characters")).and_then(Kv::str) == Some("")
}
/// FigJam's `shapeWithTextType` values that have a corresponding FigCraft board outline.
pub(super) fn board_shape(kind: &str) -> Option<BoardShape> {
Some(match kind {
"SQUARE" => BoardShape::Rectangle,
"ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle,
"ELLIPSE" => BoardShape::Ellipse,
"DIAMOND" => BoardShape::Diamond,
"TRIANGLE_UP" => BoardShape::Triangle,
"TRIANGLE_DOWN" => BoardShape::TriangleDown,
"PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight,
"PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft,
"TRAPEZOID" => BoardShape::Trapezoid,
"PENTAGON" => BoardShape::Pentagon,
"HEXAGON" => BoardShape::Hexagon,
"OCTAGON" => BoardShape::Octagon,
"STAR" => BoardShape::Star,
"PLUS" => BoardShape::Plus,
"ARROW_LEFT" => BoardShape::ArrowLeft,
"ARROW_RIGHT" => BoardShape::ArrowRight,
"CHEVRON" => BoardShape::Chevron,
"SPEECH_BUBBLE" => BoardShape::SpeechBubble,
"ENG_DATABASE" => BoardShape::Database,
"DOCUMENT_SINGLE" => BoardShape::Document,
"PREDEFINED_PROCESS" => BoardShape::PredefinedProcess,
"MANUAL_INPUT" => BoardShape::ManualInput,
"INTERNAL_STORAGE" => BoardShape::InternalStorage,
_ => return None,
})
}
/// REST importer warnings reworded for a `.fig` import (`None`: drop it).
pub(super) fn adapt_warning(w: String) -> Option<String> {
@@ -110,538 +260,3 @@ pub(super) fn adapt_warning(w: String) -> Option<String> {
}
Some(w.replace("the variables JSON", "the file").replace("the file JSON", "the file"))
}
// ---- small readers ----
/// A generated child is identified by one exact template GUID, not its array position.
fn generated_record<'a>(v: &View<'a>, field: &str, local_id: u32) -> Option<&'a Kv<'a>> {
v.get(field)?.get("overrides")?.list().iter().find(|row| {
row.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list).is_some_and(|guids| {
guids.len() == 1 && num(&guids[0], "sessionID") == Some(40_000_000.0) && num(&guids[0], "localID") == Some(f64::from(local_id))
})
})
}
fn num(n: &Kv, k: &str) -> Option<f64> {
n.get(k).and_then(Kv::f64)
}
fn guid(v: &Kv) -> Option<String> {
Some(format!("{}:{}", num(v, "sessionID")? as u64, num(v, "localID")? as u64))
}
#[cfg(test)]
mod connector_snapshot_budget_tests;
/// A `GUID`-holding reference (`StyleId`, `VariableID`, …): its `guid`.
fn ref_guid(v: &Kv) -> Option<String> {
v.get("guid").and_then(guid).filter(|g| g != NO_STYLE)
}
fn vec2(v: &Kv) -> Option<Value> {
Some(json!({"x": num(v, "x")?, "y": num(v, "y")?}))
}
fn size(v: &Kv) -> Option<(f64, f64)> {
Some((num(v, "x")?, num(v, "y")?))
}
fn matrix(m: &Kv) -> Option<Affine> {
let c = |k: &str| num(m, k);
let a = Affine::new([c("m00")?, c("m10")?, c("m01")?, c("m11")?, c("m02")?, c("m12")?]);
a.as_coeffs().iter().all(|x| x.is_finite()).then_some(a)
}
fn rows(a: Affine) -> Value {
let [a, b, c, d, e, f] = a.as_coeffs();
json!([[a, c, e], [b, d, f]])
}
fn copy_num(o: &mut Obj, n: &View, from: &str, to: &str) {
if let Some(x) = n.num(from) {
o.insert(to.into(), json!(x));
}
}
/// [`copy_num`] for a length: the layers of a scaled instance give it at the instance's scale.
fn copy_len(o: &mut Obj, n: &View, from: &str, to: &str) {
if let Some(x) = n.len(from) {
o.insert(to.into(), json!(x));
}
}
/// `x` at scale `k`; `None` when the result is not finite.
fn scaled(x: f64, k: f64) -> Option<f64> {
if k == 1.0 {
return Some(x);
}
let r = x * k;
r.is_finite().then_some(r)
}
fn copy_str(o: &mut Obj, n: &View, from: &str, to: &str) {
if let Some(s) = n.str(from) {
o.insert(to.into(), json!(s));
}
}
/// A node seen through override layers: the last layer with a field wins.
#[derive(Clone)]
struct View<'a> {
layers: Vec<&'a Kv<'a>>,
/// The factor each layer's lengths take (`scales[i]` is for `layers[i]`): the layers of a main
/// inside a scaled instance have the instance's, the override and derived rows of the instance
/// 1, being at the instance's scale already (#2091).
scales: Vec<f64>,
/// Size and transform worked out from the constraints, over the layers' own.
fitted: Option<((f64, f64), Affine)>,
}
impl<'a> View<'a> {
fn of(n: &'a Kv<'a>) -> Self {
Self::of_scaled(n, 1.0)
}
/// A node of a main inside an instance scaled by `k`: its lengths read `k` times as long.
fn of_scaled(n: &'a Kv<'a>, k: f64) -> Self {
Self { layers: vec![n], scales: vec![k], fitted: None }
}
/// This view with the layers of `upper` over it (`upper`'s fitted size and place).
fn over(&self, upper: &Self) -> Self {
let mut v = self.clone();
v.layers.extend(upper.layers.iter().copied());
v.scales.extend(upper.scales.iter().copied());
v.fitted = upper.fitted;
v
}
/// The factor of the lowest layer (the layer's own main), for values a style gives.
fn base_scale(&self) -> f64 {
self.scales.first().copied().unwrap_or(1.0)
}
fn size(&self) -> Option<(f64, f64)> {
self.fitted.map(|f| f.0).or_else(|| {
let (v, k) = self.find("size")?;
let (x, y) = size(v)?;
Some((scaled(x, k)?, scaled(y, k)?))
})
}
fn transform(&self) -> Option<Affine> {
self.fitted.map(|f| f.1).or_else(|| {
let (v, k) = self.find("transform")?;
let m = matrix(v)?;
if k == 1.0 {
return Some(m);
}
let [a, b, c, d, e, f] = m.as_coeffs();
let m = Affine::new([a, b, c, d, scaled(e, k)?, scaled(f, k)?]);
Some(m)
})
}
/// This view with `top` over it, each layer with the factor its lengths take.
fn with(&self, top: impl IntoIterator<Item = (&'a Kv<'a>, f64)>) -> Self {
let mut v = self.clone();
for (layer, scale) in top {
v.layers.push(layer);
v.scales.push(scale);
}
v
}
/// The factor of the layer that links a style in `key` (or `legacy`), the lowest layer's when
/// none does: what the linked style's lengths take.
fn link_scale(&self, key: &str, legacy: &str) -> f64 {
self.find(key).or_else(|| self.find(legacy)).map_or_else(|| self.base_scale(), |f| f.1)
}
/// This view with `style` just above the layer that links it in `key` (or `legacy`): the style
/// beats that layer's and lower layers' copies of its fields (stale when the style changed
/// since, or written for the style linked before), and override rows above the link beat it.
fn styled(&self, style: Option<&'a Kv<'a>>, key: &str, legacy: &str) -> Self {
let mut v = self.clone();
if let Some(s) = style {
let linked_in = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some());
let at = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1);
let at = at.min(v.layers.len());
// The style is at the scale of the layer that links it.
let k = at.checked_sub(1).and_then(|i| v.scales.get(i)).copied().unwrap_or(1.0);
v.layers.insert(at, s);
v.scales.insert(at, k);
}
v
}
/// An effect/grid list follows the same precedence as text styles: an override above the
/// style link wins, while the style beats stale copies on and below its linking row. A style
/// without the list is empty; it must not expose a stale list from a lower row.
fn styled_list(&self, style: &'a Kv<'a>, list: &str, key: &str, legacy: &str) -> (&'a [Kv<'a>], f64) {
let linked_in = |k: &str| self.layers.iter().rposition(|l| l.get(k).is_some());
let above = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1);
self.layers
.iter()
.zip(&self.scales)
.skip(above)
.rev()
.find_map(|(row, scale)| row.get(list).map(|v| (v.list(), *scale)))
.unwrap_or_else(|| (style.get(list).map(Kv::list).unwrap_or_default(), self.link_scale(key, legacy)))
}
fn get(&self, k: &str) -> Option<&'a Kv<'a>> {
self.layers.iter().rev().find_map(|l| l.get(k))
}
/// [`Self::get`], and the factor of the layer that has it.
fn find(&self, k: &str) -> Option<(&'a Kv<'a>, f64)> {
self.layers.iter().zip(&self.scales).rev().find_map(|(l, s)| l.get(k).map(|v| (v, *s)))
}
/// A length: the number `k` holds at the scale of the layer that has it.
fn len(&self, k: &str) -> Option<f64> {
let (v, s) = self.find(k)?;
scaled(v.f64()?, s)
}
/// [`Self::list`], and the factor of the layer that has it.
fn list_scaled(&self, k: &str) -> (&'a [Kv<'a>], f64) {
self.find(k).map_or((&[], 1.0), |(v, s)| (v.list(), s))
}
fn num(&self, k: &str) -> Option<f64> {
self.get(k).and_then(Kv::f64)
}
fn str(&self, k: &str) -> Option<&'a str> {
self.get(k).and_then(Kv::str)
}
fn flag(&self, k: &str) -> Option<bool> {
self.get(k).and_then(Kv::bool)
}
fn list(&self, k: &str) -> &'a [Kv<'a>] {
self.get(k).map(Kv::list).unwrap_or_default()
}
}
struct Mapper<'a> {
nodes: BTreeMap<String, &'a Kv<'a>>,
kids: BTreeMap<String, Vec<(&'a str, String)>>,
blobs: Vec<&'a [u8]>,
/// Component property definitions: id → (REST name "Name#id", type).
prop_defs: BTreeMap<String, (String, &'a str)>,
/// The copies of a set's definitions each variant keeps (no name or type of their own; the
/// variant's layers and its instances' assignments use them): copy id → the definition's id.
prop_parents: BTreeMap<String, String>,
/// File nodes by asset `key` and `version`: references can name a collection, variable or
/// style as the asset instead of the guid, and the file carries the resources to resolve
/// them (the collection node itself says the same `key`).
assets: BTreeMap<String, BTreeMap<String, String>>,
styles: Obj,
/// Descriptions of components and component sets (REST `components` / `componentSets`).
components: Obj,
sets: Obj,
/// Layers and keys of each main, built when an instance of it first needs them.
override_scopes: BTreeMap<String, Rc<OverrideScope>>,
/// Entries held by `override_scopes` (bounded by `max_nodes` together).
override_scope_entries: usize,
/// Component-bearing branches of the file's internal canvases (cached library definitions).
library_contexts: Vec<Value>,
/// Layers visited while scanning internal canvases, across all of them.
library_scan_count: usize,
warnings: crate::rest::Warnings,
count: usize,
/// The mains in the file that instances or instance swap defaults name, and the mains mapped
/// as layers: the difference is what the layer cap kept out.
referenced_mains: BTreeSet<String>,
mapped_mains: BTreeSet<String>,
/// Most layers produced or scanned, instance expansion included; the one place the cap comes
/// from (see [`super::layer_budget`]).
max_nodes: usize,
/// Layers kept back for the visible pages' top level while library copies are mapped, so the
/// copies can't take the whole budget and leave the pages empty.
reserved: usize,
/// Vector networks, each built once: the layers that show one (every instance of a main
/// holding it) name it by `vectorNetworkRef`. Kept out of the JSON, where a large file's
/// networks took gigabytes.
networks: Vec<Option<VectorNetwork>>,
/// Index in `networks` by its blob, position scale, style table, point-radius scale and the
/// layer's corner radius (which points without one of their own take).
network_ids: HashMap<(usize, u64, u64, usize, u64, u64), usize>,
/// Region paint elements (paints and gradient stops) read so far: one budget for the whole
/// file, since layers with region paints don't share their network.
region_paint_elements: usize,
/// The file is a FigJam whiteboard: its objects are built as native board items.
board: bool,
}
impl<'a> Mapper<'a> {
fn new(msg: &'a Kv<'a>, max_nodes: usize) -> Self {
let mut nodes = BTreeMap::new();
let mut kids: BTreeMap<String, Vec<(&'a str, String)>> = BTreeMap::new();
let mut prop_defs = BTreeMap::new();
let mut prop_parents = BTreeMap::new();
let changes = msg.get("nodeChanges").map(Kv::list).unwrap_or_default();
// The last change of a GUID wins; a REMOVED change deletes what came before it.
for n in changes {
let Some(id) = n.get("guid").and_then(guid) else { continue };
if n.get("phase").and_then(Kv::str) == Some("REMOVED") {
nodes.remove(&id);
} else {
nodes.insert(id, n);
}
}
for n in changes {
let Some(id) = n.get("guid").and_then(guid) else { continue };
if !nodes.get(&id).is_some_and(|latest| std::ptr::eq(*latest, n)) {
continue;
}
// Variables and their collections are read from the node list (`of_type`), never
// as layers: out of the layer tree, an instance's expansion doesn't walk them again for
// every instance without counting them (#1077).
if let Some(p) = n.get("parentIndex")
&& let Some(parent) = p.get("guid").and_then(guid)
&& !matches!(n.get("type").and_then(Kv::str), Some("VARIABLE" | "VARIABLE_SET"))
{
kids.entry(parent).or_default().push((p.get("position").and_then(Kv::str).unwrap_or(""), id.clone()));
}
for d in n.get("componentPropDefs").map(Kv::list).unwrap_or_default() {
let Some(did) = d.get("id").and_then(guid) else { continue };
if let (Some(name), Some(ty)) = (d.get("name").and_then(Kv::str), d.get("type").and_then(Kv::str)) {
prop_defs.insert(did.clone(), (format!("{name}#{did}"), ty));
} else if let Some(parent) = d.get("parentPropDefId").and_then(guid) {
prop_parents.insert(did, parent);
}
}
}
for list in kids.values_mut() {
list.sort();
list.dedup_by(|a, b| a.1 == b.1);
}
let blobs =
msg.get("blobs").map(Kv::list).unwrap_or_default().iter().map(|b| b.get("bytes").and_then(Kv::bytes).unwrap_or_default()).collect();
let mut assets: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
for n in msg.get("nodeChanges").map(Kv::list).unwrap_or_default() {
let (Some(key), Some(id)) = (n.get("key").and_then(Kv::str), n.get("guid").and_then(guid)) else { continue };
if key.is_empty() || key.len() > MAX_ASSET_PART {
continue;
}
let version = n.get("version").and_then(Kv::str).filter(|v| !v.is_empty() && v.len() <= MAX_ASSET_PART).unwrap_or("");
assets.entry(key.to_string()).or_default().entry(version.to_string()).or_insert(id);
}
Self {
nodes,
kids,
blobs,
prop_defs,
prop_parents,
assets,
styles: Obj::new(),
components: Obj::new(),
sets: Obj::new(),
override_scopes: BTreeMap::new(),
override_scope_entries: 0,
library_contexts: Vec::new(),
library_scan_count: 0,
warnings: crate::rest::Warnings::default(),
count: 0,
referenced_mains: BTreeSet::new(),
mapped_mains: BTreeSet::new(),
max_nodes,
reserved: 0,
networks: Vec::new(),
board: false,
network_ids: HashMap::new(),
region_paint_elements: 0,
}
}
/// The id of the resource a `VariableSetID` (or `VariableID`, `StyleId`) names: its `guid`,
/// else the file node its asset `key` and `version` names (a collection from a library is
/// referenced as the asset, and the file's own node for it says the same `key`). `None` when
/// the reference has neither or the asset names nothing (or ambiguously) in the file.
/// Original code for this importer: the field names are those of the schema each file embeds.
fn resource_id(&self, v: &Kv) -> Option<String> {
// A guid names the resource when this file holds a node by it. One from another file (the
// library a style or collection came from, as a paste carries) names nothing here: the
// asset it also names finds the file's copy (#1638).
if let Some(g) = v.get("guid").and_then(guid).filter(|g| *g != NO_STYLE && self.nodes.contains_key(g)) {
return Some(g);
}
let asset = v.get("assetRef")?;
let key = asset.get("key").and_then(Kv::str)?;
let versions = self.assets.get(key)?;
let version = asset.get("version").and_then(Kv::str);
match version {
Some(v) => versions.get(v),
// Without a version: an unversioned record, else the file's only one.
None => versions.get("").or_else(|| (versions.len() == 1).then(|| versions.values().next()).flatten()),
}
.cloned()
}
/// The collection a `VariableSetID` names, as one collection per library asset: a file that
/// took several updates of a library holds a copy of the collection for each version it met,
/// all with the same asset `key`. Variables and explicit modes may name any of those copies,
/// while the mode ids stay the same across them, so every copy maps to the newest one (the
/// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set
/// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the
/// default mode of the newest copy. A reference by asset that names no copy by itself (no
/// version, or a version the file doesn't hold, while it holds several) still names the asset:
/// its newest live copy.
pub(super) fn collection_id(&self, v: &Kv) -> Option<String> {
let by_asset = || v.get("assetRef")?.get("key").and_then(Kv::str).and_then(VarCanon::newest_set);
match self.resource_id(v) {
Some(id) if self.nodes.contains_key(&id) => Some(self.canonical_collection(&id).unwrap_or(id)),
// The asset index can name a node a later change removed: the asset's live copy instead.
Some(id) => by_asset().or(Some(id)),
None => by_asset(),
}
}
/// The newest live copy of collection node `id`'s library asset, when it has a key.
pub(super) fn canonical_collection(&self, id: &str) -> Option<String> {
let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?;
VarCanon::newest_set(key)
}
/// A note about what this file's mapping left out or changed. Counted, as the REST importer
/// counts its own: these notes are met once per layer, so the kinds were named once each with
/// no sign of how much of the file they covered -- a file whose every text layer lost a
/// setting read the same as one where a single layer did (#467). The collector keeps the
/// first-seen order and the same cap, since some notes name fields of the file (image
/// filters).
fn warn(&mut self, w: impl Into<String>) {
self.warnings.add(w.into());
}
fn children(&self, id: &str) -> Vec<String> {
self.kids.get(id).map(|k| k.iter().map(|(_, c)| c.clone()).collect()).unwrap_or_default()
}
/// How many layers may be produced now: the cap, less what is kept for the visible pages.
fn budget(&self) -> usize {
self.max_nodes.saturating_sub(self.reserved)
}
}
/// A library version (`"40727:1183"`) as numbers to order by; unparsable parts rank lowest.
fn version_rank(v: &str) -> (u64, u64) {
let mut parts = v.split(':').map(|p| p.trim().parse::<u64>().unwrap_or(0));
(parts.next().unwrap_or(0), parts.next().unwrap_or(0))
}
/// Library variables, one per asset. A file that took several updates of a library keeps a copy
/// of a variable for each version it met (same `key`, another `version`), and layers and other
/// variables name them by that asset (`assetRef {key, version}`) rather than by guid. Each
/// reference goes to the newest copy: it has the values of every mode the library has now, where
/// an older one lacks the modes added since (a layer under a page set to such a mode fell back to
/// the default one). Kept per thread while a file is mapped: the paint and variable readers that
/// meet references are free functions.
#[derive(Default)]
pub(super) struct VarCanon {
by_key: HashMap<String, String>,
by_id: HashMap<String, String>,
/// Every live variable node of the file, with a key or not.
local: BTreeSet<String>,
/// The newest live copy of each library collection, by asset key. Read from the file's live
/// nodes (the last change of each guid, REMOVED ones gone), not from the asset index, which
/// keeps the first node it met for a key and version even when a later change removed it.
sets_by_key: HashMap<String, String>,
}
thread_local! {
static VAR_CANON: std::cell::RefCell<Option<VarCanon>> = const { std::cell::RefCell::new(None) };
}
/// Removes the thread's table when the mapping is done.
pub(super) struct VarCanonGuard;
impl Drop for VarCanonGuard {
/// Clears the thread's table, so a later file on this thread starts without it.
fn drop(&mut self) {
VAR_CANON.with(|c| c.borrow_mut().take());
}
}
impl VarCanon {
/// Builds the table from mapper `m`'s live nodes (newest copy per asset key, for variables and
/// for collections) and installs it for this thread until the returned guard is dropped.
fn install(m: &Mapper) -> VarCanonGuard {
let mut newest: HashMap<String, ((u64, u64), String)> = HashMap::new();
let mut copies: Vec<(String, String)> = Vec::new();
let mut local = BTreeSet::new();
let mut sets: HashMap<String, ((u64, u64), String)> = HashMap::new();
for (id, n) in &m.nodes {
let ty = n.get("type").and_then(Kv::str);
if !matches!(ty, Some("VARIABLE" | "VARIABLE_SET")) || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) {
continue;
}
if ty == Some("VARIABLE_SET") {
if let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) {
let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or(""));
let e = sets.entry(key.to_string()).or_insert_with(|| (rank, id.clone()));
if rank > e.0 || (rank == e.0 && *id > e.1) {
*e = (rank, id.clone());
}
}
continue;
}
local.insert(id.clone());
let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue };
let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or(""));
copies.push((id.clone(), key.to_string()));
let e = newest.entry(key.to_string()).or_insert_with(|| (rank, id.clone()));
if rank > e.0 || (rank == e.0 && *id > e.1) {
*e = (rank, id.clone());
}
}
let mut t = VarCanon::default();
for (id, key) in copies {
if let Some((_, canon)) = newest.get(&key) {
t.by_id.insert(id, canon.clone());
}
}
t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect();
t.local = local;
t.sets_by_key = sets.into_iter().map(|(k, (_, id))| (k, id)).collect();
VAR_CANON.with(|c| *c.borrow_mut() = Some(t));
VarCanonGuard
}
/// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. A guid
/// counts when this file holds a variable by it; one from another file (a paste carries the
/// library's own guids) names nothing here, so the asset it also names is tried before it is
/// kept as it is.
pub(super) fn resolve(r: &Kv) -> Option<String> {
let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE);
VAR_CANON.with(|c| {
let c = c.borrow();
let Some(t) = c.as_ref() else { return by_guid.clone() };
if let Some(g) = by_guid.as_ref().filter(|g| t.local.contains(*g)) {
return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone()));
}
let by_asset = r.get("assetRef").and_then(|a| a.get("key")).and_then(Kv::str).and_then(|k| t.by_key.get(k)).cloned();
by_asset.or(by_guid)
})
}
/// The newest live copy of the library collection with asset key `key`.
pub(super) fn newest_set(key: &str) -> Option<String> {
VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.sets_by_key.get(key).cloned()))
}
/// Whether a table is installed on this thread (for tests: none outlives the mapping).
#[cfg(test)]
pub(crate) fn installed() -> bool {
VAR_CANON.with(|c| c.borrow().is_some())
}
/// Whether variable node `id` is an older copy another one replaces.
pub(super) fn superseded(id: &str) -> bool {
VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id))
}
}
-216
View File
@@ -1,216 +0,0 @@
//! FigJam whiteboard objects as native board items: what a `.jam` import builds in place of the
//! generated frames a `.fig` keeps. The REST JSON carries them as a `board` field
//! ([`crate::rest`] reads it).
use super::layer::{own_text, valid_size};
use super::paint::paint;
use super::{Affine, Kv, MAX_DEPTH, Mapper, Obj, Value, View, generated_record, json, num};
use figcraft_doc::BoardShape;
impl<'a> Mapper<'a> {
/// A sticky as a native board sticky: its frame (size, place, opacity and shadows as saved,
/// the saved colour) holding the note and, when saved, the author line. `None` (nothing
/// changed) unless every generated record is complete: then the caller keeps the generated
/// layers.
pub(super) fn native_sticky(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) {
return None;
}
let record = |id: u32| {
let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?);
let view = View::of(style).with([(bounds, 1.0)]);
(valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view)
};
let background = record(0)?;
let fills = background.list("fillPaints");
let solid = matches!(fills, [p] if p.get("type").and_then(Kv::str) == Some("SOLID") && p.get("visible").and_then(Kv::bool) != Some(false));
if !solid || !background.list("strokePaints").is_empty() {
return None;
}
let note = record(1).filter(|n| own_text(n).is_some())?;
let author = record(2).filter(|a| a.flag("visible") != Some(false) && own_text(a).is_some());
let wanted = 1 + usize::from(author.is_some());
if depth >= MAX_DEPTH || self.count.saturating_add(wanted) > self.budget() {
return None;
}
let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?;
let at = note.transform().unwrap_or_default().as_coeffs();
let pad = |x: f64| if x.is_finite() { x.clamp(0.0, (w.min(h) / 2.0).max(0.0)) } else { 0.0 };
let (pad_x, pad_y) = (pad(at[4]), pad(at[5]));
// Everything is valid: build.
let paints: Vec<Value> = fills.iter().filter_map(|p| paint(p, &mut |m| self.warn(m))).collect();
o.insert("fills".into(), Value::Array(paints));
o.insert("strokes".into(), json!([]));
o.insert("clipsContent".into(), json!(false));
match background.len("cornerRadius") {
Some(r) => o.insert("cornerRadius".into(), json!(r)),
None => o.remove("cornerRadius"),
};
for (k, val) in [
("layoutMode", json!("VERTICAL")),
("primaryAxisAlignItems", json!("SPACE_BETWEEN")),
("counterAxisAlignItems", json!("MIN")),
("primaryAxisSizingMode", json!("AUTO")),
("counterAxisSizingMode", json!("FIXED")),
("minHeight", json!(h)),
("itemSpacing", json!(8.0)),
("paddingTop", json!(pad_y)),
("paddingBottom", json!(pad_y)),
("paddingLeft", json!(pad_x)),
("paddingRight", json!(pad_x)),
] {
o.insert(k.into(), val);
}
let mut kids = Vec::new();
let mut written = String::new();
for (local, view) in [(1, Some(note)), (2, author)] {
let Some(view) = view else { continue };
let chars = own_text(&view).unwrap_or_default();
let mut layer = Obj::new();
layer.insert("id".into(), json!(format!("{rest_id};generated{local}")));
layer.insert("type".into(), json!("TEXT"));
layer.insert("name".into(), json!(if local == 1 { chars.chars().take(40).collect::<String>() } else { "Author".to_string() }));
self.common(&mut layer, &view, "TEXT", Affine::IDENTITY, None);
self.text(&mut layer, &view);
if let Some(Value::Object(style)) = layer.get_mut("style") {
style.insert("textAutoResize".into(), json!("HEIGHT"));
style.insert("textAlignHorizontal".into(), json!("LEFT"));
}
layer.insert("layoutSizingHorizontal".into(), json!("FILL"));
if local == 2 {
written = chars.trim().to_string();
}
self.count += 1;
kids.push(Value::Object(layer));
}
o.insert("board".into(), json!({"type": "sticky", "author": written}));
Some(kids)
}
}
impl<'a> Mapper<'a> {
/// A sticky or shape with text as a native board item, or `None` with the note that it is
/// a frame with its generated layers.
pub(super) fn native_board_item(&mut self, own: &str, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
let native = if own == "STICKY" { self.native_sticky(o, v, rest_id, depth) } else { self.native_shape(o, v, rest_id, depth) };
if native.is_none() && own == "STICKY" {
self.warn("sticky layers import as frames with their text");
} else if native.is_none() {
self.warn("shape with text layers import as frames with their text");
}
native
}
}
impl<'a> Mapper<'a> {
/// A shape with text as a native board shape: an empty frame holding FigCraft's own outline
/// (the file's paints and weight) and the text, centred. `None` (nothing changed) when the kind
/// has no FigCraft outline or a generated record is damaged: then the caller keeps the
/// generated layers.
pub(super) fn native_shape(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
let kind = v.str("shapeWithTextType").unwrap_or("SQUARE");
let Some(shape) = board_shape(kind) else {
self.warn(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind)));
return None;
};
if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) {
return None;
}
let record = |id: u32| {
let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?);
let view = View::of(style).with([(bounds, 1.0)]);
(valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view)
};
let background = record(0)?;
let body = record(1)?;
// Blank generated text must not hide text the outer node still carries (#1397): the
// generated layers keep it.
if own_text(&body).is_none() && own_text(v).is_some() {
return None;
}
if depth >= MAX_DEPTH || self.count.saturating_add(2) > self.budget() {
return None;
}
let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?;
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return None;
}
// The REST reader caps every size; the outline is drawn at the capped size too, so it
// stays inside its frame.
let (w, h) = (w.min(crate::rest::props::MAX_SIZE), h.min(crate::rest::props::MAX_SIZE));
// Everything is valid: build the outline from the record's paints, then the frame.
let mut outline = Obj::new();
outline.insert("id".into(), json!(format!("{rest_id};generated0")));
outline.insert("type".into(), json!("VECTOR"));
outline.insert("name".into(), json!("Outline"));
self.common(&mut outline, &background, "VECTOR", Affine::IDENTITY, None);
outline.insert("size".into(), json!({"x": w, "y": h}));
outline.insert("relativeTransform".into(), json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]));
outline.insert("vectorNetwork".into(), serde_json::to_value(figcraft_doc::VectorNetwork::from_path(&shape.path(w, h))).ok()?);
outline.insert("layoutPositioning".into(), json!("ABSOLUTE"));
outline.insert("constraints".into(), json!({"horizontal": "SCALE", "vertical": "SCALE"}));
outline.remove("cornerRadius");
let mut label = Obj::new();
label.insert("id".into(), json!(format!("{rest_id};generated1")));
label.insert("type".into(), json!("TEXT"));
label.insert("name".into(), json!(own_text(&body).map_or_else(|| "Text".to_string(), |c| c.chars().take(40).collect())));
self.common(&mut label, &body, "TEXT", Affine::IDENTITY, None);
self.text(&mut label, &body);
if let Some(Value::Object(style)) = label.get_mut("style") {
style.insert("textAutoResize".into(), json!("HEIGHT"));
style.insert("textAlignHorizontal".into(), json!("CENTER"));
}
label.insert("layoutSizingHorizontal".into(), json!("FILL"));
o.insert("fills".into(), json!([]));
o.insert("strokes".into(), json!([]));
o.insert("clipsContent".into(), json!(false));
o.remove("cornerRadius");
let [top, right, bottom, left] = shape.text_insets();
for (k, val) in [
("layoutMode", json!("VERTICAL")),
("primaryAxisAlignItems", json!("CENTER")),
("counterAxisAlignItems", json!("CENTER")),
("primaryAxisSizingMode", json!("FIXED")),
("counterAxisSizingMode", json!("FIXED")),
("paddingTop", json!(top * h)),
("paddingRight", json!(right * w)),
("paddingBottom", json!(bottom * h)),
("paddingLeft", json!(left * w)),
] {
o.insert(k.into(), val);
}
self.count += 2;
o.insert("board".into(), json!({"type": "shape", "shape": shape.id()}));
Some(vec![Value::Object(outline), Value::Object(label)])
}
}
/// FigJam's `shapeWithTextType` as the outline FigCraft draws for it; `None` for the kinds it has none for.
pub(in crate::fig) fn board_shape(kind: &str) -> Option<BoardShape> {
Some(match kind {
"SQUARE" => BoardShape::Rectangle,
"ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle,
"ELLIPSE" => BoardShape::Ellipse,
"DIAMOND" => BoardShape::Diamond,
"TRIANGLE_UP" => BoardShape::Triangle,
"TRIANGLE_DOWN" => BoardShape::TriangleDown,
"PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight,
"PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft,
"TRAPEZOID" => BoardShape::Trapezoid,
"PENTAGON" => BoardShape::Pentagon,
"HEXAGON" => BoardShape::Hexagon,
"OCTAGON" => BoardShape::Octagon,
"STAR" => BoardShape::Star,
"PLUS" => BoardShape::Plus,
"ARROW_LEFT" => BoardShape::ArrowLeft,
"ARROW_RIGHT" => BoardShape::ArrowRight,
"CHEVRON" => BoardShape::Chevron,
"SPEECH_BUBBLE" => BoardShape::SpeechBubble,
"ENG_DATABASE" => BoardShape::Database,
"DOCUMENT_SINGLE" => BoardShape::Document,
"PREDEFINED_PROCESS" => BoardShape::PredefinedProcess,
"MANUAL_INPUT" => BoardShape::ManualInput,
"INTERNAL_STORAGE" => BoardShape::InternalStorage,
_ => return None,
})
}
-506
View File
@@ -1,506 +0,0 @@
use super::layer::own_text;
use super::text::char_styles;
use super::{BTreeMap, BTreeSet, Kv, MAX_DEPTH, MAX_SCALE_FACTOR, MIN_SCALE_FACTOR, Mapper, Obj, Rc, Value, View, guid, json};
/// An override row names a layer of the main by its current GUID or by the `overrideKey` the
/// layer had when the row was written: the key becomes the current GUID, unless the layer is
/// current already or the key is ambiguous.
fn normalize_override_segment(path: &mut [String], index: usize, scope: &OverrideScope) {
let Some(segment) = path.get(index) else { return };
if scope.current.contains(segment) {
return;
}
if let Some(Some(current)) = scope.aliases.get(segment) {
path[index] = current.clone();
}
}
/// Overrides and derived layout by id path.
type Overrides<'a> = BTreeMap<Vec<String>, Vec<OverrideRow<'a>>>;
/// Where an override entry comes from.
#[derive(Clone, Copy, PartialEq)]
pub(super) enum Entry {
Override,
Derived,
/// Derived layout of a nested instance for a size it no longer has: its size and place no
/// longer hold, the rest (resolved colours, text) still does.
Stale,
}
/// One override or derived-layout row addressed to a layer.
#[derive(Clone)]
pub(super) struct OverrideRow<'a> {
pub(super) row: &'a Kv<'a>,
pub(super) entry: Entry,
/// How many mains are being expanded around the instance that wrote the row: the rows of
/// the enclosing (outer) instances win over those of the inner ones.
source_depth: usize,
/// How many levels below the writing instance the row restates (`overrideLevel`; 0 for the
/// instance's own rows).
level: usize,
/// Position among the rows of the instance that wrote it; later rows win.
ordinal: usize,
/// The factor the row's lengths take: 1 for the rows of an instance in the document, the
/// factor of the layer of the enclosing main that holds the rows for a nested instance's own
/// (they are written in that main's space, #2091).
pub(super) scale: f64,
}
/// The nested level an override row restates: its `overrideLevel`, capped; 0 when it has none.
fn override_level(row: &Kv) -> usize {
row.get("overrideLevel").and_then(Kv::f64).filter(|l| l.is_finite() && *l > 0.0).map_or(0, |l| l.min(MAX_DEPTH as f64) as usize)
}
/// The layers of a main by current GUID, and the old `overrideKey` of each that has one
/// (`None` when two layers claim the same key).
pub(super) struct OverrideScope {
current: BTreeSet<String>,
aliases: BTreeMap<String, Option<String>>,
}
/// Values by key that nested instances add to their outer instances' (property values, slot
/// contents): an outer instance's value wins. Each instance keeps only what it adds and shares the
/// rest, instead of copying every outer value (#1077); lookups walk at most the nesting depth.
pub(super) struct Chain<V> {
own: BTreeMap<String, V>,
outer: Option<Rc<Chain<V>>>,
}
impl<V> Chain<V> {
/// `outer`'s values, then `own`'s for keys `outer` lacks (shared as it is when `own` adds nothing).
fn over(outer: Option<&Rc<Chain<V>>>, own: BTreeMap<String, V>) -> Rc<Self> {
match outer {
Some(o) if own.is_empty() => Rc::clone(o),
_ => Rc::new(Self { own, outer: outer.cloned() }),
}
}
pub(super) fn get(&self, key: &str) -> Option<&V> {
self.outer.as_ref().and_then(|o| o.get(key)).or_else(|| self.own.get(key))
}
}
/// Where an instance's expanded layers are: the overrides and derived layout of the outermost
/// instance (by id path), the path of the instance being expanded, and the property values.
#[derive(Clone)]
pub(super) struct Inst<'a> {
pub(super) root: String,
pub(super) path: Vec<String>,
pub(super) overrides: Rc<Overrides<'a>>,
/// Property values with the factor their lengths take (the layer of the writing instance's
/// node that holds the assignment, as for override rows).
props: Rc<Chain<(&'a Kv<'a>, f64)>>,
/// Slot property GUID → private slot-content node GUID.
pub(super) slot_contents: Rc<Chain<String>>,
/// Layers imported from a slot's independent content subtree.
pub(super) slot_content: bool,
/// Mains being expanded (an instance inside its own main stops there).
symbols: Vec<String>,
/// The factor the lengths of the expanded layers take: the instance's `uniformScaleFactor`
/// times those of the instances around it (#2091). Override and derived rows are already at
/// the instance's scale and take none.
pub(super) scale: f64,
}
impl<'a> Mapper<'a> {
/// The layers of main `main` by current GUID and by `overrideKey`. An instance nested in the
/// main is not entered: its layers belong to another main.
fn override_scope(&mut self, main: &str) -> Rc<OverrideScope> {
if let Some(scope) = self.override_scopes.get(main) {
return Rc::clone(scope);
}
let mut current = BTreeSet::new();
let mut aliases: BTreeMap<String, Option<String>> = BTreeMap::new();
let mut visited = BTreeSet::new();
let mut pending: Vec<(String, usize)> = self.children(main).into_iter().map(|id| (id, 1)).collect();
let mut complete = true;
while let Some((id, depth)) = pending.pop() {
if depth > MAX_DEPTH || visited.len() >= self.max_nodes {
complete = false;
break;
}
if !visited.insert(id.clone()) {
continue;
}
let Some(node) = self.nodes.get(&id) else { continue };
current.insert(id.clone());
if let Some(alias) = node.get("overrideKey").and_then(guid) {
let target = aliases.entry(alias).or_insert_with(|| Some(id.clone()));
if target.as_deref().is_some_and(|target| target != id) {
*target = None;
}
}
if node.get("type").and_then(Kv::str) != Some("INSTANCE") {
pending.extend(self.children(&id).into_iter().map(|child| (child, depth + 1)));
}
}
// A scope cut short could name the wrong layer for a key: use none of the keys.
if !complete {
aliases.clear();
}
let scope = Rc::new(OverrideScope { current, aliases });
let cost = scope.current.len() + scope.aliases.len();
if cost <= self.max_nodes.saturating_sub(self.override_scope_entries) {
self.override_scope_entries += cost;
self.override_scopes.insert(main.to_string(), Rc::clone(&scope));
}
scope
}
pub(super) fn is_instance_swap(&self, def: &Kv) -> Option<()> {
matches!(self.prop_def(&guid(def)?), Some((_, "INSTANCE_SWAP"))).then_some(())
}
/// The definition a copy of it was made from, followed to the original: the values an instance
/// sets are kept under it, since an assignment and the layers that read it may name different
/// copies of one definition.
pub(super) fn prop_root(&self, def: &str) -> String {
let mut def = def;
for _ in 0..=MAX_DEPTH {
let Some(parent) = self.prop_parents.get(def) else { break };
def = parent;
}
def.to_string()
}
/// The definition `def` names: its own, or the set's for a variant's copy of it.
fn prop_def(&self, def: &str) -> Option<&(String, &'a str)> {
let mut def = def;
for _ in 0..=MAX_DEPTH {
if let Some(found) = self.prop_defs.get(def) {
return Some(found);
}
def = self.prop_parents.get(def)?;
}
None
}
/// Component property definitions and description.
pub(super) fn component(&mut self, o: &mut Obj, v: &View<'a>, id: &str) {
let mut defs = Obj::new();
for d in v.list("componentPropDefs") {
if d.get("isDeleted").and_then(Kv::bool) == Some(true) {
continue;
}
let Some((name, ty)) = d.get("id").and_then(guid).and_then(|i| self.prop_defs.get(&i).cloned()) else { continue };
let init = d.get("initialValue");
let def = match ty {
"BOOL" => json!({"type": "BOOLEAN", "defaultValue": init.and_then(|i| i.get("boolValue")).and_then(Kv::bool).unwrap_or(true)}),
"TEXT" => json!({"type": "TEXT", "defaultValue": init.and_then(prop_text).unwrap_or("")}),
"INSTANCE_SWAP" => match init.and_then(|i| i.get("guidValue")).and_then(guid) {
Some(g) => {
if self.nodes.contains_key(&g) {
self.referenced_mains.insert(g.clone());
}
json!({"type": "INSTANCE_SWAP", "defaultValue": g})
}
None => continue,
},
"VARIANT" => json!({"type": "VARIANT"}),
"SLOT" => {
self.warn_non_default_slot_config(d);
self.warn_dropped_slot_preferred_values(d);
json!({"type": "SLOT"})
}
_ => {
self.warn(format!("{} component properties are not supported and were skipped", ty.to_ascii_lowercase()));
continue;
}
};
defs.insert(name, def);
}
if !defs.is_empty() {
o.insert("componentPropertyDefinitions".into(), Value::Object(defs));
}
if let Some(d) = v.str("symbolDescription").or_else(|| v.str("description")).filter(|d| !d.is_empty()) {
let into = if o.get("type").and_then(Value::as_str) == Some("COMPONENT_SET") { &mut self.sets } else { &mut self.components };
into.insert(id.to_string(), json!({"description": d}));
}
}
/// Preferred slot values are source component keys, but this mapper has no proven way to map
/// those keys to file GUIDs. They are dropped instead of guessing native NodeIds.
fn warn_dropped_slot_preferred_values(&mut self, def: &Kv<'a>) {
let entries = def.get("preferredValues").and_then(|v| v.get("instanceSwapValues")).map(Kv::list).unwrap_or_default();
if !entries.is_empty() {
self.warn("preferred slot component keys cannot be resolved to file nodes and were skipped");
}
}
fn warn_non_default_slot_config(&mut self, def: &Kv<'a>) {
let Some(config) = def.get("slotPropConfig") else { return };
let non_default = [
("stretchChildOnInsert", Some(false)),
("displayByDefault", Some(false)),
("minChildren", None),
("maxChildren", None),
("allowPreferredValuesOnly", Some(false)),
]
.into_iter()
.any(|(field, bool_default)| {
let Some(value) = config.get(field) else { return false };
if let Some(default) = bool_default { value.bool() != Some(default) } else { value.f64() != Some(0.0) }
});
if non_default {
self.warn("non-default slot settings are not represented and were skipped");
}
}
/// A layer's component property references, and inside an instance the values they take.
pub(super) fn prop_refs(&mut self, o: &mut Obj, v: &View<'a>, inst: Option<&Inst<'a>>) {
let mut refs = Obj::new();
for e in v.get("parameterConsumptionMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() {
let field = match e.get("variableField").and_then(Kv::str) {
Some("VISIBLE") => "visible",
Some("TEXT_DATA") => "characters",
Some("OVERRIDDEN_SYMBOL_ID") => "mainComponent",
Some("SLOT_CONTENT_ID") => "slot",
_ => continue,
};
let Some(def) =
e.get("variableData").and_then(|d| d.get("value")).and_then(|x| x.get("propRefValue")).and_then(|p| p.get("defId")).and_then(guid)
else {
continue;
};
// Expanded frames must follow their main frame's source link. A direct slot reference
// makes the engine resolve ownership against the instance, where the property is not defined.
if !(field == "slot" && inst.is_some())
&& let Some((name, _)) = self.prop_def(&def)
{
refs.insert(field.into(), json!(name));
}
let Some(&(val, val_scale)) = inst.and_then(|i| i.props.get(&self.prop_root(&def))) else { continue };
match field {
"visible" => {
if let Some(b) = val.get("boolValue").and_then(Kv::bool) {
o.insert("visible".into(), json!(b));
}
}
"characters" => {
if let Some(t) = prop_text(val) {
o.insert("characters".into(), json!(t));
// Run styles count the chars they were made for: for other chars only
// the value's own apply.
if own_text(v) != Some(t) {
o.remove("characterStyleOverrides");
o.remove("styleOverrideTable");
o.remove("_figLineStarts");
if let Some(tv) = prop_text_data(val) {
let size = o.get("style").and_then(|s| s.get("fontSize")).and_then(Value::as_f64);
char_styles(o, tv, val_scale, size, &mut |w| self.warn(w));
}
}
}
}
_ => {}
}
}
if !refs.is_empty() {
o.insert("componentPropertyReferences".into(), Value::Object(refs));
}
}
/// An instance's main and properties; the context its expanded layers are built in.
pub(super) fn instance(&mut self, o: &mut Obj, v: &View<'a>, id: &str, outer: Option<&Inst<'a>>, rest_id: &str) -> Option<(Inst<'a>, String)> {
let sd = v.get("symbolData");
let mut sym = v.get("overriddenSymbolID").and_then(guid).or_else(|| sd.and_then(|s| s.get("symbolID")).and_then(guid));
// An instance swap property value picks the main.
if let Some(i) = outer
&& let Some(def) = prop_ref(v, "OVERRIDDEN_SYMBOL_ID")
&& let Some(g) = i.props.get(&self.prop_root(&def)).and_then(|(p, _)| prop_guid(p))
{
sym = Some(g);
}
let Some(sym) = sym else {
self.warn("instances without a main component were imported as empty frames");
return None;
};
o.insert("componentId".into(), json!(sym));
let assignments = v.list("componentPropAssignments");
let mut props = Obj::new();
for a in assignments {
let Some((name, ty)) = a.get("defID").and_then(guid).and_then(|d| self.prop_def(&d).cloned()) else { continue };
let val = assigned(a);
let p = match ty {
"BOOL" => val.and_then(|x| x.get("boolValue")).and_then(Kv::bool).map(|b| json!({"type": "BOOLEAN", "value": b})),
"TEXT" => val.and_then(prop_text).map(|t| json!({"type": "TEXT", "value": t})),
"INSTANCE_SWAP" => val.and_then(prop_guid).map(|g| json!({"type": "INSTANCE_SWAP", "value": g})),
_ => None,
};
if let Some(p) = p {
props.insert(name, p);
}
}
if !props.is_empty() {
o.insert("componentProperties".into(), Value::Object(props));
}
if !self.nodes.contains_key(&sym) {
self.warn("instances of components that aren't in the file show no layers");
return None;
}
if !self.referenced_mains.contains(&sym) {
self.referenced_mains.insert(sym.clone());
}
if outer.is_some_and(|i| i.symbols.contains(&sym)) {
return None;
}
// Overrides by id path below this instance (the instance itself is addressed by its main's id).
let own_path: Vec<String> = outer.map(|i| [i.path.as_slice(), &[id.to_string()]].concat()).unwrap_or_default();
let scope = self.override_scope(&sym);
let mut overrides: Overrides<'a> = BTreeMap::new();
if let Some(inherited) = outer {
// Only rows addressed below this instance can apply inside it (every path looked up in
// it starts with `own_path`); they sort together, so the others aren't even visited. A
// nested instance used to copy all of its outer instance's rows (#1077).
let below = inherited.overrides.range(own_path.clone()..).take_while(|(path, _)| path.starts_with(&own_path));
for (path, rows) in below.filter(|(path, _)| path.len() > own_path.len()) {
let mut path = path.clone();
// Rows an outer instance wrote for this instance's layers may use their old keys.
normalize_override_segment(&mut path, own_path.len(), &scope);
overrides.entry(path).or_default().extend(rows.iter().cloned());
}
}
// A nested instance's derived layout is for the size it has in its main: resized here, the
// sizes and places in it no longer hold and its layers follow their constraints instead.
// A scaled size is the factor's product, rounded to a float: a looser match.
let tolerance = if outer.is_some_and(|i| i.scale != 1.0) { 1e-4 } else { 1e-6 };
let differs = |a: f64, b: f64| (a - b).abs() > tolerance * a.abs().max(b.abs()).max(1.0);
let outer_scale = outer.map_or(1.0, |i| i.scale);
let resized = outer.is_some()
&& match (self.nodes.get(id).and_then(|b| View::of_scaled(b, outer_scale).size()), v.size()) {
(Some(a), Some(b)) => differs(a.0, b.0) || differs(a.1, b.1),
(a, b) => a.is_some() != b.is_some(),
};
let mut local: Overrides<'a> = BTreeMap::new();
// The lists are at the scale of the layer of this node that holds them.
let scale_of = |k: &str| v.find(k).map_or(1.0, |f| f.1);
let lists = [
(sd.and_then(|s| s.get("symbolOverrides")).map(Kv::list).unwrap_or_default(), scale_of("symbolData")),
(v.list("derivedSymbolData"), scale_of("derivedSymbolData")),
];
let source_depth = outer.map_or(0, |i| i.symbols.len());
let mut ordinal = 0;
for (layer, (list, row_scale)) in lists.into_iter().enumerate() {
for ov in list {
let row_ordinal = ordinal;
ordinal += 1;
let mut rel: Vec<String> =
ov.get("guidPath").and_then(|g| g.get("guids")).map(Kv::list).unwrap_or_default().iter().filter_map(guid).collect();
if rel.is_empty() || rel == [sym.clone()] {
continue;
}
normalize_override_segment(&mut rel, 0, &scope);
// Explicit overrides, then derived layout (stale once the instance is resized).
let entry = match (layer, resized) {
(0, _) => Entry::Override,
(_, false) => Entry::Derived,
(_, true) => Entry::Stale,
};
local.entry([own_path.as_slice(), &rel].concat()).or_default().push(OverrideRow {
row: ov,
entry,
source_depth,
level: override_level(ov),
ordinal: row_ordinal,
scale: row_scale,
});
}
}
for (path, rows) in local {
overrides.entry(path).or_default().extend(rows);
}
for rows in overrides.values_mut() {
// Deeper rows apply first and outer rows win: a row restating a nested level counts at
// that level's depth, wherever it sits on the wire. Equal depths keep the outer source
// last, then wire order.
rows.sort_by_key(|row| (std::cmp::Reverse(row.source_depth + row.level), std::cmp::Reverse(row.source_depth), row.ordinal));
}
// This instance's own property values and slot contents; the outer instances' win.
let assignment_scale = v.find("componentPropAssignments").map_or(1.0, |f| f.1);
let mut all_props: BTreeMap<String, (&'a Kv<'a>, f64)> = BTreeMap::new();
let mut slot_contents: BTreeMap<String, String> = BTreeMap::new();
for a in assignments {
if let (Some(d), Some(val)) = (a.get("defID").and_then(guid), assigned(a)) {
all_props.entry(self.prop_root(&d)).or_insert((val, assignment_scale));
}
let Some(def) = a.get("defID").and_then(guid) else { continue };
if self.prop_def(&def).is_none_or(|(_, ty)| *ty != "SLOT") {
continue;
}
let var_value = a.get("varValue");
if var_value.and_then(|v| v.get("dataType")).and_then(Kv::str) != Some("SLOT_CONTENT_ID") {
self.warn("malformed slot content assignment was skipped");
continue;
}
let target = var_value.and_then(|v| v.get("value")).and_then(|v| v.get("slotContentIdValue")).and_then(|v| v.get("guid")).and_then(guid);
let Some(target) = target else {
self.warn("malformed slot content assignment was skipped");
continue;
};
if target == "4294967295:4294967295" {
self.warn("slot content assignment uses the empty GUID sentinel and was skipped");
continue;
}
if self.nodes.get(&target).is_none_or(|n| n.get("isSlotContent").and_then(Kv::bool) != Some(true)) {
self.warn("slot content assignment target is missing or is not slot content");
continue;
}
slot_contents.entry(self.prop_root(&def)).or_insert(target);
}
let mut symbols = outer.map(|i| i.symbols.clone()).unwrap_or_default();
symbols.push(sym.clone());
let root = outer.map_or_else(|| rest_id.to_string(), |i| i.root.clone());
// The scale the Scale tool gave the instance; a junk factor changes nothing.
let factor = sd
.and_then(|s| s.get("uniformScaleFactor"))
.and_then(Kv::f64)
.filter(|k| (MIN_SCALE_FACTOR..=MAX_SCALE_FACTOR).contains(k))
.unwrap_or(1.0);
let scale = (outer_scale * factor).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR);
Some((
Inst {
root,
path: own_path,
overrides: Rc::new(overrides),
props: Chain::over(outer.map(|i| &i.props), all_props),
slot_contents: Chain::over(outer.map(|i| &i.slot_contents), slot_contents),
slot_content: false,
symbols,
scale,
},
sym,
))
}
}
/// The text of a component property value.
fn prop_text<'k>(v: &'k Kv) -> Option<&'k str> {
prop_text_data(v).and_then(|t| t.get("characters")).and_then(Kv::str)
}
/// The text data of a component property value: `textValue`, or `textDataValue` in the variable form.
fn prop_text_data<'k, 's>(v: &'k Kv<'s>) -> Option<&'k Kv<'s>> {
v.get("textValue").or_else(|| v.get("textDataValue"))
}
/// The main an instance swap value names: `guidValue`, or `symbolIdValue` in the variable form.
pub(super) fn prop_guid(v: &Kv) -> Option<String> {
v.get("guidValue").and_then(guid).or_else(|| v.get("symbolIdValue")?.get("guid").and_then(guid))
}
/// The value a component property assignment sets: `value`, or the variable form `varValue` holds
/// when `value` is empty, as current files write many booleans and instance swaps.
pub(super) fn assigned<'k, 's>(assignment: &'k Kv<'s>) -> Option<&'k Kv<'s>> {
assignment.get("value").filter(|v| !matches!(v, Kv::Object(fields) if fields.is_empty())).or_else(|| assignment.get("varValue")?.get("value"))
}
/// The property a layer's `field` is bound to (`parameterConsumptionMap`).
pub(super) fn prop_ref(v: &View, field: &str) -> Option<String> {
v.get("parameterConsumptionMap")?.get("entries")?.list().iter().find_map(|e| {
if e.get("variableField").and_then(Kv::str) != Some(field) {
return None;
}
e.get("variableData")?.get("value")?.get("propRefValue")?.get("defId").and_then(guid)
})
}
-521
View File
@@ -1,521 +0,0 @@
use super::layer::{cap_name, own_text, svg_path, valid_size};
use super::paint::{paint, stroke};
use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows};
use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape};
use figcraft_doc::{ConnectorPath, MAX_RUNS, RouteEnd, Routing, Side, attach_points, attached_sides, route_along};
/// How a connector imports: from its saved snapshot (`terminal`: as one vector, no room for its
/// label), or drawn from its ends, as a frame with its line and `label` when it has one.
#[derive(Clone, Copy)]
pub(super) struct ConnectorShape {
pub snapshot: bool,
pub terminal: bool,
pub label: bool,
}
impl<'a> Mapper<'a> {
/// A connector's own properties on `o`; returns the children it adds (a line and a label).
pub(super) fn connector_layer(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, space: Affine, shape: ConnectorShape) -> Vec<Value> {
if shape.snapshot {
if shape.terminal {
self.connector_snapshot_flatten(o, v, rest_id, space);
} else {
o.insert("fills".into(), json!([]));
o.insert("strokes".into(), json!([]));
for key in ["styles", "strokeWeight", "strokeAlign", "strokeJoin", "strokeDashes", "strokeCap"] {
o.remove(key);
}
o.insert("clipsContent".into(), json!(false));
}
return Vec::new();
}
let mid = self.connector(o, v, space);
self.connector_line_style(o, v);
if shape.label {
return self.connector_label(o, v, rest_id, mid);
}
if connector_has_saved_label(v) {
self.warn("connector labels were skipped");
}
Vec::new()
}
/// Whether a connector without a snapshot keeps its label: it has text of its own and there is
/// room for its two children under the depth and layer limits.
pub(super) fn connector_label_fits(&self, v: &View<'a>, depth: usize) -> bool {
own_text(v).is_some() && depth < super::MAX_DEPTH && self.count.saturating_add(2) < self.budget()
}
/// A connector's end caps, and when it has no saved outline or network its line between its
/// ends (free points, or a sibling layer): straight to the point given on the layer (its
/// centre unless given), or elbowed or curved from a side of it, as a board connector runs;
/// an elbow saved with its path (FigJam's control points) runs along it (#1910).
/// Returns the middle of that line by length, in the connector's own coordinates.
pub(super) fn connector(&mut self, o: &mut Obj, v: &View<'a>, space: Affine) -> Option<Point> {
for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] {
if let Some(c) = v.str(from) {
o.insert(to.into(), json!(cap_name(c)));
}
}
if ["vectorNetwork", "vectorNetworkRef", "fillGeometry", "strokeGeometry"].iter().any(|k| o.contains_key(*k)) {
return None;
}
let routing = match v.str("connectorLineStyle") {
Some("ELBOWED") => Routing::Elbow,
Some("CURVED") => Routing::Curved,
_ => Routing::Straight,
};
let parent = v.get("parentIndex").and_then(|p| p.get("guid")).and_then(guid);
let end = |k: &str| -> Option<RouteEnd> {
let e = v.get(k)?;
let end = match e.get("endpointNodeID").and_then(guid).filter(|g| g != NO_STYLE) {
Some(id) => {
let n = *self.nodes.get(&id)?;
// Only siblings share the connector's coordinates.
if n.get("parentIndex").and_then(|p| p.get("guid")).and_then(guid) != parent {
return None;
}
let (w, h) = n.get("size").map_or((0.0, 0.0), |s| (num(s, "x").unwrap_or(0.0), num(s, "y").unwrap_or(0.0)));
let at = e.get("relativePosition").and_then(|r| Some((num(r, "x")?, num(r, "y")?)));
let t = n.get("transform").and_then(matrix).unwrap_or_default();
// An automatic magnet (`AUTO`: the side is picked when the connector is drawn;
// `CENTER`: the end aims at the layer's middle) attaches to the side facing the
// other end, as a board connector drawn here does; the file's `relativePosition`
// is not where such an end sits (#1909).
let automatic = matches!(e.get("magnet").and_then(Kv::str), Some("AUTO" | "CENTER"));
match routing {
Routing::Straight if !automatic => {
let (rx, ry) = at.unwrap_or((0.5, 0.5));
RouteEnd::Point(t * Point::new(w * rx, h * ry))
}
_ => RouteEnd::Box(t.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), side(e, at)),
}
}
None => RouteEnd::Point(e.get("position").and_then(|p| Some(Point::new(num(p, "x")?, num(p, "y")?)))?),
};
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
let ok = match end {
RouteEnd::Point(p) | RouteEnd::On(_, _, p) => finite(p),
RouteEnd::Box(b, _) => finite(b.origin()) && finite(Point::new(b.x1, b.y1)),
};
ok.then_some(end)
};
let ends = end("connectorStart").zip(end("connectorEnd"));
let path = ends.filter(|_| routing == Routing::Elbow).and_then(|(a, b)| saved_runs(v, a, b));
let Some(pts) = ends.and_then(|(a, b)| route_along(a, b, routing, path.as_ref())) else {
self.warn("connectors whose ends can't be placed are empty");
return None;
};
if routing != Routing::Straight && path.is_none() {
self.warn("elbowed and curved connectors without a saved path follow FigCraft's own routing");
}
// A curved route is one curve: its ends and the two control points between them.
let (path, vertices) = match (routing, pts.as_slice()) {
(Routing::Curved, [p0, c0, c1, p1]) => {
let mut path = BezPath::new();
path.move_to(*p0);
path.curve_to(*c0, *c1, *p1);
(path, vec![*p0, *p1])
}
_ => (pts.iter().enumerate().map(|(i, p)| if i == 0 { PathEl::MoveTo(*p) } else { PathEl::LineTo(*p) }).collect(), pts.clone()),
};
let b = path.bounding_box();
let (x0, y0) = (b.x0, b.y0);
o.insert("relativeTransform".into(), rows(space * Affine::translate((x0, y0))));
o.insert("size".into(), json!({"x": b.width(), "y": b.height()}));
let segments: Vec<Value> = match (routing, pts.as_slice()) {
(Routing::Curved, [p0, c0, c1, p1]) => vec![json!({"a": 0, "b": 1, "ta": [c0.x - p0.x, c0.y - p0.y], "tb": [c1.x - p1.x, c1.y - p1.y]})],
_ => (1..vertices.len()).map(|i| json!({"a": i - 1, "b": i})).collect(),
};
let vertices: Vec<Value> = vertices.iter().map(|p| json!({"x": p.x - x0, "y": p.y - y0})).collect();
o.insert("vectorNetwork".into(), json!({"vertices": vertices, "segments": segments}));
middle(&path).map(|m| m - b.origin().to_vec2())
}
/// The line's paint, weight, cap and dashes, which a connector keeps in its generated line
/// record rather than on itself: without a saved snapshot the routed line took none of them and
/// drew nothing (#1807). The connector's own values, when it has any, win.
fn connector_line_style(&mut self, o: &mut Obj, v: &View<'a>) {
let Some(line_style) = generated_record(v, "nodeGenerationData", 0) else { return };
let style = View::of(line_style);
// A connector that writes its own (even empty) paints or dash pattern keeps them: an empty
// list is no stroke, or a solid line, not a missing value.
if v.get("strokePaints").is_none() && o.get("strokes").and_then(Value::as_array).is_none_or(Vec::is_empty) {
let strokes: Vec<Value> = style.list("strokePaints").iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect();
if !strokes.is_empty() {
o.insert("strokes".into(), Value::Array(strokes));
}
}
let mut line = Obj::new();
stroke(&mut line, &style);
if v.get("dashPattern").is_some() {
line.remove("strokeDashes");
}
for (key, value) in line {
o.entry(key).or_insert(value);
}
}
/// A connector with a label but no saved snapshot of it, as the frame a saved one imports as:
/// `o` keeps the connector's place and size and gives its line to a vector child, and the
/// label is a text child centred on `mid` (the line's middle; the frame's centre when the line
/// came saved). Returns the two children.
pub(super) fn connector_label(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, mid: Option<Point>) -> Vec<Value> {
let (w, h) = o.get("size").map_or((0.0, 0.0), |s| (s["x"].as_f64().unwrap_or(0.0), s["y"].as_f64().unwrap_or(0.0)));
let mut line = Obj::new();
line.insert("id".into(), json!(format!("{rest_id};line")));
line.insert("type".into(), json!("VECTOR"));
line.insert("name".into(), json!(format!("{} line", v.str("name").unwrap_or("Connector"))));
line.insert("size".into(), json!({"x": w, "y": h}));
line.insert("relativeTransform".into(), rows(Affine::IDENTITY));
// The connector's fill paints colour its label; the line is only stroked.
let label_fills = o.remove("fills").filter(|f| f.as_array().is_some_and(|a| !a.is_empty()));
for key in LINE_KEYS {
if let Some(value) = o.remove(*key) {
line.insert((*key).into(), value);
}
}
o.insert("fills".into(), json!([]));
o.insert("strokes".into(), json!([]));
o.insert("clipsContent".into(), json!(false));
let mut text = Obj::new();
text.insert("id".into(), json!(format!("{rest_id};label")));
text.insert("type".into(), json!("TEXT"));
self.text(&mut text, v);
let characters = text.get("characters").and_then(Value::as_str).unwrap_or_default().to_string();
text.insert("name".into(), json!(characters));
text.insert("fills".into(), label_fills.unwrap_or_else(|| json!([{"type": "SOLID", "color": {"r": 0, "g": 0, "b": 0, "a": 1}}])));
// Centred on the line's middle in a box of the label's width, as tall as its lines (laid out
// again with the fonts at hand, so the box only centres it).
let size = text.get("style").and_then(|s| s["fontSize"].as_f64()).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(16.0);
let lines = characters.lines().count().max(1) as f64;
let (bw, bh) = (LABEL_WIDTH, lines * size * 1.4);
if let Some(style) = text.get_mut("style").and_then(Value::as_object_mut) {
style.insert("textAlignHorizontal".into(), json!("CENTER"));
style.insert("textAlignVertical".into(), json!("CENTER"));
style.insert("textAutoResize".into(), json!("NONE"));
}
let at = mid.unwrap_or(Point::new(w / 2.0, h / 2.0));
text.insert("size".into(), json!({"x": bw, "y": bh}));
text.insert("relativeTransform".into(), rows(Affine::translate((at.x - bw / 2.0, at.y - bh / 2.0))));
self.count += 2;
self.warn("connector labels without a saved snapshot are centred on the line, without their background");
vec![Value::Object(line), Value::Object(text)]
}
pub(super) fn connector_snapshot_supported(&self, v: &View<'a>) -> bool {
if v.str("connectorType") != Some("MANUAL")
|| v.get("connectorVersion").and_then(Kv::f64) != Some(1.0)
|| v.str("connectorLineStyle") != Some("STRAIGHT")
|| v.get("derivedImmutableFrameData").and_then(|data| data.get("version")).and_then(Kv::f64) != Some(1.0)
{
return false;
}
let Some(line) = generated_record(v, "derivedImmutableFrameData", 0) else { return false };
if line.get("transform").and_then(matrix).is_none() || valid_size(line.get("size")).is_none() {
return false;
}
let geometry = ["fillGeometry", "strokeGeometry"].iter().any(|key| {
line.get(key).map(Kv::list).unwrap_or_default().iter().any(|path| {
num(path, "commandsBlob")
.and_then(|index| self.blobs.get(index as usize))
.and_then(|blob| svg_path(blob))
.is_some_and(|data| !data.is_empty())
})
});
let network = line
.get("vectorData")
.and_then(|data| num(data, "vectorNetworkBlob"))
.and_then(|index| self.blobs.get(index as usize))
.and_then(|blob| network::decode(blob))
.is_some_and(|network| !network.segments.is_empty());
(geometry || network) && generated_record(v, "nodeGenerationData", 0).is_some()
}
pub(super) fn connector_snapshot_flatten(&mut self, out: &mut Obj, v: &View<'a>, rest_id: &str, space: Affine) {
let parent = space * v.get("transform").and_then(matrix).unwrap_or_default();
let Some(vector) = self.connector_snapshot_vector(v, rest_id, parent, false) else {
self.warn("connector snapshot vector data is missing; connector was left empty");
return;
};
for key in [
"size",
"relativeTransform",
"fills",
"strokes",
"strokeWeight",
"strokeAlign",
"strokeJoin",
"strokeDashes",
"strokeCap",
"strokeCapStart",
"strokeCapEnd",
"styles",
"fillGeometry",
"strokeGeometry",
"vectorNetwork",
] {
if let Some(value) = vector.get(key) {
out.insert(key.to_string(), value.clone());
}
}
if vector.get("visible").and_then(Value::as_bool) == Some(false) {
out.insert("visible".into(), json!(false));
}
if let Some(line_opacity) = vector.get("opacity").and_then(Value::as_f64) {
let root_opacity = out.get("opacity").and_then(Value::as_f64).unwrap_or(1.0);
out.insert("opacity".into(), json!(root_opacity * line_opacity));
}
if connector_has_saved_label(v) {
let reason = if self.count >= self.budget() { "node budget" } else { "depth limit" };
self.warn(format!("connector label was skipped: {reason} prevents nested snapshot children"));
}
}
/// Build the saved vector child or flattened terminal connector from the same child-only view.
fn connector_snapshot_vector(&mut self, v: &View<'a>, rest_id: &str, space: Affine, nested: bool) -> Option<Obj> {
let (Some(line), Some(line_style)) = (generated_record(v, "derivedImmutableFrameData", 0), generated_record(v, "nodeGenerationData", 0))
else {
return None;
};
let mut vector = Obj::new();
vector.insert("id".into(), json!(if nested { format!("{rest_id};vector") } else { rest_id.to_string() }));
vector.insert("type".into(), json!("VECTOR"));
if let Some(name) = v.str("name") {
vector.insert("name".into(), json!(if nested { format!("{name} vector") } else { name.to_string() }));
}
let line_view = View::of(line).with([(line_style, 1.0)]);
self.common(&mut vector, &line_view, "VECTOR", space, None);
self.geometry(&mut vector, &line_view);
for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] {
if let Some(cap) = v.str(from) {
vector.entry(to).or_insert_with(|| json!(cap_name(cap)));
}
}
Some(vector)
}
/// Snapshot the straight, manual connector contract carried by its generated children.
pub(crate) fn connector_snapshot_children(&mut self, v: &View<'a>, rest_id: &str) -> Vec<Value> {
if self.count >= self.budget() {
self.warn(format!("the file has more than {} layers; connector snapshot children were skipped", self.max_nodes));
return Vec::new();
}
let Some(vector) = self.connector_snapshot_vector(v, rest_id, Affine::IDENTITY, true) else {
self.warn("connector snapshot vector data is missing; connector was left empty");
return Vec::new();
};
let mut children = Vec::new();
children.push(Value::Object(vector));
self.count += 1;
let Some(text_frame) = generated_record(v, "derivedImmutableFrameData", 1) else {
if connector_has_saved_label(v) {
self.warn("connector label was skipped: derived text bounds are missing");
}
return children;
};
let Some(background) = generated_record(v, "derivedImmutableFrameData", 2) else {
if connector_has_saved_label(v) || valid_size(text_frame.get("size")).is_some_and(|(w, h)| w > 0.0 && h > 0.0) {
self.warn("connector label was skipped: derived background bounds are missing");
}
return children;
};
let Some(text_style) = generated_record(v, "nodeGenerationData", 1) else {
if valid_size(text_frame.get("size")).is_some_and(|(w, h)| w > 0.0 && h > 0.0) {
self.warn("connector label was skipped: text style data is missing");
}
return children;
};
let text_view = View::of(text_frame).with([(text_style, 1.0)]);
let Some(characters) = text_view.get("textData").and_then(|d| d.get("characters")).and_then(Kv::str).filter(|s| !s.trim().is_empty()) else {
return children;
};
let Some(text_transform) = text_frame.get("transform").and_then(matrix) else {
self.warn("connector label was skipped: text transform is invalid");
return children;
};
let Some(background_transform) = background.get("transform").and_then(matrix) else {
self.warn("connector label was skipped: background transform is invalid");
return children;
};
let Some(text_size) = valid_size(text_frame.get("size")) else {
self.warn("connector label was skipped: text bounds are invalid");
return children;
};
let Some(background_size) = valid_size(background.get("size")) else {
self.warn("connector label was skipped: background bounds are invalid");
return children;
};
let composed_text_transform = background_transform * text_transform;
if !composed_text_transform.as_coeffs().iter().all(|coefficient| coefficient.is_finite()) {
self.warn("connector label was skipped: composed text transform is invalid");
return children;
}
let Some(background_style) = generated_record(v, "nodeGenerationData", 2) else {
self.warn("connector label background was skipped: style data is missing");
self.add_connector_text(&mut children, rest_id, characters, text_size, composed_text_transform, &text_view);
return children;
};
let background_view = View::of(background).with([(background_style, 1.0)]);
if !background_view.list("fillPaints").is_empty() {
if self.count >= self.budget() {
self.warn(format!("the file has more than {} layers; connector label background was skipped", self.max_nodes));
} else {
let mut rect = Obj::new();
rect.insert("id".into(), json!(format!("{rest_id};label-background")));
rect.insert("type".into(), json!("RECTANGLE"));
rect.insert("name".into(), json!("connector label background"));
self.common(&mut rect, &background_view, "RECTANGLE", Affine::IDENTITY, None);
rect.insert("size".into(), json!({"x": background_size.0, "y": background_size.1}));
rect.insert("relativeTransform".into(), rows(background_transform));
rect.insert("clipsContent".into(), json!(false));
children.push(Value::Object(rect));
self.count += 1;
}
}
self.add_connector_text(&mut children, rest_id, characters, text_size, composed_text_transform, &text_view);
children
}
fn add_connector_text(
&mut self,
children: &mut Vec<Value>,
rest_id: &str,
characters: &str,
size: (f64, f64),
transform: Affine,
view: &View<'a>,
) {
if self.count >= self.budget() {
self.warn(format!("the file has more than {} layers; connector label was skipped", self.max_nodes));
return;
}
let mut text = Obj::new();
text.insert("id".into(), json!(format!("{rest_id};label-text")));
text.insert("type".into(), json!("TEXT"));
text.insert("name".into(), json!(characters));
text.insert("size".into(), json!({"x": size.0, "y": size.1}));
self.common(&mut text, view, "TEXT", Affine::IDENTITY, None);
text.insert("relativeTransform".into(), rows(transform));
self.text(&mut text, view);
children.push(Value::Object(text));
self.count += 1;
}
}
pub(super) fn connector_has_saved_label(v: &View<'_>) -> bool {
own_text(v).is_some()
|| generated_record(v, "nodeGenerationData", 1)
.and_then(|r| r.get("textData"))
.and_then(|d| d.get("characters"))
.and_then(Kv::str)
.is_some_and(|s| !s.trim().is_empty())
}
/// The path a FigJam elbow connector was saved with: its `connectorControlPoints`, one per run
/// between the first and the last, each a point on its run (in the connector's parent's
/// coordinates, like its ends) with the run's axis; the first run leaves the start's side and the
/// last arrives at the end's, so neither is saved. `None` without any, or when they don't make
/// such a path: a point off both axes, two runs in a row the same way, a first or last run that
/// would leave or arrive sideways to its side, or more runs than a hand could make here.
fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option<ConnectorPath> {
let saved = v.list("connectorControlPoints");
if saved.is_empty() || saved.len() + 2 > MAX_RUNS {
return None;
}
let (p0, p1) = attach_points(from, to);
let mid = p0.midpoint(p1);
let mut at = Vec::with_capacity(saved.len());
let (mut first, mut last) = (None, None);
for p in saved {
let pos = p.get("position").and_then(|q| Some(Point::new(num(q, "x")?, num(q, "y")?)))?;
let (ax, ay) = p.get("axis").and_then(|q| Some((num(q, "x")?, num(q, "y")?)))?;
let sideways = match (ax != 0.0, ay != 0.0) {
(true, false) => true,
(false, true) => false,
_ => return None,
};
if last == Some(sideways) {
return None;
}
first.get_or_insert(!sideways);
last = Some(sideways);
at.push(if sideways { pos.y - mid.y } else { pos.x - mid.x });
}
// The run through each end goes the way its side faces, out of the object: the first leaves
// the start's side for the first saved run, the last arrives at the end's from the last saved
// run. One along the side, or back into the object, doesn't.
let (across, last) = (first?, last?);
let (&a0, &a1) = (at.first()?, at.last()?);
// Where the run from `p` (`sideways`: going across) meets the saved run at `v`.
let onto = |sideways: bool, p: Point, v: f64| if sideways { Point::new(mid.x + v, p.y) } else { Point::new(p.x, mid.y + v) };
let out_of = |s: Option<Side>, p: Point, q: Point| s.is_none_or(|s| (q - p).dot(s.normal()) > 0.0);
let (s0, s1) = attached_sides(from, to);
let fits = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1));
fits.then_some(ConnectorPath::Runs { across, at })
}
/// The side of its layer a connector end leaves from: the `magnet` the file names (`AUTO` and
/// `CENTER`: the side facing the other end, whatever `relativePosition` says; #1909), else the edge
/// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end.
fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side {
match e.get("magnet").and_then(Kv::str) {
Some("TOP") => Side::Top,
Some("RIGHT") => Side::Right,
Some("BOTTOM") => Side::Bottom,
Some("LEFT") => Side::Left,
Some("AUTO" | "CENTER") => Side::Auto,
_ => match at {
Some((x, _)) if x <= 0.0 => Side::Left,
Some((x, _)) if x >= 1.0 => Side::Right,
Some((_, y)) if y <= 0.0 => Side::Top,
Some((_, y)) if y >= 1.0 => Side::Bottom,
_ => Side::Auto,
},
}
}
/// What a connector's line carries, moved to the line child when the connector becomes a frame.
const LINE_KEYS: &[&str] = &[
"vectorNetwork",
"vectorNetworkRef",
"fillGeometry",
"strokeGeometry",
"fills",
"strokes",
"strokeWeight",
"strokeAlign",
"strokeJoin",
"strokeDashes",
"strokeCap",
"strokeCapStart",
"strokeCapEnd",
"strokeWidthProfile",
"styles",
];
/// How wide a label without a saved snapshot is laid out, centred on its connector.
const LABEL_WIDTH: f64 = 200.0;
/// The point halfway along `path` by length.
fn middle(path: &BezPath) -> Option<Point> {
let mut pts: Vec<Point> = Vec::new();
figcraft_doc::geom::kurbo::flatten(path.iter(), 0.25, |el| {
if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el {
pts.push(p);
}
});
let total: f64 = pts.windows(2).map(|s| (s[1] - s[0]).hypot()).sum();
let mut left = total / 2.0;
for s in pts.windows(2) {
let l = (s[1] - s[0]).hypot();
if l >= left && l > 0.0 {
return Some(s[0].lerp(s[1], left / l));
}
left -= l;
}
pts.first().copied()
}
@@ -1,178 +0,0 @@
//! Connector snapshot flattening stays within the node and depth budgets.
use super::{MAX_DEPTH, Mapper, View};
use crate::fig::kiwi::Kv;
use crate::rest::MAX_NODES;
use figcraft_doc::geom::Affine;
fn obj(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> {
Kv::Object(fields)
}
fn guid(local_id: u64) -> Kv<'static> {
obj(vec![("sessionID", Kv::Uint(40_000_000)), ("localID", Kv::Uint(local_id))])
}
fn path_blob() -> Vec<u8> {
let mut bytes = vec![1];
bytes.extend(0.0f32.to_le_bytes());
bytes.extend(0.0f32.to_le_bytes());
bytes.push(2);
bytes.extend(20.0f32.to_le_bytes());
bytes.extend(10.0f32.to_le_bytes());
bytes
}
fn record(local_id: u64, mut fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> {
fields.push(("guidPath", obj(vec![("guids", Kv::Array(vec![guid(local_id)]))])));
obj(fields)
}
fn message() -> Kv<'static> {
let line = record(
0,
vec![
(
"transform",
obj(vec![
("m00", Kv::Float(1.0)),
("m01", Kv::Float(0.0)),
("m02", Kv::Float(0.0)),
("m10", Kv::Float(0.0)),
("m11", Kv::Float(1.0)),
("m12", Kv::Float(0.0)),
]),
),
("size", obj(vec![("x", Kv::Float(20.0)), ("y", Kv::Float(10.0))])),
("fillGeometry", Kv::Array(vec![obj(vec![("commandsBlob", Kv::Uint(0))])])),
],
);
let text = record(
1,
vec![
(
"transform",
obj(vec![
("m00", Kv::Float(1.0)),
("m01", Kv::Float(0.0)),
("m02", Kv::Float(0.0)),
("m10", Kv::Float(0.0)),
("m11", Kv::Float(1.0)),
("m12", Kv::Float(0.0)),
]),
),
("size", obj(vec![("x", Kv::Float(50.0)), ("y", Kv::Float(20.0))])),
],
);
let background = record(
2,
vec![
(
"transform",
obj(vec![
("m00", Kv::Float(1.0)),
("m01", Kv::Float(0.0)),
("m02", Kv::Float(0.0)),
("m10", Kv::Float(0.0)),
("m11", Kv::Float(1.0)),
("m12", Kv::Float(0.0)),
]),
),
("size", obj(vec![("x", Kv::Float(60.0)), ("y", Kv::Float(30.0))])),
],
);
let line_style = record(0, vec![]);
let text_style = record(1, vec![("textData", obj(vec![("characters", Kv::Str("budget label".into()))]))]);
let background_style = record(2, vec![("fillPaints", Kv::Array(vec![]))]);
obj(vec![
(
"nodeChanges",
Kv::Array(vec![obj(vec![
("guid", obj(vec![("sessionID", Kv::Uint(1)), ("localID", Kv::Uint(123))])),
("type", Kv::Enum("CONNECTOR")),
("name", Kv::Str("budget connector".into())),
("connectorType", Kv::Enum("MANUAL")),
("connectorVersion", Kv::Float(1.0)),
("connectorLineStyle", Kv::Enum("STRAIGHT")),
("derivedImmutableFrameData", obj(vec![("version", Kv::Float(1.0)), ("overrides", Kv::Array(vec![line, text, background]))])),
("nodeGenerationData", obj(vec![("overrides", Kv::Array(vec![line_style, text_style, background_style]))])),
])]),
),
("blobs", Kv::Array(vec![obj(vec![("bytes", Kv::Bytes(path_blob()))])])),
])
}
#[test]
fn connector_snapshot_respects_last_and_zero_child_slots() {
let message = message();
let node = message.get("nodeChanges").unwrap().list().first().unwrap();
let view = View::of(node);
let mut mapper = Mapper::new(&message, MAX_NODES);
mapper.count = MAX_NODES - 1;
let children = mapper.connector_snapshot_children(&view, "1:123");
assert_eq!(children.len(), 1, "the final available slot preserves the saved vector");
assert_eq!(children[0]["type"], "VECTOR");
assert!(!children[0]["fillGeometry"].as_array().unwrap().is_empty(), "saved outline survives the budget limit");
assert_eq!(children[0]["fillGeometry"][0]["path"], "M 0 0 L 20 10");
assert_eq!(mapper.count, MAX_NODES);
assert!(mapper.warnings.seen().any(|warning| warning == format!("the file has more than {MAX_NODES} layers; connector label was skipped")));
let mut mapper = Mapper::new(&message, MAX_NODES);
mapper.count = MAX_NODES;
let children = mapper.connector_snapshot_children(&view, "1:123");
assert!(children.is_empty());
assert_eq!(mapper.count, MAX_NODES, "the node budget is never exceeded");
assert!(mapper.warnings.seen().any(|warning| warning.contains("connector snapshot children were skipped")));
}
#[test]
fn connector_snapshot_flattens_vector_at_depth_and_node_limits() {
let message = message();
let mut mapper = Mapper::new(&message, MAX_NODES);
let depth_limited = mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector");
assert_eq!(depth_limited["type"], "VECTOR");
assert!(!depth_limited["fillGeometry"].as_array().unwrap().is_empty());
assert!(depth_limited.get("children").is_none());
assert!(mapper.warnings.seen().any(|warning| warning == "connector label was skipped: depth limit prevents nested snapshot children"));
let mut mapper = Mapper::new(&message, MAX_NODES);
mapper.count = MAX_NODES - 1;
let budget_limited = mapper.layer("1:123", None, Affine::IDENTITY, None, None, 0).expect("last allowed connector");
assert_eq!(budget_limited["type"], "VECTOR");
assert!(!budget_limited["fillGeometry"].as_array().unwrap().is_empty());
assert!(budget_limited.get("children").is_none());
assert_eq!(mapper.count, MAX_NODES);
assert!(mapper.warnings.seen().any(|warning| warning == "connector label was skipped: node budget prevents nested snapshot children"));
}
/// A mapper note is met once per layer, so the kinds were named once each with no sign of how much
/// of the file they covered: a file whose every layer lost a setting read the same as one where a
/// single layer did (#467). They are counted now, with the `(×n)` the REST importer already uses
/// and the import report already reads back off before translating a note.
#[test]
fn a_note_met_more_than_once_carries_its_count() {
let message = message();
let mut mapper = Mapper::new(&message, MAX_NODES);
for _ in 0..2 {
mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector");
}
let notes = std::mem::take(&mut mapper.warnings).finish();
let counted: Vec<&String> = notes.iter().filter(|n| n.contains("(×")).collect();
assert!(
counted.iter().any(|n| n.ends_with("(×2)") && n.contains("connector label was skipped: depth limit")),
"the note met twice says so: {notes:?}"
);
assert!(notes.iter().all(|n| !n.ends_with("(×1)")), "a count of one is left off: {notes:?}");
// One layer, and the same notes have no count at all.
let mut mapper = Mapper::new(&message, MAX_NODES);
mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector");
let once = std::mem::take(&mut mapper.warnings).finish();
assert!(once.iter().all(|n| !n.contains("(×")), "{once:?}");
assert_eq!(
once.len(),
counted.len() + notes.iter().filter(|n| !n.contains("(×")).count(),
"the same kinds, counted or not: {once:?} vs {notes:?}"
);
}
-333
View File
@@ -1,333 +0,0 @@
use super::component::{assigned, prop_guid};
use super::paint::color;
use super::variables::variable_value;
use super::{Affine, BTreeMap, BTreeSet, Kv, MAX_DEPTH, Mapper, Obj, Value, View, copy_str, guid, json, rows};
impl<'a> Mapper<'a> {
/// The DOCUMENT with its pages.
pub(super) fn document(&mut self) -> Value {
let doc_id = self.nodes.iter().find(|(_, n)| n.get("type").and_then(Kv::str) == Some("DOCUMENT")).map(|(id, _)| id.clone());
let pages: Vec<String> = match &doc_id {
Some(d) => self.children(d),
None => self.nodes.iter().filter(|(_, n)| n.get("type").and_then(Kv::str) == Some("CANVAS")).map(|(id, _)| id.clone()).collect(),
};
let mut internal = Vec::new();
let mut visible = Vec::new();
for p in pages {
let Some(&n) = self.nodes.get(&p) else { continue };
if n.get("type").and_then(Kv::str) != Some("CANVAS") {
self.warn("document children other than pages were skipped");
continue;
}
// The hidden page that holds styles, variables and library copies.
if n.get("internalOnly").and_then(Kv::bool) == Some(true) {
internal.push((p, n));
} else {
visible.push((p, n));
}
}
// The library copies the pages use come first: in a file past the layer cap, the pages'
// last layers are skipped rather than the mains every instance of them needs (#981).
let visible_pages: Vec<String> = visible.iter().map(|(p, _)| p.clone()).collect();
let required_mains = self.referenced_component_mains(&visible_pages);
// The pages and their top-level layers, up to half the cap, stay for the pages.
let top: usize = visible_pages.iter().map(|p| 1 + self.children(p).len()).sum();
self.reserved = top.min(self.max_nodes / 2);
for (id, canvas) in internal {
if let Some(context) = self.library_context(&id, canvas, &required_mains) {
self.library_contexts.push(context);
}
}
self.reserved = 0;
let out: Vec<Value> = visible.into_iter().map(|(p, n)| self.page(&p, n)).collect();
if out.is_empty() {
self.warn("the file has no pages");
}
let mut doc = json!({"id": doc_id.unwrap_or_else(|| "0:0".into()), "type": "DOCUMENT"});
doc["children"] = Value::Array(out);
doc
}
/// The ids of the components the visible pages use, directly or through the components they
/// use in turn (nested instances, swap targets, overrides naming another main).
fn referenced_component_mains(&mut self, visible_pages: &[String]) -> BTreeSet<String> {
let mut mains = BTreeSet::new();
let mut visited = BTreeSet::new();
let mut pending: Vec<(String, usize)> = visible_pages.iter().flat_map(|page| self.children(page)).map(|id| (id, 1)).collect();
while let Some((id, depth)) = pending.pop() {
if depth > MAX_DEPTH {
self.warn(format!("component references below {MAX_DEPTH} layer levels were skipped"));
continue;
}
if !visited.insert(id.clone()) {
continue;
}
if visited.len() > self.max_nodes {
let max = self.max_nodes;
self.warn(format!("the component reference scan reached the {max}-layer limit"));
break;
}
let Some(node) = self.nodes.get(&id) else { continue };
for target in self.component_main_targets(node) {
if mains.insert(target.clone()) {
pending.push((target, 1));
}
}
pending.extend(self.children(&id).into_iter().map(|child| (child, depth + 1)));
}
mains
}
/// The mains a layer names: an instance's own, the ones its overrides swap in, the instance-swap
/// defaults and values of component properties.
fn component_main_targets(&self, node: &Kv<'a>) -> Vec<String> {
let mut targets: Vec<String> = node
.get("componentPropDefs")
.map(Kv::list)
.unwrap_or_default()
.iter()
.filter_map(|definition| {
self.is_instance_swap(definition.get("id")?)?;
definition.get("initialValue")?.get("guidValue").and_then(guid)
})
.collect();
if node.get("type").and_then(Kv::str) != Some("INSTANCE") {
return targets;
}
// The instance and the override rows below it (rows carry the same fields, nested).
let mut pending: Vec<(&Kv<'a>, usize)> = vec![(node, 0)];
let mut rows = 0usize;
while let Some((row, depth)) = pending.pop() {
rows += 1;
if depth > MAX_DEPTH || rows > self.max_nodes {
break;
}
let data = row.get("symbolData");
targets.extend(row.get("overriddenSymbolID").and_then(guid));
targets.extend(data.and_then(|d| d.get("symbolID")).and_then(guid));
for assignment in row.get("componentPropAssignments").map(Kv::list).unwrap_or_default() {
if assignment.get("defID").is_some_and(|def| self.is_instance_swap(def).is_some()) {
targets.extend(assigned(assignment).and_then(prop_guid));
}
}
let overrides = data.and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default();
let derived = row.get("derivedSymbolData").map(Kv::list).unwrap_or_default();
pending.extend(overrides.iter().chain(derived).map(|row| (row, depth + 1)));
}
targets
}
/// The branches of the internal canvas `id` that hold the `required_mains` (with the frames
/// they sit in), as a frame of its own: the cached definitions of components that come from a
/// library. `None` when it holds none.
fn library_context(&mut self, id: &str, canvas: &'a Kv<'a>, required_mains: &BTreeSet<String>) -> Option<Value> {
let mut included = BTreeSet::new();
let mut parents: BTreeMap<String, String> = BTreeMap::new();
// The canvas itself is never a layer of the walk, whatever the parent links say.
let mut visited = BTreeSet::from([id.to_string()]);
// Each entry: layer, depth, inside a required definition.
let mut pending: Vec<(String, usize, bool)> = self.children(id).into_iter().map(|child| (child, 1, false)).collect();
while let Some((node_id, depth, in_definition)) = pending.pop() {
if depth > MAX_DEPTH {
self.warn(format!("internal library branches deeper than {MAX_DEPTH} levels were skipped"));
continue;
}
if !visited.insert(node_id.clone()) {
continue;
}
self.library_scan_count += 1;
if self.library_scan_count > self.max_nodes {
let max = self.max_nodes;
self.warn(format!("the internal library scan reached the {max}-layer limit; the remaining branches were skipped"));
break;
}
let Some(node) = self.nodes.get(&node_id) else { continue };
let kind = node.get("type").and_then(Kv::str);
let definition = (kind == Some("SYMBOL") || (kind == Some("FRAME") && node.get("isStateGroup").and_then(Kv::bool) == Some(true)))
&& required_mains.contains(&node_id);
let in_definition = in_definition || definition;
if in_definition {
included.insert(node_id.clone());
}
if definition {
// The frames around it keep the path its layers are addressed by.
let mut ancestor = parents.get(&node_id);
for _ in 0..=MAX_DEPTH {
let Some(parent) = ancestor else { break };
if !included.insert(parent.clone()) {
break;
}
ancestor = parents.get(parent);
}
}
for child in self.children(&node_id).into_iter().rev() {
// A layer reached again keeps the parent it was first reached by, so the parents
// lead back to the canvas.
if visited.contains(&child) {
continue;
}
parents.entry(child.clone()).or_insert_with(|| node_id.clone());
pending.push((child, depth + 1, in_definition));
}
}
if included.is_empty() {
return None;
}
let mut context = Obj::new();
context.insert("id".into(), json!(id));
context.insert("type".into(), json!("FRAME"));
copy_str(&mut context, &View::of(canvas), "name", "name");
context.insert("size".into(), json!({"x": 0.0, "y": 0.0}));
context.insert("relativeTransform".into(), rows(Affine::IDENTITY));
context.insert(crate::rest::FIG_SOURCE_FIELD.into(), json!({"origin": id, "expanded": false, "wireFrame": true, "wireInstance": false}));
self.variable_bindings(&mut context, &View::of(canvas));
let mut children = Vec::new();
for child in self.children(id) {
children.extend(self.layer_filtered(&child, None, Affine::IDENTITY, None, None, 0, Some(&included)));
}
if !children.is_empty() {
context.insert("children".into(), Value::Array(children));
}
Some(Value::Object(context))
}
fn page(&mut self, id: &str, n: &'a Kv<'a>) -> Value {
let v = View::of(n);
let mut o = Obj::new();
o.insert("id".into(), json!(id));
o.insert("type".into(), json!("CANVAS"));
copy_str(&mut o, &v, "name", "name");
if let Some(c) = v.get("backgroundColor") {
o.insert("backgroundColor".into(), color(c));
}
if let Some(c) = v.get("prototypeBackgroundColor") {
o.insert("prototypeBackgrounds".into(), json!([color(c)]));
}
self.variable_bindings(&mut o, &v);
let mut flows: Vec<(&str, Value)> = Vec::new();
let mut kids = Vec::new();
for c in self.children(id) {
if let Some(sp) = self.nodes.get(&c).and_then(|k| k.get("prototypeStartingPoint")) {
let name = sp.get("name").and_then(Kv::str).filter(|s| !s.is_empty()).unwrap_or("Flow");
flows.push((sp.get("position").and_then(Kv::str).unwrap_or(""), json!({"nodeId": c, "name": name})));
}
kids.extend(self.layer(&c, None, Affine::IDENTITY, None, None, 0));
}
flows.sort_by(|a, b| a.0.cmp(b.0));
if !flows.is_empty() {
o.insert("flowStartingPoints".into(), Value::Array(flows.into_iter().map(|f| f.1).collect()));
}
o.insert("children".into(), Value::Array(kids));
Value::Object(o)
}
/// The shared styles the file defines, in their order: each with the sample layer that holds
/// its values (`styleDefinitions`, our extension of the file JSON; the REST importer reads it).
pub(super) fn style_definitions(&mut self) -> Vec<Value> {
let mut found: Vec<(&'a str, String, &'a Kv<'a>)> = Vec::new();
for (id, n) in &self.nodes {
let live = n.get("isSoftDeleted").and_then(Kv::bool) != Some(true) && n.get("isSoftDeletedStyle").and_then(Kv::bool) != Some(true);
if live && n.get("styleType").and_then(Kv::str).is_some_and(|t| matches!(t, "FILL" | "TEXT" | "EFFECT" | "GRID")) {
found.push((n.get("sortPosition").and_then(Kv::str).unwrap_or(""), id.clone(), n));
}
}
found.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
let mut out = Vec::new();
for (_, id, n) in found {
let Some(node) = self.layer(&id, None, Affine::IDENTITY, None, None, 0) else { break };
let name = n.get("name").and_then(Kv::str).unwrap_or("Style");
let desc = n.get("styleDescription").or_else(|| n.get("description")).and_then(Kv::str).unwrap_or("");
let ty = n.get("styleType").and_then(Kv::str).unwrap_or("");
out.push(json!({"id": id, "name": name, "description": desc, "styleType": ty, "node": node}));
}
out
}
/// Collections and variables, as the local variables response's `meta`, with their ids in the
/// file's order (`collectionOrder` and `variableOrder`, our extensions).
pub(super) fn variables(&self) -> Option<Value> {
let of_type = |t: &'static str, key: &'static str| {
let live = move |n: &Kv| n.get("type").and_then(Kv::str) == Some(t) && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true);
let mut list: Vec<(&str, &String, &'a Kv<'a>)> = self
.nodes
.iter()
.filter(|(_, n)| live(n))
.map(|(id, n)| (n.get(key).and_then(|p| p.get("position").or(Some(p))).and_then(Kv::str).unwrap_or(""), id, *n))
.collect();
list.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
list.into_iter().map(|(_, id, n)| (id, n))
};
let mut order = Vec::new();
let mut collections = Obj::new();
// Copies of one library collection (one per version the file met) become one: the newest
// keeps its modes in its order, the others add the modes it no longer has.
let mut extra: BTreeMap<String, Vec<(String, Value)>> = BTreeMap::new();
for (id, n) in of_type("VARIABLE_SET", "parentIndex") {
let modes = sorted_modes(n);
match self.canonical_collection(id).filter(|c| c != id) {
Some(canonical) => extra.entry(canonical).or_default().extend(modes),
None => {
order.push(json!(id));
let default = modes.first().map_or(Value::Null, |m| m.1["modeId"].clone());
let name = n.get("name").and_then(Kv::str).unwrap_or("Collection");
let modes: Vec<Value> = modes.into_iter().map(|m| m.1).collect();
collections.insert(id.clone(), json!({"id": id, "name": name, "modes": modes, "defaultModeId": default}));
}
}
}
for (canonical, more) in extra {
let Some(modes) = collections.get_mut(&canonical).and_then(|c| c.get_mut("modes")).and_then(Value::as_array_mut) else { continue };
for (_, m) in more {
if !modes.iter().any(|x| x["modeId"] == m["modeId"]) {
modes.push(m);
}
}
}
let mut variable_order = Vec::new();
let mut variables = Obj::new();
for (id, n) in of_type("VARIABLE", "sortPosition") {
if super::VarCanon::superseded(id) {
continue;
}
let Some(set) = n.get("variableSetID").and_then(|s| self.collection_id(s)).filter(|s| collections.contains_key(s)) else { continue };
let ty = n.get("variableResolvedType").and_then(Kv::str).unwrap_or("");
if !matches!(ty, "BOOLEAN" | "FLOAT" | "STRING" | "COLOR") {
continue;
}
let mut values = Obj::new();
for e in n.get("variableDataValues").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() {
if let (Some(mode), Some(val)) = (e.get("modeID").and_then(guid), e.get("variableData").and_then(variable_value)) {
values.insert(mode, val);
}
}
let name = n.get("name").and_then(Kv::str).unwrap_or("Variable");
let desc = n.get("description").and_then(Kv::str).unwrap_or("");
let mut var =
json!({"id": id, "name": name, "variableCollectionId": set, "resolvedType": ty, "valuesByMode": values, "description": desc});
// The properties pickers offer the variable for, under the REST names.
if let Some(scopes) = n.get("variableScopes") {
var["scopes"] = scopes.list().iter().filter_map(Kv::str).map(|s| if s == "STROKE" { "STROKE_COLOR" } else { s }).collect();
}
variable_order.push(json!(id));
variables.insert(id.clone(), var);
}
(!collections.is_empty())
.then(|| json!({"variableCollections": collections, "variables": variables, "collectionOrder": order, "variableOrder": variable_order}))
}
}
/// A collection node's modes in their order (`sortPosition`), as `(position, {modeId, name})`.
fn sorted_modes(n: &Kv) -> Vec<(String, Value)> {
let mut modes: Vec<(String, Value)> = n
.get("variableSetModes")
.map(Kv::list)
.unwrap_or_default()
.iter()
.filter_map(|m| {
let mode = json!({"modeId": m.get("id").and_then(guid)?, "name": m.get("name").and_then(Kv::str).unwrap_or("Mode")});
Some((m.get("sortPosition").and_then(Kv::str).unwrap_or("").to_string(), mode))
})
.collect();
modes.sort_by(|a, b| a.0.cmp(&b.0));
modes
}
@@ -1,37 +0,0 @@
//! Malformed image paint filters are skipped with a warning, and image hashes too long to name
//! an image aren't spelled out.
use super::*;
#[test]
fn malformed_non_finite_filter_is_skipped_with_warning() {
let paint = Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("paintFilter", Kv::Object(vec![("exposure", Kv::Float(f32::NAN))]))]);
let mut warnings = Vec::new();
let value = super::paint(&paint, &mut |warning| warnings.push(warning)).unwrap();
assert!(value.get("filters").is_none(), "{value}");
assert!(warnings.iter().any(|warning| warning.contains("malformed image filter `exposure`")), "{warnings:?}");
}
#[test]
fn boolean_filter_values_are_malformed_even_when_false() {
for (field, value, expected_warning) in [
("exposure", Kv::Bool(true), "malformed image filter `exposure`"),
("exposure", Kv::Bool(false), "malformed image filter `exposure`"),
("mystery", Kv::Bool(false), "malformed unsupported image filter `mystery`"),
] {
let paint = Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("paintFilter", Kv::Object(vec![(field, value)]))]);
let mut warnings = Vec::new();
let value = super::paint(&paint, &mut |warning| warnings.push(warning)).unwrap();
assert!(value.get("filters").is_none(), "{value}");
assert!(warnings.iter().any(|warning| warning.contains(expected_warning)), "{warnings:?}");
}
}
#[test]
fn an_oversized_image_hash_is_not_spelled_out() {
let paint = |len: usize| Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("image", Kv::Object(vec![("hash", Kv::Bytes(vec![0xab; len]))]))]);
let image_ref = |len: usize| super::paint(&paint(len), &mut |_| {}).and_then(|p| p.get("imageRef").cloned());
assert_eq!(image_ref(20), Some(Value::String("ab".repeat(20))));
assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH), Some(Value::String("ab".repeat(crate::fig::MAX_IMAGE_HASH))));
assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH + 1), Some(Value::String(String::new())));
}
-927
View File
@@ -1,927 +0,0 @@
use super::component::{Entry, Inst, OverrideRow, prop_ref};
use super::connector::{ConnectorShape, connector_has_saved_label};
use super::layout::{layout_grid, tracks};
use super::paint::{effect, export_setting, has_bound_variables, paint, paint_bound, stroke};
use super::{
Affine, BTreeMap, BTreeSet, Kv, MAX_COMMANDS, MAX_DEPTH, Mapper, Obj, Value, View, copy_len, copy_num, copy_str, generated_record, guid, json,
matrix, network, num, rows, scaled, size,
};
/// How the layers of a resized container follow it when the file gives no derived layout for
/// them: a frame's by their constraints, from its main's size to its own; a group's scale with it.
#[derive(Clone, Copy)]
pub(super) enum Fit {
Frame { from: (f64, f64), to: (f64, f64) },
Scale(f64, f64),
}
impl Fit {
fn frame(from: Option<(f64, f64)>, to: Option<(f64, f64)>) -> Option<Self> {
let (from, to) = (from?, to?);
((from.0 - to.0).abs() > 1e-9 || (from.1 - to.1).abs() > 1e-9).then_some(Fit::Frame { from, to })
}
fn scale(from: Option<(f64, f64)>, to: Option<(f64, f64)>) -> Option<Self> {
let (from, to) = (from?, to?);
let k = |a: f64, b: f64| if a > 1e-9 { b / a } else { 1.0 };
let (kx, ky) = (k(from.0, to.0), k(from.1, to.1));
((kx - 1.0).abs() > 1e-9 || (ky - 1.0).abs() > 1e-9).then_some(Fit::Scale(kx, ky))
}
/// The size and transform (in the parent's coordinates) of a `w` × `h` layer at `t` with
/// constraints `h_con`, `v_con`. Like the editor's constraint solver, a layer keeps its
/// rotation and flip and stretches along its own axes.
fn apply(self, w: f64, h: f64, t: Affine, h_con: Option<&str>, v_con: Option<&str>) -> ((f64, f64), Affine) {
let [a, b, c, d, _, _] = t.as_coeffs();
let lin = Affine::new([a, b, c, d, 0.0, 0.0]);
let bb = figcraft_doc::geom::transform_rect_bbox(t, figcraft_doc::geom::Rect::new(0.0, 0.0, w, h));
// Where the new box goes: its top-left (constraints) or its centre (a group's scale).
let (kx, ky, x0, y0, centred) = match self {
Fit::Frame { from, to } => {
let axis = |con: Option<&str>, lo: f64, hi: f64, old: f64, new: f64| match con {
Some("MAX" | "FIXED_MAX") => (lo + new - old, hi + new - old),
Some("STRETCH") => (lo, hi + new - old),
Some("CENTER") => (lo + (new - old) / 2.0, hi + (new - old) / 2.0),
Some("SCALE") if old > 1e-9 => (lo * new / old, hi * new / old),
_ => (lo, hi),
};
let (x0, x1) = axis(h_con, bb.x0, bb.x1, from.0, to.0);
let (y0, y1) = axis(v_con, bb.y0, bb.y1, from.1, to.1);
let k = |new: f64, old: f64| if old > 1e-9 { (new / old).max(0.0) } else { 1.0 };
(k(x1 - x0, bb.width()), k(y1 - y0, bb.height()), x0, y0, false)
}
Fit::Scale(kx, ky) => (kx, ky, bb.center().x * kx, bb.center().y * ky, true),
};
let along = |x: f64, y: f64, fallback: f64| {
let len = x.hypot(y);
let k = (kx * x).hypot(ky * y) / len;
if len > 1e-12 && k.is_finite() { k } else { fallback }
};
let size = (w * along(a, b, kx), h * along(c, d, ky));
let nb = figcraft_doc::geom::transform_rect_bbox(lin, figcraft_doc::geom::Rect::new(0.0, 0.0, size.0, size.1));
let at = if centred { nb.center() } else { figcraft_doc::geom::Point::new(nb.x0, nb.y0) };
(size, Affine::translate((x0 - at.x, y0 - at.y)) * lin)
}
}
struct LayerChildren<'s, 'a> {
id: &'s str,
inst: Option<&'s Inst<'a>>,
base: &'s Kv<'a>,
child_space: Affine,
view: &'s View<'a>,
object: &'s mut Obj,
ty: &'s str,
rest_id: &'s str,
connector_snapshot: bool,
connector_terminal: bool,
depth: usize,
included: Option<&'s BTreeSet<String>>,
slot_content: Option<String>,
}
impl<'a> Mapper<'a> {
/// Layer `id` (inside instance `inst` when expanding one) and its subtree. `space`: from the
/// parent's coordinates to the enclosing frame's (groups and booleans place their children in
/// the frame's space, like the REST JSON). `parent`: the parent's view (grid tracks).
pub(crate) fn layer(
&mut self,
id: &str,
inst: Option<&Inst<'a>>,
space: Affine,
parent: Option<&View<'a>>,
fit: Option<Fit>,
depth: usize,
) -> Option<Value> {
self.layer_filtered(id, inst, space, parent, fit, depth, None)
}
/// [`Self::layer`], keeping only the layers in `included` (all when `None`) below the
/// top-level one: the cached library definitions of an internal canvas.
pub(super) fn layer_filtered(
&mut self,
id: &str,
inst: Option<&Inst<'a>>,
space: Affine,
parent: Option<&View<'a>>,
fit: Option<Fit>,
depth: usize,
included: Option<&BTreeSet<String>>,
) -> Option<Value> {
if included.is_some_and(|ids| !ids.contains(id)) {
return None;
}
if depth > MAX_DEPTH {
self.warn(format!("layers nested deeper than {MAX_DEPTH} levels were skipped"));
return None;
}
if self.count >= self.budget() {
let max = self.max_nodes;
self.warn(format!("the file has more than {max} layers; the rest were skipped"));
return None;
}
let base = *self.nodes.get(id)?;
let path = inst.map(|i| [i.path.as_slice(), &[id.to_string()]].concat());
let entries: &[OverrideRow<'a>] = match (inst, &path) {
(Some(i), Some(p)) => i.overrides.get(p).map(Vec::as_slice).unwrap_or_default(),
_ => &[],
};
// Inside a scaled instance the main's lengths are the factor times as long; the rows of
// the instance are at its scale already (#2091).
let scale = inst.map_or(1.0, |i| i.scale);
let mut view = View::of_scaled(base, scale).with(entries.iter().map(|e| (e.row, e.scale)));
// A layer of a resized instance the file gives no derived layout for follows its
// constraints from the main's geometry, then takes the size and place overridden on it
// (auto layout places the others, as in the editor).
let derived = entries.iter().any(|e| e.entry == Entry::Derived && (e.row.get("size").is_some() || e.row.get("transform").is_some()));
let stacked = parent.and_then(|p| p.str("stackMode")).is_some_and(|m| matches!(m, "HORIZONTAL" | "VERTICAL" | "GRID"))
&& view.str("stackPositioning") != Some("ABSOLUTE");
let main = View::of_scaled(base, scale);
// The size and place a row gives, at the scale of the row (a nested instance's own rows
// are at its enclosing main's scale).
let set = |k: &str| entries.iter().rev().filter(|e| e.entry != Entry::Stale).find_map(|e| e.row.get(k).map(|r| (r, e.scale)));
let set_size = || {
let (r, k) = set("size")?;
let (x, y) = size(r)?;
Some((scaled(x, k)?, scaled(y, k)?))
};
let set_transform = || {
let (r, k) = set("transform")?;
let m = matrix(r)?;
let [a, b, c, d, e, f] = m.as_coeffs();
Some(Affine::new([a, b, c, d, scaled(e, k)?, scaled(f, k)?]))
};
if let (Some(f), false, false, Some((w, h))) = (fit, derived, stacked, main.size()) {
let t = main.transform().unwrap_or_default();
let (fw, ft) = f.apply(w, h, t, view.str("horizontalConstraint"), view.str("verticalConstraint"));
view.fitted = Some((set_size().unwrap_or(fw), set_transform().unwrap_or(ft)));
} else if entries.iter().any(|e| e.entry == Entry::Stale && (e.row.get("size").is_some() || e.row.get("transform").is_some()))
&& let Some(s) = set_size().or_else(|| main.size())
{
view.fitted = Some((s, set_transform().or_else(|| main.transform()).unwrap_or_default()));
}
let rest_id = match (inst, &path) {
(Some(i), Some(p)) => format!("I{};{}", i.root, p.join(";")),
_ => id.to_string(),
};
let own = view.str("type").unwrap_or("");
let connector_snapshot = own == "CONNECTOR" && self.connector_snapshot_supported(&view);
// Only a connector with a saved label needs the frame wrapper; an unlabelled one stays a single vector.
let connector_terminal =
connector_snapshot && (!connector_has_saved_label(&view) || depth >= MAX_DEPTH || self.count.saturating_add(1) >= self.budget());
// A supported connector snapshot has its own note below instead of the generic stand-in one.
let stand = stand_in(own).filter(|_| !connector_snapshot);
// A label without a snapshot: the connector becomes a frame holding its line and its label.
let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth);
let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? };
// A whiteboard's sticky or shape with text says it imports as a frame only when it can't be a native one.
let native_board = self.board && matches!(own, "STICKY" | "SHAPE_WITH_TEXT");
if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_board) {
self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " ")));
}
if connector_snapshot {
self.warn("connector layers import as static frame/vector snapshots with labels when present; live endpoint bindings are not retained");
}
self.count += 1;
if own == "SYMBOL" && inst.is_none() {
self.mapped_mains.insert(id.to_string());
}
let mut o = Obj::new();
o.insert("id".into(), json!(rest_id));
// Private provenance for the .fig importer; ordinary REST import ignores it.
o.insert(
crate::rest::FIG_SOURCE_FIELD.into(),
json!({
"origin": id,
"expanded": inst.is_some(),
"wireFrame": own == "FRAME",
"wireInstance": own == "INSTANCE",
"slotContent": inst.is_some_and(|i| i.slot_content),
// A size the instance gives this layer itself (kept when the instance relays out).
"sizeOverride": entries.iter().any(|e| e.entry == Entry::Override && e.row.get("size").is_some()),
}),
);
o.insert("type".into(), json!(ty));
copy_str(&mut o, &view, "name", "name");
self.common(&mut o, &view, ty, space, parent);
match ty {
"TEXT" => {
self.text(&mut o, &view);
if own == "TEXT_PATH" {
self.text_path(&mut o, &view);
}
}
"VECTOR" | "STAR" | "REGULAR_POLYGON" => self.geometry(&mut o, &view),
"ELLIPSE" => {
if let Some(a) = view.get("arcData") {
let arc: Obj =
["startingAngle", "endingAngle", "innerRadius"].iter().filter_map(|k| Some((k.to_string(), json!(num(a, k)?)))).collect();
o.insert("arcData".into(), Value::Object(arc));
}
}
"BOOLEAN_OPERATION" => {
if let Some(op) = view.str("booleanOperation") {
o.insert("booleanOperation".into(), json!(if op == "XOR" { "EXCLUDE" } else { op }));
}
}
_ => {}
}
let connector_kids = if own == "CONNECTOR" {
let shape = ConnectorShape { snapshot: connector_snapshot, terminal: connector_terminal, label: connector_label };
self.connector_layer(&mut o, &view, &rest_id, space, shape)
} else {
Vec::new()
};
if ty == "COMPONENT" || ty == "COMPONENT_SET" {
self.component(&mut o, &view, &rest_id);
}
self.prop_refs(&mut o, &view, inst);
let slot_content = if own == "FRAME" {
prop_ref(&view, "SLOT_CONTENT_ID").and_then(|def| inst.and_then(|i| i.slot_contents.get(&self.prop_root(&def)).cloned()))
} else {
None
};
if slot_content.is_some()
&& let Some(source) = o.get_mut(crate::rest::FIG_SOURCE_FIELD).and_then(Value::as_object_mut)
{
source.insert("slotOverride".into(), json!(true));
}
let child_space = if matches!(ty, "GROUP" | "BOOLEAN_OPERATION") { space * view.transform().unwrap_or_default() } else { Affine::IDENTITY };
let mut kids = self.map_layer_children(LayerChildren {
id,
inst,
base,
child_space,
view: &view,
object: &mut o,
ty,
rest_id: &rest_id,
connector_snapshot,
connector_terminal,
depth,
included,
slot_content,
});
kids.splice(0..0, connector_kids);
if stand.is_some_and(|s| s.0 == "FRAME") {
let native = if native_board { self.native_board_item(own, &mut o, &view, &rest_id, depth) } else { None };
if let Some(native) = native {
kids.splice(0..0, native);
} else if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) {
kids.splice(0..0, snapshot);
} else {
kids.splice(0..0, self.shape_with_text(&mut o, &view, own, &rest_id));
kids.extend(self.inner_text(&o, &view, &rest_id, own == "STICKY"));
}
}
if !kids.is_empty() {
o.insert("children".into(), Value::Array(kids));
}
Some(Value::Object(o))
}
fn map_layer_children(&mut self, context: LayerChildren<'_, 'a>) -> Vec<Value> {
let LayerChildren {
id,
inst,
base,
child_space,
view,
object: o,
ty,
rest_id,
connector_snapshot,
connector_terminal,
depth,
included,
slot_content,
} = context;
let mut kids = if connector_snapshot && !connector_terminal { self.connector_snapshot_children(view, rest_id) } else { Vec::new() };
if connector_terminal {
// The saved vector is flattened into the connector node when no child slot remains.
} else if ty == "INSTANCE" {
if let Some((sub, sym)) = self.instance(o, view, id, inst, rest_id) {
let main = self.nodes.get(&sym).map(|m| View::of_scaled(m, sub.scale));
// A scaled main's size is the factor's product, rounded to a float: it matches an
// instance of that size without a fit that would round the layers again.
let near = |a: f64, b: f64| (a - b).abs() <= 1e-4 * a.abs().max(b.abs()).max(1.0);
let fit = match (main.as_ref().and_then(View::size), view.size()) {
(Some(a), Some(b)) if sub.scale != 1.0 && near(a.0, b.0) && near(a.1, b.1) => None,
(a, b) => Fit::frame(a, b),
};
// An instance that records no auto layout of its own has its main's.
let view = match main {
Some(m) if view.get("stackMode").is_none() && m.get("stackMode").is_some() => {
let layered = m.over(view);
self.auto_layout(o, &layered);
layered
}
_ => view.clone(),
};
for c in self.children(&sym) {
// The main's branch can live outside the cached context being mapped.
kids.extend(self.layer_filtered(&c, Some(&sub), child_space, Some(&view), fit, depth + 1, None));
}
}
} else if let Some(content) = slot_content {
let mut content_inst = inst.cloned();
if let Some(content_inst) = &mut content_inst {
content_inst.slot_content = true;
}
for c in self.children(&content) {
kids.extend(self.layer_filtered(&c, content_inst.as_ref(), child_space, Some(view), None, depth + 1, included));
}
} else {
// Inside an instance a layer's children are its main's: they follow it from the main's
// size to its own.
let fit = match (inst, ty) {
(None, _) => None,
(Some(i), "GROUP" | "BOOLEAN_OPERATION") => Fit::scale(View::of_scaled(base, i.scale).size(), view.size()),
(Some(i), _) => Fit::frame(View::of_scaled(base, i.scale).size(), view.size()),
};
for c in self.children(id) {
kids.extend(self.layer_filtered(&c, inst, child_space, Some(view), fit, depth + 1, included));
}
}
kids
}
fn mapped_type<'s>(
own: &'s str,
view: &View<'a>,
connector_snapshot: bool,
connector_terminal: bool,
stand: Option<(&'static str, &'static str)>,
) -> Option<&'s str> {
match own {
"ROUNDED_RECTANGLE" => Some("RECTANGLE"),
"SYMBOL" => Some("COMPONENT"),
"FRAME" if view.flag("isStateGroup") == Some(true) => Some("COMPONENT_SET"),
"FRAME" if view.flag("resizeToFit") == Some(true) => Some("GROUP"),
"VARIABLE" | "VARIABLE_SET" => None,
"CONNECTOR" if connector_snapshot && connector_terminal => Some("VECTOR"),
"CONNECTOR" if connector_snapshot => Some("FRAME"),
t => Some(stand.map_or(t, |s| s.0)),
}
}
/// FigJam notes and shapes keep their paints and text on generated template children,
/// not on the outer node. Keep the saved layout as ordinary editable layers (including a
/// note's author), without applying the background's opacity or transform to the wrapper.
/// When no generated body survives, retain usable outer text alongside successful children.
fn board_snapshot(&mut self, o: &mut Obj, v: &View<'a>, own: &str, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
if !matches!(own, "STICKY" | "SHAPE_WITH_TEXT") || v.get("nodeGenerationData").is_none() {
return None;
}
if v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) {
self.warn("note or shape generated layout is missing or unsupported; using its outer frame");
return None;
}
let mut children = Vec::new();
let mut has_body = false;
for local_id in 0..if own == "STICKY" { 3 } else { 2 } {
let style = generated_record(v, "nodeGenerationData", local_id);
let bounds = generated_record(v, "derivedImmutableFrameData", local_id);
let (Some(style), Some(bounds)) = (style, bounds) else {
if style.is_some() || bounds.is_some() {
self.warn("note or shape generated child is missing its style or bounds; child skipped");
}
continue;
};
let child = View::of(style).with([(bounds, 1.0)]);
let chars = own_text(&child);
if local_id != 0 && chars.is_none() {
continue;
}
if valid_size(child.get("size")).is_none() || child.transform().is_none() {
self.warn("note or shape generated child has invalid bounds; child skipped");
continue;
}
if self.count >= self.budget() || depth >= MAX_DEPTH {
self.warn("note or shape generated children exceed the layer or nesting limit; remaining children skipped");
break;
}
let mut layer = Obj::new();
let ty = if local_id == 0 { "RECTANGLE" } else { "TEXT" };
layer.insert("id".into(), json!(format!("{rest_id};generated{local_id}")));
layer.insert("type".into(), json!(ty));
layer.insert("name".into(), json!(chars.map_or_else(|| "Background".into(), |c| c.chars().take(40).collect::<String>())));
self.common(&mut layer, &child, ty, Affine::IDENTITY, None);
if local_id == 0 {
// Network decoding is only enabled for vectors; choose that type before
// geometry sees a saved network, then restore the rectangle if it is unusable.
if child.get("vectorData").is_some() {
layer.insert("type".into(), json!("VECTOR"));
}
self.geometry(&mut layer, &child);
let outlined = |layer: &Obj| ["fillGeometry", "strokeGeometry", "vectorNetworkRef"].iter().any(|key| layer.contains_key(*key));
if own == "SHAPE_WITH_TEXT" && !outlined(&layer) {
self.geometry(&mut layer, v);
}
if outlined(&layer) {
layer.insert("type".into(), json!("VECTOR"));
} else {
layer.insert("type".into(), json!("RECTANGLE"));
if own == "SHAPE_WITH_TEXT" && !matches!(v.str("shapeWithTextType"), None | Some("SQUARE" | "ROUNDED_RECTANGLE")) {
self.warn("shape generated outline is missing or damaged; using its rectangle");
}
}
o.insert("fills".into(), json!([]));
o.insert("strokes".into(), json!([]));
} else {
self.text(&mut layer, &child);
if let Some(Value::Object(style)) = layer.get_mut("style") {
style.insert("textAutoResize".into(), json!("NONE"));
}
}
self.count += 1;
has_body |= local_id == 1;
children.push(Value::Object(layer));
}
if depth < MAX_DEPTH && !has_body {
children.extend(self.inner_text(o, v, rest_id, own == "STICKY"));
}
Some(children)
}
/// A non-rectangular shape-with-text's shape, as a vector under its frame (which gives up its
/// paints to it).
fn shape_with_text(&mut self, o: &mut Obj, v: &View<'a>, own: &str, rest_id: &str) -> Option<Value> {
let shape = v.str("shapeWithTextType").unwrap_or("SQUARE");
let outlined = !v.list("fillGeometry").is_empty() || !v.list("strokeGeometry").is_empty();
if own != "SHAPE_WITH_TEXT" || matches!(shape, "SQUARE" | "ROUNDED_RECTANGLE") || !outlined || self.count >= self.budget() {
return None;
}
let mut s = Obj::new();
s.insert("id".into(), json!(format!("{rest_id};shape")));
s.insert("type".into(), json!("VECTOR"));
s.insert("name".into(), json!(shape.to_ascii_lowercase().replace('_', " ")));
for k in ["size", "strokeWeight", "strokeAlign", "strokeJoin", "strokeDashes"] {
if let Some(x) = o.get(k) {
s.insert(k.into(), x.clone());
}
}
for k in ["fills", "strokes"] {
s.insert(k.into(), o.insert(k.into(), json!([])).unwrap_or_else(|| json!([])));
}
s.insert("relativeTransform".into(), rows(Affine::IDENTITY));
self.geometry(&mut s, v);
if !s.contains_key("fillGeometry") && !s.contains_key("strokeGeometry") {
// Damaged outlines: the frame keeps its paints and box.
for k in ["fills", "strokes"] {
o.insert(k.into(), s.remove(k).unwrap_or_else(|| json!([])));
}
return None;
}
self.count += 1;
Some(Value::Object(s))
}
/// The text a stand-in frame holds (a sticky note's, a shape's, a table cell's) as a text
/// layer filling it, inset a little; centred unless it's a note.
fn inner_text(&mut self, o: &Obj, v: &View<'a>, rest_id: &str, note: bool) -> Option<Value> {
let chars = own_text(v)?;
if self.count >= self.budget() {
return None;
}
self.count += 1;
let size = |k: &str| o.get("size").and_then(|s| s.get(k)).and_then(Value::as_f64).unwrap_or(0.0);
let (w, h) = (size("x"), size("y"));
let pad = (w.min(h) / 4.0).clamp(0.0, 16.0);
let mut t = Obj::new();
t.insert("id".into(), json!(format!("{rest_id};text")));
t.insert("type".into(), json!("TEXT"));
t.insert("name".into(), json!(chars.chars().take(40).collect::<String>()));
t.insert("size".into(), json!({"x": (w - 2.0 * pad).max(1.0), "y": (h - 2.0 * pad).max(1.0)}));
t.insert("relativeTransform".into(), rows(Affine::translate((pad, pad))));
self.text(&mut t, v);
if let Some(Value::Object(st)) = t.get_mut("style") {
let (hor, ver) = if note { ("LEFT", "TOP") } else { ("CENTER", "CENTER") };
st.entry("textAlignHorizontal").or_insert_with(|| json!(hor));
st.entry("textAlignVertical").or_insert_with(|| json!(ver));
st.insert("textAutoResize".into(), json!("NONE"));
}
Some(Value::Object(t))
}
/// Fields every layer type shares.
pub(super) fn common(&mut self, o: &mut Obj, v: &View<'a>, ty: &str, space: Affine, parent: Option<&View<'a>>) {
for (from, to) in [("visible", "visible"), ("locked", "locked"), ("mask", "isMask")] {
if let Some(b) = v.flag(from) {
o.insert(to.into(), json!(b));
}
}
if let Some(m) = v.str("maskType") {
o.insert("maskType".into(), json!(if m == "OUTLINE" { "VECTOR" } else { m }));
}
copy_num(o, v, "opacity", "opacity");
if let Some(b) = v.str("blendMode").filter(|b| *b != "UNSET") {
o.insert("blendMode".into(), json!(b));
}
if let Some((x, y)) = v.size() {
o.insert("size".into(), json!({"x": x, "y": y}));
}
let t = v.transform().unwrap_or_default();
o.insert("relativeTransform".into(), rows(space * t));
// Paints, from the shared style when one is linked (the layer's own copy can be stale),
// unless the layer's own paints are bound to variables: those bindings must not be lost.
let mut styles = Obj::new();
let own = |k: &str| Some(v.list(k)).filter(|l| l.iter().any(paint_bound));
let fill_style = self.style(v, "styleIdForFill", "inheritFillStyleID", "fill", &mut styles);
let fills = own("fillPaints")
.unwrap_or_else(|| fill_style.map_or_else(|| v.list("fillPaints"), |s| s.get("fillPaints").map(Kv::list).unwrap_or_default()));
o.insert("fills".into(), Value::Array(fills.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect()));
let stroke_style = self.style(v, "styleIdForStrokeFill", "inheritFillStyleIDForStroke", "stroke", &mut styles);
let strokes = own("strokePaints")
.unwrap_or_else(|| stroke_style.map_or_else(|| v.list("strokePaints"), |s| s.get("fillPaints").map(Kv::list).unwrap_or_default()));
o.insert("strokes".into(), Value::Array(strokes.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect()));
let effect_style = self.style(v, "styleIdForEffect", "inheritEffectStyleID", "effect", &mut styles);
let (effects, effects_scale) =
effect_style.map_or_else(|| v.list_scaled("effects"), |s| v.styled_list(s, "effects", "styleIdForEffect", "inheritEffectStyleID"));
if !effects.is_empty() {
o.insert("effects".into(), Value::Array(effects.iter().filter_map(|e| effect(e, effects_scale)).collect()));
}
let grid_style = self.style(v, "styleIdForGrid", "inheritGridStyleID", "grid", &mut styles);
let (grids, grids_scale) =
grid_style.map_or_else(|| v.list_scaled("layoutGrids"), |s| v.styled_list(s, "layoutGrids", "styleIdForGrid", "inheritGridStyleID"));
if !grids.is_empty() {
o.insert("layoutGrids".into(), Value::Array(grids.iter().map(|g| layout_grid(g, grids_scale)).collect()));
}
if ty == "TEXT" {
self.style(v, "styleIdForText", "inheritTextStyleID", "text", &mut styles);
}
if !styles.is_empty() {
o.insert("styles".into(), Value::Object(styles));
}
stroke(o, v);
copy_len(o, v, "cornerRadius", "cornerRadius");
copy_num(o, v, "cornerSmoothing", "cornerSmoothing");
if v.flag("rectangleCornerRadiiIndependent") == Some(true) {
let r = |k: &str| v.len(k).unwrap_or(0.0);
o.insert(
"rectangleCornerRadii".into(),
json!([
r("rectangleTopLeftCornerRadius"),
r("rectangleTopRightCornerRadius"),
r("rectangleBottomRightCornerRadius"),
r("rectangleBottomLeftCornerRadius")
]),
);
}
let constraint = |k: &str, min: &'static str, max: &'static str, both: &'static str| match v.str(k) {
Some("CENTER") => "CENTER",
Some("MAX" | "FIXED_MAX") => max,
Some("STRETCH") => both,
Some("SCALE") => "SCALE",
_ => min,
};
o.insert(
"constraints".into(),
json!({
"horizontal": constraint("horizontalConstraint", "LEFT", "RIGHT", "LEFT_RIGHT"),
"vertical": constraint("verticalConstraint", "TOP", "BOTTOM", "TOP_BOTTOM"),
}),
);
if matches!(ty, "FRAME" | "COMPONENT" | "COMPONENT_SET" | "INSTANCE" | "SECTION") {
o.insert("clipsContent".into(), json!(!v.flag("frameMaskDisabled").unwrap_or(false)));
self.auto_layout(o, v);
}
child_layout(o, v, parent);
let exports: Vec<Value> = v.list("exportSettings").iter().map(export_setting).collect();
if !exports.is_empty() {
o.insert("exportSettings".into(), Value::Array(exports));
}
if let Some(b) = v.flag("sectionContentsHidden") {
o.insert("sectionContentsHidden".into(), json!(b));
}
self.prototype(o, v);
self.variable_bindings(o, v);
}
/// `fillGeometry` / `strokeGeometry` as SVG path data, and star/polygon parameters.
pub(super) fn geometry(&mut self, o: &mut Obj, v: &View<'a>) {
for key in ["fillGeometry", "strokeGeometry"] {
let mut out = Vec::new();
for p in v.list(key) {
let Some(blob) = num(p, "commandsBlob").and_then(|i| self.blobs.get(i as usize)).copied() else { continue };
let Some(d) = svg_path(blob) else {
self.warn("damaged vector geometry was skipped");
continue;
};
if d.is_empty() {
continue;
}
let winding = if p.get("windingRule").and_then(Kv::str) == Some("ODD") { "EVENODD" } else { "NONZERO" };
out.push(json!({"path": d, "windingRule": winding}));
}
if !out.is_empty() {
o.insert(key.into(), Value::Array(out));
}
}
let vector = o.get("type").and_then(Value::as_str) == Some("VECTOR");
if vector && !self.network(o, v) && !o.contains_key("fillGeometry") && !o.contains_key("strokeGeometry") && v.str("type") != Some("CONNECTOR")
{
self.warn("vectors without geometry are empty");
}
if !vector {
copy_num(o, v, "count", "pointCount");
copy_num(o, v, "starInnerScale", "innerRadius");
}
}
/// The editable network of `vectorData` as `vectorNetwork` (the REST importer's extension),
/// scaled to the layer's size, with per-point corner radii, handle mirroring and end caps.
/// False when there's none or it's damaged (the outlines stand in).
fn network(&mut self, o: &mut Obj, v: &View<'a>) -> bool {
let Some((vd, radius_scale)) = v.find("vectorData") else { return false };
let Some(blob_id) = num(vd, "vectorNetworkBlob").map(|i| i as usize) else { return false };
let Some(blob) = self.blobs.get(blob_id).copied() else { return false };
let Some(net) = network::decode(blob) else {
self.warn("damaged vector networks import as outlines");
return false;
};
let styles: BTreeMap<u64, &Kv> =
vd.get("styleOverrideTable").map(Kv::list).unwrap_or_default().iter().filter_map(|s| Some((num(s, "styleID")? as u64, s))).collect();
let mut has_uninterpreted = false;
let mut has_missing = false;
for segment in &net.segments {
if segment.style == 0 {
continue;
}
if styles.contains_key(&u64::from(segment.style)) {
has_uninterpreted = true;
} else {
has_missing = true;
}
}
if has_uninterpreted {
self.warn("style settings of some vector segments aren't supported; those segments use the layer's stroke");
}
if has_missing {
self.warn("some vector segments refer to style settings missing from the file; they use the layer's stroke");
}
// An open path shows its fill, which regions can't hold: the outline keeps the look.
let fills_shown =
o.get("fills").and_then(Value::as_array).is_some_and(|f| f.iter().any(|p| p.get("visible").and_then(Value::as_bool) != Some(false)));
if net.segments.is_empty() || (net.regions.is_empty() && fills_shown && o.contains_key("fillGeometry")) {
return false;
}
let style = |id: u32| styles.get(&u64::from(id)).copied().filter(|_| id != 0);
let scale = |k: &str| {
let size = v.size().map(|s| if k == "x" { s.0 } else { s.1 });
let norm = vd.get("normalizedSize").and_then(|s| num(s, k));
size.zip(norm).filter(|(s, n)| s.is_finite() && *n > 1e-9).map_or(1.0, |(s, n)| s / n)
};
let (sx, sy) = (scale("x"), scale("y"));
// A point whose style doesn't set a radius takes the layer's, as the editor draws it.
let layer_radius = v.len("cornerRadius");
let vertices: Vec<Value> = net
.vertices
.iter()
.map(|p| {
let mut out = json!({"x": p.x * sx, "y": p.y * sy});
let st = style(p.style);
// Point radii are lengths in this row's space, unlike the normalized positions.
// An override/derived row already carries the instance's scale.
if let Some(r) = st.and_then(|s| num(s, "cornerRadius")).and_then(|r| scaled(r, radius_scale)).or(layer_radius).filter(|r| *r > 0.0) {
out["radius"] = json!(r);
}
match st.and_then(|s| s.get("handleMirroring")).and_then(Kv::str) {
Some("ANGLE") => out["mirror"] = json!("angle"),
Some("ANGLE_AND_LENGTH") => out["mirror"] = json!("angleAndLength"),
Some("NONE") => out["mirror"] = json!("none"),
_ => {}
}
if let Some(join @ ("MITER" | "BEVEL" | "ROUND")) = st.and_then(|s| s.get("strokeJoin")).and_then(Kv::str) {
out["join"] = json!(join.to_ascii_lowercase());
}
out
})
.collect();
let segments: Vec<Value> =
net.segments.iter().map(|s| json!({"a": s.a, "b": s.b, "ta": [s.ta.0 * sx, s.ta.1 * sy], "tb": [s.tb.0 * sx, s.tb.1 * sy]})).collect();
let regions: Vec<Value> = net
.regions
.iter()
.map(|r| {
let mut region = json!({"loops": r.loops, "winding": if r.non_zero { "nonZero" } else { "evenOdd" }});
if r.style != 0 {
match style(r.style) {
Some(s) => {
let fills = s.get("fillPaints").and_then(|own_fills| {
if own_fills.list().iter().any(paint_bound) {
return Some(own_fills);
}
let linked_style = self
.style_link(&View::of(s), "styleIdForFill", "inheritFillStyleID")
.and_then(|id| self.nodes.get(&id).copied())
.filter(|style| style.get("styleType").and_then(Kv::str) == Some("FILL"));
match linked_style {
Some(style) => style.get("fillPaints"),
None => Some(own_fills),
}
});
if let Some(fills) = fills {
if let Kv::Array(source_paints) = fills {
let paint_cost = source_paints.iter().fold(source_paints.len(), |cost, paint| {
cost.saturating_add(paint.get("stops").map(Kv::list).unwrap_or_default().len())
});
let oversized_stops =
source_paints.iter().any(|paint| paint.get("stops").map(Kv::list).unwrap_or_default().len() > 256);
if source_paints.len() > 256 || oversized_stops || self.region_paint_elements.saturating_add(paint_cost) > 200_000
{
self.warn("vector region paint data exceeded import limits and was skipped");
return region;
}
self.region_paint_elements += paint_cost;
let paints: Vec<Value> = source_paints.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect();
if paints.len() != source_paints.len() {
self.warn("invalid vector region paints were skipped");
}
if paints.iter().any(has_bound_variables) {
self.warn("variable-bound vector region paints keep resolved appearance; live bindings were left out");
}
if s.get("styleIdForFill").is_some() {
self.warn("linked vector region fill styles keep resolved appearance; live style links were left out");
}
region["_figRegionFills"] = Value::Array(paints);
} else {
self.warn("invalid vector region fill paint list; layer fill used");
}
}
}
None => self.warn("vector region references a missing fill style; layer fill used"),
}
}
region
})
.collect();
// An absent layer join is the source default.
let layer_join = v.str("strokeJoin").unwrap_or("MITER");
let point_join = |p: &network::Vertex| style(p.style).and_then(|s| s.get("strokeJoin"));
let known = |j: &str| matches!(j, "MITER" | "BEVEL" | "ROUND");
let unresolved_style = net.vertices.iter().any(|p| p.style != 0 && style(p.style).is_none());
let unknown_join = net.vertices.iter().any(|p| point_join(p).is_some_and(|j| !j.str().is_some_and(known)));
let unsupported_join = net.vertices.iter().any(|p| point_join(p).and_then(Kv::str).is_some_and(|j| known(j) && j != layer_join));
if unresolved_style {
self.warn("some vector points refer to point settings missing from the file; they use the layer's joins and plain corners");
}
if unknown_join {
self.warn("vector points with unknown stroke joins use the layer join");
}
if unsupported_join && (o.contains_key("strokeDashes") || o.contains_key("strokeWidthProfile")) {
self.warn("point stroke joins were preserved; dashed or variable-width strokes render with the layer join");
}
// The stroke starts at the first end point and stops at the last (as the editor draws it).
let mut degree = vec![0usize; net.vertices.len()];
for s in &net.segments {
for i in [s.a, s.b] {
if let Some(d) = degree.get_mut(i) {
*d += 1;
}
}
}
let ends: Vec<usize> = (0..degree.len()).filter(|i| degree.get(*i) == Some(&1)).collect();
let cap =
|i: Option<&usize>| i.and_then(|i| net.vertices.get(*i)).and_then(|p| style(p.style)).and_then(|s| s.get("strokeCap")).and_then(Kv::str);
let (first, last) = (cap(ends.first()), cap(ends.last()));
if first.is_some() || last.is_some() {
let node = v.str("strokeCap").unwrap_or("NONE");
o.insert("strokeCapStart".into(), json!(cap_name(first.unwrap_or(node))));
o.insert("strokeCapEnd".into(), json!(cap_name(last.unwrap_or(node))));
}
// Every instance of a main shows the same network: it is written once and shared.
let mut entry = json!({});
entry["vertices"] = Value::Array(vertices);
entry["segments"] = Value::Array(segments);
entry["regions"] = Value::Array(regions.clone());
if regions.iter().any(|r| r.get("_figRegionFills").is_some()) {
o.insert("vectorNetwork".into(), entry);
return true;
}
// A resized instance and a K-scaled one can have the same box but different radii.
let key =
(blob_id, sx.to_bits(), sy.to_bits(), std::ptr::from_ref(vd) as usize, radius_scale.to_bits(), layer_radius.unwrap_or(0.0).to_bits());
let id = match self.network_ids.get(&key) {
Some(id) => *id,
None => {
self.networks.push(crate::rest::network(&entry));
self.network_ids.insert(key, self.networks.len() - 1);
self.networks.len() - 1
}
};
o.insert("vectorNetworkRef".into(), json!(id));
true
}
}
/// The text a layer that isn't a text layer carries (a note's, a shape's), unless blank.
pub(super) fn own_text<'a>(v: &View<'a>) -> Option<&'a str> {
v.get("textData").and_then(|t| t.get("characters")).and_then(Kv::str).filter(|c| !c.trim().is_empty())
}
pub(super) fn valid_size(value: Option<&Kv<'_>>) -> Option<(f64, f64)> {
let x = num(value?, "x")?;
let y = num(value?, "y")?;
(x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0).then_some((x, y))
}
/// The REST name of a stroke cap.
pub(super) fn cap_name(cap: &str) -> &str {
match cap {
"ARROW_LINES" => "LINE_ARROW",
"ARROW_EQUILATERAL" => "TRIANGLE_ARROW",
c => c,
}
}
/// The layer kind (and how the warning names it) that a layer the editor has no counterpart for
/// imports as: frames for notes, shapes, tables, slides and the like (their text as a text layer),
/// vectors for connectors and marker strokes, plain text for text on a path.
fn stand_in(ty: &str) -> Option<(&'static str, &'static str)> {
Some(match ty {
"STICKY"
| "SHAPE_WITH_TEXT"
| "CODE_BLOCK"
| "TABLE"
| "TABLE_CELL"
| "STAMP"
| "MEDIA"
| "WIDGET"
| "SLIDE"
| "SLIDE_GRID"
| "SLIDE_ROW"
| "INTERACTIVE_SLIDE_ELEMENT"
| "MODULE" => ("FRAME", "frames with their text"),
"CONNECTOR" | "HIGHLIGHT" | "WASHI_TAPE" => ("VECTOR", "vectors"),
"TEXT_PATH" => ("TEXT", "text off its path"),
_ => return None,
})
}
/// How a layer sizes and sits in an auto layout parent.
fn child_layout(o: &mut Obj, v: &View, parent: Option<&View>) {
copy_num(o, v, "stackChildPrimaryGrow", "layoutGrow");
if v.str("stackChildAlignSelf") == Some("STRETCH") {
o.insert("layoutAlign".into(), json!("STRETCH"));
}
if v.str("stackPositioning") == Some("ABSOLUTE") {
o.insert("layoutPositioning".into(), json!("ABSOLUTE"));
}
for (k, w, h) in [("minSize", "minWidth", "minHeight"), ("maxSize", "maxWidth", "maxHeight")] {
if let Some((val, scale)) = v.find(k).and_then(|(s, scale)| Some((s.get("value")?, scale))) {
for (axis, to) in [("x", w), ("y", h)] {
if let Some(x) = num(val, axis).and_then(|x| scaled(x, scale)).filter(|x| *x > 0.0 && *x < 1e9) {
o.insert(to.into(), json!(x));
}
}
}
}
if let Some(p) = parent.filter(|p| p.str("stackMode") == Some("GRID")) {
for (anchor, list, to) in [("gridColumnAnchor", "gridColumns", "gridColumnAnchorIndex"), ("gridRowAnchor", "gridRows", "gridRowAnchorIndex")]
{
if let Some(i) = v.get(anchor).and_then(guid).and_then(|g| tracks(p, list).iter().position(|t| *t == g)) {
o.insert(to.into(), json!(i));
}
}
copy_num(o, v, "gridColumnSpan", "gridColumnSpan");
copy_num(o, v, "gridRowSpan", "gridRowSpan");
}
}
/// SVG path data of a geometry blob: commands `0` close, `1` move, `2` line, `3` quadratic and
/// `4` cubic, each followed by its points as little-endian `f32` pairs. `None` when damaged.
pub(super) fn svg_path(b: &[u8]) -> Option<String> {
let mut out = String::new();
let mut i = 0usize;
let mut n = 0usize;
while i < b.len() {
n += 1;
if n > MAX_COMMANDS {
return None;
}
let (letter, points) = match *b.get(i)? {
0 => ('Z', 0),
1 => ('M', 1),
2 => ('L', 1),
3 => ('Q', 2),
4 => ('C', 3),
_ => return None,
};
i += 1;
if !out.is_empty() {
out.push(' ');
}
out.push(letter);
for _ in 0..points * 2 {
let bytes: [u8; 4] = b.get(i..i + 4)?.try_into().ok()?;
let x = f32::from_le_bytes(bytes);
if !x.is_finite() {
return None;
}
out.push_str(&format!(" {x}"));
i += 4;
}
}
Some(out)
}
-190
View File
@@ -1,190 +0,0 @@
use super::paint::{bound, color};
use super::{BTreeMap, BTreeSet, Kv, MAX_GRID_TRACK_VALUE, MAX_GRID_TRACKS, Mapper, Obj, Value, View, copy_len, guid, json, num, scaled};
impl<'a> Mapper<'a> {
pub(super) fn auto_layout(&mut self, o: &mut Obj, v: &View<'a>) {
let Some(mode) = v.str("stackMode").filter(|m| matches!(*m, "HORIZONTAL" | "VERTICAL" | "GRID")) else { return };
o.insert("layoutMode".into(), json!(mode));
copy_len(o, v, "stackSpacing", "itemSpacing");
copy_len(o, v, "stackCounterSpacing", "counterAxisSpacing");
if v.str("stackWrap") == Some("WRAP") {
o.insert("layoutWrap".into(), json!("WRAP"));
}
if v.str("stackCounterAlignContent") == Some("SPACE_BETWEEN") {
o.insert("counterAxisAlignContent".into(), json!("SPACE_BETWEEN"));
}
let (h, vert) = (v.len("stackHorizontalPadding").unwrap_or(0.0), v.len("stackVerticalPadding").unwrap_or(0.0));
o.insert("paddingLeft".into(), json!(h));
o.insert("paddingTop".into(), json!(vert));
o.insert("paddingRight".into(), json!(v.len("stackPaddingRight").unwrap_or(h)));
o.insert("paddingBottom".into(), json!(v.len("stackPaddingBottom").unwrap_or(vert)));
let main = match v.str("stackPrimaryAlignItems").or_else(|| v.str("stackJustify")) {
Some("CENTER") => "CENTER",
Some("MAX") => "MAX",
Some("SPACE_AROUND") => "SPACE_AROUND",
// `SPACE_EVENLY` is the format's older name for equal gaps without edge space.
Some("SPACE_EVENLY_CSS") => "SPACE_EVENLY",
Some("SPACE_BETWEEN" | "SPACE_EVENLY") => "SPACE_BETWEEN",
_ => "MIN",
};
o.insert("primaryAxisAlignItems".into(), json!(main));
let cross = match v.str("stackCounterAlignItems").or_else(|| v.str("stackAlign")) {
Some("CENTER") => "CENTER",
Some("MAX") => "MAX",
Some("BASELINE") => "BASELINE",
_ => "MIN",
};
o.insert("counterAxisAlignItems".into(), json!(cross));
let sizing = |k: &str| if v.str(k).is_some_and(|s| s.starts_with("RESIZE_TO_FIT")) { "AUTO" } else { "FIXED" };
// A flow that records no sizing for its primary axis sizes it by its content: auto layout
// did before that axis could be fixed.
let primary = if v.get("stackPrimarySizing").is_none() && mode != "GRID" { "AUTO" } else { sizing("stackPrimarySizing") };
o.insert("primaryAxisSizingMode".into(), json!(primary));
o.insert("counterAxisSizingMode".into(), json!(sizing("stackCounterSizing")));
if let Some(b) = v.flag("bordersTakeSpace") {
o.insert("strokesIncludedInLayout".into(), json!(b));
}
if let Some(b) = v.flag("stackReverseZIndex") {
o.insert("itemReverseZIndex".into(), json!(b));
}
if mode == "GRID" {
copy_len(o, v, "gridColumnGap", "gridColumnGap");
copy_len(o, v, "gridRowGap", "gridRowGap");
o.insert("gridColumnCount".into(), json!(tracks(v, "gridColumns").len()));
o.insert("gridRowCount".into(), json!(tracks(v, "gridRows").len()));
let track_data = [("columnTracks", "gridColumns", "gridColumnsSizing"), ("rowTracks", "gridRows", "gridRowsSizing")]
.into_iter()
.filter_map(|(out_key, order_key, sizing_key)| {
self.map_grid_tracks(v, order_key, sizing_key).map(|mapped| (out_key.to_string(), mapped))
})
.collect::<Obj>();
if !track_data.is_empty() {
let source = o.entry(crate::rest::FIG_SOURCE_FIELD).or_insert_with(|| json!({}));
if let Some(source) = source.as_object_mut() {
source.insert("gridTracks".into(), Value::Object(track_data));
}
}
}
}
/// Track sizing maps are keyed by GUID; their order comes from the separate track list.
fn map_grid_tracks(&mut self, v: &View<'a>, order_key: &str, sizing_key: &str) -> Option<Value> {
let track_entries = v.get(order_key).and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default();
let sizes = v.get(sizing_key).and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default();
if track_entries.len() > MAX_GRID_TRACKS {
self.warn("grid track list exceeds 1000 entries; the tracks use the default equal sizing");
return None;
}
if sizes.is_empty() {
return None;
}
if sizes.len() > MAX_GRID_TRACKS {
self.warn("grid track sizing list exceeds 1000 entries; the tracks use the default equal sizing");
return None;
}
let ordered = tracks(v, order_key);
let ordered_ids: BTreeSet<&str> = ordered.iter().map(String::as_str).collect();
let mut size_by_id: BTreeMap<String, Option<&Kv<'a>>> = BTreeMap::new();
for entry in sizes {
let Some(id) = entry.get("id").and_then(guid) else {
self.warn("stale or invalid grid track sizing entries were ignored");
continue;
};
if !ordered_ids.contains(id.as_str()) {
self.warn("stale or invalid grid track sizing entries were ignored");
continue;
}
match size_by_id.entry(id) {
std::collections::btree_map::Entry::Vacant(slot) => {
slot.insert(Some(entry));
}
std::collections::btree_map::Entry::Occupied(mut slot) => {
slot.insert(None);
self.warn("duplicate grid track sizing entries use equal tracks");
}
}
}
let mut mapped = Vec::with_capacity(ordered.len());
for id in ordered {
if let Some(Some(entry)) = size_by_id.get(&id) {
match grid_track_sizing(entry.get("trackSize")) {
Some(track) => mapped.push(track),
None => {
self.warn("grid track sizing is unsupported or malformed; affected tracks use equal sizing");
mapped.push(json!({"sizing": "fill", "value": 1.0}));
}
}
} else {
mapped.push(json!({"sizing": "fill", "value": 1.0}));
}
}
Some(Value::Array(mapped))
}
}
/// The track ids of a grid's columns or rows, in order.
pub(super) fn tracks(v: &View, key: &str) -> Vec<String> {
let mut t: Vec<(&str, String)> = v
.get(key)
.and_then(|m| m.get("entries"))
.map(Kv::list)
.unwrap_or_default()
.iter()
.filter_map(|e| Some((e.get("position").and_then(Kv::str).unwrap_or(""), e.get("id").and_then(guid)?)))
.collect();
t.sort();
t.into_iter().map(|e| e.1).collect()
}
/// Convert only unconstrained tracks, whose min and max sizing functions agree.
fn grid_track_sizing(size: Option<&Kv<'_>>) -> Option<Value> {
let size = size?;
let min = size.get("minSizing")?;
let max = size.get("maxSizing")?;
let min_type = min.get("type").and_then(Kv::str)?;
let max_type = max.get("type").and_then(Kv::str)?;
if min_type != max_type {
return None;
}
match min_type {
"FIXED" => {
let px = num(min, "value")?;
let max_px = num(max, "value")?;
(px == max_px && px.is_finite() && (0.0..=MAX_GRID_TRACK_VALUE).contains(&px)).then(|| json!({"sizing": "fixed", "value": px}))
}
"FLEX" => {
let fr = num(min, "value")?;
let max_fr = num(max, "value")?;
(fr == max_fr && fr.is_finite() && fr > 0.0 && fr <= MAX_GRID_TRACK_VALUE).then(|| json!({"sizing": "fill", "value": fr}))
}
"HUG" => Some(json!({"sizing": "hug", "value": 0.0})),
_ => None,
}
}
/// A layout grid; `k`: the factor its lengths take (a scaled instance's layer).
pub(super) fn layout_grid(g: &Kv, k: f64) -> Value {
let pattern = match (g.get("pattern").and_then(Kv::str), g.get("axis").and_then(Kv::str)) {
(Some("GRID"), _) => "GRID",
(_, Some("Y")) => "ROWS",
_ => "COLUMNS",
};
let mut o = json!({"pattern": pattern, "alignment": g.get("type").and_then(Kv::str).unwrap_or("STRETCH")});
for (from, to) in [("sectionSize", "sectionSize"), ("numSections", "count"), ("gutterSize", "gutterSize"), ("offset", "offset")] {
let length = from != "numSections";
if let Some(x) = num(g, from).and_then(|x| scaled(x, if length { k } else { 1.0 })) {
o[to] = json!(x);
}
}
if let Some(c) = g.get("color") {
o["color"] = color(c);
}
if let Some(b) = g.get("visible").and_then(Kv::bool) {
o["visible"] = json!(b);
}
let vars = [("numSectionsVar", "count"), ("offsetVar", "offset"), ("sectionSizeVar", "sectionSize"), ("gutterSizeVar", "gutterSize")];
if let Some(b) = bound(Some(g), &vars) {
o["boundVariables"] = b;
}
o
}
-337
View File
@@ -1,337 +0,0 @@
use super::layer::cap_name;
use super::variables::alias;
use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, copy_len, copy_str, guid, json, matrix, num, rows, scaled, vec2};
fn filter_number(value: &Kv) -> Option<f64> {
let number = match value {
Kv::Float(value) => f64::from(*value),
Kv::Int(value) => *value as f64,
Kv::Uint(value) => *value as f64,
_ => return None,
};
number.is_finite().then_some(number)
}
pub(super) fn color(c: &Kv) -> Value {
let ch = |k: &str| num(c, k).unwrap_or(0.0);
json!({"r": ch("r"), "g": ch("g"), "b": ch("b"), "a": num(c, "a").unwrap_or(1.0)})
}
impl<'a> Mapper<'a> {
/// The style a layer links in `key`, by guid or by library asset (the file's copy of a library
/// style), or in the older `legacy` field when `key` names none. An explicit NO_STYLE guid in
/// `key` with no asset is a detach and wins over the legacy field.
pub(super) fn style_link(&self, v: &View, key: &str, legacy: &str) -> Option<String> {
let fallback = || v.get(legacy).and_then(guid).filter(|g| g != NO_STYLE);
let Some(link) = v.get(key) else { return fallback() };
match (self.resource_id(link), link.get("guid").and_then(guid)) {
(Some(id), _) => Some(id),
(None, Some(_)) => None,
(None, None) => fallback(),
}
}
/// The style node a layer links in `key` (or the older `legacy` field), recorded for the REST
/// `styles` map under `slot`.
/// A link to a style the file doesn't hold leaves the layer its own values (the colours it
/// stored with it), with a note.
pub(super) fn style(&mut self, v: &View<'a>, key: &str, legacy: &str, slot: &str, out: &mut Obj) -> Option<&'a Kv<'a>> {
let found = self.style_link(v, key, legacy).and_then(|id| Some((self.nodes.get(&id).copied()?, id)));
let Some((node, id)) = found.filter(|(n, _)| n.get("styleType").and_then(Kv::str).is_some()) else {
let named = |l: &Kv| l.get("assetRef").is_some() || l.get("guid").and_then(guid).is_some_and(|g| g != NO_STYLE);
if v.get(key).is_some_and(named) || v.get(legacy).and_then(guid).is_some_and(|g| g != NO_STYLE) {
self.warn("links to shared styles that aren't in the file kept the layers' own values");
}
return None;
};
out.insert(slot.into(), json!(id));
if !self.styles.contains_key(&id) {
let name = node.get("name").and_then(Kv::str).unwrap_or("Style");
let desc = node.get("styleDescription").or_else(|| node.get("description")).and_then(Kv::str).unwrap_or("");
self.styles.insert(id, json!({"name": name, "description": desc}));
}
Some(node)
}
}
pub(super) fn stroke(o: &mut Obj, v: &View) {
copy_len(o, v, "strokeWeight", "strokeWeight");
if let Some(a) = v.str("strokeAlign").filter(|a| *a != "OFFSET") {
o.insert("strokeAlign".into(), json!(a));
}
copy_str(o, v, "strokeJoin", "strokeJoin");
if let Some(cap) = v.str("strokeCap") {
o.insert("strokeCap".into(), json!(cap_name(cap)));
}
// A layer written as the outline of its stroke keeps what it was as plugin data
// (`outlinedStroke`, our extension of the file JSON).
let (id, key) = crate::fig::export::STASH;
let kept = v.list("pluginData").iter().find(|p| p.get("pluginID").and_then(Kv::str) == Some(id) && p.get("key").and_then(Kv::str) == Some(key));
if let Some(original) = kept.and_then(|p| p.get("value")).and_then(Kv::str).and_then(|s| serde_json::from_str::<Value>(s).ok()) {
o.insert("outlinedStroke".into(), original);
}
// A variable width: each point's reach on the two sides of the path (shares of the stroke
// weight), as `[t, scale, bias]` (`strokeWidthProfile`, our extension of the file JSON).
let profile: Vec<Value> = v
.list("variableWidthPoints")
.iter()
.filter_map(|p| {
let (left, right) = (num(p, "ascent")?.max(0.0), num(p, "descent")?.max(0.0));
let bias = if left + right > 0.0 { (right - left) / (left + right) } else { 0.0 };
Some(json!([num(p, "position")?, left + right, bias]))
})
.collect();
if !profile.is_empty() {
o.insert("strokeWidthProfile".into(), Value::Array(profile));
}
let (dash_list, dash_scale) = v.list_scaled("dashPattern");
let dashes: Vec<f64> = dash_list.iter().filter_map(Kv::f64).filter_map(|d| scaled(d, dash_scale)).collect();
if !dashes.is_empty() {
o.insert("strokeDashes".into(), json!(dashes));
}
// A miter limit L bevels joins sharper than 2·asin(1/L).
if let Some(l) = v.num("miterLimit").filter(|l| *l > 1.0) {
o.insert("strokeMiterAngle".into(), json!((2.0 * (1.0 / l).asin()).to_degrees()));
}
if v.flag("borderStrokeWeightsIndependent") == Some(true) {
// A side that isn't written has no border.
let side = |k: &str| v.len(k).unwrap_or(0.0);
o.insert(
"individualStrokeWeights".into(),
json!({"top": side("borderTopWeight"), "right": side("borderRightWeight"), "bottom": side("borderBottomWeight"), "left": side("borderLeftWeight")}),
);
}
}
/// Whether a paint's colour or one of its gradient stops is bound to a variable.
pub(super) fn paint_bound(p: &Kv) -> bool {
alias(p.get("colorVar")).is_some() || p.get("stopsVar").map(Kv::list).unwrap_or_default().iter().any(|s| alias(s.get("colorVar")).is_some())
}
pub(crate) fn paint(p: &Kv, warn: &mut dyn FnMut(String)) -> Option<Value> {
let ty = p.get("type").and_then(Kv::str)?;
let mut o = Obj::new();
o.insert("type".into(), json!(ty));
if let Some(x) = num(p, "opacity") {
o.insert("opacity".into(), json!(x));
}
if let Some(b) = p.get("visible").and_then(Kv::bool) {
o.insert("visible".into(), json!(b));
}
if let Some(b) = p.get("blendMode").and_then(Kv::str) {
o.insert("blendMode".into(), json!(b));
}
let t = p.get("transform").and_then(matrix);
match ty {
"SOLID" => {
if let Some(c) = p.get("color") {
o.insert("color".into(), color(c));
}
if let Some(var) = alias(p.get("colorVar")) {
o.insert("boundVariables".into(), json!({"color": {"type": "VARIABLE_ALIAS", "id": var}}));
}
}
_ if ty.starts_with("GRADIENT_") => {
// The paint transform maps the layer's unit box to gradient space, where a linear
// gradient runs from (0, ½) to (1, ½) and the others are centred on (½, ½).
let inv = t.filter(|t| t.determinant().abs() > 1e-12).map_or(Affine::IDENTITY, Affine::inverse);
let pts = if ty == "GRADIENT_LINEAR" { [(0.0, 0.5), (1.0, 0.5), (0.0, 1.0)] } else { [(0.5, 0.5), (1.0, 0.5), (0.5, 1.0)] };
let handles: Vec<Value> = pts
.iter()
.map(|(x, y)| {
let q = inv * Point::new(*x, *y);
json!({"x": q.x, "y": q.y})
})
.collect();
o.insert("gradientHandlePositions".into(), Value::Array(handles));
// Stops bound to variables are listed again, each with its variable.
let vars = p.get("stopsVar").map(Kv::list).unwrap_or_default();
let stops: Vec<Value> = p
.get("stops")
.map(Kv::list)
.unwrap_or_default()
.iter()
.enumerate()
.map(|(i, s)| {
let mut stop = json!({"position": num(s, "position").unwrap_or(0.0), "color": s.get("color").map_or(Value::Null, color)});
if let Some(b) = bound(vars.get(i), &[("colorVar", "color")]) {
stop["boundVariables"] = b;
}
stop
})
.collect();
o.insert("gradientStops".into(), Value::Array(stops));
}
"IMAGE" => {
// A hash longer than any the file's images can be named by resolves to nothing: it
// isn't spelled out, which a shared style would repeat for every layer using it.
let hash: String = p
.get("image")
.and_then(|i| i.get("hash"))
.and_then(Kv::bytes)
.filter(|h| h.len() <= crate::fig::MAX_IMAGE_HASH)
.unwrap_or_default()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
o.insert("imageRef".into(), json!(hash));
let mode = p.get("imageScaleMode").and_then(Kv::str).unwrap_or("FILL");
o.insert("scaleMode".into(), json!(mode));
if let (Some(t), "STRETCH") = (t, mode) {
o.insert("imageTransform".into(), rows(t));
}
if let Some(s) = num(p, "scale") {
o.insert("scalingFactor".into(), json!(s));
}
if let Some(r) = num(p, "rotation") {
o.insert("rotation".into(), json!(r));
}
match (p.get("filterColorAdjust"), p.get("paintFilter")) {
(Some(_), Some(_)) => {
warn("image filters are ambiguous because both filter containers are present; filter conversion was skipped".into())
}
(Some(_), None) => warn("legacy image filter container is unsupported; filter conversion was skipped".into()),
(None, Some(filters)) => {
let mut mapped = Obj::new();
let fields = [
("exposure", "exposure"),
("contrast", "contrast"),
("vibrance", "saturation"),
("temperature", "temperature"),
("tint", "tint"),
("highlights", "highlights"),
("shadows", "shadows"),
];
if let Kv::Object(values) = filters {
for (source, target) in fields {
if let Some(value) = filters.get(source) {
match filter_number(value) {
Some(value) => {
mapped.insert(target.into(), json!(value));
}
None => warn(format!("malformed image filter `{source}` was skipped")),
}
}
}
for (name, value) in values {
if fields.iter().any(|(known, _)| *known == *name) {
continue;
}
match filter_number(value) {
Some(0.0) => {}
Some(_) => warn(format!("nonzero unsupported image filter `{}` was skipped", crate::rest::props::clip_str(name))),
None => warn(format!("malformed unsupported image filter `{}` was skipped", crate::rest::props::clip_str(name))),
}
}
} else {
warn("malformed image paintFilter container was skipped".into());
}
if !mapped.is_empty() {
o.insert("filters".into(), Value::Object(mapped));
}
}
(None, None) => {}
}
}
_ => {}
}
Some(Value::Object(o))
}
pub(super) fn has_bound_variables(value: &Value) -> bool {
match value {
Value::Object(object) => object.contains_key("boundVariables") || object.values().any(has_bound_variables),
Value::Array(values) => values.iter().any(has_bound_variables),
_ => false,
}
}
/// The variables bound to the fields of a paint stop, an effect or a layout grid, as its REST
/// `boundVariables`: `fields` pairs the format's field with the REST name.
pub(super) fn bound(v: Option<&Kv>, fields: &[(&str, &str)]) -> Option<Value> {
let v = v?;
let found: Obj =
fields.iter().filter_map(|(from, to)| Some((to.to_string(), json!({"type": "VARIABLE_ALIAS", "id": alias(v.get(from))?})))).collect();
(!found.is_empty()).then_some(Value::Object(found))
}
/// A layer effect; `k`: the factor its lengths take (a scaled instance's layer).
pub(super) fn effect(e: &Kv, k: f64) -> Option<Value> {
let ty = match e.get("type").and_then(Kv::str)? {
"FOREGROUND_BLUR" => "LAYER_BLUR",
"GRAIN" => "TEXTURE",
t => t,
};
let mut o = Obj::new();
o.insert("type".into(), json!(ty));
for key in ["radius", "spread", "startRadius", "density", "opacity"] {
let length = matches!(key, "radius" | "spread" | "startRadius");
if let Some(x) = num(e, key).and_then(|x| scaled(x, if length { k } else { 1.0 })) {
o.insert(key.into(), json!(x));
}
}
for k in ["visible", "showShadowBehindNode", "clipToShape"] {
if let Some(b) = e.get(k).and_then(Kv::bool) {
o.insert(k.into(), json!(b));
}
}
for k in ["blendMode", "noiseType"] {
if let Some(s) = e.get(k).and_then(Kv::str) {
o.insert(k.into(), json!(s));
}
}
for k in ["color", "secondaryColor"] {
if let Some(c) = e.get(k) {
o.insert(k.into(), color(c));
}
}
// `startOffset` and `endOffset` are positions in the layer's unit box, not lengths: they stay.
for (from, to) in [("offset", "offset"), ("noiseSize", "noiseSizeVector")] {
if let Some(p) = e.get(from).and_then(vec2) {
o.insert(to.into(), scale_vec2(p, k));
}
}
for key in ["startOffset", "endOffset"] {
if let Some(p) = e.get(key).and_then(vec2) {
o.insert(key.into(), p);
}
}
if e.get("blurOpType").and_then(Kv::str) == Some("PROGRESSIVE") {
o.insert("blurType".into(), json!("PROGRESSIVE"));
}
let vars = [
("colorVar", "color"),
("radiusVar", "radius"),
("spreadVar", "spread"),
("xVar", "offsetX"),
("yVar", "offsetY"),
("startRadiusVar", "startRadius"),
];
if let Some(b) = bound(Some(e), &vars) {
o.insert("boundVariables".into(), b);
}
Some(Value::Object(o))
}
/// A `{"x", "y"}` vector at scale `k` (unchanged when that is not finite).
fn scale_vec2(p: Value, k: f64) -> Value {
let axis = |name: &str| p.get(name).and_then(Value::as_f64).and_then(|x| scaled(x, k));
match (axis("x"), axis("y")) {
(Some(x), Some(y)) => json!({"x": x, "y": y}),
_ => p,
}
}
pub(super) fn export_setting(e: &Kv) -> Value {
let c = e.get("constraint");
let ty = match c.and_then(|c| c.get("type")).and_then(Kv::str) {
Some("CONTENT_WIDTH") => "WIDTH",
Some("CONTENT_HEIGHT") => "HEIGHT",
_ => "SCALE",
};
json!({
"format": e.get("imageType").and_then(Kv::str).unwrap_or("PNG"),
"suffix": e.get("suffix").and_then(Kv::str).unwrap_or(""),
"constraint": {"type": ty, "value": c.and_then(|c| num(c, "value")).unwrap_or(1.0)},
})
}
-179
View File
@@ -1,179 +0,0 @@
use super::paint::color;
use super::variables::variable_data;
use super::{Kv, MAX_ACTION_DEPTH, Mapper, Obj, Value, View, copy_str, guid, json, num, ref_guid};
impl<'a> Mapper<'a> {
pub(super) fn prototype(&mut self, o: &mut Obj, v: &View<'a>) {
let mut list = Vec::new();
for it in v.list("prototypeInteractions") {
if it.get("isDeleted").and_then(Kv::bool) == Some(true) {
continue;
}
if let Some(i) = self.interaction(it) {
list.push(i);
}
}
if !list.is_empty() {
o.insert("interactions".into(), Value::Array(list));
}
let overflow = match v.str("scrollDirection") {
Some("HORIZONTAL") => Some("HORIZONTAL_SCROLLING"),
Some("VERTICAL") => Some("VERTICAL_SCROLLING"),
Some("BOTH") => Some("HORIZONTAL_AND_VERTICAL_SCROLLING"),
_ => None,
};
if let Some(d) = overflow {
o.insert("overflowDirection".into(), json!(d));
}
let behavior = match v.str("scrollBehavior") {
Some("FIXED_WHEN_CHILD_OF_SCROLLING_FRAME") => Some("FIXED"),
Some("STICKY_SCROLLS") => Some("STICKY_SCROLLS"),
_ => None,
};
if let Some(b) = behavior {
o.insert("scrollBehavior".into(), json!(b));
}
copy_str(o, v, "overlayPositionType", "overlayPositionType");
copy_str(o, v, "overlayBackgroundInteraction", "overlayBackgroundInteraction");
if let Some(a) = v.get("overlayBackgroundAppearance") {
let ty = a.get("backgroundType").and_then(Kv::str).unwrap_or("NONE");
o.insert("overlayBackground".into(), json!({"type": ty, "color": a.get("backgroundColor").map_or(Value::Null, color)}));
}
}
fn interaction(&mut self, it: &Kv) -> Option<Value> {
let ev = it.get("event");
let ty = match ev.and_then(|e| e.get("interactionType")).and_then(Kv::str).unwrap_or("ON_CLICK") {
"DRAG" => "ON_DRAG",
"MOUSE_IN" => "MOUSE_ENTER",
"MOUSE_OUT" => "MOUSE_LEAVE",
t => t,
};
let mut trigger = json!({"type": ty});
if let Some(t) = ev.and_then(|e| num(e, "transitionTimeout")) {
// Seconds as 32-bit floats: whole milliseconds.
trigger["timeout"] = json!((t * 1000.0).round());
}
if let Some(k) = ev.and_then(|e| e.get("keyTrigger")) {
let codes: Vec<f64> = k.get("keyCodes").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).collect();
trigger["keyCodes"] = json!(codes);
if let Some(d) = k.get("triggerDevice").and_then(Kv::str) {
trigger["device"] = json!(if d.contains("KEYBOARD") { "KEYBOARD" } else { d });
}
}
let actions: Vec<Value> = it.get("actions").map(Kv::list).unwrap_or_default().iter().filter_map(|a| self.action(a, 0)).collect();
(!actions.is_empty()).then(|| json!({"trigger": trigger, "actions": actions}))
}
/// One prototype action in the REST shape (`depth`: conditionals it's nested in).
fn action(&mut self, a: &Kv, depth: usize) -> Option<Value> {
Some(match a.get("connectionType").and_then(Kv::str) {
Some("INTERNAL_NODE") | None => {
let dest = a.get("transitionNodeID").and_then(guid)?;
let nav = match a.get("navigationType").and_then(Kv::str) {
Some("SWAP_STATE") => "CHANGE_TO",
Some(n) => n,
None => "NAVIGATE",
};
let mut act = json!({"type": "NODE", "destinationId": dest, "navigation": nav});
if let Some(t) = transition(a) {
act["transition"] = t;
}
if let Some(b) = a.get("transitionPreserveScroll").and_then(Kv::bool) {
act["preserveScrollPosition"] = json!(b);
}
if let Some(p) = a.get("overlayRelativePosition") {
act["overlayRelativePosition"] = json!({"x": num(p, "x"), "y": num(p, "y")});
}
act
}
Some("URL") => json!({"type": "URL", "url": a.get("connectionURL").and_then(Kv::str)?}),
Some("BACK") => json!({"type": "BACK"}),
Some("CLOSE") => json!({"type": "CLOSE"}),
Some("NONE") => return None,
Some("SET_VARIABLE") => {
let var = a.get("targetVariable").and_then(|t| t.get("id")).and_then(ref_guid).or_else(|| a.get("targetVariableID").and_then(guid));
// Missing parts are left out: the REST importer skips the action with a warning.
let mut act = json!({"type": "SET_VARIABLE", "variableId": var});
if let Some(d) = a.get("targetVariableData").and_then(|d| variable_data(d, 0)) {
act["variableValue"] = d;
}
act
}
Some("SET_VARIABLE_MODE") => json!({
"type": "SET_VARIABLE_MODE",
"variableCollectionId": a.get("targetVariableSetID").and_then(ref_guid),
"variableModeId": a.get("targetVariableModeID").and_then(guid),
}),
Some("CONDITIONAL") if depth < MAX_ACTION_DEPTH => {
let mut blocks = Vec::new();
for b in a.get("conditionalActions").map(Kv::list).unwrap_or_default() {
let actions: Vec<Value> =
b.get("actions").map(Kv::list).unwrap_or_default().iter().filter_map(|x| self.action(x, depth + 1)).collect();
let mut block = json!({"actions": actions});
// A condition that can't be read must not turn the block into an "else".
if let Some(c) = b.get("condition") {
block["condition"] = variable_data(c, 0).unwrap_or_else(|| json!({}));
}
blocks.push(block);
}
json!({"type": "CONDITIONAL", "conditionalBlocks": blocks})
}
Some(other) => {
self.warn(format!("{} prototype actions are not imported from .fig files yet", other.to_ascii_lowercase().replace('_', " ")));
return None;
}
})
}
}
/// A prototype action's transition (`None`: instant).
fn transition(a: &Kv) -> Option<Value> {
let ty = a.get("transitionType").and_then(Kv::str)?;
// Directions name where the incoming screen moves (SLIDE_FROM_LEFT moves right).
let (kind, dir) = match ty {
"INSTANT_TRANSITION" => return None,
"DISSOLVE" | "FADE" => ("DISSOLVE", None),
"SMART_ANIMATE" | "MAGIC_MOVE" => ("SMART_ANIMATE", None),
"SCROLL_ANIMATE" => ("SCROLL_ANIMATE", None),
t => {
let prefixes = [
("SLIDE_FROM_", "SLIDE_IN"),
("PUSH_FROM_", "PUSH"),
("MOVE_FROM_", "MOVE_IN"),
("SLIDE_OUT_TO_", "SLIDE_OUT"),
("MOVE_OUT_TO_", "MOVE_OUT"),
];
let (kind, side) = prefixes.iter().find_map(|(p, k)| t.strip_prefix(p).map(|r| (*k, r)))?;
let incoming = matches!(kind, "SLIDE_IN" | "PUSH" | "MOVE_IN");
let dir = match (side, incoming) {
("LEFT", true) | ("RIGHT", false) => "RIGHT",
("RIGHT", true) | ("LEFT", false) => "LEFT",
("TOP", true) | ("BOTTOM", false) => "BOTTOM",
_ => "TOP",
};
(kind, Some(dir))
}
};
let easing = match a.get("easingType").and_then(Kv::str) {
Some("IN_CUBIC" | "EASE_IN") => "EASE_IN",
Some("INOUT_CUBIC") => "EASE_IN_AND_OUT",
Some("LINEAR") => "LINEAR",
Some("IN_BACK_CUBIC") => "EASE_IN_BACK",
Some("OUT_BACK_CUBIC") => "EASE_OUT_BACK",
Some("INOUT_BACK_CUBIC") => "EASE_IN_AND_OUT_BACK",
Some("GENTLE_SPRING") => "GENTLE",
Some("CUSTOM_CUBIC") => "CUSTOM_CUBIC_BEZIER",
_ => "EASE_OUT",
};
let mut e = json!({"type": easing});
let f: Vec<f64> = a.get("easingFunction").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).collect();
if let (true, [x1, y1, x2, y2, ..]) = (easing == "CUSTOM_CUBIC_BEZIER", f.as_slice()) {
e["easingFunctionCubicBezier"] = json!({"x1": x1, "y1": y1, "x2": x2, "y2": y2});
}
let mut t = json!({"type": kind, "duration": (num(a, "transitionDuration").unwrap_or(0.3) * 1000.0).round(), "easing": e});
if let Some(d) = dir {
t["direction"] = json!(d);
}
Some(t)
}
-323
View File
@@ -1,323 +0,0 @@
use super::paint::paint;
use super::{Kv, Mapper, Obj, Value, View, copy_len, copy_str, json, network, num, scaled};
/// The value from the last override layer holding a valid one for an optional text setting; invalid instance rows fall through.
/// `length`: the setting is a length, at the scale of the layer that has it.
fn text_num(v: &View, key: &str, length: bool) -> Option<f64> {
v.layers.iter().zip(&v.scales).rev().find_map(|(layer, k)| {
layer.get(key).and_then(|value| match value {
Kv::Bool(_) => None,
_ => scaled(value.f64()?, if length { *k } else { 1.0 }),
})
})
}
fn text_flag(v: &View, key: &str) -> Option<bool> {
v.layers.iter().rev().find_map(|layer| layer.get(key).and_then(Kv::bool))
}
fn insert_text_options(style: &mut Obj, v: &View) {
if let Some(value) = text_num(v, "listSpacing", true) {
style.insert("listSpacing".into(), json!(value));
}
for k in ["hangingList", "hangingPunctuation"] {
if let Some(value) = text_flag(v, k) {
style.insert(k.into(), json!(value));
}
}
if let Some(value) = leading_trim(v) {
style.insert("leadingTrim".into(), json!(value));
}
}
fn leading_trim<'a>(v: &View<'a>) -> Option<&'a str> {
v.layers.iter().rev().find_map(|layer| match layer.get("leadingTrim").and_then(Kv::str) {
Some(value @ ("NONE" | "CAP_HEIGHT")) => Some(value),
_ => None,
})
}
/// The chars that start a wrapped line in the layout the file saved with the text
/// (`derivedTextData`'s `baselines`, each line's `firstCharacter` in UTF-16 units), when that layout
/// is for these characters; lines after a hard break are left out (empty: it wraps nowhere). None
/// when the saved layout is missing, for other text or inconsistent.
fn saved_line_starts(v: &View, chars: &str) -> Option<Vec<usize>> {
// Derived data from below the layer that set the characters was laid out for other text.
let top = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some());
if top("derivedTextData")? < top("textData")? {
return None;
}
let baselines = v.get("derivedTextData")?.get("baselines")?.list();
// UTF-16 offset of each char, and of the end.
let mut offsets: Vec<usize> = Vec::with_capacity(chars.len() + 1);
let mut unit = 0;
for c in chars.chars() {
offsets.push(unit);
unit += c.len_utf16();
}
offsets.push(unit);
let list: Vec<char> = chars.chars().collect();
let mut starts = Vec::new();
let mut prev = None;
for b in baselines {
let u = num(b, "firstCharacter").filter(|u| *u >= 0.0 && u.fract() == 0.0 && *u < unit as f64)? as usize;
let c = offsets.binary_search(&u).ok()?;
// Lines start at the first char, then further on each time.
if !prev.map_or(c == 0, |p| c > p) {
return None;
}
prev = Some(c);
if c > 0 && !list.get(c - 1).is_some_and(|ch| matches!(ch, '\n' | '\u{2028}')) {
starts.push(c);
}
}
prev.map(|_| starts)
}
impl<'a> Mapper<'a> {
pub(super) fn text(&mut self, o: &mut Obj, v: &View<'a>) {
let (key, legacy) = ("styleIdForText", "inheritTextStyleID");
let style_node = self.style_link(v, key, legacy).and_then(|s| self.nodes.get(&s).copied());
// Overrides above the one that links the style beat it; it beats the copies below.
let sv = v.styled(style_node.filter(|s| s.get("styleType").and_then(Kv::str) == Some("TEXT")), key, legacy);
let found = v.find("textData");
let (td, td_scale) = (found.map(|f| f.0), found.map_or(1.0, |f| f.1));
let chars = td.and_then(|t| t.get("characters")).and_then(Kv::str).unwrap_or("");
o.insert("characters".into(), json!(chars));
// Where the file's own layout wrapped the lines (not a REST field).
if let Some(starts) = saved_line_starts(v, chars) {
o.insert("_figLineStarts".into(), json!(starts));
}
let mut style = text_style(&sv, None);
// The style's typography beats the layer's own copy of it (the copy is stale when the style
// changed). The file cannot tell a stale copy of these four values from a deliberate local
// one, and "original", "none" and 0 could never be set locally if the style always won, so
// a value the layer or an override sets itself is taken as deliberate.
if let Some(decoration @ ("NONE" | "UNDERLINE" | "STRIKETHROUGH")) = v.str("textDecoration") {
style.insert("textDecoration".into(), json!(decoration));
}
if let Some(skip_ink) = v.flag("textDecorationSkipInk") {
style.insert("textDecorationSkipInk".into(), json!(skip_ink));
}
if let Some(case @ ("ORIGINAL" | "UPPER" | "LOWER" | "TITLE" | "SMALL_CAPS" | "SMALL_CAPS_FORCED")) = v.str("textCase") {
style.insert("textCase".into(), json!(case));
}
for k in ["textAlignHorizontal", "textAlignVertical", "textAutoResize", "textTruncation"] {
copy_str(&mut style, v, k, k);
}
// Paragraph settings belong to the effective text layer, including explicit zero clears.
for k in ["paragraphSpacing", "paragraphIndent"] {
copy_len(&mut style, v, k, k);
}
insert_text_options(&mut style, v);
if let Some(n) = v.num("maxLines").filter(|n| *n >= 1.0) {
style.insert("maxLines".into(), json!(n));
}
let size = sv.len("fontSize");
if let Some(b) = o.get_mut("style").and_then(|s| s.get_mut("boundVariables")).map(Value::take) {
style.insert("boundVariables".into(), b);
}
o.insert("style".into(), Value::Object(style));
let Some(td) = td else { return };
char_styles(o, td, td_scale, size, &mut |w| self.warn(w));
let raw = td.get("lines").map(Kv::list).unwrap_or_default();
let lines: Vec<&str> = raw
.iter()
.map(|l| match l.get("lineType").and_then(Kv::str) {
Some("ORDERED_LIST") => "ORDERED",
Some("UNORDERED_LIST") => "UNORDERED",
_ => "NONE",
})
.collect();
if lines.iter().any(|l| *l != "NONE") {
o.insert("lineTypes".into(), json!(lines));
}
// A forced base direction per paragraph (`sourceDirectionality`; not a REST field).
let dirs: Vec<&str> = raw
.iter()
.map(|l| match l.get("sourceDirectionality").and_then(Kv::str) {
Some("LTR") => "LTR",
Some("RTL") => "RTL",
_ => "AUTO",
})
.collect();
if dirs.iter().any(|d| *d != "AUTO") {
o.insert("lineDirections".into(), json!(dirs));
}
// Where a numbered list starts counting, less one (not a REST field).
let starts: Vec<u32> =
raw.iter().map(|l| num(l, "listStartOffset").filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32)).collect();
if starts.iter().any(|n| *n > 0) {
o.insert("listStartOffsets".into(), json!(starts));
}
}
/// Carry supported text-path data through the private .fig REST ingress only.
pub(super) fn text_path(&mut self, o: &mut Obj, v: &View<'a>) {
let fail = |this: &mut Self, reason: &str| {
this.warn(format!("text path {reason}; text imports off its path"));
};
let Some(start) = v.get("textPathStart") else {
fail(self, "has no start data");
return;
};
let (Some(t), Some(forward)) = (num(start, "tValue"), start.get("forward").and_then(Kv::bool)) else {
fail(self, "has invalid start data");
return;
};
let Some(vd) = v.get("vectorData") else {
fail(self, "has no vector data");
return;
};
let Some(blob) = num(vd, "vectorNetworkBlob")
.filter(|i| i.is_finite() && *i >= 0.0 && i.fract() == 0.0)
.and_then(|i| usize::try_from(i as u64).ok())
.and_then(|i| self.blobs.get(i))
.copied()
else {
fail(self, "has no vector network");
return;
};
let Some(net) = network::decode(blob) else {
fail(self, "has damaged vector data");
return;
};
let Some(norm) = vd.get("normalizedSize") else {
fail(self, "has invalid normalized size");
return;
};
let (Some(nx), Some(ny), Some((w, h))) = (num(norm, "x"), num(norm, "y"), v.size()) else {
fail(self, "has invalid dimensions");
return;
};
let axis_scale = |size: f64, normalized: f64, values: &[f64]| -> Option<f64> {
if !size.is_finite() || size < 0.0 || !normalized.is_finite() || normalized < 0.0 {
return None;
}
if normalized > 1e-9 {
if size <= 0.0 {
return None;
}
return Some(size / normalized);
}
(size == 0.0 && values.iter().all(|v| *v == 0.0)).then_some(1.0)
};
let xs: Vec<f64> = net.vertices.iter().map(|p| p.x).chain(net.segments.iter().flat_map(|s| [s.ta.0, s.tb.0])).collect();
let ys: Vec<f64> = net.vertices.iter().map(|p| p.y).chain(net.segments.iter().flat_map(|s| [s.ta.1, s.tb.1])).collect();
let sx = axis_scale(w, nx, &xs);
let sy = axis_scale(h, ny, &ys);
let (Some(sx), Some(sy)) = (sx, sy) else {
fail(self, "has invalid path scale");
return;
};
if v.str("textAlignVertical").is_some_and(|x| x != "TOP") {
fail(self, "uses unsupported vertical placement");
return;
}
if v.get("textData").and_then(|td| td.get("characters")).and_then(Kv::str).is_some_and(|s| s.chars().any(|c| matches!(c, '\n' | '\r'))) {
fail(self, "contains multiple lines");
return;
}
let path = match crate::fig::text_path::from_network(&net, sx, sy, t, forward) {
Ok(path) => path,
Err(reason) => {
fail(self, reason);
return;
}
};
let has_decoration = |style: &Value| style.get("textDecoration").and_then(Value::as_str).is_some_and(|x| x != "NONE");
let decorated = o.get("style").is_some_and(has_decoration)
|| o.get("styleOverrideTable").and_then(Value::as_object).into_iter().flat_map(|styles| styles.values()).any(has_decoration);
if decorated {
self.warn("text path underline or strikethrough decoration is not rendered");
}
o.insert("_figTextPath".into(), json!({"d": path.d, "start": path.start, "flip": path.flip}));
}
}
/// Per-character styles of text data `td` (`characterStyleIDs` + `styleOverrideTable`) as REST
/// `characterStyleOverrides` + `styleOverrideTable`; `scale`: the factor the lengths of `td` take
/// (a scaled instance's layer); `size`: the base font size.
pub(super) fn char_styles(o: &mut Obj, td: &Kv, scale: f64, size: Option<f64>, warn: &mut dyn FnMut(String)) {
let ids: Vec<u64> = td.get("characterStyleIDs").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).map(|i| i as u64).collect();
if ids.iter().all(|i| *i == 0) {
return;
}
let mut table = Obj::new();
for e in td.get("styleOverrideTable").map(Kv::list).unwrap_or_default() {
let Some(sid) = num(e, "styleID") else { continue };
let mut s = text_style(&View::of_scaled(e, scale), size);
if let Some(fills) = e.get("fillPaints") {
s.insert("fills".into(), Value::Array(fills.list().iter().filter_map(|p| paint(p, warn)).collect()));
}
table.insert((sid as u64).to_string(), Value::Object(s));
}
o.insert("characterStyleOverrides".into(), json!(ids));
o.insert("styleOverrideTable".into(), Value::Object(table));
}
/// The REST TypeStyle fields a node (or text override entry) sets. `size`: the font size that
/// letter spacing in percent refers to when the entry doesn't set one.
fn text_style(v: &View, size: Option<f64>) -> Obj {
let mut s = Obj::new();
if let Some(f) = v.get("fontName") {
for (from, to) in [("family", "fontFamily"), ("style", "fontStyle"), ("postscript", "fontPostScriptName")] {
if let Some(x) = f.get(from).and_then(Kv::str).filter(|x| !x.is_empty()) {
// Compact and spaced style names ("SemiBold", "Semi Bold") are the same style.
s.insert(to.into(), if from == "style" { json!(crate::fig::style_name(x)) } else { json!(x) });
}
}
}
copy_len(&mut s, v, "fontSize", "fontSize");
copy_len(&mut s, v, "paragraphSpacing", "paragraphSpacing");
copy_len(&mut s, v, "paragraphIndent", "paragraphIndent");
insert_text_options(&mut s, v);
copy_str(&mut s, v, "textCase", "textCase");
copy_str(&mut s, v, "textDecoration", "textDecoration");
if let Some(skip_ink) = v.flag("textDecorationSkipInk") {
s.insert("textDecorationSkipInk".into(), json!(skip_ink));
}
copy_str(&mut s, v, "leadingTrim", "leadingTrim");
let font_size = v.len("fontSize").or(size).unwrap_or(12.0);
if let Some((ls, k)) = v.find("letterSpacing") {
let val = num(ls, "value").unwrap_or(0.0);
let px = match ls.get("units").and_then(Kv::str) {
Some("PIXELS") => scaled(val, k).unwrap_or(val),
Some("PERCENT") => {
// Private (read by `rest/text.rs`): REST spacing is in pixels; keep the percent.
s.insert("_letterSpacingPercent".into(), json!(val));
val / 100.0 * font_size
}
_ => val * font_size,
};
s.insert("letterSpacing".into(), json!(px));
}
if let Some((lh, k)) = v.find("lineHeight") {
let val = num(lh, "value").unwrap_or(100.0);
match lh.get("units").and_then(Kv::str) {
Some("PIXELS") => {
s.insert("lineHeightUnit".into(), json!("PIXELS"));
s.insert("lineHeightPx".into(), json!(scaled(val, k).unwrap_or(val)));
}
// shortcut: percent units count from the font's own line height (100 % is "auto"), which
// the document can only say for 100 %; other values read as % of the font size. Upgrade
// when line heights can be a share of the font's own.
Some("PERCENT") if (val - 100.0).abs() < 1e-6 => {
s.insert("lineHeightUnit".into(), json!("INTRINSIC_%"));
}
Some("PERCENT") => {
s.insert("lineHeightUnit".into(), json!("FONT_SIZE_%"));
s.insert("lineHeightPercentFontSize".into(), json!(val));
}
_ => {
s.insert("lineHeightUnit".into(), json!("FONT_SIZE_%"));
s.insert("lineHeightPercentFontSize".into(), json!(val * 100.0));
}
}
}
// An empty URL is kept: on an override entry it clears the text's own link.
if let Some(u) = v.get("hyperlink").and_then(|h| h.get("url")).and_then(Kv::str) {
s.insert("hyperlink".into(), json!({"type": "URL", "url": u}));
}
s
}
-168
View File
@@ -1,168 +0,0 @@
use super::paint::color;
use super::{Kv, MAX_EXPR_DEPTH, Mapper, Obj, Value, View, guid, json, num, ref_guid};
impl<'a> Mapper<'a> {
/// Layer `v`'s variable bindings (`boundVariables`, and the text style's) and its explicitly
/// set modes (`explicitVariableModes`) into `o`, in the REST shape. Variables and collections
/// named by library asset resolve to their newest copy in the file.
pub(super) fn variable_bindings(&mut self, o: &mut Obj, v: &View<'a>) {
let mut bound = Obj::new();
let mut text_bound = Obj::new();
for e in v.get("variableConsumptionMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() {
let Some(var) = alias(e.get("variableData")) else { continue };
let a = json!({"type": "VARIABLE_ALIAS", "id": var});
let field = e.get("variableField").and_then(Kv::str).unwrap_or("");
match (binding_key(field), text_binding_key(field)) {
(Some(k), _) => {
bound.insert(k.into(), a);
}
(_, Some(k)) => {
text_bound.insert(k.into(), a);
}
_ if field == "CORNER_RADIUS" => {
for k in ["topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius"] {
bound.insert(k.into(), a.clone());
}
}
_ if field.starts_with("BORDER_") => {
let side = match field {
"BORDER_TOP_WEIGHT" => "strokeTopWeight",
"BORDER_RIGHT_WEIGHT" => "strokeRightWeight",
"BORDER_BOTTOM_WEIGHT" => "strokeBottomWeight",
_ => "strokeLeftWeight",
};
bound.insert(side.into(), a);
}
_ if field == "WIDTH" || field == "HEIGHT" => {
let axis = if field == "WIDTH" { "x" } else { "y" };
let size = bound.entry("size").or_insert_with(|| json!({}));
size[axis] = a;
}
_ => self.warn(format!("variables bound to {} are not imported from .fig files yet", field.to_ascii_lowercase().replace('_', " "))),
}
}
if !bound.is_empty() {
o.insert("boundVariables".into(), Value::Object(bound));
}
// (The text style itself is added after this: it keeps these.)
if !text_bound.is_empty() {
o.insert("style".into(), json!({"boundVariables": text_bound}));
}
let mut modes = Obj::new();
let mut lost = false;
for e in v.get("variableModeBySetMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() {
let (Some(set), Some(mode)) = (e.get("variableSetID"), e.get("variableModeID").and_then(guid)) else { continue };
match self.collection_id(set) {
Some(id) => {
modes.insert(id, json!(mode));
}
// A mode of a collection neither named by guid nor resolvable in the file.
None if set.get("guid").is_some() || set.get("assetRef").is_some() => lost = true,
None => {}
}
}
if lost {
self.warn("variable modes of collections that aren't in the file were skipped");
}
if !modes.is_empty() {
o.insert("explicitVariableModes".into(), Value::Object(modes));
}
}
}
/// The REST `boundVariables` key of a bound layer field.
fn binding_key(field: &str) -> Option<&'static str> {
Some(match field {
"STROKE_WEIGHT" => "strokeWeight",
"STACK_SPACING" => "itemSpacing",
"STACK_COUNTER_SPACING" => "counterAxisSpacing",
"STACK_PADDING_LEFT" => "paddingLeft",
"STACK_PADDING_TOP" => "paddingTop",
"STACK_PADDING_RIGHT" => "paddingRight",
"STACK_PADDING_BOTTOM" => "paddingBottom",
"VISIBLE" => "visible",
"TEXT_DATA" => "characters",
"OPACITY" => "opacity",
"MIN_WIDTH" => "minWidth",
"MAX_WIDTH" => "maxWidth",
"MIN_HEIGHT" => "minHeight",
"MAX_HEIGHT" => "maxHeight",
"RECTANGLE_TOP_LEFT_CORNER_RADIUS" => "topLeftRadius",
"RECTANGLE_TOP_RIGHT_CORNER_RADIUS" => "topRightRadius",
"RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS" => "bottomLeftRadius",
"RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS" => "bottomRightRadius",
_ => return None,
})
}
/// The REST text style `boundVariables` key of a bound text field.
fn text_binding_key(field: &str) -> Option<&'static str> {
Some(match field {
"FONT_SIZE" => "fontSize",
"FONT_FAMILY" => "fontFamily",
"FONT_STYLE" => "fontStyle",
"LETTER_SPACING" => "letterSpacing",
"LINE_HEIGHT" => "lineHeight",
"PARAGRAPH_SPACING" => "paragraphSpacing",
"PARAGRAPH_INDENT" => "paragraphIndent",
_ => return None,
})
}
/// A `VariableData` (literal, variable reference or expression) in the REST shape; `None` for
/// kinds a prototype can't evaluate.
pub(super) fn variable_data(d: &Kv, depth: usize) -> Option<Value> {
let v = d.get("value")?;
let ty = d.get("dataType").and_then(Kv::str)?;
let value = match ty {
"ALIAS" => json!({"type": "VARIABLE_ALIAS", "id": v.get("alias").and_then(ref_guid)?}),
"EXPRESSION" if depth < MAX_EXPR_DEPTH => {
let e = v.get("expressionValue")?;
let function = match e.get("expressionFunction").and_then(Kv::str)? {
"MULTIPLY" => "MULTIPLICATION",
"DIVIDE" => "DIVISION",
f => f,
};
let args = e.get("expressionArguments").map(Kv::list).unwrap_or_default();
let args = args.iter().map(|x| variable_data(x, depth + 1)).collect::<Option<Vec<Value>>>()?;
json!({"expressionFunction": function, "expressionArguments": args})
}
"BOOLEAN" => json!(v.get("boolValue").and_then(Kv::bool)?),
"FLOAT" => json!(num(v, "floatValue").filter(|x| x.is_finite())?),
"STRING" => json!(v.get("textValue").and_then(Kv::str)?),
"COLOR" => color(v.get("colorValue")?),
_ => return None,
};
let mut out = json!({"type": ty, "value": value});
if let Some(r) = d.get("resolvedDataType").and_then(Kv::str) {
out["resolvedType"] = json!(r);
}
Some(out)
}
/// The variable an `ALIAS` variable data points at: by guid, or by library asset (the newest copy
/// of it in the file).
pub(super) fn alias(d: Option<&Kv>) -> Option<String> {
let d = d?;
if d.get("dataType").and_then(Kv::str) != Some("ALIAS") {
return None;
}
d.get("value").and_then(|v| v.get("alias")).and_then(super::VarCanon::resolve)
}
pub(super) fn variable_value(d: &Kv) -> Option<Value> {
if let Some(a) = alias(Some(d)) {
return Some(json!({"type": "VARIABLE_ALIAS", "id": a}));
}
let v = d.get("value")?;
if let Some(c) = v.get("colorValue") {
return Some(color(c));
}
if let Some(b) = v.get("boolValue").and_then(Kv::bool) {
return Some(json!(b));
}
if let Some(x) = num(v, "floatValue") {
return Some(json!(x));
}
v.get("textValue").and_then(Kv::str).map(|s| json!(s))
}
-133
View File
@@ -1,133 +0,0 @@
//! Vector network blobs: the editable form of a vector layer (`vectorData.vectorNetworkBlob`).
//!
//! Little-endian throughout: `u32` counts of vertices, segments and regions; each vertex a style
//! id (`u32`) and its position (`f32` x, y); each segment a style id, its start vertex (`u32`) and
//! tangent (`f32` x, y), then its end vertex and tangent; each region a `u32` holding its style id
//! shifted left once with the winding rule in the low bit (set: non-zero, clear: even-odd), a loop
//! count, and per loop a segment count and the segment indices. Positions are in the space of
//! `vectorData.normalizedSize`. Style ids point into `vectorData.styleOverrideTable` (0: none).
/// Most vertices, segments, regions or loop entries read from one blob.
const MAX_ITEMS: usize = 200_000;
pub(super) struct Vertex {
pub style: u32,
pub x: f64,
pub y: f64,
}
pub(super) struct Segment {
pub style: u32,
pub a: usize,
pub ta: (f64, f64),
pub b: usize,
pub tb: (f64, f64),
}
pub(super) struct Region {
pub style: u32,
pub non_zero: bool,
pub loops: Vec<Vec<usize>>,
}
#[derive(Default)]
pub(super) struct Network {
pub vertices: Vec<Vertex>,
pub segments: Vec<Segment>,
pub regions: Vec<Region>,
}
struct Reader<'b> {
b: &'b [u8],
pos: usize,
}
impl Reader<'_> {
fn u32(&mut self) -> Option<u32> {
let v = u32::from_le_bytes(self.b.get(self.pos..self.pos + 4)?.try_into().ok()?);
self.pos += 4;
Some(v)
}
fn f32(&mut self) -> Option<f64> {
Some(f64::from(f32::from_bits(self.u32()?))).filter(|x| x.is_finite())
}
/// An index below `len`.
fn index(&mut self, len: usize) -> Option<usize> {
Some(self.u32()? as usize).filter(|i| *i < len)
}
/// A count of items of at least `size` bytes each that the rest of the blob can hold.
fn count(&mut self, size: usize) -> Option<usize> {
let n = self.u32()? as usize;
(n <= MAX_ITEMS && n * size <= self.b.len().saturating_sub(self.pos)).then_some(n)
}
}
/// The network in blob `b`; `None` when it's truncated, out of range or not finite.
pub(super) fn decode(b: &[u8]) -> Option<Network> {
let mut r = Reader { b, pos: 0 };
let (nv, ns, nr) = (r.u32()? as usize, r.u32()? as usize, r.u32()? as usize);
if nv > MAX_ITEMS || ns > MAX_ITEMS || nr > MAX_ITEMS || nv * 12 + ns * 28 + nr * 8 > b.len().saturating_sub(12) {
return None;
}
let mut net = Network::default();
for _ in 0..nv {
net.vertices.push(Vertex { style: r.u32()?, x: r.f32()?, y: r.f32()? });
}
for _ in 0..ns {
let style = r.u32()?;
net.segments.push(Segment { style, a: r.index(nv)?, ta: (r.f32()?, r.f32()?), b: r.index(nv)?, tb: (r.f32()?, r.f32()?) });
}
let mut entries = 0usize;
for _ in 0..nr {
let sw = r.u32()?;
let mut loops = Vec::new();
for _ in 0..r.count(4)? {
let n = r.count(4)?;
entries += n;
if entries > MAX_ITEMS {
return None;
}
loops.push((0..n).map(|_| r.index(ns)).collect::<Option<Vec<usize>>>()?);
}
net.regions.push(Region { style: sw >> 1, non_zero: sw & 1 == 1, loops });
}
Some(net)
}
/// The blob of `net` (the export writes it; so do test fixtures). Callers pass finite values.
pub(super) fn encode(net: &Network) -> Vec<u8> {
let mut out = Vec::new();
let u = |v: u32, out: &mut Vec<u8>| out.extend_from_slice(&v.to_le_bytes());
let fl = |v: f64, out: &mut Vec<u8>| out.extend_from_slice(&(v as f32).to_le_bytes());
for n in [net.vertices.len(), net.segments.len(), net.regions.len()] {
u(n as u32, &mut out);
}
for v in &net.vertices {
u(v.style, &mut out);
fl(v.x, &mut out);
fl(v.y, &mut out);
}
for s in &net.segments {
u(s.style, &mut out);
u(s.a as u32, &mut out);
fl(s.ta.0, &mut out);
fl(s.ta.1, &mut out);
u(s.b as u32, &mut out);
fl(s.tb.0, &mut out);
fl(s.tb.1, &mut out);
}
for r in &net.regions {
u((r.style << 1) | u32::from(r.non_zero), &mut out);
u(r.loops.len() as u32, &mut out);
for l in &r.loops {
u(l.len() as u32, &mut out);
for i in l {
u(*i as u32, &mut out);
}
}
}
out
}
+25 -3
View File
@@ -359,6 +359,28 @@ fn vector_region_missing_and_empty_paints_remain_distinct() {
assert_eq!(network_of(&empty, "Wave").regions[0].fills, Some(Vec::new()));
}
#[test]
fn vector_region_fills_survive_a_fig_export() {
let solid = o(vec![("type", e("SOLID")), ("color", o(vec![("r", f(0.2)), ("g", f(0.4)), ("b", f(0.8)), ("a", f(1.0))])), ("opacity", f(0.5))]);
let gradient = o(vec![
("type", e("GRADIENT_LINEAR")),
(
"stops",
arr(vec![
o(vec![("position", f(0.0)), ("color", o(vec![("r", f(1.0)), ("g", f(0.0)), ("b", f(0.0)), ("a", f(1.0))]))]),
o(vec![("position", f(1.0)), ("color", o(vec![("r", f(0.0)), ("g", f(0.0)), ("b", f(1.0)), ("a", f(1.0))]))]),
]),
),
]);
let (doc, _) = import(&region_canvas(Some(vec![solid, gradient]), 1), "Region fills").unwrap();
let first = network_of(&doc, "Wave").regions[0].fills.clone();
assert!(first.as_ref().is_some_and(|fills| fills.len() == 2), "{first:?}");
let (bytes, warnings) = crate::fig::export::export(&doc, None).unwrap();
assert!(!warnings.iter().any(|warning| warning.contains("region")), "{warnings:?}");
let (back, _) = import(&bytes, "Again").unwrap();
assert_eq!(network_of(&back, "Wave").regions[0].fills, first);
}
#[test]
fn vector_region_linked_fill_uses_style_paints_without_recording_definition() {
let linked = solid(0.9, 0.1, 0.2);
@@ -753,7 +775,7 @@ fn connectors_without_a_saved_path_follow_their_line_style() {
let line: Vec<_> =
network_of(&doc, "Line").vertices.iter().map(|v| world("Line") * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
assert_eq!(line, [(100.0, 650.0), (300.0, 650.0)]);
assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("are routed afresh")), "{warnings:?}");
}
/// #1909: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER`
@@ -1033,7 +1055,7 @@ fn an_elbow_connector_saved_with_its_path_keeps_it() {
// Each end starts `END_GAP` (4) outside its side's border.
assert_eq!(line, [(50.0, 704.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (296.0, 850.0)]);
// The fixture's own Link, saved without a path, is routed here: the note counts it alone.
let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect();
let routed: Vec<_> = warnings.iter().filter(|w| w.contains("are routed afresh")).collect();
assert_eq!(routed.len(), 1, "{warnings:?}");
assert!(!routed[0].contains('×'), "a connector with its path isn't counted among those routed here: {routed:?}");
}
@@ -1081,5 +1103,5 @@ fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() {
for name in ["Sideways", "Askew", "Repeated", "Backwards", "Inside"] {
assert_eq!(line(name), plain, "{name} is routed as one without a path");
}
assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("are routed afresh")), "{warnings:?}");
}
+22 -24
View File
@@ -795,11 +795,11 @@ fn hashes_naming_one_blob_share_one_copy_of_it() {
("blobs", Kv::Array(vec![o(vec![("bytes", Kv::Bytes(png()))]), o(vec![("bytes", Kv::Bytes(vec![7; 16]))])])),
("nodeChanges", Kv::Array((1..=50).map(|h| image(h, 0)).chain([image(99, 1), image(98, 2)]).collect())),
]);
let copies = embedded_copies(&msg);
let copies = embedded_copies(&msg, MAX_IMAGE);
assert_eq!(copies.len(), 51, "the hash naming no blob is left out");
let first = &copies[&"01".repeat(20)];
assert_eq!(**first, *png());
assert_eq!(copies.values().filter(|c| Arc::ptr_eq(c, first)).count(), 50);
assert_eq!(copies.values().filter(|c| std::sync::Arc::ptr_eq(c, first)).count(), 50);
assert_eq!(*copies[&"63".repeat(20)], [7; 16]);
}
@@ -814,7 +814,7 @@ fn hashes_naming_one_blob_are_imported_once() {
let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])];
nodes.extend((2..42).map(|i| rect(i, i as u8, 0)));
let msg = o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(png()))])]))]);
let copies = embedded_copies(&msg);
let copies = embedded_copies(&msg, MAX_IMAGE);
let aliases = embedded_aliases(&copies, |_| false);
assert_eq!(aliases.len(), 39);
assert!(aliases.values().all(|c| *c == "02".repeat(20)));
@@ -974,13 +974,13 @@ mod image_budget {
// Shorten the first member's compressed size, cutting its deflate stream mid-image.
change_member_field(&mut zip, 1, 20, 15);
let limit = members[0].1.len() as u64;
let archive = Archive::open(&zip).unwrap();
archive.image_budget.remaining.set(limit);
let archive = Archive::open_with(&zip, Limits { max_image: MAX_IMAGE, max_image_total: limit }).unwrap();
assert!(archive.image(&"01".repeat(20)).is_none());
let remaining = archive.image_budget.remaining.get();
assert!(remaining > 0 && remaining < limit, "partial read left {remaining} of {limit} bytes");
// The failed read keeps its charge (craft-fig charges the declared size).
let remaining = archive.image_bytes_left();
assert!(remaining < limit, "partial read left {remaining} of {limit} bytes");
assert!(archive.image(&"02".repeat(20)).is_none());
assert_eq!(archive.image_budget.remaining.get(), remaining);
assert_eq!(archive.image_bytes_left(), remaining);
let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap();
assert_ne!(bytes(&doc, 1), members[1].1);
assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}");
@@ -1013,14 +1013,13 @@ mod image_budget {
let members = [(1, image(1)), (2, image(2))];
let mut zip = file(&[1, 2], &members);
change_member_field(&mut zip, 1, 24, 1);
let archive = Archive::open(&zip).unwrap();
archive.image_budget.remaining.set(members[0].1.len() as u64 - 1);
let archive = Archive::open_with(&zip, Limits { max_image: MAX_IMAGE, max_image_total: members[0].1.len() as u64 - 1 }).unwrap();
// Whether the ZIP reader refuses the mismatch or reads on, the member is not returned
// and the budget is never overdrawn.
assert!(archive.image(&"01".repeat(20)).is_none());
assert_eq!(archive.image_budget.remaining.get(), 0);
assert_eq!(archive.image_budget.skipped.get(), 1);
assert!(archive.image_bytes_left() < members[0].1.len() as u64);
assert!(archive.image(&"02".repeat(20)).is_none());
assert_eq!(archive.image_budget.remaining.get(), 0);
assert_eq!(archive.image_budget.skipped.get(), 2);
assert!(archive.images_skipped() >= 1);
}
#[test]
@@ -1153,23 +1152,23 @@ fn mangled_kiwi_never_panics() {
#[test]
fn large_files_get_a_larger_value_budget() {
// Small files keep the fixed floor: a few bytes can't expand into a huge tree.
assert_eq!(kiwi::value_budget(0), 20_000_000);
assert_eq!(kiwi::value_budget(1 << 20), 20_000_000);
assert_eq!(craft_fig::value_budget(0), 20_000_000);
assert_eq!(craft_fig::value_budget(1 << 20), 20_000_000);
// A real 400 000-layer file: an 83.5 MB canvas whose message unpacks to 334 MB and holds
// 30.5 million values was refused as "too many values".
assert!(kiwi::value_budget(83_491_232) > 30_514_899);
assert!(craft_fig::value_budget(83_491_232) > 30_514_899);
// A real 194 MB design-system file (UX4G): a 39.5 MB canvas holding 29.7 million values.
assert!(kiwi::value_budget(39_528_420) > 29_703_730);
assert!(craft_fig::value_budget(39_528_420) > 29_703_730);
// Still bounded by the largest canvas read.
assert!(kiwi::value_budget(MAX_CANVAS as usize) <= 128 << 20);
assert!(craft_fig::value_budget(MAX_CANVAS as usize) <= 128 << 20);
// Counting every scalar field, a dense file may reach about 2.4 values per compressed byte (the
// 15 MB text-heavy fixture in `value_budget_tests` measures 1.8): below the ceiling the budget must
// cover that, the floor still holds up to 5 MB of canvas, and 32 MiB is enough for the ceiling.
assert!(kiwi::value_budget(8 << 20) >= (8 << 20) * 12 / 5);
assert!(craft_fig::value_budget(8 << 20) >= (8 << 20) * 12 / 5);
#[cfg(not(target_pointer_width = "32"))]
assert!(kiwi::value_budget(30_000_000) >= 30_000_000 * 12 / 5);
assert_eq!(kiwi::value_budget(5_000_000), 20_000_000);
assert_eq!(kiwi::value_budget(32 << 20), kiwi::value_budget(MAX_CANVAS as usize));
assert!(craft_fig::value_budget(30_000_000) >= 30_000_000 * 12 / 5);
assert_eq!(craft_fig::value_budget(5_000_000), 20_000_000);
assert_eq!(craft_fig::value_budget(32 << 20), craft_fig::value_budget(MAX_CANVAS as usize));
}
#[test]
@@ -1822,7 +1821,6 @@ fn same_version_library_copies_resolve_deterministically_and_leave_no_table() {
let page = doc.nodes().find(|n| n.name == "Page").unwrap();
assert_eq!(page.var_modes.get(&id).map(String::as_str), Some("1:90"));
picked.push(id);
assert!(!super::map::VarCanon::installed());
}
assert_eq!(picked, ["1:6", "1:6"]);
}
-316
View File
@@ -1,316 +0,0 @@
//! Convert the simple vector network used by text-on-path layers in `.fig` files into a native text path.
use figcraft_doc::{
TextPath,
geom::{
BezPath,
kurbo::{CubicBez, Line, ParamCurve, ParamCurveArclen, Point},
},
};
use super::network::{Network, Segment};
const START_SEGMENT_STYLE: u32 = 0x01ff_ffff;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Use {
segment: usize,
forward: bool,
}
/// Build a native path from a validated connected chain or cycle. The marked source segment is
/// oriented a→b; `t` is local to that line/cubic. Coordinates are scaled into layer space.
pub(super) fn from_network(net: &Network, sx: f64, sy: f64, t: f64, forward: bool) -> Result<TextPath, &'static str> {
if !t.is_finite() || !(0.0..=1.0).contains(&t) {
return Err("invalid start parameter");
}
if !sx.is_finite() || !sy.is_finite() || sx <= 0.0 || sy <= 0.0 {
return Err("invalid path scale");
}
let markers: Vec<usize> = net.segments.iter().enumerate().filter_map(|(i, s)| (s.style == START_SEGMENT_STYLE).then_some(i)).collect();
let [marked] = markers.as_slice() else {
return Err("missing or ambiguous start segment marker");
};
let (uses, closed) = ordered_chain(net, *marked)?;
let mut d = BezPath::new();
let mut total = 0.0;
let mut prefix = 0.0;
let mut start_segment_length = 0.0;
for use_ in &uses {
let (p0, p1, p2, p3) = cubic(net, *use_, sx, sy)?;
if d.elements().is_empty() {
d.move_to((p0.0, p0.1));
}
let line = p1 == p0 && p2 == p3;
let (length, partial) = if line {
d.line_to((p3.0, p3.1));
let line = Line::new(Point::new(p0.0, p0.1), Point::new(p3.0, p3.1));
(line.arclen(1e-9), line.arclen(1e-9) * t)
} else {
d.curve_to((p1.0, p1.1), (p2.0, p2.1), (p3.0, p3.1));
let curve = CubicBez::new((p0.0, p0.1), (p1.0, p1.1), (p2.0, p2.1), (p3.0, p3.1));
let partial = if t <= 0.0 { 0.0 } else { curve.subsegment(0.0..t).arclen(1e-9) };
(curve.arclen(1e-9), partial)
};
if !length.is_finite() || length <= 1e-10 {
return Err("zero-length path segment");
}
if use_.segment == *marked {
start_segment_length = partial;
if !start_segment_length.is_finite() {
return Err("invalid path length");
}
prefix = total;
}
total += length;
}
if closed {
d.close_path();
}
if !total.is_finite() || total <= 1e-10 {
return Err("zero-length path");
}
let mut start = ((prefix + start_segment_length) / total).clamp(0.0, 1.0);
let flip = !forward;
if flip {
start = 1.0 - start;
}
let path = TextPath { d: d.to_svg(), start, flip };
let lines = figcraft_doc::geom::measure::polylines(&path.path()).ok_or("cannot be measured by text renderer")?;
if lines.first().is_none_or(|line| line.length() <= 1e-9) {
return Err("cannot be measured by text renderer");
}
Ok(path)
}
/// Return every segment in chain order. Open chains are oriented so the marked segment runs a→b;
/// cycles start at the marked segment's a vertex and traverse it first.
fn ordered_chain(net: &Network, marked: usize) -> Result<(Vec<Use>, bool), &'static str> {
let marker = net.segments.get(marked).ok_or("invalid start segment index")?;
let mut adjacency = vec![Vec::<usize>::new(); net.vertices.len()];
for (i, s) in net.segments.iter().enumerate() {
if s.a >= adjacency.len() || s.b >= adjacency.len() {
return Err("invalid path vertex index");
}
if s.a == s.b {
return Err("path contains a segment that starts and ends at the same vertex");
}
adjacency[s.a].push(i);
adjacency[s.b].push(i);
}
let mut endpoints = Vec::new();
for edges in &adjacency {
if edges.len() > 2 {
return Err("branched path network");
}
if edges.len() == 1 {
endpoints.push(edges[0]);
}
}
if !endpoints.is_empty() && endpoints.len() != 2 {
return Err("disconnected or malformed path network");
}
let cycle = endpoints.is_empty();
let mut used = vec![false; net.segments.len()];
let mut out = Vec::with_capacity(net.segments.len());
if cycle {
out.push(Use { segment: marked, forward: true });
used[marked] = true;
let mut at = marker.b;
let mut visited = vec![false; net.vertices.len()];
visited[marker.a] = true;
visited[marker.b] = true;
while at != marker.a {
let next = adjacency[at].iter().copied().find(|i| !used[*i]).ok_or("disconnected path cycle")?;
used[next] = true;
let s = &net.segments[next];
let is_forward = s.a == at;
at = if is_forward { s.b } else { s.a };
if at != marker.a && std::mem::replace(&mut visited[at], true) {
return Err("path cycle is not simple");
}
out.push(Use { segment: next, forward: is_forward });
if out.len() > net.segments.len() {
return Err("invalid path cycle");
}
}
} else {
let endpoint = adjacency.iter().position(|e| e.len() == 1).ok_or("missing path endpoint")?;
let mut at = endpoint;
while let Some(next) = adjacency[at].iter().copied().find(|i| !used[*i]) {
used[next] = true;
let s = &net.segments[next];
let is_forward = s.a == at;
at = if is_forward { s.b } else { s.a };
out.push(Use { segment: next, forward: is_forward });
}
let Some(marker_use) = out.iter().find(|u| u.segment == marked) else { return Err("disconnected start segment") };
if !marker_use.forward {
out.reverse();
for u in &mut out {
u.forward = !u.forward;
}
}
}
if !used.iter().all(|x| *x) {
return Err("disconnected path network");
}
Ok((out, cycle))
}
type P = (f64, f64);
fn cubic(net: &Network, use_: Use, sx: f64, sy: f64) -> Result<(P, P, P, P), &'static str> {
let s: &Segment = net.segments.get(use_.segment).ok_or("invalid path segment index")?;
let a = net.vertices.get(s.a).ok_or("invalid path vertex index")?;
let b = net.vertices.get(s.b).ok_or("invalid path vertex index")?;
let p0 = (a.x * sx, a.y * sy);
let p3 = (b.x * sx, b.y * sy);
let ta = (s.ta.0 * sx, s.ta.1 * sy);
let tb = (s.tb.0 * sx, s.tb.1 * sy);
if [p0.0, p0.1, p3.0, p3.1, ta.0, ta.1, tb.0, tb.1].iter().any(|x| !x.is_finite()) {
return Err("invalid path coordinates");
}
let (p0, p1, p2, p3) =
if ta == (0.0, 0.0) && tb == (0.0, 0.0) { (p0, p0, p3, p3) } else { (p0, (p0.0 + ta.0, p0.1 + ta.1), (p3.0 + tb.0, p3.1 + tb.1), p3) };
if use_.forward { Ok((p0, p1, p2, p3)) } else { Ok((p3, p2, p1, p0)) }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fig::network::{Segment, Vertex};
use figcraft_doc::geom::kurbo::PathEl;
fn vertex(x: f64, y: f64) -> Vertex {
Vertex { style: 0, x, y }
}
fn segment(style: u32, a: usize, b: usize, ta: (f64, f64), tb: (f64, f64)) -> Segment {
Segment { style, a, ta, b, tb }
}
fn curved() -> Network {
Network {
vertices: vec![vertex(0.0, 82.5), vertex(300.0, 82.5), vertex(600.0, 82.5)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (70.0, -110.0), (-70.0, -110.0)), segment(0, 1, 2, (70.0, 110.0), (-70.0, 110.0))],
..Network::default()
}
}
#[test]
fn local_cubic_parameter_converts_to_path_distance() {
let path = from_network(&curved(), 1.0, 1.0, 0.0086954795, true).unwrap();
assert!((path.start - 0.004744078).abs() < 0.00001);
// Cubic t is not its fraction of total path length.
assert!((path.start - 0.0086954795).abs() > 0.003);
let elements = path.path().elements().to_vec();
assert!(matches!(elements.first(), Some(PathEl::MoveTo(p)) if p.x == 0.0 && p.y == 82.5));
assert!(matches!(elements.get(1), Some(PathEl::CurveTo(..))));
}
#[test]
fn second_segment_marker_and_t_are_respected() {
let mut net = curved();
net.segments[0].style = 0;
net.segments[1].style = START_SEGMENT_STYLE;
let path = from_network(&net, 1.0, 1.0, 0.49800667, true).unwrap();
assert!((path.start - 0.7490379757).abs() < 0.00002);
}
#[test]
fn reverse_direction_inverts_normalized_start() {
let net = Network {
vertices: vec![vertex(0.0, 0.0), vertex(600.0, 0.0)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))],
..Network::default()
};
let path = from_network(&net, 1.0, 1.0, 0.83986014, false).unwrap();
assert!(path.flip);
assert!((path.start - 0.16013986).abs() < 1e-8);
assert!(matches!(path.path().elements().get(1), Some(PathEl::LineTo(p)) if p.x == 600.0 && p.y == 0.0));
}
#[test]
fn rejects_missing_duplicate_and_zero_length_segments() {
let mut net = curved();
net.segments[0].style = 0;
assert_eq!(from_network(&net, 1.0, 1.0, 0.5, true), Err("missing or ambiguous start segment marker"));
net.segments[1].style = START_SEGMENT_STYLE;
net.segments[0].style = START_SEGMENT_STYLE;
assert_eq!(from_network(&net, 1.0, 1.0, 0.5, true), Err("missing or ambiguous start segment marker"));
let zero = Network {
vertices: vec![vertex(0.0, 0.0), vertex(0.0, 0.0)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))],
..Network::default()
};
assert_eq!(from_network(&zero, 1.0, 1.0, 0.5, true), Err("zero-length path segment"));
}
#[test]
fn rejects_branching_and_disconnected_segments() {
let branch = Network {
vertices: vec![vertex(0.0, 0.0), vertex(1.0, 0.0), vertex(2.0, 0.0), vertex(1.0, 1.0)],
segments: vec![
segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)),
segment(0, 1, 2, (0.0, 0.0), (0.0, 0.0)),
segment(0, 1, 3, (0.0, 0.0), (0.0, 0.0)),
],
..Network::default()
};
assert_eq!(from_network(&branch, 1.0, 1.0, 0.5, true), Err("branched path network"));
let disconnected = Network {
vertices: vec![vertex(0.0, 0.0), vertex(1.0, 0.0), vertex(2.0, 0.0), vertex(3.0, 0.0)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)), segment(0, 2, 3, (0.0, 0.0), (0.0, 0.0))],
..Network::default()
};
assert_eq!(from_network(&disconnected, 1.0, 1.0, 0.5, true), Err("disconnected or malformed path network"));
}
#[test]
fn scales_geometry_and_accepts_closed_cycles() {
let cycle = Network {
vertices: vec![vertex(0.0, 0.0), vertex(100.0, 0.0), vertex(100.0, 100.0)],
segments: vec![
segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)),
segment(0, 1, 2, (0.0, 0.0), (0.0, 0.0)),
segment(0, 2, 0, (0.0, 0.0), (0.0, 0.0)),
],
..Network::default()
};
let path = from_network(&cycle, 2.0, 3.0, 0.5, true).unwrap();
let elements = path.path().elements().to_vec();
assert!(matches!(elements.first(), Some(PathEl::MoveTo(p)) if p.x == 0.0 && p.y == 0.0));
assert!(matches!(elements.get(1), Some(PathEl::LineTo(p)) if p.x == 200.0 && p.y == 0.0));
let total = 200.0 + 300.0 + 130_000.0_f64.sqrt();
assert!((path.start - 100.0 / total).abs() < 1e-8);
assert!(matches!(elements.last(), Some(PathEl::ClosePath)));
}
#[test]
fn rejects_paths_the_native_renderer_cannot_measure() {
let count = 40_000usize;
let many_lines = Network {
vertices: (0..=count).map(|i| vertex(i as f64, 0.0)).collect(),
segments: (0..count).map(|i| segment(if i == 0 { START_SEGMENT_STYLE } else { 0 }, i, i + 1, (0.0, 0.0), (0.0, 0.0))).collect(),
..Network::default()
};
assert_eq!(from_network(&many_lines, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer"));
// Past the cap the builders hold their sizes to (`figcraft_geom::MAX_COORD`, inclusive).
let huge = Network {
vertices: vec![vertex(0.0, 0.0), vertex(2e9, 0.0)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))],
..Network::default()
};
assert_eq!(from_network(&huge, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer"));
let tiny = Network {
vertices: vec![vertex(0.0, 0.0), vertex(5e-10, 0.0)],
segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))],
..Network::default()
};
assert_eq!(from_network(&tiny, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer"));
}
}
+5 -5
View File
@@ -4,7 +4,7 @@
use super::kiwi::{Kv, Schema, encode};
use super::tests::{Lcg, arr, at, f, g, node, o, s, schema, solid, u, xy};
use super::{decode_canvas, export, import, kiwi};
use super::{decode_canvas, import};
fn frac(r: &mut Lcg, hi: f64) -> f64 {
(r.next() % 100_000) as f64 / 100_000.0 * hi
@@ -84,7 +84,7 @@ fn one_list_canvas(sc: &Schema, count: u32, elements: impl IntoIterator<Item = u
let mut msg = head.0;
msg.extend(elements);
msg.push(0);
export::canvas(&encode::schema(sc), &msg).unwrap()
craft_fig::encode_canvas(&encode::schema(sc), &msg).unwrap()
}
/// `pages` pages of `rects` rectangles and `texts` texts of `chars` characters, framed the way the
@@ -125,7 +125,7 @@ fn opens_whole(label: &str, pages: usize, rects: usize, texts: usize, chars: usi
let file = canvas(pages, rects, texts, chars);
let (sc, msg) = decode_canvas(&file).unwrap();
let root = sc.find("Message").unwrap();
let one_per_byte = file.len().clamp(kiwi::value_budget(0), kiwi::value_budget(usize::MAX));
let one_per_byte = file.len().clamp(craft_fig::value_budget(0), craft_fig::value_budget(usize::MAX));
let refused = sc.decode_message_within(root, &msg, one_per_byte).is_err_and(|e| e.0 == "message: too many values");
assert!(refused, "{label}: one value per compressed byte no longer refuses it");
let (doc, warnings) = import(&file, label).unwrap_or_else(|e| panic!("{label}: refused: {e}"));
@@ -133,7 +133,7 @@ fn opens_whole(label: &str, pages: usize, rects: usize, texts: usize, chars: usi
assert!(warnings.is_empty(), "{label}: {warnings:?}");
println!("{label}: {} canvas bytes, {} layers", file.len(), doc.node_count());
drop(doc);
assert!(sc.decode_message_within(root, &msg, kiwi::value_budget(file.len()) / 10 * 9).is_ok(), "{label}: not within 90% of its budget");
assert!(sc.decode_message_within(root, &msg, craft_fig::value_budget(file.len()) / 10 * 9).is_ok(), "{label}: not within 90% of its budget");
file.len()
}
@@ -151,7 +151,7 @@ fn dense_canvases_open_whole() {
#[ignore = "heavy: --release --ignored, about 9 GB"]
fn a_canvas_budgeted_at_the_ceiling_opens_whole() {
let packed = opens_whole("50 MB text-heavy canvas", 106, 0, 5000, 100);
assert_eq!(kiwi::value_budget(packed), kiwi::value_budget(usize::MAX), "budgeted at the ceiling");
assert_eq!(craft_fig::value_budget(packed), craft_fig::value_budget(usize::MAX), "budgeted at the ceiling");
}
/// However far a small canvas inflates, the floor bounds what it may decode.
+193 -333
View File
@@ -31,76 +31,26 @@ pub use library::{is_valid_library_id, read_library, read_library_within};
mod density;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek, Write};
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::Arc;
use figcraft_doc::{Document, ImageData};
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::{Value, json};
use serde_json::Value;
#[cfg(test)]
use serde_json::json;
use sha2::Digest;
pub const EXTENSION: &str = "figcraft";
pub const FORMAT: &str = "figcraft";
pub const VERSION: u32 = 1;
/// Largest archive member we read (guards against zip bombs).
const MAX_MEMBER: u64 = 512 * 1024 * 1024;
/// `document.json` may unpack to [`DOCUMENT_RATIO`] times what it takes in the archive, within
/// [`MAX_MEMBER`] and [`MAX_DOCUMENT`]: a large document saved by us (a 900 000-layer file packs
/// 1.48 GB into 244 MB) opens again, while a small archive still can't unpack into gigabytes.
/// 32-bit targets (wasm32) have a 4 GB address space in all, so their ceiling is lower.
const DOCUMENT_RATIO: u64 = 16;
#[cfg(not(target_pointer_width = "32"))]
const MAX_DOCUMENT: u64 = 4 * 1024 * 1024 * 1024;
#[cfg(target_pointer_width = "32")]
const MAX_DOCUMENT: u64 = 1024 * 1024 * 1024;
/// Most versions a file keeps: saving more is refused, extra entries in a file are skipped.
pub const MAX_VERSIONS: usize = 100;
pub use craft_figcraft_format::{
BRANCH_INDEX, BranchEntry as NativeBranchEntry, BranchIndex as NativeBranchIndex, BranchState as NativeBranchState, DOCUMENT_RATIO, EXTENSION,
FORMAT, FormatError, IMAGE_BUDGET, ImageBudget, MAX_BRANCHES, MAX_DOCUMENT, MAX_MEMBER, MAX_UNPACKED, MAX_VERSION_BYTES, MAX_VERSION_DESCRIPTION,
MAX_VERSION_INDEX, MAX_VERSION_NAME, MAX_VERSIONS, ReadBudget, VERSION, VersionEntry as NativeVersionEntry, VersionIndex as NativeVersionIndex,
clip, document_limit, is_valid_version_id,
};
const JSON_LEVEL: i64 = 3;
/// The export warning for colour calculations that resolve to nothing (an operand missing, or more
/// than 32 variables to read), shared by the Penpot and `.fig` exports.
pub(crate) const CALCULATIONS_LEFT_OUT: &str = "colour calculations that don't resolve were left out";
/// Longest version name and description kept (chars).
pub const MAX_VERSION_NAME: usize = 200;
pub const MAX_VERSION_DESCRIPTION: usize = 2000;
/// Largest version index and total size of the version snapshots read from one file.
const MAX_VERSION_INDEX: u64 = 16 * 1024 * 1024;
const MAX_VERSION_BYTES: u64 = 1024 * 1024 * 1024;
/// Most images, and image bytes together, read from one file (members past it are left out).
const IMAGE_BUDGET: ImageBudget = ImageBudget { images: 20_000, bytes: 4 * 1024 * 1024 * 1024 };
/// Most bytes one open of a `.figcraft` file unpacks, every area together: its document, images,
/// published library, version history and branches ([`Unpacked`], #1079). Each area keeps its own
/// cap; their sum was about 10 GB. Read in that order, the document (a 900 000-layer one unpacks
/// to 1.5 GB) and the images up to their own 4 GiB cap fit, so a file whose images pass that cap
/// (#1313: an 84 MiB document with 7.3 GiB of images) keeps as many as before; the history and
/// branches share what is left. 32-bit targets (wasm32) have 4 GB of address space in all.
#[cfg(not(target_pointer_width = "32"))]
const MAX_UNPACKED: u64 = 6 * 1024 * 1024 * 1024;
#[cfg(target_pointer_width = "32")]
const MAX_UNPACKED: u64 = 2 * 1024 * 1024 * 1024;
const BRANCH_INDEX: &str = "branches/index.json";
/// Most branches a file keeps: making more is refused, extra entries in a file are skipped.
pub const MAX_BRANCHES: usize = 100;
/// Deflate level of JSON members (see [`json_options`]).
const JSON_LEVEL: i64 = 3;
#[derive(Debug)]
pub enum FormatError {
Io(String),
Corrupt(String),
Newer(u32),
}
impl std::fmt::Display for FormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::Io(e) => write!(f, "{e}"),
FormatError::Corrupt(e) => write!(f, "not a valid FigCraft file: {e}"),
FormatError::Newer(v) => write!(f, "this file was saved by a newer FigCraft (format version {v})"),
}
}
}
impl std::error::Error for FormatError {}
/// One entry of a file's version history: a named snapshot of the document.
#[derive(Clone, Debug)]
@@ -191,16 +141,6 @@ pub struct Branch {
pub versions: Vec<Version>,
}
/// Whether `id` can name a version (and its archive entry).
pub fn is_valid_version_id(id: &str) -> bool {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// `s` cut to at most `max` chars.
pub fn clip(s: &str, max: usize) -> String {
s.chars().take(max).collect()
}
/// A file as read: the document, the repairs made (and versions skipped), and its version
/// history, oldest first.
#[derive(Debug)]
@@ -243,33 +183,14 @@ pub(crate) fn image_data(data: Vec<u8>) -> ImageData {
ImageData { bytes: Arc::new(data), width: w, height: h }
}
/// `document.json`: the format header, the image index and the document's own fields, written
/// straight from the document (no intermediate JSON tree).
#[derive(Serialize)]
struct DocumentJson<'a> {
format: &'static str,
version: u32,
#[serde(rename = "imageIndex", serialize_with = "image_index")]
images: &'a BTreeMap<String, ImageData>,
#[serde(flatten)]
doc: &'a Document,
}
/// The image hashes a `document.json` lists in its `imageIndex` (`None` without one).
type ImageIndex = Option<BTreeSet<String>>;
impl<'a> DocumentJson<'a> {
fn new(doc: &'a Document) -> Self {
Self { format: FORMAT, version: VERSION, images: &doc.images, doc }
}
}
/// The `imageIndex`: `[{hash, width, height}]` for every image the document holds.
fn image_index<S: Serializer>(images: &&BTreeMap<String, ImageData>, s: S) -> Result<S::Ok, S::Error> {
#[derive(Serialize)]
struct Entry<'a> {
hash: &'a str,
width: u32,
height: u32,
}
s.collect_seq(images.iter().map(|(hash, i)| Entry { hash, width: i.width, height: i.height }))
fn native_image_index(doc: &Document) -> Vec<craft_figcraft_format::ImageIndexEntry> {
doc.images
.iter()
.map(|(hash, image)| craft_figcraft_format::ImageIndexEntry { hash: hash.clone(), width: image.width, height: image.height })
.collect()
}
/// A serializer adapter that writes `0` in place of every NaN or infinite float. JSON has no such
@@ -452,13 +373,17 @@ impl<S: serde::ser::SerializeStructVariant> serde::ser::SerializeStructVariant f
/// Serialize the document (without images) to the JSON value stored in `document.json`.
/// NaN and infinite numbers are written as `0`.
pub fn to_json(doc: &Document) -> Result<Value, FormatError> {
DocumentJson::new(doc).serialize(Finite(serde_json::value::Serializer)).map_err(io_err)
{
let mut bytes = Vec::new();
craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), &mut bytes).map_err(io_err)?;
serde_json::from_slice(&bytes).map_err(io_err)
}
}
/// Write the document (without images) as `document.json` content to `w`.
/// NaN and infinite numbers are written as `0`.
pub fn write_json(doc: &Document, w: impl Write) -> Result<(), FormatError> {
DocumentJson::new(doc).serialize(Finite(&mut serde_json::Serializer::new(w))).map_err(io_err)
craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), w).map_err(io_err)
}
/// Parse `document.json` content.
@@ -466,109 +391,55 @@ pub fn from_json(text: &str) -> Result<(Document, Vec<String>), FormatError> {
parse_json(text).map(|(doc, issues, _)| (doc, issues))
}
/// The image hashes a `document.json` lists in its `imageIndex` (`None` without one).
type ImageIndex = Option<BTreeSet<String>>;
/// The header of a `document.json` (its format version and image index), read in a pass that
/// skips over everything else without building it.
#[derive(Default)]
struct Header {
version: Option<u64>,
images: ImageIndex,
}
impl<'de> Deserialize<'de> for Header {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct HeaderVisitor;
impl<'de> Visitor<'de> for HeaderVisitor {
type Value = Header;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a FigCraft document object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Header, A::Error> {
let mut h = Header::default();
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"version" => h.version = map.next_value::<Value>()?.as_u64(),
"imageIndex" => {
h.images = map
.next_value::<Value>()?
.as_array()
.map(|a| a.iter().filter_map(|i| i.get("hash").and_then(Value::as_str).map(str::to_string)).collect());
}
_ => {
map.next_value::<IgnoredAny>()?;
}
}
}
Ok(h)
}
}
d.deserialize_map(HeaderVisitor)
}
}
/// Parse `document.json` content; also returns its [`ImageIndex`]. The header is checked first
/// (a newer file is refused before its document is read), then the document is deserialized
/// straight from the text.
fn parse_json(text: &str) -> Result<(Document, Vec<String>, ImageIndex), FormatError> {
let corrupt = |e: serde_json::Error| FormatError::Corrupt(e.to_string());
let header: Header = serde_json::from_str(text).map_err(corrupt)?;
if let Some(ver) = header.version
&& ver > u64::from(VERSION)
{
return Err(FormatError::Newer(u32::try_from(ver).unwrap_or(u32::MAX)));
}
let mut doc: Document = serde_json::from_str(text).map_err(corrupt)?;
let (mut doc, header) = craft_figcraft_format::read_document_json::<Document>(text).map_err(|e| match e {
craft_figcraft_format::ReadDocumentError::Json(error) => FormatError::Corrupt(error.to_string()),
craft_figcraft_format::ReadDocumentError::NewerVersion(error) => FormatError::Newer(error.0),
})?;
let images = header.images.map(|hashes| hashes.into_iter().collect());
let issues = doc.validate();
if !issues.is_empty() {
doc.repair();
}
Ok((doc, issues, header.images))
Ok((doc, issues, images))
}
pub(crate) fn io_err(e: impl std::fmt::Display) -> FormatError {
FormatError::Io(e.to_string())
}
/// Add one member to the archive.
pub(crate) fn put<W: Write + Seek>(
z: &mut zip::ZipWriter<W>,
/// JSON compression for Penpot and external ZIP exporters.
pub(crate) fn json_options() -> zip::write::SimpleFileOptions {
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL))
}
/// Add one member to the native archive.
pub(crate) fn put(
z: &mut craft_figcraft_format::ArchiveWriter,
name: &str,
opts: zip::write::SimpleFileOptions,
compression: craft_figcraft_format::Compression,
bytes: &[u8],
) -> Result<(), FormatError> {
z.start_file(name, opts).map_err(io_err)?;
z.write_all(bytes).map_err(io_err)
z.add(name, bytes, compression).map_err(io_err)
}
/// `files` (name, bytes; a `/` in a name makes a folder) as one zip archive: several exports
/// delivered as a single download (#969).
pub fn zip_files<'a>(files: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Result<Vec<u8>, FormatError> {
let mut buf = std::io::Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
for (name, bytes) in files {
put(&mut z, name, zip::write::SimpleFileOptions::default(), bytes)?;
}
z.finish().map_err(io_err)?;
}
Ok(buf.into_inner())
craft_figcraft_format::write_archive(files.into_iter().map(|(name, bytes)| craft_figcraft_format::Member {
name,
bytes,
compression: craft_figcraft_format::Compression::Deflated,
}))
.map_err(io_err)
}
/// Add `doc` as a `document.json`-style member, serialized straight into the compressor.
fn put_json<W: Write + Seek>(z: &mut zip::ZipWriter<W>, name: &str, doc: &Document) -> Result<(), FormatError> {
z.start_file(name, json_options()).map_err(io_err)?;
// The serializer writes many small pieces: batch them before they reach the compressor.
let mut w = std::io::BufWriter::with_capacity(1 << 16, z);
write_json(doc, &mut w)?;
w.flush().map_err(io_err)
}
/// How JSON members are compressed. Document JSON is very repetitive: a fast level compresses it
/// nearly as well as the default one (about 15% larger) in half the time.
pub(crate) fn json_options() -> zip::write::SimpleFileOptions {
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL))
fn put_json(z: &mut craft_figcraft_format::ArchiveWriter, name: &str, doc: &Document) -> Result<(), FormatError> {
z.add_document_json(name, &FiniteValue(doc), &native_image_index(doc)).map_err(io_err)
}
/// Write a `.figcraft` archive to bytes.
@@ -588,50 +459,62 @@ pub fn save_bytes_with_history(
versions: &[Version],
branches: &[Branch],
) -> Result<Vec<u8>, FormatError> {
let mut buf = std::io::Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
put_json(&mut z, "document.json", doc)?;
// Every image once, whether the document, a version or a branch uses it.
let mut written = BTreeSet::new();
let branch_images = branches.iter().flat_map(|b| [&b.base.images, &b.head.images].into_iter().chain(b.versions.iter().map(Version::images)));
for (hash, img) in std::iter::once(&doc.images).chain(versions.iter().map(Version::images)).chain(branch_images).flatten() {
if written.insert(hash) {
put(&mut z, &format!("images/{hash}"), stored, &img.bytes)?;
}
let mut z = craft_figcraft_format::ArchiveWriter::new();
let stored = craft_figcraft_format::Compression::Stored;
put_json(&mut z, "document.json", doc)?;
// Every image once, whether the document, a version or a branch uses it.
let mut written = BTreeSet::new();
let branch_images = branches.iter().flat_map(|b| [&b.base.images, &b.head.images].into_iter().chain(b.versions.iter().map(Version::images)));
for (hash, img) in std::iter::once(&doc.images).chain(versions.iter().map(Version::images)).chain(branch_images).flatten() {
if written.insert(hash) {
put(&mut z, &format!("images/{hash}"), stored, img.bytes.as_slice())?;
}
if let Some(t) = thumbnail_png {
put(&mut z, "thumbnail.png", stored, t)?;
}
put_versions(&mut z, "versions", versions)?;
if !branches.is_empty() {
let mut ids = BTreeSet::new();
let mut index = Vec::with_capacity(branches.len());
for b in branches {
if !is_valid_version_id(&b.id) || !ids.insert(b.id.as_str()) {
return Err(FormatError::Io(format!("invalid or duplicate branch id `{}`", b.id)));
}
put_json(&mut z, &format!("branches/{}/base.json", b.id), &b.base)?;
put_json(&mut z, &format!("branches/{}/head.json", b.id), &b.head)?;
put_versions(&mut z, &format!("branches/{}/versions", b.id), &b.versions)?;
let images = |d: &Document| d.images.keys().cloned().collect::<Vec<String>>();
index.push(json!({"id": b.id, "name": b.name, "time": b.time, "client": b.client, "state": b.state,
"baseImages": images(&b.base), "headImages": images(&b.head)}));
}
put(&mut z, BRANCH_INDEX, json_options(), &serde_json::to_vec(&json!({"branches": index})).map_err(io_err)?)?;
}
if let Some(lib) = &doc.published {
library::write(&mut z, lib, &written)?;
}
z.finish().map_err(io_err)?;
}
Ok(buf.into_inner())
if let Some(t) = thumbnail_png {
put(&mut z, "thumbnail.png", stored, t)?;
}
put_versions(&mut z, "versions", versions)?;
if !branches.is_empty() {
let mut ids = BTreeSet::new();
let mut index = Vec::with_capacity(branches.len());
for b in branches {
if !is_valid_version_id(&b.id) || !ids.insert(b.id.as_str()) {
return Err(FormatError::Io(format!("invalid or duplicate branch id `{}`", b.id)));
}
put_json(&mut z, &format!("branches/{}/base.json", b.id), &b.base)?;
put_json(&mut z, &format!("branches/{}/head.json", b.id), &b.head)?;
put_versions(&mut z, &format!("branches/{}/versions", b.id), &b.versions)?;
let images = |d: &Document| d.images.keys().cloned().collect::<Vec<String>>();
index.push(NativeBranchEntry {
id: b.id.clone(),
name: b.name.clone(),
time: b.time,
client: b.client,
state: match b.state {
BranchState::Active => NativeBranchState::Active,
BranchState::Merged => NativeBranchState::Merged,
BranchState::Archived => NativeBranchState::Archived,
},
base_images: images(&b.base),
head_images: images(&b.head),
});
}
put(
&mut z,
BRANCH_INDEX,
craft_figcraft_format::Compression::Level(3),
&craft_figcraft_format::write_branch_index(&NativeBranchIndex { branches: index }).map_err(io_err)?,
)?;
}
if let Some(lib) = &doc.published {
library::write(&mut z, lib, &written)?;
}
z.finish().map_err(io_err)
}
/// Write version history `versions` (oldest first) under `dir`: `<dir>/index.json` and one
/// `<dir>/<id>.json` snapshot per version. Nothing when there are none.
fn put_versions<W: Write + Seek>(z: &mut zip::ZipWriter<W>, dir: &str, versions: &[Version]) -> Result<(), FormatError> {
fn put_versions(z: &mut craft_figcraft_format::ArchiveWriter, dir: &str, versions: &[Version]) -> Result<(), FormatError> {
if versions.is_empty() {
return Ok(());
}
@@ -644,16 +527,23 @@ fn put_versions<W: Write + Seek>(z: &mut zip::ZipWriter<W>, dir: &str, versions:
let name = format!("{dir}/{}.json", v.id);
match &v.snapshot {
Snapshot::Doc(d) => put_json(z, &name, d)?,
Snapshot::Stored { json, .. } => put(z, &name, json_options(), json)?,
Snapshot::Stored { json, .. } => put(z, &name, craft_figcraft_format::Compression::Level(3), json)?,
}
let images: Vec<&String> = v.images().keys().collect();
let mut entry = json!({"id": v.id, "name": v.name, "description": v.description, "time": v.time, "images": images});
if v.auto {
entry["auto"] = json!(true);
}
index.push(entry);
index.push(NativeVersionEntry {
id: v.id.clone(),
name: v.name.clone(),
description: v.description.clone(),
time: v.time,
auto: v.auto,
images: v.images().keys().cloned().collect(),
});
}
put(z, &format!("{dir}/index.json"), json_options(), &serde_json::to_vec(&json!({"versions": index})).map_err(io_err)?)?;
put(
z,
&format!("{dir}/index.json"),
craft_figcraft_format::Compression::Level(3),
&craft_figcraft_format::write_version_index(&NativeVersionIndex { versions: index }).map_err(io_err)?,
)?;
Ok(())
}
@@ -662,75 +552,22 @@ pub fn load_bytes(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError>
load_bytes_with_versions(bytes).map(|l| (l.doc, l.issues))
}
/// Read archive member `name`, refusing members larger than `limit` bytes.
pub(crate) fn read_member<R: Read + Seek>(z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, FormatError> {
/// Read a member from a foreign ZIP archive, refusing entries larger than `limit`.
pub(crate) fn read_member<R: Read + std::io::Seek>(z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, FormatError> {
let f = z.by_name(name).map_err(|e| FormatError::Corrupt(format!("{name}: {e}")))?;
let too_large = || FormatError::Corrupt(format!("{name} is too large"));
if f.size() > limit {
return Err(too_large());
return Err(FormatError::Corrupt(format!("{name} is too large")));
}
let mut data = Vec::new();
f.take(limit.saturating_add(1)).read_to_end(&mut data).map_err(|e| FormatError::Corrupt(format!("{name}: {e}")))?;
if data.len() as u64 > limit {
return Err(too_large());
return Err(FormatError::Corrupt(format!("{name} is too large")));
}
Ok(data)
}
/// What one file open may still unpack, every area together ([`MAX_UNPACKED`]).
pub(crate) struct Unpacked {
left: u64,
total: u64,
}
impl Unpacked {
pub(crate) fn new(total: u64) -> Self {
Self { left: total, total }
}
/// Why a member is left out once the total is spent.
fn passed(&self) -> String {
match self.total / (1024 * 1024) {
0 => format!("too large: the file's contents together pass {} bytes", self.total),
mb => format!("too large: the file's contents together pass {mb} MB"),
}
}
/// Whether member `name` (by its recorded size) needs more than is left.
fn exceeded<R: Read + Seek>(&self, z: &mut zip::ZipArchive<R>, name: &str) -> bool {
z.by_name(name).is_ok_and(|f| f.size() > self.left)
}
/// [`read_member`] within `limit` (the area's own cap) and what is left of the total, which the
/// member then uses up.
pub(crate) fn read<R: Read + Seek>(&mut self, z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, FormatError> {
if self.exceeded(z, name) && z.by_name(name).is_ok_and(|f| f.size() <= limit) {
return Err(FormatError::Corrupt(format!("{name}: {}", self.passed())));
}
let cap = limit.min(self.left);
let size = z.by_name(name).map_or(0, |f| f.size());
let data = read_member(z, name, cap);
// A read that failed part way (a bad checksum at the end, say) did its unpacking all the
// same: it is charged in full, so an index naming that member again can't repeat it. One
// refused for its recorded size before any unpacking costs nothing.
if size <= cap {
self.left = self.left.saturating_sub(data.as_ref().map_or(size, |d| d.len() as u64));
}
data
}
}
/// Largest `document.json` read from an archive of `len` bytes in which it takes `packed`.
pub(crate) fn document_limit(packed: u64, len: u64) -> u64 {
packed.min(len).saturating_mul(DOCUMENT_RATIO).clamp(MAX_MEMBER, MAX_DOCUMENT)
}
/// How many images, and how many bytes of them together, one file may give.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ImageBudget {
pub images: usize,
pub bytes: u64,
}
/// The remaining archive-wide expansion budget while the app maps native records.
pub(crate) type Unpacked = ReadBudget;
/// Read a `.figcraft` archive (or bare JSON) with its version history.
pub fn load_bytes_with_versions(bytes: &[u8]) -> Result<Loaded, FormatError> {
@@ -750,22 +587,28 @@ pub(crate) fn load_limited(bytes: &[u8], budget: ImageBudget, total: u64) -> Res
let (doc, issues) = from_json(text)?;
return Ok(Loaded { issues, ..Loaded::from(doc) });
}
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| FormatError::Corrupt(e.to_string()))?;
let packed = z.by_name("document.json").map(|f| f.compressed_size()).unwrap_or(0);
let limit = document_limit(packed, bytes.len() as u64);
let mut z =
craft_figcraft_format::Archive::open(bytes, craft_figcraft_format::ArchiveLimits { max_entries: u64::MAX, max_total_bytes: u64::MAX })
.map_err(|e| FormatError::Corrupt(e.to_string()))?;
load_archive(&mut z, budget, total, bytes.len() as u64)
}
fn load_archive(z: &mut impl craft_figcraft_format::NativeArchive, budget: ImageBudget, total: u64, archive_len: u64) -> Result<Loaded, FormatError> {
let packed = z.compressed_size("document.json").unwrap_or(0);
let limit = document_limit(packed, archive_len);
let mut unpacked = Unpacked::new(total);
let text = String::from_utf8(unpacked.read(&mut z, "document.json", limit)?).map_err(|e| FormatError::Corrupt(e.to_string()))?;
let text = String::from_utf8(unpacked.read(z, "document.json", limit)?).map_err(|e| FormatError::Corrupt(e.to_string()))?;
let (mut doc, mut issues, own_images) = parse_json(&text)?;
let ImagesRead { images, unread, past_budget } = read_images(&mut z, own_images.as_ref(), budget, &mut unpacked);
let ImagesRead { images, unread, past_budget } = read_images(z, own_images.as_ref(), budget, &mut unpacked);
report_lost_images(&mut issues, &unread, &past_budget, own_images.as_ref(), &images);
let images_past_budget = past_budget.len();
match library::read(&mut z, &images, &mut unpacked) {
match library::read(z, &images, &mut unpacked) {
Ok(lib) => doc.published = lib.map(Arc::new),
Err(e) => issues.push(format!("the published library was skipped: {e}")),
}
let mut budget = MAX_VERSION_BYTES;
let versions = read_versions(&mut z, "versions", &images, &mut issues, &mut budget, &mut unpacked);
let branches = read_branches(&mut z, &images, &mut issues, &mut unpacked);
let versions = read_versions(z, "versions", &images, &mut issues, &mut budget, &mut unpacked);
let branches = read_branches(z, &images, &mut issues, &mut unpacked);
// Images only the version history or branches use stay with them.
let branch_images =
branches.iter().flat_map(|b| b.base.images.keys().chain(b.head.images.keys()).chain(b.versions.iter().flat_map(|v| v.images().keys())));
@@ -782,13 +625,14 @@ pub(crate) fn load_limited(bytes: &[u8], budget: ImageBudget, total: u64) -> Res
/// The archive's `images/` members by hash, within `budget`, and the ones that couldn't be read
/// with why. The document's own images (`own`) are read first, so a file past the budget loses
/// the images only its history uses before its own.
fn read_images<R: Read + Seek>(
z: &mut zip::ZipArchive<R>,
fn read_images(
z: &mut impl craft_figcraft_format::NativeArchive,
own: Option<&BTreeSet<String>>,
budget: ImageBudget,
unpacked: &mut Unpacked,
) -> ImagesRead {
let mut hashes: Vec<String> = z.file_names().filter_map(|n| n.strip_prefix("images/")).filter(|h| !h.is_empty()).map(str::to_string).collect();
let mut hashes: Vec<String> =
z.names().into_iter().filter_map(|n| n.strip_prefix("images/").map(str::to_owned)).filter(|h| !h.is_empty()).collect();
hashes.sort_by_key(|h| !own.is_some_and(|o| o.contains(h)));
let mut images = BTreeMap::new();
let mut unread = Vec::new();
@@ -809,7 +653,7 @@ fn read_images<R: Read + Seek>(
unread.push((hash, FormatError::Corrupt(format!("the file has more than {} images", budget.images))));
continue;
}
if z.by_name(&name).is_ok_and(|f| f.size() > left) {
if z.declared_size(&name).is_some_and(|size| size > left) {
let mb = budget.bytes / (1024 * 1024);
past_budget.insert(hash.clone());
unread.push((hash, FormatError::Corrupt(format!("the file's images together pass {mb} MB"))));
@@ -817,9 +661,9 @@ fn read_images<R: Read + Seek>(
}
// Past the file's total, an image is left out as one past the images' own budget: it stays
// in the file, which can't then be saved over without losing it (#1313).
if unpacked.exceeded(z, &name) {
if unpacked.exceeds_remaining(z, &name) {
past_budget.insert(hash.clone());
unread.push((hash, FormatError::Corrupt(unpacked.passed())));
unread.push((hash, FormatError::Corrupt(unpacked.exhausted_message())));
continue;
}
match unpacked.read(z, &name, left.min(MAX_MEMBER)) {
@@ -880,8 +724,8 @@ fn report_lost_images(
/// The version history kept under `dir` in an archive (none when it has no index), reading at
/// most `budget` bytes of snapshots. Damaged entries are skipped and reported in `issues`; nothing
/// here fails the load.
fn read_versions<R: Read + Seek>(
z: &mut zip::ZipArchive<R>,
fn read_versions(
z: &mut impl craft_figcraft_format::NativeArchive,
dir: &str,
images: &BTreeMap<String, ImageData>,
issues: &mut Vec<String>,
@@ -889,12 +733,12 @@ fn read_versions<R: Read + Seek>(
unpacked: &mut Unpacked,
) -> Vec<Version> {
let index_name = format!("{dir}/index.json");
if z.index_for_name(&index_name).is_none() {
if !z.contains(&index_name) {
return Vec::new();
}
let index = match unpacked
.read(z, &index_name, MAX_VERSION_INDEX)
.and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|e| FormatError::Corrupt(e.to_string())))
.and_then(|b| craft_figcraft_format::read_version_index(&b).map_err(|e| FormatError::Corrupt(e.to_string())))
{
Ok(v) => v,
Err(e) => {
@@ -902,14 +746,13 @@ fn read_versions<R: Read + Seek>(
return Vec::new();
}
};
let entries = index.get("versions").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let mut out: Vec<Version> = Vec::new();
for e in entries {
for e in index.versions {
if out.len() >= MAX_VERSIONS {
issues.push(format!("only the first {MAX_VERSIONS} versions were kept"));
break;
}
let id = e.get("id").and_then(Value::as_str).unwrap_or_default();
let id = e.id.as_str();
if !is_valid_version_id(id) || out.iter().any(|v| v.id == id) {
issues.push("a version with an invalid id was skipped".into());
continue;
@@ -922,21 +765,13 @@ fn read_versions<R: Read + Seek>(
}
};
*budget = budget.saturating_sub(json.len() as u64);
let text = |k: &str, max: usize| e.get(k).and_then(Value::as_str).map(|s| clip(s, max)).unwrap_or_default();
let images = e
.get("images")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.filter_map(|h| images.get(h).map(|i| (h.to_string(), i.clone())))
.collect();
let images = e.images.iter().filter_map(|h| images.get(h).map(|i| (h.clone(), i.clone()))).collect();
out.push(Version {
id: id.to_string(),
name: text("name", MAX_VERSION_NAME),
description: text("description", MAX_VERSION_DESCRIPTION),
time: e.get("time").and_then(Value::as_u64).unwrap_or(0),
auto: e.get("auto").and_then(Value::as_bool).unwrap_or(false),
name: clip(&e.name, MAX_VERSION_NAME),
description: clip(&e.description, MAX_VERSION_DESCRIPTION),
time: e.time,
auto: e.auto,
snapshot: Snapshot::Stored { json: Arc::new(json), images },
});
}
@@ -945,18 +780,18 @@ fn read_versions<R: Read + Seek>(
/// The branches of an archive (none when it has no index), parsed. Damaged entries are skipped and
/// reported in `issues`; nothing here fails the load.
fn read_branches<R: Read + Seek>(
z: &mut zip::ZipArchive<R>,
fn read_branches(
z: &mut impl craft_figcraft_format::NativeArchive,
images: &BTreeMap<String, ImageData>,
issues: &mut Vec<String>,
unpacked: &mut Unpacked,
) -> Vec<Branch> {
if z.index_for_name(BRANCH_INDEX).is_none() {
if !z.contains(BRANCH_INDEX) {
return Vec::new();
}
let index = match unpacked
.read(z, BRANCH_INDEX, MAX_VERSION_INDEX)
.and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|e| FormatError::Corrupt(e.to_string())))
.and_then(|b| craft_figcraft_format::read_branch_index(&b).map_err(|e| FormatError::Corrupt(e.to_string())))
{
Ok(v) => v,
Err(e) => {
@@ -964,28 +799,26 @@ fn read_branches<R: Read + Seek>(
return Vec::new();
}
};
let entries = index.get("branches").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let mut out: Vec<Branch> = Vec::new();
let mut budget = MAX_VERSION_BYTES;
for e in entries {
for e in index.branches {
if out.len() >= MAX_BRANCHES {
issues.push(format!("only the first {MAX_BRANCHES} branches were kept"));
break;
}
let id = e.get("id").and_then(Value::as_str).unwrap_or_default();
let id = e.id.as_str();
if !is_valid_version_id(id) || out.iter().any(|b| b.id == id) {
issues.push("a branch with an invalid id was skipped".into());
continue;
}
let mut snapshot = |part: &str, list: &str| -> Result<Arc<Document>, FormatError> {
let mut snapshot = |part: &str, hashes: &[String]| -> Result<Arc<Document>, FormatError> {
let json = unpacked.read(z, &format!("branches/{id}/{part}.json"), budget.min(MAX_MEMBER))?;
budget = budget.saturating_sub(json.len() as u64);
let (mut doc, _) = from_json(std::str::from_utf8(&json).map_err(|e| FormatError::Corrupt(e.to_string()))?)?;
let hashes = e.get(list).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
doc.images = hashes.filter_map(|h| images.get(h).map(|i| (h.to_string(), i.clone()))).collect();
doc.images = hashes.iter().filter_map(|h| images.get(h).map(|i| (h.clone(), i.clone()))).collect();
Ok(Arc::new(doc))
};
let (base, head) = match (snapshot("base", "baseImages"), snapshot("head", "headImages")) {
let (base, head) = match (snapshot("base", &e.base_images), snapshot("head", &e.head_images)) {
(Ok(b), Ok(h)) => (b, h),
(Err(err), _) | (_, Err(err)) => {
issues.push(format!("branch `{id}` was skipped: {err}"));
@@ -994,10 +827,14 @@ fn read_branches<R: Read + Seek>(
};
out.push(Branch {
id: id.to_string(),
name: e.get("name").and_then(Value::as_str).map(|s| clip(s, MAX_VERSION_NAME)).unwrap_or_default(),
time: e.get("time").and_then(Value::as_u64).unwrap_or(0),
client: e.get("client").and_then(Value::as_u64).and_then(|c| u32::try_from(c).ok()).unwrap_or(0),
state: e.get("state").and_then(|s| BranchState::deserialize(s).ok()).unwrap_or(BranchState::Active),
name: clip(&e.name, MAX_VERSION_NAME),
time: e.time,
client: e.client,
state: match e.state {
NativeBranchState::Active => BranchState::Active,
NativeBranchState::Merged => BranchState::Merged,
NativeBranchState::Archived => BranchState::Archived,
},
versions: read_versions(z, &format!("branches/{id}/versions"), images, issues, &mut budget, unpacked),
base,
head,
@@ -1062,8 +899,29 @@ pub fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Resul
#[cfg(not(target_arch = "wasm32"))]
pub fn load_file(path: &std::path::Path) -> Result<(Document, Vec<String>), FormatError> {
let bytes = std::fs::read(path).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?;
load_bytes(&bytes)
let mut file = std::fs::File::open(path).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?;
let archive_len = file.metadata().map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?.len();
let mut first = None;
let mut chunk = [0u8; 8192];
loop {
let count = file.read(&mut chunk).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?;
if count == 0 {
break;
}
if let Some(byte) = chunk[..count].iter().copied().find(|byte| !byte.is_ascii_whitespace()) {
first = Some(byte);
break;
}
}
file.seek(SeekFrom::Start(0)).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?;
if first == Some(b'{') {
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?;
return load_bytes(&bytes);
}
let mut archive = craft_figcraft_format::SeekArchive::open(file, u64::MAX).map_err(|e| FormatError::Corrupt(e.to_string()))?;
let loaded = load_archive(&mut archive, IMAGE_BUDGET, MAX_UNPACKED, archive_len)?;
Ok((loaded.doc, loaded.issues))
}
#[cfg(test)]
@@ -1081,6 +939,8 @@ mod large_tests;
#[cfg(test)]
mod staging_tests;
#[cfg(test)]
mod streaming_tests;
#[cfg(test)]
mod thumbnail_tests;
#[cfg(test)]
mod unpacked_total_tests;
+104 -46
View File
@@ -10,24 +10,22 @@
//! so a missing, damaged or oversized library file is an error, never a crash.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek, Write};
use std::io::{Read, Seek};
use std::sync::Arc;
use figcraft_doc::{ImageData, LibraryManifest, NodeKind, PublishedLibrary, used_images};
use figcraft_doc::{
ImageData, LibraryAsset, LibraryCollection, LibraryManifest, LibraryStyle, LibraryVariable, NodeId, NodeKind, PublishedLibrary, used_images,
};
use crate::{FormatError, MAX_MEMBER, Unpacked, from_json, image_data, io_err, json_options, put, put_json};
use crate::{FormatError, MAX_MEMBER, Unpacked, from_json, image_data, io_err};
const MANIFEST: &str = "library/manifest.json";
const SNAPSHOT: &str = "library/document.json";
const IMAGES: &str = "library/images/";
/// Largest manifest read.
const MAX_MANIFEST: u64 = 16 * 1024 * 1024;
/// Most bytes of images read for one library.
const MAX_IMAGE_BYTES: u64 = 1024 * 1024 * 1024;
/// Longest library id and name kept.
const MAX_ID: usize = 64;
const MAX_NAME: usize = 200;
const MAX_DESCRIPTION: usize = 2000;
use craft_figcraft_format::library as native;
// Test helpers use these names when constructing deliberately bounded archive entries.
#[cfg(test)]
const MANIFEST: &str = native::MANIFEST;
#[cfg(test)]
const MAX_MANIFEST: u64 = native::MAX_MANIFEST_BYTES;
fn corrupt(e: impl std::fmt::Display) -> FormatError {
FormatError::Corrupt(e.to_string())
@@ -35,52 +33,112 @@ fn corrupt(e: impl std::fmt::Display) -> FormatError {
/// Whether `id` can be a library id: 1–64 ASCII letters, digits, `-` and `_`.
pub fn is_valid_library_id(id: &str) -> bool {
(1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
native::is_valid_id(id)
}
fn to_native_manifest(m: &LibraryManifest) -> native::Manifest {
native::Manifest {
id: m.id.clone(),
name: m.name.clone(),
version: m.version,
description: m.description.clone(),
time: m.time,
components: m
.components
.iter()
.map(|a| native::Component { id: a.id.0, name: a.name.clone(), set: a.set, version: a.version, published: a.published })
.collect(),
styles: m
.styles
.iter()
.map(|s| native::Style { id: s.id.clone(), name: s.name.clone(), kind: s.kind.clone(), version: s.version, published: s.published })
.collect(),
collections: m
.collections
.iter()
.map(|c| native::Collection { id: c.id.clone(), name: c.name.clone(), version: c.version, published: c.published })
.collect(),
variables: m
.variables
.iter()
.map(|v| native::Variable {
id: v.id.clone(),
name: v.name.clone(),
collection: v.collection.clone(),
kind: v.kind.clone(),
version: v.version,
published: v.published,
})
.collect(),
}
}
fn from_native_manifest(m: native::Manifest) -> LibraryManifest {
LibraryManifest {
id: m.id,
name: m.name,
version: m.version,
description: m.description,
time: m.time,
components: m
.components
.into_iter()
.map(|a| LibraryAsset { id: NodeId(a.id), name: a.name, set: a.set, version: a.version, published: a.published })
.collect(),
styles: m
.styles
.into_iter()
.map(|s| LibraryStyle { id: s.id, name: s.name, kind: s.kind, version: s.version, published: s.published })
.collect(),
collections: m
.collections
.into_iter()
.map(|c| LibraryCollection { id: c.id, name: c.name, version: c.version, published: c.published })
.collect(),
variables: m
.variables
.into_iter()
.map(|v| LibraryVariable { id: v.id, name: v.name, collection: v.collection, kind: v.kind, version: v.version, published: v.published })
.collect(),
}
}
/// Write the published library's entries. `written` are the images already in `images/`.
pub(crate) fn write<W: Write + Seek>(z: &mut zip::ZipWriter<W>, lib: &PublishedLibrary, written: &BTreeSet<&String>) -> Result<(), FormatError> {
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
put(z, MANIFEST, json_options(), &serde_json::to_vec(&lib.manifest).map_err(io_err)?)?;
put_json(z, SNAPSHOT, &lib.doc)?;
for (hash, img) in &lib.doc.images {
if !written.contains(hash) && ImageData::is_valid_key(hash) {
put(z, &format!("{IMAGES}{hash}"), stored, &img.bytes)?;
}
}
Ok(())
pub(crate) fn write(z: &mut craft_figcraft_format::ArchiveWriter, lib: &PublishedLibrary, written: &BTreeSet<&String>) -> Result<(), FormatError> {
let already_written = written.iter().map(|hash| (*hash).clone()).collect();
let images = lib.doc.images.iter().map(|(hash, image)| (hash.as_str(), image.bytes.as_slice()));
native::write_members(
z,
&to_native_manifest(&lib.manifest),
&crate::FiniteValue(&lib.doc),
&crate::native_image_index(&lib.doc),
&already_written,
images,
)
.map_err(io_err)
}
/// The published library in an archive (`None` when the file was never published). `own` are
/// the images already read from `images/`; what it unpacks comes out of `unpacked` (beyond the
/// per-part caps).
pub(crate) fn read<R: Read + Seek>(
z: &mut zip::ZipArchive<R>,
pub(crate) fn read(
z: &mut impl craft_figcraft_format::NativeArchive,
own: &BTreeMap<String, ImageData>,
unpacked: &mut Unpacked,
) -> Result<Option<PublishedLibrary>, FormatError> {
if z.index_for_name(MANIFEST).is_none() {
if !z.contains(native::MANIFEST) {
return Ok(None);
}
let mut manifest: LibraryManifest = serde_json::from_slice(&unpacked.read(z, MANIFEST, MAX_MANIFEST)?).map_err(corrupt)?;
let wire_manifest = native::read_manifest(&unpacked.read(z, native::MANIFEST, native::MAX_MANIFEST_BYTES)?).map_err(corrupt)?;
let mut manifest = from_native_manifest(wire_manifest);
if !is_valid_library_id(&manifest.id) {
return Err(corrupt("the library has an invalid id"));
}
let text = String::from_utf8(unpacked.read(z, SNAPSHOT, MAX_MEMBER)?).map_err(corrupt)?;
let mut budget = MAX_IMAGE_BYTES;
let text = String::from_utf8(unpacked.read(z, native::DOCUMENT, MAX_MEMBER)?).map_err(corrupt)?;
let (mut doc, _) = from_json(&text)?;
for hash in used_images(&doc) {
if !ImageData::is_valid_key(&hash) {
continue;
}
if let Some(img) = own.get(&hash) {
doc.images.insert(hash, img.clone());
continue;
}
let name = [format!("{IMAGES}{hash}"), format!("images/{hash}")].into_iter().find(|n| z.index_for_name(n).is_some());
// A missing or oversized image shows as a placeholder, like in any other file.
let Some(data) = name.and_then(|n| unpacked.read(z, &n, budget.min(MAX_MEMBER)).ok()) else { continue };
budget = budget.saturating_sub(data.len() as u64);
let available: BTreeSet<String> = own.keys().cloned().collect();
let images = native::read_image_resources(z, used_images(&doc), &available, unpacked);
for (hash, data) in images {
doc.images.insert(hash, image_data(data));
}
// Keep what the snapshot really holds; clip what people see.
@@ -92,8 +150,8 @@ pub(crate) fn read<R: Read + Seek>(
manifest.styles.retain(|s| styles.contains(s.id.as_str()));
manifest.collections.retain(|c| collections.contains(c.id.as_str()));
manifest.variables.retain(|v| variables.contains(&(v.id.as_str(), v.collection.as_str())));
manifest.name = manifest.name.chars().take(MAX_NAME).collect();
manifest.description = manifest.description.chars().take(MAX_DESCRIPTION).collect();
manifest.name = native::clip_display(&manifest.name, native::MAX_NAME_CHARS);
manifest.description = native::clip_display(&manifest.description, native::MAX_DESCRIPTION_CHARS);
Ok(Some(PublishedLibrary { manifest, doc: Arc::new(doc) }))
}
@@ -107,7 +165,7 @@ pub fn read_library<R: Read + Seek>(r: R) -> Result<Option<PublishedLibrary>, Fo
/// archive that would unpack to more is refused, or loses the images past it), for libraries from
/// people the reader doesn't trust (a server).
pub fn read_library_within<R: Read + Seek>(r: R, max_bytes: u64) -> Result<Option<PublishedLibrary>, FormatError> {
let mut z = zip::ZipArchive::new(r).map_err(corrupt)?;
let mut z = craft_figcraft_format::SeekArchive::open(r, u64::MAX).map_err(corrupt)?;
read(&mut z, &BTreeMap::new(), &mut Unpacked::new(max_bytes))
}
+8 -43
View File
@@ -61,18 +61,18 @@ pub use variables::export as export_variables;
pub const MAX_NODES: usize = 200_000;
/// Deepest layer nesting followed.
const MAX_DEPTH: usize = 256;
/// Private .fig provenance, consumed only by the `.fig` import ([`import_with_networks`]).
pub(crate) const FIG_SOURCE_FIELD: &str = "_figSource";
/// Hidden .fig library context; accepted only by the `.fig` import ([`import_with_networks`]).
pub(crate) const FIG_LIBRARY_CONTEXTS_FIELD: &str = "_figLibraryContexts";
/// Ids of mains in a `.fig` file that its layer cap kept out; read only by the `.fig` import.
pub(crate) const FIG_CAPPED_MAINS_FIELD: &str = "_figCappedMains";
/// The `.fig` mapping's private handoffs, read only by the `.fig` import ([`import_with_networks`]).
pub(crate) use craft_fig::rest::{FIG_CAPPED_MAINS_FIELD, FIG_LIBRARY_CONTEXTS_FIELD, FIG_SOURCE_FIELD};
/// Longest SVG path string read from one geometry entry.
const MAX_PATH_BYTES: usize = 4 << 20;
/// Most path elements in one vector.
const MAX_PATH_ELEMENTS: usize = 200_000;
/// Most distinct warnings reported.
pub(crate) const MAX_WARNINGS: usize = 200;
#[cfg(test)]
pub(crate) use craft_figma_rest::MAX_WARNINGS;
/// Distinct warnings in first-seen order, with repeat counts (at most 200). The
/// import report reads the `(×n)` suffix off before it looks the note up in the catalogue, so a
/// counted note is still translated (`ui-egui`'s `note_text`).
pub(crate) use craft_figma_rest::Warnings;
/// Most shared style definitions read.
const MAX_STYLES: usize = 10_000;
/// Image key used for image fills without an `imageRef`.
@@ -348,41 +348,6 @@ fn children(v: &Value) -> &[Value] {
v.get("children").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default()
}
/// Distinct warnings in first-seen order, with repeat counts. Shared with the `.fig` mapper
/// (`crate::fig::map`), whose notes repeat per layer in the same way.
#[derive(Default)]
pub(crate) struct Warnings {
list: Vec<(String, usize)>,
index: BTreeMap<String, usize>,
}
impl Warnings {
pub(crate) fn add(&mut self, msg: String) {
if let Some(i) = self.index.get(&msg) {
if let Some(e) = self.list.get_mut(*i) {
e.1 += 1;
}
} else if self.list.len() < MAX_WARNINGS {
self.index.insert(msg.clone(), self.list.len());
self.list.push((msg, 1));
}
}
/// The notes met so far, without their counts, for the tests that ask whether one was met
/// (the product reads them through [`Self::finish`], with the counts).
#[cfg(test)]
pub(crate) fn seen(&self) -> impl Iterator<Item = &str> {
self.list.iter().map(|(msg, _)| msg.as_str())
}
/// The notes, each with `(×n)` after it where it was met more than once. The import report
/// reads that suffix off before it looks the note up in the catalogue, so a counted note is
/// still translated (`ui-egui`'s `note_text`).
pub(crate) fn finish(self) -> Vec<String> {
self.list.into_iter().map(|(m, n)| if n > 1 { format!("{m} (×{n})") } else { m }).collect()
}
}
/// The coordinate spaces a child is placed in: its parent's (`world`) and that of the nearest
/// ancestor that is not a group or boolean (`frame`), both relative to the page.
#[derive(Clone, Copy)]
+64
View File
@@ -0,0 +1,64 @@
//! The seekable on-disk reader uses the same format and recovery behavior as the byte reader.
#![cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
use figcraft_doc::{Document, NodeKind};
use super::*;
fn png(red: u8) -> Vec<u8> {
let image = image::RgbaImage::from_pixel(2, 2, image::Rgba([red, 0, 0, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
bytes
}
#[test]
fn seekable_reader_matches_byte_reader_for_history_and_branch_archives() {
let mut document = Document::new("Current");
let current_image = add_image(&mut document, png(10)).unwrap().0;
let mut older = Document::new("Older");
let old_image = add_image(&mut older, png(20)).unwrap().0;
let version = Version::new("v1", "Before", "", 1, Arc::new(older.clone()));
let mut head = document.clone();
let page = head.first_page().unwrap();
head.create(page, NodeKind::Rectangle, "Branch shape", 1.0, 2.0, 3.0, 4.0).unwrap();
add_image(&mut head, png(30)).unwrap();
let branch = Branch {
id: "b1".into(),
name: "Explore".into(),
time: 2,
client: 4,
state: BranchState::Active,
base: Arc::new(document.clone()),
versions: vec![Version::new("v2", "Branch base", "", 3, Arc::new(document.clone()))],
head: Arc::new(head),
};
let bytes = save_bytes_with_history(&document, None, &[version], &[branch]).unwrap();
let from_bytes = load_bytes_with_versions(&bytes).unwrap();
assert_eq!(from_bytes.versions.len(), 1);
assert_eq!(from_bytes.branches.len(), 1);
assert!(from_bytes.doc.images.contains_key(&current_image));
assert!(from_bytes.versions[0].images().contains_key(&old_image));
let path = std::env::temp_dir().join(format!("figcraft-stream-reader-{}.figcraft", std::process::id()));
std::fs::write(&path, &bytes).unwrap();
let from_file = load_file(&path).unwrap();
let _ = std::fs::remove_file(&path);
assert_eq!(from_file, (from_bytes.doc, from_bytes.issues));
}
#[test]
fn seekable_reader_keeps_newer_document_error_precedence() {
let bytes = crate::zip_files([("document.json", br#"{"version":999,"document":["malformed"]}"#.as_slice())]).unwrap();
let path = std::env::temp_dir().join(format!("figcraft-stream-newer-{}.figcraft", std::process::id()));
std::fs::write(&path, bytes).unwrap();
let result = load_file(&path);
let _ = std::fs::remove_file(&path);
assert!(matches!(result, Err(FormatError::Newer(999))));
}
+16 -27
View File
@@ -7,13 +7,12 @@ use std::io::{Read, Seek};
use std::path::Path;
/// Largest `thumbnail.png` read from an archive.
pub const MAX_THUMBNAIL_BYTES: u64 = 8 * 1024 * 1024;
pub const MAX_THUMBNAIL_BYTES: u64 = craft_figcraft_format::MAX_PREVIEW_THUMBNAIL_BYTES;
/// Largest image file read as its own picture.
pub const MAX_IMAGE_FILE_BYTES: u64 = 32 * 1024 * 1024;
/// Widest or tallest picture decoded (pixels); a larger one gives none.
pub const MAX_THUMBNAIL_SIDE: u32 = 8192;
/// Largest `document.json` read for its page colour, and `.fig` `meta.json`.
const MAX_DOCUMENT_BYTES: u64 = 64 * 1024 * 1024;
/// Largest `.fig` `meta.json` read for its page colour.
const MAX_META_BYTES: u64 = 1024 * 1024;
/// Most memory one decode may take.
const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024;
@@ -29,8 +28,7 @@ pub struct Thumbnail {
/// The bytes of `thumbnail.png` in a zip archive (`.figcraft`, `.fig`); `None` when it isn't a zip,
/// has no thumbnail, or the thumbnail is larger than [`MAX_THUMBNAIL_BYTES`].
pub fn thumbnail_png<R: Read + Seek>(archive: R) -> Option<Vec<u8>> {
let mut z = zip::ZipArchive::new(archive).ok()?;
crate::read_member(&mut z, "thumbnail.png", MAX_THUMBNAIL_BYTES).ok()
craft_figcraft_format::read_preview_thumbnail(archive).ok().flatten()
}
/// The bytes of `previews/preview.png` in a `.sketch` zip; `None` as [`thumbnail_png`] gives it.
@@ -148,35 +146,26 @@ pub fn file_preview(path: &Path, fit: u32) -> Preview {
/// The [`Preview`] of a `.figcraft` or `.fig` archive: `thumbnail.png`, and the first page's colour
/// from `document.json` (`.figcraft`) or `meta.json` (`.fig`).
pub fn archive_preview<R: Read + Seek>(archive: R, fit: u32) -> Preview {
let Ok(mut z) = zip::ZipArchive::new(archive) else { return Preview::default() };
let picture = crate::read_member(&mut z, "thumbnail.png", MAX_THUMBNAIL_BYTES).ok().and_then(|png| decode_thumbnail(&png, fit));
let (page, kind) = if z.file_names().any(|n| n == "document.json") {
crate::read_member(&mut z, "document.json", MAX_DOCUMENT_BYTES).ok().map(|json| figcraft_page(&json)).unwrap_or_default()
let Ok(mut z) = craft_figcraft_format::SeekArchive::open(archive, u64::MAX) else { return Preview::default() };
let native = craft_figcraft_format::read_preview_archive_from(&mut z);
let picture = native.thumbnail_png.and_then(|png| decode_thumbnail(&png, fit));
let (page, kind) = if native.has_document {
native.document.as_ref().map(figcraft_page).unwrap_or_default()
} else {
(crate::read_member(&mut z, "meta.json", MAX_META_BYTES).ok().and_then(|json| fig_page(&json)), figcraft_doc::FileKind::Design)
let meta = z.read("meta.json", MAX_META_BYTES).ok().flatten();
(meta.as_deref().and_then(fig_page), figcraft_doc::FileKind::Design)
};
Preview { page, picture, kind }
}
/// The first page's background in a `.figcraft` `document.json`, and the file's kind.
fn figcraft_page(json: &[u8]) -> (Option<[f32; 4]>, figcraft_doc::FileKind) {
#[derive(serde::Deserialize)]
struct Head {
#[serde(default)]
pages: Vec<u64>,
#[serde(default)]
nodes: std::collections::BTreeMap<String, Node>,
#[serde(default)]
kind: figcraft_doc::FileKind,
}
#[derive(serde::Deserialize)]
struct Node {
#[serde(default)]
background: Option<serde_json::Value>,
}
let Ok(head) = serde_json::from_slice::<Head>(json) else { return (None, figcraft_doc::FileKind::Design) };
fn figcraft_page(head: &craft_figcraft_format::PreviewDocument) -> (Option<[f32; 4]>, figcraft_doc::FileKind) {
let page = head.pages.first().and_then(|first| head.nodes.get(&first.to_string())).and_then(|n| n.background.as_ref()).and_then(rgba);
(page, head.kind)
let kind = match head.kind {
craft_figcraft_format::PreviewKind::Design => figcraft_doc::FileKind::Design,
craft_figcraft_format::PreviewKind::Board => figcraft_doc::FileKind::Board,
};
(page, kind)
}
/// The canvas colour a `.fig` file's `meta.json` gives (`client_meta.background_color`).
+2 -2
View File
@@ -108,8 +108,8 @@ fn a_read_that_fails_part_way_still_spends_the_total() {
let mut bytes = buf.into_inner();
let at = 30 + "snapshots/v1.json".len() + body.len() / 2;
bytes[at] ^= 0xff;
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let size = z.by_name("snapshots/v1.json").unwrap().size();
let mut z = craft_figcraft_format::SeekArchive::open(std::io::Cursor::new(bytes), u64::MAX).unwrap();
let size = z.declared_size("snapshots/v1.json").unwrap();
assert_eq!(size, body.len() as u64);
let mut total = crate::Unpacked::new(size + size / 2);
assert!(total.read(&mut z, "snapshots/v1.json", 1 << 20).is_err(), "the damaged member fails");
+1 -1
View File
@@ -1739,7 +1739,7 @@ status = "draft — needs native review"
"duplicate grid track sizing entries use equal tracks" = "duplirani unosi veličina traka mreže koriste jednake trake"
"e.g. count + 1" = "npr. count + 1"
"e.g. count >= 3 and not done" = "npr. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "kutni i zakrivljeni konektori bez sačuvane putanje slijede FigCraftovo vlastito usmjeravanje"
"elbowed and curved connectors without a saved path are routed afresh" = "kutni i zakrivljeni konektori bez sačuvane putanje slijede FigCraftovo vlastito usmjeravanje"
"entries without a node type were skipped" = "unosi bez vrste čvora su preskočeni"
"figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft:// linkovi iz preglednika, chata ili e-pošte otvaraju ovu aplikaciju i pridružuju se sesiji."
"from {server}" = "sa servera {server}"
+1 -1
View File
@@ -1948,7 +1948,7 @@ status = "draft — needs native review"
"Your unsaved files were too large for the browser to keep." = "Ihre ungespeicherten Dateien waren zu groß, als dass der Browser sie behalten konnte."
"Z to A" = "Z bis A"
"connector labels without a saved snapshot are centred on the line, without their background" = "Verbinder-Beschriftungen ohne gespeicherten Schnappschuss werden mittig auf der Linie und ohne Hintergrund dargestellt"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "Abgewinkelte und gebogene Verbinder ohne gespeicherten Pfad folgen dem eigenen Routing von FigCraft"
"elbowed and curved connectors without a saved path are routed afresh" = "Abgewinkelte und gebogene Verbinder ohne gespeicherten Pfad folgen dem eigenen Routing von FigCraft"
"instance swap properties whose default component was past the layer limit were skipped" = "Instanztausch-Eigenschaften, deren Standardkomponente über dem Ebenenlimit lag, wurden übersprungen"
"instances whose component was past the layer limit were imported as frames" = "Instanzen, deren Komponente über dem Ebenenlimit lag, wurden als Rahmen importiert"
"invalid vector region fill paint list; layer fill used" = "Ungültige Füllungsliste der Vektorregion; Füllung der Ebene verwendet"
+5 -2
View File
@@ -21,6 +21,7 @@ name = "English"
"A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "A collection of this file with these modes and variables: override their values per mode and add variables of its own"
"A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "A .figcraft file with this name already exists. Choose its full name to confirm replacement."
"A later vote" = "A later vote"
"A layer in an auto layout frame is placed by its frame" = "A layer in an auto layout frame is placed by its frame"
"A layer on its own aligns to its frame: select more layers, or one in a frame" = "A layer on its own aligns to its frame: select more layers, or one in a frame"
"A responsive product page: hero, features, figures, a quote and a footer" = "A responsive product page: hero, features, figures, a quote and a footer"
"A spring plays until it settles: its mass, stiffness and damping set how long" = "A spring plays until it settles: its mass, stiffness and damping set how long"
@@ -1404,6 +1405,7 @@ name = "English"
"Server for online sharing" = "Server for online sharing"
"Server key" = "Server key"
"Set as default" = "Set as default"
"Set as opening page" = "Set as opening page"
"Set corner smoothing to 60%" = "Set corner smoothing to 60%"
"Set variable" = "Set variable"
"Set variable mode" = "Set variable mode"
@@ -1628,6 +1630,7 @@ name = "English"
"This version can't be read." = "This version can't be read."
"This version doesn't have it: all of it is new." = "This version doesn't have it: all of it is new."
"Tidy up" = "Tidy up"
"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Select a row, a column or a full grid of three or more layers, outside an auto layout flow"
"Tile" = "Tile"
"Tile type" = "Tile type"
"Timer" = "Timer"
@@ -1820,7 +1823,7 @@ name = "English"
"duplicate grid track sizing entries use equal tracks" = "duplicate grid track sizing entries use equal tracks"
"e.g. count + 1" = "e.g. count + 1"
"e.g. count >= 3 and not done" = "e.g. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "elbowed and curved connectors without a saved path follow FigCraft's own routing"
"elbowed and curved connectors without a saved path are routed afresh" = "elbowed and curved connectors without a saved path are routed afresh"
"entries without a node type were skipped" = "entries without a node type were skipped"
"figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft:// links from a browser, chat or email open this app and join the session."
"from {server}" = "from {server}"
@@ -1889,7 +1892,6 @@ name = "English"
"set-variable actions without a value were skipped" = "set-variable actions without a value were skipped"
"set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped"
"shape generated outline is missing or damaged; using its rectangle" = "shape generated outline is missing or damaged; using its rectangle"
"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text"
"slot content assignment target is missing or is not slot content" = "slot content assignment target is missing or is not slot content"
"slot content assignment uses the empty GUID sentinel and was skipped" = "slot content assignment uses the empty GUID sentinel and was skipped"
"slot layers without a matching slot property were imported as frames" = "slot layers without a matching slot property were imported as frames"
@@ -1899,6 +1901,7 @@ name = "English"
"stars and polygons without point counts or geometry use the default point count" = "stars and polygons without point counts or geometry use the default point count"
"sticky layers import as frames with their text" = "sticky layers import as frames with their text"
"style settings of some vector segments aren't supported; those segments use the layer's stroke" = "style settings of some vector segments aren't supported; those segments use the layer's stroke"
"swapped instances whose previous component isn't in the file took the new component's look" = "swapped instances whose previous component isn't in the file took the new component's look"
"text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered"
"text style overrides refer to missing table entries" = "text style overrides refer to missing table entries"
"the file has no pages" = "the file has no pages"
+1 -1
View File
@@ -1789,7 +1789,7 @@ status = "draft — needs native review"
"duplicate grid track sizing entries use equal tracks" = "päällekkäiset ruudukon kokomääritykset käyttävät tasakokoisia osia"
"e.g. count + 1" = "esim. count + 1"
"e.g. count >= 3 and not done" = "esim. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "kulmikkaat ja kaarevat yhdistimet, joilla ei ole tallennettua polkua, seuraavat FigCraftin omaa reititystä"
"elbowed and curved connectors without a saved path are routed afresh" = "kulmikkaat ja kaarevat yhdistimet, joilla ei ole tallennettua polkua, seuraavat FigCraftin omaa reititystä"
"entries without a node type were skipped" = "kohteet, joilta puuttuu solmutyyppi, ohitettiin"
"figcraft:// links from a browser, chat or email open this app and join the session." = "selaimen, keskustelun tai sähköpostin figcraft://-linkit avaavat tämän sovelluksen ja liittyvät istuntoon."
"from {server}" = "palvelimelta {server}"
+1 -1
View File
@@ -1783,7 +1783,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv
"duplicate grid track sizing entries use equal tracks" = "ბადის ტრეკის ზომის დუბლირებული ჩანაწერებისას ტრეკები თანაბარია"
"e.g. count + 1" = "მაგ. count + 1"
"e.g. count >= 3 and not done" = "მაგ. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "შენახული ტრაექტორიის გარეშე კუთხოვანი და მრუდი შემაერთებლები FigCraft-ის საკუთარ მარშრუტს მიჰყვება"
"elbowed and curved connectors without a saved path are routed afresh" = "შენახული ტრაექტორიის გარეშე კუთხოვანი და მრუდი შემაერთებლები FigCraft-ის საკუთარ მარშრუტს მიჰყვება"
"entries without a node type were skipped" = "კვანძის ტიპის გარეშე ჩანაწერები გამოტოვებულია"
"figcraft:// links from a browser, chat or email open this app and join the session." = "ბრაუზერიდან, ჩატიდან ან ელფოსტიდან figcraft:// ბმულები ხსნის ამ აპს და უერთდება სესიას."
"from {server}" = "წყარო: {server}"
+1 -1
View File
@@ -1810,7 +1810,7 @@ name = "Svenska"
"duplicate grid track sizing entries use equal tracks" = "dubbla storleksposter för rutnätsspår använder lika stora spår"
"e.g. count + 1" = "t.ex. count + 1"
"e.g. count >= 3 and not done" = "t.ex. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "vinklade och böjda kopplingar utan sparad bana följer FigCrafts egen dragning"
"elbowed and curved connectors without a saved path are routed afresh" = "vinklade och böjda kopplingar utan sparad bana följer FigCrafts egen dragning"
"entries without a node type were skipped" = "poster utan nodtyp hoppades över"
"figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft://-länkar från en webbläsare, chatt eller e-post öppnar den här appen och ansluter till sessionen."
"from {server}" = "från {server}"
+1 -1
View File
@@ -1811,7 +1811,7 @@ status = "draft — needs native review"
"duplicate grid track sizing entries use equal tracks" = "நகல் கட்ட டிராக் அளவு உள்ளீடுகள் சம டிராக்குகளைப் பயன்படுத்தும்"
"e.g. count + 1" = "எ.கா. count + 1"
"e.g. count >= 3 and not done" = "எ.கா. count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "சேமித்த பாதை இல்லாத வளைந்த மற்றும் மடிந்த கனெக்டர்கள் FigCraft-இன் சொந்த வழித்தடத்தைப் பின்பற்றும்"
"elbowed and curved connectors without a saved path are routed afresh" = "சேமித்த பாதை இல்லாத வளைந்த மற்றும் மடிந்த கனெக்டர்கள் FigCraft-இன் சொந்த வழித்தடத்தைப் பின்பற்றும்"
"entries without a node type were skipped" = "நோட் வகை இல்லாத உள்ளீடுகள் தவிர்க்கப்பட்டன"
"figcraft:// links from a browser, chat or email open this app and join the session." = "உலாவி, அரட்டை அல்லது மின்னஞ்சலில் உள்ள figcraft:// இணைப்புகள் இந்த ஆப்ஸைத் திறந்து அமர்வில் சேர்க்கும்."
"from {server}" = "{server} இலிருந்து"
+1 -1
View File
@@ -1779,7 +1779,7 @@ status = "draft — needs native review"
"duplicate grid track sizing entries use equal tracks" = "重複的格線軌道大小項目會使用相等軌道"
"e.g. count + 1" = "例如 count + 1"
"e.g. count >= 3 and not done" = "例如 count >= 3 and not done"
"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "沒有儲存路徑的肘形與曲線連接線會採用 FigCraft 自己的路徑規劃"
"elbowed and curved connectors without a saved path are routed afresh" = "沒有儲存路徑的肘形與曲線連接線會採用 FigCraft 自己的路徑規劃"
"entries without a node type were skipped" = "已略過沒有節點類型的項目"
"figcraft:// links from a browser, chat or email open this app and join the session." = "來自瀏覽器、聊天或電子郵件的 figcraft:// 連結會開啟此應用程式並加入工作階段。"
"from {server}" = "來自 {server}"
+12
View File
@@ -995,6 +995,18 @@ pub fn disabled(resp: &Response) {
node(resp, "", |n| n.set_disabled());
}
/// `resp`'s node also says `text` (a menu row's state, e.g. "locked"), after any description
/// already set (joined with ", ").
pub fn describe(resp: &Response, text: &str) {
node(resp, "", |n| {
let d = match n.description() {
Some(old) if !old.is_empty() => format!("{old}, {text}"),
_ => text.to_string(),
};
n.set_description(d);
});
}
/// What a layer row says besides its name.
pub struct RowInfo<'a> {
/// The layer's type ("Frame", "Text").
+7
View File
@@ -206,6 +206,13 @@ pub fn gradient_dragging(ctx: &egui::Context) -> bool {
matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Gradient { .. }))
}
/// Whether the open image fill's crop (its handles, or a drag on the image) is being dragged, the
/// press that starts it included: the open colour picker holds that paint in Crop mode, so the
/// press is its own control, not one outside it that would close it and commit the drag (#2307).
pub fn crop_dragging(ctx: &egui::Context) -> bool {
matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Crop { .. }))
}
/// Whether the document has a gesture open: a handle drag edits only inside its own.
fn gesture_open(app: &FigApp) -> bool {
app.session.ds().is_ok_and(|d| d.interaction.is_some())
+5 -1
View File
@@ -398,7 +398,11 @@ fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) {
app.canvas.pressure = None;
}
app.canvas.last_pointer = Some(Point::new(ev.x, ev.y));
if let Err(e) = app.session.pointer(&ev) {
// A gesture something else committed under the held button (a colour picker closing on this
// press) leaves the rest of its drag with nothing to edit: that is not worth saying.
if let Err(e) = app.session.pointer(&ev)
&& !matches!(e, figcraft_engine::EngineError::NoGesture)
{
app.toast(e.to_string());
}
app.canvas.last_hover = hover.then(|| HoverKey::of(app, ev));
+1
View File
@@ -701,6 +701,7 @@ fn shape_overlay(app: &FigApp, painter: &egui::Painter, col: Color32) {
let text = match hint.handle {
ShapeHandle::Radius { .. } => format!("{} {}", tr("Radius"), hint.value),
ShapeHandle::Ratio => format!("{} {}%", tr("Ratio"), hint.value),
ShapeHandle::Count => format!("{} {}", tr("Count"), hint.value),
};
pill(painter, c + vec2(12.0, 12.0), Align2::LEFT_TOP, text, col);
}
@@ -237,3 +237,18 @@ fn the_gesture_start_stands_in_only_while_the_selection_is_only_moved() {
app.session.ds_mut().unwrap().selection.pop();
assert!(crate::selection_cache::moved(app.session.ds().unwrap()).is_none());
}
#[test]
fn the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow() {
let mut s = Session::new();
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap());
let kid = id(s.execute("shape.rectangle", &json!({"parent": f, "x": 0, "y": 0, "width": 20, "height": 20})).unwrap());
s.execute("node.set", &json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0}})).unwrap();
s.execute("select.set", &json!({"ids": [kid]})).unwrap();
let app = FigApp::new(s, Box::new(NoServices));
let ctx = Context::default();
let ds = app.session.ds().unwrap();
let pv = crate::right::position_values(&ctx, &ds.doc.clone(), &ds.selection.clone());
assert!(!pv.can_align, "Align is greyed out");
assert!(pv.align_blocked, "and the tip says the frame places the layer");
}
+99
View File
@@ -127,3 +127,102 @@ fn copying_a_link_from_a_frames_name_label_links_that_frame() {
crate::menus::invoke(&mut u.app, "edit.copyLink");
assert_eq!(copied.lock().unwrap().last().cloned(), Some(format!("figcraft://node/{}", a.0)));
}
/// Two overlapping rectangles, the upper one locked; the menu opens on the overlap with nothing
/// selected. Returns the app's UI and the ids (lower, locked).
fn overlap_ui() -> (Ui, figcraft_doc::NodeId, figcraft_doc::NodeId) {
let mut s = Session::new();
let lower = id(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 80, "name": "Lower"})).unwrap());
let upper = id(&s.execute("shape.rectangle", &json!({"x": 120, "y": 120, "width": 80, "height": 80, "name": "Upper"})).unwrap());
s.execute("object.toggleLock", &json!({"ids": [upper], "locked": true})).unwrap();
let mut u = Ui::new(s);
u.frame(vec![]);
(u, lower, upper)
}
/// Measured in Figma's web app, 2026-11-10 (Lock and unlock layers: locked layers are listed in Select layer).
#[test]
fn select_layer_marks_locked_layers_with_a_padlock_and_picks_them() {
let (mut u, lower, upper) = overlap_ui();
let at = u.app.to_screen(150.0, 150.0);
crate::canvas::open_context_menu(&mut u.app, at, false);
u.app.session.set_selection(vec![]);
crate::menus::open_select_layer(&u.ctx, true);
u.frame(vec![]);
let shapes = flat(&u.frame_output(vec![]).shapes);
// The Layers panel lists the same names; the menu's rows are the right-most copies.
let menu_row = |name: &str| {
let (_, pos, size) = crate::live_tests::texts(&shapes)
.into_iter()
.filter(|(t, _, _)| t == name)
.max_by(|a, b| a.1.x.total_cmp(&b.1.x))
.unwrap_or_else(|| panic!("no row {name:?}"));
(pos, size)
};
let (lower_at, upper_at) = (menu_row("Lower"), menu_row("Upper"));
assert!(lower_at.0.x > 300.0 && upper_at.0.x > 300.0, "both layers are listed in the menu");
let in_leading = |(pos, size): (Pos2, egui::Vec2)| {
let c = pos + size / 2.0;
shapes
.iter()
.filter(|s| !matches!(s, egui::Shape::Text(_)))
.filter(|s| {
let r = s.visual_bounding_rect();
r.is_positive()
&& (r.center().y - c.y).abs() < 8.0
&& r.max.x < c.x - size.x / 2.0 - 4.0
&& r.min.x > c.x - size.x / 2.0 - 40.0
&& r.width() < 20.0
})
.count()
};
assert!(in_leading(upper_at) > 0, "the locked row has a padlock in its leading column");
assert_eq!(in_leading(lower_at), 0, "the other row has nothing there");
let p = upper_at.0 + upper_at.1 / 2.0;
for pressed in [true, false] {
u.frame(vec![
egui::Event::PointerMoved(p),
egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
]);
}
assert_eq!(u.app.session.selection(), vec![upper], "picking the locked row selects it");
let _ = lower;
}
/// The padlock is only paint: the locked row says "locked" to assistive technology too.
#[test]
fn select_layer_locked_row_is_described_as_locked() {
let (mut u, _, _) = overlap_ui();
let at = u.app.to_screen(150.0, 150.0);
crate::canvas::open_context_menu(&mut u.app, at, false);
u.app.session.set_selection(vec![]);
crate::menus::open_select_layer(&u.ctx, true);
u.ctx.enable_accesskit();
u.frame(vec![]);
let nodes: Vec<egui::accesskit::Node> =
u.frame_output(vec![]).platform_output.accesskit_update.expect("an AccessKit update").nodes.into_iter().map(|(_, n)| n).collect();
let row = |name: &str| {
nodes
.iter()
.find(|n| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some(name))
.unwrap_or_else(|| panic!("no menu row {name:?}"))
};
assert!(row("Upper").description().is_some_and(|d| d.contains("locked")), "the locked row says locked");
assert!(!row("Lower").description().is_some_and(|d| d.contains("locked")), "the other row doesn't");
}
/// Measured on a single locked layer only (Figma's web app, 2026-11-10): the least certain rule.
#[test]
fn select_layer_needs_more_than_one_layer_under_the_pointer() {
let (mut u, _, _) = overlap_ui();
let one = u.app.to_screen(105.0, 105.0);
crate::canvas::open_context_menu(&mut u.app, one, false);
u.frame(vec![]);
let shapes = flat(&u.frame_output(vec![]).shapes);
assert!(!has_text(&shapes, "Select layer"), "one layer under the pointer: no Select layer");
let two = u.app.to_screen(150.0, 150.0);
crate::canvas::open_context_menu(&mut u.app, two, false);
u.frame(vec![]);
let shapes = flat(&u.frame_output(vec![]).shapes);
assert!(has_text(&shapes, "Select layer"), "two layers: it shows");
}
+50
View File
@@ -194,6 +194,56 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() {
assert!((scaled[0] - after[0] * 5.0 / 6.0).abs() < 1e-6 && (scaled[3] - after[3] * 5.0 / 6.0).abs() < 1e-6, "{after:?} -> {scaled:?}");
}
/// The reporter's sequence (#2307): the colour picker open on an image fill held in Crop mode
/// (Crop chosen in its mode dropdown, or reopened on a fill that already is), then a press on the
/// layer and a drag. The drag moves the picture inside the layer (its crop), not the layer, the
/// press doesn't close the picker under it, and no internal gesture message reaches the user.
#[test]
fn crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_layer() {
let (mut u, layer, _) = setup();
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
for _ in 0..4 {
u.frame(vec![]);
}
choose_mode(&mut u, "Fill", "Crop");
// Crop mode on the canvas ended (a click away from the image); the picker opens on the Crop fill.
u.app.ui.crop = None;
u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] });
for _ in 0..4 {
u.frame(vec![]);
}
let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") };
let at = u.app.session.doc().unwrap().node(layer).unwrap().transform.as_coeffs();
let from = u.app.to_screen(100.0, 50.0);
u.drag_to(from, from + vec2(30.0, 10.0));
u.frame(vec![]);
u.button(from + vec2(30.0, 10.0), false);
let n = u.app.session.doc().unwrap().node(layer).unwrap().clone();
assert_eq!(n.transform.as_coeffs(), at, "the layer stays where it is");
assert_eq!((n.width, n.height), (200.0, 100.0), "and keeps its size");
let (m, Some(after)) = mode(&u, layer) else { panic!("a crop") };
assert_eq!(m, ImageScaleMode::Crop);
assert_ne!(after, before, "the drag moved the picture inside the layer");
assert_eq!(u.app.session.selection(), vec![layer]);
assert!(u.app.ui.toast.as_ref().is_none_or(|(t, _)| !t.contains("gesture")), "no internal gesture message: {:?}", u.app.ui.toast);
}
/// A drag the colour picker's close committed under the held button (a press on a layer closing
/// the picker) leaves the rest of its drag with no gesture: that says nothing to the user.
#[test]
fn a_drag_whose_gesture_was_committed_under_the_button_shows_no_message() {
let (mut u, layer, _) = setup();
u.app.run("select.set", json!({"ids": [layer]}));
let from = u.app.to_screen(100.0, 50.0);
u.button(from, true);
u.app.session.commit_interaction().unwrap();
for k in 1..=10 {
u.frame(vec![Event::PointerMoved(from + vec2(3.0, 1.0) * k as f32)]);
}
u.button(from + vec2(30.0, 10.0), false);
assert!(u.app.ui.toast.is_none(), "no message: {:?}", u.app.ui.toast);
}
/// The first paint, an image, of `id`'s fills (`fills`) or strokes, or of region `region` of a vector.
fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option<usize>) -> figcraft_color::ImagePaint {
let n = u.app.session.doc().unwrap().node(id).unwrap();
+71 -11
View File
@@ -594,23 +594,40 @@ fn group_rows(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
}
}
/// Rename the last part of group `g` of a collection (its variables `members`) to `new`: every
/// variable under it moves along (one undo step).
fn rename_group(app: &mut FigApp, members: &[&Variable], g: &str, new: &str, st: &mut Editor) {
let new = new.trim().replace('/', "-");
/// What renaming group `g` (of the variables `members`) to `new` does: the group's new path and
/// each moved variable's (id, new name). `new` replaces the group's last part; a `/` in it nests
/// the group, as in Figma ("Palette/Orange" puts it in a group Palette, made if there is none).
/// Each part is trimmed and empty parts are dropped. The renames come deepest name first, so a
/// variable moving into the group's own new path ("Orange" to "Orange/Warm") never takes a name
/// another moved variable still holds. None when nothing changes.
fn group_renames(members: &[&Variable], g: &str, new: &str) -> Option<(String, Vec<(String, String)>)> {
let new = new.split('/').map(str::trim).filter(|p| !p.is_empty()).collect::<Vec<_>>().join("/");
if new.is_empty() {
return;
return None;
}
let renamed = match g.rsplit_once('/') {
Some((parent, _)) => format!("{parent}/{new}"),
None => new,
};
if renamed == g {
return None;
}
let prefix = format!("{g}/");
let mut moved: Vec<(&Variable, &str)> = members.iter().filter_map(|v| Some((*v, v.name.strip_prefix(&prefix)?))).collect();
// A longer name can only be one a shorter one moves to: rename those out of the way first.
moved.sort_by_key(|(_, rest)| std::cmp::Reverse(rest.len()));
Some((renamed.clone(), moved.into_iter().map(|(v, rest)| (v.id.clone(), format!("{renamed}/{rest}"))).collect()))
}
/// Rename group `g` of a collection (its variables `members`) to `new` (see [`group_renames`]):
/// every variable under it moves along, in one undo step.
fn rename_group(app: &mut FigApp, members: &[&Variable], g: &str, new: &str, st: &mut Editor) {
let Some((renamed, moves)) = group_renames(members, g, new) else {
return;
};
let steps: Vec<serde_json::Value> =
moves.iter().map(|(id, name)| json!({"command": "variable.update", "params": {"variable": id, "name": name}})).collect();
let prefix = format!("{g}/");
let steps: Vec<serde_json::Value> = members
.iter()
.filter(|v| v.name.starts_with(&prefix))
.map(|v| json!({"command": "variable.update", "params": {"variable": v.id, "name": format!("{renamed}/{}", &v.name[prefix.len()..])}}))
.collect();
if app.run("command.batch", json!({"label": "Rename group", "commands": steps})).is_some()
&& st.group.as_deref().is_some_and(|s| s == g || s.starts_with(&prefix))
{
@@ -1308,7 +1325,7 @@ fn bulk_details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Edit
#[cfg(test)]
mod tests {
use super::{groups, tri};
use super::{group_renames, groups, tri};
#[test]
fn tri_is_checked_empty_or_mixed() {
@@ -1330,4 +1347,47 @@ mod tests {
assert_eq!(groups(names.into_iter()), ["color", "color/brand", "space"]);
assert!(groups(["a", "b"].into_iter()).is_empty());
}
/// The renames of group `g` among `names` (numbers in one collection) typed as `new`, by name.
fn renames(names: &[&str], g: &str, new: &str) -> Option<(String, Vec<(String, String)>)> {
let mut s = figcraft_engine::Session::new();
s.execute("variable.createCollection", &serde_json::json!({"name": "Theme"})).unwrap();
for n in names {
s.execute("variable.create", &serde_json::json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
}
let vars = &s.doc().unwrap().variables.variables;
let members: Vec<_> = vars.iter().collect();
let (renamed, moves) = group_renames(&members, g, new)?;
let by_name = |id: &str| vars.iter().find(|v| v.id == id).unwrap().name.clone();
Some((renamed, moves.into_iter().map(|(id, n)| (by_name(&id), n)).collect()))
}
#[test]
fn a_slash_in_a_group_rename_nests_the_group_keeping_its_parent() {
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
assert_eq!(
renames(&["Orange/100", "Orange/200", "Blue/100"], "Orange", "Palette/Orange"),
Some(("Palette/Orange".into(), vec![pair("Orange/100", "Palette/Orange/100"), pair("Orange/200", "Palette/Orange/200")]))
);
assert_eq!(
renames(&["a/b/x"], "a/b", " / Warm // c / "),
Some(("a/Warm/c".into(), vec![pair("a/b/x", "a/Warm/c/x")])),
"parts are trimmed, empty parts dropped, and the parent stays"
);
}
#[test]
fn a_group_rename_to_nothing_or_to_itself_does_nothing() {
for new in ["", " ", "/", " / // ", "Orange", " Orange ", "/Orange/"] {
assert_eq!(renames(&["Orange/100"], "Orange", new), None, "{new:?}");
}
assert_eq!(renames(&["a/b/x"], "a/b", "b/"), None);
}
#[test]
fn a_group_moved_into_its_own_subgroup_renames_the_deeper_names_first() {
let (_, moves) = renames(&["Orange/100", "Orange/Warm/100"], "Orange", "Orange/Warm").unwrap();
let order: Vec<&str> = moves.iter().map(|(old, _)| old.as_str()).collect();
assert_eq!(order, ["Orange/Warm/100", "Orange/100"]);
}
}
+5 -4
View File
@@ -941,7 +941,7 @@ fn enter_in_another_field_after_tab_keeps_the_scale_tool() {
assert_eq!(u.app.session.tool.tool, figcraft_engine::ToolId::Scale);
}
/// K, 2, Enter: 100 x 100 becomes 200 x 200 about the panel's origin, the tool is Move, one undo step.
/// K, 2, Enter: 100 x 100 becomes 200 x 200 about the panel's origin (the centre), the tool is Move, one undo step.
#[test]
fn k_two_enter_scales_the_selection_by_two() {
let (mut u, r) = scale_setup();
@@ -951,8 +951,8 @@ fn k_two_enter_scales_the_selection_by_two() {
u.frame(vec![Event::Text("2".to_string())]);
key(&mut u, Key::Enter, Modifiers::NONE);
u.frame(vec![]);
// About the panel's origin, FigCraft's top-left default (Figma's grid starts at the centre).
assert_eq!(geom(&u, r), (0.0, 0.0, 200.0, 200.0));
// About the panel's origin, which starts at the centre as Figma's grid does.
assert_eq!(geom(&u, r), (-50.0, -50.0, 200.0, 200.0));
assert!(!scale_field_focused(&u), "the field let go of the keyboard");
assert_eq!(u.app.session.tool.tool, figcraft_engine::ToolId::Move);
assert_eq!(u.app.session.ds().unwrap().selection, vec![r]);
@@ -971,7 +971,8 @@ fn the_scale_field_takes_2x_and_1_5() {
u.frame(vec![Event::Text(text.to_string())]);
key(&mut u, Key::Enter, Modifiers::NONE);
u.frame(vec![]);
assert_eq!(geom(&u, r), (0.0, 0.0, size, size), "{text}");
let at = 50.0 - size / 2.0;
assert_eq!(geom(&u, r), (at, at, size, size), "{text}");
}
}
+21
View File
@@ -204,9 +204,30 @@ fn importer_notes() -> BTreeSet<String> {
keys.extend(literals(&std::fs::read_to_string(&path).unwrap(), &["warn("]));
}
}
// The `.fig` mapping itself is craft-fig's (`craft_fig::rest`); its notes are ours to translate.
let rest = craft_fig_src().join("rest");
for path in sources(&rest).into_iter().chain([rest.with_extension("rs")]) {
if !path.file_name().unwrap().to_string_lossy().contains("tests") {
keys.extend(literals(&std::fs::read_to_string(&path).unwrap(), &["warn("]));
}
}
keys
}
/// The `src` directory of the craft-fig sources this build uses, as Cargo resolved them.
fn craft_fig_src() -> std::path::PathBuf {
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
let out = std::process::Command::new(cargo)
.args(["metadata", "--format-version", "1", "--offline"])
.current_dir(env!("CARGO_MANIFEST_DIR"))
.output()
.unwrap();
assert!(out.status.success(), "cargo metadata: {}", String::from_utf8_lossy(&out.stderr));
let meta: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
let package = meta["packages"].as_array().unwrap().iter().find(|p| p["name"] == "craft-fig").expect("craft-fig is a dependency");
std::path::Path::new(package["manifest_path"].as_str().unwrap()).parent().unwrap().join("src")
}
/// The lookup functions whose first argument is a catalog key.
const LOOKUPS: &[&str] = &["tr(", "trf(", "trn(", "tr_noop("];
@@ -643,6 +643,50 @@ fn the_page_menus_rename_starts_with_the_keyboard_in_the_name() {
assert_clicking_page_opens_it(&mut u, p2, p1, r2);
}
/// Right-clicks `at` in the pages list and returns the menu's "Set as opening page" item, if shown.
fn opening_item(u: &mut Ui, at: Pos2) -> Option<Pos2> {
u.frame(vec![
Event::PointerMoved(at),
Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
]);
u.frame(vec![Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]);
let shapes: Vec<egui::Shape> = u.frame_output(vec![]).shapes.into_iter().map(|c| c.shape).collect();
crate::live_tests::has_text(&shapes, "Set as opening page").then(|| crate::live_tests::text_center(&shapes, "Set as opening page"))
}
/// The pages list's menu offers "Set as opening page" on a page and not on a divider, and using it
/// writes the document's opening page without moving the viewer's own page (#1817).
#[test]
fn the_page_menu_sets_the_opening_page_and_not_on_dividers() {
let mut s = Session::new();
let p1 = s.page().unwrap();
let p2 = id(s.execute("page.add", &json!({})).unwrap());
let div = id(s.execute("page.add", &json!({"name": "-"})).unwrap());
s.execute("page.move", &json!({"id": div, "index": 1})).unwrap();
s.execute("page.select", &json!({"id": p1})).unwrap();
let mut u = Ui::new(s);
let (r1, r2) = (page_row(&mut u, p1, p2), page_row(&mut u, p2, p1));
let mid = Pos2::new(r1.x, (r1.y + r2.y) / 2.0);
u.app.session.execute("page.select", &json!({"id": p1})).unwrap();
u.frame(vec![]);
assert_eq!(opening_item(&mut u, mid), None, "a divider has no such item");
u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
for _ in 0..5 {
u.frame(vec![]);
}
let item = opening_item(&mut u, r2).expect("a page has the item (and its menu is open)");
assert_ne!(u.app.session.doc().unwrap().current_page, Some(p2), "not the opening page yet");
u.frame(vec![Event::PointerMoved(item)]);
u.button(item, true);
u.button(item, false);
for _ in 0..3 {
u.frame(vec![]);
}
assert_eq!(u.app.session.doc().unwrap().current_page, Some(p2), "the document's opening page is the clicked page");
assert_eq!(u.app.session.page().unwrap(), p1, "the viewer's own page stays");
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
}
/// The y of the line between the pages and the layers, above the layers' row at `layer` (found by
/// the resize cursor it shows when hovered).
fn pages_edge_at(u: &mut Ui, layer: f32) -> f32 {
@@ -841,3 +885,100 @@ fn search_fields_keep_their_text_in_the_middle() {
let off = off_centre(&mut u, "Search assets");
assert!(off < 1.0, "Search assets is {off} points off the middle");
}
/// The centre of `id`'s icon, a top-level row: the row's left edge is the first point from the
/// left at which the pointer is over it, and the icon's centre is 8 (margin) + 4 + 22 points
/// further right.
fn icon_of(u: &mut Ui, id: NodeId) -> Pos2 {
let y = u.row_at(id).y;
let mut left = None;
for x in 0..150 {
let p = Pos2::new(x as f32, y);
u.app.session.ds_mut().unwrap().hover = None;
u.frame(vec![Event::PointerMoved(p)]);
if u.app.session.ds().unwrap().hover == Some(id) {
left = Some(x as f32);
break;
}
}
Pos2::new(left.expect("the row has a left edge") + 34.0, y)
}
/// Measured in Figma's web app, 2026-11-12: a double-click on a layer's icon zooms the canvas to
/// the layer and starts no rename (a double-click on the name renames, as before).
#[test]
fn a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming() {
let mut s = Session::new();
rect(&mut s, "near", 0.0, None);
let far = rect(&mut s, "far", 3000.0, None);
s.execute("select.none", &json!({})).unwrap();
let mut u = Ui::new(s);
u.frame(vec![]);
let icon = icon_of(&mut u, far);
let view = |u: &Ui| {
let v = &u.app.session.ds().unwrap().view;
(v.cx, v.cy, v.zoom)
};
let before = view(&u);
for _ in 0..2 {
u.button(icon, true);
u.button(icon, false);
}
u.frame(vec![]);
assert_eq!(u.app.ui.rename, None, "a double-click on the icon renames nothing");
assert_eq!(u.app.session.selection(), vec![far], "the layer is selected");
let after = view(&u);
assert_ne!(after, before, "the view moved");
u.app.session.execute("view.set", &json!({"cx": before.0, "cy": before.1, "zoom": before.2})).unwrap();
u.app.session.execute("view.zoomSelection", &json!({})).unwrap();
assert_eq!(after, view(&u), "the view frames the layer, as view.zoomSelection does");
}
/// A double-click's release is also a click on the row; with Ctrl held it must not toggle the layer
/// back out of the selection the zoom just made, nor can Shift restore a range.
#[test]
fn an_icon_double_click_keeps_its_selection_when_a_modifier_is_held() {
let mut s = Session::new();
rect(&mut s, "near", 0.0, None);
let far = rect(&mut s, "far", 3000.0, None);
s.execute("select.none", &json!({})).unwrap();
let mut u = Ui::new(s);
u.frame(vec![]);
let icon = icon_of(&mut u, far);
let before = (u.app.session.ds().unwrap().view.cx, u.app.session.ds().unwrap().view.zoom);
for _ in 0..2 {
for pressed in [true, false] {
let e = Event::PointerButton { pos: icon, button: egui::PointerButton::Primary, pressed, modifiers: CMD };
u.frame_with(vec![Event::PointerMoved(icon), e], CMD);
}
}
u.frame(vec![]);
assert_eq!(u.app.session.selection(), vec![far], "the layer stays selected");
assert_eq!(u.app.ui.rename, None);
let v = &u.app.session.ds().unwrap().view;
assert_ne!((v.cx, v.zoom), before, "the view frames the layer");
}
/// A Shift-double-click on an icon leaves just that layer selected, and it becomes the anchor: the
/// next Shift-click selects the range from it, not a toggle.
#[test]
fn an_icon_double_click_becomes_the_range_anchor() {
let (mut u, [a, b, c, d]) = four();
u.frame(vec![]);
let a_row = u.row_at(a);
click(&mut u, a_row, Modifiers::NONE);
let icon = icon_of(&mut u, b);
for _ in 0..2 {
for pressed in [true, false] {
let e = Event::PointerButton { pos: icon, button: egui::PointerButton::Primary, pressed, modifiers: SHIFT };
u.frame_with(vec![Event::PointerMoved(icon), e], SHIFT);
}
}
for _ in 0..30 {
u.frame(vec![]);
}
assert_eq!(u.app.session.selection(), vec![b], "the icon's layer is all that is selected");
let d_row = u.row_at(d);
click(&mut u, d_row, SHIFT);
assert_eq!(sorted(u.app.session.selection()), sorted(vec![b, c, d]), "the range from the icon's layer");
}
+2
View File
@@ -278,6 +278,8 @@ mod text_link_tests;
#[cfg(test)]
mod text_mixed_fill_tests;
#[cfg(test)]
mod tidy_tests;
#[cfg(test)]
mod titlebar_tests;
#[cfg(test)]
mod ui_params_tests;
+15 -8
View File
@@ -15,7 +15,8 @@ pub fn open_select_layer(ctx: &egui::Context, open: bool) {
}
/// The context menu's "Select layer" submenu (right-click on the canvas): every layer under the
/// click, nested ones indented, the selected ones checked. Returns whether one was picked.
/// click (locked ones with a padlock), nested ones indented, the selected ones checked; shown
/// only with more than one layer under the pointer. Returns whether one was picked.
pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2, t: &Tokens) -> bool {
if !app.canvas.rect.contains(pos) {
return false;
@@ -23,15 +24,21 @@ pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2,
let p = app.to_page(pos);
let Ok(ds) = app.session.ds() else { return false };
let tol = 2.0 / ds.view.zoom.max(1e-6);
let layers: Vec<(figcraft_doc::NodeId, usize, String)> =
figcraft_doc::geometry::layers_at(&ds.doc, ds.page, p, tol, Some(&figcraft_engine::booleans::result_outline(&ds.doc, &ds.selection)))
let opts = figcraft_doc::geometry::HitOpts { locked: true };
let layers: Vec<(figcraft_doc::NodeId, usize, String, bool)> = {
let result = figcraft_engine::booleans::result_outline(&ds.doc, &ds.selection);
figcraft_doc::geometry::layers_at_opts(&ds.doc, ds.page, p, tol, Some(&result), opts)
.into_iter()
.take(40)
.filter_map(|(id, depth)| {
ds.doc.node(id).map(|n| (id, depth, if n.name.is_empty() { n.kind.type_name().to_lowercase() } else { n.name.clone() }))
ds.doc.node(id).map(|n| {
let name = if n.name.is_empty() { n.kind.type_name().to_lowercase() } else { n.name.clone() };
(id, depth, name, figcraft_engine::tools::locked_in(&ds.doc, id))
})
})
.collect();
if layers.is_empty() {
.collect()
};
if layers.len() < 2 {
return false;
}
let sel = ds.selection.clone();
@@ -40,8 +47,8 @@ pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2,
SubmenuOptions { area: Id::unique("ctx_select_layer"), key: SELECT_LAYER, label: tr("Select layer"), gap: 4.0, constrain: true, tokens: t },
|ui| {
let mut picked = None;
for (id, depth, name) in &layers {
if indented_item(ui, name, "", true, sel.contains(id), 12.0 * (*depth).min(8) as f32, t) {
for (id, depth, name, locked) in &layers {
if indented_item(ui, name, "", true, sel.contains(id), *locked, 12.0 * (*depth).min(8) as f32, t) {
picked = Some(*id);
}
}
+10 -3
View File
@@ -395,17 +395,22 @@ fn need_width(ui: &Ui, w: f32) {
}
pub(crate) fn item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, t: &Tokens) -> bool {
indented_item(ui, label, shortcut, enabled, checked, 0.0, t)
indented_item(ui, label, shortcut, enabled, checked, false, 0.0, t)
}
/// A menu row whose label starts `indent` pixels further in (nested layers).
pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, indent: f32, t: &Tokens) -> bool {
/// A menu row whose label starts `indent` pixels further in (nested layers); `locked` paints a
/// padlock in the leading column (a checked row shows the check instead).
#[allow(clippy::too_many_arguments)]
pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, locked: bool, indent: f32, t: &Tokens) -> bool {
let w = ui.available_width();
let (r, resp) = ui.allocate_exact_size(vec2(w, 28.0), Sense::click());
a11y::menu_item(&resp, label, shortcut, checked.then_some(true));
if !enabled {
a11y::disabled(&resp);
}
if locked {
a11y::describe(&resp, i18n::tr("locked"));
}
// The keyboard's item is highlighted like the hovered one.
a11y::own_focus(&resp);
let hov = plain_row_hover(ui, &resp) && enabled;
@@ -415,6 +420,8 @@ pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: b
let col = if enabled { t.menu_text } else { t.menu_dim };
if checked {
icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 12.0, r.center().y), vec2(12.0, 12.0)), Icon::Check, col);
} else if locked {
icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 12.0, r.center().y), vec2(12.0, 12.0)), Icon::Lock, col);
}
let galley = ui.painter().layout_no_wrap(label.to_string(), regular(12.0), col);
let keys = (!shortcut.is_empty())
+24 -3
View File
@@ -333,6 +333,13 @@ fn pages(app: &mut FigApp, ui: &mut Ui) {
}
ui.close();
}
// The page the file opens on, for everyone (#1817); a divider can't be one.
if !divider && ui.button(tr("Set as opening page")).clicked() {
if !crate::menus::dev_mode_refuses(app, "page.setOpening") {
app.run("page.setOpening", json!({"id": id}));
}
ui.close();
}
if ui.button(tr("Delete page")).clicked() {
if !crate::menus::dev_mode_refuses(app, "page.delete") {
delete_page(app, id);
@@ -1241,7 +1248,8 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
let icon = node_icon(&doc, row.id);
let shown = n.visible && !row.dimmed;
let icon_col = row_color(&t, is_comp || icon == Icon::Slot, shown, t.icon, t.text_tertiary);
icons::paint(ui.painter(), Rect::from_center_size(pos2(x0 + 22.0, r.center().y), vec2(14.0, 14.0)), icon, icon_col);
let icon_rect = Rect::from_center_size(pos2(x0 + 22.0, r.center().y), vec2(14.0, 14.0));
icons::paint(ui.painter(), icon_rect, icon, icon_col);
let name_x = x0 + 36.0;
if app.ui.rename.is_some_and(|rn| rn.id == row.id) {
if let Some(new) = rename_field(app, ui, row.id, row.depth, &n.name, r) {
@@ -1262,8 +1270,21 @@ fn layers(app: &mut FigApp, ui: &mut Ui) {
if resp.clicked() {
clicked = Some((row.id, ui.input(|i| i.modifiers)));
}
if resp.double_clicked() && !crate::menus::dev_mode_refuses(app, "object.rename") {
app.ui.rename = Some(Rename { id: row.id, start: true });
if resp.double_clicked() {
// On the icon it zooms to the layer and renames nothing (measured in Figma's web
// app, 2026-11-12); elsewhere on the row it renames.
if resp.interact_pointer_pos().is_some_and(|p| icon_rect.contains(p)) {
if sel.as_slice() != [row.id] {
app.run("select.set", json!({"ids": [row.id]}));
}
app.run("view.zoomSelection", json!({}));
// The release is also a click: it must not toggle or extend the selection.
clicked = None;
// The layer is the anchor of the next Shift-click's range.
app.ui.layer_anchor = Some(row.id);
} else if !crate::menus::dev_mode_refuses(app, "object.rename") {
app.ui.rename = Some(Rename { id: row.id, start: true });
}
}
if resp.secondary_clicked() {
if !sel.contains(&row.id) {
+28 -8
View File
@@ -614,6 +614,8 @@ fn position(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, shown: &Arc<Docu
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PositionValues {
pub can_align: bool,
/// Align is off because the one selected layer is placed by its auto layout frame.
pub align_blocked: bool,
pub x: Option<f64>,
pub y: Option<f64>,
pub rot: Option<f64>,
@@ -644,6 +646,7 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc<Document>, sel: &[N
let parent = |n: &Node| n.parent.and_then(|p| doc.node(p));
crate::selection_cache::cached(ctx, "position", doc, sel, &[], || PositionValues {
can_align: figcraft_engine::cmd::arrange::can_align(doc, sel),
align_blocked: figcraft_engine::cmd::arrange::align_blocked_by_auto_layout(doc, sel),
x: common(doc, sel, |n| x_of(doc, n)),
y: common(doc, sel, |n| y_of(doc, n)),
rot: common(doc, sel, |n| rot_of(doc, n)),
@@ -657,12 +660,18 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc<Document>, sel: &[N
})
}
/// Whether the Design panel offers Tidy up for `sel`: three or more layers forming a row, a column
/// or a full grid, none in an auto layout flow (`can_tidy`).
pub(crate) fn tidy_available(ctx: &egui::Context, doc: &Arc<Document>, sel: &[NodeId]) -> bool {
crate::selection_cache::cached(ctx, "tidy", doc, sel, &[], || figcraft_engine::tidy::can_tidy(doc, sel))
}
/// Draw alignment and distribution, X/Y and rotation with flip/rotate controls, the
/// absolute-position toggle and frame constraints.
fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, sel: &[NodeId]) {
let pv = position_values(ui.ctx(), doc, sel);
let col = widgets::col_width(ui.available_width());
align_row(app, ui, sel, pv.can_align, col);
align_row(app, ui, sel, pv.can_align, pv.align_blocked, col);
position_row(app, ui, doc, sel, &pv, col);
rotation_row(app, ui, doc, sel, pv.rot, col);
if pv.in_frame {
@@ -671,7 +680,7 @@ fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, sel: &[No
}
/// Alignment, and distribution and tidy up for three or more layers.
fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, col: f32) {
fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, blocked: bool, col: f32) {
let ids = sel.to_vec();
widgets::sublabels(ui, tr("Alignment"), None);
row(ui, 32.0, |ui| {
@@ -691,19 +700,30 @@ fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, col
let v = widgets::segmented(ui, &items[3..], None, w).map(|i| i + 3);
h.or(v)
});
picked.response.on_disabled_hover_text(tr("A layer on its own aligns to its frame: select more layers, or one in a frame"));
let why = if blocked {
tr("A layer in an auto layout frame is placed by its frame")
} else {
tr("A layer on its own aligns to its frame: select more layers, or one in a frame")
};
picked.response.on_disabled_hover_text(why);
if let Some(i) = picked.inner {
app.run(cmds[i], json!({"ids": ids}));
}
if sel.len() > 2 {
let more = icons::button(ui, Icon::DistributeH, 24.0, false, tr("Distribute and tidy"));
menu_popup(&more).show(|ui| {
for (l, c) in [
(tr("Distribute horizontal spacing"), "distribute.horizontal"),
(tr("Distribute vertical spacing"), "distribute.vertical"),
(tr("Tidy up"), "arrange.tidy"),
let can_tidy = app.session.ds().is_ok_and(|ds| tidy_available(ui.ctx(), &ds.doc, &ids));
for (l, c, on) in [
(tr("Distribute horizontal spacing"), "distribute.horizontal", true),
(tr("Distribute vertical spacing"), "distribute.vertical", true),
(tr("Tidy up"), "arrange.tidy", can_tidy),
] {
if menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or("")) {
let item = ui.add_enabled_ui(on, |ui| menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or("")));
if !on {
item.response
.on_disabled_hover_text(tr("Select a row, a column or a full grid of three or more layers, outside an auto layout flow"));
}
if item.inner {
app.run(c, json!({"ids": ids}));
ui.close();
}
+30
View File
@@ -0,0 +1,30 @@
//! The Design panel's Tidy up row follows the engine's rule (measured in Figma's web app on
//! 2026-11-12): offered for three or more layers forming a row, a column or a full grid, greyed out otherwise.
use egui::Context;
use figcraft_doc::NodeId;
use figcraft_engine::Session;
use serde_json::json;
use crate::{FigApp, NoServices};
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn available(layers: &[(f64, f64, f64, f64)]) -> bool {
let mut s = Session::new();
let ids: Vec<NodeId> = layers.iter().map(|(x, y, w, h)| rect(&mut s, *x, *y, *w, *h)).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let app = FigApp::new(s, Box::new(NoServices));
let ctx = Context::default();
let doc = app.session.ds().unwrap().doc.clone();
crate::right::tidy_available(&ctx, &doc, &ids)
}
#[test]
fn tidy_up_is_off_in_the_panel_for_overlapping_layers() {
assert!(available(&[(0., 0., 50., 50.), (80., 0., 50., 50.), (160., 0., 50., 50.)]), "three squares in a row");
assert!(!available(&[(100., 460., 50., 30.), (140., 430., 80., 60.), (130., 400., 30., 90.)]), "the overlapping triple");
assert!(!available(&[(0., 0., 50., 50.), (87., 0., 50., 50.)]), "two squares");
}
@@ -332,6 +332,87 @@ fn a_second_duplicate_group_takes_the_next_free_name() {
assert_eq!(n.len(), 6);
}
/// A collection with the variables `names` (numbers).
fn named_window(names: &[&str]) -> Ui {
let mut s = Session::new();
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
for n in names {
s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
}
let mut u = Ui::new(s);
u.app.ui.variables = Some(Default::default());
for _ in 0..10 {
u.frame(vec![]);
}
u
}
/// Right-click the group row `name`, choose Rename group, type `to` and press Enter.
fn rename_group(u: &mut Ui, name: &str, to: &str) {
let p = row(u, name);
click(u, p, PointerButton::Secondary, Modifiers::NONE);
let menu = flat(&u.frame_output(vec![]).shapes);
click(u, text_center(&menu, "Rename group"), PointerButton::Primary, Modifiers::NONE);
u.frame(vec![Event::Text(to.into())]);
for pressed in [true, false] {
u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
}
for _ in 0..5 {
u.frame(vec![]);
}
}
fn sorted_names(u: &Ui) -> Vec<String> {
let mut n = names(u);
n.sort();
n
}
#[test]
fn renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step() {
let mut u = named_window(&["Orange/100", "Orange/200", "Blue/100"]);
let before = u.app.session.undo_labels(100).len();
rename_group(&mut u, "Orange", "Palette/Orange");
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
assert_eq!(sorted_names(&u), ["Blue/100", "Palette/Orange/100", "Palette/Orange/200"]);
assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step");
assert_eq!(u.app.session.undo_labels(1), ["Rename group"]);
// The sidebar lists Palette with Orange indented under it.
let shapes = flat(&u.frame_output(vec![]).shapes);
let (parent, child) = (text_center(&shapes, "Palette"), text_center(&shapes, "Orange"));
assert!(child.y > parent.y && child.x > parent.x, "Orange is indented under Palette: {parent:?} {child:?}");
assert!(!has_text(&shapes, "Palette-Orange"));
u.app.session.undo().unwrap();
assert_eq!(sorted_names(&u), ["Blue/100", "Orange/100", "Orange/200"]);
}
#[test]
fn a_nested_groups_new_path_stays_in_its_parent_and_drops_empty_parts() {
let mut u = named_window(&["Palette/Orange/100", "Palette/Orange/200"]);
rename_group(&mut u, "Orange", " /Warm // Orange / ");
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
assert_eq!(sorted_names(&u), ["Palette/Warm/Orange/100", "Palette/Warm/Orange/200"]);
}
#[test]
fn renaming_a_group_into_its_own_new_subgroup_moves_the_deeper_names_first() {
// Orange/100 takes Orange/Warm/100, which itself moves on to Orange/Warm/Warm/100.
let mut u = named_window(&["Orange/100", "Orange/Warm/100"]);
rename_group(&mut u, "Orange", "Orange/Warm");
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
assert_eq!(sorted_names(&u), ["Orange/Warm/100", "Orange/Warm/Warm/100"]);
}
#[test]
fn a_group_rename_onto_a_variable_name_that_stays_changes_nothing() {
// The longer name moves first, whatever the order of the variables: Orange/1000 moves, then
// Orange/200 collides, and the move already made is undone.
let mut u = named_window(&["Orange/1000", "Orange/200", "Palette/Orange/200"]);
rename_group(&mut u, "Orange", "Palette/Orange");
assert!(u.app.ui.last_error.as_deref().is_some_and(|e| e.contains("Palette/Orange/200")), "{:?}", u.app.ui.last_error);
assert_eq!(sorted_names(&u), ["Orange/1000", "Orange/200", "Palette/Orange/200"]);
}
fn open_edit_variables(u: &mut Ui) -> Vec<egui::Shape> {
let menu = select_three_and_open_menu(u);
assert!(has_text(&menu, "Edit variables"), "the bulk menu offers Edit variables");
+2 -1
View File
@@ -1041,7 +1041,8 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) {
let picking = app.session.tool.pick_only || app.session.tool.picked.is_some();
// Nor may a press on the open gradient's handles or stops on the canvas: they are this picker's
// controls, and the canvas took the press before the picker drew (#1852).
let own = picking || crate::handles::gradient_dragging(ctx);
// Nor may one on the crop of an image paint held in Crop mode (#2307).
let own = picking || crate::handles::gradient_dragging(ctx) || crate::handles::crop_dragging(ctx);
pop = pop.close_on_outside(!own);
// Only the opening control is held out: any other sidebar or canvas press dismisses it.
let mut held: Vec<Rect> = app.ui.picker_button.into_iter().collect();
+4 -1
View File
@@ -1,6 +1,6 @@
# Collaboration parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
@@ -15,6 +15,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Real-time co-editing | yes | **core built, no networking** (#103): client-scoped ids, per-property change sets with fractional positions, server ordering and validation, optimistic clients, binary messages; randomized multi-client convergence tests over real commands. Live sessions over the network landed (`crates/collab-net`): the WebSocket transport (keep-alive, size and rate limits, a live connection reconnecting until you leave, and rejoining with offline edits merged), hosting from the app (this machine or the local network) with invite links, live cursors with name tags, selections, avatars and follow, `collab.*` commands. Document sync between apps works over them (the host's server orders every batch; guests open the host's file as a new tab). Sessions are per document: each open file has its own or none, several run at once (host one, join another, publish a third) and keep syncing behind the tab in front, and closing a file ends its session only. Revert to saved is refused until the document leaves its live session; its access checks and sync association stay intact. Undo is per person (only your own steps, others' later writes left alone), refused edits roll back with a toast, and a reconnect resumes as the same client with what it missed (or a snapshot) and sends what was made offline. The browser build joins (same messages through the browser's WebSocket API); `figcraft://` invite links open the desktop app and join. Styles, variables, collections, modes and comments made in a session take ids from their creator's space (the server checks it), so concurrent creations all survive; modes, per-mode values and replies inside one entry still resolve last-writer-wins. A standalone `figcraft-server` keeps many files, persists them (a snapshot plus a log, compacted), loses nothing confirmed across a restart (apps resume as the same participants) and takes files published from the app (File ▸ Publish to server…). The desktop app and the CLI open `wss://` links too (TLS through a reverse proxy), and releases ship the server for Linux with a deployment guide (systemd, Caddy, nginx, Docker) and `install.sh`. A server can be open to the public: anyone publishes without the key, within limits per address, and files nobody opens expire. Message limits follow the server's `max_file_mb`, so files above 64 MiB publish and open (the client takes at most 1 GiB from a server, and the server warns when large limits meet open publishing, #705); a damaged generation field in a file's log no longer drops the edits flushed to it (#687). Image entries are checked as they apply: a key must be a plain name (letters, digits, `-`, `_`; it becomes `images/<key>` in a saved file), bytes under a content-hash key must hash to it (lowercase sha256), a side is at most 65 535 px and the decoded bytes at most 256 MiB (what the importers read), a key's bytes can't be replaced and an image a layer shows can't be removed, so no collaborator can poison the shared image store or balloon memory; snapshots and server logs from before these checks open without the images they refuse (#1086). The batches kept for apps that reconnect are bounded in bytes by default (64 MiB; `max_log_mb` on `figcraft-server`), and an app further behind catches up with a snapshot (#1069). Placing a layer among its siblings is a binary search, so large pastes and reorders in one batch no longer take quadratic time (#1065). A refused batch's fixes take time linear in the batch: each deleted layer is restored once and each entry fix looked up once (#1063). Left: server archives beyond Linux | 25–55 |
| Live cursors, selections, viewports; follow / observation mode; spotlight | yes | **done, in live sessions**: named cursors (one name for live sessions and comments: Preferences ▸ Your name, also in the Share popover and the Join dialog, kept in the browser too; a rename shows at once in the sessions you're in, #1380), selection outlines, avatars (an AI agent attached over MCP also shows its avatar and an outline around the layers it last edited or selected while it works, in or out of a session, #1416), follow (click an avatar), others' text carets and selected characters with their names, a note when two people type in one layer; spotlight (your avatar's menu, `collab.spotlight`): everyone follows your view and page, people who join later too, anyone who moves their view stops following and a banner offers to follow again, a newer spotlight takes over. Left: polish (no accounts, so anyone in the session can spotlight) | 2–4 |
| Cursor chat, audio, high-fives | yes | **partial, in live sessions**: cursor chat (`/` opens a bubble at your pointer; everyone sees it as you type, it fades a few seconds after the last change, Enter sends and Escape takes it back, 100 characters; `collab.cursorChat` for agents); sent as ephemeral presence the host checks and rate-limits, never stored. No audio, high-fives or emote reactions | 2–5 |
| Opening page of a shared file | the page a link names, else the first | **partial**: a file joined from a server opens on its opening page, which is the open document's current page: the page the file was opened on (the page stored in the file when it was opened, else the first page) until someone sets one, not always the first page; a later page switch, a save on another page or publishing does not move it (a local save stamps the page being viewed into the saved file's bytes for the next time that file is opened, but does not change the open document's opening page, which is the synced property, and a link cannot name a page; `page.setOpening {id?}` (the pages list's Set as opening page, the MCP server too) writes it as a document change, one undo step, so everyone who joins afterwards lands on it, unless a spotlight is on, in which case they follow the spotlighter's page instead; each viewer's own page stays their own (#1817) | — |
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 |
| Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) |
| Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Developer Mode compares a ready-for-dev layer with its state when marked) | — |
@@ -26,6 +27,8 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. |
| 2026-11-04 | minor | M9, #1817: a file on a server opened on the page that was current at publish time, with no way to change it: `DocProp::CurrentPage` was synced but nothing wrote it. `page.setOpening {id?}` (the pages list's "Set as opening page", the MCP server too) writes the opening page as a document change, one undo step, so everyone who joins afterwards lands on it; a divider is refused; nobody's own page moves. Tests: `page_opening_tests`, `collab_live_tests::the_opening_page_syncs_and_moves_no_ones_view`. Numbers unchanged. |
| 2026-11-04 | minor | M9: a session you joined no longer turns into a local file by itself. A dropped connection reconnects until you leave (a minute's pause after each 12 attempts, a pause Retry now skips); only the host ending the session and refusals that are for good stop it; queued messages go out paced. While disconnected the tab shows a red mark and a strip across the canvas says so; a session that ended stays on its tab with Try again, Save a copy and Dismiss |
| 2026-11-04 | minor | M9: joining a session again merges what you did while disconnected as one undoable edit, through the three-way merge branches use, as the same client when the server still knows it. What conflicts keeps the other person's, and your whole version opens beside it as an unsaved copy. A server that no longer knows you merges the same way instead of discarding unconfirmed work |
| 2026-11-06 | patch | M9, #2026: one conflicting auto layout edit added a conflict for every size and place it moved (a padding changed on both sides of a file with one instance gave 10, with 15 instances 138), and a `layout` conflict took all auto layout fields together, so a gap changed only on the branch was lost if main won the padding. `merge::plan` now leaves out values both sides work out for themselves: a hugging frame's or a filling child's size, text sizing to its characters, an auto layout child's place (when both sides turn it the same way) and a value a layer in an instance takes from its main; merging keeps the file merged into's own value and normalising lays it out from the merged inputs. `layout` and `childLayout` merge field by field: a field changed on one side merges, each field changed both ways is its own conflict (`<id>/layout.padding`, shown as auto layout padding with both sides' values). Tests: `branch_tests::one_conflicting_auto_layout_edit_is_one_conflict`, `branch_tests::auto_layout_fields_changed_one_way_survive_a_conflict`, `branch_tests::sizes_auto_layout_works_out_never_conflict`; the merge fuzz test leaves worked-out values out of what each side must show |
+2 -1
View File
@@ -1,6 +1,6 @@
# Components, variants, styles and variables parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
@@ -81,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
| Date | Change | Summary |
|---|---|---|
| 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. |
| 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged |
| 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged |
| 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered |
+3 -1
View File
@@ -1,6 +1,6 @@
# Dev Mode parity
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7)
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7)
**Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect
to the code components of a repository (with their imports, also inside generated layer trees),
@@ -10,10 +10,12 @@ repository, third-party integrations. Remaining: 1–2 h.
| Feature | Status | Notes |
|---|---|---|
| 2026-11-12 | patch | SwiftUI, Compose and Flutter code export kept one colour per layer (the bottom visible solid, or a gradient's first stop) and dropped every other fill (#2271). Now each writes every visible solid and gradient fill of a frame, group, rectangle or ellipse, in paint order, and a gradient as a gradient. SwiftUI chains `.background(...)` with the top fill first, since each one goes behind the ones before it (a rectangle or ellipse fills with the bottom paint and lays a copy of the shape over it for each paint above). Compose chains `Modifier.background(...)` with the bottom fill first, since each one draws over the ones before it (a linear gradient snaps to eight directions, radial and angular ones sit at the box's centre). Flutter keeps the top fill in the `Container` and wraps each fill under it in a `DecoratedBox`, the bottom fill outermost and the drop shadow on the outermost box. A layer with one solid fill gives the same code as before; a lone gradient is now a gradient, not its first stop's colour. Still not written: image and pattern fills in the native targets, ArkUI (one background and one gradient per component, so a stack needs extra nodes) and text with several fills. The incumbent's iOS and Android output wasn't measured: the order follows how each platform paints. Percentages and hours unchanged |
| 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name |
| Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why |
| Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) |
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) |
| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) |
| Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours |
| Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet |
| Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) |
+8 -4
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where iLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the Line truncated
Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of
`/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's
@@ -81,8 +81,9 @@ visible and opaque (a page also its background opacity): a reader takes what is
draws nothing below a hidden page. The message
lists one node change per layer, parents first, each with its GUID, its parent and a position
string that orders it among its siblings; vector networks and outlines go in blobs, written once
each. `.fig` export warns and drops vector region paint stacks; import and editing preserve their
source paint coordinates.
each. `.fig` export writes a vector's region paint stacks (each filled area's own paints as an entry of the
network's style table, named by the area's style id); a region's kept paint frame is left out with a
warning; import and editing preserve their source paint coordinates.
Scaled instances retain an explicit override when a length is reset to the unscaled main's value,
rather than losing it to the field diff. This covers corners, strokes, layout and grid lengths,
@@ -93,6 +94,8 @@ scales and empty-style clears; they have not been checked in other software.
- **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded
rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable
network blobs with per-point corner radius, handle mirroring, caps and joins, each filled area's own paints, plus the outline of
their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the
network blobs with per-point corner radius, handle mirroring, caps and joins, plus the outline of
their filled areas), text, text on a path (the first part of its path, where the text starts and its side), boolean groups, slices; the fill outline of frames and shapes and the
stroke outline of plain strokes (a ring around boxes and whole ellipses, the widened path of other
@@ -134,7 +137,7 @@ scales and empty-style clears; they have not been checked in other software.
- **Left out, with a warning each:** colour calculations that resolve to nothing (an operand
missing, or more than 32 variables to read), variable bindings the format has no field for (component
properties, arc fields, font weight: written as the values they give), text styles on part of a
text (written as values), variables' publishing, code syntax and inheritance settings, extended
text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended
collections (written as collections of their own), comments, Developer Mode annotations, statuses,
resources, measurements and code links, plugin data, ruler
guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush
@@ -197,6 +200,7 @@ scales and empty-style clears; they have not been checked in other software.
| Date | Change | Summary |
|---|---|---|
| 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software |
| 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software |
| 2026-11-12 | minor | M6, #2297: the `.fig` exporter writes an image paint's adjustments as `paintFilter` (seven fields: exposure, contrast, vibrance from saturation, temperature, tint, highlights, shadows; the tint's sign is flipped, as the importer reads it), and no longer warns about them; the importer already read them. Not checked in other software |
| 2026-11-12 | patch | M6, #2273: `.fig` import: a numbered list keeps its start only on the item where it starts counting. Figma writes the start on every line of the list (measured in Figma's web app, 2026-11-12, from a saved .fig: a list started at 5 has `listStartOffset` 4 on all its lines, and after Backspace takes a middle item out of the list, the item after it starts a new list and is written with 0), so reading every line's value restarted the items after a split at the old start. The export is unchanged and a re-import now equals what went in; REST `listStartOffsets` read the same way |
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more