Skip to main content

drawland_graph/
library.rs

1//! The library a profile calls, by name: `features.tiles`, `areas.union`,
2//! `draw`, `compose.mask`… Every check, default and message is here, once,
3//! for JavaScript, Python and Rust alike. What each call adds to the graph is
4//! the operation as the graph's JSON writes it.
5
6use crate::arg::{describe, show_number, Arg, Lazy, Obj};
7use crate::graph::{Graph, Result};
8use drawland_core::grammar::{Clip, Section};
9use serde_json::{json, Map, Value};
10use std::f64::consts::PI;
11
12/// Every function of the library, as a script names it: what `drawland.d.ts`
13/// declares and the Python package exposes.
14pub const FUNCTIONS: &[&str] = &[
15    "areas.around",
16    "areas.band",
17    "areas.buffer",
18    "areas.difference",
19    "areas.extendToFrame",
20    "areas.fillHoles",
21    "areas.grow",
22    "areas.intersect",
23    "areas.move",
24    "areas.polygons",
25    "areas.shape",
26    "areas.text",
27    "areas.union",
28    "burin.script",
29    "burin.terrain",
30    "compose.clip",
31    "compose.deoverlap",
32    "compose.filter",
33    "compose.hand",
34    "compose.linemerge",
35    "compose.linesort",
36    "compose.mask",
37    "compose.order",
38    "compose.orient",
39    "compose.reloop",
40    "compose.simplify",
41    "draw",
42    "engine.ocean",
43    "features.contours",
44    "features.geojson",
45    "features.json",
46    "features.osm",
47    "features.soundings",
48    "features.tiles",
49    "features.where",
50    "fills.cover",
51    "fills.fill",
52    "ink.at",
53    "ink.ramp",
54    "ink.width",
55    "lines.clip",
56    "lines.contours",
57    "lines.dedupe",
58    "lines.join",
59    "lines.merge",
60    "lines.of",
61    "lines.rings",
62    "lines.segments",
63    "lines.shape",
64    "lines.terrain",
65    "lines.text",
66    "modules.graticule",
67    "modules.labels",
68    "modules.roads",
69    "output",
70    "paint",
71    "page.toWorld",
72    "title",
73    "view",
74    "world.at",
75    "world.toPage",
76];
77
78/// The values a script reads rather than calls: `page.width`, `world.center`…
79pub const PROPERTIES: &[&str] = &[
80    "page.center",
81    "page.frame",
82    "page.height",
83    "page.width",
84    "world.bearing",
85    "world.bounds",
86    "world.center",
87    "world.projection",
88    "world.scale",
89    "world.zoom",
90];
91
92/// Whether `a` holds a range by zoom or scale: a Mapbox expression that
93/// reads `["zoom"]` or `["scale"]`, anywhere in it.
94fn reads_frame(a: &Arg) -> bool {
95    match a {
96        Arg::List(items) => {
97            let json = a.to_json();
98            if drawland_core::expr::Expr::is_expression(&json) {
99                drawland_core::expr::Expr::parse(&json).map(|e| e.reads().frame).unwrap_or(false)
100            } else {
101                items.iter().any(reads_frame)
102            }
103        }
104        Arg::Map(o) => o.0.iter().any(|(_, v)| reads_frame(v)),
105        _ => false,
106    }
107}
108
109#[derive(Clone, Copy, PartialEq)]
110enum Kind {
111    Features,
112    Area,
113    Lines,
114}
115
116impl Kind {
117    fn wants(self) -> &'static str {
118        match self {
119            Kind::Features => "features (from features.osm or features.tiles)",
120            Kind::Area => "an area (from areas.*, page.frame or a module's .area)",
121            Kind::Lines => "lines (from lines.*, fills.fill or a module)",
122        }
123    }
124}
125
126fn is(v: Option<&Arg>, kind: Kind) -> bool {
127    matches!(
128        (v, kind),
129        (Some(Arg::Features(_)), Kind::Features) | (Some(Arg::Area { .. }), Kind::Area) | (Some(Arg::Lines { .. }), Kind::Lines)
130    )
131}
132
133/// The argument at `i`, `None` past the end.
134fn at(args: &[Arg], i: usize) -> Option<&Arg> {
135    args.get(i)
136}
137
138/// An optional argument: `None` past the end or when it is `undefined`-like
139/// (the caller left it out).
140fn opt(args: &[Arg], i: usize) -> Option<&Arg> {
141    args.get(i)
142}
143
144impl Graph {
145    fn fail<T>(&self, message: impl Into<String>) -> Result<T> {
146        Err(self.error(message))
147    }
148
149    /// The graph reference of `v`, checked to be a `kind`.
150    fn need(&self, v: Option<&Arg>, kind: Kind, wh: &str) -> Result<String> {
151        if !is(v, kind) {
152            return self.fail(format!("{wh} expects {}, got {}", kind.wants(), describe(v)));
153        }
154        match v.expect("checked") {
155            Arg::Lines { r, module: Some(m) } => self.fail(format!("{wh}: {r} comes from module {m}; it can be drawn, not transformed")),
156            Arg::Features(r) | Arg::Area { r, .. } | Arg::Lines { r, .. } => Ok(r.clone()),
157            _ => unreachable!(),
158        }
159    }
160
161    /// `f(a, b, c)` or `f([a, b, c])`.
162    fn many(&self, args: &[Arg], kind: Kind, wh: &str) -> Result<Vec<String>> {
163        let items: &[Arg] = match args {
164            [Arg::List(l)] => l,
165            _ => args,
166        };
167        let n = items.len();
168        items
169            .iter()
170            .enumerate()
171            .map(|(i, x)| self.need(Some(x), kind, &if n > 1 { format!("{wh} (input {})", i + 1) } else { wh.to_string() }))
172            .collect()
173    }
174
175    fn object<'a>(&self, v: Option<&'a Arg>, wh: &str) -> Result<&'a Obj> {
176        match v {
177            Some(Arg::Map(o)) => Ok(o),
178            other => self.fail(format!("{wh} expects an object, got {}", describe(other))),
179        }
180    }
181
182    /// An options object that may be left out: `{}` then.
183    fn options(&self, v: Option<&Arg>, wh: &str) -> Result<Obj> {
184        match v {
185            None => Ok(Obj::new()),
186            v => self.object(v, wh).cloned(),
187        }
188    }
189
190    /// A length in millimetres: `0.3` or `"0.3mm"`.
191    fn mm(&self, v: Option<&Arg>, wh: &str) -> Result<f64> {
192        let n = match v {
193            Some(Arg::Num(n)) => *n,
194            Some(Arg::Str(s)) => parse_mm(s).unwrap_or(f64::NAN),
195            _ => f64::NAN,
196        };
197        if !n.is_finite() {
198            return self.fail(format!("{wh} is a length in millimetres like 0.3 or \"0.3mm\", got {}", describe(v)));
199        }
200        Ok(n)
201    }
202
203    fn make(&mut self, section: Section, op: Value) -> Result<String> {
204        self.node(section, op)
205    }
206
207    fn new_features(&mut self, op: Value) -> Result<Arg> {
208        Ok(Arg::Features(self.make(Section::Features, op)?))
209    }
210
211    fn area(&mut self, op: Value) -> Result<Arg> {
212        let r = self.make(Section::Areas, op)?;
213        Ok(Arg::Area { mask: r.clone(), r })
214    }
215
216    fn lines_node(&mut self, section: Section, op: Value) -> Result<Arg> {
217        Ok(Arg::Lines { r: self.make(section, op)?, module: None })
218    }
219
220    /// Call the library's function `name` (`"areas.union"`) with `args`.
221    pub fn call(&mut self, name: &str, args: &[Arg]) -> Result<Arg> {
222        // What a caller left off the end is not there.
223        let mut n = args.len();
224        while n > 0 && args[n - 1] == Arg::Null {
225            n -= 1;
226        }
227        let args = &args[..n];
228        // A range by zoom or scale (a Mapbox expression reading `["zoom"]` or
229        // `["scale"]`) in a call's options is the value at this frame: the
230        // graph is made for one frame (a sheet, a scene), so the value is
231        // known now. A screen's `paint` keeps its expressions, worked out at
232        // every frame of a moving screen.
233        let at_frame;
234        let args = if !matches!(name, "paint" | "output" | "title") && args.iter().any(reads_frame) {
235            at_frame = self.at_frame(name, args)?;
236            &at_frame[..]
237        } else {
238            args
239        };
240        match name {
241            "features.osm" => {
242                let tags = self.object(at(args, 0), "features.osm")?.clone();
243                self.new_features(json!({ "osm_select": Arg::Map(tags).to_json() }))
244            }
245            "features.tiles" => {
246                let flat: Vec<Arg> = args.iter().flat_map(|a| match a {
247                    Arg::List(l) => l.clone(),
248                    other => vec![other.clone()],
249                }).collect();
250                if flat.is_empty() {
251                    return self.fail("features.tiles needs a preset or a layer:class rule");
252                }
253                self.new_features(json!({ "tiles_select": Arg::List(flat).to_json() }))
254            }
255            "features.json" => self.features_json(args),
256            "features.contours" => self.features_contours(args),
257            "features.soundings" => self.features_soundings(args),
258            "features.geojson" => {
259                match at(args, 0) {
260                    Some(Arg::Map(o)) => {
261                        if o.get("type").and_then(Arg::as_str).is_none() {
262                            return self.fail("features.geojson: an inline object is GeoJSON, with a type");
263                        }
264                        let o = o.clone();
265                        self.new_features(json!({ "data_select": { "geojson": Arg::Map(o).to_json() } }))
266                    }
267                    Some(Arg::Str(s)) if !s.trim().is_empty() => {
268                        let s = s.trim().to_string();
269                        self.new_features(json!({ "data_select": s }))
270                    }
271                    other => self.fail(format!("features.geojson takes a URL, a file path, or a GeoJSON object, got {}", describe(other))),
272                }
273            }
274            "features.where" => self.features_where(args),
275
276            "areas.band" => self.areas_band(args),
277            "areas.polygons" => {
278                let r = self.need(at(args, 0), Kind::Features, "areas.polygons")?;
279                self.area(json!({ "tools_polygons": r }))
280            }
281            "areas.union" => {
282                let refs = self.many(args, Kind::Area, "areas.union")?;
283                if refs.is_empty() {
284                    return self.fail("areas.union needs at least one area");
285                }
286                self.area(json!({ "tools_union": refs }))
287            }
288            "areas.difference" => {
289                let b = self.need(at(args, 0), Kind::Area, "areas.difference")?;
290                let refs = self.many(&args[1..], Kind::Area, "areas.difference cut")?;
291                if refs.is_empty() {
292                    return Ok(args[0].clone());
293                }
294                self.area(json!({ "tools_difference": { "base": b, "cut": refs } }))
295            }
296            "areas.intersect" => {
297                let base = self.need(at(args, 0), Kind::Area, "areas.intersect")?;
298                let keep = self.need(at(args, 1), Kind::Area, "areas.intersect keep")?;
299                self.area(json!({ "tools_intersect": { "base": base, "keep": keep } }))
300            }
301            "areas.fillHoles" => {
302                let r = self.need(at(args, 0), Kind::Area, "areas.fillHoles")?;
303                self.area(json!({ "tools_fill_holes": r }))
304            }
305            "areas.move" => {
306                let by = match at(args, 1) {
307                    Some(Arg::List(l)) if l.len() == 2 => Arg::List(l.clone()),
308                    other => return self.fail(format!("areas.move: by is [across, down], like [\"2mm\", \"1mm\"], got {}", describe(other))),
309                };
310                let of = self.need(at(args, 0), Kind::Area, "areas.move")?;
311                self.area(json!({ "tools_move": { "of": of, "by": by.to_json() } }))
312            }
313            "areas.grow" => {
314                let by = self.length_arg(at(args, 1), "areas.grow: by is a length like \"0.5mm\"")?;
315                let of = self.need(at(args, 0), Kind::Area, "areas.grow")?;
316                self.area(json!({ "tools_grow": { "of": of, "by": by } }))
317            }
318            "areas.around" => {
319                let by = self.length_arg(at(args, 1), "areas.around: by is a length like \"2mm\"")?;
320                let of = self.need(at(args, 0), Kind::Features, "areas.around")?;
321                self.area(json!({ "tools_around": { "of": of, "by": by } }))
322            }
323            "areas.shape" => {
324                let op = self.shape_op(at(args, 0), "areas.shape")?;
325                self.area(json!({ "tools_shape": op }))
326            }
327            "areas.text" => {
328                let op = self.text_op(at(args, 0), "areas.text")?;
329                self.area(json!({ "tools_text_area": op }))
330            }
331            "areas.buffer" => {
332                let options = self.options(opt(args, 2), "areas.buffer options")?;
333                let by = self.length_arg(at(args, 1), "areas.buffer: by is a length like \"0.2mm\"")?;
334                let lines = self.need(at(args, 0), Kind::Lines, "areas.buffer")?;
335                let mut op = json!({ "lines": lines, "by": by });
336                if let Some(cap) = options.get("cap") {
337                    match cap.as_str() {
338                        Some("round") => {}
339                        Some("flat") => {
340                            op["cap"] = json!("flat");
341                        }
342                        _ => return self.fail(format!("areas.buffer: cap is \"round\" or \"flat\", got {}", describe(Some(cap)))),
343                    }
344                }
345                self.area(json!({ "tools_buffer_lines": op }))
346            }
347            "areas.extendToFrame" => {
348                let options = self.options(opt(args, 2), "areas.extendToFrame options")?;
349                let of = self.need(at(args, 0), Kind::Area, "areas.extendToFrame")?;
350                let within = self.need(at(args, 1), Kind::Area, "areas.extendToFrame within")?;
351                let mut op = json!({ "of": of, "within": within });
352                if let Some(g) = options.get("gapMm").filter(|g| **g != Arg::Null) {
353                    op["gap_mm"] = g.to_json();
354                }
355                self.area(json!({ "tools_extend_to_frame": op }))
356            }
357
358            "engine.ocean" => {
359                let frame = self.get_property("page.frame")?;
360                let tiles = self.call("features.tiles", &[Arg::str("ocean")])?;
361                let polys = self.call("areas.polygons", &[tiles])?;
362                let raw = self.call("areas.intersect", &[polys, frame.clone()])?;
363                let grown = self.call("areas.grow", &[raw, Arg::str("0.35mm")])?;
364                self.call("areas.extendToFrame", &[grown, frame])
365            }
366
367            "page.toWorld" => {
368                let (x, y) = self.page_point(at(args, 0), "page.toWorld")?;
369                let f = self.frame("page.toWorld")?;
370                match f.to_world(x, y) {
371                    Some((lng, lat)) => Ok(Arg::Map(crate::obj! { "lat" => lat, "lng" => lng })),
372                    None => self.fail(format!("page.toWorld: [{}, {}] is off the edge of the projection's world", show_number(x), show_number(y))),
373                }
374            }
375            // A Mapbox expression's value at this frame (a range by zoom or
376            // scale, worked out above, or any other expression of no feature).
377            "world.at" => {
378                let Some(e) = args.first() else { return self.fail("world.at takes an expression, [\"step\", [\"zoom\"], …] say") };
379                let json = e.to_json();
380                if !drawland_core::expr::Expr::is_expression(&json) {
381                    return Ok(e.clone());
382                }
383                let r = self.at_frame("world.at", args)?;
384                Ok(r.into_iter().next().unwrap_or(Arg::Null))
385            }
386            "world.toPage" => {
387                let (lat, lng) = self.ground_point(at(args, 0), "world.toPage")?;
388                let f = self.frame("world.toPage")?;
389                let (x, y) = f.to_page(lng, lat);
390                Ok(Arg::List(vec![Arg::Num(x), Arg::Num(y)]))
391            }
392
393            "lines.rings" => {
394                let options = self.options(opt(args, 1), "lines.rings options")?;
395                let of = self.need(at(args, 0), Kind::Area, "lines.rings")?;
396                let ext = options.get("exteriorOnly").is_some_and(Arg::truthy);
397                self.lines_node(Section::Lines, json!({ "tools_rings": { "of": of, "exterior_only": ext } }))
398            }
399            "lines.of" => {
400                let r = self.need(at(args, 0), Kind::Features, "lines.of")?;
401                self.lines_node(Section::Lines, json!({ "tools_lines": r }))
402            }
403            "lines.shape" => {
404                let mut op = self.shape_op(at(args, 0), "lines.shape")?;
405                let spec = at(args, 0).and_then(Arg::as_map).expect("shape_op checked it");
406                let closed = matches!(spec.get("points"), None | Some(Arg::Null)) || spec.get("closed").is_some_and(Arg::truthy);
407                op["closed"] = Value::Bool(closed);
408                self.lines_node(Section::Lines, json!({ "tools_path": op }))
409            }
410            "lines.text" => {
411                let op = self.text_op(at(args, 0), "lines.text")?;
412                self.lines_node(Section::Lines, json!({ "tools_text": op }))
413            }
414            "lines.segments" => {
415                let r = self.need(at(args, 0), Kind::Features, "lines.segments")?;
416                self.lines_node(Section::Lines, json!({ "tools_segments": r }))
417            }
418            "lines.dedupe" => {
419                let r = self.need(at(args, 0), Kind::Lines, "lines.dedupe")?;
420                self.lines_node(Section::Lines, json!({ "tools_dedupe": r }))
421            }
422            "lines.merge" => {
423                let r = self.need(at(args, 0), Kind::Lines, "lines.merge")?;
424                self.lines_node(Section::Lines, json!({ "tools_merge": r }))
425            }
426            "lines.join" => {
427                let refs = self.many(args, Kind::Lines, "lines.join")?;
428                if refs.is_empty() {
429                    return self.fail("lines.join needs at least one set of lines");
430                }
431                self.lines_node(Section::Lines, json!({ "tools_join": refs }))
432            }
433            "lines.clip" => {
434                let options = self.options(opt(args, 2), "lines.clip options")?;
435                let lines = self.need(at(args, 0), Kind::Lines, "lines.clip")?;
436                let within = self.need(at(args, 1), Kind::Area, "lines.clip within")?;
437                let invert = options.get("invert").is_some_and(Arg::truthy);
438                self.lines_node(Section::Lines, json!({ "tools_clip": { "lines": lines, "within": within, "invert": invert } }))
439            }
440            "lines.terrain" => {
441                let options = self.options(opt(args, 0), "lines.terrain options")?;
442                self.lines_terrain(options)
443            }
444            "lines.contours" => {
445                let options = self.options(opt(args, 0), "lines.contours options")?;
446                let mut rest = options.without(&["from", "to"]);
447                let mut wh = match rest.get("where") {
448                    Some(Arg::Map(w)) => w.clone(),
449                    _ => Obj::new(),
450                };
451                if let Some(v) = options.get("from") {
452                    wh.set("elevMin", v.clone());
453                }
454                if let Some(v) = options.get("to") {
455                    wh.set("elevMax", v.clone());
456                }
457                rest.set("where", Arg::Map(wh));
458                rest.set("draw", Arg::str("fill"));
459                self.lines_terrain(rest)
460            }
461
462            "burin.terrain" | "burin.script" => self.burin_terrain(args),
463
464            "fills.fill" => {
465                let spec = self.object(at(args, 0), "fills.fill")?.clone();
466                let area = self.need(spec.get("in"), Kind::Area, "fills.fill in")?;
467                let mut op = Map::new();
468                op.insert("in".into(), Value::String(area));
469                for (k, v) in spec.without(&["in", "per", "content"]).0 {
470                    op.insert(k, v.to_json());
471                }
472                if let Some(per) = spec.get("per") {
473                    op.insert("per".into(), per.to_json());
474                }
475                if let Some(content) = spec.get("content") {
476                    op.insert("content".into(), Value::String(self.need(Some(content), Kind::Lines, "fills.fill content")?));
477                }
478                if let Some(m @ Arg::Lines { .. }) = spec.get("motif") {
479                    op.insert("motif".into(), Value::String(self.need(Some(m), Kind::Lines, "fills.fill motif")?));
480                }
481                self.lines_node(Section::Fills, json!({ "tools_fill": Value::Object(op) }))
482            }
483            "fills.cover" => {
484                let spec = self.object(at(args, 0), "fills.cover")?.clone();
485                if spec.has("per") || spec.has("content") {
486                    return self.fail("fills.cover: takes a pattern, not per or content");
487                }
488                let area = self.need(spec.get("in"), Kind::Area, "fills.cover in")?;
489                let mut op = Map::new();
490                op.insert("in".into(), Value::String(area));
491                for (k, v) in spec.without(&["in"]).0 {
492                    op.insert(k, v.to_json());
493                }
494                if let Some(m @ Arg::Lines { .. }) = spec.get("motif") {
495                    op.insert("motif".into(), Value::String(self.need(Some(m), Kind::Lines, "fills.cover motif")?));
496                }
497                self.area(json!({ "tools_fill_cover": Value::Object(op) }))
498            }
499
500            "ink.ramp" => self.ink_ramp(args),
501            "ink.width" => {
502                let a = self.mm(at(args, 0), "ink.width thin")?;
503                let b = self.mm(at(args, 1), "ink.width thick")?;
504                let t = self.unit(at(args, 2), "ink.width")?;
505                let w = a + (b - a) * t;
506                Ok(Arg::Str(format!("{}mm", show_number((w * 1000.0).round() / 1000.0))))
507            }
508            "ink.at" => {
509                let nums: Vec<Option<f64>> = (0..3).map(|i| at(args, i).and_then(Arg::as_finite)).collect();
510                match nums[..] {
511                    [Some(v), Some(lo), Some(hi)] if lo != hi => Ok(Arg::Num(((v - lo) / (hi - lo)).clamp(0.0, 1.0))),
512                    _ => self.fail("ink.at takes three numbers, the value and two different ends"),
513                }
514            }
515
516            "modules.roads" => self.modules_roads(args),
517            "modules.graticule" => self.modules_graticule(args),
518            "modules.labels" => self.modules_labels(args),
519
520            "draw" => {
521                let spec = self.object(at(args, 0), "draw")?.clone();
522                if let Some(extra) = spec.without(&["id", "from", "stroke"]).keys().next() {
523                    return self.fail(format!("draw: unknown key {extra} (id, from, stroke)"));
524                }
525                let from = match spec.get("from") {
526                    Some(Arg::Lines { r, .. }) => r.clone(),
527                    other => return self.fail(format!("draw: from expects {}, got {}", Kind::Lines.wants(), describe(other))),
528                };
529                let id = spec.get("id").map(stringify);
530                Ok(Arg::Str(self.add_draw(&from, id, spec.get("stroke"))?))
531            }
532
533            "paint" => self.paint(args),
534
535            "compose.order" => {
536                let items: &[Arg] = match args {
537                    [Arg::List(l)] => l,
538                    _ => args,
539                };
540                self.set_order(items.iter().map(stringify).collect());
541                Ok(Arg::Null)
542            }
543            "compose.mask" => {
544                let spec = self.object(at(args, 0), "compose.mask")?.clone();
545                let from = match spec.get("from") {
546                    Some(Arg::Area { mask, .. }) => mask.clone(),
547                    other => return self.fail(format!("compose.mask: from expects {}, got {}", Kind::Area.wants(), describe(other))),
548                };
549                let occludes = match spec.get("occludes") {
550                    None => Vec::new(),
551                    Some(Arg::List(l)) => l.iter().map(stringify).collect(),
552                    other => return self.fail(format!("compose.mask: occludes is a list of draw ids, got {}", describe(other))),
553                };
554                let name = match spec.get("name") {
555                    None | Some(Arg::Null) => None,
556                    Some(n) => Some(stringify(n)),
557                };
558                self.add_mask(name, &from, occludes)?;
559                Ok(Arg::Null)
560            }
561            "compose.clip" => {
562                let clip = match at(args, 0) {
563                    Some(Arg::Str(s)) if s == "auto" => Clip::Auto,
564                    Some(Arg::Str(s)) if s == "none" => Clip::None,
565                    Some(Arg::List(l)) => {
566                        let refs = l.iter().map(|a| self.need(Some(a), Kind::Area, "compose.clip")).collect::<Result<Vec<_>>>()?;
567                        self.clip_areas(&refs)?
568                    }
569                    other => return self.fail(format!("compose.clip expects \"auto\", \"none\" or a list of areas, got {}", describe(other))),
570                };
571                self.set_clip(clip);
572                Ok(Arg::Null)
573            }
574            "compose.deoverlap" => self.optimize(args, "deoverlap", Some("tolerance"), &[
575                ("tolerance", "tolerance"),
576                ("selfOverlap", "self_overlap"),
577                ("acrossLayers", "across_layers"),
578                ("angle", "angle"),
579                ("prefer", "prefer"),
580                ("minLength", "min_length"),
581                ("drop", "drop"),
582            ], is_length_value),
583            "compose.linemerge" => self.optimize(args, "linemerge", Some("tolerance"), &[("tolerance", "tolerance")], is_length_value),
584            "compose.simplify" => self.optimize(args, "simplify", Some("tolerance"), &[("tolerance", "tolerance")], is_length_value),
585            "compose.filter" => self.optimize(args, "filter", Some("minLength"), &[("minLength", "min_length")], is_length_value),
586            "compose.reloop" => self.optimize(args, "reloop", None, &[], is_length_value),
587            "compose.hand" => self.optimize(args, "hand", Some("preset"), &[
588                ("preset", "preset"),
589                ("wobble", "wobble"),
590                ("wavelength", "wavelength"),
591                ("tremor", "tremor"),
592                ("bow", "bow"),
593                ("overshoot", "overshoot"),
594                ("close", "close"),
595                ("reach", "reach"),
596                ("corners", "corners"),
597                ("retrace", "retrace"),
598                ("retraceOffset", "retrace_offset"),
599                ("seed", "seed"),
600            ], |v| matches!(v, Arg::Str(s) if s == "steady" || s == "sketch")),
601            "compose.orient" => self.optimize(args, "orient", Some("direction"), &[
602                ("direction", "direction"),
603                ("angle", "direction"),
604                ("maxLength", "max_length"),
605                ("splitReversals", "split_reversals"),
606            ], is_direction_value),
607            "compose.linesort" => self.optimize(args, "linesort", Some("direction"), &[
608                ("twoOpt", "two_opt"),
609                ("passes", "passes"),
610                ("follow", "follow"),
611                ("direction", "direction"),
612                ("angle", "direction"),
613                ("maxLength", "max_length"),
614                ("splitReversals", "split_reversals"),
615            ], is_direction_value),
616
617            "output" => {
618                let spec = self.object(at(args, 0), "output")?.clone();
619                self.set_plain_output(&spec)?;
620                Ok(Arg::Null)
621            }
622            "title" => match at(args, 0) {
623                Some(Arg::Str(s)) => {
624                    let s = s.clone();
625                    self.set_title(s);
626                    Ok(Arg::Null)
627                }
628                other => self.fail(format!("title expects a string, got {}", describe(other))),
629            },
630            "view" => self.fail("view takes a style: call it from a script, or use Graph::view_begin / view_end"),
631            other => match other.strip_prefix("page.").or_else(|| other.strip_prefix("world.")) {
632                Some(_) if PROPERTIES.contains(&other) => self.get_property(other),
633                _ => self.fail(format!("{other} is not a function of the library")),
634            },
635        }
636    }
637
638    /// `args` with each range by zoom or scale worked out at this frame.
639    fn at_frame(&mut self, name: &str, args: &[Arg]) -> Result<Vec<Arg>> {
640        let f = self.frame(name)?;
641        let frame = drawland_core::expr::Frame::new(f.output.scale / 1000.0, f.output.center.1);
642        fn walk(a: &Arg, frame: drawland_core::expr::Frame, name: &str) -> std::result::Result<Arg, String> {
643            Ok(match a {
644                Arg::List(items) => {
645                    let json = a.to_json();
646                    if drawland_core::expr::Expr::is_expression(&json) {
647                        let e = drawland_core::expr::Expr::parse(&json).map_err(|m| format!("{name}: {m}"))?;
648                        if e.reads().feature {
649                            return Err(format!(
650                                "{name}: an expression here reads the zoom or the scale, not a feature's tags (those are a screen's paint, or a module's classes and rules)"
651                            ));
652                        }
653                        Arg::from_json(&e.eval(&drawland_core::expr::Context { frame, tags: None }))
654                    } else {
655                        Arg::List(items.iter().map(|i| walk(i, frame, name)).collect::<std::result::Result<_, _>>()?)
656                    }
657                }
658                Arg::Map(o) => Arg::Map(crate::arg::Obj(o.0.iter().map(|(k, v)| Ok((k.clone(), walk(v, frame, name)?))).collect::<std::result::Result<_, String>>()?)),
659                other => other.clone(),
660            })
661        }
662        args.iter().map(|a| walk(a, frame, name)).collect::<std::result::Result<_, _>>().or_else(|m| self.fail(m))
663    }
664
665    /// The value of `page.width`, `world.center` and the like.
666    pub fn get_property(&mut self, name: &str) -> Result<Arg> {
667        match name {
668            "page.width" => Ok(Arg::Num(self.current_output("page.width")?.width.0)),
669            "page.height" => Ok(Arg::Num(self.current_output("page.height")?.height.0)),
670            "page.center" => {
671                let o = self.current_output("page.center")?;
672                Ok(Arg::List(vec![Arg::Num(o.width.0 / 2.0), Arg::Num(o.height.0 / 2.0)]))
673            }
674            "page.frame" => self.area(json!({ "engine_frame": {} })),
675            "world.scale" => Ok(Arg::Num(self.current_output("world.scale")?.scale.0)),
676            "world.zoom" => {
677                let f = self.frame("world.zoom")?;
678                Ok(Arg::Num(drawland_core::expr::Frame::new(f.output.scale / 1000.0, f.output.center.1).zoom))
679            }
680            "world.bearing" => Ok(Arg::Num(self.current_output("world.bearing")?.bearing)),
681            "world.projection" => {
682                let p = self.current_output("world.projection")?.projection;
683                Ok(Arg::from_json(&serde_json::to_value(p).unwrap_or(Value::Null)))
684            }
685            "world.center" => {
686                let f = self.frame("world.center")?;
687                Ok(Arg::Map(crate::obj! { "lat" => f.output.center.1, "lng" => f.output.center.0 }))
688            }
689            "world.bounds" => {
690                let f = self.frame("world.bounds")?;
691                let b = f.bounds();
692                Ok(Arg::Map(crate::obj! { "north" => b.north, "south" => b.south, "east" => b.east, "west" => b.west }))
693            }
694            other => self.fail(format!("{other} is not a property of the library")),
695        }
696    }
697
698    /// A module's part made when it is first asked for: `graticule.keys`,
699    /// `labels.area`, a label rule's `lines`. The same part every time.
700    pub fn get(&mut self, of: &Arg, part: &str) -> Result<Arg> {
701        let Arg::Lazy(lazy) = of else {
702            return self.fail(format!("{} has no part {part}", describe(Some(of))));
703        };
704        let key = format!("{lazy:?}:{part}");
705        if let Some(found) = self.top_ref().memo.get(&key) {
706            return Ok(found.clone());
707        }
708        let made = match (lazy, part) {
709            (Lazy::Graticule(look), "lines") => self.graticule_part(look, Section::Lines, "grid")?,
710            (Lazy::Graticule(look), "keys") => self.graticule_part(look, Section::Areas, "keys")?,
711            (Lazy::Graticule(look), "labels") => self.graticule_part(look, Section::Lines, "labels")?,
712            (Lazy::Graticule(look), "labelArea") => self.graticule_part(look, Section::Areas, "labels")?,
713            (Lazy::Labels { r, .. }, "lines") => Arg::Lines { r: r.clone(), module: None },
714            (Lazy::Labels { r, .. }, "area") => self.area(json!({ "tools_label_area": r }))?,
715            (Lazy::Labels { r, .. }, "dots") => self.area(json!({ "tools_label_area": { "of": r, "dots": true } }))?,
716            (Lazy::Labels { r, rules }, id) if rules.iter().any(|x| x == id) => Arg::Lazy(Lazy::LabelRule { r: r.clone(), rule: id.to_string() }),
717            (Lazy::LabelRule { r, rule }, "lines") => self.lines_node(Section::Lines, json!({ "tools_label_lines": { "of": r, "rule": rule } }))?,
718            (Lazy::LabelRule { r, rule }, "area") => self.area(json!({ "tools_label_area": { "of": r, "rule": rule } }))?,
719            (Lazy::LabelRule { r, rule }, "dots") => self.area(json!({ "tools_label_area": { "of": r, "rule": rule, "dots": true } }))?,
720            (lazy, part) => {
721                let what = match lazy {
722                    Lazy::Graticule(_) => "a graticule has lines, keys, labels and labelArea",
723                    Lazy::Labels { .. } => "labels have lines, area, dots and a part per rule id",
724                    Lazy::LabelRule { .. } => "a label rule has lines, area and dots",
725                };
726                return self.fail(format!("no part {part}: {what}"));
727            }
728        };
729        self.top().memo.insert(key, made.clone());
730        Ok(made)
731    }
732
733    /// The parts a lazy module part has, for a binding to expose.
734    pub fn parts(of: &Lazy) -> Vec<String> {
735        match of {
736            Lazy::Graticule(_) => ["lines", "keys", "labels", "labelArea"].map(String::from).to_vec(),
737            Lazy::Labels { rules, .. } => ["lines", "area", "dots"].iter().map(|s| s.to_string()).chain(rules.iter().cloned()).collect(),
738            Lazy::LabelRule { .. } => ["lines", "area", "dots"].map(String::from).to_vec(),
739        }
740    }
741
742    // -----------------------------------------------------------------------
743    // features
744    // -----------------------------------------------------------------------
745
746    fn features_json(&mut self, args: &[Arg]) -> Result<Arg> {
747        let url = match at(args, 0) {
748            Some(Arg::Str(s)) if !s.trim().is_empty() => s.trim().to_string(),
749            other => return self.fail(format!("features.json takes a URL or a file path, got {}", describe(other))),
750        };
751        let paths = self.object(at(args, 1), "features.json paths")?.clone();
752        for k in ["lat", "lng"] {
753            if !matches!(paths.get(k), Some(Arg::Str(s)) if !s.is_empty()) {
754                let what = if k == "lat" { "latitude" } else { "longitude" };
755                return self.fail(format!("features.json needs {k}, the dot-path to each item's {what}"));
756            }
757        }
758        if !matches!(paths.get("items"), None | Some(Arg::Null) | Some(Arg::Str(_))) {
759            return self.fail("features.json items is a dot-path, like \"data\"");
760        }
761        if let Some(extra) = paths.without(&["items", "lat", "lng"]).keys().next() {
762            return self.fail(format!("features.json: unknown key {extra} (items, lat, lng)"));
763        }
764        let items = paths.get("items").and_then(Arg::as_str).unwrap_or("").to_string();
765        self.new_features(json!({ "data_select": { "json": {
766            "url": url, "items": items, "lat": paths.get("lat").map(Arg::to_json), "lng": paths.get("lng").map(Arg::to_json)
767        } } }))
768    }
769
770    fn features_contours(&mut self, args: &[Arg]) -> Result<Arg> {
771        let o = self.object(at(args, 0), "features.contours")?.clone();
772        let allowed = ["step", "from", "to", "index", "blur", "minLength"];
773        if let Some(extra) = o.without(&allowed).keys().next() {
774            return self.fail(format!("features.contours: unknown key {extra} ({})", allowed.join(", ")));
775        }
776        for k in ["step", "from", "to", "index", "blur"] {
777            if let Some(v) = o.get(k) {
778                if v.as_finite().is_none() {
779                    return self.fail(format!("features.contours {k} is a number, got {}", describe(Some(v))));
780                }
781            }
782        }
783        let Some(step) = o.get("step") else {
784            return self.fail("features.contours needs a step, the metres between contours");
785        };
786        let mut spec = Map::new();
787        spec.insert("step".into(), step.to_json());
788        for k in ["from", "to", "index", "blur"] {
789            if let Some(v) = o.get(k) {
790                spec.insert(k.into(), v.to_json());
791            }
792        }
793        if o.has("minLength") {
794            spec.insert("min_length".into(), crate::arg::number(self.mm(o.get("minLength"), "features.contours minLength")?));
795        }
796        self.new_features(json!({ "terrain_select": { "contours": Value::Object(spec) } }))
797    }
798
799    fn features_soundings(&mut self, args: &[Arg]) -> Result<Arg> {
800        let o = self.object(at(args, 0), "features.soundings")?.clone();
801        if let Some(extra) = o.without(&["every", "on", "blur", "jitter"]).keys().next() {
802            return self.fail(format!("features.soundings: unknown key {extra} (every, on, blur, jitter)"));
803        }
804        if !o.has("every") {
805            return self.fail("features.soundings needs every, the distance between points");
806        }
807        let mut spec = Map::new();
808        spec.insert("every".into(), crate::arg::number(self.mm(o.get("every"), "features.soundings every")?));
809        if let Some(on) = o.get("on") {
810            if !matches!(on.as_str(), Some("sea" | "land" | "all")) {
811                return self.fail(format!("features.soundings on is \"sea\", \"land\" or \"all\", got {}", describe(Some(on))));
812            }
813            spec.insert("on".into(), on.to_json());
814        }
815        if let Some(blur) = o.get("blur") {
816            if blur.as_finite().is_none() {
817                return self.fail(format!("features.soundings blur is a number, got {}", describe(Some(blur))));
818            }
819            spec.insert("blur".into(), blur.to_json());
820        }
821        if let Some(j) = o.get("jitter") {
822            if !j.as_num().is_some_and(|j| (0.0..=1.0).contains(&j)) {
823                return self.fail(format!("features.soundings jitter is 0 to 1, got {}", describe(Some(j))));
824            }
825            spec.insert("jitter".into(), j.to_json());
826        }
827        self.new_features(json!({ "terrain_select": { "soundings": Value::Object(spec) } }))
828    }
829
830    fn features_where(&mut self, args: &[Arg]) -> Result<Arg> {
831        let r = self.need(at(args, 0), Kind::Features, "features.where")?;
832        let tags = self.object(at(args, 1), "features.where tags")?.clone();
833        if tags.is_empty() {
834            return self.fail("features.where needs at least one tag");
835        }
836        for (k, v) in &tags.0 {
837            if let Arg::Map(b) = v {
838                let extra = b.keys().any(|x| x != "min" && x != "max");
839                if extra || b.is_empty() {
840                    return self.fail(format!("features.where: {k} takes {{ min, max }}, got {}", v.to_json()));
841                }
842                for bound in ["min", "max"] {
843                    if let Some(x) = b.get(bound) {
844                        if x.as_finite().is_none() {
845                            return self.fail(format!("features.where: {k}.{bound} must be a number, got {}", describe(Some(x))));
846                        }
847                    }
848                }
849            }
850        }
851        self.new_features(json!({ "tools_where": { "of": r, "tags": Arg::Map(tags).to_json() } }))
852    }
853
854    // -----------------------------------------------------------------------
855    // areas, shapes, text
856    // -----------------------------------------------------------------------
857
858    fn length_arg(&self, v: Option<&Arg>, message: &str) -> Result<Value> {
859        match v {
860            Some(a @ (Arg::Num(_) | Arg::Str(_))) => Ok(a.to_json()),
861            other => self.fail(format!("{message}, got {}", describe(other))),
862        }
863    }
864
865    fn areas_band(&mut self, args: &[Arg]) -> Result<Arg> {
866        let wh = self.options(opt(args, 0), "areas.band")?;
867        let options = self.options(opt(args, 1), "areas.band options")?;
868        let mut w = Map::new();
869        for k in ["elevMin", "elevMax", "depthMin", "depthMax"] {
870            if let Some(v) = wh.get(k) {
871                if v.as_finite().is_none() {
872                    return self.fail(format!("areas.band {k} must be a number of metres"));
873                }
874                w.insert(k.into(), v.to_json());
875            }
876        }
877        if let Some(extra) = wh.keys().find(|k| !w.contains_key(*k)) {
878            return self.fail(format!("areas.band: unknown key {extra} (elevMin, elevMax, depthMin, depthMax)"));
879        }
880        let depth = w.contains_key("depthMin") || w.contains_key("depthMax");
881        let mut op = Map::new();
882        op.insert("where".into(), Value::Object(w));
883        if let Some(a) = options.get("in") {
884            op.insert("in_area".into(), Value::String(self.need(Some(a), Kind::Area, "areas.band in")?));
885        }
886        // Smoother edges than a hatching pass reads: belts, not pixels.
887        let blur = match options.get("blur") {
888            None | Some(Arg::Null) => json!(4),
889            Some(b) => b.to_json(),
890        };
891        let mut style = json!({ "input_blur": blur, "mod_wobble": 0 });
892        // A depth band is a fill of the sea: burin fills land unless told so.
893        if depth {
894            style["ground"] = json!("sea");
895        }
896        op.insert("style".into(), style);
897        self.area(json!({ "tools_terrain_band": Value::Object(op) }))
898    }
899
900    /// A shape written in the profile: `at` is `[x, y]` on the page (lengths
901    /// or "50%") or `{ lat, lng }` on the ground; the outline is a `circle`
902    /// radius, a `rect: [w, h]`, a regular polygon `{ sides, r }`, or
903    /// `points: [[dx, dy], …]` in mm from `at`. `rotate` turns it clockwise.
904    fn shape_op(&self, spec: Option<&Arg>, wh: &str) -> Result<Value> {
905        let spec = self.object(spec, wh)?;
906        let at = match spec.get("at") {
907            None | Some(Arg::Null) => json!(["50%", "50%"]),
908            Some(a) => a.to_json(),
909        };
910        let ring = |n: usize, r: f64, start: f64| -> Value {
911            Value::Array(
912                (0..n)
913                    .map(|i| {
914                        let t = start + (2.0 * PI * i as f64) / n as f64;
915                        json!([crate::arg::number(r * t.cos()), crate::arg::number(r * t.sin())])
916                    })
917                    .collect(),
918            )
919        };
920        let given = |k: &str| matches!(spec.get(k), Some(v) if *v != Arg::Null);
921        let points = if given("circle") {
922            ring(64, self.mm(spec.get("circle"), &format!("{wh}.circle"))?, 0.0)
923        } else if given("sides") {
924            let n = spec.get("sides").and_then(Arg::as_num).unwrap_or(0.0).max(0.0) as usize;
925            ring(n, self.mm(spec.get("r"), &format!("{wh}.r"))?, -PI / 2.0)
926        } else if given("rect") {
927            let rect = spec.get("rect").and_then(Arg::as_list).unwrap_or(&[]);
928            let half: Vec<f64> = (0..rect.len().max(2))
929                .map(|i| self.mm(rect.get(i), &format!("{wh}.rect[{i}]")).map(|v| v / 2.0))
930                .collect::<Result<_>>()?;
931            let (w, h) = (half[0], half[1]);
932            json!([[-w, -h], [w, -h], [w, h], [-w, h]].map(|p| p.map(crate::arg::number)))
933        } else if let Some(Arg::List(p)) = spec.get("points") {
934            Arg::List(p.clone()).to_json()
935        } else {
936            return self.fail(format!("{wh} needs a circle, rect, sides + r, or points"));
937        };
938        let rotate = match spec.get("rotate") {
939            None | Some(Arg::Null) => json!(0),
940            Some(r) => r.to_json(),
941        };
942        Ok(json!({ "at": at, "points": points, "rotate": rotate }))
943    }
944
945    /// A line of text centred on `at` (as for shapes); `size` is the capital
946    /// height; `font` as in `modules.labels`.
947    fn text_op(&self, spec: Option<&Arg>, wh: &str) -> Result<Value> {
948        let spec = self.object(spec, wh)?;
949        let text = match spec.get("text") {
950            Some(Arg::Str(s)) if !s.is_empty() => s.clone(),
951            _ => return self.fail(format!("{wh}.text is a string")),
952        };
953        let or = |k: &str, d: Value| match spec.get(k) {
954            None | Some(Arg::Null) => d,
955            Some(v) => v.to_json(),
956        };
957        let mut op = json!({ "at": or("at", json!(["50%", "50%"])), "text": text, "size": or("size", json!("4mm")), "rotate": or("rotate", json!(0)) });
958        if let Some(f) = spec.get("font").filter(|f| **f != Arg::Null) {
959            op["font"] = self.label_font(f, &format!("{wh}.font"))?;
960        }
961        if let Some(c) = spec.get("counters").filter(|c| **c != Arg::Null) {
962            match c.as_str() {
963                Some("open") => {
964                    op["openCounters"] = json!(true);
965                }
966                Some("closed") => {}
967                _ => return self.fail(format!("{wh}.counters is \"open\" or \"closed\", got {}", describe(Some(c)))),
968            }
969        }
970        Ok(op)
971    }
972
973    /// A draw.land Hershey id (`"futural"`) or `{ origin: "drawland" |
974    /// "stroke" | "google", … }`.
975    fn label_font(&self, font: &Arg, wh: &str) -> Result<Value> {
976        if let Arg::Str(s) = font {
977            if s.is_empty() {
978                return self.fail(format!("{wh}: font id is a non-empty string"));
979            }
980            return Ok(json!(s));
981        }
982        let o = self.object(Some(font), wh)?;
983        let nonempty = |k: &str| matches!(o.get(k), Some(Arg::Str(s)) if !s.is_empty());
984        match o.get("origin").and_then(Arg::as_str) {
985            Some("drawland") => {
986                if !nonempty("id") {
987                    return self.fail(format!("{wh}: drawland font needs id"));
988                }
989                let mut out = json!({ "origin": "drawland", "id": o.get("id").map(Arg::to_json) });
990                if let Some(url) = o.get("url").filter(|u| **u != Arg::Null) {
991                    if !nonempty("url") {
992                        return self.fail(format!("{wh}: drawland font url is a non-empty string"));
993                    }
994                    out["url"] = url.to_json();
995                }
996                Ok(out)
997            }
998            Some("stroke") => {
999                if !nonempty("url") {
1000                    return self.fail(format!("{wh}: stroke font needs url"));
1001                }
1002                Ok(json!({ "origin": "stroke", "url": o.get("url").map(Arg::to_json) }))
1003            }
1004            Some("google") => {
1005                if !nonempty("family") {
1006                    return self.fail(format!("{wh}: google font needs family"));
1007                }
1008                let weight = match o.get("weight") {
1009                    None => 400.0,
1010                    Some(w) => match w.as_finite() {
1011                        Some(w) => w,
1012                        None => return self.fail(format!("{wh}: google font weight is a number, got {}", describe(Some(w)))),
1013                    },
1014                };
1015                let mut out = json!({ "origin": "google", "family": o.get("family").map(Arg::to_json), "weight": crate::arg::number(weight.round()) });
1016                if o.get("italic").is_some_and(Arg::truthy) {
1017                    out["italic"] = json!(true);
1018                }
1019                Ok(out)
1020            }
1021            _ => self.fail(format!("{wh}: font origin is \"drawland\", \"stroke\", or \"google\"")),
1022        }
1023    }
1024
1025    fn page_point(&self, p: Option<&Arg>, wh: &str) -> Result<(f64, f64)> {
1026        match p {
1027            Some(Arg::List(l)) if l.len() == 2 => Ok((self.mm(l.first(), &format!("{wh}[0]"))?, self.mm(l.get(1), &format!("{wh}[1]"))?)),
1028            other => self.fail(format!("{wh} takes [x, y] in page millimetres, got {}", describe(other))),
1029        }
1030    }
1031
1032    fn ground_point(&self, p: Option<&Arg>, wh: &str) -> Result<(f64, f64)> {
1033        let o = p.and_then(Arg::as_map);
1034        match o.map(|o| (o.get("lat").and_then(Arg::as_finite), o.get("lng").and_then(Arg::as_finite))) {
1035            Some((Some(lat), Some(lng))) => Ok((lat, lng)),
1036            _ => self.fail(format!("{wh} takes {{ lat, lng }} in degrees, got {}", describe(p))),
1037        }
1038    }
1039
1040    // -----------------------------------------------------------------------
1041    // lines.terrain, burin
1042    // -----------------------------------------------------------------------
1043
1044    fn lines_terrain(&mut self, o: Obj) -> Result<Arg> {
1045        let mut op = Map::new();
1046        if let Some(a) = o.get("in") {
1047            op.insert("in_area".into(), Value::String(self.need(Some(a), Kind::Area, "lines.terrain in")?));
1048        }
1049        for k in ["color", "width", "angle", "layer"] {
1050            if let Some(v) = o.get(k) {
1051                op.insert(k.into(), v.to_json());
1052            }
1053        }
1054        if let Some(s) = o.get("shore") {
1055            op.insert("shore".into(), Value::Bool(s.truthy()));
1056        }
1057        if let Some(d) = o.get("draw") {
1058            match d.as_str() {
1059                Some("lines" | "fill" | "dots") => {
1060                    op.insert("draw".into(), d.to_json());
1061                }
1062                _ => return self.fail(format!("lines.terrain draw must be \"lines\", \"fill\" or \"dots\", not {}", d.to_json())),
1063            }
1064        }
1065        if let Some(wh) = o.get("where") {
1066            let wh = self.object(Some(wh), "lines.terrain where")?;
1067            let mut w = Map::new();
1068            for k in ["elevMin", "elevMax", "depthMin", "depthMax"] {
1069                if let Some(v) = wh.get(k) {
1070                    if v.as_finite().is_none() {
1071                        return self.fail(format!("lines.terrain where.{k} must be a number of metres"));
1072                    }
1073                    w.insert(k.into(), v.to_json());
1074                }
1075            }
1076            if !w.is_empty() {
1077                op.insert("where".into(), Value::Object(w));
1078            }
1079        }
1080        // `style` and any other key are burin style parameters, by name.
1081        let mut params = match o.get("style") {
1082            Some(Arg::Map(s)) => s.clone(),
1083            _ => Obj::new(),
1084        };
1085        for (k, v) in o.without(&["in", "color", "width", "angle", "layer", "shore", "style", "where", "draw"]).0 {
1086            params.set(&k, v);
1087        }
1088        if !params.is_empty() {
1089            op.insert("style".into(), Arg::Map(params).to_json());
1090        }
1091        self.lines_node(Section::Lines, json!({ "tools_terrain": Value::Object(op) }))
1092    }
1093
1094    /// `burin.terrain(atlas, options)`: the atlas is the burin document as
1095    /// burin builds it (from JavaScript, a function run by burin's own
1096    /// builder; elsewhere, the document's JSON).
1097    fn burin_terrain(&mut self, args: &[Arg]) -> Result<Arg> {
1098        let atlas = match at(args, 0) {
1099            Some(a @ Arg::Map(_)) => a.to_json(),
1100            Some(Arg::Str(s)) => match serde_json::from_str::<Value>(s) {
1101                Ok(v) => v,
1102                Err(e) => return self.fail(format!("burin.terrain: the burin document is not JSON: {e}")),
1103            },
1104            other => return self.fail(format!("burin.terrain expects a burin document, got {}", describe(other))),
1105        };
1106        let options = self.options(opt(args, 1), "burin.terrain options")?;
1107        let mut op = Map::new();
1108        op.insert("atlas".into(), Value::String(atlas.to_string()));
1109        if let Some(a) = options.get("in") {
1110            op.insert("in_area".into(), Value::String(self.need(Some(a), Kind::Area, "burin.terrain in")?));
1111        }
1112        if let Some(regions) = options.get("regions") {
1113            let regions = self.object(Some(regions), "burin.terrain regions")?.clone();
1114            let mut named = Map::new();
1115            for (name, reg) in &regions.0 {
1116                named.insert(name.clone(), Value::String(self.need(Some(reg), Kind::Area, &format!("burin.terrain regions.{name}"))?));
1117            }
1118            op.insert("regions".into(), Value::Object(named));
1119        }
1120        if let Some(w) = options.get("water") {
1121            op.insert("water".into(), Value::String(self.need(Some(w), Kind::Area, "burin.terrain water")?));
1122        }
1123        self.lines_node(Section::Lines, json!({ "tools_burin": Value::Object(op) }))
1124    }
1125
1126    // -----------------------------------------------------------------------
1127    // ink
1128    // -----------------------------------------------------------------------
1129
1130    fn unit(&self, t: Option<&Arg>, wh: &str) -> Result<f64> {
1131        match t.and_then(Arg::as_num).filter(|n| !n.is_nan()) {
1132            Some(t) => Ok(t.clamp(0.0, 1.0)),
1133            None => self.fail(format!("{wh}: t is a number from 0 to 1, got {}", describe(t))),
1134        }
1135    }
1136
1137    fn rgb(&self, hex: &Arg, wh: &str) -> Result<[f64; 3]> {
1138        let parsed = hex.as_str().and_then(|s| {
1139            let h = s.strip_prefix('#')?;
1140            if !h.chars().all(|c| c.is_ascii_hexdigit()) {
1141                return None;
1142            }
1143            let h: String = match h.len() {
1144                3 => h.chars().flat_map(|c| [c, c]).collect(),
1145                6 => h.to_string(),
1146                _ => return None,
1147            };
1148            let c = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok().map(f64::from);
1149            Some([c(0)?, c(2)?, c(4)?])
1150        });
1151        match parsed {
1152            Some(c) => Ok(c),
1153            None => self.fail(format!("{wh}: colours are \"#rgb\" or \"#rrggbb\", got {}", describe(Some(hex)))),
1154        }
1155    }
1156
1157    fn ink_ramp(&self, args: &[Arg]) -> Result<Arg> {
1158        let stops = match at(args, 0) {
1159            Some(Arg::List(l)) if l.len() >= 2 => l,
1160            other => return self.fail(format!("ink.ramp needs two colours or more, got {}", describe(other))),
1161        };
1162        let cs: Vec<[f64; 3]> = stops.iter().map(|s| self.rgb(s, "ink.ramp")).collect::<Result<_>>()?;
1163        let pos = self.unit(at(args, 1), "ink.ramp")? * (cs.len() - 1) as f64;
1164        let i = (pos.floor() as usize).min(cs.len() - 2);
1165        let f = pos - i as f64;
1166        let mix: String = (0..3).map(|k| format!("{:02x}", (cs[i][k] + (cs[i + 1][k] - cs[i][k]) * f).round() as u8)).collect();
1167        Ok(Arg::Str(format!("#{mix}")))
1168    }
1169
1170    // -----------------------------------------------------------------------
1171    // modules
1172    // -----------------------------------------------------------------------
1173
1174    fn road_measure(&self, v: &Arg, wh: &str) -> Result<Value> {
1175        if let Some(n) = v.as_finite() {
1176            return Ok(crate::arg::number(n));
1177        }
1178        if let Arg::Map(o) = v {
1179            if o.len() == 1 {
1180                let (k, x) = &o.0[0];
1181                if (k == "ground" || k == "paper") && x.as_finite().is_some() {
1182                    return Ok(json!({ k.clone(): x.to_json() }));
1183                }
1184            }
1185        }
1186        self.fail(format!("{wh} expects a number or {{ ground: number }} / {{ paper: number }}, got {}", describe(Some(v))))
1187    }
1188
1189    fn modules_roads(&mut self, args: &[Arg]) -> Result<Arg> {
1190        const KEYS: [(&str, &str); 9] = [
1191            ("widthMode", "width_mode"),
1192            ("widthMultiplier", "width_multiplier"),
1193            ("useWidthTag", "use_width_tag"),
1194            ("multiplyByLanes", "multiply_by_lanes"),
1195            ("inferLanesByClass", "infer_lanes_by_class"),
1196            ("centerlineMinWidth", "centerline_min_width"),
1197            ("jointClose", "joint_close"),
1198            ("clearance", "clearance"),
1199            ("classes", "classes"),
1200        ];
1201        const CLASS_KEYS: [(&str, &str); 7] = [
1202            ("ground", "ground"),
1203            ("paper", "paper"),
1204            ("width", "width"),
1205            ("lanes", "lanes"),
1206            ("centerline", "centerline"),
1207            ("singleLine", "single_line"),
1208            ("clearance", "clearance"),
1209        ];
1210        let options = self.options(opt(args, 0), "modules.roads options")?;
1211        let graph_key = |k: &str| KEYS.iter().find(|(js, _)| *js == k).map(|(_, g)| *g);
1212        let mut op = Map::new();
1213        for (k, v) in &options.0 {
1214            match k.as_str() {
1215                "from" => {
1216                    op.insert("from".into(), Value::String(self.need(Some(v), Kind::Features, "modules.roads from")?));
1217                }
1218                "widthMode" => {
1219                    if !matches!(v.as_str(), Some("ground" | "paper")) {
1220                        return self.fail(format!("modules.roads widthMode expects \"ground\" or \"paper\", got {}", describe(Some(v))));
1221                    }
1222                    op.insert("width_mode".into(), v.to_json());
1223                }
1224                "widthMultiplier" => {
1225                    if !v.as_finite().is_some_and(|n| n > 0.0) {
1226                        return self.fail(format!("modules.roads widthMultiplier expects a positive number, got {}", describe(Some(v))));
1227                    }
1228                    op.insert("width_multiplier".into(), v.to_json());
1229                }
1230                "useWidthTag" | "multiplyByLanes" | "inferLanesByClass" => {
1231                    op.insert(graph_key(k).expect("listed").into(), Value::Bool(v.truthy()));
1232                }
1233                "centerlineMinWidth" | "jointClose" | "clearance" => {
1234                    op.insert(graph_key(k).expect("listed").into(), self.road_measure(v, &format!("modules.roads {k}"))?);
1235                }
1236                "classes" => {
1237                    let classes = self.object(Some(v), "modules.roads classes")?.clone();
1238                    let mut out = Map::new();
1239                    for (cls, spec) in &classes.0 {
1240                        let cwhere = format!("modules.roads classes.{cls}");
1241                        if let Some(n) = spec.as_finite() {
1242                            out.insert(cls.clone(), crate::arg::number(n));
1243                            continue;
1244                        }
1245                        let spec = self.object(Some(spec), &cwhere)?;
1246                        let mut entry = Map::new();
1247                        for (ck, cv) in &spec.0 {
1248                            let Some((_, gk)) = CLASS_KEYS.iter().find(|(js, _)| js == ck) else {
1249                                let allowed: Vec<&str> = CLASS_KEYS.iter().map(|(js, _)| *js).collect();
1250                                return self.fail(format!("{cwhere}: unknown key {ck} ({})", allowed.join(", ")));
1251                            };
1252                            match ck.as_str() {
1253                                "ground" | "paper" | "width" => {
1254                                    if cv.as_finite().is_none() {
1255                                        return self.fail(format!("{cwhere}.{ck} expects a number, got {}", describe(Some(cv))));
1256                                    }
1257                                    entry.insert(gk.to_string(), cv.to_json());
1258                                }
1259                                "lanes" => {
1260                                    if !cv.as_finite().is_some_and(|n| n > 0.0) {
1261                                        return self.fail(format!("{cwhere}.lanes expects a positive number, got {}", describe(Some(cv))));
1262                                    }
1263                                    entry.insert("lanes".into(), cv.to_json());
1264                                }
1265                                "centerline" | "singleLine" => {
1266                                    entry.insert(gk.to_string(), Value::Bool(cv.truthy()));
1267                                }
1268                                _ => {
1269                                    entry.insert("clearance".into(), self.road_measure(cv, &format!("{cwhere}.clearance"))?);
1270                                }
1271                            }
1272                        }
1273                        out.insert(cls.clone(), Value::Object(entry));
1274                    }
1275                    op.insert("classes".into(), Value::Object(out));
1276                }
1277                other => {
1278                    let allowed: Vec<&str> = std::iter::once("from").chain(KEYS.iter().map(|(js, _)| *js)).collect();
1279                    return self.fail(format!("modules.roads: unknown option {other} ({})", allowed.join(", ")));
1280                }
1281            }
1282        }
1283        let r = self.make(Section::Areas, json!({ "module_roads": Value::Object(op) }))?;
1284        let out = |name: &str| Arg::Lines { r: format!("roads.{name}"), module: Some("roads".into()) };
1285        Ok(Arg::Map(Obj(vec![
1286            ("area".into(), Arg::Area { r, mask: "roads.area".into() }),
1287            ("outlines".into(), out("outlines")),
1288            ("details".into(), out("details")),
1289            ("trails".into(), out("trails")),
1290            ("centerlines".into(), out("centerlines")),
1291            ("seams".into(), out("seams")),
1292            ("rails".into(), out("rails")),
1293        ])))
1294    }
1295
1296    /// `paint({ id, from, fill | line | text, halo, minzoom, maxzoom, filter })`:
1297    /// a layer of the screen. What `from` is decides the look it takes: an
1298    /// area a `fill`, lines a `line`, features a `text`. A look's property
1299    /// may be a Mapbox expression (`["step", ["zoom"], …]`); `minzoom`,
1300    /// `maxzoom` and `filter` say when the layer, or a feature of it, is
1301    /// shown, as Mapbox's do.
1302    fn paint(&mut self, args: &[Arg]) -> Result<Arg> {
1303        use drawland_core::paint::{Halo, Shown, Style};
1304        let spec = self.object(at(args, 0), "paint")?.clone();
1305        if let Some(extra) = spec.without(&["id", "from", "fill", "line", "text", "halo", "minzoom", "maxzoom", "filter"]).keys().next() {
1306            return self.fail(format!("paint: unknown key {extra} (id, from, fill, line, text, halo, minzoom, maxzoom, filter)"));
1307        }
1308        let id = match spec.get("id") {
1309            Some(Arg::Str(s)) if !s.trim().is_empty() => s.clone(),
1310            other => return self.fail(format!("paint: id names the layer, got {}", describe(other))),
1311        };
1312        let (from, key) = match spec.get("from") {
1313            Some(Arg::Area { r, .. }) => (r.clone(), "fill"),
1314            Some(Arg::Lines { r, .. }) => (r.clone(), "line"),
1315            Some(Arg::Features(r)) => (r.clone(), "text"),
1316            other => {
1317                return self.fail(format!(
1318                    "paint: from expects an area (filled), lines (lined) or features (named), got {}",
1319                    describe(other)
1320                ))
1321            }
1322        };
1323        if let Some(other) = ["fill", "line", "text"].into_iter().find(|k| *k != key && spec.has(k)) {
1324            let what = match key {
1325                "fill" => "an area",
1326                "line" => "lines",
1327                _ => "features",
1328            };
1329            return self.fail(format!("paint {id:?}: from is {what}, painted with {key}, not {other}"));
1330        }
1331        let body = spec.get(key).map(Arg::to_json).unwrap_or_else(|| Value::Object(Map::new()));
1332        let look = Style::new(key, body).or_else(|e| self.fail(format!("paint {id:?}: {e}")))?;
1333        let zoom = |k: &str| -> Result<Option<f64>> {
1334            match spec.get(k) {
1335                None | Some(Arg::Null) => Ok(None),
1336                Some(z) => match z.as_num() {
1337                    Some(z) => Ok(Some(z)),
1338                    None => self.fail(format!("paint {id:?}: {k} is a zoom, a number, got {}", describe(Some(z)))),
1339                },
1340            }
1341        };
1342        let (minzoom, maxzoom) = (zoom("minzoom")?, zoom("maxzoom")?);
1343        let filter = spec.get("filter").map(Arg::to_json);
1344        let shown = Shown::new(minzoom, maxzoom, filter).or_else(|e| self.fail(format!("paint {id:?}: {e}")))?;
1345        let mut halo_units = Vec::new();
1346        let halo: Halo = match spec.get("halo") {
1347            None | Some(Arg::Null) => Halo::default(),
1348            Some(h) => {
1349                let mut v = h.to_json();
1350                drawland_core::units::screen_units(&mut v, &mut halo_units);
1351                serde_json::from_value(v)
1352                    .or_else(|_| self.fail(format!("paint {id:?}: halo is pixels or cells, n or [across, down], got {}", describe(Some(h)))))?
1353            }
1354        };
1355        let look = look.and_units(&halo_units);
1356        Ok(Arg::Str(self.add_paint(id, &from, look, shown, halo)?))
1357    }
1358
1359    fn modules_graticule(&mut self, args: &[Arg]) -> Result<Arg> {
1360        let o = self.options(opt(args, 0), "modules.graticule options")?;
1361        if let Some(extra) = o.without(&["in", "step", "ticks", "band", "gap", "size", "font"]).keys().next() {
1362            return self.fail(format!("modules.graticule: unknown option {extra} (in, step, ticks, band, gap, size, font)"));
1363        }
1364        let within = self.need(o.get("in"), Kind::Area, "modules.graticule in")?;
1365        let step = o.get("step");
1366        if !step.and_then(Arg::as_num).is_some_and(|s| s > 0.0) {
1367            return self.fail(format!("modules.graticule: step is minutes of arc between lines, got {}", describe(step)));
1368        }
1369        if let Some(t) = o.get("ticks") {
1370            if !t.as_num().is_some_and(|t| t >= 0.0) {
1371                return self.fail(format!("modules.graticule: ticks is minutes of arc per border key, got {}", describe(Some(t))));
1372            }
1373        }
1374        let mut look = Map::new();
1375        look.insert("in".into(), Value::String(within));
1376        look.insert("step".into(), step.map(Arg::to_json).unwrap_or(Value::Null));
1377        for k in ["ticks", "band", "gap", "size"] {
1378            if let Some(v) = o.get(k) {
1379                look.insert(k.into(), v.to_json());
1380            }
1381        }
1382        if let Some(f) = o.get("font") {
1383            look.insert("font".into(), self.label_font(f, "modules.graticule font")?);
1384        }
1385        Ok(Arg::Lazy(Lazy::Graticule(Value::Object(look))))
1386    }
1387
1388    fn graticule_part(&mut self, look: &Value, section: Section, part: &str) -> Result<Arg> {
1389        let mut op = look.clone();
1390        op["part"] = json!(part);
1391        match section {
1392            Section::Lines => self.lines_node(Section::Lines, json!({ "tools_graticule": op })),
1393            _ => self.area(json!({ "tools_graticule_area": op })),
1394        }
1395    }
1396
1397    fn label_look(&self, look: &Obj, wh: &str, what: &str, others: &[&str]) -> Result<Map<String, Value>> {
1398        const LOOK: [(&str, &str); 11] = [
1399            ("size", "size"),
1400            ("minSize", "min_size"),
1401            ("padding", "padding"),
1402            ("spacing", "spacing"),
1403            ("curved", "curved"),
1404            ("upper", "upper"),
1405            ("font", "font"),
1406            ("buffer", "buffer"),
1407            ("bufferStep", "buffer_step"),
1408            ("keepCenterline", "keep_centerline"),
1409            ("marker", "marker"),
1410        ];
1411        let mut out = Map::new();
1412        for (k, v) in &look.0 {
1413            let Some((_, g)) = LOOK.iter().find(|(js, _)| js == k) else {
1414                let all: Vec<&str> = others.iter().copied().chain(LOOK.iter().map(|(js, _)| *js)).collect();
1415                return self.fail(format!("{wh}: unknown {what} {k} ({})", all.join(", ")));
1416            };
1417            match k.as_str() {
1418                "font" => {
1419                    out.insert("font".into(), self.label_font(v, &format!("{wh} font"))?);
1420                }
1421                "curved" | "upper" | "keepCenterline" => {
1422                    out.insert(g.to_string(), Value::Bool(v.truthy()));
1423                }
1424                "buffer" => {
1425                    if !v.as_num().is_some_and(|n| n.fract() == 0.0 && n >= 0.0) {
1426                        return self.fail(format!("{wh}: buffer is a non-negative integer, got {}", describe(Some(v))));
1427                    }
1428                    out.insert("buffer".into(), v.to_json());
1429                }
1430                _ => {
1431                    out.insert(g.to_string(), v.to_json());
1432                }
1433            }
1434        }
1435        Ok(out)
1436    }
1437
1438    fn modules_labels(&mut self, args: &[Arg]) -> Result<Arg> {
1439        let o = self.options(opt(args, 0), "modules.labels options")?;
1440        let sets: Vec<Arg> = match o.get("from") {
1441            Some(Arg::List(l)) => l.clone(),
1442            Some(f) => vec![f.clone()],
1443            None => vec![],
1444        };
1445        if sets.is_empty() && matches!(o.get("from"), Some(Arg::List(_))) {
1446            return self.fail("modules.labels: from needs at least one feature set");
1447        }
1448        let sets: &[Option<&Arg>] = &if sets.is_empty() { vec![None] } else { sets.iter().map(Some).collect() };
1449        let n = sets.len();
1450        let from = sets
1451            .iter()
1452            .enumerate()
1453            .map(|(i, f)| {
1454                let wh = if n > 1 { format!("modules.labels from (input {})", i + 1) } else { "modules.labels from".into() };
1455                self.need(*f, Kind::Features, &wh).map(Value::String)
1456            })
1457            .collect::<Result<Vec<_>>>()?;
1458        let mut op = Map::new();
1459        op.insert("from".into(), Value::Array(from));
1460        let look = o.without(&["from", "in", "avoid", "keys", "rules"]);
1461        op.extend(self.label_look(&look, "modules.labels", "option", &["from", "in", "avoid", "keys", "rules"])?);
1462        if let Some(a) = o.get("in") {
1463            op.insert("in".into(), Value::String(self.need(Some(a), Kind::Area, "modules.labels in")?));
1464        }
1465        if let Some(a) = o.get("avoid") {
1466            op.insert("avoid".into(), Value::String(self.need(Some(a), Kind::Area, "modules.labels avoid")?));
1467        }
1468        if let Some(keys) = o.get("keys") {
1469            let ks: Vec<Arg> = match keys {
1470                Arg::List(l) => l.clone(),
1471                k => vec![k.clone()],
1472            };
1473            if ks.is_empty() || !ks.iter().all(|k| matches!(k, Arg::Str(_))) {
1474                return self.fail(format!("modules.labels: keys is a tag or a list of tags, got {}", describe(Some(keys))));
1475            }
1476            op.insert("keys".into(), Arg::List(ks).to_json());
1477        }
1478        let mut ids = Vec::new();
1479        if let Some(rules) = o.get("rules") {
1480            let rules = match rules {
1481                Arg::List(l) if !l.is_empty() => l.clone(),
1482                other => return self.fail(format!("modules.labels: rules is a non-empty list, got {}", describe(Some(other)))),
1483            };
1484            let mut out = Vec::new();
1485            for (i, rule) in rules.iter().enumerate() {
1486                let wh = format!("modules.labels rules[{i}]");
1487                let rule = self.object(Some(rule), &wh)?;
1488                let tags = self.object(rule.get("tags"), &format!("{wh}.tags"))?;
1489                if tags.is_empty() {
1490                    return self.fail(format!("{wh}.tags needs at least one tag"));
1491                }
1492                let mut entry = Map::new();
1493                entry.insert("tags".into(), Arg::Map(tags.clone()).to_json());
1494                entry.extend(self.label_look(&rule.without(&["tags", "id"]), &wh, "key", &["tags", "id"])?);
1495                if let Some(id) = rule.get("id") {
1496                    let ok = id.as_str().is_some_and(|s| {
1497                        let mut c = s.chars();
1498                        c.next().is_some_and(|f| f == '_' || f.is_ascii_alphabetic()) && c.all(|x| x == '_' || x.is_ascii_alphanumeric())
1499                    });
1500                    if !ok {
1501                        return self.fail(format!("{wh}: id is a name (letters, digits, underscore), got {}", describe(Some(id))));
1502                    }
1503                    let id = id.as_str().expect("checked").to_string();
1504                    if ids.contains(&id) {
1505                        return self.fail(format!("modules.labels: duplicate rule id {id}"));
1506                    }
1507                    entry.insert("id".into(), json!(id));
1508                    ids.push(id);
1509                }
1510                out.push(Value::Object(entry));
1511            }
1512            op.insert("rules".into(), Value::Array(out));
1513        }
1514        let r = self.make(Section::Lines, json!({ "tools_labels": Value::Object(op) }))?;
1515        Ok(Arg::Lazy(Lazy::Labels { r, rules: ids }))
1516    }
1517
1518    // -----------------------------------------------------------------------
1519    // compose: the plotter steps
1520    // -----------------------------------------------------------------------
1521
1522    fn optimize(&mut self, args: &[Arg], name: &str, shorthand: Option<&str>, keys: &[(&str, &str)], is_shorthand: fn(&Arg) -> bool) -> Result<Arg> {
1523        let wh = format!("compose.{name}");
1524        let (a, b) = (at(args, 0).filter(|a| **a != Arg::Null), at(args, 1));
1525        let mut layers: Vec<String> = Vec::new();
1526        let raw: Option<Arg> = match a {
1527            None => b.cloned(),
1528            Some(Arg::List(l)) => {
1529                layers = l.iter().map(stringify).collect();
1530                b.cloned()
1531            }
1532            Some(o @ Arg::Map(_)) => {
1533                if b.is_some() {
1534                    return self.fail(format!("{wh}: unexpected second argument when first is options"));
1535                }
1536                Some(o.clone())
1537            }
1538            Some(v @ (Arg::Str(_) | Arg::Num(_))) => {
1539                if b.is_some() {
1540                    if !matches!(v, Arg::Str(_)) {
1541                        return self.fail(format!("{wh}: layers expects a draw id or list of draw ids, got {}", describe(a)));
1542                    }
1543                    layers = vec![stringify(v)];
1544                    b.cloned()
1545                } else if shorthand.is_some() && is_shorthand(v) {
1546                    Some(Arg::Map(Obj(vec![(shorthand.unwrap().to_string(), v.clone())])))
1547                } else if let Arg::Str(s) = v {
1548                    layers = vec![s.clone()];
1549                    None
1550                } else {
1551                    return self.fail(format!("{wh}: unexpected {}", describe(a)));
1552                }
1553            }
1554            other => return self.fail(format!("{wh}: unexpected {}", describe(other))),
1555        };
1556        let mut spec = Map::new();
1557        let mut except: Vec<String> = Vec::new();
1558        if let Some(raw) = raw {
1559            match (shorthand, &raw) {
1560                (Some(k), v) if is_shorthand(v) => {
1561                    let g = keys.iter().find(|(js, _)| *js == k).map(|(_, g)| *g).unwrap_or(k);
1562                    spec.insert(g.into(), v.to_json());
1563                }
1564                _ => {
1565                    let o = self.object(Some(&raw), &wh)?;
1566                    for (k, v) in &o.0 {
1567                        if k == "except" {
1568                            match v {
1569                                Arg::List(l) => except = l.iter().map(stringify).collect(),
1570                                other => return self.fail(format!("{wh}: except is a list of draw ids, got {}", describe(Some(other)))),
1571                            }
1572                        } else if let Some((_, g)) = keys.iter().find(|(js, _)| js == k) {
1573                            spec.insert(g.to_string(), v.to_json());
1574                        } else {
1575                            let allowed: Vec<&str> = keys.iter().map(|(js, _)| *js).chain(std::iter::once("except")).collect();
1576                            return self.fail(format!("{wh}: unknown key {k} ({})", allowed.join(", ")));
1577                        }
1578                    }
1579                }
1580            }
1581        }
1582        let mut step = Map::new();
1583        step.insert(name.into(), Value::Object(spec));
1584        if !layers.is_empty() {
1585            step.insert("layers".into(), json!(layers));
1586        }
1587        if !except.is_empty() {
1588            step.insert("except".into(), json!(except));
1589        }
1590        self.add_optimize(Value::Object(step))?;
1591        Ok(Arg::Null)
1592    }
1593
1594    // -----------------------------------------------------------------------
1595    // output and its warps
1596    // -----------------------------------------------------------------------
1597
1598    /// The output, warps and all, except a `remap`: a function, which the
1599    /// caller samples with [`Graph::remap_grid`] and [`Graph::remap_mesh`].
1600    fn set_plain_output(&mut self, spec: &Obj) -> Result<()> {
1601        let warps: Vec<Arg> = match spec.get("warp") {
1602            None | Some(Arg::Null) => vec![],
1603            Some(Arg::List(l)) => l.clone(),
1604            Some(w) => vec![w.clone()],
1605        };
1606        if warps.iter().any(is_remap) {
1607            return self.fail("output: a remap warp is a function: call output from a script, or sample it with Graph::remap_grid");
1608        }
1609        self.set_output(spec)
1610    }
1611
1612    /// `output` with its `remap` warps still to sample: the output set with
1613    /// none, and whether to sample them (not in a draft, which leaves them
1614    /// out and keeps the others).
1615    pub fn output_begin(&mut self, spec: &Obj) -> Result<bool> {
1616        let spec = self.object(Some(&Arg::Map(spec.clone())), "output")?.clone();
1617        let warps: Vec<Arg> = match spec.get("warp") {
1618            None | Some(Arg::Null) => vec![],
1619            Some(Arg::List(l)) => l.clone(),
1620            Some(w) => vec![w.clone()],
1621        };
1622        if !warps.iter().any(is_remap) {
1623            self.set_output(&spec)?;
1624            return Ok(false);
1625        }
1626        let mut plain = spec.clone();
1627        if self.ask_draft() {
1628            plain.set("warp", Arg::List(warps.into_iter().filter(|w| !is_remap(w)).collect()));
1629            self.set_output(&plain)?;
1630            return Ok(false);
1631        }
1632        plain.set("warp", Arg::List(vec![]));
1633        self.set_output(&plain)?;
1634        Ok(true)
1635    }
1636
1637    /// The warps done so far set on the output, so `page.toWorld` answers
1638    /// through them while the next `remap` is sampled.
1639    pub fn output_warps(&mut self, done: &[Arg]) -> Result<()> {
1640        self.set_warp(&Arg::List(done.to_vec()))
1641    }
1642
1643    /// The page points the `remap` warp at `n` (its `{ remap, grid }`) is
1644    /// sampled at: `(grid + 1)²` of them, row by row.
1645    pub fn remap_grid(&self, warp: &Obj, n: usize) -> Result<(usize, usize, Vec<[f64; 2]>)> {
1646        if !matches!(warp.get("remap"), Some(Arg::Func)) {
1647            return self.fail(format!("output.warp[{n}].remap is a function ([x, y]) => [x, y], got {}", describe(warp.get("remap"))));
1648        }
1649        if let Some(k) = warp.keys().find(|k| *k != "remap" && *k != "grid") {
1650            return self.fail(format!("output.warp[{n}]: unknown key {k}; a remap takes remap and grid"));
1651        }
1652        let grid = warp.get("grid").cloned().unwrap_or(Arg::Num(48.0));
1653        let (gx, gy) = match &grid {
1654            Arg::List(l) if l.len() == 2 => (l[0].clone(), l[1].clone()),
1655            g => (g.clone(), g.clone()),
1656        };
1657        let cells = |g: &Arg| g.as_num().filter(|n| n.fract() == 0.0 && (1.0..=256.0).contains(n)).map(|n| n as usize);
1658        let (Some(gx), Some(gy)) = (cells(&gx), cells(&gy)) else {
1659            return self.fail(format!(
1660                "output.warp[{n}].grid is a whole number of cells from 1 to 256 (or [across, down]), got {}",
1661                describe(Some(&grid))
1662            ));
1663        };
1664        let o = self.current_output("output.warp")?;
1665        let (width, height) = (o.width.0, o.height.0);
1666        let mut points = Vec::with_capacity((gx + 1) * (gy + 1));
1667        for j in 0..=gy {
1668            for i in 0..=gx {
1669                points.push([width * i as f64 / gx as f64, height * j as f64 / gy as f64]);
1670            }
1671        }
1672        Ok((gx + 1, gy + 1, points))
1673    }
1674
1675    /// The `remap` warp at `n` as the engine draws it: a mesh of where each
1676    /// sampled point went. `went[i]` is what the function gave for
1677    /// `points[i]`.
1678    pub fn remap_mesh(&self, n: usize, columns: usize, rows: usize, points: &[[f64; 2]], went: &[Arg]) -> Result<Arg> {
1679        let mut out = Vec::with_capacity(went.len());
1680        for (p, to) in points.iter().zip(went) {
1681            match to {
1682                Arg::List(l) if l.len() == 2 && l.iter().all(|v| v.as_finite().is_some()) => out.push(to.clone()),
1683                other => {
1684                    return self.fail(format!(
1685                        "output.warp[{n}].remap([{:.2}, {:.2}]) returned {}, not [x, y] in page mm",
1686                        p[0],
1687                        p[1],
1688                        describe(Some(other))
1689                    ))
1690                }
1691            }
1692        }
1693        Ok(Arg::Map(crate::obj! { "mesh" => Arg::Map(crate::obj! {
1694            "columns" => columns as u32, "rows" => rows as u32, "points" => Arg::List(out)
1695        }) }))
1696    }
1697}
1698
1699/// A warp that is a `remap`, still holding its function.
1700pub fn is_remap(w: &Arg) -> bool {
1701    matches!(w, Arg::Map(o) if o.has("remap"))
1702}
1703
1704/// `String(v)`, as an id is written.
1705fn stringify(v: &Arg) -> String {
1706    match v {
1707        Arg::Str(s) => s.clone(),
1708        Arg::Num(n) => show_number(*n),
1709        Arg::Bool(b) => b.to_string(),
1710        Arg::Null => "null".into(),
1711        other => other.to_json().to_string(),
1712    }
1713}
1714
1715/// `0.3mm` → `0.3`.
1716fn parse_mm(s: &str) -> Option<f64> {
1717    let s = s.trim().strip_suffix("mm")?.trim_end();
1718    if s.is_empty() || !s.chars().all(|c| c.is_ascii_digit() || c == '.') {
1719        return None;
1720    }
1721    s.parse().ok()
1722}
1723
1724fn is_length_value(v: &Arg) -> bool {
1725    match v {
1726        Arg::Num(_) => true,
1727        Arg::Str(s) => {
1728            let s = s.trim();
1729            let lower = s.to_ascii_lowercase();
1730            let num = ["mm", "cm", "in", "pt", "px"].iter().find_map(|u| lower.strip_suffix(u)).unwrap_or(&lower).trim_end();
1731            let num = num.strip_prefix('-').unwrap_or(num);
1732            let mut parts = num.splitn(2, '.');
1733            let int = parts.next().unwrap_or("");
1734            let frac = parts.next();
1735            !int.is_empty() && int.chars().all(|c| c.is_ascii_digit()) && frac.is_none_or(|f| !f.is_empty() && f.chars().all(|c| c.is_ascii_digit()))
1736        }
1737        _ => false,
1738    }
1739}
1740
1741const DIRECTIONS: [&str; 32] = [
1742    "lr", "left-to-right", "e", "east", "tl-br", "nw-se", "se", "southeast", "tb", "top-to-bottom", "s", "south", "tr-bl", "ne-sw", "sw",
1743    "southwest", "rl", "right-to-left", "w", "west", "br-tl", "se-nw", "nw", "northwest", "bt", "bottom-to-top", "n", "north", "bl-tr",
1744    "sw-ne", "ne", "northeast",
1745];
1746
1747fn is_direction_value(v: &Arg) -> bool {
1748    match v {
1749        Arg::Num(n) => n.is_finite(),
1750        Arg::Str(s) => DIRECTIONS.contains(&s.trim().to_ascii_lowercase().as_str()),
1751        _ => false,
1752    }
1753}