subspace-dashboard 0.1.0

Subspace Framework board kit: the Dashboard trait, shared widgets and design tokens. Internal crate; apps depend on `subspace-framework`.
Documentation
use gpui_kit::RenderImage;
use image::{DynamicImage, Frame, ImageDecoder as _, ImageFormat, ImageReader, Limits};
use std::{io::Cursor, sync::Arc};

pub const MAX_ENCODED_BYTES: usize = 8 * 1024 * 1024;
const MAX_PIXELS: u64 = 8 * 1024 * 1024;
const MAX_DIMENSION: u32 = 8192;
const MAX_DECODE_ALLOC: u64 = 64 * 1024 * 1024;

/// Decode only a bounded first frame. GPUI consumes BGRA pixels, not RGBA.
pub fn decode(bytes: &[u8], mime: &str) -> Result<Arc<RenderImage>, String> {
    Ok(render_image(raster(bytes, mime)?))
}

fn raster(bytes: &[u8], mime: &str) -> Result<DynamicImage, String> {
    if bytes.len() > MAX_ENCODED_BYTES {
        return Err("Image exceeds 8 MiB".into());
    }
    let format = match mime {
        "image/png" => ImageFormat::Png,
        "image/jpeg" => ImageFormat::Jpeg,
        "image/gif" => ImageFormat::Gif,
        "image/webp" => ImageFormat::WebP,
        _ => return Err("Unsupported image type".into()),
    };
    let mut limits = Limits::default();
    limits.max_image_width = Some(MAX_DIMENSION);
    limits.max_image_height = Some(MAX_DIMENSION);
    limits.max_alloc = Some(MAX_DECODE_ALLOC);
    let (width, height) = ImageReader::with_format(Cursor::new(bytes), format)
        .into_dimensions()
        .map_err(|_| "Cannot decode image")?;
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err("Image exceeds 8,192 px".into());
    }
    if u64::from(width) * u64::from(height) > MAX_PIXELS {
        return Err("Image exceeds 8 megapixels".into());
    }
    let mut reader = ImageReader::with_format(Cursor::new(bytes), format);
    reader.limits(limits);
    let decoder = reader.into_decoder().map_err(|_| "Cannot decode image")?;
    let (width, height) = decoder.dimensions();
    if u64::from(width) * u64::from(height) > MAX_PIXELS {
        return Err("Image exceeds 8 megapixels".into());
    }
    DynamicImage::from_decoder(decoder).map_err(|_| "Cannot decode image".into())
}

fn render_image(image: DynamicImage) -> Arc<RenderImage> {
    let mut rgba = image.into_rgba8();
    for pixel in rgba.pixels_mut() {
        pixel.0.swap(0, 2);
    }
    Arc::new(RenderImage::new(vec![Frame::new(rgba)]))
}

#[cfg(test)]
mod tests;