mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-24 17:27:03 +00:00
Merge pull request #2436 from storytold/cutover/vectordrawable-writer
M6: use the shared Android VectorDrawable XML writer
This commit is contained in:
Generated
+1
-1
@@ -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=5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7#5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
]
|
||||
|
||||
+1
-1
@@ -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 = "5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" }
|
||||
# internal
|
||||
figcraft-geom = { path = "crates/geom" }
|
||||
figcraft-color = { path = "crates/color" }
|
||||
|
||||
+2
-1
@@ -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. |
|
||||
|
||||
@@ -103,7 +103,7 @@ pub fn try_export(doc: &Document, ids: &[NodeId], opts: &VdOptions) -> Result<Vd
|
||||
let first = ids.first().and_then(|i| doc.node(*i)).map(|n| n.name.clone()).unwrap_or_default();
|
||||
walker.nothing_drawn(&first);
|
||||
}
|
||||
let xml = xml::document(w, h, &items);
|
||||
let xml = xml::document(w, h, items);
|
||||
Ok(VdExport { xml, warnings: walker.finish() })
|
||||
}
|
||||
|
||||
|
||||
+123
-198
@@ -1,211 +1,136 @@
|
||||
//! 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 _;
|
||||
//! Maps FigCraft's projected drawable into the shared XML writer.
|
||||
//! Geometry, colour policy and compatibility decisions remain in the application.
|
||||
|
||||
use crate::model::{Fill, GradKind, Item, ItemKind};
|
||||
use craft_vectordrawable::model as wire;
|
||||
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.
|
||||
#[cfg(test)]
|
||||
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}") }
|
||||
}
|
||||
// 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 {
|
||||
/// `<tag` and its attributes, one per line; `close` ends it with `/>`, 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, "{}</{tag}>", " ".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("<?xml version=\"1.0\" encoding=\"utf-8\"?>\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 <vector> without a <path> ("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;
|
||||
pub(crate) fn color(c: Color) -> String {
|
||||
craft_vectordrawable::write::color(wire_color(c))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_attributes_preserve_exact_xml() {
|
||||
assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞	"), "<&>"'	 é𝄞&#9;");
|
||||
}
|
||||
fn item(it: Item) -> 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 }),
|
||||
children: Vec::new(),
|
||||
}),
|
||||
};
|
||||
wire::Item { kind, bbox: it.bbox }
|
||||
}
|
||||
|
||||
#[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");
|
||||
// Explicit iterator frames keep traversal scratch proportional to depth, not sibling count.
|
||||
fn items(input: Vec<Item>) -> Vec<wire::Item> {
|
||||
let mut parents = Vec::new();
|
||||
let mut current = (input.into_iter(), Vec::new());
|
||||
loop {
|
||||
let depth = parents.len() + 1;
|
||||
if let Some(mut source) = current.0.next() {
|
||||
let children = match &mut source.kind {
|
||||
ItemKind::Group(g) => std::mem::take(&mut g.children),
|
||||
ItemKind::Path(_) => Vec::new(),
|
||||
};
|
||||
let mapped = item(source);
|
||||
if !children.is_empty() && depth < XML_DEPTH {
|
||||
let previous = std::mem::replace(&mut current, (children.into_iter(), Vec::new()));
|
||||
parents.push((previous, mapped));
|
||||
} else {
|
||||
discard_items(children);
|
||||
current.1.push(mapped);
|
||||
}
|
||||
} else {
|
||||
let Some((mut previous, mut parent)) = parents.pop() else { return current.1 };
|
||||
if let wire::ItemKind::Group(g) = &mut parent.kind {
|
||||
g.children = current.1;
|
||||
}
|
||||
previous.1.push(parent);
|
||||
current = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn discard_items(items: Vec<Item>) {
|
||||
let mut frames = vec![items.into_iter()];
|
||||
while let Some(frame) = frames.last_mut() {
|
||||
if let Some(mut item) = frame.next() {
|
||||
if let ItemKind::Group(g) = &mut item.kind {
|
||||
frames.push(std::mem::take(&mut g.children).into_iter());
|
||||
}
|
||||
} else {
|
||||
frames.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn document(width: f64, height: f64, input: Vec<Item>) -> String {
|
||||
let items = items(input);
|
||||
let output = craft_vectordrawable::write::document_with_depth_limit(width, height, &items, XML_DEPTH);
|
||||
// Recursive enum destruction also consumes stack, even with an iterative writer.
|
||||
let mut frames = vec![items.into_iter()];
|
||||
while let Some(frame) = frames.last_mut() {
|
||||
if let Some(mut item) = frame.next() {
|
||||
if let wire::ItemKind::Group(g) = &mut item.kind {
|
||||
frames.push(std::mem::take(&mut g.children).into_iter());
|
||||
}
|
||||
} else {
|
||||
frames.pop();
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "xml_legacy_test.rs"]
|
||||
mod legacy;
|
||||
#[cfg(test)]
|
||||
#[path = "xml_parity_tests.rs"]
|
||||
mod parity_tests;
|
||||
|
||||
@@ -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 {
|
||||
/// `<tag` and its attributes, one per line; `close` ends it with `/>`, 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, "{}</{tag}>", " ".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("<?xml version=\"1.0\" encoding=\"utf-8\"?>\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 <vector> without a <path> ("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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
use super::*;
|
||||
use crate::model::{Grad, GroupItem, GroupXf, NativeStroke, PathItem};
|
||||
use figcraft_geom::{BezPath, Rect};
|
||||
|
||||
fn path(fill: Option<Fill>, 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("<path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_groups_and_default_attributes_match() {
|
||||
for clip in [None, Some(BezPath::new())] {
|
||||
let group = Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Group(GroupItem {
|
||||
name: None,
|
||||
xf: Some(GroupXf { translate: (0.0, -0.0), rotation: -0.0001, scale: (1.0, 1.0) }),
|
||||
clip,
|
||||
children: vec![],
|
||||
}),
|
||||
};
|
||||
parity(12.0, 12.0, &[group]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_depth_fits_the_browser_sized_stack() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
let mut leaf = path(Some(Fill::Solid(Color::BLACK)), "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] }) };
|
||||
}
|
||||
assert!(document(1.0, 1.0, vec![leaf]).contains("<path"));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_siblings_nested_empty_and_clipped_groups_keep_closing_order() {
|
||||
let leaf = || path(Some(Fill::Solid(Color::BLACK)), "round", "bevel", Color::WHITE);
|
||||
let group = |name: &str, clip, children| Item {
|
||||
bbox: Rect::ZERO,
|
||||
kind: ItemKind::Group(GroupItem { name: Some(name.into()), xf: None, clip, children }),
|
||||
};
|
||||
let items = vec![
|
||||
leaf(),
|
||||
group(
|
||||
"outer",
|
||||
None,
|
||||
vec![
|
||||
group("empty", None, vec![]),
|
||||
group("clipped-empty", Some(BezPath::new()), vec![]),
|
||||
group("inner", Some(BezPath::new()), vec![leaf(), group("deeper", None, vec![leaf()]), leaf()]),
|
||||
leaf(),
|
||||
],
|
||||
),
|
||||
group("sibling", None, vec![leaf()]),
|
||||
leaf(),
|
||||
];
|
||||
parity(48.0, 32.0, &items);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_depth_input_is_discarded_without_recursive_destruction() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
let mut leaf = path(Some(Fill::Solid(Color::BLACK)), "butt", "miter", Color::BLACK);
|
||||
for _ in 0..XML_DEPTH * 3 {
|
||||
leaf = Item { bbox: Rect::ZERO, kind: ItemKind::Group(GroupItem { name: None, xf: None, clip: None, children: vec![leaf] }) };
|
||||
}
|
||||
let output = document(1.0, 1.0, vec![leaf]);
|
||||
assert_eq!(output.matches("<group").count(), XML_DEPTH);
|
||||
assert_eq!(output.matches("</group>").count(), XML_DEPTH - 1);
|
||||
assert!(!output.contains("<path"));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user