Skip to main content

drawland_graph/
graph.rs

1//! The graph being built: its nodes, draws and composition, the output and
2//! the frame `page` and `world` read from it, and the views drawn into it,
3//! each a graph of its own.
4
5use crate::arg::{Arg, Obj};
6use drawland_core::frame::Frame;
7use drawland_core::grammar::{self, At, Clip, Compose, Def, Draw, Grammar, Id, Mask, Name, Section, Target};
8use drawland_core::profile::{OutputSpec, StrokeSpec};
9use serde_json::Value;
10use std::collections::HashMap;
11use std::fmt;
12
13/// How deep views may nest (a view drawing a style that has views of its own).
14pub const VIEW_DEPTH: usize = 4;
15
16/// What went wrong, and where in the script when the caller said
17/// ([`Graph::at`]).
18#[derive(Clone, Debug, PartialEq)]
19pub struct Error {
20    pub message: String,
21    pub at: Option<At>,
22    /// The script asked about a place its output names only by this address:
23    /// look it up and build again with the place given ([`Graph::new`]).
24    pub address: Option<String>,
25}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29        match self.at {
30            Some(at) => write!(f, "{at}: {}", self.message),
31            None => f.write_str(&self.message),
32        }
33    }
34}
35
36impl std::error::Error for Error {}
37
38pub type Result<T> = std::result::Result<T, Error>;
39
40/// A view's id, corner, ink, and the output keys its spec sets.
41#[derive(Clone, Debug)]
42pub(crate) struct ViewHead {
43    pub id: String,
44    pub at: (f64, f64),
45    pub keys: serde_json::Map<String, Value>,
46    pub ink: Option<String>,
47}
48
49/// One graph's worth: the page's, or a view's.
50#[derive(Default)]
51pub(crate) struct Builder {
52    pub title: Option<String>,
53    pub output: Option<OutputSpec>,
54    pub defs: Vec<Def>,
55    pub count: usize,
56    pub draw: Vec<Draw>,
57    pub order: Vec<Id>,
58    pub order_at: Option<At>,
59    pub masks: Vec<(String, Mask)>,
60    pub clip: Option<Clip>,
61    pub optimize: Vec<drawland_core::optimize::OptimizeStep>,
62    pub views: Vec<grammar::View>,
63    pub view: Option<ViewHead>,
64    /// The host's place, `(lat, lng)`, over the one the output asks.
65    pub place: Option<(f64, f64)>,
66    pub frame: Option<Frame>,
67    /// The parts of modules made so far, by what made them.
68    pub memo: HashMap<String, Arg>,
69}
70
71/// A draw.land graph, built a call at a time.
72///
73/// The library's functions are [`Graph::call`] by name (`"areas.union"`),
74/// as JavaScript and Python call them, or the typed methods of [`crate::api`]
75/// for Rust. [`Graph::finish`] gives the graph the engine draws.
76pub struct Graph {
77    pub(crate) stack: Vec<Builder>,
78    /// Where in the script the call being made is, for the graph's nodes and
79    /// for errors: set by the caller before each call.
80    pub at: Option<At>,
81    /// `Some` in a draft: whether a `remap` has been left out yet.
82    pub(crate) draft: Option<bool>,
83    pub(crate) wanted_address: Option<String>,
84}
85
86impl Default for Graph {
87    fn default() -> Self {
88        Graph::new(None)
89    }
90}
91
92impl Graph {
93    /// An empty graph. `place` (`(lat, lng)`) goes over whatever place the
94    /// output asks: `world` answers for it.
95    pub fn new(place: Option<(f64, f64)>) -> Graph {
96        Graph { stack: vec![Builder { place, ..Builder::default() }], at: None, draft: None, wanted_address: None }
97    }
98
99    /// A draft graph, for a page following a drag: `output` leaves its
100    /// `remap` warps out, since sampling one runs a function hundreds of
101    /// times. [`Graph::drafted`] says whether one was.
102    pub fn draft(place: Option<(f64, f64)>) -> Graph {
103        Graph { draft: Some(false), ..Graph::new(place) }
104    }
105
106    /// Whether a draft left a `remap` out.
107    pub fn drafted(&self) -> bool {
108        self.draft == Some(true)
109    }
110
111    /// The address the script needed coordinates for, if it asked `world`
112    /// about an output that names only one.
113    pub fn wanted_address(&self) -> Option<&str> {
114        self.wanted_address.as_deref()
115    }
116
117    pub(crate) fn top(&mut self) -> &mut Builder {
118        self.stack.last_mut().expect("a graph always has its page")
119    }
120
121    pub(crate) fn top_ref(&self) -> &Builder {
122        self.stack.last().expect("a graph always has its page")
123    }
124
125    /// An error at the call being made.
126    pub fn error(&self, message: impl Into<String>) -> Error {
127        Error { message: message.into(), at: self.at, address: None }
128    }
129
130    /// A new node in `section`, from its operation as the graph writes it
131    /// (`{ "tools_union": [...] }`): its reference.
132    pub(crate) fn node(&mut self, section: Section, op: Value) -> Result<String> {
133        let key = op.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
134        let parsed = grammar::op_from_json(section, op).map_err(|e| self.error(strip_kind(&e.to_string())))?;
135        let short = key
136            .strip_prefix("tools_")
137            .or_else(|| key.strip_prefix("engine_"))
138            .or_else(|| key.strip_suffix("_select"))
139            .unwrap_or(&key)
140            .to_string();
141        let name = match key.strip_prefix("module_") {
142            Some(module) => {
143                if self.top_ref().defs.iter().any(|d| d.name == module) {
144                    return Err(self.error(format!("modules.{module} is called twice; call it once and reuse its outputs")));
145                }
146                module.to_string()
147            }
148            None => {
149                let b = self.top();
150                b.count += 1;
151                format!("{short}_{}", b.count)
152            }
153        };
154        let def = Def { name, op: parsed, at: self.at };
155        let reference = def.reference().to_string();
156        self.top().defs.push(def);
157        Ok(reference)
158    }
159
160    pub(crate) fn add_draw(&mut self, from: &str, id: Option<String>, stroke: Option<&Arg>) -> Result<String> {
161        let from = target(from).map_err(|e| self.error(format!("draw: {e}")))?;
162        let stroke = match stroke {
163            None => None,
164            Some(s) => {
165                let s = s.to_json();
166                Some(serde_json::from_value::<StrokeSpec>(s.clone()).map_err(|e| {
167                    self.error(format!("draw: stroke {s}: {e}; write solid, dash, dotted, none or {{ style, dash, gap, mark, color, width, cap, join }}"))
168                })?)
169            }
170        };
171        let draw = Draw { id, from, stroke, at: self.at };
172        let group = draw.group();
173        if self.top_ref().draw.iter().any(|d| d.group() == group) {
174            return Err(self.error(format!("draw: the id {group:?} is already drawn")));
175        }
176        self.top().draw.push(draw);
177        Ok(group)
178    }
179
180    pub(crate) fn set_order(&mut self, ids: Vec<String>) {
181        let at = self.at;
182        let b = self.top();
183        b.order = ids.into_iter().map(Id).collect();
184        b.order_at = at;
185    }
186
187    pub(crate) fn add_mask(&mut self, name: Option<String>, from: &str, occludes: Vec<String>) -> Result<()> {
188        let from = target(from).map_err(|e| self.error(format!("compose.mask: {e}")))?;
189        let name = name.unwrap_or_else(|| format!("mask_{}", self.top_ref().masks.len() + 1));
190        if self.top_ref().masks.iter().any(|(n, _)| *n == name) {
191            return Err(self.error(format!("compose.mask: the name {name:?} is already used")));
192        }
193        let at = self.at;
194        self.top().masks.push((name, Mask { from, occludes: occludes.into_iter().map(Id).collect(), at }));
195        Ok(())
196    }
197
198    pub(crate) fn set_clip(&mut self, clip: Clip) {
199        self.top().clip = Some(clip);
200    }
201
202    pub(crate) fn clip_areas(&self, refs: &[String]) -> Result<Clip> {
203        refs.iter()
204            .map(|r| Name::parse(r))
205            .collect::<std::result::Result<Vec<_>, _>>()
206            .map(Clip::Areas)
207            .map_err(|e| self.error(format!("compose.clip: {e}")))
208    }
209
210    pub(crate) fn add_optimize(&mut self, step: Value) -> Result<()> {
211        let raw: grammar::RawOptimizeStep =
212            serde_json::from_value(step).map_err(|e| self.error(format!("compose: {}", strip_kind(&e.to_string()))))?;
213        let step = drawland_core::optimize::OptimizeStep {
214            layers: raw.layers.into_iter().map(Id).collect(),
215            except: raw.except.into_iter().map(Id).collect(),
216            op: raw.op,
217            at: self.at,
218        };
219        self.top().optimize.push(step);
220        Ok(())
221    }
222
223    /// The output as it will be: inside a view, the view's place and
224    /// rectangle win over what the style asks, so a style drawn in a view
225    /// keeps its look (pens, patterns) at the view's place; the host's place
226    /// wins over the script's.
227    pub(crate) fn set_output(&mut self, spec: &Obj) -> Result<()> {
228        let mut spec = Arg::Map(spec.clone()).to_json();
229        if let (Some(obj), Some(keys)) = (spec.as_object_mut(), self.top_ref().view.as_ref().map(|v| v.keys.clone())) {
230            for k in ["address", "slices"] {
231                obj.remove(k);
232            }
233            obj.extend(keys);
234        }
235        if let (Some(obj), Some((lat, lng))) = (spec.as_object_mut(), self.top_ref().place) {
236            obj.remove("address");
237            obj.insert("lat".into(), Value::from(lat));
238            obj.insert("lng".into(), Value::from(lng));
239        }
240        self.top().frame = None;
241        let output: OutputSpec = serde_json::from_value(spec).map_err(|e| self.error(format!("output: {e}")))?;
242        if self.top().output.replace(output).is_some() {
243            return Err(self.error("output is set twice"));
244        }
245        Ok(())
246    }
247
248    /// The output's warps replaced, so `page` and `world` answer through
249    /// them: how a `remap` is sampled through the warps before it.
250    pub(crate) fn set_warp(&mut self, warps: &Arg) -> Result<()> {
251        let warps: drawland_core::warp::Warps =
252            serde_json::from_value(warps.to_json()).map_err(|e| self.error(format!("output.warp: {e}")))?;
253        let b = self.top();
254        b.frame = None;
255        if b.output.as_mut().map(|o| o.warp = warps).is_none() {
256            return Err(self.error("output.warp: call output({ … }) first"));
257        }
258        Ok(())
259    }
260
261    /// Whether this is a draft, which leaves `remap` warps out; asking in
262    /// one marks the graph drafted.
263    pub(crate) fn ask_draft(&mut self) -> bool {
264        match self.draft {
265            Some(_) => {
266                self.draft = Some(true);
267                true
268            }
269            None => false,
270        }
271    }
272
273    /// The output `page` and `world` describe: the script's own, or inside
274    /// a view whose style never called `output`, the view's keys.
275    pub fn current_output(&self, asked: &str) -> Result<OutputSpec> {
276        let b = self.top_ref();
277        match (&b.output, &b.view) {
278            (Some(o), _) => Ok(o.clone()),
279            (None, Some(v)) => {
280                serde_json::from_value(Value::Object(v.keys.clone())).map_err(|e| self.error(format!("{asked}: {e}")))
281            }
282            (None, None) => Err(self.error(format!("{asked}: call output({{ … }}) first"))),
283        }
284    }
285
286    /// The frame `world` and the conversions answer from, worked out once
287    /// per output.
288    pub fn frame(&mut self, asked: &str) -> Result<Frame> {
289        if let Some(f) = self.top_ref().frame.clone() {
290            return Ok(f);
291        }
292        let spec = self.current_output(asked)?;
293        let (lat, lng) = match (spec.lat, spec.lng, &spec.address) {
294            (Some(lat), Some(lng), _) => (lat, lng),
295            (_, _, Some(address)) => {
296                self.wanted_address = Some(address.clone());
297                let mut e = self.error(format!(
298                    "{asked}: the output's place is the address {address:?}; a script can't look it up, so give the output a lat and lng"
299                ));
300                e.address = Some(address.clone());
301                return Err(e);
302            }
303            _ => return Err(self.error(format!("{asked}: the output has no place; give it a lat and lng"))),
304        };
305        let frame = Frame::new(&spec, (lng, lat));
306        self.top().frame = Some(frame.clone());
307        Ok(frame)
308    }
309
310    /// `view({ … }, style)` begins: the calls until [`Graph::view_end`]
311    /// build the view's own graph.
312    pub fn view_begin(&mut self, spec: &Arg) -> Result<()> {
313        let head = view_keys(spec).map_err(|e| self.error(e))?;
314        if self.stack.len() > VIEW_DEPTH {
315            return Err(self.error("views nest too deep"));
316        }
317        if self.top_ref().views.iter().any(|v| v.id == head.id) {
318            return Err(self.error(format!("two views are called {:?}", head.id)));
319        }
320        self.stack.push(Builder { view: Some(head), ..Builder::default() });
321        Ok(())
322    }
323
324    /// The view's graph is done: it joins the page's views (`ok`), or is
325    /// dropped (its style failed). Its id.
326    pub fn view_end(&mut self, ok: bool) -> Result<Arg> {
327        if self.stack.len() < 2 {
328            return Err(self.error("view_end without view_begin"));
329        }
330        let inner = self.stack.pop().expect("checked above");
331        let head = inner.view.clone().expect("a view's builder");
332        if !ok {
333            return Ok(Arg::Null);
334        }
335        let grammar = inner.finish().map_err(|e| Error { message: format!("view {}: {}", head.id, e.message), at: self.at, address: None })?;
336        self.top().views.push(grammar::View { id: head.id.clone(), at: head.at, grammar: Box::new(grammar), ink: head.ink });
337        Ok(Arg::Str(head.id))
338    }
339
340    /// The id of the view being built, if any.
341    pub fn view_id(&self) -> Option<&str> {
342        self.top_ref().view.as_ref().map(|v| v.id.as_str())
343    }
344
345    pub(crate) fn set_title(&mut self, text: String) {
346        self.top().title = Some(text);
347    }
348
349    /// The graph built: validated, ready for the engine.
350    pub fn finish(mut self) -> Result<Grammar> {
351        if self.stack.len() != 1 {
352            return Err(self.error("a view was begun and never ended"));
353        }
354        self.stack.pop().expect("the page").finish()
355    }
356}
357
358impl Builder {
359    fn finish(self) -> Result<Grammar> {
360        let output = match (self.output, &self.view) {
361            (Some(o), _) => o,
362            // A view whose style never called `output`: its own keys are all.
363            (None, Some(v)) => serde_json::from_value(Value::Object(v.keys.clone()))
364                .map_err(|e| Error { message: format!("view: {e}"), at: None, address: None })?,
365            (None, None) => serde_json::from_value(Value::Object(Default::default())).expect("an empty output is valid"),
366        };
367        let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
368        for section in Section::ALL {
369            let defs: Vec<Def> = self.defs.iter().filter(|d| d.op.section() == section).cloned().collect();
370            if !defs.is_empty() {
371                sections.push((section, defs));
372            }
373        }
374        let groups: Vec<String> = self.draw.iter().map(Draw::group).collect();
375        if let Some(missing) = self.order.iter().find(|id| !groups.contains(&id.0)) {
376            return Err(Error {
377                message: format!("compose.order names {:?}, which no draw writes", missing.0),
378                at: self.order_at,
379                address: None,
380            });
381        }
382        let compose = Compose {
383            order: self.order,
384            masks: self.masks,
385            clip: Default::default(),
386            clip_default: self.clip.unwrap_or(Clip::Auto),
387            optimize: self.optimize,
388        };
389        let graph = Grammar { title: self.title, output, sections, draw: self.draw, compose, views: self.views };
390        grammar::validate(&graph).map_err(|e| {
391            let message = e.to_string();
392            Error { at: find_at(&message), message, address: None }
393        })?;
394        Ok(graph)
395    }
396}
397
398/// `$lines.x`, `$fills.x` or `roads.outlines`.
399fn target(text: &str) -> std::result::Result<Target, String> {
400    if text.starts_with('$') {
401        return Name::parse(text).map(|name| Target { module: None, name });
402    }
403    match text.split_once('.') {
404        Some((module, output)) => Ok(Target {
405            module: Some(module.to_string()),
406            name: Name { section: Section::Lines, name: output.to_string() },
407        }),
408        None => Err(format!("{text:?} is not a reference")),
409    }
410}
411
412/// The output keys a view's spec sets: `{ id, at: [x, y], size: [w, h] }` in
413/// page mm, and the place (`lat`, `lng`, `scale`, `bearing`, `tileZoom`,
414/// `projection`).
415fn view_keys(spec: &Arg) -> std::result::Result<ViewHead, String> {
416    let spec = spec.to_json();
417    let o = spec.as_object().ok_or("view takes { at, size, lat, lng, scale, … }")?;
418    let pair = |k: &str| -> std::result::Result<(f64, f64), String> {
419        match o.get(k).and_then(Value::as_array).map(|a| a.iter().map(Value::as_f64).collect::<Vec<_>>()) {
420            Some(v) if v.len() == 2 && v.iter().all(Option::is_some) => Ok((v[0].unwrap(), v[1].unwrap())),
421            _ => Err(format!("view.{k} is [x, y] in millimetres")),
422        }
423    };
424    let at = pair("at")?;
425    let (w, h) = pair("size")?;
426    if w <= 0.0 || h <= 0.0 {
427        return Err("view.size must be positive".into());
428    }
429    let id = o.get("id").and_then(Value::as_str).ok_or("view.id names the view, as compose.mask occludes it")?.to_string();
430    let mut keys = serde_json::Map::new();
431    keys.insert("width".into(), Value::String(format!("{w}mm")));
432    keys.insert("height".into(), Value::String(format!("{h}mm")));
433    keys.insert("padding".into(), Value::from(0));
434    for k in ["lat", "lng", "scale", "bearing", "tileZoom", "projection"] {
435        if let Some(v) = o.get(k) {
436            keys.insert(k.into(), v.clone());
437        }
438    }
439    let ink = match o.get("ink") {
440        None | Some(Value::Null) => None,
441        Some(Value::String(c)) if !c.trim().is_empty() => Some(c.trim().to_string()),
442        Some(v) => return Err(format!("view.ink is a colour like \"#e4572e\", got {v}")),
443    };
444    Ok(ViewHead { id, at, keys, ink })
445}
446
447/// `profile: …` and the like: the grammar's own prefixes mean nothing to a
448/// script author.
449pub(crate) fn strip_kind(message: &str) -> String {
450    message.strip_prefix("profile: ").unwrap_or(message).to_string()
451}
452
453/// The first `line N column M` in a message.
454pub fn find_at(message: &str) -> Option<At> {
455    let start = message.find("line ")?;
456    let rest = &message[start + 5..];
457    let (line, rest) = rest.split_once(" column ")?;
458    let column: String = rest.chars().take_while(char::is_ascii_digit).collect();
459    Some(At(line.parse().ok()?, column.parse().ok()?))
460}