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