notedeck

One damus client to rule them all
git clone git://jb55.com/notedeck
Log | Files | Refs | README | LICENSE

imgcache.rs (1890B)


      1 use crate::Result;
      2 use egui::TextureHandle;
      3 use poll_promise::Promise;
      4 
      5 use egui::ColorImage;
      6 
      7 use std::collections::HashMap;
      8 use std::fs::File;
      9 
     10 use std::path;
     11 
     12 pub type ImageCacheValue = Promise<Result<TextureHandle>>;
     13 pub type ImageCacheMap = HashMap<String, ImageCacheValue>;
     14 
     15 pub struct ImageCache {
     16     pub cache_dir: path::PathBuf,
     17     url_imgs: ImageCacheMap,
     18 }
     19 
     20 impl ImageCache {
     21     pub fn new(cache_dir: path::PathBuf) -> Self {
     22         Self {
     23             cache_dir,
     24             url_imgs: HashMap::new(),
     25         }
     26     }
     27 
     28     pub fn rel_dir() -> &'static str {
     29         "img"
     30     }
     31 
     32     /*
     33     pub fn fetch(image: &str) -> Result<Image> {
     34         let m_cached_promise = img_cache.map().get(image);
     35         if m_cached_promise.is_none() {
     36             let res = crate::images::fetch_img(
     37                 img_cache,
     38                 ui.ctx(),
     39                 &image,
     40                 ImageType::Content(width.round() as u32, height.round() as u32),
     41             );
     42             img_cache.map_mut().insert(image.to_owned(), res);
     43         }
     44     }
     45     */
     46 
     47     pub fn write(cache_dir: &path::Path, url: &str, data: ColorImage) -> Result<()> {
     48         let file_path = cache_dir.join(Self::key(url));
     49         let file = File::options()
     50             .write(true)
     51             .create(true)
     52             .truncate(true)
     53             .open(file_path)?;
     54         let encoder = image::codecs::webp::WebPEncoder::new_lossless(file);
     55 
     56         encoder.encode(
     57             data.as_raw(),
     58             data.size[0] as u32,
     59             data.size[1] as u32,
     60             image::ColorType::Rgba8.into(),
     61         )?;
     62 
     63         Ok(())
     64     }
     65 
     66     pub fn key(url: &str) -> String {
     67         base32::encode(base32::Alphabet::Crockford, url.as_bytes())
     68     }
     69 
     70     pub fn map(&self) -> &ImageCacheMap {
     71         &self.url_imgs
     72     }
     73 
     74     pub fn map_mut(&mut self) -> &mut ImageCacheMap {
     75         &mut self.url_imgs
     76     }
     77 }