Skip to main content

lichtung_plot/
recipe.rs

1//! Portable native declarations stored in versioned TOML documents.
2//! Reading and extracting declarations never prepares a rendered scene.
3
4mod address;
5mod bindings;
6pub(crate) mod capture;
7pub(crate) mod codec;
8pub(crate) mod collection;
9mod composition;
10pub(crate) mod declaration;
11mod definitions;
12mod document;
13pub(crate) mod figure;
14mod keys;
15pub(crate) mod plot_input;
16mod readers;
17pub(crate) mod resolve;
18mod run;
19pub(crate) mod schema;
20mod source;
21pub(crate) mod style;
22mod template;
23mod text;
24pub(crate) mod theme;
25
26use std::path::{Path, PathBuf};
27
28pub use crate::data::BindingSelector;
29pub use bindings::{
30    BindingArguments, BindingColumnType, BindingField, BindingInput, BindingObject, Bindings,
31};
32pub use composition::RecipeDocument;
33pub use declaration::{BindingRequirement, BindingValueType};
34pub use figure::RecipeFigure;
35pub use run::{OutputDeclaration, RunAction, RunOptions, RunResult};
36pub use source::{BindingSource, BindingSourceInput};
37pub use style::StyleSource;
38
39use toml_edit::{DocumentMut, InlineTable, Item, Table, Value};
40
41use crate::{
42    operation::{self, OperationOptions},
43    Result, Theme,
44};
45
46use codec::{invalid, Codec};
47
48/// Initial stable recipe grammar version. Compatible declaration additions
49/// do not depend on the package's patch version.
50pub const RECIPE_VERSION: &str = "0.3.0";
51
52/// The authored range of a Plot recipe.
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54pub enum PlotRecipeScope {
55    /// Complete editable native declaration.
56    #[default]
57    Full,
58    /// The complete effective visual requests for a compatible target.
59    Style,
60}
61
62/// The authored range of a Canvas recipe.
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
64pub enum CanvasRecipeScope {
65    /// Complete editable content and composition.
66    #[default]
67    Full,
68    /// The effective root appearance and actual child visual requests.
69    Style,
70    /// The actual fillable grid and independent reservations.
71    Layout,
72}
73
74/// One independent, validated native declaration document.
75///
76/// A Recipe retains the authored TOML rather than a rendered image. Reading
77/// and writing it never looks up fonts or prepares scientific layout.
78#[derive(Debug, Clone)]
79pub struct Recipe {
80    document: DocumentMut,
81    base: PathBuf,
82    bindings: Vec<BindingInfo>,
83    warnings: Vec<RecipeWarning>,
84}
85
86/// One logical source and the actual declarations consuming it.
87#[derive(Debug, Clone)]
88pub struct BindingInfo {
89    name: String,
90    source: Option<BindingSource>,
91    requirements: Vec<BindingRequirement>,
92}
93impl BindingInfo {
94    /// Logical binding name.
95    pub fn name(&self) -> &str {
96        &self.name
97    }
98    /// Authored default source, if any.
99    pub fn source(&self) -> Option<&BindingSource> {
100        self.source.as_ref()
101    }
102    /// Actual role requirements across the document.
103    pub fn requirements(&self) -> &[BindingRequirement] {
104        &self.requirements
105    }
106}
107
108/// A recoverable unresolved original key in a declaration.
109#[derive(Debug, Clone)]
110pub struct RecipeWarning {
111    field: String,
112    binding: String,
113    reason: String,
114}
115impl RecipeWarning {
116    pub(crate) fn new(field: &str, binding: &str, reason: &str) -> Self {
117        Self {
118            field: field.to_owned(),
119            binding: binding.to_owned(),
120            reason: reason.to_owned(),
121        }
122    }
123    /// Actual authored field.
124    pub fn field(&self) -> &str {
125        &self.field
126    }
127    /// Logical binding consuming the original key.
128    pub fn binding(&self) -> &str {
129        &self.binding
130    }
131    /// Reason the key is still required.
132    pub fn reason(&self) -> &str {
133        &self.reason
134    }
135}
136
137impl Recipe {
138    fn from_theme(theme: &Theme) -> Self {
139        let mut document = DocumentMut::new();
140        document["recipe_version"] = toml_edit::value(RECIPE_VERSION);
141        let toml_edit::Value::InlineTable(value) = theme.encode() else {
142            unreachable!("complete theme table")
143        };
144        document["theme"] = Item::Table(section(value));
145        Self {
146            document,
147            base: PathBuf::new(),
148            bindings: Vec::new(),
149            warnings: Vec::new(),
150        }
151    }
152
153    /// Read a versioned recipe from a real local TOML file.
154    pub fn read(path: impl AsRef<Path>) -> Result<Self> {
155        Self::read_with_operation(path, &OperationOptions::default())
156    }
157
158    /// Read and validate declarations under one cancellable operation.
159    pub fn read_with_operation(path: impl AsRef<Path>, options: &OperationOptions) -> Result<Self> {
160        operation::run(options, || Self::read_document(path.as_ref()))
161    }
162
163    pub(crate) fn read_document(path: &Path) -> Result<Self> {
164        let source = operation::external(|| std::fs::read_to_string(path))?;
165        operation::checkpoint()?;
166        let document = source
167            .parse::<DocumentMut>()
168            .map_err(|error| invalid(format!("recipe {}: {error}", path.display())))?;
169        let (bindings, warnings) = Self::inventory(&document)
170            .map_err(|error| error.with_prefix(&format!("recipe {}", path.display())))?;
171        let absolute = std::path::absolute(path)?;
172        let base = absolute
173            .parent()
174            .ok_or_else(|| invalid("recipe path has no directory"))?
175            .to_owned();
176        Ok(Self {
177            document,
178            base,
179            bindings,
180            warnings,
181        })
182    }
183
184    /// Restore the independent Theme declaration. No construction context
185    /// or installed font can change the result.
186    pub fn theme(&self) -> Result<Theme> {
187        let value = self
188            .document
189            .get("theme")
190            .ok_or_else(|| invalid("recipe has no independent theme"))?;
191        Theme::decode(value, None).map_err(|error| error.with_prefix("theme"))
192    }
193
194    /// Write this declaration to the supplied local TOML path atomically.
195    pub fn write(&self, path: impl AsRef<Path>) -> Result<()> {
196        self.write_with_operation(path, &OperationOptions::default())
197    }
198
199    /// Write a complete recipe under one cancellable operation.
200    pub fn write_with_operation(
201        &self,
202        path: impl AsRef<Path>,
203        options: &OperationOptions,
204    ) -> Result<()> {
205        operation::run(options, || self.write_document(path.as_ref()))
206    }
207
208    pub(crate) fn write_document(&self, path: &Path) -> Result<()> {
209        let document = self.document_for_path(path)?;
210        let source = document.to_string();
211        operation::checkpoint()?;
212        crate::orchestrator::write_atomic(path, source.as_bytes())
213    }
214}
215
216// Keep scalar compound values inline while giving the author's complete
217// role groups their own ordinary TOML sections.
218fn section(value: InlineTable) -> Table {
219    let mut table = Table::new();
220    for (key, value) in value {
221        let item = match value {
222            Value::InlineTable(value) if !atomic_table(&value) => Item::Table(section(value)),
223            value => Item::Value(value),
224        };
225        table.insert(&key, item);
226    }
227    table
228}
229
230fn atomic_table(value: &InlineTable) -> bool {
231    value.contains_key("rgb")
232        || value.contains_key("numerator")
233        || ["em", "px", "short_side"]
234            .iter()
235            .any(|name| value.contains_key(name))
236}
237
238impl Theme {
239    /// Capture this complete immutable Theme as a portable native declaration.
240    pub fn get_recipe(&self) -> Result<Recipe> {
241        self.get_recipe_with_operation(&OperationOptions::default())
242    }
243
244    /// Capture the Theme under one declaration operation.
245    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
246        operation::run(options, || {
247            let recipe = Recipe::from_theme(self);
248            operation::checkpoint()?;
249            Ok(recipe)
250        })
251    }
252
253    /// Write a Theme recipe to a local file and return that same declaration.
254    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
255        self.recipe_with_operation(path, &OperationOptions::default())
256    }
257
258    /// Capture and write this Theme under one operation.
259    pub fn recipe_with_operation(
260        &self,
261        path: impl AsRef<Path>,
262        options: &OperationOptions,
263    ) -> Result<Recipe> {
264        operation::run(options, || {
265            let recipe = Recipe::from_theme(self);
266            recipe.write_document(path.as_ref())?;
267            Ok(recipe)
268        })
269    }
270}