notedeck

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

imgcache.rs (1437B)


      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_datadir() -> &'static str {
     29         "cache/img"
     30     }
     31 
     32     pub fn write(cache_dir: &path::Path, url: &str, data: ColorImage) -> Result<()> {
     33         let file_path = cache_dir.join(Self::key(url));
     34         let file = File::options()
     35             .write(true)
     36             .create(true)
     37             .truncate(true)
     38             .open(file_path)?;
     39         let encoder = image::codecs::webp::WebPEncoder::new_lossless(file);
     40 
     41         encoder.encode(
     42             data.as_raw(),
     43             data.size[0] as u32,
     44             data.size[1] as u32,
     45             image::ColorType::Rgba8.into(),
     46         )?;
     47 
     48         Ok(())
     49     }
     50 
     51     pub fn key(url: &str) -> String {
     52         base32::encode(base32::Alphabet::Crockford, url.as_bytes())
     53     }
     54 
     55     pub fn map(&self) -> &ImageCacheMap {
     56         &self.url_imgs
     57     }
     58 
     59     pub fn map_mut(&mut self) -> &mut ImageCacheMap {
     60         &mut self.url_imgs
     61     }
     62 }