M6: Open and import Adobe XD (.xd) files, best effort (#2077) (#2912)

* M6: Open and import Adobe XD (.xd) files, best effort (#2077)

The archive's artboards, pasteboard layers, groups, rectangles, circles,
lines and paths, solid, linear-gradient and image fills, strokes, opacity,
drop shadows and blurs, clip paths and text with styled ranges are mapped
onto the REST importer, as the .sketch import is. Point text is measured
so its first baseline and aligned edge stay where the file put them.
File > Open, Import, drop, CLI and MCP take .xd files, in the browser too.

* M6: XD import: clip paths take only shapes, one style range keeps its decoration, groups refit after point text (#2077)

From review: a clip path holding a group clipped by itself recursed without end;
a single style range covering a whole text dropped its underline or strikethrough;
groups kept the bounds of the guessed text size after the point text was measured.
This commit is contained in:
BFlat
2026-12-02 10:16:44 +07:00
committed by GitHub
parent 61947923d4
commit c7546e9e0e
17 changed files with 909 additions and 23 deletions
+2 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -14,6 +14,7 @@ use figcraft_doc::{PrintSettings, VdCompat};
///
/// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig
/// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort),
/// .xd (Adobe XD, best effort),
/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2,
/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer).
#[derive(Parser)]
+2 -2
View File
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"file.open",
"Open",
"{path | data (base64) + name (tells the format; opens as a new unsaved document), variables? (REST: the local variables JSON as an object, JSON text or a path; default `<name>.variables.json` or `variables.json` next to the file), higherFigLimits? (.fig: allow more memory for this open), reload? (a file already open: read it again into its tab, which must have no unsaved changes)} (.figcraft, .json: FigCraft or REST API file JSON, .fig (best effort), .penpot, .sketch (Sketch 48 or newer, best effort), .svg, .png, .jpg …); REST, .fig, .penpot and .sketch imports return `warnings`; a file opened anew returns `summary` {name, pages, layers, images} (one that was already open returns its `index`, with `stale: true` when the file changed on disk since the tab read or saved it, or `reloaded: true` after `reload`)",
"{path | data (base64) + name (tells the format; opens as a new unsaved document), variables? (REST: the local variables JSON as an object, JSON text or a path; default `<name>.variables.json` or `variables.json` next to the file), higherFigLimits? (.fig: allow more memory for this open), reload? (a file already open: read it again into its tab, which must have no unsaved changes)} (.figcraft, .json: FigCraft or REST API file JSON, .fig (best effort), .penpot, .sketch (Sketch 48 or newer, best effort), .xd (Adobe XD, best effort), .svg, .png, .jpg …); REST, .fig, .penpot, .sketch and .xd imports return `warnings`; a file opened anew returns `summary` {name, pages, layers, images} (one that was already open returns its `index`, with `stale: true` when the file changed on disk since the tab read or saved it, or `reloaded: true` after `reload`)",
false,
open
),
@@ -168,7 +168,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"file.import",
"Import",
"{path | data (base64) + name, higherFigLimits? (.fig: allow more memory for this import), x?, y?, center? (SVG: centre it on x, y), variables? (REST: the local variables JSON as an object, JSON text or a path)} SVG becomes an editable frame (shapes, text, gradients, masks, effects; with `warnings` for what it left out), images become image layers, .figcraft, .penpot, REST API file JSON, .fig and .sketch pages are appended with their variables and flows (REST, .fig, .penpot and .sketch: with `warnings`; those return `summary` {name, pages, layers, images} of the file read)",
"{path | data (base64) + name, higherFigLimits? (.fig: allow more memory for this import), x?, y?, center? (SVG: centre it on x, y), variables? (REST: the local variables JSON as an object, JSON text or a path)} SVG becomes an editable frame (shapes, text, gradients, masks, effects; with `warnings` for what it left out), images become image layers, .figcraft, .penpot, REST API file JSON, .fig, .sketch and .xd pages are appended with their variables and flows (REST, .fig, .penpot, .sketch and .xd: with `warnings`; those return `summary` {name, pages, layers, images} of the file read)",
true,
import
),
+49 -10
View File
@@ -142,6 +142,14 @@ fn load_any(
font_notes.append(&mut notes); // Show missing-font details first in the UI toast.
Ok((figcraft_format::Loaded { issues: font_notes, ..doc.into() }, true, false))
}
"xd" => {
let (mut doc, notes) = figcraft_format::xd::import(bytes, &file_stem(name_hint)).map_err(|e| EngineError::Other(e.to_string()))?;
// Measuring the text needs the installed fonts known first.
figcraft_text::fontdb::scan_system_fonts();
match_font_families(&mut doc);
xd_point_text(&mut doc);
Ok((figcraft_format::Loaded { issues: notes, ..doc.into() }, true, false))
}
e if matches!(e, "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "heic" | "heif")
|| figcraft_format::raw::is_extension(e) =>
{
@@ -229,16 +237,7 @@ fn reflow_overridden_text(doc: &mut Document) {
}
for id in changed {
if let Some((w, h)) = doc.node(id).and_then(figcraft_text::auto_size) {
// Sketch grows auto-width text from its aligned edge: a centred one stays centred, a
// right-aligned one keeps its right edge.
let shift = doc.node(id).map_or(0.0, |n| match &n.kind {
NodeKind::Text(t) if t.auto_resize == figcraft_doc::TextAutoResize::WidthAndHeight => match t.align_h {
figcraft_doc::TextAlignH::Center => (n.width - w) / 2.0,
figcraft_doc::TextAlignH::Right => n.width - w,
_ => 0.0,
},
_ => 0.0,
});
let shift = doc.node(id).map_or(0.0, |n| aligned_edge_shift(n, w));
figcraft_layout::set_size(doc, id, w, h);
if shift.is_finite()
&& shift != 0.0
@@ -251,6 +250,46 @@ fn reflow_overridden_text(doc: &mut Document) {
}
}
/// How far auto-width text `n` moves right when it takes width `w`, growing from its aligned edge
/// as Sketch and XD grow it: a centred one stays centred, a right-aligned one keeps its right edge.
fn aligned_edge_shift(n: &figcraft_doc::Node, w: f64) -> f64 {
match &n.kind {
NodeKind::Text(t) if t.auto_resize == figcraft_doc::TextAutoResize::WidthAndHeight => match t.align_h {
figcraft_doc::TextAlignH::Center => (n.width - w) / 2.0,
figcraft_doc::TextAlignH::Right => n.width - w,
_ => 0.0,
},
_ => 0.0,
}
}
/// XD anchors point text at its first baseline and aligned edge, and the import guessed the
/// width and ascent: each auto-width text takes its measured size, growing from its aligned edge,
/// and moves so its first baseline sits where XD put it.
fn xd_point_text(doc: &mut Document) {
let ids: Vec<NodeId> = doc
.nodes()
.filter(|n| matches!(&n.kind, NodeKind::Text(t) if t.auto_resize == figcraft_doc::TextAutoResize::WidthAndHeight))
.map(|n| n.id)
.collect();
for id in ids {
let Some(n) = doc.node(id) else { continue };
let (Some((w, h)), NodeKind::Text(t)) = (figcraft_text::auto_size(n), &n.kind) else { continue };
let baseline = figcraft_text::layout_cached(t, None, None).lines.first().map(|l| l.baseline);
let down = baseline.map_or(0.0, |b| figcraft_format::xd::POINT_ASCENT * t.style.font_size - b);
let shift = aligned_edge_shift(n, w);
figcraft_layout::set_size(doc, id, w, h);
if let Some(n) = doc.node_mut(id)
&& shift.is_finite()
&& down.is_finite()
{
n.transform *= figcraft_doc::geom::Affine::translate((shift, down));
}
// The groups around it were fitted to the guess.
doc.fit_ancestors(id);
}
}
/// Font families a `.sketch` import guessed from PostScript names ("Ping Fang SC" from
/// "PingFangSC-Semibold") take the installed family's name when they differ only in spaces and
/// case.
+1 -1
View File
@@ -323,7 +323,7 @@ pub(super) fn import(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(out)
}
"figcraft" | "json" | "fig" | "jam" | "sketch" | "penpot" => {
"figcraft" | "json" | "fig" | "jam" | "sketch" | "penpot" | "xd" => {
let resolver = path.as_deref().map(rest_images);
let images: figcraft_format::rest::ImageResolver = match &resolver {
Some(r) => r,
+2
View File
@@ -811,6 +811,8 @@ mod widget_panel_tests;
mod widget_shapes_tests;
#[cfg(test)]
mod widgets_tests;
#[cfg(test)]
mod xd_import_tests;
#[cfg(test)]
mod export_bounds_tests;
+97
View File
@@ -0,0 +1,97 @@
//! `.xd` files through the file commands. The importer's own tests (fixtures built in code) are in
//! `figcraft_format::xd`.
use std::io::Write;
use base64::Engine;
use serde_json::{Value, json};
use figcraft_doc::NodeKind;
use figcraft_doc::geom::Point;
use crate::Session;
/// A minimal `.xd` zip: one artboard "Board" at (100, 50), 400 × 300, holding `layers` (in
/// document coordinates).
fn xd(layers: Value) -> Vec<u8> {
let manifest = json!({"children": [{"path": "artwork", "children": [
{"path": "artboard-a", "name": "Board", "uxdesign#bounds": {"x": 100, "y": 50, "width": 400, "height": 300}}
]}]});
let board = json!({"children": [{"type": "artboard", "artboard": {"children": layers}}]});
let mut out = Vec::new();
{
let mut z = zip::ZipWriter::new(std::io::Cursor::new(&mut out));
let o = zip::write::SimpleFileOptions::default();
for (name, body) in [
("mimetype", "application/vnd.adobe.sparkler.project+dcxucf".to_string()),
("manifest", manifest.to_string()),
("artwork/artboard-a/graphics/graphicContent.agc", board.to_string()),
] {
z.start_file(name, o).unwrap();
z.write_all(body.as_bytes()).unwrap();
}
z.finish().unwrap();
}
out
}
/// Centred point text anchored at document (300, 200): 200, 150 inside the board.
fn centred_text() -> Value {
json!({"type": "text", "name": "Label", "transform": {"a": 1, "b": 0, "c": 0, "d": 1, "tx": 300, "ty": 200},
"style": {"fill": {"type": "solid", "color": {"mode": "RGB", "value": {"r": 0, "g": 0, "b": 0}}},
"font": {"family": "Sans", "style": "Regular", "size": 24}, "textAttributes": {"paragraphAlign": "center"}},
"text": {"frame": {"type": "positioned"}, "paragraphs": [{"lines": [[{"x": -10, "y": 0, "from": 0, "to": 13}]]}], "rawText": "Hello, world!"}})
}
fn open(s: &mut Session, bytes: &[u8]) -> Value {
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
s.execute("file.open", &json!({"data": data, "name": "design.xd"})).unwrap()
}
#[test]
fn xd_files_open_with_point_text_on_its_anchor() {
let mut s = Session::new();
let r = open(&mut s, &xd(json!([centred_text()])));
assert_eq!(r["summary"]["pages"], 1, "{r}");
let doc = s.doc().unwrap();
let board = doc.nodes().find(|n| n.name == "Board").unwrap();
assert!(board.kind.is_frame_like());
let label = doc.nodes().find(|n| n.name == "Label").unwrap();
let NodeKind::Text(t) = &label.kind else { panic!("not text") };
assert_eq!(t.characters, "Hello, world!");
let at = doc.world_transform(label.id) * Point::ORIGIN;
let anchor = doc.world_transform(board.id) * Point::new(200.0, 150.0);
assert!((at.x + label.width / 2.0 - anchor.x).abs() < 1e-6, "centred on the anchor: {at:?} width {}", label.width);
if let Some(line) = figcraft_text::layout_cached(t, None, None).lines.first() {
assert!((at.y + line.baseline - anchor.y).abs() < 1e-6, "first baseline on the anchor: {at:?} + {}", line.baseline);
}
}
#[test]
fn xd_import_appends_its_page_and_damaged_files_fail_cleanly() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let before = s.doc().unwrap().pages.len();
let data = base64::engine::general_purpose::STANDARD.encode(xd(json!([centred_text()])));
let r = s.execute("file.import", &json!({"data": data, "name": "more.xd"})).unwrap();
assert!(r["summary"]["layers"].as_u64().unwrap() >= 2, "{r}");
assert_eq!(s.doc().unwrap().pages.len(), before + 1);
let mut broken = xd(json!([]));
broken.truncate(broken.len() / 2);
let data = base64::engine::general_purpose::STANDARD.encode(broken);
assert!(s.execute("file.open", &json!({"data": data, "name": "broken.xd"})).is_err());
}
/// Opens every `.xd` file in `FIGCRAFT_XD_SAMPLES` (a local folder; skipped when unset).
#[test]
fn local_xd_samples_open() {
let Ok(dir) = std::env::var("FIGCRAFT_XD_SAMPLES") else { return };
let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "xd")).collect();
assert!(!files.is_empty(), "no .xd files in {dir}");
for path in files {
let mut s = Session::new();
let r = s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
println!("{}: {} warnings {}", path.display(), r["summary"], r["warnings"]);
assert!(r["summary"]["layers"].as_u64().unwrap() > 0);
}
}
+1
View File
@@ -35,6 +35,7 @@ mod streaming_save;
pub mod thumbnail;
mod version_store;
pub mod video;
pub mod xd;
pub use density::{pixel_density, placed_size};
#[cfg(not(target_arch = "wasm32"))]
+537
View File
@@ -0,0 +1,537 @@
//! Import of Adobe XD (`.xd`) files (best effort).
//!
//! Adobe publishes no specification of the file. This reader is written from what XD files
//! published under open licences show (the MIT-licensed design files in public repositories,
//! unpacked and read as data) and from the public XD plug-in API reference
//! (developer.adobe.com/xd/uxp/develop/reference: Text, Rectangle, ImageFill, Shadow, Blur,
//! Color, Group, Matrix) for what the values mean. No other implementation was read.
//!
//! An `.xd` file is a ZIP archive. `mimetype` names the project type, `manifest` (JSON) lists the
//! artboards under `artwork` with their bounds (`uxdesign#bounds`) and the folder each one's
//! layers are in (`artwork/<folder>/graphics/graphicContent.agc`, JSON); `pasteboard` holds the
//! layers outside artboards. `resources/graphics/graphicContent.agc` holds what layers refer to
//! by id (gradients, clip paths) and `resources/<uid>` the image files. Layers are `shape` (a
//! `rect`, `circle`, `line` or SVG `path`), `text` and `group`, each with a 2D affine
//! `transform` into its parent's space; an artboard's layers are in document coordinates.
//!
//! The layers map onto the REST API file JSON shape and the REST importer builds the document,
//! as for `.sketch` files, so the import shares its budgets and import report. All artboards land
//! on one page, as frames. Anything not understood is skipped with a warning; malformed input
//! never panics.
use std::cell::RefCell;
use std::collections::BTreeSet;
use figcraft_doc::Document;
use figcraft_doc::geom::{Affine, Shape};
use serde_json::{Map, Value, json};
use crate::FormatError;
#[cfg(test)]
mod tests;
/// What `mimetype` starts with in an XD file.
const MIME: &[u8] = b"application/vnd.adobe.sparkler.project";
const MAX_ENTRIES: u64 = 100_000;
/// Most bytes all members read may expand to together, and most one JSON member may.
const MAX_TOTAL: u64 = 1 << 30;
const MAX_JSON: u64 = 256 << 20;
const MAX_NOTES: usize = 100;
/// Longest SVG path data read for one shape.
const MAX_PATH: usize = 4 << 20;
/// Point text is anchored at its first baseline; the import places its top this share of the font
/// size above it. The editor measures the real ascent when fonts are at hand and moves the text by
/// the difference (`figcraft_engine`'s XD load).
pub const POINT_ASCENT: f64 = 0.8;
/// Read the `.xd` file `bytes` into a document named `name`, with notes on what was left out.
pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec<String>), FormatError> {
let limits = craft_zip::Limits { max_entries: MAX_ENTRIES, max_total_bytes: MAX_TOTAL };
let mut zip = craft_zip::Archive::open(bytes, limits).map_err(|e| corrupt(format!("not an XD file ({e})")))?;
if !zip.read("mimetype", 256).ok().flatten().is_some_and(|m| m.starts_with(MIME)) {
return Err(corrupt("not an XD file (no XD project type in `mimetype`)"));
}
let manifest = read_json(&mut zip, "manifest")?.ok_or_else(|| corrupt("the file has no `manifest`"))?;
let resources = read_json(&mut zip, "resources/graphics/graphicContent.agc").ok().flatten().unwrap_or(Value::Null);
let max_nodes = crate::fig::layer_budget(bytes.len());
let mut cx = Cx { resources: &resources, warnings: Vec::new(), seen: BTreeSet::new(), ids: 0, nodes: 0, max_nodes };
let artwork = list(&manifest, "children").iter().find(|c| str_of(c, "path") == Some("artwork"));
let mut layers = Vec::new();
for entry in artwork.map_or(&[][..], |a| list(a, "children")) {
let Some(folder) = str_of(entry, "path").filter(|p| is_safe_name(p)) else {
cx.warn("artboards with an unreadable folder name were skipped");
continue;
};
let agc = match read_json(&mut zip, &format!("artwork/{folder}/graphics/graphicContent.agc")) {
Ok(Some(agc)) => agc,
_ => {
cx.warn("artboards whose layers are missing or damaged were skipped");
continue;
}
};
if folder == "pasteboard" {
layers.extend(list(&agc, "children").iter().filter_map(|c| cx.node(c, Affine::IDENTITY)));
} else {
layers.extend(cx.artboard(entry, &agc));
}
}
let page = json!({"id": "0:1", "name": "Page 1", "type": "CANVAS", "children": layers});
let json = json!({"name": name, "document": {"id": "0:0", "type": "DOCUMENT", "children": [page]}});
let zip = RefCell::new(zip);
let image_max = figcraft_doc::ImageData::MAX_BYTES;
let images = |uid: &str| is_safe_name(uid).then(|| zip.borrow_mut().read(&format!("resources/{uid}"), image_max).ok().flatten()).flatten();
let (doc, more) = crate::rest::import_with_networks_plain(&json, &images, Vec::new(), max_nodes)?;
let mut warnings = cx.warnings;
warnings.extend(more);
Ok((doc, warnings))
}
/// The mapping's state while walking the file.
struct Cx<'a> {
/// `resources/graphics/graphicContent.agc`: gradients and clip paths by id.
resources: &'a Value,
warnings: Vec<String>,
seen: BTreeSet<String>,
/// REST ids handed out, and layers mapped so far against the most the file may give.
ids: u64,
nodes: usize,
max_nodes: usize,
}
impl Cx<'_> {
fn warn(&mut self, msg: impl Into<String>) {
let msg = msg.into();
if self.seen.len() <= MAX_NOTES && self.seen.insert(msg.clone()) {
self.warnings.push(if self.seen.len() > MAX_NOTES { "more notes were left out".into() } else { msg });
}
}
fn id(&mut self) -> String {
self.ids += 1;
format!("1:{}", self.ids)
}
/// The frame of an artboard: its bounds from the manifest entry, its layers from `agc`.
fn artboard(&mut self, entry: &Value, agc: &Value) -> Option<Value> {
let board = list(agc, "children").iter().find(|c| str_of(c, "type") == Some("artboard"))?;
let bounds = entry.get("uxdesign#bounds").or_else(|| {
let id = board.get("artboard").and_then(|a| str_of(a, "ref"))?;
self.resources.get("artboards")?.get(id)
});
let Some((x, y, w, h)) = bounds.and_then(|b| Some((num(b, "x")?, num(b, "y")?, num(b, "width")?, num(b, "height")?))) else {
self.warn("artboards without bounds were skipped");
return None;
};
// An artboard's layers are in document coordinates; the frame's children are in its own.
let inside = Affine::translate((-x, -y));
let kids = board.get("artboard").map_or(&[][..], |a| list(a, "children"));
let children: Vec<Value> = kids.iter().filter_map(|c| self.node(c, inside)).collect();
let style = board.get("style");
Some(json!({
"id": self.id(),
"name": str_of(entry, "name").unwrap_or("Artboard"),
"type": "FRAME",
"relativeTransform": rows(Affine::translate((x, y))),
"size": {"x": w, "y": h},
"fills": style.and_then(|s| s.get("fill")).and_then(|f| self.paint(f)).into_iter().collect::<Vec<_>>(),
"clipsContent": true,
"children": children,
}))
}
/// One layer, with `parent` taking its parent's space to the enclosing frame's. (Nesting is
/// bounded by the JSON reader's own depth limit: clip paths add only shapes.)
fn node(&mut self, j: &Value, parent: Affine) -> Option<Value> {
if self.nodes >= self.max_nodes {
self.warn("the file has more layers than the import handles; the rest were skipped");
return None;
}
self.nodes += 1;
let m = parent * transform(j.get("transform"));
let mut out = match str_of(j, "type")? {
"shape" => self.shape(j, m)?,
"text" => self.text(j, m)?,
"group" => self.group(j, m)?,
other => {
self.warn(format!("{} layers are not supported and were skipped", clip(other)));
return None;
}
};
let style = j.get("style");
out.insert("id".into(), self.id().into());
if let Some(n) = str_of(j, "name") {
out.insert("name".into(), clip(n).into());
}
if let Some(o) = style.and_then(|s| num(s, "opacity")) {
out.insert("opacity".into(), o.clamp(0.0, 1.0).into());
}
if j.get("visible").and_then(Value::as_bool) == Some(false) {
out.insert("visible".into(), false.into());
}
self.effects(style, &mut out);
Some(Value::Object(out))
}
fn shape(&mut self, j: &Value, m: Affine) -> Option<Map<String, Value>> {
let s = j.get("shape")?;
let mut out = match str_of(s, "type")? {
"rect" => {
let (x, y) = (num(s, "x").unwrap_or(0.0), num(s, "y").unwrap_or(0.0));
let mut o = placed("RECTANGLE", m * Affine::translate((x, y)), num(s, "width")?, num(s, "height")?);
// The radii are top left, top right, bottom right, bottom left, as REST lists them.
match s.get("r") {
Some(Value::Array(r)) if r.len() == 4 => {
o.insert("rectangleCornerRadii".into(), r.iter().map(|v| v.as_f64().unwrap_or(0.0).max(0.0)).collect::<Vec<_>>().into());
}
Some(r) if r.is_number() => {
o.insert("cornerRadius".into(), r.clone());
}
_ => {}
}
o
}
"circle" => {
let r = num(s, "r")?.max(0.0);
let (cx, cy) = (num(s, "cx").unwrap_or(r), num(s, "cy").unwrap_or(r));
placed("ELLIPSE", m * Affine::translate((cx - r, cy - r)), 2.0 * r, 2.0 * r)
}
"line" => {
let p = |k: &str| num(s, k).unwrap_or(0.0);
self.vector(&format!("M{} {}L{} {}", p("x1"), p("y1"), p("x2"), p("y2")), m)?
}
"path" => self.vector(str_of(s, "path")?, m)?,
other => {
self.warn(format!("{} shapes are not supported and were skipped", clip(other)));
return None;
}
};
self.paints(j.get("style"), &mut out);
Some(out)
}
/// A vector layer from SVG path data in the layer's space, its box fitted to the path.
fn vector(&mut self, d: &str, m: Affine) -> Option<Map<String, Value>> {
let path = (d.len() <= MAX_PATH).then(|| figcraft_doc::geom::svg_path(d).ok()).flatten();
let Some(mut path) = path.filter(|p| !p.elements().is_empty()) else {
self.warn("shapes with invalid or oversized path data were skipped");
return None;
};
let b = path.bounding_box();
if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) {
self.warn("shapes with invalid or oversized path data were skipped");
return None;
}
path.apply_affine(Affine::translate((-b.x0, -b.y0)));
let mut o = placed("VECTOR", m * Affine::translate((b.x0, b.y0)), b.width(), b.height());
o.insert("fillGeometry".into(), json!([{"path": path.to_svg(), "windingRule": "NONZERO"}]));
Some(o)
}
fn group(&mut self, j: &Value, m: Affine) -> Option<Map<String, Value>> {
let kids = j.get("group").map_or(&[][..], |g| list(g, "children"));
let mut children: Vec<Value> = kids.iter().filter_map(|c| self.node(c, m)).collect();
// A clip path masks the group: the mask goes first, under the layers it shows.
let clip_ref = j.get("style").and_then(|s| s.get("clipPath")).and_then(|c| str_of(c, "ref"));
if let Some(r) = clip_ref {
let resources = self.resources;
let shapes = resources.get("resources").and_then(|r| r.get("clipPaths")).and_then(|c| c.get(r)).map_or(&[][..], |c| list(c, "children"));
// Only plain shapes clip, so a clip path naming itself (or another one) can't recurse.
if shapes.iter().any(|s| str_of(s, "type") != Some("shape")) {
self.warn("clip paths made of anything but shapes were skipped");
}
let masks: Vec<Value> = shapes
.iter()
.filter(|s| str_of(s, "type") == Some("shape"))
.filter_map(|s| self.node(s, m))
.map(|mut s| {
// Only the outline clips: opaque, whatever the clip shape's own fill.
s["isMask"] = true.into();
s["name"] = "Clip".into();
s["fills"] = json!([{"type": "SOLID", "color": {"r": 0, "g": 0, "b": 0, "a": 1}}]);
s
})
.collect();
if masks.is_empty() {
self.warn("clipped groups whose clip shape is missing show unclipped");
}
children.splice(0..0, masks);
}
if children.is_empty() {
return None;
}
let mut o = placed("GROUP", m, 0.0, 0.0);
o.insert("children".into(), children.into());
Some(o)
}
fn text(&mut self, j: &Value, m: Affine) -> Option<Map<String, Value>> {
let t = j.get("text")?;
let raw = str_of(t, "rawText").unwrap_or("");
// The last paragraph ends with a line break the text doesn't show.
let characters = raw.strip_suffix('\n').unwrap_or(raw);
let style = j.get("style");
let font = style.and_then(|s| s.get("font"));
let attrs = style.and_then(|s| s.get("textAttributes"));
let size = font.and_then(|f| num(f, "size")).filter(|s| *s > 0.0).unwrap_or(12.0);
let align = match attrs.and_then(|a| str_of(a, "paragraphAlign")) {
Some("center") => "CENTER",
Some("right") => "RIGHT",
_ => "LEFT",
};
let frame = t.get("frame");
let area = frame.and_then(|f| Some((num(f, "width")?, num(f, "height")?)));
let (at, w, h, resize) = match area {
Some((w, h)) => (m, w, h, "NONE"),
None => {
// Point text: the origin is the first baseline at the aligned edge. Its width is
// what centred and right-aligned lines start left of that edge.
let lines: Vec<&Value> = list(t, "paragraphs").iter().flat_map(|p| list(p, "lines")).collect();
let start = lines.iter().filter_map(|l| l.get(0)).filter_map(|s| num(s, "x")).fold(0.0_f64, f64::min);
let baseline = lines.first().and_then(|l| l.get(0)).and_then(|s| num(s, "y")).unwrap_or(0.0);
let guess = characters.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64 * size * 0.55;
let w = match align {
"CENTER" if start < 0.0 => -2.0 * start,
"RIGHT" if start < 0.0 => -start,
_ => guess,
}
.max(1.0);
let left = match align {
"CENTER" => -w / 2.0,
"RIGHT" => -w,
_ => 0.0,
};
let h = lines.len().max(1) as f64 * size * 1.2;
(m * Affine::translate((left, baseline - POINT_ASCENT * size)), w, h, "WIDTH_AND_HEIGHT")
}
};
let mut s = Map::new();
if let Some(f) = font {
for (from, to) in [("family", "fontFamily"), ("postscriptName", "fontPostScriptName"), ("style", "fontStyle")] {
if let Some(v) = str_of(f, from) {
s.insert(to.into(), clip(v).into());
}
}
}
s.insert("fontSize".into(), size.into());
s.insert("textAlignHorizontal".into(), align.into());
s.insert("textAutoResize".into(), resize.into());
// Character spacing is in thousandths of the font size.
if let Some(ls) = attrs.and_then(|a| num(a, "letterSpacing")) {
s.insert("letterSpacing".into(), (ls * size / 1000.0).into());
}
// Distance between baselines in pixels; 0 is the font's own.
if let Some(lh) = attrs.and_then(|a| num(a, "lineHeight")).filter(|l| *l > 0.0) {
s.insert("lineHeightPx".into(), lh.into());
s.insert("lineHeightUnit".into(), "PIXELS".into());
}
let mut o = placed("TEXT", at, w, h);
o.insert("characters".into(), characters.into());
o.insert("style".into(), Value::Object(s));
let ranges = j.get("meta").and_then(|m| m.get("ux")).map_or(&[][..], |u| list(u, "rangedStyles"));
if !ranges.is_empty() {
self.ranges(ranges, characters, size, &mut o);
}
self.paints(style, &mut o);
Some(o)
}
/// Styled ranges of a text, as per-character style overrides (ranges count UTF-16 units).
fn ranges(&mut self, ranges: &[Value], characters: &str, base_size: f64, o: &mut Map<String, Value>) {
let units = characters.encode_utf16().count();
let mut per_unit: Vec<u64> = Vec::with_capacity(units);
let mut table = Map::new();
for (i, r) in ranges.iter().enumerate() {
let len = r.get("length").and_then(Value::as_u64).and_then(|l| usize::try_from(l).ok()).unwrap_or(0);
let take = len.min(units - per_unit.len());
let key = i as u64 + 1;
per_unit.extend(std::iter::repeat_n(key, take));
let mut s = Map::new();
for (from, to) in [("fontFamily", "fontFamily"), ("fontStyle", "fontStyle"), ("postscriptName", "fontPostScriptName")] {
if let Some(v) = str_of(r, from) {
s.insert(to.into(), clip(v).into());
}
}
let size = num(r, "fontSize").filter(|s| *s > 0.0);
if let Some(size) = size {
s.insert("fontSize".into(), size.into());
}
if let Some(cs) = num(r, "charSpacing") {
s.insert("letterSpacing".into(), (cs * size.unwrap_or(base_size) / 1000.0).into());
}
if let Some(argb) = r.get("fill").and_then(|f| f.get("value")).and_then(Value::as_u64) {
s.insert("fills".into(), json!([{"type": "SOLID", "color": argb_color(argb)}]));
}
if r.get("underline").and_then(Value::as_bool) == Some(true) {
s.insert("textDecoration".into(), "UNDERLINE".into());
} else if r.get("strikethrough").and_then(Value::as_bool) == Some(true) {
s.insert("textDecoration".into(), "STRIKETHROUGH".into());
}
table.insert(key.to_string(), Value::Object(s));
if per_unit.len() == units {
break;
}
}
o.insert("characterStyleOverrides".into(), per_unit.into());
o.insert("styleOverrideTable".into(), Value::Object(table));
}
/// The layer's fill and stroke.
fn paints(&mut self, style: Option<&Value>, o: &mut Map<String, Value>) {
let fill = style.and_then(|s| s.get("fill")).and_then(|f| self.paint(f));
o.insert("fills".into(), fill.into_iter().collect::<Vec<_>>().into());
let stroke = style.and_then(|s| s.get("stroke"));
if let Some(p) = stroke.and_then(|s| self.paint(s)) {
let s = stroke.unwrap_or(&Value::Null);
o.insert("strokes".into(), json!([p]));
o.insert("strokeWeight".into(), num(s, "width").unwrap_or(1.0).max(0.0).into());
let align = match str_of(s, "align") {
Some("inside") => "INSIDE",
Some("outside") => "OUTSIDE",
_ => "CENTER",
};
o.insert("strokeAlign".into(), align.into());
}
}
fn paint(&mut self, p: &Value) -> Option<Value> {
match str_of(p, "type")? {
"none" => None,
"solid" => Some(json!({"type": "SOLID", "color": color(p.get("color")?)})),
"gradient" => {
let g = p.get("gradient")?;
let def = str_of(g, "ref").and_then(|r| self.resources.get("resources")?.get("gradients")?.get(r));
if def.and_then(|d| str_of(d, "type")) != Some("linear") {
self.warn("gradients other than linear ones were skipped");
return None;
}
let stops: Vec<Value> = def
.map_or(&[][..], |d| list(d, "stops"))
.iter()
.filter_map(|s| Some(json!({"position": num(s, "offset")?.clamp(0.0, 1.0), "color": color(s.get("color")?)})))
.collect();
// The ends are shares of the layer's box, as REST handles are.
let at = |x: &str, y: &str| json!({"x": num(g, x).unwrap_or(0.0), "y": num(g, y).unwrap_or(0.0)});
Some(json!({"type": "GRADIENT_LINEAR", "gradientHandlePositions": [at("x1", "y1"), at("x2", "y2")], "gradientStops": stops}))
}
"pattern" => {
let uid = p.get("pattern").and_then(|p| p.get("meta")).and_then(|m| m.get("ux")).and_then(|u| str_of(u, "uid"));
let Some(uid) = uid.filter(|u| is_safe_name(u)) else {
self.warn("image fills without an image in the file were skipped");
return None;
};
Some(json!({"type": "IMAGE", "imageRef": uid, "scaleMode": "FILL"}))
}
other => {
self.warn(format!("{} fills are not supported and were skipped", clip(other)));
None
}
}
}
/// The layer's shadows and blurs (a background blur's fill opacity scales the fills).
fn effects(&mut self, style: Option<&Value>, o: &mut Map<String, Value>) {
let mut out = Vec::new();
for f in style.map_or(&[][..], |s| list(s, "filters")) {
let params = f.get("params").unwrap_or(&Value::Null);
match str_of(f, "type") {
Some("dropShadow") => out.extend(list(params, "dropShadows").iter().map(|d| {
json!({
"type": "DROP_SHADOW",
"offset": {"x": num(d, "dx").unwrap_or(0.0), "y": num(d, "dy").unwrap_or(0.0)},
"radius": num(d, "r").unwrap_or(0.0).max(0.0),
"color": d.get("color").map_or_else(|| json!({"r": 0, "g": 0, "b": 0, "a": 0.25}), color),
})
})),
Some("uxdesign#blur") => {
let background = params.get("backgroundEffect").and_then(Value::as_bool) == Some(true);
if background {
if num(params, "brightnessAmount").unwrap_or(0.0) != 0.0 {
self.warn("background blur brightness was not imported");
}
let opacity = num(params, "fillOpacity").unwrap_or(1.0).clamp(0.0, 1.0);
for fill in o.get_mut("fills").and_then(Value::as_array_mut).into_iter().flatten() {
fill["opacity"] = opacity.into();
}
}
let kind = if background { "BACKGROUND_BLUR" } else { "LAYER_BLUR" };
out.push(json!({"type": kind, "radius": num(params, "blurAmount").unwrap_or(0.0).max(0.0)}));
}
Some(other) => self.warn(format!("{} effects are not supported and were skipped", clip(other))),
None => {}
}
}
if !out.is_empty() {
o.insert("effects".into(), out.into());
}
}
}
/// A REST layer of type `ty` at `at` (into the enclosing frame) with size `w` × `h`.
fn placed(ty: &str, at: Affine, w: f64, h: f64) -> Map<String, Value> {
let mut o = Map::new();
o.insert("type".into(), ty.into());
o.insert("relativeTransform".into(), rows(at));
o.insert("size".into(), json!({"x": w.max(0.0), "y": h.max(0.0)}));
o
}
/// REST's `[[a, c, e], [b, d, f]]`.
fn rows(t: Affine) -> Value {
let [a, b, c, d, e, f] = t.as_coeffs();
json!([[a, c, e], [b, d, f]])
}
/// An XD `{a, b, c, d, tx, ty}` matrix; anything missing or not finite reads as no transform.
fn transform(t: Option<&Value>) -> Affine {
let Some(t) = t else { return Affine::IDENTITY };
let k = |key: &str, default: f64| t.get(key).map_or(Some(default), |v| v.as_f64().filter(|x| x.is_finite()));
match (k("a", 1.0), k("b", 0.0), k("c", 0.0), k("d", 1.0), k("tx", 0.0), k("ty", 0.0)) {
(Some(a), Some(b), Some(c), Some(d), Some(e), Some(f)) => Affine::new([a, b, c, d, e, f]),
_ => Affine::IDENTITY,
}
}
/// An XD colour (`{mode, value: {r, g, b}, alpha?}`, channels 0–255) as a REST colour.
fn color(c: &Value) -> Value {
let v = c.get("value").unwrap_or(&Value::Null);
let ch = |k: &str| (num(v, k).unwrap_or(0.0) / 255.0).clamp(0.0, 1.0);
json!({"r": ch("r"), "g": ch("g"), "b": ch("b"), "a": num(c, "alpha").unwrap_or(1.0).clamp(0.0, 1.0)})
}
/// A colour packed as an ARGB integer (alpha in the high byte).
fn argb_color(v: u64) -> Value {
let ch = |shift: u32| ((v >> shift) & 0xff) as f64 / 255.0;
json!({"r": ch(16), "g": ch(8), "b": ch(0), "a": ch(24)})
}
fn read_json(zip: &mut craft_zip::Archive<'_>, name: &str) -> Result<Option<Value>, FormatError> {
let Some(bytes) = zip.read(name, MAX_JSON).map_err(|e| corrupt(e.to_string()))? else { return Ok(None) };
serde_json::from_slice(&bytes).map(Some).map_err(|e| corrupt(format!("{name}: {e}")))
}
/// A member or folder name made only of letters, digits, `-` and `_` (no path of its own).
fn is_safe_name(s: &str) -> bool {
!s.is_empty() && s.len() <= 128 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
fn corrupt(msg: impl Into<String>) -> FormatError {
FormatError::Corrupt(msg.into())
}
fn list<'v>(v: &'v Value, key: &str) -> &'v [Value] {
v.get(key).and_then(Value::as_array).map_or(&[], Vec::as_slice)
}
fn str_of<'v>(v: &'v Value, key: &str) -> Option<&'v str> {
v.get(key).and_then(Value::as_str)
}
fn num(v: &Value, key: &str) -> Option<f64> {
v.get(key).and_then(Value::as_f64).filter(|x| x.is_finite())
}
/// Names and kinds from the file, cut to a length a note or layer name can hold.
fn clip(s: &str) -> String {
s.chars().take(200).collect()
}
+206
View File
@@ -0,0 +1,206 @@
use std::io::{Cursor, Write};
use figcraft_doc::geom::Point;
use figcraft_doc::{Document, Node, NodeKind};
use serde_json::{Value, json};
use zip::write::SimpleFileOptions;
use super::import;
/// An `.xd` archive (built here, from our own made-up content) with `members` besides `mimetype`.
pub(crate) fn archive(members: &[(&str, Value)]) -> Vec<u8> {
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
z.start_file("mimetype", SimpleFileOptions::default()).unwrap();
z.write_all(b"application/vnd.adobe.sparkler.project+dcxucf").unwrap();
for (name, v) in members {
z.start_file(*name, SimpleFileOptions::default()).unwrap();
z.write_all(v.to_string().as_bytes()).unwrap();
}
z.finish().unwrap().into_inner()
}
/// One artboard named "Home" at `(x, y)`, 400 × 300, holding `layers` (in document coordinates).
pub(crate) fn one_board(x: f64, y: f64, layers: Value, resources: Value) -> Vec<u8> {
let manifest = json!({"children": [{"path": "artwork", "children": [
{"path": "pasteboard"},
{"path": "artboard-a1", "name": "Home", "uxdesign#bounds": {"x": x, "y": y, "width": 400, "height": 300}}
]}]});
let board = json!({"children": [{"type": "artboard", "artboard": {"children": layers},
"style": {"fill": {"type": "solid", "color": {"mode": "RGB", "value": {"r": 255, "g": 255, "b": 255}}}}}]});
archive(&[
("manifest", manifest),
("artwork/pasteboard/graphics/graphicContent.agc", json!({"children": []})),
("artwork/artboard-a1/graphics/graphicContent.agc", board),
("resources/graphics/graphicContent.agc", json!({"resources": resources})),
])
}
fn at(tx: f64, ty: f64) -> Value {
json!({"a": 1, "b": 0, "c": 0, "d": 1, "tx": tx, "ty": ty})
}
fn solid(r: u8, g: u8, b: u8) -> Value {
json!({"type": "solid", "color": {"mode": "RGB", "value": {"r": r, "g": g, "b": b}}})
}
fn named<'d>(doc: &'d Document, name: &str) -> &'d Node {
doc.nodes().find(|n| n.name == name).unwrap_or_else(|| panic!("no layer {name}"))
}
fn origin(doc: &Document, name: &str) -> Point {
doc.world_transform(named(doc, name).id) * Point::ORIGIN
}
#[test]
fn artboards_become_frames_with_their_layers_inside() {
let layers = json!([
{"type": "shape", "name": "Card", "transform": at(1020.0, 540.0), "style": {"fill": solid(200, 10, 10)},
"shape": {"type": "rect", "x": 0, "y": 0, "width": 100, "height": 50, "r": [8, 8, 0, 0]}},
{"type": "group", "name": "Icons", "transform": at(1100.0, 600.0), "group": {"children": [
{"type": "shape", "name": "Dot", "transform": at(10.0, 0.0), "style": {"fill": solid(0, 0, 255)},
"shape": {"type": "circle", "cx": 8, "cy": 8, "r": 8}},
{"type": "shape", "name": "Chevron", "transform": at(40.0, 0.0),
"style": {"stroke": {"type": "solid", "color": {"mode": "RGB", "value": {"r": 0, "g": 0, "b": 0}}, "width": 2}},
"shape": {"type": "path", "path": "M 2 2 L 8 6 L 2 10"}}
]}}
]);
let (doc, warnings) = import(&one_board(1000.0, 500.0, layers, json!({})), "Design").unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
let home = named(&doc, "Home");
assert!(home.kind.is_frame_like() && home.clip, "artboards are clipping frames");
let card = named(&doc, "Card");
assert_eq!(card.parent, Some(home.id));
// Placed inside the frame where the document coordinates put it.
let (frame, c) = (origin(&doc, "Home"), origin(&doc, "Card"));
assert!((c.x - frame.x - 20.0).abs() < 1e-6 && (c.y - frame.y - 40.0).abs() < 1e-6, "{c:?} in {frame:?}");
assert!(card.corners.radii[0] > 0.0 && card.corners.radii[2] == 0.0, "per-corner radii kept: {:?}", card.corners.radii);
assert!(matches!(named(&doc, "Icons").kind, NodeKind::Group));
assert!(matches!(named(&doc, "Dot").kind, NodeKind::Ellipse { .. }));
let chevron = named(&doc, "Chevron");
assert!(matches!(chevron.kind, NodeKind::Vector { .. }) && !chevron.strokes.is_empty() && chevron.fills.is_empty());
// The group's offset carries to its layers, and the vector's box starts where its path does.
let (dot, chev) = (origin(&doc, "Dot"), origin(&doc, "Chevron"));
assert!((chev.x - dot.x - 32.0).abs() < 1e-6 && (chev.y - dot.y - 2.0).abs() < 1e-6, "{chev:?} vs {dot:?}");
}
#[test]
fn gradients_images_clips_shadows_and_ranged_text_come_across() {
let layers = json!([
{"type": "shape", "name": "Banner", "transform": at(0.0, 0.0),
"style": {"fill": {"type": "gradient", "gradient": {"x1": 0, "y1": 0.5, "x2": 1, "y2": 0.5, "units": "objectBoundingBox", "ref": "g1"}},
"filters": [{"type": "dropShadow", "params": {"dropShadows": [{"dx": 0, "dy": 3, "r": 6,
"color": {"mode": "RGB", "value": {"r": 0, "g": 0, "b": 0}, "alpha": 0.2}}]}}]},
"shape": {"type": "rect", "x": 0, "y": 0, "width": 200, "height": 40}},
{"type": "shape", "name": "Photo", "transform": at(0.0, 50.0),
"style": {"fill": {"type": "pattern", "pattern": {"width": 10, "height": 10, "meta": {"ux": {"scaleBehavior": "fill", "uid": "abc123"}}}}},
"shape": {"type": "rect", "x": 0, "y": 0, "width": 100, "height": 100}},
{"type": "group", "name": "Grid", "transform": at(0.0, 200.0), "style": {"clipPath": {"ref": "c1"}}, "group": {"children": [
{"type": "shape", "name": "Cell", "transform": at(0.0, 0.0), "style": {"fill": solid(1, 2, 3)},
"shape": {"type": "rect", "x": 0, "y": 0, "width": 300, "height": 300}}
]}},
{"type": "text", "name": "Title", "transform": at(200.0, 100.0),
"meta": {"ux": {"rangedStyles": [
{"length": 4, "fontFamily": "Sans", "fontStyle": "Bold", "fontSize": 20, "charSpacing": 0, "fill": {"value": 4294901760_u64}},
{"length": 6, "fontFamily": "Sans", "fontStyle": "Regular", "fontSize": 20, "charSpacing": 0, "fill": {"value": 4278190080_u64}}
]}},
"style": {"fill": solid(0, 0, 0), "font": {"family": "Sans", "style": "Regular", "size": 20}, "textAttributes": {"paragraphAlign": "center", "letterSpacing": 50}},
"text": {"frame": {"type": "positioned"}, "paragraphs": [{"lines": [[{"x": -50, "y": 0, "from": 0, "to": 10}]]}], "rawText": "Big plain\n"}},
{"type": "text", "name": "Link", "transform": at(0.0, 300.0),
"meta": {"ux": {"rangedStyles": [{"length": 4, "fontFamily": "Sans", "fontSize": 12, "underline": true, "fill": {"value": 4278190080_u64}}]}},
"style": {"fill": solid(0, 0, 0), "font": {"family": "Sans", "style": "Regular", "size": 12}},
"text": {"frame": {"type": "area", "width": 100, "height": 20}, "paragraphs": [], "rawText": "Docs"}}
]);
let resources = json!({
"gradients": {"g1": {"type": "linear", "stops": [
{"offset": 0, "color": {"mode": "RGB", "value": {"r": 255, "g": 0, "b": 0}}},
{"offset": 1, "color": {"mode": "RGB", "value": {"r": 0, "g": 0, "b": 255}}}]}},
"clipPaths": {"c1": {"type": "clipPath", "children": [{"type": "shape", "shape": {"type": "rect", "x": 0, "y": 0, "width": 50, "height": 50}}]}}
});
let (doc, _) = import(&one_board(0.0, 0.0, layers, resources), "Design").unwrap();
let banner = named(&doc, "Banner");
assert!(matches!(banner.fills[0].kind, figcraft_doc::color::PaintKind::Gradient(_)));
assert_eq!(banner.effects.len(), 1);
// The image isn't in the archive: the layer still has its image fill (shown as missing).
assert!(matches!(named(&doc, "Photo").fills[0].kind, figcraft_doc::color::PaintKind::Image(_)));
let grid = named(&doc, "Grid");
let first = doc.node(grid.children[0]).unwrap();
assert!(first.is_mask && first.fills.iter().any(|f| f.visible && f.opacity > 0.0), "the clip path masks the group's layers, opaque");
assert!(grid.height < 300.0, "the group takes the clip's bounds, not the cell's");
let title = named(&doc, "Title");
let NodeKind::Text(t) = &title.kind else { panic!("not text") };
assert_eq!(t.characters, "Big plain", "the closing line break is dropped");
assert!(t.runs.len() >= 2, "each styled range keeps its style: {:?}", t.runs);
assert!(t.style.letter_spacing.resolve(20.0) > 0.0, "character spacing is a share of the size");
// One range over the whole text keeps what only ranges carry.
let NodeKind::Text(link) = &named(&doc, "Link").kind else { panic!("not text") };
let underlined = |st: &figcraft_doc::TextStyle| st.decoration == figcraft_doc::TextDecoration::Underline;
assert!(underlined(&link.style) || link.runs.iter().any(|r| underlined(&r.style)), "{link:?}");
// Centred point text sits centred on its anchor.
let o = origin(&doc, "Title");
assert!((o.x + title.width / 2.0 - 200.0).abs() < 1e-6 && o.y < 100.0, "{o:?} width {}", title.width);
}
#[test]
fn pasteboard_layers_and_unknown_kinds() {
let manifest = json!({"children": [{"path": "artwork", "children": [{"path": "pasteboard"}, {"path": "../evil", "name": "Bad"}]}]});
let paste = json!({"children": [
{"type": "shape", "name": "Loose", "transform": at(-50.0, -60.0), "style": {"fill": solid(9, 9, 9)},
"shape": {"type": "rect", "x": 0, "y": 0, "width": 10, "height": 10}},
{"type": "widget", "name": "Odd"}
]});
let bytes = archive(&[("manifest", manifest), ("artwork/pasteboard/graphics/graphicContent.agc", paste)]);
let (doc, warnings) = import(&bytes, "Loose").unwrap();
let o = origin(&doc, "Loose");
assert!((o.x + 50.0).abs() < 1e-6 && (o.y + 60.0).abs() < 1e-6);
assert!(warnings.iter().any(|w| w.contains("widget")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("folder")), "{warnings:?}");
}
#[test]
fn damaged_and_hostile_files_fail_cleanly() {
assert!(import(b"not a zip", "x").is_err());
// A ZIP without the XD project type.
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
z.start_file("manifest", SimpleFileOptions::default()).unwrap();
z.write_all(b"{}").unwrap();
assert!(import(&z.finish().unwrap().into_inner(), "x").is_err());
// No manifest, a broken one, and an artboard whose layers are not JSON.
assert!(import(&archive(&[]), "x").is_err());
let manifest = json!({"children": [{"path": "artwork", "children": [{"path": "artboard-b", "name": "B", "uxdesign#bounds": {"x": 0, "y": 0, "width": 1, "height": 1}}]}]});
let mut bytes = archive(&[("manifest", manifest)]);
let (_, warnings) = import(&bytes, "x").unwrap();
assert!(!warnings.is_empty());
bytes.truncate(bytes.len() / 2);
assert!(import(&bytes, "x").is_err());
// Nesting deeper than the JSON reader follows: that artboard is skipped with a note.
let mut deep = json!({"type": "shape", "shape": {"type": "rect", "width": 1, "height": 1}});
for _ in 0..400 {
deep = json!({"type": "group", "group": {"children": [deep]}});
}
let (_, warnings) = import(&one_board(0.0, 0.0, json!([deep]), json!({})), "x").unwrap();
assert!(warnings.iter().any(|w| w.contains("damaged")), "{warnings:?}");
// Odd values and wrong types everywhere.
let junk = json!([
{"type": "shape", "transform": {"a": "x", "tx": f64::MAX}, "shape": {"type": "rect", "width": -5, "height": null, "r": "big"}},
{"type": "shape", "shape": {"type": "path", "path": "M 1 1 L nonsense"}},
{"type": "shape", "shape": {"type": "circle"}},
{"type": "text", "text": {"rawText": 5, "paragraphs": "no"}, "meta": {"ux": {"rangedStyles": [{"length": 1e30}, {"length": -1}]}}},
{"type": "text", "text": {"rawText": "ab"}, "meta": {"ux": {"rangedStyles": [{"length": 99}, {"length": 99}]}}},
{"type": "group", "style": {"clipPath": {"ref": "missing"}}, "group": {"children": 3}},
{"type": "shape", "style": {"fill": {"type": "gradient", "gradient": {"ref": "nope"}}, "filters": [{"type": "x"}, 3]},
"shape": {"type": "rect", "width": 1, "height": 1}},
{"type": "shape", "style": {"fill": {"type": "pattern", "pattern": {"meta": {"ux": {"uid": "../../manifest"}}}}},
"shape": {"type": "rect", "width": 1, "height": 1}},
null, 7, "text"
]);
let (doc, warnings) = import(&one_board(0.0, 0.0, junk, json!({"clipPaths": 4})), "x").unwrap();
assert!(warnings.iter().any(|w| w.contains("path data")), "{warnings:?}");
assert!(doc.nodes().count() > 1);
// A clip path whose group is clipped by that same clip path doesn't recurse.
let looped = json!({"type": "group", "style": {"clipPath": {"ref": "c"}}, "group": {"children": [
{"type": "shape", "shape": {"type": "rect", "width": 5, "height": 5}}]}});
let clips = json!({"clipPaths": {"c": {"children": [looped.clone(), {"type": "shape", "shape": {"type": "rect", "width": 2, "height": 2}}]}}});
let (doc, warnings) = import(&one_board(0.0, 0.0, json!([looped]), clips), "x").unwrap();
assert!(warnings.iter().any(|w| w.contains("anything but shapes")), "{warnings:?}");
assert!(doc.nodes().any(|n| n.is_mask), "the clip path's own shape still clips");
}
+1 -1
View File
@@ -403,7 +403,7 @@ fn tools() -> Vec<Value> {
tool(
"open_file",
"Open file",
"Open a .figcraft or .json document (FigCraft or REST API file JSON), a .fig or .sketch file (best effort, with `warnings` for what wasn't imported; .sketch from Sketch 48 or newer), an .svg (becomes vectors) or an image (becomes an image layer) as the active document. Returns the new document's summary.",
"Open a .figcraft or .json document (FigCraft or REST API file JSON), a .fig, .sketch or .xd file (best effort, with `warnings` for what wasn't imported; .sketch from Sketch 48 or newer, .xd from Adobe XD), an .svg (becomes vectors) or an image (becomes an image layer) as the active document. Returns the new document's summary.",
obj(
json!({
"path": string("File path"),
+1 -1
View File
@@ -132,7 +132,7 @@ impl FigApp {
let exts: &[&str] = if place {
&["png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "heic", "heif"]
} else {
&["penpot", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "heic", "heif", "figcraft", "fig", "jam", "sketch"]
&["penpot", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "heic", "heif", "figcraft", "fig", "jam", "sketch", "xd"]
};
// Camera raw files place as the image they develop to; videos as a layer with a video fill.
let exts: Vec<&str> =
+3 -3
View File
@@ -5,7 +5,7 @@ use super::{OsStr, Path, theme};
/// The file types File ▸ Open and a drop on the home screen open.
pub(crate) const OPEN_EXTENSIONS: &[&str] =
&["figcraft", "fig", "jam", "penpot", "sketch", "json", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "heic", "heif"];
&["figcraft", "fig", "jam", "penpot", "sketch", "xd", "json", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "heic", "heif"];
/// [`OPEN_EXTENSIONS`] and the camera raw files, which open as an image too: what File ▸ Open offers.
pub(crate) fn open_extensions() -> Vec<&'static str> {
@@ -19,12 +19,12 @@ pub(crate) fn opens(path: &Path) -> bool {
.is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e)) || figcraft_format::raw::is_extension(e))
}
/// Whether `path` is a whole document (`.figcraft`, `.fig`, `.jam`, `.penpot`, `.sketch`, file JSON) rather than an image or SVG:
/// Whether `path` is a whole document (`.figcraft`, `.fig`, `.jam`, `.penpot`, `.sketch`, `.xd`, file JSON) rather than an image or SVG:
/// dropped on the canvas it opens as a file of its own instead of adding its pages to the open one.
pub(crate) fn is_document(path: &Path) -> bool {
path.extension()
.and_then(OsStr::to_str)
.is_some_and(|e| ["figcraft", "fig", "jam", "penpot", "sketch", "json"].iter().any(|x| x.eq_ignore_ascii_case(e)))
.is_some_and(|e| ["figcraft", "fig", "jam", "penpot", "sketch", "xd", "json"].iter().any(|x| x.eq_ignore_ascii_case(e)))
}
/// Reads the contents of dropped file `name` that has no file on disk to read by path.
+1 -1
View File
@@ -214,7 +214,7 @@ figcraft-cli export app.figcraft -o handoff.fig
### `convert <in> <out> [--in-place] [--strict]`
By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort),
`.penpot` (Penpot 2.x archive, best effort), `.svg` (an editable frame: groups,
`.xd` (Adobe XD, best effort), `.penpot` (Penpot 2.x archive, best effort), `.svg` (an editable frame: groups,
shapes, text, gradients, masks and effects; `info` lists what it left out as `note:` lines), `.png/.jpg/.webp/.gif/.tif/.bmp`
(an image layer), camera raw files (`.rw2`, `.cr2`, `.cr3`, `.nef`, `.arw`, `.raf`, `.orf`, `.dng` and the other
containers craft-raw reads: an image layer of the picture developed with the camera's as-shot white balance and a
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -521,7 +521,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
| `select {ids}` | Replace the selection (`[]` deselects). |
| `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?, quality?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`; `quality` is the JPG quality, 1 to 100 (default 90). The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps `<text>`, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (PNG: `sRGB` chunk, or ICC and `cICP` for Display P3; JPG: ICC profile; WebP: ICC profile for Display P3, none for sRGB) (SVG, XML and RGB PDF output are always sRGB; PDF with `cmyk` is DeviceCMYK). The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `<layer><suffix>.<format>`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG; `layout: "flutter" | "ios" | "android"` exports the layers as PNGs in that app project's folders instead: `2.0x/` and `3.0x/` folders, an `.imageset` with `@2x`, `@3x` and `Contents.json`, or `drawable-mdpi` … `drawable-xxxhdpi`, names in lower snake case). |
| `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. |
| `open_file {path, variables?, reload?}` / `save_file {path?}` | Open `.figcraft`, `.json` (FigCraft JSON or REST API file JSON with its variables, see below), `.fig` or FigJam `.jam` (best effort, see below), `.sketch` (Sketch 48 and newer, best effort), `.svg` (see Importing SVG below) or an image; save as `.figcraft`. `open_file` returns `opened` (for a file opened anew, a `summary` of `name`, `pages`, `layers` and `images`, and `warnings` or `repairs`; a file that was already open gives its `index`, with `stale: true` when the file changed on disk since that tab read or saved it; `reload: true` reads it again into the tab, refused while the tab has unsaved changes) and the document's `document` outline. |
| `open_file {path, variables?, reload?}` / `save_file {path?}` | Open `.figcraft`, `.json` (FigCraft JSON or REST API file JSON with its variables, see below), `.fig` or FigJam `.jam` (best effort, see below), `.sketch` (Sketch 48 and newer, best effort), `.xd` (Adobe XD, best effort, with `warnings`), `.svg` (see Importing SVG below) or an image; save as `.figcraft`. `open_file` returns `opened` (for a file opened anew, a `summary` of `name`, `pages`, `layers` and `images`, and `warnings` or `repairs`; a file that was already open gives its `index`, with `stale: true` when the file changed on disk since that tab read or saved it; `reload: true` reads it again into the tab, refused while the tab has unsaved changes) and the document's `document` outline. |
| `undo` / `redo` | Step through history. |
| `pointer {kind, x, y, to?, steps?, tool?, shift, alt, cmd, pressure?, pressureTo?}` | Mouse gestures in page coordinates with the current tool: `click`, `double`, `drag`, `down`, `move`, `up`, `hover`. A dragged layer drops into the frame or auto layout slot under the pointer, except one inside a group, a boolean group or an instance (outside its slots), which only moves. `pressure` (0–1) is pen pressure; a drag goes from `pressure` to `pressureTo` (see Brushes and pen pressure). |
| `key {key, shift, alt, cmd}` | A shortcut or key as if typed on the canvas (every default shortcut, tool keys, Escape, Delete, arrows, number keys for opacity, arrows that pan the view when nothing is selected; while editing text, the text shortcuts and then text editing keys). Keys are names like `A`, `0`, `Enter`, `ArrowLeft`, `=`, `/`, or egui's (`Plus`, `Questionmark`); `cmd` is Cmd on macOS and Ctrl elsewhere. |
+1 -1
View File
@@ -129,7 +129,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects
|---|---|---|---|---|---|
| Features (depth) | 35 | 63% | 28–67 (areas 1–13, 15, 16, 20) | The table above; core editor ~72% | this file |
| UI/UX fidelity | 15 | 58% | 40–60 | Look & feel compared side by side with UI3 (~65% by the builders); tool-by-tool interaction not yet compared (move and resize modifiers compared in Figma's web app on 2026-11-08 and matching, Ctrl/Cmd not measured; hover states and popovers not compared) (a cursor for every tool and modifier, number fields and panel widths built from the documentation, not compared); accessibility names and keyboard navigation landed | [ui-parity](ui-parity.md) |
| File formats | 12 | 61% | 5–10 | `.sketch` read (Sketch 48 and newer, best effort; 2026-10-21): live symbols, shared styles, Sketch 2025 frames and stacks, checked on three real files against Sketch's own renders (0.8–2% of pixels differ on average); `.fig` read, best effort, with editable vector networks and (2026-10-17) more fidelity, budgets for large files and an import report (tested on generated fixtures, not real files); layers copied from another design app paste the same way (tested only with clipboard HTML made from our own export), `.fig` write experimental (round trips through our own importer; written files open and draw in other software); REST JSON import, SVG in/out, PNG/JPG/WebP/PDF export solid, with a behaviour suite from the documentation | [file-format-parity](file-format-parity.md) |
| File formats | 12 | 61% | 5–10 | `.xd` read (best effort, 2026-12-02: layers, fills, text, images, clip paths; no components or prototype links yet); `.sketch` read (Sketch 48 and newer, best effort; 2026-10-21): live symbols, shared styles, Sketch 2025 frames and stacks, checked on three real files against Sketch's own renders (0.8–2% of pixels differ on average); `.fig` read, best effort, with editable vector networks and (2026-10-17) more fidelity, budgets for large files and an import report (tested on generated fixtures, not real files); layers copied from another design app paste the same way (tested only with clipboard HTML made from our own export), `.fig` write experimental (round trips through our own importer; written files open and draw in other software); REST JSON import, SVG in/out, PNG/JPG/WebP/PDF export solid, with a behaviour suite from the documentation | [file-format-parity](file-format-parity.md) |
| Collaboration | 10 | 13% | 52–104 | Local comments, version history and branches with review and merge; the multiplayer core (sync model, server ordering, client reconciliation, convergence tests) landed in #103, and live sessions (preview) co-edit a file hosted by a desktop app or kept on a self-hosted `figcraft-server` with edit and view links, joined from the app or the browser, with cursor chat and spotlight (`docs/collab-protocol.md`) | [collaboration-parity](collaboration-parity.md) |
| Stability | 8 | 55% | 20–40 | Never-crash lints, command guard with rollback, recovery copies, 963 tests incl. junk-parameter sweeps and a seeded retained-render walk; but two days old, one release (v0.2.0), no field reports, QA mostly on macOS | [gaps](gaps.md) |
| Performance | 6 | 60% | 30–60 | `cargo xtask bench`: 50k-layer page ~8 ms zoomed out, 10k-layer edits ~0.2 ms, 2,000-instance design system edits 4–64 ms; CPU (tiny-skia) canvas where Figma renders on the GPU; nothing timed against Figma on the same file | [hardware-parity](hardware-parity.md) |