Skip to main content

kova_native_assets/
lib.rs

1//! Image and vector assets for Kova Native.
2//!
3//! * [`ImageData`] — decoded raster images (PNG, JPEG, WebP), stored as
4//!   premultiplied RGBA ready for the GPU atlas.
5//! * [`SvgData`] — parsed SVG documents, rasterized on demand at the exact
6//!   device pixel size they are drawn at (crisp at any scale factor).
7//! * [`AssetCache`] — deduplicates loads by source so the same file is
8//!   decoded once no matter how many elements display it.
9
10use kova_native_core::{ImageId, KovaError, KovaResult, Size};
11use parking_lot::Mutex;
12use resvg::{tiny_skia, usvg};
13use rustc_hash::FxHashMap;
14use std::path::{Path, PathBuf};
15use std::sync::{Arc, OnceLock};
16
17/// A decoded raster image (premultiplied RGBA8).
18#[derive(Debug)]
19pub struct ImageData {
20    id: ImageId,
21    width: u32,
22    height: u32,
23    pixels: Vec<u8>,
24}
25
26impl ImageData {
27    /// Decodes PNG/JPEG/WebP bytes.
28    pub fn decode(bytes: &[u8]) -> KovaResult<Arc<ImageData>> {
29        let img = image::load_from_memory(bytes)
30            .map_err(|e| KovaError::Asset(format!("image decode failed: {e}")))?;
31        let rgba = img.to_rgba8();
32        let (width, height) = rgba.dimensions();
33        Ok(Self::from_rgba(width, height, rgba.into_raw()))
34    }
35
36    /// Wraps straight-alpha RGBA8 pixels (premultiplies them).
37    pub fn from_rgba(width: u32, height: u32, mut pixels: Vec<u8>) -> Arc<ImageData> {
38        assert_eq!(
39            pixels.len(),
40            (width * height * 4) as usize,
41            "pixel buffer size mismatch"
42        );
43        premultiply(&mut pixels);
44        Arc::new(ImageData {
45            id: ImageId::next(),
46            width,
47            height,
48            pixels,
49        })
50    }
51
52    pub fn open(path: impl AsRef<Path>) -> KovaResult<Arc<ImageData>> {
53        let bytes = std::fs::read(path.as_ref()).map_err(|e| {
54            KovaError::Asset(format!("cannot read {}: {e}", path.as_ref().display()))
55        })?;
56        Self::decode(&bytes)
57    }
58
59    pub fn id(&self) -> ImageId {
60        self.id
61    }
62
63    pub fn width(&self) -> u32 {
64        self.width
65    }
66
67    pub fn height(&self) -> u32 {
68        self.height
69    }
70
71    pub fn size(&self) -> Size {
72        Size::new(self.width as f32, self.height as f32)
73    }
74
75    /// Premultiplied RGBA8 pixels.
76    pub fn pixels(&self) -> &[u8] {
77        &self.pixels
78    }
79}
80
81fn premultiply(pixels: &mut [u8]) {
82    for px in pixels.as_chunks_mut::<4>().0 {
83        let a = px[3] as u16;
84        if a < 255 {
85            px[0] = ((px[0] as u16 * a + 127) / 255) as u8;
86            px[1] = ((px[1] as u16 * a + 127) / 255) as u8;
87            px[2] = ((px[2] as u16 * a + 127) / 255) as u8;
88        }
89    }
90}
91
92/// A parsed SVG document.
93pub struct SvgData {
94    id: ImageId,
95    tree: usvg::Tree,
96}
97
98impl std::fmt::Debug for SvgData {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.debug_struct("SvgData")
101            .field("id", &self.id)
102            .field("size", &self.size())
103            .finish()
104    }
105}
106
107impl SvgData {
108    pub fn parse(bytes: &[u8]) -> KovaResult<Arc<SvgData>> {
109        let tree = usvg::Tree::from_data(bytes, &usvg::Options::default())
110            .map_err(|e| KovaError::Asset(format!("svg parse failed: {e}")))?;
111        Ok(Arc::new(SvgData {
112            id: ImageId::next(),
113            tree,
114        }))
115    }
116
117    pub fn open(path: impl AsRef<Path>) -> KovaResult<Arc<SvgData>> {
118        let bytes = std::fs::read(path.as_ref()).map_err(|e| {
119            KovaError::Asset(format!("cannot read {}: {e}", path.as_ref().display()))
120        })?;
121        Self::parse(&bytes)
122    }
123
124    pub fn id(&self) -> ImageId {
125        self.id
126    }
127
128    /// Intrinsic size from the document's width/height/viewBox.
129    pub fn size(&self) -> Size {
130        let s = self.tree.size();
131        Size::new(s.width(), s.height())
132    }
133
134    /// Rasterizes into premultiplied RGBA8 at exactly `width` x `height`
135    /// pixels, scaling the document to fit (aspect ratio preserved, centered).
136    pub fn rasterize(&self, width: u32, height: u32) -> Option<Vec<u8>> {
137        let mut pixmap = tiny_skia::Pixmap::new(width.max(1), height.max(1))?;
138        let size = self.tree.size();
139        let scale = (width as f32 / size.width()).min(height as f32 / size.height());
140        let dx = (width as f32 - size.width() * scale) * 0.5;
141        let dy = (height as f32 - size.height() * scale) * 0.5;
142        let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy);
143        resvg::render(&self.tree, transform, &mut pixmap.as_mut());
144        Some(pixmap.take())
145    }
146
147    /// Rasterizes to an 8-bit coverage mask (alpha channel only), for
148    /// monochrome icons tinted at draw time.
149    pub fn rasterize_mask(&self, width: u32, height: u32) -> Option<Vec<u8>> {
150        let rgba = self.rasterize(width, height)?;
151        Some(rgba.as_chunks::<4>().0.iter().map(|px| px[3]).collect())
152    }
153}
154
155/// Where an asset comes from.
156#[derive(Clone, Debug, PartialEq, Eq, Hash)]
157pub enum AssetSource {
158    Path(PathBuf),
159    /// Embedded bytes, identified by their address and length (for
160    /// `include_bytes!` data, which is `'static`).
161    Static(usize, usize),
162}
163
164impl AssetSource {
165    pub fn from_static(bytes: &'static [u8]) -> Self {
166        AssetSource::Static(bytes.as_ptr() as usize, bytes.len())
167    }
168}
169
170/// Caches decoded assets by source. Thread safe, so decoding can happen on
171/// background threads.
172#[derive(Default)]
173pub struct AssetCache {
174    images: Mutex<FxHashMap<AssetSource, Result<Arc<ImageData>, String>>>,
175    svgs: Mutex<FxHashMap<AssetSource, Result<Arc<SvgData>, String>>>,
176}
177
178impl AssetCache {
179    /// The process wide cache.
180    pub fn global() -> &'static AssetCache {
181        static CACHE: OnceLock<AssetCache> = OnceLock::new();
182        CACHE.get_or_init(AssetCache::default)
183    }
184
185    pub fn image_from_path(&self, path: impl AsRef<Path>) -> KovaResult<Arc<ImageData>> {
186        let key = AssetSource::Path(path.as_ref().to_path_buf());
187        self.load_image(key, || ImageData::open(path.as_ref()))
188    }
189
190    pub fn image_from_static(&self, bytes: &'static [u8]) -> KovaResult<Arc<ImageData>> {
191        self.load_image(AssetSource::from_static(bytes), || ImageData::decode(bytes))
192    }
193
194    pub fn svg_from_path(&self, path: impl AsRef<Path>) -> KovaResult<Arc<SvgData>> {
195        let key = AssetSource::Path(path.as_ref().to_path_buf());
196        self.load_svg(key, || SvgData::open(path.as_ref()))
197    }
198
199    pub fn svg_from_static(&self, bytes: &'static [u8]) -> KovaResult<Arc<SvgData>> {
200        self.load_svg(AssetSource::from_static(bytes), || SvgData::parse(bytes))
201    }
202
203    fn load_image(
204        &self,
205        key: AssetSource,
206        load: impl FnOnce() -> KovaResult<Arc<ImageData>>,
207    ) -> KovaResult<Arc<ImageData>> {
208        if let Some(entry) = self.images.lock().get(&key) {
209            return entry.clone().map_err(KovaError::Asset);
210        }
211        let result = load().map_err(|e| e.to_string());
212        self.images.lock().insert(key, result.clone());
213        result.map_err(KovaError::Asset)
214    }
215
216    fn load_svg(
217        &self,
218        key: AssetSource,
219        load: impl FnOnce() -> KovaResult<Arc<SvgData>>,
220    ) -> KovaResult<Arc<SvgData>> {
221        if let Some(entry) = self.svgs.lock().get(&key) {
222            return entry.clone().map_err(KovaError::Asset);
223        }
224        let result = load().map_err(|e| e.to_string());
225        self.svgs.lock().insert(key, result.clone());
226        result.map_err(KovaError::Asset)
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    const SVG: &[u8] =
235        br##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
236        <circle cx="12" cy="12" r="10" fill="#ff0000"/></svg>"##;
237
238    #[test]
239    fn svg_rasterizes_at_requested_size() {
240        let svg = SvgData::parse(SVG).unwrap();
241        assert_eq!(svg.size(), Size::new(24.0, 24.0));
242        let px = svg.rasterize(48, 48).unwrap();
243        assert_eq!(px.len(), 48 * 48 * 4);
244        let center = &px[((24 * 48 + 24) * 4)..((24 * 48 + 24) * 4 + 4)];
245        assert_eq!(center, &[255, 0, 0, 255]);
246        let corner = &px[0..4];
247        assert_eq!(corner[3], 0);
248        let mask = svg.rasterize_mask(12, 12).unwrap();
249        assert_eq!(mask.len(), 144);
250    }
251
252    #[test]
253    fn png_roundtrip_and_cache() {
254        // Encode a 2x1 PNG in memory.
255        let mut png = Vec::new();
256        {
257            let img =
258                image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 128]).unwrap();
259            img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
260                .unwrap();
261        }
262        let data = ImageData::decode(&png).unwrap();
263        assert_eq!((data.width(), data.height()), (2, 1));
264        // Second pixel is premultiplied.
265        assert_eq!(&data.pixels()[4..8], &[0, 0, 128, 128]);
266
267        let bytes: &'static [u8] = Box::leak(png.into_boxed_slice());
268        let cache = AssetCache::default();
269        let a = cache.image_from_static(bytes).unwrap();
270        let b = cache.image_from_static(bytes).unwrap();
271        assert!(Arc::ptr_eq(&a, &b));
272        assert!(cache.image_from_path("does/not/exist.png").is_err());
273    }
274}