use std::{
cell::RefCell,
hash::{Hash as _, Hasher as _},
path::Path,
rc::Rc,
sync::Arc,
};
use gpui_kit::{
App, ImgResourceLoader, ObjectFit, RenderImage, Resource, SharedString, SharedUri, Window,
};
use rustc_hash::{FxHashMap, FxHasher};
use super::{LiveGridDelegate, LiveGridState};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ImageFit {
#[default]
Contain,
Cover,
Fill,
ScaleDown,
None,
}
impl ImageFit {
pub(crate) fn object_fit(self) -> ObjectFit {
match self {
Self::Contain => ObjectFit::Contain,
Self::Cover => ObjectFit::Cover,
Self::Fill => ObjectFit::Fill,
Self::ScaleDown => ObjectFit::ScaleDown,
Self::None => ObjectFit::None,
}
}
}
#[derive(Clone)]
#[non_exhaustive]
pub enum CellImage {
Ready(Arc<RenderImage>),
Loading,
Missing,
}
pub trait CellImageSource: 'static {
fn image(&self, id: &str, window: &mut Window, cx: &mut App) -> CellImage;
}
#[derive(Clone)]
#[non_exhaustive]
pub enum CellImages {
Assets(AssetImageSource),
Custom(Arc<dyn CellImageSource>),
}
impl Default for CellImages {
fn default() -> Self {
Self::Assets(AssetImageSource::default())
}
}
impl From<AssetImageSource> for CellImages {
fn from(source: AssetImageSource) -> Self {
Self::Assets(source)
}
}
impl From<Arc<dyn CellImageSource>> for CellImages {
fn from(source: Arc<dyn CellImageSource>) -> Self {
Self::Custom(source)
}
}
impl CellImages {
pub fn custom(source: impl CellImageSource) -> Self {
Self::Custom(Arc::new(source))
}
pub(crate) fn begin_frame(&self) {
if let Self::Assets(source) = self {
source.begin_frame();
}
}
#[inline]
pub(crate) fn image(&self, id: &str, window: &mut Window, cx: &mut App) -> CellImage {
match self {
Self::Assets(source) => source.image(id, window, cx),
Self::Custom(source) => source.image(id, window, cx),
}
}
}
#[derive(Clone, Default)]
pub struct AssetImageSource {
cache: Rc<RefCell<ImageCache>>,
}
#[derive(Default)]
struct ImageCache {
entries: FxHashMap<u64, ImageEntry>,
capacity: Option<usize>,
lookups: u64,
frame: u64,
asset_requests: u64,
}
struct ImageEntry {
id: Box<str>,
resource: Resource,
image: CellImage,
last_used: u64,
frame: u64,
}
impl AssetImageSource {
pub fn with_capacity(self, capacity: usize) -> Self {
self.cache.borrow_mut().capacity = Some(capacity.max(1));
self
}
pub fn asset_requests(&self) -> u64 {
self.cache.borrow().asset_requests
}
pub fn len(&self) -> usize {
self.cache.borrow().entries.len()
}
pub fn is_empty(&self) -> bool {
self.cache.borrow().entries.is_empty()
}
fn begin_frame(&self) {
self.cache.borrow_mut().frame += 1;
}
}
fn resource(id: &str) -> Resource {
if id.starts_with("http://") || id.starts_with("https://") {
Resource::Uri(SharedUri::from(id.to_owned()))
} else if Path::new(id).is_absolute() {
Resource::Path(Path::new(id).into())
} else {
Resource::Embedded(SharedString::from(id.to_owned()))
}
}
impl CellImageSource for AssetImageSource {
fn image(&self, id: &str, window: &mut Window, cx: &mut App) -> CellImage {
let mut hasher = FxHasher::default();
id.hash(&mut hasher);
let key = hasher.finish();
let mut cache = self.cache.borrow_mut();
cache.lookups += 1;
let (lookup, frame) = (cache.lookups, cache.frame);
let known = cache
.entries
.get(&key)
.is_some_and(|entry| &*entry.id == id);
if !known {
cache.make_room(window, cx);
cache.entries.insert(
key,
ImageEntry {
id: id.into(),
resource: resource(id),
image: CellImage::Loading,
last_used: lookup,
frame,
},
);
}
let ImageCache {
entries,
asset_requests,
..
} = &mut *cache;
let entry = entries.get_mut(&key).expect("inserted above");
entry.last_used = lookup;
entry.frame = frame;
if let CellImage::Loading = entry.image {
*asset_requests += 1;
entry.image = match window.use_asset::<ImgResourceLoader>(&entry.resource, cx) {
None => CellImage::Loading,
Some(Ok(image)) => CellImage::Ready(image),
Some(Err(_)) => CellImage::Missing,
};
}
entry.image.clone()
}
}
impl ImageCache {
fn make_room(&mut self, window: &mut Window, cx: &mut App) {
let Some(capacity) = self.capacity else {
return;
};
while self.entries.len() >= capacity {
let frame = self.frame;
let Some(oldest) = self
.entries
.iter()
.filter(|(_, entry)| entry.frame != frame)
.min_by_key(|(_, entry)| entry.last_used)
.map(|(key, _)| *key)
else {
return;
};
let entry = self.entries.remove(&oldest).expect("found above");
cx.remove_asset::<ImgResourceLoader>(&entry.resource);
if let CellImage::Ready(image) = entry.image {
let _ = window.drop_image(image);
}
}
}
}
impl<D: LiveGridDelegate> LiveGridState<D> {
pub fn with_image_source(mut self, source: impl Into<CellImages>) -> Self {
self.images = source.into();
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_resource() {
assert!(matches!(
resource("https://example.com/a.png"),
Resource::Uri(uri) if uri.as_ref() == "https://example.com/a.png"
));
assert!(matches!(
resource("http://localhost/a.png"),
Resource::Uri(_)
));
#[cfg(not(windows))]
assert!(matches!(
resource("/tmp/a.png"),
Resource::Path(path) if path.as_ref() == Path::new("/tmp/a.png")
));
assert!(matches!(
resource("images/a.png"),
Resource::Embedded(path) if path.as_ref() == "images/a.png"
));
}
}