Skip to main content

nsh_core/element/
asset.rs

1//! The files a crate ships (`asset!`, `assets!`): images with their
2//! natural size, fonts with their family, other files by URI, as TS's
3//! imports of them give. A crate's files live in its `assets/` directory
4//! and are published at `asset:/@<package>/<path>`; the registry lists
5//! them ([`super::Registry::assets`]) so that `nsh run` serves and `nsh
6//! package` copies them, and the engine registers the fonts before the
7//! first render.
8
9use super::SharedString;
10use crate::geometry::{Points, Size};
11
12/// An image file of a crate (`asset!("logo@2x.png")`; TS: `import logo
13/// from "./logo@2x.png"`): its URL and natural size, which lays the image
14/// out before it loads.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct ImageAsset {
17    /// `asset:/@<package>/<path>`.
18    pub url: &'static str,
19    /// Its size in points, the size it lays out at: the file's pixels over
20    /// the `@2x` / `@3x` of its name. (What decoding reports, as
21    /// [`super::ImageSize`] does, is in [`crate::geometry::DevicePixels`].)
22    pub size: Size<Points>,
23    /// The pixel densities it ships in, 1 being the file itself:
24    /// `asset!("logo.png")` with `logo@2x.png` and `logo@3x.png` next to it
25    /// gives `[1.0, 2.0, 3.0]`, and images load the one for the screen's
26    /// pixel ratio. Empty when the file is the only one (or its name has a
27    /// density suffix).
28    pub scales: &'static [f32],
29}
30
31/// A font file of a crate (`asset!("Pacifico-Regular.ttf")`; TS: `import
32/// pacifico from "./Pacifico-Regular.ttf"`): styles name it by
33/// [`Self::family`] (`.font_family(PACIFICO.family)`). The engine registers
34/// the fonts the registry ships ([`super::Registry::assets`]) before the
35/// first render.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct FontAsset {
38    /// `asset:/@<package>/<path>`.
39    pub uri: &'static str,
40    /// Its family name.
41    pub family: &'static str,
42}
43
44/// Any other file of a crate (a video, a page): its URI for the elements
45/// that load URIs (`video(CLIP.uri)`).
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct FileAsset {
48    /// `asset:/@<package>/<path>`.
49    pub uri: &'static str,
50}
51
52/// What an [`AssetFile`] is.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum AssetKind {
55    /// An image (`png`, `jpg`, `jpeg`, `gif`, `webp`, `heic`).
56    Image,
57    /// A font (`ttf`, `otf`), registered before the first render.
58    Font,
59    /// Anything else.
60    File,
61}
62
63/// A file a crate ships, as `assets!()` lists them.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AssetFile {
66    /// `asset:/@<package>/<path>`.
67    pub uri: &'static str,
68    /// The file where the crate was built: what `nsh` serves and copies, and
69    /// what a development build may read. `Some` in development builds and
70    /// in builds with the `declarations` feature. `None` in other release
71    /// builds, as a packaged app is, whose binary then carries no path of
72    /// the machine that built it ([`__asset_source!`](crate::__asset_source)).
73    pub source: Option<&'static str>,
74    /// What it is.
75    pub kind: AssetKind,
76}
77
78/// Expanded by `assets!` for each file's [`AssetFile::source`]: `Some(path)`
79/// in development builds and where the build carries declarations
80/// ([`super::DECLARATIONS`]), as the toolchain's own programs do; `None` in
81/// other release builds, which packages ship. Chosen by `cfg`, so a packaged
82/// app's binary never has the path: `--remap-path-prefix` does not reach a
83/// literal.
84///
85/// A development build is told by `debug_assertions`, so a release profile
86/// that turns on `debug-assertions` keeps the paths.
87#[doc(hidden)]
88#[macro_export]
89#[cfg(any(test, debug_assertions, feature = "declarations"))]
90macro_rules! __asset_source {
91    ($path:literal) => {
92        ::core::option::Option::Some($path)
93    };
94}
95#[doc(hidden)]
96#[macro_export]
97#[cfg(not(any(test, debug_assertions, feature = "declarations")))]
98macro_rules! __asset_source {
99    ($path:literal) => {
100        ::core::option::Option::None
101    };
102}
103
104impl AssetFile {
105    /// Its path among the app's assets (`@gallery-native/logo@2x.png`): the
106    /// URI without `asset:/`.
107    pub fn path(&self) -> &'static str {
108        self.uri.strip_prefix("asset:/").unwrap_or(self.uri)
109    }
110}
111
112/// What an image shows ([`super::image`], [`super::Image::placeholder`]):
113/// a URL, a file path or `asset:/` URI (strings), or an [`ImageAsset`],
114/// whose natural size lays it out before it loads.
115#[derive(Debug, Clone, PartialEq)]
116pub struct ImageSrc {
117    pub(crate) uri: SharedString,
118    pub(crate) size: Option<(f32, f32)>,
119    pub(crate) scales: crate::ImageScales,
120    /// The bytes of a `blob:` URL the app's VM resolved, as `<Image>`'s
121    /// `src` has them ([`super::JsHost::image_blob`]); the URI is then their
122    /// key.
123    pub(crate) data: Option<crate::ImageData>,
124}
125
126impl<T: Into<SharedString>> From<T> for ImageSrc {
127    fn from(uri: T) -> Self {
128        Self {
129            uri: uri.into(),
130            size: None,
131            scales: crate::ImageScales::NONE,
132            data: None,
133        }
134    }
135}
136
137impl From<ImageAsset> for ImageSrc {
138    fn from(asset: ImageAsset) -> Self {
139        Self {
140            uri: asset.url.into(),
141            size: Some((asset.size.width.0, asset.size.height.0)),
142            scales: asset.scales.iter().copied().collect(),
143            data: None,
144        }
145    }
146}
147
148impl From<&ImageAsset> for ImageSrc {
149    fn from(asset: &ImageAsset) -> Self {
150        (*asset).into()
151    }
152}
153
154impl ImageSrc {
155    /// The natural size in points that [`super::image`] lays out at when
156    /// its style leaves width or height unset. A single styled dimension
157    /// keeps this size's aspect ratio; two styled dimensions set the box.
158    /// The source's pixels and their dimensions stay the same.
159    ///
160    /// ```
161    /// use nsh_core::{
162    ///     element::ImageSrc,
163    ///     geometry::{Size, px},
164    /// };
165    ///
166    /// let pixels = vec![7u8; 200 * 100 * 4];
167    /// let src = ImageSrc::rgba(200, 100, pixels).size(Size::new(px(100.0), px(50.0)));
168    /// ```
169    pub fn size(mut self, size: Size<Points>) -> Self {
170        self.size = Some((size.width.0, size.height.0));
171        self
172    }
173
174    /// Whether its URL is empty: no image, as an `<Image>` whose `src`
175    /// is `""` shows none.
176    pub fn is_empty(&self) -> bool {
177        self.uri.is_empty()
178    }
179
180    /// The source of a menu item's icon; `None` for an empty URL.
181    pub(crate) fn menu_icon(&self) -> Option<crate::ImageSource> {
182        (!self.is_empty()).then(|| {
183            crate::ImageSource {
184                uri: self.uri.to_arc(),
185                size: self.size.map(|(w, h)| crate::geometry::size_pt(w, h)),
186                scales: self.scales,
187                data: self.data.clone(),
188            }
189            .inline()
190        })
191    }
192
193    /// A `width` × `height` pixel buffer as a source: straight (not
194    /// premultiplied) 8-bit RGBA, rows top to bottom with no padding,
195    /// `width * height * 4` bytes, held as they are (`Vec<u8>`,
196    /// `Arc<[u8]>`, ...; not copied). It lays out at `width` × `height`
197    /// points, as a `data:` image does; [`Self::size`] sets its natural
198    /// layout size for a buffer drawn at another pixel density. Frames
199    /// made elsewhere (a renderer, a camera, a thread drawing a preview)
200    /// show without being encoded; each buffer is an image of its own,
201    /// which the caches drop once no view shows it.
202    ///
203    /// ```ignore
204    /// let pixels: Arc<[u8]> = render_page(); // 1192 × 1684 × 4 bytes
205    /// image(ImageSrc::rgba(1192, 1684, pixels)).w_full()
206    /// ```
207    ///
208    /// # Panics
209    ///
210    /// When `pixels` is not `width * height * 4` bytes long, or a side is 0.
211    pub fn rgba(width: u32, height: u32, pixels: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
212        Self {
213            uri: crate::image::rgba_key().into(),
214            size: Some((width as f32, height as f32)),
215            scales: crate::ImageScales::NONE,
216            data: Some(crate::ImageData::from_rgba(width, height, pixels)),
217        }
218    }
219
220    /// The SVG document `markup` itself as a source ([`super::svg`],
221    /// [`super::image`]): its markup is the image, as an `<svg>` written
222    /// inline in a web page is.
223    pub fn svg_markup(markup: &str) -> Self {
224        use std::fmt::Write;
225        let mut uri = String::with_capacity(markup.len() + 32);
226        uri.push_str("data:image/svg+xml,");
227        for b in markup.bytes() {
228            if b.is_ascii_alphanumeric() || b" -._~!$'()*+,;=:@/?".contains(&b) {
229                uri.push(b as char);
230            } else {
231                let _ = write!(uri, "%{b:02X}");
232            }
233        }
234        uri.into()
235    }
236}
237
238crate::static_reactive!(
239    ImageSrc: ImageSrc,
240    ImageAsset,
241    &ImageAsset,
242    super::SharedString,
243    String,
244    &'static str
245);
246
247#[cfg(test)]
248mod tests {
249    /// Tests build like development builds: the path is kept.
250    #[test]
251    fn a_development_build_keeps_the_path() {
252        assert_eq!(
253            crate::__asset_source!("/app/assets/a.png"),
254            Some("/app/assets/a.png")
255        );
256    }
257}