Skip to main content

background_picker/
cache.rs

1//! Freedesktop.org thumbnail cache directory, hashing, and validity rules.
2//! See <https://specifications.freedesktop.org/thumbnail-spec/>.
3
4use 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
13/// Returns (creating it if necessary) the freedesktop "normal" thumbnail cache directory.
14///
15/// # Errors
16///
17/// Returns an error if the directory cannot be created.
18pub 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/// Computes the SHA1 hash of the file's `file://` URI, matching the hash used by
30/// pcmanfm and other freedesktop-compliant file managers for thumbnail cache keys.
31#[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/// The path this app would use to cache a thumbnail for `file_path` inside `cache_dir`.
49#[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/// A cached thumbnail is valid as long as it exists and is not older than the source file.
55#[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/// Looks for a thumbnail already created by another application (file manager, etc.),
73/// checking freedesktop-standard cache sizes in order of preference.
74#[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}