Skip to main content

lichtung_plot/composition/
asset.rs

1//! The resource-owning side of fixed images.
2
3mod css;
4mod png;
5mod raster_image;
6mod resources;
7mod svg;
8
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use crate::{Error, Result};
13use base64::{engine::general_purpose::STANDARD, Engine};
14pub(crate) use png::{png_samples, PngSamples};
15pub(crate) fn png_alpha_ink(
16    bytes: &[u8],
17    object: crate::layout::Rect,
18    clip: crate::layout::Rect,
19    rendering: super::ImageRendering,
20) -> Result<crate::layout::InkExtent> {
21    super::ink::png_ink(&png::decode(bytes, false)?, object, clip, rendering)
22}
23pub(crate) use svg::raster_svg;
24use svg::SvgAsset;
25
26/// Validated, owned local image input. The source bytes and referenced resources
27/// are retained independently of the caller's buffer or filesystem.
28#[derive(Debug, Clone)]
29pub struct ImageAsset(Arc<Asset>, Option<Arc<PathBuf>>);
30
31/// An actual external SVG font substitution made while freezing glyphs.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ImageFontSubstitution {
34    /// Authored family selection requesting the font or missing glyph.
35    pub requested: String,
36    /// Actual family used in the selected glyphs.
37    pub selected: String,
38    /// Missing source scalar for a glyph-level substitution, when applicable.
39    pub scalar: Option<char>,
40}
41
42#[derive(Debug)]
43enum Asset {
44    Png {
45        bytes: Arc<[u8]>,
46        metadata: png::PngMetadata,
47    },
48    Svg(SvgAsset),
49}
50
51/// Intrinsic dimensions and aspect ratio are independent: a viewBox is not a
52/// declaration of CSS-pixel width and height.
53#[derive(Debug, Clone, Copy)]
54pub(super) struct Intrinsics {
55    pub size: [Option<f64>; 2],
56    pub ratio: Option<f64>,
57}
58
59impl Intrinsics {
60    pub(super) fn sized(width: f64, height: f64) -> Self {
61        Self {
62            size: [Some(width), Some(height)],
63            ratio: Some(width / height),
64        }
65    }
66
67    pub(super) fn complete(self) -> Option<(f64, f64)> {
68        match (self.size, self.ratio) {
69            ([Some(w), Some(h)], _) => Some((w, h)),
70            ([Some(w), None], Some(ratio)) => Some((w, w / ratio)),
71            ([None, Some(h)], Some(ratio)) => Some((h * ratio, h)),
72            _ => None,
73        }
74    }
75}
76
77impl ImageAsset {
78    /// Capture an already colored, immutable sRGB pixel buffer as an image.
79    pub fn from_pixels(
80        pixels: impl std::borrow::Borrow<crate::output::PixelBuffer>,
81    ) -> Result<Self> {
82        Self::from_pixels_with_operation(
83            pixels.borrow(),
84            &crate::operation::OperationOptions::default(),
85        )
86    }
87
88    /// Capture existing pixel samples under this call's operation options.
89    pub fn from_pixels_with_operation(
90        pixels: &crate::output::PixelBuffer,
91        options: &crate::operation::OperationOptions,
92    ) -> Result<Self> {
93        crate::operation::run(options, || {
94            let size = resvg::tiny_skia::IntSize::from_wh(pixels.width(), pixels.height())
95                .expect("admitted raster size");
96            let density = pixels
97                .dpi()
98                .map(crate::layout::dpi_to_pixels_per_meter)
99                .transpose()?;
100            let straight = pixels.straight_rgba()?;
101            let bytes = crate::render::svg_backend::encode_png(
102                &straight,
103                size,
104                crate::output::PngCompression::Balanced,
105                density,
106            )?;
107            Self::read_png(&bytes)
108        })
109    }
110
111    /// Read a local PNG or SVG file and seal its actual drawing dependencies.
112    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
113        Self::from_path_with_operation(path, &crate::operation::OperationOptions::default())
114    }
115
116    /// Seal a local image under this operation's cancellation options.
117    pub fn from_path_with_operation(
118        path: impl AsRef<Path>,
119        options: &crate::operation::OperationOptions,
120    ) -> Result<Self> {
121        crate::operation::run(options, || Self::read_path(path.as_ref()))
122    }
123
124    pub(super) fn read_path(path: &Path) -> Result<Self> {
125        let path = std::path::absolute(path)?;
126        let bytes = crate::operation::external(|| std::fs::read(&path))?;
127        crate::operation::checkpoint()?;
128        let mut asset = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
129            Self::read_png(&bytes)?
130        } else {
131            let svg = SvgAsset::from_file(&bytes, &path)
132                .map_err(|error| error.with_prefix(&format!("SVG asset {}", path.display())))?;
133            Self(Arc::new(Asset::Svg(svg)), None)
134        };
135        asset.1 = Some(Arc::new(path));
136        Ok(asset)
137    }
138
139    /// Capture the supplied PNG's original encoded bytes.
140    pub fn from_png_bytes(bytes: &[u8]) -> Result<Self> {
141        Self::from_png_bytes_with_operation(bytes, &crate::operation::OperationOptions::default())
142    }
143
144    /// Capture a PNG under this operation's cancellation options.
145    pub fn from_png_bytes_with_operation(
146        bytes: &[u8],
147        options: &crate::operation::OperationOptions,
148    ) -> Result<Self> {
149        crate::operation::run(options, || Self::read_png(bytes))
150    }
151
152    fn read_png(bytes: &[u8]) -> Result<Self> {
153        let metadata = png::metadata(bytes)?;
154        Ok(Self(
155            Arc::new(Asset::Png {
156                bytes: Arc::from(bytes),
157                metadata,
158            }),
159            None,
160        ))
161    }
162
163    /// Capture a self-contained static SVG, without a filesystem base.
164    pub fn from_svg_bytes(bytes: &[u8]) -> Result<Self> {
165        Self::from_svg_bytes_with_operation(bytes, &crate::operation::OperationOptions::default())
166    }
167
168    /// Capture self-contained SVG under this operation's cancellation options.
169    pub fn from_svg_bytes_with_operation(
170        bytes: &[u8],
171        options: &crate::operation::OperationOptions,
172    ) -> Result<Self> {
173        crate::operation::run(options, || {
174            Ok(Self(
175                Arc::new(Asset::Svg(SvgAsset::from_bytes(bytes)?)),
176                None,
177            ))
178        })
179    }
180
181    pub(super) fn declared_path(&self) -> Option<&Path> {
182        self.1.as_deref().map(PathBuf::as_path)
183    }
184
185    /// Intrinsic CSS width, if specified by this source.
186    pub fn width(&self) -> Option<f64> {
187        self.intrinsics().size[0]
188    }
189
190    /// Intrinsic CSS height, if specified by this source.
191    pub fn height(&self) -> Option<f64> {
192        self.intrinsics().size[1]
193    }
194
195    /// Intrinsic width-to-height ratio, when the source has one.
196    pub fn aspect_ratio(&self) -> Option<f64> {
197        self.intrinsics().ratio
198    }
199
200    pub(super) fn intrinsics(&self) -> Intrinsics {
201        match &*self.0 {
202            Asset::Png { metadata, .. } => {
203                Intrinsics::sized(f64::from(metadata.size.0), f64::from(metadata.size.1))
204            }
205            Asset::Svg(svg) => svg.intrinsics(),
206        }
207    }
208
209    pub(super) fn prepare(&self, viewport: (f64, f64)) -> Result<AssetView> {
210        match &*self.0 {
211            Asset::Png { bytes, .. } => Ok(AssetView {
212                preserved: data_uri("image/png", bytes).into(),
213                outlined: None,
214                preserve_error: None,
215                substitutions: Vec::new(),
216            }),
217            Asset::Svg(svg) => svg.prepare(viewport),
218        }
219    }
220
221    pub(super) fn known_empty(&self) -> bool {
222        matches!(&*self.0, Asset::Png { metadata, .. } if metadata.coverage == png::Coverage::Empty)
223    }
224
225    pub(super) fn exact_ink(
226        &self,
227        viewport: (f64, f64),
228        object: crate::layout::Rect,
229        clip: crate::layout::Rect,
230        rendering: super::ImageRendering,
231        view: Option<&AssetView>,
232    ) -> Result<crate::layout::InkExtent> {
233        use crate::layout::{InkExtent, Rect};
234        let Some(clip) = object.intersection(clip) else {
235            return Ok(InkExtent::Empty);
236        };
237        match &*self.0 {
238            Asset::Png { bytes, metadata } => match metadata.coverage {
239                png::Coverage::Empty => Ok(InkExtent::Empty),
240                png::Coverage::Full => Ok(InkExtent::Bounds(clip)),
241                png::Coverage::Partial => {
242                    super::ink::png_ink(&png::decode(bytes, false)?, object, clip, rendering)
243                }
244            },
245            Asset::Svg(asset) => {
246                let source = Rect::new(0., 0., viewport.0, viewport.1)?;
247                let local_clip = super::ink::map_rect(clip, object, source)?;
248                let ink = if let Some(Ok(href)) = view.and_then(|view| view.outlined.as_ref()) {
249                    let (_, bytes) = read_data_uri(href)?;
250                    let svg = std::str::from_utf8(&bytes).map_err(|error| {
251                        Error::Render(format!("retained outline SVG: {error}").into())
252                    })?;
253                    super::ink::svg_ink(svg, source, local_clip)?
254                } else {
255                    asset.exact_ink(source, local_clip)?
256                };
257                super::ink::map_ink(ink, source, object)
258            }
259        }
260    }
261}
262
263/// An actual source viewport with a retained preserve-text representation and
264/// its format-local outline result. Failure of outlining doesn't affect SVG
265/// publication that preserves the author's text.
266#[derive(Debug, Clone)]
267pub(super) struct AssetView {
268    pub preserved: Arc<str>,
269    pub outlined: Option<std::result::Result<Arc<str>, crate::errors::Diagnostic>>,
270    pub preserve_error: Option<crate::errors::Diagnostic>,
271    pub substitutions: Vec<ImageFontSubstitution>,
272}
273
274impl AssetView {
275    pub fn href(&self, outline: bool) -> Result<&str> {
276        match (outline, &self.outlined) {
277            (true, Some(Ok(href))) => Ok(href),
278            (true, Some(Err(error))) => Err(Error::Render(error.clone())),
279            _ => Ok(&self.preserved),
280        }
281    }
282}
283
284pub(crate) fn data_uri(mime: &str, bytes: &[u8]) -> String {
285    format!("data:{mime};base64,{}", STANDARD.encode(bytes))
286}
287
288pub(crate) fn read_data_uri(value: &str) -> Result<(String, Vec<u8>)> {
289    let url = data_url::DataUrl::process(value)
290        .map_err(|error| Error::Data(format!("invalid image data URI: {error:?}").into()))?;
291    let mime = format!("{}/{}", url.mime_type().type_, url.mime_type().subtype);
292    let (bytes, _) = url
293        .decode_to_vec()
294        .map_err(|error| Error::Data(format!("invalid encoded image data: {error:?}").into()))?;
295    Ok((mime, bytes))
296}