Skip to main content

lichtung_plot/recipe/
figure.rs

1use std::path::Path;
2
3use crate::{
4    kind,
5    operation::OperationOptions,
6    output::{Format, PngOptions},
7    plots::PlotKind,
8    Error, Plot, Result, Theme,
9};
10
11macro_rules! families {
12    ($($family:ident => $name:literal),+ $(,)?) => {
13        pub(crate) const FAMILIES: &[(PlotKind,&str)] = &[$((PlotKind::$family,$name),)+];
14        /// A rebuilt, editable native figure retains its exact family.
15        #[derive(Clone)]
16        #[non_exhaustive]
17        #[expect(clippy::large_enum_variant,reason="the exact native Canvas branch owns its editable value directly")]
18        pub enum RecipeFigure {
19            $(#[doc=concat!("A native ",$name," plot.")] $family(Plot<kind::$family>),)+
20            /// A rebuilt editable Canvas grid.
21            Canvas(crate::Canvas),
22            /// An independent complete theme declaration.
23            Theme(Box<Theme>),
24        }
25
26        impl RecipeFigure {
27            pub(crate) fn from_description(description:crate::builder::PlotDescription) -> Self {
28                match description.kind() {
29                    $(PlotKind::$family=>Self::$family(Plot::from_recipe_description(description)),)+
30                }
31            }
32
33            /// Inspect the actual plot family, if this declaration is a plot.
34            pub const fn kind(&self)->Option<PlotKind> {
35                match self {
36                    $(Self::$family(_)=>Some(PlotKind::$family),)+
37                    Self::Canvas(_)|Self::Theme(_)=>None,
38                }
39            }
40
41            pub(crate) fn check_science(&self)->Result<()> {
42                match self {
43                    $(Self::$family(plot)=>check_plot(plot.description()),)+
44                    Self::Canvas(canvas)=>canvas.check_recipe_science(),
45                    Self::Theme(_)=>Ok(()),
46                }
47            }
48
49            /// Validate the complete rebuilt figure.
50            pub fn preflight(&self)->Result<()> {
51                self.preflight_with_operation(&OperationOptions::default())
52            }
53
54            /// Perform this operation using the caller's cancellation options.
55            pub fn preflight_with_operation(&self,options:&OperationOptions)->Result<()> {
56                match self {
57                    $(Self::$family(plot)=>plot.preflight_with_operation(options),)+
58                    Self::Canvas(canvas)=>canvas.preflight_with_operation(options),
59                    Self::Theme(_)=>Ok(()),
60                }
61            }
62
63            /// Read the accepted native layout.
64            pub fn layout_report(&self)->Result<crate::layout::LayoutReport> {
65                self.layout_report_with_operation(&OperationOptions::default())
66            }
67
68            /// Perform this operation using the caller's cancellation options.
69            pub fn layout_report_with_operation(&self,options:&OperationOptions)->Result<crate::layout::LayoutReport> {
70                match self {
71                    $(Self::$family(plot)=>plot.layout_report_with_operation(options),)+
72                    Self::Canvas(canvas)=>canvas.layout_report_with_operation(options),
73                    Self::Theme(_)=>Err(no_figure()),
74                }
75            }
76
77            /// Freeze the figure with its same-operation scientific results.
78            pub fn render_with_results(&self)->Result<crate::stats::RenderWithResults> {
79                self.render_with_results_with_operation(&OperationOptions::default())
80            }
81
82            /// Perform this operation using the caller's cancellation options.
83            pub fn render_with_results_with_operation(&self,options:&OperationOptions)->Result<crate::stats::RenderWithResults> {
84                match self {
85                    $(Self::$family(plot)=>plot.render_with_results_with_operation(options),)+
86                    Self::Canvas(canvas)=>canvas.render_with_results_with_operation(options),
87                    Self::Theme(_)=>Err(no_figure()),
88                }
89            }
90
91            /// Extract the current editable declaration.
92            pub fn get_recipe(&self)->Result<super::Recipe> {
93                self.get_recipe_with_operation(&OperationOptions::default())
94            }
95
96            /// Perform this operation using the caller's cancellation options.
97            pub fn get_recipe_with_operation(&self,options:&OperationOptions)->Result<super::Recipe> {
98                match self {
99                    $(Self::$family(plot)=>plot.get_recipe_with_operation(options),)+
100                    Self::Canvas(canvas)=>canvas.get_recipe_with_operation(options),
101                    Self::Theme(theme)=>theme.get_recipe_with_operation(options),
102                }
103            }
104
105            /// Freeze the rebuilt figure in a native Output.
106            pub fn render(&self)->Result<crate::Output> {
107                self.render_with_operation(&OperationOptions::default())
108            }
109
110            /// Prepare and freeze under one cancellable operation.
111            pub fn render_with_operation(&self,options:&OperationOptions)->Result<crate::Output> {
112                crate::operation::run(options,||self.freeze())
113            }
114
115            pub(crate) fn freeze(&self)->Result<crate::Output> {
116                match self {
117                    $(Self::$family(plot)=>plot.freeze(),)+
118                    Self::Canvas(canvas)=>canvas.freeze(),
119                    Self::Theme(_)=>Err(no_figure()),
120                }
121            }
122
123            /// Publish outlined SVG.
124            pub fn svg(&self,path:impl AsRef<Path>)->Result<crate::Output> {
125                self.svg_with_operation(path,&OperationOptions::default())
126            }
127            /// Publish with the caller's cancellation options.
128            pub fn svg_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
129                self.save_with_operation(path,Format::svg(),options)
130            }
131
132            /// Publish SVG retaining selectable text.
133            pub fn svg_preserve_text(&self,path:impl AsRef<Path>)->Result<crate::Output> {
134                self.svg_preserve_text_with_operation(path,&OperationOptions::default())
135            }
136            /// Publish with the caller's cancellation options.
137            pub fn svg_preserve_text_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
138                self.save_with_operation(path,Format::svg().preserve_text(true),options)
139            }
140
141            /// Publish the default balanced PNG.
142            pub fn png(&self,path:impl AsRef<Path>)->Result<crate::Output> {
143                self.png_with_operation(path,&OperationOptions::default())
144            }
145            /// Publish with the caller's cancellation options.
146            pub fn png_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
147                self.save_with_operation(path,Format::png(),options)
148            }
149
150            /// Publish a source-sized PNG.
151            pub fn png_preview(&self,path:impl AsRef<Path>)->Result<crate::Output> {
152                self.png_preview_with_operation(path,&OperationOptions::default())
153            }
154            /// Publish with the caller's cancellation options.
155            pub fn png_preview_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<crate::Output> {
156                self.save_with_operation(path,PngOptions { sizing:crate::output::PngSizing::Source,compression:crate::output::PngCompression::Balanced },options)
157            }
158
159            /// Publish a PNG with explicit device options.
160            pub fn png_with_options(&self,path:impl AsRef<Path>,options:PngOptions)->Result<crate::Output> {
161                self.png_with_options_with_operation(path,options,&OperationOptions::default())
162            }
163            /// Publish a PNG with explicit sampling and operation options.
164            pub fn png_with_options_with_operation(&self,path:impl AsRef<Path>,options:PngOptions,operation:&OperationOptions)->Result<crate::Output> {
165                self.save_with_operation(path,options,operation)
166            }
167
168            /// Write the current native declaration and return that same Recipe.
169            pub fn recipe(&self,path:impl AsRef<Path>)->Result<super::Recipe> {
170                self.recipe_with_operation(path,&OperationOptions::default())
171            }
172            /// Extract and write the declaration under one operation.
173            pub fn recipe_with_operation(&self,path:impl AsRef<Path>,options:&OperationOptions)->Result<super::Recipe> {
174                match self {
175                    $(Self::$family(plot)=>plot.recipe_with_operation(path,options),)+
176                    Self::Canvas(canvas)=>canvas.recipe_with_operation(path,options),
177                    Self::Theme(theme)=>theme.recipe_with_operation(path,options),
178                }
179            }
180        }
181
182        impl TryFrom<&RecipeFigure> for crate::composition::CompositionSource {
183            type Error=Error;
184            fn try_from(figure:&RecipeFigure)->Result<Self>{
185                match figure{
186                    $(RecipeFigure::$family(plot)=>Ok(plot.into()),)+
187                    RecipeFigure::Canvas(canvas)=>Ok(canvas.into()),
188                    RecipeFigure::Theme(_)=>Err(no_figure()),
189                }
190            }
191        }
192
193        pub(crate) fn plot_kind(name:&str)->Result<PlotKind> {
194            match name {
195                $($name=>Ok(PlotKind::$family),)+
196                _=>Err(Error::Data(format!("unknown plot kind {name:?}").into())),
197            }
198        }
199    }
200}
201
202fn no_figure() -> Error {
203    Error::Data("independent theme has no drawable figure".into())
204}
205
206pub(crate) fn check_plot(source: &crate::builder::PlotDescription) -> Result<()> {
207    crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
208    source.validate_configuration(source.kind())?;
209    let appearance = source.resolve_theme()?;
210    let operation = crate::font::canonical::OperationContext::new();
211    let (registry, _) = crate::plots::shared_x::prepare_plot(source, &operation, &appearance)?;
212    crate::layout::interior::guide::validate_categorical_scale(
213        source,
214        &registry.panels,
215        &appearance,
216        None,
217    )
218}
219
220families! {
221    Scatter=>"scatter", Histogram=>"histogram", Density=>"density", Qq=>"qq",
222    PointInterval=>"point_interval", Line=>"line", Trajectory=>"trajectory", LinePath=>"line_path",
223    Interaction=>"interaction", Coefficient=>"coefficient", Forest=>"forest", Dumbbell=>"dumbbell",
224    Heatmap=>"heatmap", Bar=>"bar", HorizontalBar=>"horizontal_bar", StackedBar=>"stacked_bar",
225    StackedHorizontalBar=>"stacked_horizontal_bar", Boxplot=>"boxplot", Violin=>"violin", Raincloud=>"raincloud",
226    Regression=>"regression", Marginal=>"marginal", Matrix=>"matrix", Beeswarm=>"beeswarm", Waterfall=>"waterfall",
227}