Skip to main content

lichtung_plot/recipe/
run.rs

1//! Explicit document execution and publication settings.
2
3use std::{
4    io::Write,
5    path::{Path, PathBuf},
6};
7
8use toml_edit::{Item, TableLike, Value};
9
10use crate::{
11    layout::LayoutReport,
12    operation::{self, OperationOptions},
13    output::{save_inner, Format},
14    Output, Result,
15};
16
17use crate::recipe::schema::{self as grammar, Schema};
18
19use super::{
20    codec::{choice, invalid, Codec},
21    source, Bindings, Recipe,
22};
23
24/// The implemented execution actions for a static recipe.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum RunAction {
28    /// Produce one complete image.
29    Image,
30    /// Prepare the editable native base's actual layout.
31    Layout,
32}
33
34choice!(RunAction {Image=>"image",Layout=>"layout"});
35
36impl std::str::FromStr for RunAction {
37    type Err = crate::Error;
38
39    fn from_str(value: &str) -> Result<Self> {
40        Self::decode(&Item::Value(value.into()), None)
41    }
42}
43
44/// The actual result of one successful document execution.
45#[derive(Debug, Clone)]
46#[non_exhaustive]
47pub enum RunResult {
48    /// The complete scene frozen by the same execution that published the image.
49    Image(Output),
50    /// The actual accepted native layout.
51    Layout(LayoutReport),
52}
53
54/// Call-local overrides. They never rewrite the document.
55#[derive(Default)]
56#[must_use]
57pub struct RunOptions<'a> {
58    bindings: Option<&'a Bindings<'a>>,
59    action: Option<RunAction>,
60    output: Option<PathBuf>,
61    layout_writer: Option<&'a mut dyn Write>,
62}
63
64impl<'a> RunOptions<'a> {
65    /// Substitute logical sources for the selected operation.
66    pub fn bindings(mut self, bindings: &'a Bindings<'a>) -> Self {
67        self.bindings = Some(bindings);
68        self
69    }
70
71    /// Select the operation explicitly.
72    pub const fn action(mut self, action: RunAction) -> Self {
73        self.action = Some(action);
74        self
75    }
76
77    /// Override just the selected action's destination, relative to the caller.
78    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
79        self.output = Some(path.into());
80        self
81    }
82
83    /// Write the native layout JSON to this stream if the layout action has no
84    /// declared or call-local file destination. Image actions do not use it.
85    pub fn layout_writer(mut self, writer: &'a mut dyn Write) -> Self {
86        self.layout_writer = Some(writer);
87        self
88    }
89}
90
91/// A requested default action and its independent destination and device.
92#[derive(Debug, Clone)]
93#[non_exhaustive]
94#[expect(
95    clippy::large_enum_variant,
96    reason = "a single call-local publication declaration needs no heap indirection"
97)]
98pub enum OutputDeclaration {
99    /// An image file and explicitly selected native format.
100    Image {
101        /// Local destination.
102        path: PathBuf,
103        /// Actual encoder and its publication settings.
104        format: Format,
105    },
106    /// Native layout, optionally written as JSON.
107    Layout {
108        /// Local report destination, or no file.
109        path: Option<PathBuf>,
110    },
111}
112
113impl OutputDeclaration {
114    /// Declare the image action with an explicit format.
115    pub fn image(path: impl Into<PathBuf>, format: impl Into<Format>) -> Self {
116        Self::Image {
117            path: path.into(),
118            format: format.into(),
119        }
120    }
121
122    /// Declare the layout action and its optional report file.
123    pub fn layout(path: Option<PathBuf>) -> Self {
124        Self::Layout { path }
125    }
126}
127
128#[derive(Default)]
129struct Settings<'a> {
130    action: Option<RunAction>,
131    image: Option<PathBuf>,
132    layout: Option<PathBuf>,
133    image_options: Option<&'a Item>,
134}
135
136fn path_field(fields: &dyn TableLike, name: &str) -> Result<Option<PathBuf>> {
137    fields
138        .get(name)
139        .map(|item| {
140            let path = item
141                .as_str()
142                .filter(|path| !path.is_empty())
143                .ok_or_else(|| invalid(format!("{name} requires a nonempty local path")))?;
144            Ok(PathBuf::from(path))
145        })
146        .transpose()
147}
148
149const OUTPUT_FIELDS: &[grammar::Field] = &[
150    grammar::optional::<RunAction>("action"),
151    grammar::custom(
152        "image",
153        false,
154        |_| serde_json::json!({"type":"string","minLength":1}),
155    ),
156    grammar::custom(
157        "layout",
158        false,
159        |_| serde_json::json!({"type":"string","minLength":1}),
160    ),
161    grammar::optional::<Format>("image_options"),
162];
163pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
164    grammar::record(ctx, OUTPUT_FIELDS)
165}
166
167impl<'a> Settings<'a> {
168    fn read(item: Option<&'a Item>) -> Result<Self> {
169        let Some(item) = item else {
170            return Ok(Self::default());
171        };
172        let fields = grammar::record_fields(item, OUTPUT_FIELDS)?;
173        let settings = Self {
174            action: fields
175                .get("action")
176                .map(|item| RunAction::decode(item, None))
177                .transpose()?,
178            image: path_field(fields, "image")?,
179            layout: path_field(fields, "layout")?,
180            image_options: fields.get("image_options"),
181        };
182        if let Some(options) = settings.image_options {
183            let inferred = settings
184                .image
185                .as_ref()
186                .and_then(|path| Format::from_path(path).ok());
187            let _ = Format::decode(options, inferred)
188                .map_err(|error| error.with_prefix("image_options"))?;
189        }
190        Ok(settings)
191    }
192
193    fn destination(
194        &self,
195        action: RunAction,
196        override_path: Option<PathBuf>,
197        base: &Path,
198    ) -> Result<Option<PathBuf>> {
199        if override_path.is_some() {
200            return Ok(override_path);
201        }
202        let path = match action {
203            RunAction::Image => &self.image,
204            RunAction::Layout => &self.layout,
205        };
206        path.as_ref()
207            .map(|path| source::expand_path(path, base))
208            .transpose()
209    }
210
211    fn format(&self, destination: &Path) -> Result<Format> {
212        // An explicit device wins; otherwise a known declared suffix selects
213        // the encoder even when the destination was overridden for this run.
214        let inferred = self
215            .image
216            .as_ref()
217            .and_then(|path| Format::from_path(path).ok())
218            .or_else(|| Format::from_path(destination).ok());
219        if let Some(options) = self.image_options {
220            if options.get("device").is_none() && inferred.is_none() {
221                return Err(invalid(
222                    "image output requires an explicit device or an SVG/PNG filename",
223                ));
224            }
225            return Format::decode(options, inferred)
226                .map_err(|error| error.with_prefix("image_options"));
227        }
228        inferred.ok_or_else(|| {
229            invalid("image output requires an explicit device or an SVG/PNG filename")
230        })
231    }
232}
233
234pub(super) fn validate_output(item: Option<&Item>) -> Result<()> {
235    Settings::read(item)
236        .map(drop)
237        .map_err(|error| error.with_prefix("output"))
238}
239
240pub(super) fn rebase_output(item: &mut Item, base: &Path) -> Result<()> {
241    let fields = item
242        .as_table_like_mut()
243        .ok_or_else(|| invalid("output must be a table"))?;
244    for name in ["image", "layout"] {
245        if let Some(path) = fields.get_mut(name) {
246            let rebased = source::rebase(
247                Path::new(path.as_str().expect("validated destination")),
248                base,
249            );
250            *path = path_item(&rebased)?;
251        }
252    }
253    Ok(())
254}
255
256fn path_item(path: &Path) -> Result<Item> {
257    let path = path
258        .to_str()
259        .filter(|path| !path.is_empty())
260        .ok_or_else(|| invalid("output path requires nonempty Unicode"))?;
261    Ok(toml_edit::value(path))
262}
263
264fn declared_path(path: &Path, base: &Path) -> Result<Item> {
265    if path.as_os_str().is_empty() {
266        return Err(invalid("output path must not be empty"));
267    }
268    path_item(&source::rebase(path, base))
269}
270
271impl Recipe {
272    /// Set an explicit output declaration, retaining the other action's settings.
273    pub fn set_output(&mut self, declaration: OutputDeclaration) -> Result<()> {
274        let directory = std::env::current_dir()?;
275        let mut document = self.document.clone();
276        if document.get("output").is_none() {
277            document["output"] = Item::Table(toml_edit::Table::new());
278        }
279        let fields = document["output"]
280            .as_table_like_mut()
281            .expect("validated output table");
282        let action = match declaration {
283            OutputDeclaration::Image { path, format } => {
284                format.validate()?;
285                fields.insert("image", declared_path(&path, &directory)?);
286                fields.insert("image_options", Item::Value(format.encode()));
287                RunAction::Image
288            }
289            OutputDeclaration::Layout { path } => {
290                if let Some(path) = path {
291                    fields.insert("layout", declared_path(&path, &directory)?);
292                } else {
293                    fields.remove("layout");
294                }
295                RunAction::Layout
296            }
297        };
298        fields.insert("action", Item::Value(action.encode()));
299        self.install(document)
300    }
301
302    /// Execute the explicitly declared action using local default inputs.
303    pub fn run(&self) -> Result<RunResult> {
304        self.run_with(RunOptions::default())
305    }
306
307    /// Execute one action with optional call-local source and destination overrides.
308    pub fn run_with(&self, options: RunOptions<'_>) -> Result<RunResult> {
309        self.run_with_operation(options, &OperationOptions::default())
310    }
311
312    /// Execute the selected action under one cancellable operation.
313    pub fn run_with_operation(
314        &self,
315        options: RunOptions<'_>,
316        operation: &OperationOptions,
317    ) -> Result<RunResult> {
318        operation::run(operation, || self.run_inner(options))
319    }
320
321    fn run_inner(&self, options: RunOptions<'_>) -> Result<RunResult> {
322        let settings = Settings::read(self.document.get("output"))?;
323        let action = options.action.or(settings.action).ok_or_else(|| {
324            invalid("recipe execution requires an explicit action (image or layout)")
325        })?;
326        let destination = settings.destination(action, options.output, &self.base)?;
327        let default = Bindings::new();
328        let bindings = options.bindings.unwrap_or(&default);
329        match action {
330            RunAction::Layout => {
331                let report = self.layout_source(bindings)?.recipe_layout_report()?;
332                if destination.is_some() || options.layout_writer.is_some() {
333                    operation::phase(crate::errors::OperationPhase::Write)?;
334                    let mut json = report.to_json()?;
335                    json.push('\n');
336                    if let Some(path) = destination {
337                        crate::orchestrator::write_atomic(&path, json.as_bytes())?;
338                    } else if let Some(writer) = options.layout_writer {
339                        crate::output::write_stream(writer, json.as_bytes())?;
340                    }
341                }
342                Ok(RunResult::Layout(report))
343            }
344            RunAction::Image => {
345                let destination = destination
346                    .ok_or_else(|| invalid("image action requires an output destination"))?;
347                let format = settings.format(&destination)?;
348                let output = if self.document.get("base").is_some() {
349                    let composite = self.composition_inner(bindings)?.compose_inner()?;
350                    save_inner(&composite, &destination, &format)?
351                } else {
352                    if self.document.get("placements").is_some() {
353                        return Err(invalid(
354                            "image action for placement declarations requires an explicit base",
355                        ));
356                    }
357                    let figure = self.build_inner(bindings)?;
358                    save_inner(&figure, &destination, &format)?
359                };
360                Ok(RunResult::Image(output))
361            }
362        }
363    }
364}