background_picker/
cache.rs1use std::fmt::Write;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::time::SystemTime;
8
9use sha1::{Digest, Sha1};
10
11use crate::error::{BackgroundPickerError, Result};
12
13pub fn thumbnail_cache_dir() -> Result<PathBuf> {
19 let cache_home = dirs::cache_dir()
20 .or_else(|| dirs::home_dir().map(|h| h.join(".cache")))
21 .unwrap_or_else(|| PathBuf::from(".cache"));
22
23 let normal_dir = cache_home.join("thumbnails").join("normal");
24 fs::create_dir_all(&normal_dir).map_err(BackgroundPickerError::CacheDirectoryCreation)?;
25
26 Ok(normal_dir)
27}
28
29#[must_use]
32pub fn thumbnail_hash(file_path: &Path) -> String {
33 let canonicalized = fs::canonicalize(file_path).unwrap_or_else(|_| file_path.to_path_buf());
34 let file_uri = format!("file://{}", canonicalized.to_string_lossy());
35
36 let mut hasher = Sha1::new();
37 hasher.update(file_uri.as_bytes());
38
39 hasher
40 .finalize()
41 .iter()
42 .fold(String::with_capacity(40), |mut hex, byte| {
43 let _ = write!(hex, "{byte:02x}");
44 hex
45 })
46}
47
48#[must_use]
50pub fn cached_thumbnail_path(file_path: &Path, cache_dir: &Path) -> PathBuf {
51 cache_dir.join(format!("{}.png", thumbnail_hash(file_path)))
52}
53
54#[must_use]
56pub fn is_cache_valid(original_path: &Path, cache_path: &Path) -> bool {
57 if !cache_path.exists() {
58 return false;
59 }
60
61 let original_modified = fs::metadata(original_path)
62 .and_then(|m| m.modified())
63 .unwrap_or(SystemTime::UNIX_EPOCH);
64
65 let cache_modified = fs::metadata(cache_path)
66 .and_then(|m| m.modified())
67 .unwrap_or(SystemTime::UNIX_EPOCH);
68
69 cache_modified >= original_modified
70}
71
72#[must_use]
75pub fn find_existing_thumbnail(file_path: &Path) -> Option<PathBuf> {
76 let thumbnails_dir = dirs::cache_dir()?.join("thumbnails");
77 let thumbnail_name = format!("{}.png", thumbnail_hash(file_path));
78
79 ["normal", "large"].into_iter().find_map(|size_dir| {
80 let thumbnail_path = thumbnails_dir.join(size_dir).join(&thumbnail_name);
81 (thumbnail_path.exists() && is_cache_valid(file_path, &thumbnail_path))
82 .then_some(thumbnail_path)
83 })
84}