Skip to main content

native_gui_core/
image_resource.rs

1use std::time::Duration;
2
3use crate::{GuiError, GuiResult};
4
5/// Maximum RGBA8 byte length of one in-memory image resource.
6pub const MAX_IMAGE_RESOURCE_BYTES: usize = 64 * 1024 * 1024;
7
8/// Maximum combined RGBA8 byte length retained by one `Ui`.
9pub const MAX_IMAGE_RESOURCE_BYTES_PER_UI: usize = 256 * 1024 * 1024;
10
11/// Stable identifier for an image resource owned by one `Ui`.
12///
13/// IDs are monotonic for the lifetime of their owner and are not reused after
14/// release.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct ImageResourceId(pub u64);
17
18/// Stable identifier for an animated image resource.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct AnimationResourceId(pub u64);
21
22/// Number of times an animation should loop.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum LoopCount {
25    /// Plays continuously without stopping.
26    Infinite,
27    /// Plays exactly `N` times (must be greater than zero).
28    Count(u32),
29}
30
31/// One pre-decoded frame in an animated sequence.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct AnimationFrame {
34    /// Image resource providing the pixels for this frame.
35    pub image: ImageResourceId,
36    /// Duration this frame is displayed before advancing.
37    pub delay: Duration,
38}
39
40impl AnimationFrame {
41    /// Creates an animation frame after checking that its delay is non-zero.
42    pub fn new(image: ImageResourceId, delay: Duration) -> GuiResult<Self> {
43        let frame = Self { image, delay };
44        frame.validate()?;
45        Ok(frame)
46    }
47
48    /// Revalidates this frame.
49    pub fn validate(&self) -> GuiResult<()> {
50        if self.delay.is_zero() {
51            return Err(GuiError::Backend(
52                "Animation frame delay must be non-zero".to_owned(),
53            ));
54        }
55        Ok(())
56    }
57}
58
59/// Validated, pre-decoded frame sequence and playback configuration.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct AnimationData {
62    pub frames: Vec<AnimationFrame>,
63    pub loop_count: LoopCount,
64}
65
66impl AnimationData {
67    /// Creates animation data after validating frame count, delays, and loop count.
68    pub fn new(frames: Vec<AnimationFrame>, loop_count: LoopCount) -> GuiResult<Self> {
69        let data = Self { frames, loop_count };
70        data.validate()?;
71        Ok(data)
72    }
73
74    /// Validates this animation sequence.
75    pub fn validate(&self) -> GuiResult<()> {
76        if self.frames.is_empty() {
77            return Err(GuiError::Backend(
78                "Animation data must contain at least one frame".to_owned(),
79            ));
80        }
81        if let LoopCount::Count(0) = self.loop_count {
82            return Err(GuiError::Backend(
83                "Animation loop count must be greater than zero".to_owned(),
84            ));
85        }
86        for frame in &self.frames {
87            frame.validate()?;
88        }
89        Ok(())
90    }
91
92    /// Number of frames in this animation.
93    pub fn frame_count(&self) -> usize {
94        self.frames.len()
95    }
96}
97
98/// Validated, row-major RGBA8 image pixels.
99///
100/// Image resources accept pixels directly; this type does not decode paths or
101/// encoded image formats. Each resource is limited to
102/// [`MAX_IMAGE_RESOURCE_BYTES`].
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct ImageData {
105    width: u32,
106    height: u32,
107    pixels: Vec<u8>,
108}
109
110impl ImageData {
111    /// Creates an RGBA8 image after checking dimensions, byte arithmetic,
112    /// resource bounds, and the exact buffer length.
113    pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> GuiResult<Self> {
114        let data = Self {
115            width,
116            height,
117            pixels,
118        };
119        data.validate()?;
120        Ok(data)
121    }
122
123    /// Revalidates this image before it crosses a backend boundary.
124    pub fn validate(&self) -> GuiResult<()> {
125        let expected = expected_rgba_bytes(self.width, self.height)?;
126        if self.pixels.len() != expected {
127            return Err(GuiError::Backend(format!(
128                "Image data expects {expected} RGBA bytes, found {}",
129                self.pixels.len()
130            )));
131        }
132        Ok(())
133    }
134
135    /// Image width in pixels.
136    pub fn width(&self) -> u32 {
137        self.width
138    }
139
140    /// Image height in pixels.
141    pub fn height(&self) -> u32 {
142        self.height
143    }
144
145    /// Row-major RGBA8 bytes.
146    pub fn pixels(&self) -> &[u8] {
147        &self.pixels
148    }
149
150    pub(crate) fn byte_len(&self) -> usize {
151        self.pixels.len()
152    }
153}
154
155fn expected_rgba_bytes(width: u32, height: u32) -> GuiResult<usize> {
156    if width == 0 || height == 0 {
157        return Err(GuiError::Backend(
158            "Image data dimensions must be positive".to_owned(),
159        ));
160    }
161
162    let expected = usize::try_from(width)
163        .ok()
164        .and_then(|width| {
165            usize::try_from(height)
166                .ok()
167                .and_then(|height| width.checked_mul(height))
168        })
169        .and_then(|pixels| pixels.checked_mul(4))
170        .ok_or_else(|| GuiError::Backend("Image data dimensions overflow byte count".to_owned()))?;
171
172    if expected > MAX_IMAGE_RESOURCE_BYTES {
173        return Err(GuiError::Backend(format!(
174            "Image resource exceeds the {MAX_IMAGE_RESOURCE_BYTES}-byte limit"
175        )));
176    }
177    Ok(expected)
178}
179
180pub(crate) fn checked_total_bytes(current: usize, additional: usize) -> GuiResult<usize> {
181    current
182        .checked_add(additional)
183        .filter(|total| *total <= MAX_IMAGE_RESOURCE_BYTES_PER_UI)
184        .ok_or(GuiError::ResourceExhausted {
185            operation: "image resource allocation",
186            code: None,
187        })
188}
189
190/// Image-resource operations implemented by a backend.
191#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
192pub struct ImageResourceCapabilities {
193    /// Bounded in-memory RGBA8 images can be loaded and released.
194    pub rgba: bool,
195    /// Pre-decoded animated image playback can be scheduled and driven.
196    pub image_animation: bool,
197    /// Encoded animation stream decoding (GIF/APNG/WebP).
198    pub animation_decode: bool,
199}
200
201impl ImageResourceCapabilities {
202    /// Returns a capability set with every operation disabled.
203    pub const fn none() -> Self {
204        Self {
205            rgba: false,
206            image_animation: false,
207            animation_decode: false,
208        }
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate::test_support::MockBackend;
216    use crate::Ui;
217
218    fn rgba(width: u32, height: u32) -> ImageData {
219        ImageData::from_rgba(width, height, vec![7; width as usize * height as usize * 4]).unwrap()
220    }
221
222    #[test]
223    fn rgba_data_validates_dimensions_lengths_overflow_and_bounds() {
224        assert!(ImageData::from_rgba(0, 1, Vec::new()).is_err());
225        assert!(ImageData::from_rgba(1, 0, Vec::new()).is_err());
226        assert!(ImageData::from_rgba(2, 1, vec![0; 7]).is_err());
227        assert!(ImageData::from_rgba(u32::MAX, u32::MAX, Vec::new()).is_err());
228        assert!(
229            ImageData::from_rgba((MAX_IMAGE_RESOURCE_BYTES / 4 + 1) as u32, 1, Vec::new()).is_err()
230        );
231
232        let image = ImageData::from_rgba(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]).unwrap();
233        assert_eq!(image.width(), 2);
234        assert_eq!(image.height(), 1);
235        assert_eq!(image.pixels(), &[1, 2, 3, 4, 5, 6, 7, 8]);
236    }
237
238    #[test]
239    fn image_resources_have_stable_lookup_and_release_lifecycle() {
240        let mut ui = Ui::new(MockBackend::default());
241        let first_data = rgba(2, 1);
242        let first = ui.load_image_resource(&first_data).unwrap();
243        assert_eq!(first, ImageResourceId(1));
244        assert!(ui.image_resource_is_live(first));
245        assert_eq!(ui.backend().image_resource(first), Some(&first_data));
246
247        ui.release_image_resource(first).unwrap();
248        assert!(!ui.image_resource_is_live(first));
249        assert_eq!(ui.backend().image_resource(first), None);
250        assert_eq!(
251            ui.release_image_resource(first),
252            Err(GuiError::Backend("Image resource not found: 1".to_owned()))
253        );
254
255        let second = ui.load_image_resource(&rgba(1, 1)).unwrap();
256        assert_eq!(second, ImageResourceId(2));
257        assert!(ui.image_resource_is_live(second));
258    }
259
260    #[test]
261    fn refused_resource_operations_are_transactional() {
262        let mut backend = MockBackend::default();
263        backend.set_image_resource_capabilities(ImageResourceCapabilities::none());
264        let mut ui = Ui::new(backend);
265        let data = rgba(1, 1);
266
267        assert_eq!(
268            ui.load_image_resource(&data),
269            Err(GuiError::UnsupportedCapability(
270                "image_resource_rgba".to_owned()
271            ))
272        );
273        assert!(!ui.image_resource_is_live(ImageResourceId(1)));
274        assert!(ui.backend().image_resources.is_empty());
275
276        ui.backend_mut()
277            .set_image_resource_capabilities(ImageResourceCapabilities {
278                rgba: true,
279                ..Default::default()
280            });
281        let id = ui.load_image_resource(&data).unwrap();
282        assert_eq!(id, ImageResourceId(1));
283
284        ui.backend_mut()
285            .set_image_resource_capabilities(ImageResourceCapabilities::none());
286        assert_eq!(
287            ui.release_image_resource(id),
288            Err(GuiError::UnsupportedCapability(
289                "image_resource_rgba".to_owned()
290            ))
291        );
292        assert!(ui.image_resource_is_live(id));
293        assert_eq!(ui.backend().image_resource(id), Some(&data));
294
295        ui.backend_mut()
296            .set_image_resource_capabilities(ImageResourceCapabilities {
297                rgba: true,
298                ..Default::default()
299            });
300        ui.release_image_resource(id).unwrap();
301        assert!(!ui.image_resource_is_live(id));
302    }
303
304    #[test]
305    fn per_ui_byte_bound_refuses_before_provider_or_id_mutation() {
306        let mut ui = Ui::new(MockBackend::default());
307        assert!(matches!(
308            checked_total_bytes(MAX_IMAGE_RESOURCE_BYTES_PER_UI, 4),
309            Err(GuiError::ResourceExhausted {
310                operation: "image resource allocation",
311                ..
312            })
313        ));
314        assert_eq!(checked_total_bytes(4, 8).unwrap(), 12);
315        assert_eq!(
316            ui.load_image_resource(&rgba(1, 1)).unwrap(),
317            ImageResourceId(1)
318        );
319    }
320
321    #[test]
322    fn ui_revalidates_image_data_before_backend_calls() {
323        let mut ui = Ui::new(MockBackend::default());
324        let invalid = ImageData {
325            width: 2,
326            height: 1,
327            pixels: vec![0; 7],
328        };
329
330        assert!(ui.load_image_resource(&invalid).is_err());
331        assert!(ui.backend().image_resources.is_empty());
332        assert_eq!(ui.widget_count(), 0);
333    }
334
335    #[test]
336    fn animation_frame_and_data_validation() {
337        assert!(AnimationFrame::new(ImageResourceId(1), Duration::ZERO).is_err());
338        let valid_frame =
339            AnimationFrame::new(ImageResourceId(1), Duration::from_millis(50)).unwrap();
340        assert_eq!(valid_frame.image, ImageResourceId(1));
341        assert_eq!(valid_frame.delay, Duration::from_millis(50));
342
343        // Empty frames rejected
344        assert!(AnimationData::new(vec![], LoopCount::Infinite).is_err());
345
346        // Count(0) rejected
347        assert!(AnimationData::new(vec![valid_frame.clone()], LoopCount::Count(0)).is_err());
348
349        // Valid Count and Infinite
350        let anim_infinite =
351            AnimationData::new(vec![valid_frame.clone()], LoopCount::Infinite).unwrap();
352        assert_eq!(anim_infinite.frame_count(), 1);
353
354        let anim_count = AnimationData::new(
355            vec![
356                valid_frame,
357                AnimationFrame::new(ImageResourceId(2), Duration::from_millis(100)).unwrap(),
358            ],
359            LoopCount::Count(3),
360        )
361        .unwrap();
362        assert_eq!(anim_count.frame_count(), 2);
363    }
364
365    #[test]
366    fn image_resource_capabilities_defaults_and_none() {
367        let none = ImageResourceCapabilities::none();
368        assert!(!none.rgba);
369        assert!(!none.image_animation);
370        assert!(!none.animation_decode);
371
372        let default_caps = ImageResourceCapabilities::default();
373        assert!(!default_caps.rgba);
374        assert!(!default_caps.image_animation);
375        assert!(!default_caps.animation_decode);
376    }
377}