native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
use std::time::Duration;

use crate::{GuiError, GuiResult};

/// Maximum RGBA8 byte length of one in-memory image resource.
pub const MAX_IMAGE_RESOURCE_BYTES: usize = 64 * 1024 * 1024;

/// Maximum combined RGBA8 byte length retained by one `Ui`.
pub const MAX_IMAGE_RESOURCE_BYTES_PER_UI: usize = 256 * 1024 * 1024;

/// Stable identifier for an image resource owned by one `Ui`.
///
/// IDs are monotonic for the lifetime of their owner and are not reused after
/// release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImageResourceId(pub u64);

/// Stable identifier for an animated image resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AnimationResourceId(pub u64);

/// Number of times an animation should loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopCount {
    /// Plays continuously without stopping.
    Infinite,
    /// Plays exactly `N` times (must be greater than zero).
    Count(u32),
}

/// One pre-decoded frame in an animated sequence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnimationFrame {
    /// Image resource providing the pixels for this frame.
    pub image: ImageResourceId,
    /// Duration this frame is displayed before advancing.
    pub delay: Duration,
}

impl AnimationFrame {
    /// Creates an animation frame after checking that its delay is non-zero.
    pub fn new(image: ImageResourceId, delay: Duration) -> GuiResult<Self> {
        let frame = Self { image, delay };
        frame.validate()?;
        Ok(frame)
    }

    /// Revalidates this frame.
    pub fn validate(&self) -> GuiResult<()> {
        if self.delay.is_zero() {
            return Err(GuiError::Backend(
                "Animation frame delay must be non-zero".to_owned(),
            ));
        }
        Ok(())
    }
}

/// Validated, pre-decoded frame sequence and playback configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnimationData {
    pub frames: Vec<AnimationFrame>,
    pub loop_count: LoopCount,
}

impl AnimationData {
    /// Creates animation data after validating frame count, delays, and loop count.
    pub fn new(frames: Vec<AnimationFrame>, loop_count: LoopCount) -> GuiResult<Self> {
        let data = Self { frames, loop_count };
        data.validate()?;
        Ok(data)
    }

    /// Validates this animation sequence.
    pub fn validate(&self) -> GuiResult<()> {
        if self.frames.is_empty() {
            return Err(GuiError::Backend(
                "Animation data must contain at least one frame".to_owned(),
            ));
        }
        if let LoopCount::Count(0) = self.loop_count {
            return Err(GuiError::Backend(
                "Animation loop count must be greater than zero".to_owned(),
            ));
        }
        for frame in &self.frames {
            frame.validate()?;
        }
        Ok(())
    }

    /// Number of frames in this animation.
    pub fn frame_count(&self) -> usize {
        self.frames.len()
    }
}

/// Validated, row-major RGBA8 image pixels.
///
/// Image resources accept pixels directly; this type does not decode paths or
/// encoded image formats. Each resource is limited to
/// [`MAX_IMAGE_RESOURCE_BYTES`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageData {
    width: u32,
    height: u32,
    pixels: Vec<u8>,
}

impl ImageData {
    /// Creates an RGBA8 image after checking dimensions, byte arithmetic,
    /// resource bounds, and the exact buffer length.
    pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> GuiResult<Self> {
        let data = Self {
            width,
            height,
            pixels,
        };
        data.validate()?;
        Ok(data)
    }

    /// Revalidates this image before it crosses a backend boundary.
    pub fn validate(&self) -> GuiResult<()> {
        let expected = expected_rgba_bytes(self.width, self.height)?;
        if self.pixels.len() != expected {
            return Err(GuiError::Backend(format!(
                "Image data expects {expected} RGBA bytes, found {}",
                self.pixels.len()
            )));
        }
        Ok(())
    }

    /// Image width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Image height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Row-major RGBA8 bytes.
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    pub(crate) fn byte_len(&self) -> usize {
        self.pixels.len()
    }
}

fn expected_rgba_bytes(width: u32, height: u32) -> GuiResult<usize> {
    if width == 0 || height == 0 {
        return Err(GuiError::Backend(
            "Image data dimensions must be positive".to_owned(),
        ));
    }

    let expected = usize::try_from(width)
        .ok()
        .and_then(|width| {
            usize::try_from(height)
                .ok()
                .and_then(|height| width.checked_mul(height))
        })
        .and_then(|pixels| pixels.checked_mul(4))
        .ok_or_else(|| GuiError::Backend("Image data dimensions overflow byte count".to_owned()))?;

    if expected > MAX_IMAGE_RESOURCE_BYTES {
        return Err(GuiError::Backend(format!(
            "Image resource exceeds the {MAX_IMAGE_RESOURCE_BYTES}-byte limit"
        )));
    }
    Ok(expected)
}

pub(crate) fn checked_total_bytes(current: usize, additional: usize) -> GuiResult<usize> {
    current
        .checked_add(additional)
        .filter(|total| *total <= MAX_IMAGE_RESOURCE_BYTES_PER_UI)
        .ok_or(GuiError::ResourceExhausted {
            operation: "image resource allocation",
            code: None,
        })
}

/// Image-resource operations implemented by a backend.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImageResourceCapabilities {
    /// Bounded in-memory RGBA8 images can be loaded and released.
    pub rgba: bool,
    /// Pre-decoded animated image playback can be scheduled and driven.
    pub image_animation: bool,
    /// Encoded animation stream decoding (GIF/APNG/WebP).
    pub animation_decode: bool,
}

impl ImageResourceCapabilities {
    /// Returns a capability set with every operation disabled.
    pub const fn none() -> Self {
        Self {
            rgba: false,
            image_animation: false,
            animation_decode: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::MockBackend;
    use crate::Ui;

    fn rgba(width: u32, height: u32) -> ImageData {
        ImageData::from_rgba(width, height, vec![7; width as usize * height as usize * 4]).unwrap()
    }

    #[test]
    fn rgba_data_validates_dimensions_lengths_overflow_and_bounds() {
        assert!(ImageData::from_rgba(0, 1, Vec::new()).is_err());
        assert!(ImageData::from_rgba(1, 0, Vec::new()).is_err());
        assert!(ImageData::from_rgba(2, 1, vec![0; 7]).is_err());
        assert!(ImageData::from_rgba(u32::MAX, u32::MAX, Vec::new()).is_err());
        assert!(
            ImageData::from_rgba((MAX_IMAGE_RESOURCE_BYTES / 4 + 1) as u32, 1, Vec::new()).is_err()
        );

        let image = ImageData::from_rgba(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]).unwrap();
        assert_eq!(image.width(), 2);
        assert_eq!(image.height(), 1);
        assert_eq!(image.pixels(), &[1, 2, 3, 4, 5, 6, 7, 8]);
    }

    #[test]
    fn image_resources_have_stable_lookup_and_release_lifecycle() {
        let mut ui = Ui::new(MockBackend::default());
        let first_data = rgba(2, 1);
        let first = ui.load_image_resource(&first_data).unwrap();
        assert_eq!(first, ImageResourceId(1));
        assert!(ui.image_resource_is_live(first));
        assert_eq!(ui.backend().image_resource(first), Some(&first_data));

        ui.release_image_resource(first).unwrap();
        assert!(!ui.image_resource_is_live(first));
        assert_eq!(ui.backend().image_resource(first), None);
        assert_eq!(
            ui.release_image_resource(first),
            Err(GuiError::Backend("Image resource not found: 1".to_owned()))
        );

        let second = ui.load_image_resource(&rgba(1, 1)).unwrap();
        assert_eq!(second, ImageResourceId(2));
        assert!(ui.image_resource_is_live(second));
    }

    #[test]
    fn refused_resource_operations_are_transactional() {
        let mut backend = MockBackend::default();
        backend.set_image_resource_capabilities(ImageResourceCapabilities::none());
        let mut ui = Ui::new(backend);
        let data = rgba(1, 1);

        assert_eq!(
            ui.load_image_resource(&data),
            Err(GuiError::UnsupportedCapability(
                "image_resource_rgba".to_owned()
            ))
        );
        assert!(!ui.image_resource_is_live(ImageResourceId(1)));
        assert!(ui.backend().image_resources.is_empty());

        ui.backend_mut()
            .set_image_resource_capabilities(ImageResourceCapabilities {
                rgba: true,
                ..Default::default()
            });
        let id = ui.load_image_resource(&data).unwrap();
        assert_eq!(id, ImageResourceId(1));

        ui.backend_mut()
            .set_image_resource_capabilities(ImageResourceCapabilities::none());
        assert_eq!(
            ui.release_image_resource(id),
            Err(GuiError::UnsupportedCapability(
                "image_resource_rgba".to_owned()
            ))
        );
        assert!(ui.image_resource_is_live(id));
        assert_eq!(ui.backend().image_resource(id), Some(&data));

        ui.backend_mut()
            .set_image_resource_capabilities(ImageResourceCapabilities {
                rgba: true,
                ..Default::default()
            });
        ui.release_image_resource(id).unwrap();
        assert!(!ui.image_resource_is_live(id));
    }

    #[test]
    fn per_ui_byte_bound_refuses_before_provider_or_id_mutation() {
        let mut ui = Ui::new(MockBackend::default());
        assert!(matches!(
            checked_total_bytes(MAX_IMAGE_RESOURCE_BYTES_PER_UI, 4),
            Err(GuiError::ResourceExhausted {
                operation: "image resource allocation",
                ..
            })
        ));
        assert_eq!(checked_total_bytes(4, 8).unwrap(), 12);
        assert_eq!(
            ui.load_image_resource(&rgba(1, 1)).unwrap(),
            ImageResourceId(1)
        );
    }

    #[test]
    fn ui_revalidates_image_data_before_backend_calls() {
        let mut ui = Ui::new(MockBackend::default());
        let invalid = ImageData {
            width: 2,
            height: 1,
            pixels: vec![0; 7],
        };

        assert!(ui.load_image_resource(&invalid).is_err());
        assert!(ui.backend().image_resources.is_empty());
        assert_eq!(ui.widget_count(), 0);
    }

    #[test]
    fn animation_frame_and_data_validation() {
        assert!(AnimationFrame::new(ImageResourceId(1), Duration::ZERO).is_err());
        let valid_frame =
            AnimationFrame::new(ImageResourceId(1), Duration::from_millis(50)).unwrap();
        assert_eq!(valid_frame.image, ImageResourceId(1));
        assert_eq!(valid_frame.delay, Duration::from_millis(50));

        // Empty frames rejected
        assert!(AnimationData::new(vec![], LoopCount::Infinite).is_err());

        // Count(0) rejected
        assert!(AnimationData::new(vec![valid_frame.clone()], LoopCount::Count(0)).is_err());

        // Valid Count and Infinite
        let anim_infinite =
            AnimationData::new(vec![valid_frame.clone()], LoopCount::Infinite).unwrap();
        assert_eq!(anim_infinite.frame_count(), 1);

        let anim_count = AnimationData::new(
            vec![
                valid_frame,
                AnimationFrame::new(ImageResourceId(2), Duration::from_millis(100)).unwrap(),
            ],
            LoopCount::Count(3),
        )
        .unwrap();
        assert_eq!(anim_count.frame_count(), 2);
    }

    #[test]
    fn image_resource_capabilities_defaults_and_none() {
        let none = ImageResourceCapabilities::none();
        assert!(!none.rgba);
        assert!(!none.image_animation);
        assert!(!none.animation_decode);

        let default_caps = ImageResourceCapabilities::default();
        assert!(!default_caps.rgba);
        assert!(!default_caps.image_animation);
        assert!(!default_caps.animation_decode);
    }
}