Skip to main content

lgui_assets/
resolver.rs

1use std::io::Read;
2use std::sync::Arc;
3
4use super::{AssetBytes, AssetError, ImageData};
5
6pub trait AssetResolver: Send + Sync + 'static {
7    fn resolve(&self, id: &str) -> Result<AssetBytes, AssetError>;
8}
9
10pub trait ImageLoader: Send + Sync + 'static {
11    fn decode(&self, bytes: &[u8]) -> Result<ImageData, AssetError>;
12}
13
14pub trait RemoteImageLoader: Send + Sync + 'static {
15    fn load(&self, url: &str) -> Result<AssetBytes, AssetError>;
16
17    fn load_response(
18        &self,
19        url: &str,
20        _etag: Option<&str>,
21        _last_modified: Option<&str>,
22    ) -> Result<RemoteImageResponse, AssetError> {
23        self.load(url).map(RemoteImageResponse::from_bytes)
24    }
25}
26
27#[derive(Clone, Debug)]
28pub struct RemoteImageResponse {
29    pub bytes: Option<AssetBytes>,
30    pub mime: Option<String>,
31    pub etag: Option<String>,
32    pub last_modified: Option<String>,
33    pub not_modified: bool,
34}
35
36impl RemoteImageResponse {
37    pub fn from_bytes(bytes: AssetBytes) -> Self {
38        Self {
39            bytes: Some(bytes),
40            mime: None,
41            etag: None,
42            last_modified: None,
43            not_modified: false,
44        }
45    }
46
47    fn not_modified() -> Self {
48        Self {
49            bytes: None,
50            mime: None,
51            etag: None,
52            last_modified: None,
53            not_modified: true,
54        }
55    }
56}
57
58#[derive(Clone)]
59#[allow(dead_code)]
60pub struct RemoteImageLoaderHandle(Arc<dyn RemoteImageLoader>);
61
62impl RemoteImageLoaderHandle {
63    pub fn new(loader: impl RemoteImageLoader) -> Self {
64        Self(Arc::new(loader))
65    }
66
67    #[doc(hidden)]
68    pub fn load(&self, url: &str) -> Result<AssetBytes, AssetError> {
69        self.0.load(url)
70    }
71
72    #[cfg(feature = "persistent-cache")]
73    pub(crate) fn load_response(
74        &self,
75        url: &str,
76        etag: Option<&str>,
77        last_modified: Option<&str>,
78    ) -> Result<RemoteImageResponse, AssetError> {
79        self.0.load_response(url, etag, last_modified)
80    }
81}
82
83#[derive(Clone, Copy, Debug, Default)]
84pub struct HttpImageLoader;
85
86impl RemoteImageLoader for HttpImageLoader {
87    fn load(&self, url: &str) -> Result<AssetBytes, AssetError> {
88        self.load_response(url, None, None)?
89            .bytes
90            .ok_or_else(|| AssetError::InvalidData("image response had no body".to_owned()))
91    }
92
93    fn load_response(
94        &self,
95        url: &str,
96        etag: Option<&str>,
97        last_modified: Option<&str>,
98    ) -> Result<RemoteImageResponse, AssetError> {
99        const MAX_IMAGE_BYTES: u64 = 32 * 1024 * 1024;
100        if !url.starts_with("https://") && !url.starts_with("http://") {
101            return Err(AssetError::Unsupported(
102                "remote images must use http or https".to_owned(),
103            ));
104        }
105        let mut request = ureq::get(url);
106        if let Some(etag) = etag {
107            request = request.set("If-None-Match", etag);
108        }
109        if let Some(last_modified) = last_modified {
110            request = request.set("If-Modified-Since", last_modified);
111        }
112        let response = match request.call() {
113            Ok(response) if response.status() == 304 => {
114                return Ok(RemoteImageResponse::not_modified())
115            }
116            Ok(response) => response,
117            Err(ureq::Error::Status(304, _)) => return Ok(RemoteImageResponse::not_modified()),
118            Err(error) => return Err(AssetError::NotFound(error.to_string())),
119        };
120        let mime = response.header("Content-Type").map(str::to_owned);
121        let response_etag = response.header("ETag").map(str::to_owned);
122        let response_last_modified = response.header("Last-Modified").map(str::to_owned);
123        let mut bytes = Vec::new();
124        response
125            .into_reader()
126            .take(MAX_IMAGE_BYTES + 1)
127            .read_to_end(&mut bytes)
128            .map_err(|error| AssetError::InvalidData(error.to_string()))?;
129        if bytes.len() as u64 > MAX_IMAGE_BYTES {
130            return Err(AssetError::InvalidData(
131                "remote image exceeds the 32 MiB limit".to_owned(),
132            ));
133        }
134        Ok(RemoteImageResponse {
135            bytes: Some(Arc::from(bytes)),
136            mime,
137            etag: response_etag,
138            last_modified: response_last_modified,
139            not_modified: false,
140        })
141    }
142}
143
144pub fn http_image_loader() -> RemoteImageLoaderHandle {
145    RemoteImageLoaderHandle::new(HttpImageLoader)
146}