1use crate::{size, DevicePixels, Result, SharedString, Size};
2use smallvec::SmallVec;
3
4use image::{Delay, Frame};
5use std::{
6 borrow::Cow,
7 fmt,
8 hash::Hash,
9 sync::atomic::{AtomicUsize, Ordering::SeqCst},
10};
11
12/// A source of assets for this app to use.
13pub trait AssetSource: 'static + Send + Sync {
14 /// Load the given asset from the source path.
15 fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>>;
16
17 /// List the assets at the given path.
18 fn list(&self, path: &str) -> Result<Vec<SharedString>>;
19}
20
21impl AssetSource for () {
22 fn load(&self, _path: &str) -> Result<Option<Cow<'static, [u8]>>> {
23 Ok(None)
24 }
25
26 fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
27 Ok(vec![])
28 }
29}
30
31/// A unique identifier for the image cache
32#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
33pub struct ImageId(usize);
34
35#[derive(PartialEq, Eq, Hash, Clone)]
36pub(crate) struct RenderImageParams {
37 pub(crate) image_id: ImageId,
38 pub(crate) frame_index: usize,
39}
40
41/// A cached and processed image.
42pub struct ImageData {
43 /// The ID associated with this image
44 pub id: ImageId,
45 data: SmallVec<[Frame; 1]>,
46}
47
48impl ImageData {
49 /// Create a new image from the given data.
50 pub fn new(data: impl Into<SmallVec<[Frame; 1]>>) -> Self {
51 static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
52
53 Self {
54 id: ImageId(NEXT_ID.fetch_add(1, SeqCst)),
55 data: data.into(),
56 }
57 }
58
59 /// Convert this image into a byte slice.
60 pub fn as_bytes(&self, frame_index: usize) -> &[u8] {
61 &self.data[frame_index].buffer()
62 }
63
64 /// Get the size of this image, in pixels.
65 pub fn size(&self, frame_index: usize) -> Size<DevicePixels> {
66 let (width, height) = self.data[frame_index].buffer().dimensions();
67 size(width.into(), height.into())
68 }
69
70 /// Get the delay of this frame from the previous
71 pub fn delay(&self, frame_index: usize) -> Delay {
72 self.data[frame_index].delay()
73 }
74
75 /// Get the number of frames for this image.
76 pub fn frame_count(&self) -> usize {
77 self.data.len()
78 }
79}
80
81impl fmt::Debug for ImageData {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.debug_struct("ImageData")
84 .field("id", &self.id)
85 .field("size", &self.size(0))
86 .finish()
87 }
88}