Skip to main content

lichtung_plot/composition/recipe/
plan.rs

1//! Independent and mixed-document composition declarations.
2
3use std::path::Path;
4
5use toml_edit::{InlineTable, Item, TableLike, Value};
6
7use crate::{
8    operation::{self, OperationOptions},
9    recipe::{
10        capture::Capture,
11        codec::{array_items, field, invalid, table},
12        declaration::BindingRequirement,
13        resolve::Resolver,
14        Recipe,
15    },
16    Result,
17};
18
19use crate::recipe::schema::{self as grammar, Schema};
20
21use super::{
22    capture_content, read_content, read_placement, SupplyContent, SupplyPlacement, CONTENT_FIELDS,
23};
24use crate::composition::{
25    plan::PlanStep, ComposeOptions, CompositionPlan, CompositionSource, Placement,
26};
27
28pub(crate) enum BaseBlueprint {
29    NativeRoot,
30    Content(Box<SupplyContent>),
31}
32
33impl BaseBlueprint {
34    pub(crate) fn read(
35        fields: &dyn TableLike,
36        native_root: bool,
37        fallback: Option<&str>,
38        requirements: &mut Vec<BindingRequirement>,
39    ) -> Result<Option<Self>> {
40        let Some(item) = fields.get("base") else {
41            return Ok(None);
42        };
43        let source = table(item, CONTENT_FIELDS)?;
44        if let Some(native) = source.get("native").and_then(Item::as_bool) {
45            if !native || source.len() != 1 || !native_root {
46                return Err(invalid(
47                    "base.native=true requires the actual declared native Plot or Canvas root",
48                ));
49            }
50            return Ok(Some(Self::NativeRoot));
51        }
52        read_content(source, "base", fallback, requirements, true)
53            .map(Box::new)
54            .map(Self::Content)
55            .map(Some)
56    }
57
58    pub(crate) fn build(
59        self,
60        root: Option<CompositionSource>,
61        resolver: &mut Resolver<'_>,
62    ) -> Result<CompositionSource> {
63        match self {
64            Self::NativeRoot => {
65                root.ok_or_else(|| invalid("composition requires its declared native root"))
66            }
67            Self::Content(source) => source.build(resolver),
68        }
69    }
70}
71
72const STEP_FIELDS: &[grammar::Field] = &[
73    grammar::optional::<bool>("expand_canvas"),
74    grammar::custom("placements", true, |ctx| {
75        grammar::array(super::placement_schema(ctx))
76    }),
77];
78const COMPOSITION_FIELDS: &[grammar::Field] = &[
79    grammar::optional::<bool>("expand_canvas"),
80    grammar::custom(
81        "steps",
82        false,
83        |ctx| serde_json::json!({"type":"array","minItems":1,"items":grammar::record(ctx,STEP_FIELDS)}),
84    ),
85];
86
87pub(crate) fn schema(ctx: &mut Schema) -> serde_json::Value {
88    grammar::with(
89        grammar::record(ctx, COMPOSITION_FIELDS),
90        grammar::at_most_one(&["expand_canvas", "steps"]),
91    )
92}
93
94pub(crate) struct StepBlueprint {
95    items: Vec<SupplyPlacement>,
96    options: ComposeOptions,
97}
98
99impl StepBlueprint {
100    fn read_items(
101        item: Option<&Item>,
102        path: &str,
103        fallback: Option<&str>,
104        requirements: &mut Vec<BindingRequirement>,
105    ) -> Result<Vec<SupplyPlacement>> {
106        item.map_or_else(
107            || Ok(Vec::new()),
108            |item| {
109                array_items(item)?
110                    .enumerate()
111                    .map(|(index, item)| {
112                        operation::check()?;
113                        read_placement(item, &format!("{path}[{index}]"), fallback, requirements)
114                    })
115                    .collect()
116            },
117        )
118    }
119
120    pub(crate) fn read(
121        fields: &dyn TableLike,
122        fallback: Option<&str>,
123        requirements: &mut Vec<BindingRequirement>,
124    ) -> Result<Vec<Self>> {
125        let configuration = fields
126            .get("composition")
127            .map(|item| grammar::record_fields(item, COMPOSITION_FIELDS))
128            .transpose()?;
129        let placements = fields.get("placements");
130        let step_list = configuration.and_then(|fields| fields.get("steps"));
131        if let Some(list) = step_list {
132            if placements.is_some()
133                || configuration.is_some_and(|fields| fields.contains_key("expand_canvas"))
134            {
135                return Err(invalid(
136                    "composition.steps is mutually exclusive with a single placement step",
137                ));
138            }
139            if !fields.contains_key("base") {
140                return Err(invalid(
141                    "chained composition requires an actual base declaration",
142                ));
143            }
144            let steps = array_items(list)?
145                .enumerate()
146                .map(|(index, item)| {
147                    let fields = grammar::record_fields(item, STEP_FIELDS)?;
148                    let items = fields.get("placements").ok_or_else(|| {
149                        invalid("composition step requires an ordered placement list")
150                    })?;
151                    Ok(Self {
152                        items: Self::read_items(
153                            Some(items),
154                            &format!("composition.steps[{index}].placements"),
155                            fallback,
156                            requirements,
157                        )?,
158                        options: ComposeOptions {
159                            expand_canvas: field(fields, "expand_canvas", Some(false))?,
160                        },
161                    })
162                })
163                .collect::<Result<Vec<_>>>()?;
164            if steps.is_empty() {
165                return Err(invalid("composition requires at least one step"));
166            }
167            Ok(steps)
168        } else if placements.is_some() || fields.contains_key("base") || configuration.is_some() {
169            if configuration.is_some() && !fields.contains_key("base") {
170                return Err(invalid(
171                    "composition options require an actual base declaration",
172                ));
173            }
174            Ok(vec![Self {
175                items: Self::read_items(placements, "placements", fallback, requirements)?,
176                options: ComposeOptions {
177                    expand_canvas: configuration.map_or(Ok(false), |fields| {
178                        field(fields, "expand_canvas", Some(false))
179                    })?,
180                },
181            }])
182        } else {
183            Ok(Vec::new())
184        }
185    }
186
187    pub(crate) fn placements(self, resolver: &mut Resolver<'_>) -> Result<Vec<Placement>> {
188        self.items
189            .into_iter()
190            .map(|item| {
191                operation::check()?;
192                item.build(resolver)
193            })
194            .collect()
195    }
196
197    pub(crate) fn check(self, resolver: &mut Resolver<'_>) -> Result<()> {
198        for item in self.placements(resolver)? {
199            item.check_recipe_science(None)?;
200        }
201        Ok(())
202    }
203}
204
205pub(crate) fn build_plan(
206    base: CompositionSource,
207    steps: Vec<StepBlueprint>,
208    resolver: &mut Resolver<'_>,
209) -> Result<CompositionPlan> {
210    let steps = steps
211        .into_iter()
212        .map(|step| {
213            let options = step.options;
214            Ok(PlanStep {
215                items: step.placements(resolver)?,
216                options,
217            })
218        })
219        .collect::<Result<Vec<_>>>()?;
220    Ok(CompositionPlan::from_parts(base, steps))
221}
222
223fn capture_placements(
224    items: &[Placement],
225    context: &mut Capture,
226    path: &str,
227    prefix: &str,
228) -> Result<Value> {
229    let values = items
230        .iter()
231        .enumerate()
232        .map(|(index, item)| {
233            operation::check()?;
234            context.owner(&format!("{prefix}placement_{index}"), |context| {
235                item.capture_recipe(context, &format!("{path}[{index}]"))
236            })
237        })
238        .collect::<Result<toml_edit::Array>>()?;
239    Ok(values.into())
240}
241
242impl CompositionPlan {
243    pub(in crate::composition) fn capture_declaration(&self) -> Result<Recipe> {
244        let mut context = Capture::new();
245        let mut fields = InlineTable::new();
246        let mut base = InlineTable::new();
247        context.owner("base", |context| {
248            capture_content(&self.base, &mut base, context, "base")
249        })?;
250        fields.insert("base", base.into());
251        if let [step] = self.steps.as_slice() {
252            fields.insert(
253                "placements",
254                capture_placements(&step.items, &mut context, "placements", "")?,
255            );
256            if step.options.expand_canvas {
257                let mut composition = InlineTable::new();
258                composition.insert("expand_canvas", true.into());
259                fields.insert("composition", composition.into());
260            }
261        } else {
262            let steps = self
263                .steps
264                .iter()
265                .enumerate()
266                .map(|(index, step)| {
267                    let mut declared = InlineTable::new();
268                    declared.insert("expand_canvas", step.options.expand_canvas.into());
269                    declared.insert(
270                        "placements",
271                        capture_placements(
272                            &step.items,
273                            &mut context,
274                            &format!("composition.steps[{index}].placements"),
275                            &format!("step_{index}_"),
276                        )?,
277                    );
278                    Ok(Value::from(declared))
279                })
280                .collect::<Result<toml_edit::Array>>()?;
281            let mut composition = InlineTable::new();
282            composition.insert("steps", steps.into());
283            fields.insert("composition", composition.into());
284        }
285        Recipe::from_capture_fields(fields, context)
286    }
287}
288
289impl Placement {
290    /// Capture this actual content and placement without preparing a base.
291    pub fn get_recipe(&self) -> Result<Recipe> {
292        self.get_recipe_with_operation(&OperationOptions::default())
293    }
294
295    /// Capture this placement under one cancellable declaration operation.
296    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
297        operation::run(options, || self.capture_declaration())
298    }
299
300    /// Write this placement and return that same independent Recipe.
301    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
302        self.recipe_with_operation(path, &OperationOptions::default())
303    }
304
305    /// Capture and atomically write the placement under one operation.
306    pub fn recipe_with_operation(
307        &self,
308        path: impl AsRef<Path>,
309        options: &OperationOptions,
310    ) -> Result<Recipe> {
311        operation::run(options, || {
312            let recipe = self.capture_declaration()?;
313            recipe.write_document(path.as_ref())?;
314            Ok(recipe)
315        })
316    }
317
318    fn capture_declaration(&self) -> Result<Recipe> {
319        let mut context = Capture::new();
320        let mut fields = InlineTable::new();
321        fields.insert(
322            "placements",
323            capture_placements(std::slice::from_ref(self), &mut context, "placements", "")?,
324        );
325        Recipe::from_capture_fields(fields, context)
326    }
327}