use std::time::Duration;
use crate::{GuiError, GuiResult};
pub const MAX_IMAGE_RESOURCE_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_IMAGE_RESOURCE_BYTES_PER_UI: usize = 256 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImageResourceId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AnimationResourceId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopCount {
Infinite,
Count(u32),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnimationFrame {
pub image: ImageResourceId,
pub delay: Duration,
}
impl AnimationFrame {
pub fn new(image: ImageResourceId, delay: Duration) -> GuiResult<Self> {
let frame = Self { image, delay };
frame.validate()?;
Ok(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(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnimationData {
pub frames: Vec<AnimationFrame>,
pub loop_count: LoopCount,
}
impl AnimationData {
pub fn new(frames: Vec<AnimationFrame>, loop_count: LoopCount) -> GuiResult<Self> {
let data = Self { frames, loop_count };
data.validate()?;
Ok(data)
}
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(())
}
pub fn frame_count(&self) -> usize {
self.frames.len()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageData {
width: u32,
height: u32,
pixels: Vec<u8>,
}
impl ImageData {
pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> GuiResult<Self> {
let data = Self {
width,
height,
pixels,
};
data.validate()?;
Ok(data)
}
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(())
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
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,
})
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImageResourceCapabilities {
pub rgba: bool,
pub image_animation: bool,
pub animation_decode: bool,
}
impl ImageResourceCapabilities {
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));
assert!(AnimationData::new(vec![], LoopCount::Infinite).is_err());
assert!(AnimationData::new(vec![valid_frame.clone()], LoopCount::Count(0)).is_err());
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);
}
}