use super::element::{attributes, elements, rust_name};
use super::ir::{channels, slug, wire, Scope};
use super::read::{call, tag};
use super::schema::{describe_issue, validate, with_defaults};
use super::source::meta;
use super::{Declared, Family};
use std::sync::OnceLock;
pub use super::{fragment, json, El, Json, Value};
elements! {
drawing: children;
artboard: children;
painting: children;
photo: children;
nest: children;
layer: children;
group: children;
rect: leaf;
ellipse: leaf;
polygon: leaf;
path: leaf;
text: leaf;
brush_stroke = "brush-stroke": leaf;
image: leaf;
raster_layer = "raster-layer": leaf;
link: leaf;
sketch: leaf;
transform: children;
offset: children;
array: children;
mirror: children;
stroke: children;
fill: children;
blur: children;
levels: children;
threshold: children;
adjust: children;
crop: children;
bucket_fill = "bucket-fill": children;
compound: children;
clip: children;
raster: children;
gradient: children;
mask: children;
line: leaf;
bucket: leaf;
gradient_fill = "gradientFill": leaf;
move_ = "move": leaf;
erase: leaf;
free_transform = "freeTransform": leaf;
text_layer = "textLayer": children;
fx: children;
drop_shadow = "dropShadow": leaf;
inner_shadow = "innerShadow": leaf;
outer_glow = "outerGlow": leaf;
inner_glow = "innerGlow": leaf;
bevel_emboss = "bevelEmboss": leaf;
satin: leaf;
color_overlay = "colorOverlay": leaf;
gradient_overlay = "gradientOverlay": leaf;
pattern_overlay = "patternOverlay": leaf;
exposure: children;
curves: children;
hsl: children;
vibrance: children;
color_balance = "colorBalance": children;
black_white = "blackWhite": children;
invert: children;
posterize: children;
develop: children;
gaussian_blur = "gaussianBlur": children;
unsharp_mask = "unsharpMask": children;
sharpen: children;
noise: children;
sheet: leaf;
stock: leaf;
options: leaf;
part: leaf;
engrave: leaf;
}
attributes! {
pub trait TwodAttrs {
id;
label;
disabled;
name;
visible;
opacity;
blend;
clip;
locked;
collapsed;
width;
height;
background;
dpi;
x;
y;
w;
h;
rx;
ry;
cx;
cy;
rotation;
sides;
radius;
d;
subpaths;
points;
text;
family;
font;
size;
weight;
align;
letter_spacing;
line_height;
fill;
stroke;
stroke_color;
stroke_width;
start_cap;
end_cap;
src;
inputs;
transform;
scale;
scale_x;
scale_y;
dx;
dy;
delta;
count;
count_x;
count_y;
sweep;
axis;
op;
kind;
erase;
texture;
tolerance;
contiguous;
selection;
color;
brightness;
contrast;
exposure;
gamma;
hue;
saturation;
lightness;
temperature;
vibrance;
in_black;
in_white;
out_black;
out_white;
level;
levels;
spacing;
asset;
annotations;
at;
drawing_scale;
from_end;
to_end;
routing;
ref_;
sketch;
unit;
brush;
mirror;
shape;
from;
to;
stops;
ev;
offset;
channel;
rgb;
r;
g;
b;
shadows;
midtones;
highlights;
preserve_luminosity;
red;
yellow;
green;
cyan;
blue;
magenta;
amount;
threshold;
monochrome;
seed;
tint;
whites;
blacks;
dehaze;
vignette;
grain;
clarity;
curve;
off;
enabled;
of;
angle;
distance;
spread;
choke;
position;
highlight;
shadow;
highlight_blend;
shadow_blend;
altitude;
depth;
soften;
direction;
pattern;
invert;
safe_z_mm;
overrides;
width_mm;
height_mm;
margin_mm;
material_id;
thickness_mm;
machine;
resolution_mm;
kerf_mm;
spacing_mm;
rotations;
max_sheets;
quantity;
outline;
holes;
source;
x_mm;
y_mm;
dither;
power_pct;
min_power_pct;
feed_mm_min;
passes;
}
}
pub(crate) const FAMILY: Family = Family { module: "twod", roots: &["drawing", "painting", "photo", "nest"], declare };
pub const LAYER_STYLES: &[&str] = &["dropShadow", "innerShadow", "outerGlow", "innerGlow", "bevelEmboss", "satin", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay"];
pub const PHOTO_ADJUSTMENTS: &[&str] = &["exposure", "levels", "curves", "hsl", "vibrance", "colorBalance", "blackWhite", "invert", "threshold", "posterize", "develop"];
pub const PHOTO_FILTERS: &[&str] = &["gaussianBlur", "unsharpMask", "sharpen", "noise"];
fn unnamed() -> String {
super::source::stem().unwrap_or_else(|| "Drawing".into())
}
fn declare(root: El) -> Result<Declared, String> {
let mut d = Doc::default();
let graph = match root.tag {
"drawing" => d.drawing(&root)?,
"painting" => d.stack_document(&PAINT, &root)?,
"photo" => d.stack_document(&PHOTO, &root)?,
_ => d.nest(&root)?,
};
Ok(Declared::Graph(graph))
}
fn place(el: &El) -> String {
call(el, &["name"])
}
pub fn twod_schema() -> &'static Json {
static SCHEMA: OnceLock<Json> = OnceLock::new();
SCHEMA.get_or_init(|| Json::parse(include_str!("twod_schema.json")).expect("twod_schema.json is JSON"))
}
fn checked(el: &El, fields: &Json) -> Result<Json, String> {
let schema = twod_schema();
let def = schema.get("roots").and_then(|r| r.get(el.tag)).and_then(Json::as_str).expect("a tag of the schema");
let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
let value = with_defaults(&root, &spread(Json::obj().with("type", el.tag), entries(fields).to_vec()), &defs)?;
let issues = validate(&root, &value, &defs, "")?;
if issues.is_empty() {
return Ok(value);
}
Err(format!("{}: {}", place(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}
fn plain(v: &Json, what: &str) -> Result<(), String> {
match v {
Json::Num(n) if !n.is_finite() => Err(format!("{what}: {n} is not a finite number")),
Json::Arr(items) => items.iter().enumerate().try_for_each(|(i, x)| plain(x, &format!("{what}[{i}]"))),
Json::Obj(entries) => entries.iter().try_for_each(|(k, x)| plain(x, &format!("{what}.{k}"))),
_ => Ok(()),
}
}
const COMPOUND_OPS: [&str; 4] = ["unite", "minus", "intersect", "exclude"];
fn attrs(el: &El, skip: &[&str]) -> Result<Json, String> {
let mut out = Json::obj();
for (k, v) in &el.attrs {
if ["id", "label", "disabled"].contains(&k.as_str()) || skip.contains(&k.as_str()) {
continue;
}
plain(v, &format!("{} {}", place(el), rust_name(k)))?;
out.set(k, v.clone());
}
Ok(out)
}
fn entries(j: &Json) -> &[(String, Json)] {
match j {
Json::Obj(e) => e,
_ => &[],
}
}
fn spread(mut inputs: Json, more: impl IntoIterator<Item = (String, Json)>) -> Json {
for (k, v) in more {
inputs.set(&k, v);
}
inputs
}
fn wires(set: &str, ids: &[String]) -> Vec<(String, Json)> {
channels(set, ids.iter().map(|id| wire(id, "out")).collect())
}
const DRAW_SOURCES: &[&str] = &["rect", "ellipse", "polygon", "path", "text", "brush-stroke"];
const DRAW_MODIFIERS: &[&str] = &["transform", "offset", "array", "mirror", "stroke", "fill", "blur", "levels", "threshold", "adjust", "crop", "bucket-fill"];
const DRAW_PIXELS: &[&str] = &["image", "raster-layer"];
const DRAW_DATA: &[&str] = &["sketch"];
const DRAW_LATER: &[&str] = &["connector"];
fn is_address(src: &str) -> bool {
if src.starts_with('/') {
return true;
}
match src.find("://") {
Some(i) if i > 0 => {
let scheme = src[..i].as_bytes();
scheme[0].is_ascii_alphabetic() && scheme.iter().all(|b| b.is_ascii_alphanumeric() || b"+.-".contains(b))
}
_ => false,
}
}
fn path_tokens(d: &str) -> Vec<String> {
let s: Vec<char> = d.chars().collect();
let digit = |i: usize| s.get(i).is_some_and(|c| c.is_ascii_digit());
let mut out = Vec::new();
let mut i = 0;
while i < s.len() {
if "MLHVCQZmlhvcqz".contains(s[i]) {
out.push(s[i].to_string());
i += 1;
continue;
}
let start = i;
let mut j = if s[i] == '-' { i + 1 } else { i };
let number = if digit(j) {
while digit(j) {
j += 1;
}
if s.get(j) == Some(&'.') {
j += 1;
while digit(j) {
j += 1;
}
}
true
} else if s.get(j) == Some(&'.') && digit(j + 1) {
j += 1;
while digit(j) {
j += 1;
}
true
} else {
false
};
if !number {
i += 1;
continue;
}
if s.get(j) == Some(&'e') {
let k = if matches!(s.get(j + 1), Some('-' | '+')) { j + 2 } else { j + 1 };
if digit(k) {
j = k;
while digit(j) {
j += 1;
}
}
}
out.push(s[start..j].iter().collect());
i = j;
}
out
}
pub fn subpaths_of(d: &str, what: &str) -> Result<Json, String> {
let tokens = path_tokens(d);
let is_cmd = |t: &str| t.chars().all(|c| c.is_ascii_alphabetic());
let pt = |x: f64, y: f64| Json::obj().with("x", x).with("y", y);
let mut out: Vec<Json> = Vec::new();
let mut i = 0;
let mut cmd = String::new();
let (mut cx, mut cy) = (0.0, 0.0);
let n = |i: &mut usize| -> Result<f64, String> {
match tokens.get(*i) {
Some(t) if !is_cmd(t) => {
*i += 1;
t.parse::<f64>().map_err(|_| format!("{what}: {t} is not a number"))
}
_ => Err(format!("{what}: d ends where a number is needed")),
}
};
let segs = |out: &mut Vec<Json>| -> Result<(), String> {
if out.is_empty() {
Err(format!("{what}: d starts with M"))
} else {
Ok(())
}
};
let push = |out: &mut Vec<Json>, seg: Json| {
if let Some(Json::Arr(s)) = out.last_mut().and_then(|sp| match sp {
Json::Obj(e) => e.iter_mut().find(|(k, _)| k == "segs").map(|(_, v)| v),
_ => None,
}) {
s.push(seg);
}
};
while i < tokens.len() {
if is_cmd(&tokens[i]) {
cmd = tokens[i].clone();
i += 1;
}
if cmd != cmd.to_uppercase() {
return Err(format!("{what}: d is written in absolute commands (M L H V C Q Z), not {cmd}"));
}
match cmd.as_str() {
"M" => {
(cx, cy) = (n(&mut i)?, n(&mut i)?);
out.push(Json::obj().with("start", pt(cx, cy)).with("segs", Json::Arr(Vec::new())));
cmd = "L".into();
}
"L" => {
(cx, cy) = (n(&mut i)?, n(&mut i)?);
segs(&mut out)?;
push(&mut out, Json::obj().with("to", pt(cx, cy)));
}
"H" => {
cx = n(&mut i)?;
segs(&mut out)?;
push(&mut out, Json::obj().with("to", pt(cx, cy)));
}
"V" => {
cy = n(&mut i)?;
segs(&mut out)?;
push(&mut out, Json::obj().with("to", pt(cx, cy)));
}
"C" => {
let c1 = pt(n(&mut i)?, n(&mut i)?);
let c2 = pt(n(&mut i)?, n(&mut i)?);
(cx, cy) = (n(&mut i)?, n(&mut i)?);
segs(&mut out)?;
push(&mut out, Json::obj().with("c1", c1).with("c2", c2).with("to", pt(cx, cy)));
}
"Q" => {
let c1 = pt(n(&mut i)?, n(&mut i)?);
(cx, cy) = (n(&mut i)?, n(&mut i)?);
segs(&mut out)?;
push(&mut out, Json::obj().with("c1", c1).with("to", pt(cx, cy)));
}
"Z" if i >= tokens.len() || is_cmd(&tokens[i]) => {
segs(&mut out)?;
let last = out.last_mut().expect("a subpath");
last.set("closed", true);
let start = last.get("start").cloned().unwrap_or(Json::Null);
cx = start.get("x").and_then(Json::as_f64).unwrap_or(0.0);
cy = start.get("y").and_then(Json::as_f64).unwrap_or(0.0);
}
_ => return Err(format!("{what}: d has no command before {}", tokens[i])),
}
}
Ok(Json::Arr(out))
}
fn pairs(v: &Json, what: &str) -> Result<Json, String> {
let Json::Arr(points) = v else { return Err(format!("{what} is a list of [x, y] points")) };
let out = points.iter().enumerate().map(|(i, p)| match p {
Json::Arr(c) if c.len() == 2 && c.iter().all(|x| matches!(x, Json::Num(_))) => Ok(Json::obj().with("x", c[0].clone()).with("y", c[1].clone())),
_ => Err(format!("{what}[{i}] is [x, y]")),
});
Ok(Json::Arr(out.collect::<Result<_, _>>()?))
}
const MIME: &[(&str, &str)] = &[("png", "image/png"), ("jpg", "image/jpeg"), ("jpeg", "image/jpeg"), ("webp", "image/webp"), ("gif", "image/gif"), ("bmp", "image/bmp")];
fn asset(src: Option<&Json>, el: &El) -> Result<Json, String> {
let src = match src {
Some(Json::Str(s)) if !s.is_empty() && !s.starts_with("data:") => s,
_ => return Err(format!("{}: src names an image file by relative path (\"scan.png\"); pixels are not written in code", place(el))),
};
let scheme = src.find(':').is_some_and(|i| i > 0 && src[..i].bytes().all(|b| b.is_ascii_alphabetic()));
if src.starts_with('/') || scheme {
return Err(format!("{}: src is a path relative to this file, not {src}", place(el)));
}
let ext = src.rsplit('.').next().unwrap_or("").to_lowercase();
let mut a = Json::obj().with("kind", "file").with("$file", src.as_str());
if let Some((_, mime)) = MIME.iter().find(|(e, _)| *e == ext) {
a.set("mime", *mime);
}
Ok(a)
}
fn stroke_points(v: &Json, what: &str) -> Result<Json, String> {
let Json::Arr(points) = v else { return Err(format!("{what} is a list of [x, y, pressure, t] points")) };
let out = points.iter().enumerate().map(|(i, p)| match p {
Json::Arr(c) if (c.len() == 4 || c.len() == 6) && c.iter().all(|x| matches!(x, Json::Num(_))) => {
let mut q = Json::obj().with("x", c[0].clone()).with("y", c[1].clone()).with("pressure", c[2].clone()).with("t", c[3].clone());
if c.len() == 6 {
q = q.with("tiltX", c[4].clone()).with("tiltY", c[5].clone());
}
Ok(q)
}
_ => Err(format!("{what}[{i}] is [x, y, pressure, t] or [x, y, pressure, t, tiltX, tiltY]")),
});
Ok(Json::Arr(out.collect::<Result<_, _>>()?))
}
const COMMON: &[&str] = &["name", "visible", "opacity", "blend", "clip", "locked"];
struct StackKind {
root: &'static str,
prefix: &'static str,
chain_type: fn(&El) -> String,
layer: fn(&El) -> Result<Option<(String, Json)>, String>,
chains: fn(&El) -> bool,
chain: fn(&El) -> Result<Json, String>,
}
fn pixel_layer(el: &El, kind: &str) -> Result<Option<(String, Json)>, String> {
let mut a = attrs(el, &["src"])?;
if el.attr_of("src").is_some() {
a.set("__asset", asset(el.attr_of("src"), el)?);
}
Ok(Some((kind.to_string(), a)))
}
fn common_refused(el: &El, a: &Json, why: &str) -> Result<(), String> {
match COMMON.iter().find(|k| a.get(k).is_some()) {
Some(k) => Err(format!("{}: {k} is the layer's ({why})", place(el))),
None => Ok(()),
}
}
fn adjustment_layer(el: &El, node_type: &str) -> Result<Option<(String, Json)>, String> {
let mut common = Json::obj();
let mut adjustment = Json::obj().with("type", el.tag);
for (k, v) in entries(&attrs(el, &[])?) {
if COMMON.contains(&k.as_str()) { &mut common } else { &mut adjustment }.set(k, v.clone());
}
Ok(Some((node_type.into(), common.with("adjustment", adjustment))))
}
fn filter_member(el: &El) -> Result<Json, String> {
let a = attrs(el, &[])?;
common_refused(el, &a, "write it on the layer it filters")?;
Ok(Json::obj().with("filter", checked(el, &a)?))
}
pub const PAINT_CHAIN: &[&str] = &["stroke", "bucket", "gradientFill", "move", "erase", "freeTransform"];
pub const PAINT_SHAPES: &[&str] = &["rect", "ellipse", "polygon", "line"];
const PAINT: StackKind = StackKind {
root: "painting",
prefix: "paint",
chain_type: |el| if PHOTO_FILTERS.contains(&el.tag) { "paint.filter".into() } else { format!("paint.{}", el.tag) },
layer: |el| match el.tag {
"layer" => pixel_layer(el, "paint.layer"),
"fill" | "group" => Ok(Some((format!("paint.{}", el.tag), attrs(el, &[])?))),
"textLayer" => {
let a = attrs(el, &[])?;
if a.get("text").and_then(Json::as_str).is_none() {
return Err(format!("{}: text is the layer's words (.text(\"Title\"))", place(el)));
}
Ok(Some(("paint.text".into(), a)))
}
t if PHOTO_ADJUSTMENTS.contains(&t) => adjustment_layer(el, "paint.adjust"),
t if PAINT_SHAPES.contains(&t) => Ok(Some(("paint.shape".into(), attrs(el, &[])?.with("shape", el.tag)))),
_ => Ok(None),
},
chains: |el| PHOTO_FILTERS.contains(&el.tag) || PAINT_CHAIN.contains(&el.tag),
chain: |el| {
if PHOTO_FILTERS.contains(&el.tag) {
return filter_member(el);
}
let mut a = attrs(el, &[])?;
common_refused(el, &a, "write it on the layer it is painted on")?;
if let (true, Some(points)) = (el.tag == "stroke", a.get("points")) {
let points = stroke_points(points, &format!("{} points", place(el)))?;
a.set("points", points);
}
Ok(a)
},
};
const PHOTO: StackKind = StackKind {
root: "photo",
prefix: "photo",
chain_type: |_| "photo.filter".into(),
layer: |el| match el.tag {
"raster" => pixel_layer(el, "photo.raster"),
"fill" | "gradient" | "group" => Ok(Some((format!("photo.{}", el.tag), attrs(el, &[])?))),
t if PHOTO_ADJUSTMENTS.contains(&t) => adjustment_layer(el, "photo.adjust"),
_ => Ok(None),
},
chains: |el| PHOTO_FILTERS.contains(&el.tag),
chain: filter_member,
};
enum MaskOf<'a> {
Held(String, bool, &'a El),
Named(String, bool, &'a El),
}
impl<'a> MaskOf<'a> {
fn el(&self) -> &'a El {
match self {
MaskOf::Held(_, _, m) | MaskOf::Named(_, _, m) => m,
}
}
}
#[derive(Default)]
struct Doc {
s: Option<Scope>,
disabled: Vec<String>,
sources: Vec<(String, Json)>,
layers: Vec<(String, String)>,
masks: Vec<(String, String, bool, String)>,
}
impl Doc {
fn scope(&mut self) -> &mut Scope {
self.s.as_mut().expect("a scope")
}
fn add(&mut self, el: &El, kind: &str, inputs: Json) -> Result<String, String> {
let id = match el.attr_of("id") {
None => None,
Some(Json::Str(s)) => Some(s.as_str()).filter(|s| !s.is_empty()),
Some(_) => return Err(format!("{}: id is a string", place(el))),
};
let label = el.attr_of("label").and_then(Json::as_str);
let Json::Obj(inputs) = inputs else { unreachable!("inputs are an object") };
let nid = self.scope().add(kind, inputs, id, label, meta(el))?;
if el.attr_of("disabled") == Some(&Json::Bool(true)) {
self.disabled.push(nid.clone());
}
Ok(nid)
}
fn build(&mut self, output: &str) -> Json {
self.build_all(&[output.to_string()])
}
fn build_all(&mut self, outputs: &[String]) -> Json {
let g = self.s.take().expect("a scope").build();
let mut nodes = g.get("nodes").cloned().unwrap_or(Json::obj());
if let Json::Obj(entries) = &mut nodes {
for (id, node) in entries.iter_mut() {
if self.disabled.contains(id) {
node.set("disabled", true);
}
if let Some((_, at)) = self.sources.iter().find(|(m, _)| m == id) {
let m = node.remove("meta").unwrap_or(Json::obj()).with("sources", at.clone());
node.set("meta", m);
}
}
}
Json::obj()
.with("id", g.get("id").cloned().unwrap_or(Json::Null))
.with("nodes", nodes)
.with("outputs", Json::Arr(outputs.iter().map(|o| o.as_str().into()).collect()))
.with("meta", g.get("meta").cloned().unwrap_or(Json::obj()))
}
fn drawn(&mut self, el: &El, top: bool) -> Result<String, String> {
let t = el.tag;
let kids: Vec<&El> = el.child_elements().collect();
if t == "layer" && !top {
return Err(format!("{}: a layer() is a child of the drawing(); inside it, group with group()", place(el)));
}
if t == "layer" || t == "group" {
let children = kids.iter().map(|c| self.drawn(c, false)).collect::<Result<Vec<_>, _>>()?;
return self.add(el, "group", spread(attrs(el, &[])?, wires("children", &children)));
}
if DRAW_SOURCES.contains(&t) {
if !kids.is_empty() {
return Err(format!("{} takes no children", place(el)));
}
let mut a = attrs(el, &[])?;
if t == "path" {
if a.get("subpaths").is_some() {
return Err(format!("{}: a path is written with d (an SVG path), not subpaths", place(el)));
}
if let Some(d) = a.remove("d") {
let Json::Str(d) = d else { return Err(format!("{}: d is an SVG path string", place(el))) };
a.set("subpaths", subpaths_of(&d, &place(el))?);
}
}
if t == "brush-stroke" {
if let Some(points) = a.get("points") {
let points = pairs(points, &format!("{} points", place(el)))?;
a.set("points", points);
}
}
return self.add(el, t, a);
}
if DRAW_DATA.contains(&t) {
if !kids.is_empty() {
return Err(format!("{} takes no children", place(el)));
}
let a = attrs(el, &[])?;
if !matches!(a.get("sketch"), Some(Json::Obj(_))) {
return Err(format!("{}: sketch is its geometry, as the editor holds it ({{ points, segments, constraints, … }})", place(el)));
}
return self.add(el, t, a);
}
if DRAW_PIXELS.contains(&t) {
if !kids.is_empty() {
return Err(format!("{} takes no children", place(el)));
}
if el.attr_of("src").is_none() {
return Err(format!("{}: src names its image file by relative path (\"photo.png\")", place(el)));
}
let a = attrs(el, &["src"])?.with("__asset", asset(el.attr_of("src"), el)?);
return self.add(el, t, a);
}
if t == "link" {
let mut placed = checked(el, &attrs(el, &[])?)?;
placed.remove("type");
let Some(Json::Str(src)) = placed.remove("src") else { unreachable!("the schema requires src") };
if src.trim().is_empty() || src.starts_with("data:") {
return Err(format!("{}: src names a drawing by its path from this file's folder (\"parts/Badge.draw.rs\") or by an address", place(el)));
}
let reference = Json::obj().with(if is_address(&src) { "assetPath" } else { "path" }, src.as_str());
return self.add(el, "draw.instance", spread(Json::obj().with("__instance", reference), entries(&placed).to_vec()));
}
if DRAW_MODIFIERS.contains(&t) {
if kids.len() != 1 {
return Err(format!("{} wraps the one node it changes", place(el)));
}
let a = attrs(el, &[])?;
let input = self.drawn(kids[0], false)?;
return self.add(el, t, a.with("in", wire(&input, "out")));
}
if t == "compound" {
if let Some(op) = el.attr_of("op") {
if !op.as_str().is_some_and(|o| COMPOUND_OPS.contains(&o)) {
return Err(format!("compound.op is unite, minus, intersect or exclude, not {}", op.text()));
}
}
let a = attrs(el, &[])?;
let shapes = kids.iter().map(|c| self.drawn(c, false)).collect::<Result<Vec<_>, _>>()?;
return self.add(el, t, spread(a, wires("children", &shapes)));
}
if t == "clip" {
if kids.len() != 2 {
return Err(format!("{} takes its content, then its mask", place(el)));
}
let a = attrs(el, &[])?;
let content = self.drawn(kids[0], false)?;
let mask = self.drawn(kids[1], false)?;
return self.add(el, t, a.with("content", wire(&content, "out")).with("mask", wire(&mask, "out")));
}
if DRAW_LATER.contains(&t) {
return Err(format!("{} is not declared in code yet (a drawing in code holds shapes, images, sketches, links, groups and modifiers)", tag(t)));
}
Err(format!("{} is not read in a drawing (see commandagi::design::twod)", tag(t)))
}
fn drawing(&mut self, root: &El) -> Result<Json, String> {
let a = attrs(root, &["name", "width", "height", "background"])?;
if let Some((k, _)) = entries(&a).first() {
return Err(format!("drawing(): {} is not read (a drawing has name, width, height, background)", rust_name(k)));
}
let own = root.attr_of("name").and_then(Json::as_str);
let mut m = Json::obj();
if let Some(own) = own {
m.set("name", own);
}
for k in ["width", "height", "background"] {
if let Some(v) = root.attr_of(k) {
plain(v, &format!("drawing() {k}"))?;
m.set(k, v.clone());
}
}
self.s = Some(Scope::new(&format!("draw:{}", slug(&own.map(str::to_string).unwrap_or_else(unnamed))), m.clone()));
let children: Vec<&El> = root.child_elements().collect();
if let Some(first) = children.iter().position(|c| c.tag == "artboard") {
if children[first..].iter().any(|c| c.tag != "artboard") {
return Err("drawing(): its layers come before its artboard()s (the drawing is the first artboard)".into());
}
}
let layers = children.iter().filter(|c| c.tag != "artboard").map(|c| self.drawn(c, true)).collect::<Result<Vec<_>, _>>()?;
let mut inputs = Vec::new();
if let Some(bg) = m.get("background") {
inputs.push(("background".to_string(), bg.clone()));
}
inputs.extend(wires("layers", &layers));
let comp = self.scope().add("composite", inputs, Some("composite"), Some("Output"), meta(root))?;
let boards: Vec<&El> = children.iter().copied().filter(|c| c.tag == "artboard").collect();
if boards.is_empty() {
return Ok(self.build(&comp));
}
let fields = |from: &Json| {
let mut f = Vec::new();
for k in ["width", "height", "background"] {
if let Some(v) = from.get(k) {
f.push((k.to_string(), v.clone()));
}
}
f
};
let page = |id: &str, name: &str, f: Vec<(String, Json)>| {
let mut p = Json::obj().with("id", id).with("name", name);
for (k, v) in f {
p.set(&k, v);
}
p.with("compositeId", id)
};
let mut pages = vec![page("composite", own.unwrap_or("Artboard 1"), fields(&m))];
let mut outputs = vec![comp];
for (i, b) in boards.iter().enumerate() {
let a = attrs(b, &["name", "width", "height", "background"])?;
if let Some((k, _)) = entries(&a).first() {
return Err(format!("{}: {} is not read (an artboard has name, width, height, background)", place(b), rust_name(k)));
}
let name = b.attr_of("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(|| format!("Artboard {}", i + 2));
let mut own_fields = Json::obj();
for k in ["width", "height", "background"] {
if let Some(v) = b.attr_of(k) {
plain(v, &format!("{} {k}", place(b)))?;
own_fields.set(k, v.clone());
}
}
let mut board_layers = Vec::new();
for c in b.child_elements() {
if c.tag == "artboard" {
return Err(format!("{}: an artboard() is a child of the drawing(), not of another artboard", place(b)));
}
board_layers.push(self.drawn(c, true)?);
}
let id = match b.attr_of("id") {
None => None,
Some(Json::Str(s)) => Some(s.clone()).filter(|s| !s.is_empty()),
Some(_) => return Err(format!("{}: id is a string", place(b))),
};
let mut inputs = Vec::new();
if let Some(bg) = own_fields.get("background") {
inputs.push(("background".to_string(), bg.clone()));
}
inputs.extend(wires("layers", &board_layers));
let nid = self.scope().add("composite", inputs, id.as_deref(), Some(&name), meta(b))?;
pages.push(page(&nid, &name, fields(&own_fields)));
outputs.push(nid);
}
self.scope().meta.set("pages", Json::Arr(pages));
Ok(self.build_all(&outputs))
}
fn mask_of<'a>(&mut self, kind: &StackKind, el: &'a El) -> Result<Option<MaskOf<'a>>, String> {
let masks: Vec<&El> = el.child_elements().filter(|c| c.tag == "mask").collect();
let Some(m) = masks.first() else { return Ok(None) };
if masks.len() > 1 {
return Err(format!("{} has one mask()", place(el)));
}
let a = attrs(m, &[])?;
for (k, v) in entries(&a) {
if (k != "enabled" && k != "of") || (k == "enabled" && !matches!(v, Json::Bool(_))) || (k == "of" && !matches!(v, Json::Str(_))) {
return Err(format!("mask() in {} has enabled and of (write the rest on the layer it holds or names)", place(el)));
}
}
let on = a.get("enabled") != Some(&Json::Bool(false));
if let Some(Json::Str(of)) = a.get("of") {
let of = of.as_str().to_string();
if m.child_elements().next().is_some() {
return Err(format!("mask(of=\"{of}\") in {} holds no layer: it names a layer of the stack", place(el)));
}
return Ok(Some(MaskOf::Named(of, on, m)));
}
let held: Vec<&El> = m.child_elements().collect();
if held.len() != 1 {
return Err(format!("mask() in {} holds one layer", place(el)));
}
let ids = self.stack(kind, &held, false)?;
Ok(Some(MaskOf::Held(ids[0].clone(), on, m)))
}
fn resolve_masks(&mut self) -> Result<(), String> {
for (id, of, on, what) in std::mem::take(&mut self.masks) {
let hits: Vec<String> = self.layers.iter().filter(|(n, _)| *n == of).map(|(_, id)| id.clone()).collect();
if hits.is_empty() {
return Err(format!("{what} is masked by \"{of}\", and no layer is named that"));
}
if hits.len() > 1 {
return Err(format!("{what} is masked by \"{of}\", and {} layers are named that", hits.len()));
}
self.scope().set_input(&id, "mask", wire(&hits[0], "out"));
if !on {
self.scope().set_input(&id, "maskEnabled", Json::Bool(false));
}
}
Ok(())
}
fn styles_of(kind: &StackKind, el: &El) -> Result<Option<(Json, Json)>, String> {
let blocks: Vec<&El> = el.child_elements().filter(|c| c.tag == "fx").collect();
let Some(block) = blocks.first() else { return Ok(None) };
if kind.prefix != "paint" {
return Err(format!("{}: fx() (layer styles) is a painting's", place(el)));
}
if blocks.len() > 1 {
return Err(format!("{} has one fx()", place(el)));
}
if !entries(&attrs(block, &[])?).is_empty() {
return Err(format!("fx() in {} has no attributes (write them on its styles)", place(el)));
}
let mut sources = Json::obj();
if let Some(at) = block.source_json() {
sources.set("fx", at);
}
let mut fx = Vec::new();
for (i, c) in block.child_elements().enumerate() {
if !LAYER_STYLES.contains(&c.tag) {
return Err(format!("{} is not a layer style ({})", tag(c.tag), LAYER_STYLES.join(", ")));
}
if c.child_elements().next().is_some() {
return Err(format!("{} in fx() takes no children", place(c)));
}
if let Some(at) = c.source_json() {
sources.set(&format!("fx.{i}"), at);
}
fx.push(spread(Json::obj().with("type", c.tag), entries(&attrs(c, &[])?).to_vec()));
}
Ok(Some((Json::Arr(fx), sources)))
}
fn add_masked(&mut self, kind: &StackKind, el: &El, node_type: &str, inputs: Json) -> Result<String, String> {
let mask = self.mask_of(kind, el)?;
let styles = Self::styles_of(kind, el)?;
let mut inputs = match &mask {
Some(MaskOf::Held(id, on, _)) => {
let i = inputs.with("mask", wire(id, "out"));
if *on { i } else { i.with("maskEnabled", false) }
}
_ => inputs,
};
let mut sources = Json::obj();
if let Some((fx, at)) = styles {
inputs.set("fx", fx);
sources = at;
}
let id = self.add(el, node_type, inputs)?;
if let Some(MaskOf::Named(of, on, _)) = &mask {
self.masks.push((id.clone(), of.clone(), *on, format!("{}'s mask()", place(el))));
}
if let Some(at) = mask.as_ref().and_then(|m| m.el().source_json()) {
sources.set("mask", at);
}
if !entries(&sources).is_empty() {
self.sources.push((id.clone(), sources));
}
Ok(id)
}
fn stack(&mut self, kind: &StackKind, children: &[&El], in_stack: bool) -> Result<Vec<String>, String> {
let mut slots = Vec::new();
for &el in children {
let Some((layer_type, inputs)) = (kind.layer)(el)? else {
if (kind.chains)(el) {
return Err(format!("{} is painted on a layer: write it inside one", place(el)));
}
return Err(format!("{} is not read in a {} (see commandagi::design::twod)", tag(el.tag), tag(kind.root)));
};
let (mut stack, mut chain) = (Vec::new(), Vec::new());
for c in el.child_elements().filter(|c| c.tag != "mask" && c.tag != "fx") {
if (kind.chains)(c) { &mut chain } else { &mut stack }.push(c);
}
let group = format!("{}.group", kind.prefix);
if !stack.is_empty() && layer_type != group {
return Err(format!("{}: only a group() holds layers", place(el)));
}
let inner = if layer_type == group { self.stack(kind, &stack, in_stack)? } else { Vec::new() };
let mut top = self.add_masked(kind, el, &layer_type, spread(inputs.clone(), wires("layers", &inner)))?;
let mut carried = Json::obj().with("name", "Layer").with("visible", true).with("opacity", 1i64).with("blend", "normal");
for k in COMMON {
if let Some(v) = inputs.get(k) {
carried.set(k, v.clone());
}
}
for c in chain {
let own = (kind.chain)(c)?;
let inputs = spread(carried.clone(), entries(&own).to_vec()).with("src", wire(&top, "out"));
top = self.add_masked(kind, c, &(kind.chain_type)(c), inputs)?;
}
if in_stack {
if let Some(Json::Str(name)) = inputs.get("name") {
self.layers.push((name.as_str().to_string(), top.clone()));
}
}
slots.push(top);
}
Ok(slots)
}
fn stack_document(&mut self, kind: &StackKind, root: &El) -> Result<Json, String> {
let a = attrs(root, &[])?;
if let Some((k, _)) = entries(&a).iter().find(|(k, _)| !["name", "width", "height", "background", "dpi"].contains(&k.as_str())) {
return Err(format!("{}: {} is not read (it has name, width, height, background, dpi)", tag(kind.root), rust_name(k)));
}
let title = a.get("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(unnamed);
self.s = Some(Scope::new(&format!("{}:{}", kind.prefix, slug(&title)), Json::obj().with("domain", kind.prefix).with("name", title)));
let kids: Vec<&El> = root.child_elements().collect();
let layers = self.stack(kind, &kids, true)?;
self.resolve_masks()?;
let Json::Obj(inputs) = spread(a, wires("layers", &layers)) else { unreachable!() };
let doc = self.scope().add(&format!("{}.doc", kind.prefix), inputs, Some("doc"), None, meta(root))?;
Ok(self.build(&doc))
}
fn nest(&mut self, root: &El) -> Result<Json, String> {
const ONE: &[&str] = &["sheet", "stock", "options"];
let a = attrs(root, &["name"])?;
if let Some((k, _)) = entries(&a).iter().find(|(k, _)| !["safeZMm", "overrides"].contains(&k.as_str())) {
return Err(format!("nest(): {} is not read (it has safe_z_mm, overrides)", rust_name(k)));
}
let title = root.attr_of("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(unnamed);
self.s = Some(Scope::new(&format!("nest:{}", slug(&title)), Json::obj().with("domain", "nest").with("name", title)));
let mut one: Vec<(String, Json)> = Vec::new();
let mut parts = Vec::new();
let mut engraves = Vec::new();
for el in root.child_elements() {
if ONE.contains(&el.tag) {
if one.iter().any(|(k, _)| k == el.tag) {
return Err(format!("a nest has one {}", tag(el.tag)));
}
let id = self.add(el, &format!("nest.{}", el.tag), attrs(el, &[])?)?;
one.push((el.tag.to_string(), wire(&id, "out")));
} else if el.tag == "part" {
if el.attr_of("id").and_then(Json::as_str).is_none() {
return Err(format!("{}: a part has an id (the name its placements and overrides use)", place(el)));
}
parts.push(self.add(el, "nest.part", attrs(el, &[])?)?);
} else if el.tag == "engrave" {
if el.attr_of("id").and_then(Json::as_str).is_none() {
return Err(format!("{}: an engrave has an id (the name the nest's code uses)", place(el)));
}
engraves.push(self.add(el, "nest.engrave", attrs(el, &[])?)?);
} else {
return Err(format!("{} is not read in a nest (it has sheet(), stock(), options(), part(), engrave())", tag(el.tag)));
}
}
if let Some(k) = ONE.iter().find(|k| !one.iter().any(|(t, _)| t == *k)) {
return Err(format!("a nest needs its {}", tag(k)));
}
let Json::Obj(inputs) = spread(spread(spread(a, one), wires("parts", &parts)), wires("engraves", &engraves)) else { unreachable!() };
let doc = self.scope().add("nest.doc", inputs, Some("nest"), None, meta(root))?;
Ok(self.build(&doc))
}
}