From 4b853f455af2c83d629de7321c1204ac35bec9b2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 15:49:46 -0500 Subject: [PATCH] M6: serialize Android drawables through craft-vectordrawable --- Cargo.lock | 2 +- Cargo.toml | 2 +- ROADMAP.md | 3 +- crates/vectordrawable/src/lib.rs | 2 +- crates/vectordrawable/src/xml.rs | 274 +++++------------- crates/vectordrawable/src/xml_legacy_test.rs | 213 ++++++++++++++ crates/vectordrawable/src/xml_parity_tests.rs | 136 +++++++++ docs/file-format-parity.md | 5 +- 8 files changed, 430 insertions(+), 207 deletions(-) create mode 100644 crates/vectordrawable/src/xml_legacy_test.rs create mode 100644 crates/vectordrawable/src/xml_parity_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 879856783..bd8070ef6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1236,7 +1236,7 @@ dependencies = [ [[package]] name = "craft-vectordrawable" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +source = "git+https://github.com/storytold/craft-libs?rev=1d5255e07f2463ea784860505e1f7ce68d6adffd#1d5255e07f2463ea784860505e1f7ce68d6adffd" dependencies = [ "kurbo", ] diff --git a/Cargo.toml b/Cargo.toml index 82831e556..479e77d32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/figcraft" [workspace.dependencies] craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } -craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } +craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1d5255e07f2463ea784860505e1f7ce68d6adffd" } # internal figcraft-geom = { path = "crates/geom" } figcraft-color = { path = "crates/color" } diff --git a/ROADMAP.md b/ROADMAP.md index fc03c5385..bebcd9168 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-17 · **Change:** minor (CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | diff --git a/crates/vectordrawable/src/lib.rs b/crates/vectordrawable/src/lib.rs index f12e91585..c79c6a9a3 100644 --- a/crates/vectordrawable/src/lib.rs +++ b/crates/vectordrawable/src/lib.rs @@ -103,7 +103,7 @@ pub fn try_export(doc: &Document, ids: &[NodeId], opts: &VdOptions) -> Result String { - let [r, g, b, a] = c.sanitized().to_rgba8(); - if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") } -} +// One document level can add a frame clip, a mask clip and a named group, plus the leaf gradient's +// transform group. Keep every layer admitted by check_export_depth, not just 256 XML groups. +const XML_DEPTH: usize = 3 * (figcraft_render::MAX_EXPORT_DEPTH + 1) + 2; +const _: () = assert!(XML_DEPTH <= craft_vectordrawable::write::MAX_CONFIGURED_DEPTH); -struct Out { - s: String, -} - -impl Out { - /// ``, else `>`. - fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) { - let pad = " ".repeat(depth); - let _ = write!(self.s, "{pad}<{tag}"); - for (i, (k, v)) in attrs.iter().enumerate() { - if i == 0 && attrs.len() == 1 { - let _ = write!(self.s, " {k}=\"{v}\""); - } else { - let _ = write!(self.s, "\n{pad} {k}=\"{v}\""); - } - } - self.s.push_str(if close { " />\n" } else { ">\n" }); - } - - fn close(&mut self, depth: usize, tag: &str) { - let _ = writeln!(self.s, "{}", " ".repeat(depth)); - } -} - -fn uses_gradient(items: &[Item]) -> bool { - items.iter().any(|it| match &it.kind { - ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))), - ItemKind::Group(g) => uses_gradient(&g.children), - }) -} - -/// The whole file: a `width`×`height` dp drawable with a viewport of the same size. -pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String { - let mut o = Out { s: String::from("\n") }; - let mut attrs = vec![("xmlns:android", ANDROID.to_string())]; - if uses_gradient(items) { - attrs.push(("xmlns:aapt", AAPT.to_string())); - } - attrs.extend([ - ("android:width", format!("{}dp", num(width))), - ("android:height", format!("{}dp", num(height))), - ("android:viewportWidth", num(width)), - ("android:viewportHeight", num(height)), - ]); - o.open(0, "vector", &attrs, false); - if items.is_empty() { - // Android refuses a without a ("no path defined"): one empty, unfilled path. - o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true); - } - for it in items { - item(&mut o, 1, it); - } - o.close(0, "vector"); - o.s -} - -fn item(o: &mut Out, depth: usize, it: &Item) { - match &it.kind { - ItemKind::Path(p) => path(o, depth, p), - ItemKind::Group(g) => group(o, depth, g), - } -} - -fn group(o: &mut Out, depth: usize, g: &GroupItem) { - let mut attrs = Vec::new(); - if let Some(n) = &g.name { - attrs.push(("android:name", esc(n))); - } - if let Some(x) = &g.xf { - let (sx, sy) = x.scale; - if num(x.rotation) != "0" { - attrs.push(("android:rotation", num(x.rotation))); - } - if num(sx) != "1" { - attrs.push(("android:scaleX", num(sx))); - } - if num(sy) != "1" { - attrs.push(("android:scaleY", num(sy))); - } - if num(x.translate.0) != "0" { - attrs.push(("android:translateX", num(x.translate.0))); - } - if num(x.translate.1) != "0" { - attrs.push(("android:translateY", num(x.translate.1))); - } - } - if g.children.is_empty() && g.clip.is_none() { - o.open(depth, "group", &attrs, true); - return; - } - o.open(depth, "group", &attrs, false); - if let Some(c) = &g.clip { - o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true); - } - for c in &g.children { - item(o, depth + 1, c); - } - o.close(depth, "group"); -} - -fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) { - attrs.push(("android:strokeColor", color(s.color))); - attrs.push(("android:strokeWidth", num(s.width))); - if s.cap != "butt" { - attrs.push(("android:strokeLineCap", s.cap.to_string())); - } - if s.join != "miter" { - attrs.push(("android:strokeLineJoin", s.join.to_string())); - } else if num(s.miter) != "4" { - attrs.push(("android:strokeMiterLimit", num(s.miter))); - } -} - -fn path(o: &mut Out, depth: usize, p: &PathItem) { - let mut attrs = Vec::new(); - if let Some(n) = &p.name { - attrs.push(("android:name", esc(n))); - } - attrs.push(("android:pathData", path_data(&p.data))); - if let Some(Fill::Solid(c)) = &p.fill { - attrs.push(("android:fillColor", color(*c))); - } - if let Some(s) = &p.stroke { - stroke_attrs(&mut attrs, s); - } - if p.even_odd && p.fill.is_some() { - attrs.push(("android:fillType", "evenOdd".to_string())); - } - let Some(Fill::Gradient(g)) = &p.fill else { - o.open(depth, "path", &attrs, true); - return; - }; - o.open(depth, "path", &attrs, false); - o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false); - let mut ga = Vec::new(); - match g.kind { - GradKind::Linear { start, end } => { - ga.push(("android:type", "linear".to_string())); - ga.push(("android:startX", num(start.0))); - ga.push(("android:startY", num(start.1))); - ga.push(("android:endX", num(end.0))); - ga.push(("android:endY", num(end.1))); - } - GradKind::Radial { center, radius } => { - ga.push(("android:type", "radial".to_string())); - ga.push(("android:centerX", num(center.0))); - ga.push(("android:centerY", num(center.1))); - ga.push(("android:gradientRadius", num(radius))); - } - GradKind::Sweep { center } => { - ga.push(("android:type", "sweep".to_string())); - ga.push(("android:centerX", num(center.0))); - ga.push(("android:centerY", num(center.1))); - } - } - o.open(depth + 2, "gradient", &ga, false); - for (off, c) in &g.stops { - o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true); - } - o.close(depth + 2, "gradient"); - o.close(depth + 1, "aapt:attr"); - o.close(depth, "path"); +fn wire_color(c: Color) -> wire::Color { + // FigCraft clamps positive infinity to one (the neutral writer maps non-finite to zero). + // Preserve the application's sanitization before passing its finite components onward. + let c = c.sanitized(); + [c.r, c.g, c.b, c.a] } #[cfg(test)] -mod shared_wire_tests { - use super::*; - use figcraft_geom::BezPath; - - #[test] - fn shared_attributes_preserve_exact_xml() { - assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞 "), "<&>"' é𝄞&#9;"); - } - - #[test] - fn shared_numbers_and_paths_preserve_android_syntax() { - assert_eq!(num(-0.0001), "0"); - assert_eq!(num(f64::NAN), "0"); - assert_eq!(num(f64::INFINITY), "0"); - assert_eq!(num(1.23456), "1.235"); - let mut p = BezPath::new(); - p.move_to((0.0, -0.0)); - p.line_to((1.23456, 2.0)); - p.quad_to((3.0, 4.0), (5.0, 6.0)); - p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); - p.close_path(); - assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z"); - } +pub(crate) fn color(c: Color) -> String { + craft_vectordrawable::write::color(wire_color(c)) } + +fn item(it: Item, depth: usize) -> wire::Item { + let kind = match it.kind { + ItemKind::Path(p) => wire::ItemKind::Path(wire::Path { + name: p.name, + data: p.data, + even_odd: p.even_odd, + fill: p.fill.map(|f| match f { + Fill::Solid(c) => wire::Fill::Solid(wire_color(c)), + Fill::Gradient(g) => wire::Fill::Gradient(wire::Gradient { + kind: match g.kind { + GradKind::Linear { start, end } => wire::GradientKind::Linear { start, end }, + GradKind::Radial { center, radius } => wire::GradientKind::Radial { center, radius }, + GradKind::Sweep { center } => wire::GradientKind::Sweep { center }, + }, + stops: g.stops.into_iter().map(|(offset, c)| (offset, wire_color(c))).collect(), + }), + }), + stroke: p.stroke.map(|s| wire::Stroke { + color: wire_color(s.color), + width: s.width, + miter: s.miter, + cap: match s.cap { + "round" => wire::Cap::Round, + "square" => wire::Cap::Square, + _ => wire::Cap::Butt, + }, + join: match s.join { + "round" => wire::Join::Round, + "bevel" => wire::Join::Bevel, + _ => wire::Join::Miter, + }, + }), + }), + ItemKind::Group(g) => wire::ItemKind::Group(wire::Group { + name: g.name, + clip: g.clip, + transform: g.xf.map(|x| wire::GroupTransform { translate: x.translate, rotation: x.rotation, scale: x.scale }), + // Bound adaptation as well as writing. Production trees are bounded by the source + // layer guard and generated wrappers; don't recurse beyond that invariant. + children: if depth < XML_DEPTH { g.children.into_iter().map(|it| item(it, depth + 1)).collect() } else { Vec::new() }, + }), + }; + wire::Item { kind, bbox: it.bbox } +} + +pub(crate) fn document(width: f64, height: f64, items: Vec) -> String { + let items: Vec<_> = items.into_iter().map(|it| item(it, 1)).collect(); + craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH) +} + +#[cfg(test)] +#[path = "xml_legacy_test.rs"] +mod legacy; +#[cfg(test)] +#[path = "xml_parity_tests.rs"] +mod parity_tests; diff --git a/crates/vectordrawable/src/xml_legacy_test.rs b/crates/vectordrawable/src/xml_legacy_test.rs new file mode 100644 index 000000000..5e8b008d1 --- /dev/null +++ b/crates/vectordrawable/src/xml_legacy_test.rs @@ -0,0 +1,213 @@ +// Test-only parity oracle: FigCraft XML writer before shared cutover. +// Original writer by Filip Strajnar (8b5441eb), with subsequent contributor fixes. +//! The pretty-printed XML: elements two spaces deeper per level, one attribute per line four +//! spaces past its element (as Android Studio formats drawables). Numbers are compact (at most +//! three decimals, no `-0`) and always finite; text is escaped for attribute values. + +use std::fmt::Write as _; + +use figcraft_color::Color; + +use crate::model::{Fill, GradKind, GroupItem, Item, ItemKind, NativeStroke, PathItem}; + +const ANDROID: &str = "http://schemas.android.com/apk/res/android"; +const AAPT: &str = "http://schemas.android.com/aapt"; + +// Shared wire primitives; app-specific drawable projection and colour policy stay here. +pub(crate) use craft_vectordrawable::write::{esc, num, path_data}; + +/// `#RRGGBB`, or `#AARRGGBB` when not opaque. +pub(crate) fn color(c: Color) -> String { + let [r, g, b, a] = c.sanitized().to_rgba8(); + if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") } +} + +struct Out { + s: String, +} + +impl Out { + /// ``, else `>`. + fn open(&mut self, depth: usize, tag: &str, attrs: &[(&str, String)], close: bool) { + let pad = " ".repeat(depth); + let _ = write!(self.s, "{pad}<{tag}"); + for (i, (k, v)) in attrs.iter().enumerate() { + if i == 0 && attrs.len() == 1 { + let _ = write!(self.s, " {k}=\"{v}\""); + } else { + let _ = write!(self.s, "\n{pad} {k}=\"{v}\""); + } + } + self.s.push_str(if close { " />\n" } else { ">\n" }); + } + + fn close(&mut self, depth: usize, tag: &str) { + let _ = writeln!(self.s, "{}", " ".repeat(depth)); + } +} + +fn uses_gradient(items: &[Item]) -> bool { + items.iter().any(|it| match &it.kind { + ItemKind::Path(p) => matches!(p.fill, Some(Fill::Gradient(_))), + ItemKind::Group(g) => uses_gradient(&g.children), + }) +} + +/// The whole file: a `width`×`height` dp drawable with a viewport of the same size. +pub(crate) fn document(width: f64, height: f64, items: &[Item]) -> String { + let mut o = Out { s: String::from("\n") }; + let mut attrs = vec![("xmlns:android", ANDROID.to_string())]; + if uses_gradient(items) { + attrs.push(("xmlns:aapt", AAPT.to_string())); + } + attrs.extend([ + ("android:width", format!("{}dp", num(width))), + ("android:height", format!("{}dp", num(height))), + ("android:viewportWidth", num(width)), + ("android:viewportHeight", num(height)), + ]); + o.open(0, "vector", &attrs, false); + if items.is_empty() { + // Android refuses a without a ("no path defined"): one empty, unfilled path. + o.open(1, "path", &[("android:pathData", "M0,0".to_string())], true); + } + for it in items { + item(&mut o, 1, it); + } + o.close(0, "vector"); + o.s +} + +fn item(o: &mut Out, depth: usize, it: &Item) { + match &it.kind { + ItemKind::Path(p) => path(o, depth, p), + ItemKind::Group(g) => group(o, depth, g), + } +} + +fn group(o: &mut Out, depth: usize, g: &GroupItem) { + let mut attrs = Vec::new(); + if let Some(n) = &g.name { + attrs.push(("android:name", esc(n))); + } + if let Some(x) = &g.xf { + let (sx, sy) = x.scale; + if num(x.rotation) != "0" { + attrs.push(("android:rotation", num(x.rotation))); + } + if num(sx) != "1" { + attrs.push(("android:scaleX", num(sx))); + } + if num(sy) != "1" { + attrs.push(("android:scaleY", num(sy))); + } + if num(x.translate.0) != "0" { + attrs.push(("android:translateX", num(x.translate.0))); + } + if num(x.translate.1) != "0" { + attrs.push(("android:translateY", num(x.translate.1))); + } + } + if g.children.is_empty() && g.clip.is_none() { + o.open(depth, "group", &attrs, true); + return; + } + o.open(depth, "group", &attrs, false); + if let Some(c) = &g.clip { + o.open(depth + 1, "clip-path", &[("android:pathData", path_data(c))], true); + } + for c in &g.children { + item(o, depth + 1, c); + } + o.close(depth, "group"); +} + +fn stroke_attrs(attrs: &mut Vec<(&str, String)>, s: &NativeStroke) { + attrs.push(("android:strokeColor", color(s.color))); + attrs.push(("android:strokeWidth", num(s.width))); + if s.cap != "butt" { + attrs.push(("android:strokeLineCap", s.cap.to_string())); + } + if s.join != "miter" { + attrs.push(("android:strokeLineJoin", s.join.to_string())); + } else if num(s.miter) != "4" { + attrs.push(("android:strokeMiterLimit", num(s.miter))); + } +} + +fn path(o: &mut Out, depth: usize, p: &PathItem) { + let mut attrs = Vec::new(); + if let Some(n) = &p.name { + attrs.push(("android:name", esc(n))); + } + attrs.push(("android:pathData", path_data(&p.data))); + if let Some(Fill::Solid(c)) = &p.fill { + attrs.push(("android:fillColor", color(*c))); + } + if let Some(s) = &p.stroke { + stroke_attrs(&mut attrs, s); + } + if p.even_odd && p.fill.is_some() { + attrs.push(("android:fillType", "evenOdd".to_string())); + } + let Some(Fill::Gradient(g)) = &p.fill else { + o.open(depth, "path", &attrs, true); + return; + }; + o.open(depth, "path", &attrs, false); + o.open(depth + 1, "aapt:attr", &[("name", "android:fillColor".to_string())], false); + let mut ga = Vec::new(); + match g.kind { + GradKind::Linear { start, end } => { + ga.push(("android:type", "linear".to_string())); + ga.push(("android:startX", num(start.0))); + ga.push(("android:startY", num(start.1))); + ga.push(("android:endX", num(end.0))); + ga.push(("android:endY", num(end.1))); + } + GradKind::Radial { center, radius } => { + ga.push(("android:type", "radial".to_string())); + ga.push(("android:centerX", num(center.0))); + ga.push(("android:centerY", num(center.1))); + ga.push(("android:gradientRadius", num(radius))); + } + GradKind::Sweep { center } => { + ga.push(("android:type", "sweep".to_string())); + ga.push(("android:centerX", num(center.0))); + ga.push(("android:centerY", num(center.1))); + } + } + o.open(depth + 2, "gradient", &ga, false); + for (off, c) in &g.stops { + o.open(depth + 3, "item", &[("android:offset", num(*off)), ("android:color", color(*c))], true); + } + o.close(depth + 2, "gradient"); + o.close(depth + 1, "aapt:attr"); + o.close(depth, "path"); +} + +#[cfg(test)] +mod shared_wire_tests { + use super::*; + use figcraft_geom::BezPath; + + #[test] + fn shared_attributes_preserve_exact_xml() { + assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞 "), "<&>"' é𝄞&#9;"); + } + + #[test] + fn shared_numbers_and_paths_preserve_android_syntax() { + assert_eq!(num(-0.0001), "0"); + assert_eq!(num(f64::NAN), "0"); + assert_eq!(num(f64::INFINITY), "0"); + assert_eq!(num(1.23456), "1.235"); + let mut p = BezPath::new(); + p.move_to((0.0, -0.0)); + p.line_to((1.23456, 2.0)); + p.quad_to((3.0, 4.0), (5.0, 6.0)); + p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); + p.close_path(); + assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z"); + } +} diff --git a/crates/vectordrawable/src/xml_parity_tests.rs b/crates/vectordrawable/src/xml_parity_tests.rs new file mode 100644 index 000000000..52b89de43 --- /dev/null +++ b/crates/vectordrawable/src/xml_parity_tests.rs @@ -0,0 +1,136 @@ +use super::*; +use crate::model::{Grad, GroupItem, GroupXf, NativeStroke, PathItem}; +use figcraft_geom::{BezPath, Rect}; + +fn path(fill: Option, cap: &'static str, join: &'static str, c: Color) -> Item { + let mut data = BezPath::new(); + data.move_to((0.0, -0.0)); + data.line_to((1.23456, 2.0)); + data.quad_to((3.0, 4.0), (5.0, 6.0)); + data.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); + data.close_path(); + Item { + bbox: Rect::ZERO, + kind: ItemKind::Path(PathItem { + name: Some("<&>\"'\t\n\r\0\u{ffff}é𝄞 ".into()), + data, + fill, + stroke: Some(NativeStroke { color: c, width: 2.34567, cap, join, miter: 3.0 }), + even_odd: true, + }), + } +} + +fn parity(w: f64, h: f64, items: &[Item]) { + let actual = document(w, h, items.to_vec()); + assert_eq!(actual, legacy::document(w, h, items)); + let parsed = roxmltree::Document::parse(&actual).unwrap(); + assert_eq!(parsed.root_element().tag_name().name(), "vector"); +} + +#[test] +fn complete_documents_preserve_exact_bytes_and_app_colour_policy() { + parity(0.0, f64::INFINITY, &[]); + let colours = [ + Color::BLACK, + Color::from_rgba8(26, 43, 60, 128), + Color { r: f32::INFINITY, g: f32::NEG_INFINITY, b: f32::NAN, a: f32::INFINITY }, + Color { r: 0.49999, g: 0.50001, b: 2.0, a: -1.0 }, + ]; + for c in colours { + let fills = [ + None, + Some(Fill::Solid(c)), + Some(Fill::Gradient(Grad { kind: GradKind::Linear { start: (0.0, 1.0), end: (3.0, 4.0) }, stops: vec![(0.0, c), (1.0, Color::WHITE)] })), + Some(Fill::Gradient(Grad { kind: GradKind::Radial { center: (5.0, 6.0), radius: 7.0 }, stops: vec![(f64::NAN, c)] })), + Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (8.0, 9.0) }, stops: vec![] })), + ]; + for fill in fills { + for cap in ["butt", "round", "square"] { + for join in ["miter", "round", "bevel"] { + let leaf = path(fill.clone(), cap, join, c); + parity(24.12345, 18.0, std::slice::from_ref(&leaf)); + let group = Item { + bbox: Rect::ZERO, + kind: ItemKind::Group(GroupItem { + name: Some("group&\"".into()), + xf: Some(GroupXf { translate: (2.0, -3.0), rotation: 45.0, scale: (1.0, 2.0) }), + clip: Some(BezPath::new()), + children: vec![leaf], + }), + }; + parity(24.0, 18.0, &[group]); + } + } + } + } +} + +#[test] +fn source_depth_wrappers_do_not_lose_the_deepest_accepted_leaf() { + let mut leaf = path(Some(Fill::Gradient(Grad { kind: GradKind::Sweep { center: (0.0, 0.0) }, stops: vec![] })), "butt", "miter", Color::BLACK); + for _ in 0..XML_DEPTH - 2 { + leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) }; + } + let items = [leaf]; + let xml = document(1.0, 1.0, items.to_vec()); + assert_eq!(xml, legacy::document(1.0, 1.0, &items)); + assert!(xml.contains("aapt") && xml.contains(" **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 PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **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 PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -57,7 +57,7 @@ export limit, not a native document nesting limit. | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | | PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 | | WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — | -| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `` with ``; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — | +| Android Vector Drawable (XML) | — | yes (ours) | an `.xml` drawable resource serialized by `craft-vectordrawable` through an app-model adapter (`file.export {format: "xml"}`, export settings, File ▸ Export…, the CLI and MCP), pretty-printed, sized in dp with the viewport in layer units, for AndroidX (VectorDrawableCompat: gradients and even-odd need API 24 without it). Shapes, booleans and text as path data with transforms baked in; solid fills and linear, radial and sweep gradients (`aapt:attr`, exact for any handles: radial and sweep in a `` that maps the unit circle); centred strokes as stroke attributes where Android draws them the same (uniform scale, one cap, no dashes or variable width), other strokes as filled outlines; clipping frames and masks as `` with ``; `android:name` from layer names with the id attribute option. What the format can't hold goes by the compatibility mode (`vdCompat`): best effort (default) applies layer opacity to each shape, rewrites even-odd fills and clip outlines as non-zero, draws diamond gradients as radial and alpha masks as outline clips, each with a warning; exact leaves out what it can't draw exactly, with a warning; ignore writes what maps without warnings: layer opacity over overlapping shapes is dropped (drawn opaque), even-odd fills keep `fillType="evenOdd"`, even-odd clip outlines clip as non-zero, diamond gradients are left out and alpha masks clip to their outline. Effects, image and pattern fills and blend modes are always left out (warned except in ignore); an export that draws nothing writes one empty path (Android refuses a drawable without a path), with a warning. Checked by parsing the XML, against FigCraft's renderer (gradients pixel by pixel), with `aapt2 compile` and `link`, and by rendering samples (linear, skewed radial and sweep gradients, a sweep with mirrored handles, even-odd booleans, centred and inside strokes, rotated text, a clipping frame, an alpha mask, a translucent group, each compatibility mode) with Android 13's (API 33) VectorDrawable on an emulator, next to FigCraft's PNG export: they match, including where the sweep starts and which way it turns, except what the compatibility mode and its warnings say (best effort: overlapping shapes in a translucent group look denser; exact and ignore leave out or draw opaque what they list). Not checked on API 21–23 (VectorDrawableCompat) | — | | Copy as CSS / SVG / PNG / text / link | yes | yes | Copy as PNG: the whole selection at 2x | — | | Dev Mode code (CSS, iOS SwiftUI, Android Compose) | yes | yes, plus HTML, React, Vue, Leptos, ArkUI and Flutter | see [dev-mode-parity](dev-mode-parity.md) | — | | `.fig` ("Save local copy") | yes | **experimental** | the whole file, also as a copy from File ▸ Save as… (the document keeps its `.figcraft` path and unsaved state); see [Export to `.fig`](#export-to-fig-experimental). Round trips through our own importer; written files checked by opening them in other software: layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft; resized and scaled instances keep their size and lay their layers out for it, variables with their modes and colour bindings resolve there (a frame set to another mode shows that mode's colours, also inside instances), colour, text, effect and grid styles are listed, and variable-width strokes that are the same on both sides of the path draw with their width | 5–15 (non-colour bindings as bindings, checks of effects, images and prototypes, and against real files) | @@ -196,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 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 |