nsh-core 0.7.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
//! Image information and loading ahead, the functions of `nsh`'s `Image`
//! (`nsh-js` makes it the image element's component). A URL the
//! app's `network` capability does not grant rejects with
//! `ERR_ACCESS_DENIED` (checked here, in the call, as the core checks the
//! loads of Rust components' calls). A `blob:` URL's bytes are in the VM already: its size is read from
//! their header here, without the platform.

use crate::{
    ImageData, ImageScales, ImageSource,
    element::{
        ImageSize, JsError, JsHost, JsIn, JsKind, JsOwned, JsValue, PropError, System, TsTypes,
        module,
    },
    geometry::DevicePixels,
};

/// Image information and loading ahead.
#[module]
pub(crate) struct Image;

/// An image's address: a string or an imported image (`ImageAsset`, with
/// the `scales` of its variants).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ImageUrl {
    url: String,
    scales: ImageScales,
    size: Option<ImageSize>,
    /// The bytes of a `blob:` URL (`URL.createObjectURL`).
    blob: Option<ImageData>,
}

impl ImageUrl {
    /// The URL the views load at the surface's pixel ratio, and the scale
    /// of that variant (1 for the URL itself).
    fn pick(self) -> (String, f32) {
        let source = ImageSource {
            uri: self.url.into(),
            size: None,
            scales: self.scales,
            data: None,
        };
        let ratio = crate::prelude::pixel_ratio();
        let scale = source.variant(ratio).unwrap_or(1.0);
        (source.uri_for(ratio).to_string(), scale)
    }
}

impl JsValue for ImageUrl {
    fn ts_type(_types: &mut TsTypes) -> String {
        "string | ImageAsset".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if let Some(url) = value.as_string() {
            let blob = match url.starts_with("blob:") {
                true => value.host().image_blob(&url).map(|(_, data)| data),
                false => None,
            };
            return Ok(Self {
                url,
                scales: ImageScales::NONE,
                size: None,
                blob,
            });
        }
        if value.kind() == JsKind::Object
            && let Some(url) = value.field("url")?.get().as_string()
        {
            let list = value.field("scales")?;
            let list = list.get();
            let mut scales = ImageScales::NONE;
            let len = list.array_len()?.unwrap_or(0);
            for i in 0..len.min(crate::ops::SCALES_READ) {
                if let Some(n) = list.index(i)?.get().as_number() {
                    scales = scales.with(n as f32);
                }
            }
            // Only variant assets use the imported file's dimensions.
            // Plain sources keep reporting the loaded file's pixels.
            let size =
                if !scales.is_empty() && url.starts_with("asset:/") && !url.contains(['?', '#']) {
                    let extent = value.field("size")?;
                    let extent = extent.get();
                    let dimension = |key| -> Result<Option<DevicePixels>, PropError> {
                        if extent.kind() != JsKind::Object {
                            return Ok(None);
                        }
                        Ok(extent
                            .field(key)?
                            .get()
                            .as_number()
                            .filter(|n| n.is_finite() && *n > 0.0 && *n <= f64::from(i32::MAX))
                            .map(|n| DevicePixels(n.round() as i32)))
                    };
                    dimension("width")?
                        .zip(dimension("height")?)
                        .map(|(width, height)| ImageSize { width, height })
                } else {
                    None
                };
            return Ok(Self {
                url,
                scales,
                size,
                blob: None,
            });
        }
        Err(value.expected("a URL or an imported image"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.new_string(&self.url)?))
    }
}

#[module]
impl Image {
    /// The image's size in pixels; its bytes stay loaded for the views that
    /// show it next. An imported image with variants loads the variant the
    /// views load and resolves with the imported file's size. Without
    /// dimensions, it falls back to the variant's pixels over its scale.
    /// Rejects when the image cannot load, with `ERR_ACCESS_DENIED` when
    /// the `network` capability does not grant its URL.
    pub(crate) async fn get_size(src: ImageUrl, sys: System) -> Result<ImageSize, JsError> {
        if let Some(data) = &src.blob {
            return blob_size(&src.url, data);
        }
        let imported_size = src.size;
        let (url, scale) = src.pick();
        granted(&sys, &url)?;
        let size = crate::prelude::image_size(url)
            .await
            .map_err(JsError::Error)?;
        if let Some(size) = imported_size {
            return Ok(size);
        }
        let unscaled = |px: DevicePixels| DevicePixels((px.0 as f32 / scale).round() as i32);
        Ok(ImageSize {
            width: unscaled(size.width),
            height: unscaled(size.height),
        })
    }

    /// Loads the image ahead of showing it: resolves once its bytes are in
    /// memory, rejects with the error when it cannot load
    /// (`ERR_ACCESS_DENIED` when the `network` capability does not grant
    /// its URL). An
    /// imported image with variants loads the variant the views load at
    /// the screen's pixel ratio.
    pub(crate) async fn prefetch(src: ImageUrl, sys: System) -> Result<(), JsError> {
        if src.blob.is_some() {
            return Ok(());
        }
        let url = src.pick().0;
        granted(&sys, &url)?;
        crate::prelude::prefetch_image(url)
            .await
            .map_err(JsError::Error)
    }
}

/// The size the header of a `blob:` URL's image gives.
fn blob_size(url: &str, data: &ImageData) -> Result<ImageSize, JsError> {
    let size = crate::picker::image_size(data.bytes()).ok_or_else(|| {
        JsError::Error(format!(
            "Image.getSize: {url} is not an image whose header gives its size \
             (PNG, JPEG, GIF, WebP, HEIC, AVIF, TIFF, BMP)"
        ))
    })?;
    Ok(ImageSize {
        width: size.width,
        height: size.height,
    })
}

/// The VM's roots its local images are read under, resolved the first time
/// a call names a source ([`crate::access::MediaFiles`]).
#[derive(Default)]
struct Files(std::cell::OnceCell<crate::access::MediaFiles>);

impl crate::element::Local for Files {}

/// Whether the app may load the image at `url`, as the core checks the
/// `Command::ImageInfo` it sends (against the same base): why not when it
/// may not.
fn granted(sys: &System, url: &str) -> Result<(), JsError> {
    // An app without capabilities reads local files unchecked: no roots to
    // resolve (`media_url` answers it before it looks at them).
    let files = (!sys.access.is_unrestricted()).then(|| sys.locals.get::<Files>());
    let files = files.as_ref().map(|files| {
        files.0.get_or_init(|| {
            let available = crate::access::native_files(sys.os);
            crate::access::MediaFiles::new(
                &sys.access,
                sys.data_dir.as_deref(),
                &sys.paths,
                available,
            )
        })
    });
    if sys
        .access
        .media_url(url, sys.base_url.as_deref(), files)
        .is_some()
    {
        return Ok(());
    }
    let base = sys.base_url.as_deref();
    let advice = crate::access::media_grant_advice(url, base);
    Err(JsError::access_denied(
        format!("Image.getSize / prefetch of {url} is not granted: {advice}"),
        crate::access::media_capability(url, base),
        url,
    ))
}