Skip to main content

lichtung_plot/recipe/
document.rs

1use std::path::Path;
2
3use toml_edit::{DocumentMut, InlineTable, Item, TableLike, Value};
4
5use crate::{
6    operation::{self, OperationOptions},
7    Result, Theme,
8};
9
10use crate::recipe::schema::{self as grammar, Schema};
11
12use super::{
13    address::Address,
14    capture::Capture,
15    codec::{invalid, Codec},
16    definitions, keys,
17    resolve::{Registry, Resolver},
18    section, source, BindingArguments, BindingInfo, BindingSource, BindingSourceInput, Bindings,
19    PlotRecipeScope, Recipe, RecipeFigure, RecipeWarning, RECIPE_VERSION,
20};
21
22const ROOT_FIELDS: &[grammar::Field] = &[
23    grammar::custom("recipe_version", true, |_| grammar::literal(RECIPE_VERSION)),
24    grammar::optional::<Theme>("theme"),
25    grammar::custom("plot", false, |ctx| {
26        grammar::one_of([
27            crate::builder::recipe::schema(ctx),
28            crate::builder::recipe::style::schema(ctx, true),
29        ])
30    }),
31    grammar::custom("canvas", false, |ctx| {
32        grammar::one_of([
33            crate::canvas::recipe::schema(ctx),
34            crate::canvas::style::schema(ctx, true),
35        ])
36    }),
37    grammar::custom("bindings", false, binding_schema),
38    grammar::custom(
39        "definitions",
40        false,
41        |ctx| serde_json::json!({"type":"object","propertyNames":{"minLength":1},"additionalProperties":crate::composition::recipe::definition_schema(ctx)}),
42    ),
43    grammar::custom("base", false, crate::composition::recipe::base_schema),
44    grammar::custom("placements", false, |ctx| {
45        grammar::array(crate::composition::recipe::placement_schema(ctx))
46    }),
47    grammar::custom(
48        "composition",
49        false,
50        crate::composition::recipe::plan_schema,
51    ),
52    grammar::custom("output", false, super::run::schema),
53];
54
55fn binding_schema(ctx: &mut Schema) -> serde_json::Value {
56    let named = grammar::one_of([grammar::object([], &[]), ctx.reference::<BindingSource>()]);
57    grammar::one_of([
58        source::file_source_schema(ctx),
59        serde_json::json!({"type":"object","propertyNames":{"minLength":1},"additionalProperties":named}),
60    ])
61}
62
63pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
64    let root = grammar::record(ctx, ROOT_FIELDS);
65    grammar::with(
66        root,
67        serde_json::json!({
68            "allOf":[
69                {"oneOf":[
70                    {"required":["plot"]},
71                    {"required":["canvas"]},
72                    {"allOf":[
73                        {"not":{"anyOf":[{"required":["plot"]},{"required":["canvas"]}]}},
74                        {"anyOf":[{"required":["theme"]},{"required":["base"]},{"required":["placements"]}]}
75                    ]}
76                ]},
77                {"dependentRequired":{"composition":["base"]}},
78                {"if":{"required":["composition"],"properties":{"composition":{"required":["steps"]}}},"then":{"not":{"required":["placements"]}}},
79                {"if":{"required":["base"],"properties":{"base":{"required":["native"],"properties":{"native":{"const":true}}}}},
80                 "then":{"anyOf":[
81                    {"required":["plot"],"properties":{"plot":{"properties":{"scope":{"not":{"const":"style"}}}}}},
82                    {"required":["canvas"],"properties":{"canvas":{"properties":{"scope":{"not":{"const":"style"}}}}}}
83                 ]}}
84            ]
85        }),
86    )
87}
88
89impl Recipe {
90    /// Ordered logical sources and their actual input requirements.
91    pub fn bindings(&self) -> &[BindingInfo] {
92        &self.bindings
93    }
94
95    /// Current unresolved original selections without reading any data.
96    pub fn warnings(&self) -> &[RecipeWarning] {
97        &self.warnings
98    }
99
100    /// Restore the native figure from the declared default sources.
101    pub fn build(&self) -> Result<RecipeFigure> {
102        self.build_with(&Bindings::new())
103    }
104
105    /// Restore from homogeneous inputs or a heterogeneous registry.
106    pub fn build_with<M>(&self, bindings: impl BindingArguments<M>) -> Result<RecipeFigure> {
107        self.build_with_operation(bindings, &OperationOptions::default())
108    }
109
110    /// Restore from the chosen inputs under a cancellable operation.
111    pub fn build_with_operation<M>(
112        &self,
113        bindings: impl BindingArguments<M>,
114        options: &OperationOptions,
115    ) -> Result<RecipeFigure> {
116        operation::run(options, || {
117            bindings.with_bindings(|bindings| self.build_inner(bindings))
118        })
119    }
120
121    pub(crate) fn build_inner(&self, bindings: &Bindings<'_>) -> Result<RecipeFigure> {
122        if self.has_style_root() {
123            return Err(invalid(
124                "a style recipe must be applied to an existing figure",
125            ));
126        }
127        let registry = Registry::read(self.document.get("bindings"))?;
128        let document = self.expanded_document(&registry)?;
129        let fields = document.as_table();
130        registry.validate_in_memory(bindings)?;
131        let mut requirements = Vec::new();
132        if let Some(figure) =
133            FigureBlueprint::read(fields, registry.default.as_deref(), &mut requirements)?
134        {
135            let mut resolver = Resolver::new(&registry, bindings, &self.base)?;
136            resolver.reserve_tokens(&requirements)?;
137            return figure.build(&mut resolver);
138        }
139        if self.is_composition_document() {
140            return Err(invalid(
141                "an independent composition requires build_document()",
142            ));
143        }
144        if fields.get("theme").is_none() && fields.contains_key("placements") {
145            return Err(invalid("a placement-only recipe requires placements()"));
146        }
147        self.theme().map(Box::new).map(RecipeFigure::Theme)
148    }
149
150    /// Check the declaration and its actual required input values.
151    pub fn check(&self) -> Result<()> {
152        self.check_with(&Bindings::new())
153    }
154
155    /// Check using explicit in-memory replacements.
156    pub fn check_with<M>(&self, bindings: impl BindingArguments<M>) -> Result<()> {
157        self.check_with_operation(bindings, &OperationOptions::default())
158    }
159
160    /// Validate actual adopted inputs and font-independent scientific preparation.
161    pub fn check_with_operation<M>(
162        &self,
163        bindings: impl BindingArguments<M>,
164        options: &OperationOptions,
165    ) -> Result<()> {
166        operation::run(options, || {
167            self.check_warnings()?;
168            bindings.with_bindings(|bindings| super::composition::check_document(self, bindings))
169        })
170    }
171
172    pub(crate) fn check_warnings(&self) -> Result<()> {
173        if let Some(warning) = self.warnings.first() {
174            return Err(invalid(format!(
175                "{} (binding {:?}): {}",
176                warning.field, warning.binding, warning.reason
177            )));
178        }
179        Ok(())
180    }
181
182    /// Declare an independent logical binding with an optional default.
183    pub fn add_binding(&mut self, name: &str, source: impl BindingSourceInput) -> Result<()> {
184        self.edit_source(name, source.into_source(), true)
185    }
186
187    /// Replace the entire default without reading it.
188    pub fn set_binding_source(
189        &mut self,
190        name: &str,
191        source: impl BindingSourceInput,
192    ) -> Result<()> {
193        self.edit_source(name, source.into_source(), false)
194    }
195
196    fn edit_source(
197        &mut self,
198        name: &str,
199        mut source: Option<BindingSource>,
200        add: bool,
201    ) -> Result<()> {
202        if let Some(source) = &mut source {
203            source.validate()?;
204            source.rebase(&std::env::current_dir()?);
205        }
206        let mut registry = Registry::read(self.document.get("bindings"))?;
207        if let Some((_, current)) = registry.entries.iter_mut().find(|(key, _)| key == name) {
208            if add {
209                return Err(invalid(format!("binding {name:?} already exists")));
210            }
211            *current = source;
212        } else if add {
213            registry.entries.push((name.to_owned(), source));
214        } else {
215            return Err(invalid(format!("undeclared binding {name:?}")));
216        }
217        let mut document = self.explicit_document()?;
218        document["bindings"] = Item::Table(registry.encode());
219        self.install(document)
220    }
221
222    /// Change one binding name and all of its actual references.
223    pub fn rename_binding(&mut self, old: &str, new: &str) -> Result<()> {
224        let mut registry = Registry::read(self.document.get("bindings"))?;
225        registry.get(old)?;
226        if old == new {
227            return Ok(());
228        }
229        if new.is_empty() || registry.entries.iter().any(|(key, _)| key == new) {
230            return Err(invalid("invalid or occupied new binding name"));
231        }
232        let mut document = self.explicit_document()?;
233        for (name, source) in &mut registry.entries {
234            if name == old {
235                new.clone_into(name);
236            }
237            if let Some(BindingSource {
238                source: source::Source::Reference { name, .. },
239                ..
240            }) = source
241            {
242                if name == old {
243                    new.clone_into(name);
244                }
245            }
246        }
247        for binding in &self.bindings {
248            for requirement in &binding.requirements {
249                if requirement.is_direct() && requirement.reference.binding == old {
250                    let mut reference = requirement.reference.clone();
251                    new.clone_into(&mut reference.binding);
252                    let address = Address::parse(&requirement.role)?;
253                    if address.enclosing_use(self.document.as_item())?.is_none() {
254                        address.set_reference(document.as_item_mut(), reference.encode())?;
255                    }
256                }
257            }
258        }
259        definitions::rename_mappings(&mut document, old, new)?;
260        document["bindings"] = Item::Table(registry.encode());
261        self.install(document)
262    }
263
264    /// Replace one role's selection, keeping its source and other settings.
265    pub fn set_selector(
266        &mut self,
267        role: &str,
268        selector: impl Into<crate::data::BindingSelector>,
269    ) -> Result<()> {
270        let requirement = self
271            .bindings
272            .iter()
273            .flat_map(|binding| &binding.requirements)
274            .find(|requirement| requirement.is_direct() && requirement.role == role)
275            .ok_or_else(|| invalid(format!("unknown data role {role:?}")))?;
276        let mut reference = requirement.reference.clone();
277        reference.selector = selector.into();
278        let mut document = self.explicit_document()?;
279        let address = Address::parse(role)?;
280        if let Some(owner) = address.enclosing_use(self.document.as_item())? {
281            let registry = Registry::read(self.document.get("bindings"))?;
282            let expanded = self.expanded_document(&registry)?;
283            let detached = owner.item(expanded.as_item())?.clone();
284            *owner.item_mut(document.as_item_mut())? = detached;
285        }
286        address.set_reference(document.as_item_mut(), reference.encode())?;
287        self.install(document)
288    }
289
290    fn explicit_document(&self) -> Result<DocumentMut> {
291        let mut document = self.document.clone();
292        for binding in &self.bindings {
293            for requirement in &binding.requirements {
294                if !requirement.is_direct() {
295                    continue;
296                }
297                let address = Address::parse(&requirement.role)?;
298                if address.enclosing_use(self.document.as_item())?.is_none() {
299                    address
300                        .set_reference(document.as_item_mut(), requirement.reference.encode())?;
301                }
302            }
303        }
304        let registry = Registry::read(document.get("bindings"))?;
305        if document.get("bindings").is_some() {
306            document["bindings"] = Item::Table(registry.encode());
307        }
308        Ok(document)
309    }
310
311    pub(super) fn document_for_path(&self, path: &Path) -> Result<DocumentMut> {
312        let mut document = self.document.clone();
313        let destination = std::path::absolute(path)?;
314        let new_base = destination
315            .parent()
316            .ok_or_else(|| invalid("recipe path has no directory"))?;
317        if new_base != self.base {
318            if let Some(bindings) = document.get("bindings") {
319                let mut registry = Registry::read(Some(bindings))?;
320                for (_, source) in &mut registry.entries {
321                    if let Some(source) = source {
322                        source.rebase(&self.base);
323                    }
324                }
325                document = self.explicit_document()?;
326                document["bindings"] = Item::Table(registry.encode());
327            }
328            rebase_document_assets(&mut document, &self.base)?;
329        }
330        Ok(document)
331    }
332
333    pub(super) fn install(&mut self, document: DocumentMut) -> Result<()> {
334        let (bindings, warnings) = Self::inventory(&document)?;
335        self.document = document;
336        self.bindings = bindings;
337        self.warnings = warnings;
338        Ok(())
339    }
340
341    pub(super) fn inventory(
342        document: &DocumentMut,
343    ) -> Result<(Vec<BindingInfo>, Vec<RecipeWarning>)> {
344        let root = document.as_item();
345        let fields = grammar::record_fields(root, ROOT_FIELDS)?;
346        let version = fields
347            .get("recipe_version")
348            .and_then(Item::as_str)
349            .ok_or_else(|| invalid("missing recipe_version"))?;
350        if version != RECIPE_VERSION {
351            return Err(invalid(format!(
352                "recipe_version must be {RECIPE_VERSION:?}, got {version:?}"
353            )));
354        }
355        if let Some(theme) = fields.get("theme") {
356            Theme::decode(theme, None).map_err(|error| error.with_prefix("theme"))?;
357        }
358        if fields.contains_key("plot") && fields.contains_key("canvas") {
359            return Err(invalid(
360                "recipe cannot contain both a Plot and a Canvas root",
361            ));
362        }
363        super::run::validate_output(fields.get("output"))?;
364        let registry = Registry::read(fields.get("bindings"))?;
365        let expanded = definitions::expand(document, &registry)?;
366        let mut requirements = expanded.requirements;
367        requirements.extend(figure_requirements(
368            expanded.document.as_table(),
369            &registry,
370        )?);
371        let document = expanded.document.as_ref();
372        let mut bindings: Vec<_> = registry
373            .entries
374            .into_iter()
375            .map(|(name, source)| BindingInfo {
376                name,
377                source,
378                requirements: Vec::new(),
379            })
380            .collect();
381        let mut warnings = Vec::new();
382        for binding in &bindings {
383            if let Some(source) = &binding.source {
384                if source
385                    .reference()
386                    .is_some_and(|(_, selector)| keys::selector_pending(selector))
387                {
388                    warnings.push(RecipeWarning::new(
389                        &format!("bindings.{}", binding.name()),
390                        binding.name(),
391                        "original key is still required",
392                    ));
393                }
394            }
395        }
396        for requirement in requirements {
397            for name in Address::parse(&requirement.role)?.group_bindings(document.as_item())? {
398                if !bindings.iter().any(|binding| binding.name == name) {
399                    return Err(invalid(format!(
400                        "{}: undeclared binding {name:?}",
401                        requirement.role
402                    )));
403                }
404            }
405            let binding = bindings
406                .iter_mut()
407                .find(|binding| binding.name == requirement.reference.binding)
408                .ok_or_else(|| {
409                    invalid(format!(
410                        "{}: undeclared binding {:?}",
411                        requirement.role, requirement.reference.binding
412                    ))
413                })?;
414            if keys::selector_pending(&requirement.reference.selector) {
415                warnings.push(RecipeWarning::new(
416                    &requirement.role,
417                    &binding.name,
418                    "original key is still required",
419                ));
420            }
421            binding.requirements.push(requirement);
422        }
423        add_indirect_requirements(&mut bindings)?;
424        Ok((bindings, warnings))
425    }
426
427    pub(crate) fn from_plot(
428        description: &crate::builder::PlotDescription,
429        scope: PlotRecipeScope,
430    ) -> Result<Self> {
431        let mut context = Capture::new();
432        let plot = match scope {
433            PlotRecipeScope::Full => description.capture_recipe(&mut context, "plot")?,
434            PlotRecipeScope::Style => description.capture_style(true)?,
435        };
436        Self::from_capture("plot", plot, context)
437    }
438
439    pub(crate) fn from_capture(root: &str, value: Value, context: Capture) -> Result<Self> {
440        let mut fields = InlineTable::new();
441        fields.insert(root, value);
442        Self::from_capture_fields(fields, context)
443    }
444
445    pub(crate) fn from_capture_fields(fields: InlineTable, mut context: Capture) -> Result<Self> {
446        let mut document = DocumentMut::new();
447        document["recipe_version"] = toml_edit::value(RECIPE_VERSION);
448        let declarations = context.bindings();
449        if !declarations.is_empty() {
450            document["bindings"] = Item::Table(declarations);
451        }
452        for (name, value) in fields {
453            let item = match value {
454                Value::InlineTable(value) => Item::Table(section(value)),
455                value => Item::Value(value),
456            };
457            document[&name] = item;
458        }
459        let (bindings, _) = Self::inventory(&document)?;
460        let names = context.final_names();
461        if names.iter().any(|(old, new)| old != new) {
462            let lookup: std::collections::HashMap<_, _> = names
463                .iter()
464                .map(|(old, new)| (old.as_str(), new.as_str()))
465                .collect();
466            for binding in &bindings {
467                let name = lookup[binding.name()];
468                for requirement in binding
469                    .requirements
470                    .iter()
471                    .filter(|requirement| requirement.is_direct())
472                {
473                    if name != binding.name() {
474                        let mut reference = requirement.reference.clone();
475                        name.clone_into(&mut reference.binding);
476                        Address::parse(&requirement.role)?
477                            .set_reference(document.as_item_mut(), reference.encode())?;
478                    }
479                }
480            }
481            let mut fields = toml_edit::Table::new();
482            for (_, name) in &names {
483                fields.insert(name, Item::Table(toml_edit::Table::new()));
484            }
485            document["bindings"] = Item::Table(fields);
486            for warning in &mut context.warnings {
487                warning.binding = lookup[warning.binding.as_str()].to_owned();
488            }
489        }
490        let (bindings, _) = Self::inventory(&document)?;
491        Ok(Self {
492            document,
493            base: std::env::current_dir()?,
494            bindings,
495            warnings: context.warnings,
496        })
497    }
498}
499
500pub(super) fn native_root(fields: &dyn TableLike) -> bool {
501    ["plot", "canvas"]
502        .iter()
503        .filter_map(|name| fields.get(name))
504        .any(|item| !super::style::is_style(item))
505}
506
507pub(super) enum FigureBlueprint {
508    Plot(crate::builder::recipe::Blueprint),
509    Canvas(Box<crate::canvas::recipe::Blueprint>),
510}
511impl FigureBlueprint {
512    pub(super) fn read(
513        fields: &dyn TableLike,
514        fallback: Option<&str>,
515        requirements: &mut Vec<super::BindingRequirement>,
516    ) -> Result<Option<Self>> {
517        if let Some(plot) = fields
518            .get("plot")
519            .filter(|item| !super::style::is_style(item))
520        {
521            return crate::builder::recipe::Blueprint::read(plot, "plot", fallback, requirements)
522                .map(Self::Plot)
523                .map(Some);
524        }
525        if let Some(canvas) = fields
526            .get("canvas")
527            .filter(|item| !super::style::is_style(item))
528        {
529            return crate::canvas::recipe::Blueprint::read(
530                canvas,
531                "canvas",
532                fallback,
533                requirements,
534            )
535            .map(Box::new)
536            .map(Self::Canvas)
537            .map(Some);
538        }
539        Ok(None)
540    }
541    pub(super) fn build(self, resolver: &mut Resolver<'_>) -> Result<RecipeFigure> {
542        match self {
543            Self::Plot(plot) => plot.build(resolver),
544            Self::Canvas(canvas) => canvas.build(resolver).map(RecipeFigure::Canvas),
545        }
546    }
547}
548
549fn figure_requirements(
550    fields: &dyn TableLike,
551    registry: &Registry,
552) -> Result<Vec<super::declaration::BindingRequirement>> {
553    use crate::composition::recipe::{BaseBlueprint, StepBlueprint};
554    let mut requirements = Vec::new();
555    if let Some(plot) = fields
556        .get("plot")
557        .filter(|item| super::style::is_style(item))
558    {
559        crate::builder::recipe::style::PlotStyle::read(plot, "plot", true)?;
560    }
561    if let Some(canvas) = fields
562        .get("canvas")
563        .filter(|item| super::style::is_style(item))
564    {
565        crate::canvas::style::CanvasStyle::read(canvas, "canvas", true)?;
566    }
567    let fallback = registry.default.as_deref();
568    FigureBlueprint::read(fields, fallback, &mut requirements)?;
569    let base = BaseBlueprint::read(fields, native_root(fields), fallback, &mut requirements)?;
570    let steps = StepBlueprint::read(fields, fallback, &mut requirements)?;
571    if base.is_none()
572        && steps.is_empty()
573        && !["plot", "canvas", "theme"]
574            .iter()
575            .any(|name| fields.contains_key(name))
576    {
577        return Err(invalid(
578            "recipe requires a native figure, independent theme, composition or placement list",
579        ));
580    }
581    Ok(requirements)
582}
583
584fn array_count(item: &Item) -> Result<usize> {
585    item.as_array()
586        .map(toml_edit::Array::len)
587        .or_else(|| item.as_array_of_tables().map(toml_edit::ArrayOfTables::len))
588        .ok_or_else(|| invalid("expected an ordered declaration list"))
589}
590
591fn rebase_content_assets(item: &mut Item, base: &Path) -> Result<()> {
592    let fields = item
593        .as_table_like_mut()
594        .ok_or_else(|| invalid("expected a content declaration"))?;
595    if let Some(asset) = fields.get_mut("asset") {
596        if let Some(path) = asset.as_str() {
597            let path = super::source::rebase(Path::new(path), base);
598            *asset = toml_edit::value(
599                path.to_str()
600                    .ok_or_else(|| invalid("asset path requires Unicode"))?,
601            );
602        }
603    }
604    if let Some(canvas) = fields.get_mut("canvas") {
605        rebase_canvas_assets(canvas, base)?;
606    }
607    Ok(())
608}
609
610fn rebase_placement_assets(items: &mut Item, base: &Path) -> Result<()> {
611    for index in 0..array_count(items)? {
612        let item = items
613            .get_mut(index)
614            .ok_or_else(|| invalid("invalid ordered content declaration"))?;
615        rebase_content_assets(item, base)?;
616    }
617    Ok(())
618}
619
620fn rebase_canvas_assets(item: &mut Item, base: &Path) -> Result<()> {
621    if let Some(panels) = item
622        .as_table_like_mut()
623        .and_then(|fields| fields.get_mut("panels"))
624    {
625        rebase_placement_assets(panels, base)?;
626    }
627    Ok(())
628}
629
630fn rebase_document_assets(document: &mut DocumentMut, base: &Path) -> Result<()> {
631    if let Some(output) = document.get_mut("output") {
632        super::run::rebase_output(output, base)?;
633    }
634    if let Some(library) = document
635        .get_mut("definitions")
636        .and_then(Item::as_table_like_mut)
637    {
638        for (_, definition) in library.iter_mut() {
639            rebase_content_assets(definition, base)?;
640        }
641    }
642    if let Some(canvas) = document.get_mut("canvas") {
643        rebase_canvas_assets(canvas, base)?;
644    }
645    if let Some(source) = document.get_mut("base") {
646        rebase_content_assets(source, base)?;
647    }
648    if let Some(placements) = document.get_mut("placements") {
649        rebase_placement_assets(placements, base)?;
650    }
651    if let Some(steps) = document
652        .get_mut("composition")
653        .and_then(Item::as_table_like_mut)
654        .and_then(|fields| fields.get_mut("steps"))
655    {
656        for index in 0..array_count(steps)? {
657            let step = steps
658                .get_mut(index)
659                .and_then(Item::as_table_like_mut)
660                .ok_or_else(|| invalid("invalid composition step"))?;
661            if let Some(placements) = step.get_mut("placements") {
662                rebase_placement_assets(placements, base)?;
663            }
664        }
665    }
666    Ok(())
667}
668
669fn add_indirect_requirements(bindings: &mut [BindingInfo]) -> Result<()> {
670    let direct = bindings
671        .iter()
672        .flat_map(|binding| &binding.requirements)
673        .cloned()
674        .collect::<Vec<_>>();
675    for mut requirement in direct {
676        let mut name = requirement.reference.binding.clone();
677        loop {
678            crate::operation::check()?;
679            let Some((parent, selector)) = bindings
680                .iter()
681                .find(|binding| binding.name == name)
682                .and_then(|binding| binding.source.as_ref())
683                .and_then(BindingSource::reference)
684                .map(|(name, selector)| (name.to_owned(), selector.clone()))
685            else {
686                break;
687            };
688            requirement.upstream.insert(0, (parent.clone(), selector));
689            bindings
690                .iter_mut()
691                .find(|binding| binding.name == parent)
692                .expect("validated default reference")
693                .requirements
694                .push(requirement.clone());
695            name = parent;
696        }
697    }
698    Ok(())
699}
700
701impl<K: crate::kind::Marker> crate::Plot<K> {
702    /// Extract the native declaration and original binding requirements.
703    pub fn get_recipe(&self) -> Result<Recipe> {
704        self.get_recipe_with_operation(&OperationOptions::default())
705    }
706
707    /// Extract the declaration under one cancellable operation.
708    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
709        self.get_recipe_with_scope_and_operation(PlotRecipeScope::Full, options)
710    }
711
712    /// Capture the requested full or visual declaration.
713    pub fn get_recipe_with_scope(&self, scope: PlotRecipeScope) -> Result<Recipe> {
714        self.get_recipe_with_scope_and_operation(scope, &OperationOptions::default())
715    }
716
717    /// Capture a selected declaration under one cancellable operation.
718    pub fn get_recipe_with_scope_and_operation(
719        &self,
720        scope: PlotRecipeScope,
721        options: &OperationOptions,
722    ) -> Result<Recipe> {
723        operation::run(options, || Recipe::from_plot(self.description(), scope))
724    }
725
726    /// Write the declaration and return that same independent Recipe.
727    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
728        self.recipe_with_operation(path, &OperationOptions::default())
729    }
730
731    /// Extract and write the declaration under one operation.
732    pub fn recipe_with_operation(
733        &self,
734        path: impl AsRef<Path>,
735        options: &OperationOptions,
736    ) -> Result<Recipe> {
737        self.recipe_with_scope_and_operation(path, PlotRecipeScope::Full, options)
738    }
739
740    /// Write the chosen declaration and return that same independent Recipe.
741    pub fn recipe_with_scope(
742        &self,
743        path: impl AsRef<Path>,
744        scope: PlotRecipeScope,
745    ) -> Result<Recipe> {
746        self.recipe_with_scope_and_operation(path, scope, &OperationOptions::default())
747    }
748
749    /// Extract and atomically write a selected declaration under one operation.
750    pub fn recipe_with_scope_and_operation(
751        &self,
752        path: impl AsRef<Path>,
753        scope: PlotRecipeScope,
754        options: &OperationOptions,
755    ) -> Result<Recipe> {
756        operation::run(options, || {
757            let recipe = Recipe::from_plot(self.description(), scope)?;
758            recipe.write_document(path.as_ref())?;
759            Ok(recipe)
760        })
761    }
762}