Skip to main content

lichtung_plot/
output.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::scene::RenderedScene;
9use crate::{Error, PngCompression, PngOptions, PngSizing};
10
11/// Opaque handle to one scene that has already been rendered.
12///
13/// Each output method borrows this handle, publishes its requested file immediately
14/// and returns a shared handle to the same frozen scene for chaining. Publication
15/// failure leaves the original handle usable; cloning never renders again.
16///
17/// Terminal methods complete the final native filename with their conventional
18/// lowercase suffix. A filename already ending in the complete expected suffix
19/// under ASCII case-insensitive comparison is preserved exactly; otherwise the
20/// suffix is appended literally. Other filename text is never interpreted or
21/// replaced, so `plot.v1` becomes `plot.v1.svg` and `plot.png` passed to
22/// [`Output::svg`] becomes `plot.png.svg`.
23///
24/// Suffix completion happens only after format conversion succeeds. The caller
25/// path must have a filename and must not currently identify a directory. Its
26/// parent must already exist.
27#[derive(Clone)]
28pub struct Output {
29    scene: Arc<RenderedScene>,
30}
31
32impl Output {
33    pub(crate) fn new(scene: RenderedScene) -> Self {
34        Self {
35            scene: Arc::new(scene),
36        }
37    }
38
39    /// Frozen canonical scene width in integral CSS pixels.
40    ///
41    /// This is the SVG root width, independent of PNG raster sizing. Inspecting
42    /// it does not measure, render, or alter the retained scene.
43    #[must_use]
44    pub fn width(&self) -> u32 {
45        self.scene.dimensions().0
46    }
47
48    /// Frozen canonical scene height in integral CSS pixels.
49    ///
50    /// This is the SVG root height, independent of PNG raster sizing. All
51    /// chained publications retain the same canonical dimensions.
52    #[must_use]
53    pub fn height(&self) -> u32 {
54        self.scene.dimensions().1
55    }
56
57    /// Publish a self-contained outlined SVG atomically.
58    ///
59    /// After text outlining succeeds, the final native filename is completed
60    /// with `.svg`. A complete ASCII case-insensitive match such as `.SVG` is
61    /// preserved exactly; otherwise `.svg` is appended without interpreting an
62    /// existing extension.
63    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
64        let bytes = self.scene.svg_with_text_as_paths()?;
65        let path = complete_suffix(path.as_ref(), ".svg")?;
66        crate::orchestrator::write_atomic(&path, &bytes)?;
67        Ok(self.clone())
68    }
69
70    /// Publish SVG with selectable and searchable text atomically.
71    ///
72    /// After borrowing the canonical SVG bytes, the final native filename is
73    /// completed with `.svg` using the literal rule documented on [`Output`].
74    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
75        let bytes = self.scene.svg_bytes();
76        let path = complete_suffix(path.as_ref(), ".svg")?;
77        crate::orchestrator::write_atomic(&path, bytes)?;
78        Ok(self.clone())
79    }
80
81    /// Publish a 300-DPI balanced-compression PNG atomically.
82    ///
83    /// The final native filename is completed with `.png` by
84    /// [`Output::png_with_options`] after rasterization succeeds.
85    pub fn png(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
86        self.png_with_options(path, PngOptions::default())
87    }
88
89    /// Publish a source-sized balanced-compression PNG without density metadata.
90    ///
91    /// The final native filename is completed with `.png` by
92    /// [`Output::png_with_options`] after rasterization succeeds.
93    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
94        self.png_with_options(
95            path,
96            PngOptions {
97                sizing: PngSizing::Source,
98                compression: PngCompression::Balanced,
99            },
100        )
101    }
102
103    /// Publish a PNG atomically using the exact caller-provided options.
104    ///
105    /// After rasterization succeeds, the final native filename is completed
106    /// with `.png`. A complete ASCII case-insensitive match such as `.PNG` is
107    /// preserved exactly; otherwise `.png` is appended without interpreting an
108    /// existing extension.
109    pub fn png_with_options(
110        &self,
111        path: impl AsRef<Path>,
112        options: PngOptions,
113    ) -> Result<Self, Error> {
114        let bytes = self.scene.png_bytes(&options)?;
115        let path = complete_suffix(path.as_ref(), ".png")?;
116        crate::orchestrator::write_atomic(&path, &bytes)?;
117        Ok(self.clone())
118    }
119}
120
121fn complete_suffix(path: &Path, expected: &str) -> Result<PathBuf, Error> {
122    if path.is_dir() {
123        return Err(io::Error::new(
124            io::ErrorKind::InvalidInput,
125            format!(
126                "render output path {} identifies a directory",
127                path.display()
128            ),
129        )
130        .into());
131    }
132    let file_name = path.file_name().ok_or_else(|| {
133        io::Error::new(
134            io::ErrorKind::InvalidInput,
135            format!("render output path {} has no file name", path.display()),
136        )
137    })?;
138    let encoded = file_name.as_encoded_bytes();
139    if encoded
140        .get(encoded.len().saturating_sub(expected.len())..)
141        .is_some_and(|ending| ending.eq_ignore_ascii_case(expected.as_bytes()))
142    {
143        return Ok(path.to_path_buf());
144    }
145
146    let mut completed = OsString::from(file_name);
147    completed.push(expected);
148    Ok(path.with_file_name(completed))
149}