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