Skip to main content

lichtung_plot/output/
value.rs

1//! Opaque terminal output handle.
2
3use std::ffi::OsString;
4use std::io;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use crate::operation::OperationOptions;
9use crate::scene::RenderedScene;
10use crate::{
11    output::{Format, PngCompression, PngOptions, PngSizing},
12    Error,
13};
14
15/// Opaque handle to one scene that has already been rendered.
16///
17/// Each output method borrows this handle, publishes its requested file immediately
18/// and returns a shared handle to the same frozen scene for chaining. Publication
19/// failure leaves the original handle usable; cloning never renders again.
20///
21/// Terminal methods complete the final native filename with their conventional
22/// lowercase suffix. A filename already ending in the complete expected suffix
23/// under ASCII case-insensitive comparison is preserved exactly; otherwise the
24/// suffix is appended literally. Other filename text is never interpreted or
25/// replaced, so `plot.v1` becomes `plot.v1.svg` and `plot.png` passed to
26/// [`Output::svg`] becomes `plot.png.svg`.
27///
28/// Suffix completion happens only after format conversion succeeds. The caller
29/// path must have a filename and must not currently identify a directory. Its
30/// parent must already exist.
31#[derive(Debug, Clone)]
32pub struct Output {
33    scene: Arc<RenderedScene>,
34}
35
36impl Output {
37    pub(crate) fn scene(&self) -> &RenderedScene {
38        &self.scene
39    }
40    pub(crate) fn new(scene: RenderedScene) -> Self {
41        Self {
42            scene: Arc::new(scene),
43        }
44    }
45
46    /// Frozen canonical scene width in CSS pixels.
47    ///
48    /// This is the SVG root width, independent of PNG raster sizing. Inspecting
49    /// it does not measure, render, or alter the retained scene.
50    #[must_use]
51    pub fn width(&self) -> f64 {
52        self.scene
53            .size()
54            .dimensions()
55            .expect("frozen scene geometry")
56            .0
57    }
58
59    /// Frozen canonical scene height in CSS pixels.
60    ///
61    /// This is the SVG root height, independent of PNG raster sizing. All
62    /// chained publications retain the same canonical dimensions.
63    #[must_use]
64    pub fn height(&self) -> f64 {
65        self.scene
66            .size()
67            .dimensions()
68            .expect("frozen scene geometry")
69            .1
70    }
71
72    /// Original physical size request, if this root was explicitly sized in an
73    /// absolute publication unit.
74    pub fn physical_size(&self) -> Option<crate::layout::PhysicalSize> {
75        self.scene.size().physical_size()
76    }
77
78    /// Read the same accepted layout retained by this frozen output.
79    pub fn layout_report(&self) -> Result<&crate::layout::LayoutReport, Error> {
80        self.scene.layout_report()
81    }
82
83    /// Actual font substitutions made for external SVG image text during
84    /// this scene's preparation. Reading the records never selects fonts.
85    pub fn image_font_substitutions(&self) -> Vec<crate::composition::ImageFontSubstitution> {
86        let mut substitutions = Vec::new();
87        self.scene
88            .collect_image_font_substitutions(&mut substitutions);
89        substitutions
90    }
91
92    /// Publish a self-contained outlined SVG atomically.
93    ///
94    /// After text outlining succeeds, the final native filename is completed
95    /// with `.svg`. A complete ASCII case-insensitive match such as `.SVG` is
96    /// preserved exactly; otherwise `.svg` is appended without interpreting an
97    /// existing extension.
98    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
99        self.svg_with_operation(path, &OperationOptions::default())
100    }
101
102    /// Publish outlined SVG under the supplied operation options.
103    pub fn svg_with_operation(
104        &self,
105        path: impl AsRef<Path>,
106        options: &OperationOptions,
107    ) -> Result<Self, Error> {
108        self.save_with_operation(path, Format::svg(), options)
109    }
110
111    /// Publish SVG with selectable and searchable text atomically.
112    ///
113    /// The final filename is completed with `.svg` using the literal
114    /// suffix rule documented on [`Output`].
115    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
116        self.svg_preserve_text_with_operation(path, &OperationOptions::default())
117    }
118
119    /// Publish selectable-text SVG under the supplied operation options.
120    pub fn svg_preserve_text_with_operation(
121        &self,
122        path: impl AsRef<Path>,
123        options: &OperationOptions,
124    ) -> Result<Self, Error> {
125        self.save_with_operation(path, Format::svg().preserve_text(true), options)
126    }
127
128    /// Publish a 300-DPI balanced-compression PNG atomically.
129    ///
130    /// The final native filename is completed with `.png` by
131    /// [`Output::png_with_options`] after rasterization succeeds.
132    pub fn png(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
133        self.png_with_operation(path, &OperationOptions::default())
134    }
135
136    /// Publish default PNG with the supplied operation options.
137    pub fn png_with_operation(
138        &self,
139        path: impl AsRef<Path>,
140        options: &OperationOptions,
141    ) -> Result<Self, Error> {
142        self.png_with_options_with_operation(path, PngOptions::default(), options)
143    }
144
145    /// Publish a source-sized balanced-compression PNG without density metadata.
146    ///
147    /// The final native filename is completed with `.png` by
148    /// [`Output::png_with_options`] after rasterization succeeds.
149    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
150        self.png_preview_with_operation(path, &OperationOptions::default())
151    }
152
153    /// Publish source-sized PNG with the supplied operation options.
154    pub fn png_preview_with_operation(
155        &self,
156        path: impl AsRef<Path>,
157        options: &OperationOptions,
158    ) -> Result<Self, Error> {
159        self.png_with_options_with_operation(
160            path,
161            PngOptions {
162                sizing: PngSizing::Source,
163                compression: PngCompression::Balanced,
164            },
165            options,
166        )
167    }
168
169    /// Publish a PNG atomically using the exact caller-provided options.
170    ///
171    /// After rasterization succeeds, the final native filename is completed
172    /// with `.png`. A complete ASCII case-insensitive match such as `.PNG` is
173    /// preserved exactly; otherwise `.png` is appended without interpreting an
174    /// existing extension.
175    pub fn png_with_options(
176        &self,
177        path: impl AsRef<Path>,
178        options: PngOptions,
179    ) -> Result<Self, Error> {
180        self.png_with_options_with_operation(path, options, &OperationOptions::default())
181    }
182
183    /// Publish PNG using the device and cancellation options.
184    pub fn png_with_options_with_operation(
185        &self,
186        path: impl AsRef<Path>,
187        options: PngOptions,
188        operation: &OperationOptions,
189    ) -> Result<Self, Error> {
190        self.save_with_operation(path, options, operation)
191    }
192}
193
194pub(super) fn complete_suffix(path: &Path, expected: &str) -> Result<PathBuf, Error> {
195    if path.is_dir() {
196        return Err(io::Error::new(
197            io::ErrorKind::InvalidInput,
198            format!(
199                "render output path {} identifies a directory",
200                path.display()
201            ),
202        )
203        .into());
204    }
205    let file_name = path.file_name().ok_or_else(|| {
206        io::Error::new(
207            io::ErrorKind::InvalidInput,
208            format!("render output path {} has no file name", path.display()),
209        )
210    })?;
211    let encoded = file_name.as_encoded_bytes();
212    if encoded
213        .get(encoded.len().saturating_sub(expected.len())..)
214        .is_some_and(|ending| ending.eq_ignore_ascii_case(expected.as_bytes()))
215    {
216        return Ok(path.to_path_buf());
217    }
218
219    let mut completed = OsString::from(file_name);
220    completed.push(expected);
221    Ok(path.with_file_name(completed))
222}