1use 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
13pub const VIEW_DEPTH: usize = 4;
15
16#[derive(Clone, Debug, PartialEq)]
19pub struct Error {
20 pub message: String,
21 pub at: Option<At>,
22 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#[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#[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 paint: Vec<drawland_core::paint::Paint>,
58 pub order: Vec<Id>,
59 pub order_at: Option<At>,
60 pub masks: Vec<(String, Mask)>,
61 pub clip: Option<Clip>,
62 pub optimize: Vec<drawland_core::optimize::OptimizeStep>,
63 pub views: Vec<grammar::View>,
64 pub view: Option<ViewHead>,
65 pub place: Option<(f64, f64)>,
67 pub frame: Option<Frame>,
68 pub memo: HashMap<String, Arg>,
70}
71
72pub struct Graph {
78 pub(crate) stack: Vec<Builder>,
79 pub at: Option<At>,
82 pub(crate) draft: Option<bool>,
84 pub(crate) wanted_address: Option<String>,
85}
86
87impl Default for Graph {
88 fn default() -> Self {
89 Graph::new(None)
90 }
91}
92
93impl Graph {
94 pub fn new(place: Option<(f64, f64)>) -> Graph {
97 Graph { stack: vec![Builder { place, ..Builder::default() }], at: None, draft: None, wanted_address: None }
98 }
99
100 pub fn draft(place: Option<(f64, f64)>) -> Graph {
104 Graph { draft: Some(false), ..Graph::new(place) }
105 }
106
107 pub fn drafted(&self) -> bool {
109 self.draft == Some(true)
110 }
111
112 pub fn wanted_address(&self) -> Option<&str> {
115 self.wanted_address.as_deref()
116 }
117
118 pub(crate) fn top(&mut self) -> &mut Builder {
119 self.stack.last_mut().expect("a graph always has its page")
120 }
121
122 pub(crate) fn top_ref(&self) -> &Builder {
123 self.stack.last().expect("a graph always has its page")
124 }
125
126 pub fn error(&self, message: impl Into<String>) -> Error {
128 Error { message: message.into(), at: self.at, address: None }
129 }
130
131 pub(crate) fn node(&mut self, section: Section, op: Value) -> Result<String> {
134 let key = op.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
135 let parsed = grammar::op_from_json(section, op).map_err(|e| self.error(strip_kind(&e.to_string())))?;
136 let short = key
137 .strip_prefix("tools_")
138 .or_else(|| key.strip_prefix("engine_"))
139 .or_else(|| key.strip_suffix("_select"))
140 .unwrap_or(&key)
141 .to_string();
142 let name = match key.strip_prefix("module_") {
143 Some(module) => {
144 if self.top_ref().defs.iter().any(|d| d.name == module) {
145 return Err(self.error(format!("modules.{module} is called twice; call it once and reuse its outputs")));
146 }
147 module.to_string()
148 }
149 None => {
150 let b = self.top();
151 b.count += 1;
152 format!("{short}_{}", b.count)
153 }
154 };
155 let def = Def { name, op: parsed, at: self.at };
156 let reference = def.reference().to_string();
157 self.top().defs.push(def);
158 Ok(reference)
159 }
160
161 pub(crate) fn add_draw(&mut self, from: &str, id: Option<String>, stroke: Option<&Arg>) -> Result<String> {
162 let from = target(from).map_err(|e| self.error(format!("draw: {e}")))?;
163 let stroke = match stroke {
164 None => None,
165 Some(s) => {
166 let s = s.to_json();
167 Some(serde_json::from_value::<StrokeSpec>(s.clone()).map_err(|e| {
168 self.error(format!("draw: stroke {s}: {e}; write solid, dash, dotted, none or {{ style, dash, gap, mark, color, width, cap, join }}"))
169 })?)
170 }
171 };
172 let draw = Draw { id, from, stroke, at: self.at };
173 let group = draw.group();
174 if self.top_ref().draw.iter().any(|d| d.group() == group) {
175 return Err(self.error(format!("draw: the id {group:?} is already drawn")));
176 }
177 self.top().draw.push(draw);
178 Ok(group)
179 }
180
181 pub(crate) fn add_paint(&mut self, id: String, from: &str, look: drawland_core::paint::Style, shown: drawland_core::paint::Shown, halo: drawland_core::paint::Halo) -> Result<String> {
183 let from = target(from).map_err(|e| self.error(format!("paint: {e}")))?;
184 if self.top_ref().paint.iter().any(|p| p.id == id) {
185 return Err(self.error(format!("paint: the id {id:?} is already painted")));
186 }
187 let at = self.at;
188 self.top().paint.push(drawland_core::paint::Paint { id: id.clone(), from, look, shown, halo, at });
189 Ok(id)
190 }
191
192 pub(crate) fn set_order(&mut self, ids: Vec<String>) {
193 let at = self.at;
194 let b = self.top();
195 b.order = ids.into_iter().map(Id).collect();
196 b.order_at = at;
197 }
198
199 pub(crate) fn add_mask(&mut self, name: Option<String>, from: &str, occludes: Vec<String>) -> Result<()> {
200 let from = target(from).map_err(|e| self.error(format!("compose.mask: {e}")))?;
201 let name = name.unwrap_or_else(|| format!("mask_{}", self.top_ref().masks.len() + 1));
202 if self.top_ref().masks.iter().any(|(n, _)| *n == name) {
203 return Err(self.error(format!("compose.mask: the name {name:?} is already used")));
204 }
205 let at = self.at;
206 self.top().masks.push((name, Mask { from, occludes: occludes.into_iter().map(Id).collect(), at }));
207 Ok(())
208 }
209
210 pub(crate) fn set_clip(&mut self, clip: Clip) {
211 self.top().clip = Some(clip);
212 }
213
214 pub(crate) fn clip_areas(&self, refs: &[String]) -> Result<Clip> {
215 refs.iter()
216 .map(|r| Name::parse(r))
217 .collect::<std::result::Result<Vec<_>, _>>()
218 .map(Clip::Areas)
219 .map_err(|e| self.error(format!("compose.clip: {e}")))
220 }
221
222 pub(crate) fn add_optimize(&mut self, step: Value) -> Result<()> {
223 let raw: grammar::RawOptimizeStep =
224 serde_json::from_value(step).map_err(|e| self.error(format!("compose: {}", strip_kind(&e.to_string()))))?;
225 let step = drawland_core::optimize::OptimizeStep {
226 layers: raw.layers.into_iter().map(Id).collect(),
227 except: raw.except.into_iter().map(Id).collect(),
228 op: raw.op,
229 at: self.at,
230 };
231 self.top().optimize.push(step);
232 Ok(())
233 }
234
235 pub(crate) fn set_output(&mut self, spec: &Obj) -> Result<()> {
240 let mut spec = Arg::Map(spec.clone()).to_json();
241 if let (Some(obj), Some(keys)) = (spec.as_object_mut(), self.top_ref().view.as_ref().map(|v| v.keys.clone())) {
242 for k in ["address", "slices"] {
243 obj.remove(k);
244 }
245 obj.extend(keys);
246 }
247 if let (Some(obj), Some((lat, lng))) = (spec.as_object_mut(), self.top_ref().place) {
248 obj.remove("address");
249 obj.insert("lat".into(), Value::from(lat));
250 obj.insert("lng".into(), Value::from(lng));
251 }
252 self.top().frame = None;
253 if let Some(obj) = spec.as_object() {
254 if obj.contains_key("screen") {
255 if let Some(k) = ["width", "height"].into_iter().find(|k| obj.contains_key(*k)) {
256 return Err(self.error(format!("output: a screen sets its own size; leave out {k}")));
257 }
258 }
259 }
260 let mut output: OutputSpec = serde_json::from_value(spec).map_err(|e| self.error(format!("output: {e}")))?;
261 output.fit_screen().map_err(|e| self.error(e))?;
262 if self.top().output.replace(output).is_some() {
263 return Err(self.error("output is set twice"));
264 }
265 Ok(())
266 }
267
268 pub(crate) fn set_warp(&mut self, warps: &Arg) -> Result<()> {
271 let warps: drawland_core::warp::Warps =
272 serde_json::from_value(warps.to_json()).map_err(|e| self.error(format!("output.warp: {e}")))?;
273 let b = self.top();
274 b.frame = None;
275 if b.output.as_mut().map(|o| o.warp = warps).is_none() {
276 return Err(self.error("output.warp: call output({ … }) first"));
277 }
278 Ok(())
279 }
280
281 pub(crate) fn ask_draft(&mut self) -> bool {
284 match self.draft {
285 Some(_) => {
286 self.draft = Some(true);
287 true
288 }
289 None => false,
290 }
291 }
292
293 pub fn current_output(&self, asked: &str) -> Result<OutputSpec> {
296 let b = self.top_ref();
297 match (&b.output, &b.view) {
298 (Some(o), _) => Ok(o.clone()),
299 (None, Some(v)) => {
300 serde_json::from_value(Value::Object(v.keys.clone())).map_err(|e| self.error(format!("{asked}: {e}")))
301 }
302 (None, None) => Err(self.error(format!("{asked}: call output({{ … }}) first"))),
303 }
304 }
305
306 pub fn frame(&mut self, asked: &str) -> Result<Frame> {
309 if let Some(f) = self.top_ref().frame.clone() {
310 return Ok(f);
311 }
312 let spec = self.current_output(asked)?;
313 let (lat, lng) = match (spec.lat, spec.lng, &spec.address) {
314 (Some(lat), Some(lng), _) => (lat, lng),
315 (_, _, Some(address)) => {
316 self.wanted_address = Some(address.clone());
317 let mut e = self.error(format!(
318 "{asked}: the output's place is the address {address:?}; a script can't look it up, so give the output a lat and lng"
319 ));
320 e.address = Some(address.clone());
321 return Err(e);
322 }
323 _ => return Err(self.error(format!("{asked}: the output has no place; give it a lat and lng"))),
324 };
325 let frame = Frame::new(&spec, (lng, lat));
326 self.top().frame = Some(frame.clone());
327 Ok(frame)
328 }
329
330 pub fn view_begin(&mut self, spec: &Arg) -> Result<()> {
333 let head = view_keys(spec).map_err(|e| self.error(e))?;
334 if self.stack.len() > VIEW_DEPTH {
335 return Err(self.error("views nest too deep"));
336 }
337 if self.top_ref().views.iter().any(|v| v.id == head.id) {
338 return Err(self.error(format!("two views are called {:?}", head.id)));
339 }
340 self.stack.push(Builder { view: Some(head), ..Builder::default() });
341 Ok(())
342 }
343
344 pub fn view_end(&mut self, ok: bool) -> Result<Arg> {
347 if self.stack.len() < 2 {
348 return Err(self.error("view_end without view_begin"));
349 }
350 let inner = self.stack.pop().expect("checked above");
351 let head = inner.view.clone().expect("a view's builder");
352 if !ok {
353 return Ok(Arg::Null);
354 }
355 let grammar = inner.finish().map_err(|e| Error { message: format!("view {}: {}", head.id, e.message), at: self.at, address: None })?;
356 self.top().views.push(grammar::View { id: head.id.clone(), at: head.at, grammar: Box::new(grammar), ink: head.ink });
357 Ok(Arg::Str(head.id))
358 }
359
360 pub fn view_id(&self) -> Option<&str> {
362 self.top_ref().view.as_ref().map(|v| v.id.as_str())
363 }
364
365 pub(crate) fn set_title(&mut self, text: String) {
366 self.top().title = Some(text);
367 }
368
369 pub fn finish(mut self) -> Result<Grammar> {
371 if self.stack.len() != 1 {
372 return Err(self.error("a view was begun and never ended"));
373 }
374 self.stack.pop().expect("the page").finish()
375 }
376}
377
378impl Builder {
379 fn finish(self) -> Result<Grammar> {
380 let output = match (self.output, &self.view) {
381 (Some(o), _) => o,
382 (None, Some(v)) => serde_json::from_value(Value::Object(v.keys.clone()))
384 .map_err(|e| Error { message: format!("view: {e}"), at: None, address: None })?,
385 (None, None) => serde_json::from_value(Value::Object(Default::default())).expect("an empty output is valid"),
386 };
387 let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
388 for section in Section::ALL {
389 let defs: Vec<Def> = self.defs.iter().filter(|d| d.op.section() == section).cloned().collect();
390 if !defs.is_empty() {
391 sections.push((section, defs));
392 }
393 }
394 let groups: Vec<String> = self.draw.iter().map(Draw::group).collect();
395 if let Some(missing) = self.order.iter().find(|id| !groups.contains(&id.0)) {
396 return Err(Error {
397 message: format!("compose.order names {:?}, which no draw writes", missing.0),
398 at: self.order_at,
399 address: None,
400 });
401 }
402 let compose = Compose {
403 order: self.order,
404 masks: self.masks,
405 clip: Default::default(),
406 clip_default: self.clip.unwrap_or(Clip::Auto),
407 optimize: self.optimize,
408 };
409 let graph = Grammar { title: self.title, output, sections, draw: self.draw, compose, paint: self.paint, views: self.views };
410 grammar::validate(&graph).map_err(|e| {
411 let message = e.to_string();
412 Error { at: find_at(&message), message, address: None }
413 })?;
414 Ok(graph)
415 }
416}
417
418fn target(text: &str) -> std::result::Result<Target, String> {
420 if text.starts_with('$') {
421 return Name::parse(text).map(|name| Target { module: None, name });
422 }
423 match text.split_once('.') {
424 Some((module, output)) => Ok(Target {
425 module: Some(module.to_string()),
426 name: Name { section: Section::Lines, name: output.to_string() },
427 }),
428 None => Err(format!("{text:?} is not a reference")),
429 }
430}
431
432fn view_keys(spec: &Arg) -> std::result::Result<ViewHead, String> {
436 let spec = spec.to_json();
437 let o = spec.as_object().ok_or("view takes { at, size, lat, lng, scale, … }")?;
438 let pair = |k: &str| -> std::result::Result<(f64, f64), String> {
439 match o.get(k).and_then(Value::as_array).map(|a| a.iter().map(Value::as_f64).collect::<Vec<_>>()) {
440 Some(v) if v.len() == 2 && v.iter().all(Option::is_some) => Ok((v[0].unwrap(), v[1].unwrap())),
441 _ => Err(format!("view.{k} is [x, y] in millimetres")),
442 }
443 };
444 let at = pair("at")?;
445 let (w, h) = pair("size")?;
446 if w <= 0.0 || h <= 0.0 {
447 return Err("view.size must be positive".into());
448 }
449 let id = o.get("id").and_then(Value::as_str).ok_or("view.id names the view, as compose.mask occludes it")?.to_string();
450 let mut keys = serde_json::Map::new();
451 keys.insert("width".into(), Value::String(format!("{w}mm")));
452 keys.insert("height".into(), Value::String(format!("{h}mm")));
453 keys.insert("padding".into(), Value::from(0));
454 for k in ["lat", "lng", "scale", "bearing", "tileZoom", "projection"] {
455 if let Some(v) = o.get(k) {
456 keys.insert(k.into(), v.clone());
457 }
458 }
459 let ink = match o.get("ink") {
460 None | Some(Value::Null) => None,
461 Some(Value::String(c)) if !c.trim().is_empty() => Some(c.trim().to_string()),
462 Some(v) => return Err(format!("view.ink is a colour like \"#e4572e\", got {v}")),
463 };
464 Ok(ViewHead { id, at, keys, ink })
465}
466
467pub(crate) fn strip_kind(message: &str) -> String {
470 message.strip_prefix("profile: ").unwrap_or(message).to_string()
471}
472
473pub fn find_at(message: &str) -> Option<At> {
475 let start = message.find("line ")?;
476 let rest = &message[start + 5..];
477 let (line, rest) = rest.split_once(" column ")?;
478 let column: String = rest.chars().take_while(char::is_ascii_digit).collect();
479 Some(At(line.parse().ok()?, column.parse().ok()?))
480}