zed/crates/gpui2/src/assets.rs

65 lines
1.6 KiB
Rust
Raw Normal View History

2023-10-04 03:23:32 +00:00
use crate::{size, DevicePixels, Result, SharedString, Size};
use anyhow::anyhow;
use image::{Bgra, ImageBuffer};
use std::{
borrow::Cow,
fmt,
2023-10-04 13:27:51 +00:00
hash::Hash,
2023-10-04 03:23:32 +00:00
sync::atomic::{AtomicUsize, Ordering::SeqCst},
};
pub trait AssetSource: 'static + Send + Sync {
fn load(&self, path: &SharedString) -> Result<Cow<[u8]>>;
fn list(&self, path: &SharedString) -> Result<Vec<SharedString>>;
}
impl AssetSource for () {
fn load(&self, path: &SharedString) -> Result<Cow<[u8]>> {
Err(anyhow!(
"get called on empty asset provider with \"{}\"",
path
))
}
fn list(&self, _path: &SharedString) -> Result<Vec<SharedString>> {
Ok(vec![])
}
}
2023-10-04 13:03:21 +00:00
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ImageId(usize);
2023-10-04 03:23:32 +00:00
pub struct ImageData {
2023-10-04 13:03:21 +00:00
pub id: ImageId,
2023-10-04 03:23:32 +00:00
data: ImageBuffer<Bgra<u8>, Vec<u8>>,
}
impl ImageData {
2023-10-04 13:03:21 +00:00
pub fn new(data: ImageBuffer<Bgra<u8>, Vec<u8>>) -> Self {
2023-10-04 03:23:32 +00:00
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
Self {
2023-10-04 13:03:21 +00:00
id: ImageId(NEXT_ID.fetch_add(1, SeqCst)),
data,
2023-10-04 03:23:32 +00:00
}
}
pub fn as_bytes(&self) -> &[u8] {
&self.data
}
pub fn size(&self) -> Size<DevicePixels> {
let (width, height) = self.data.dimensions();
size(width.into(), height.into())
}
}
impl fmt::Debug for ImageData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ImageData")
.field("id", &self.id)
.field("size", &self.data.dimensions())
.finish()
}
}