S017: thumbnail crate with freedesktop cache, generators and worker pool

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
astar76 2026-11-18 10:10:46 -06:00
commit 3443b12df2
11 changed files with 1084 additions and 27 deletions

288
Cargo.lock generated
View file

@ -506,6 +506,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "block2"
version = "0.5.1"
@ -579,6 +588,12 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@ -780,6 +795,12 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "convert_case"
version = "0.10.0"
@ -899,6 +920,15 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "ctor"
version = "0.10.1"
@ -914,6 +944,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "data-url"
version = "0.3.2"
@ -943,6 +979,17 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@ -1136,6 +1183,12 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fax"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
[[package]]
name = "fdeflate"
version = "0.3.7"
@ -1241,13 +1294,24 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "fontconfig-parser"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
dependencies = [
"roxmltree 0.20.0",
]
[[package]]
name = "fontdb"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"
dependencies = [
"fontconfig-parser",
"log",
"memmap2",
"slotmap",
"tinyvec",
]
@ -1266,8 +1330,8 @@ dependencies = [
"objc2-core-text",
"objc2-foundation 0.3.2",
"parlance",
"read-fonts",
"roxmltree",
"read-fonts 0.41.0",
"roxmltree 0.21.2",
"smallvec",
"windows",
"windows-core",
@ -1605,10 +1669,23 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
[[package]]
name = "harfrust"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "865dcc4105d51c323d8fedbb2d75b5e9c8ecddf5613f74c82f851d0afbc97114"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts 0.46.0",
"smallvec",
"yoke",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
@ -1665,6 +1742,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "i-slint-backend-linuxkms"
version = "1.19.0"
@ -1783,8 +1869,8 @@ dependencies = [
"icu_provider",
"objc2 0.6.5",
"pulldown-cmark",
"resvg",
"skrifa",
"resvg 0.49.0",
"skrifa 0.44.0",
]
[[package]]
@ -1811,12 +1897,12 @@ dependencies = [
"proc-macro2",
"quote",
"rayon",
"resvg",
"resvg 0.49.0",
"rowan",
"rspolib",
"serde",
"serde_json",
"skrifa",
"skrifa 0.44.0",
"smol_str 0.3.7",
"strum",
"swash",
@ -1861,10 +1947,10 @@ dependencies = [
"pin-weak",
"portable-atomic",
"raw-window-handle",
"resvg",
"resvg 0.49.0",
"rgb",
"scopeguard",
"skrifa",
"skrifa 0.44.0",
"slab",
"strum",
"swash",
@ -1936,7 +2022,7 @@ dependencies = [
"objc2-quartz-core 0.3.2",
"pin-weak",
"raw-window-handle",
"read-fonts",
"read-fonts 0.41.0",
"scoped-tls-hkt",
"skia-safe",
"softbuffer",
@ -1964,7 +2050,7 @@ dependencies = [
"i-slint-core",
"lyon_path",
"num-traits",
"skrifa",
"skrifa 0.44.0",
"swash",
"zeno",
]
@ -2193,9 +2279,13 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"tiff",
"zune-core",
"zune-jpeg",
]
@ -2611,6 +2701,32 @@ dependencies = [
"scopeguard",
]
[[package]]
name = "lofty"
version = "0.25.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35d45c446382e04663705aa8e786157f64ef1fa85755d410121ffbf08f54b0db"
dependencies = [
"byteorder",
"data-encoding",
"flate2",
"lofty_attr",
"log",
"ogg_pager",
"paste",
]
[[package]]
name = "lofty_attr"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdbca1b60ba7cea959ffc84ac27f3dbdbacd6dfda168c7eabbc00e48654bb9fd"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "log"
version = "0.4.35"
@ -2669,6 +2785,16 @@ dependencies = [
"serde",
]
[[package]]
name = "md-5"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
@ -3276,6 +3402,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "ogg_pager"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "166611b491f939446e64c6be930843a31eb8e6798204ec3e9f57e084c18e7446"
dependencies = [
"byteorder",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@ -3399,7 +3534,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b74c0d373e462e504ad4436710a39f099e18e848e1ee711f70cd2dcd5a69b290"
dependencies = [
"fontique",
"harfrust",
"harfrust 0.12.0",
"hashbrown 0.17.1",
"icu_locale_core",
"icu_normalizer",
@ -3409,9 +3544,15 @@ dependencies = [
"parlance",
"parley_data",
"parley_emoji",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.2.3"
@ -3747,6 +3888,20 @@ dependencies = [
"once_cell",
]
[[package]]
name = "read-fonts"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330"
dependencies = [
"bytemuck",
"foldhash",
"font-types",
"once_cell",
"smallvec",
"yoke",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
@ -3823,7 +3978,25 @@ dependencies = [
"rgb",
"svgtypes",
"tiny-skia 0.12.0",
"usvg",
"usvg 0.49.0",
"zune-jpeg",
]
[[package]]
name = "resvg"
version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77bb4b284cf8a5c8ae721594af53387fb755d2196fddb32b2acfb4fa9251fa0c"
dependencies = [
"bytemuck",
"gif",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes",
"tiny-skia 0.12.0",
"usvg 0.50.0",
"zune-jpeg",
]
@ -3849,6 +4022,12 @@ dependencies = [
"text-size",
]
[[package]]
name = "roxmltree"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "roxmltree"
version = "0.21.2"
@ -4121,7 +4300,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
name = "skrifa"
version = "0.49.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d"
dependencies = [
"bytemuck",
"once_cell",
"read-fonts 0.46.0",
"smallvec",
"yoke",
]
[[package]]
@ -4400,7 +4592,7 @@ version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e"
dependencies = [
"skrifa",
"skrifa 0.44.0",
"yazi",
"zeno",
]
@ -4539,6 +4731,20 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "tiff"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
dependencies = [
"fax",
"flate2",
"half",
"quick-error",
"weezl",
"zune-jpeg",
]
[[package]]
name = "tiny-skia"
version = "0.11.4"
@ -4773,6 +4979,14 @@ dependencies = [
[[package]]
name = "tunal-thumbs"
version = "0.1.0"
dependencies = [
"image",
"lofty",
"md-5",
"mime_guess",
"png",
"resvg 0.50.0",
]
[[package]]
name = "typed-index-collections"
@ -4784,6 +4998,12 @@ dependencies = [
"serde",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "udev"
version = "0.9.3"
@ -4889,15 +5109,43 @@ dependencies = [
"data-url",
"flate2",
"fontdb",
"harfrust",
"harfrust 0.12.0",
"imagesize",
"kurbo",
"log",
"pico-args",
"roxmltree",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"skrifa",
"skrifa 0.44.0",
"strict-num",
"svgtypes",
"tiny-skia-path 0.12.0",
"unicode-bidi",
"unicode-script",
"unicode-vo",
"xmlwriter",
]
[[package]]
name = "usvg"
version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb896f04730b97805bbc3191fc57e4bf03face0f14577dd42e783c4d8c98802"
dependencies = [
"base64",
"data-url",
"flate2",
"fontdb",
"harfrust 0.15.0",
"imagesize",
"kurbo",
"log",
"pico-args",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"skrifa 0.49.0",
"strict-num",
"svgtypes",
"tiny-skia-path 0.12.0",
@ -5718,7 +5966,7 @@ dependencies = [
"indexmap",
"kurbo",
"log",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]

View file

@ -17,3 +17,7 @@ png = "0.18"
notify-debouncer-mini = { version = "0.7", default-features = false }
mime_guess = "2.0"
jiff = "0.2"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "tiff", "ico"] }
resvg = "0.50"
lofty = "0.25"
md-5 = "0.11"

View file

@ -10,11 +10,11 @@
docs/DECISIONS.md D-004, D-012, D-016; freedesktop thumbnail spec (summarize from memory only what you're sure of; check `~/.cache/thumbnails` layout).
## Steps
- [ ] Cache per the spec: normal 128 / large 256 / x-large 512, MD5 of the file URI, PNG with `Thumb::URI` and `Thumb::MTime` (and `Thumb::Size`), fail entries under `fail/tunal-<version>`.
- [ ] Generators: raster images via `image`, SVG via `resvg`, audio cover via `lofty`, video via `ffmpeg -ss <t> -i <file> -frames:v 1` to PNG on stdout with timeout; timestamp as percent or seconds (default 10%, duration from `ffprobe`). ffmpeg missing → no video thumbnail.
- [ ] Worker pool with priority and cancel; size limit; local files only by default (remote allowed by setting).
- [ ] Example `--example thumb -- <file>` prints the cache path.
- [ ] PROGRESS entry, INDEX line, commit `S017: …`
- [x] Cache per the spec: normal 128 / large 256 / x-large 512, MD5 of the file URI, PNG with `Thumb::URI` and `Thumb::MTime` (and `Thumb::Size`), fail entries under `fail/tunal-<version>`.
- [x] Generators: raster images via `image`, SVG via `resvg`, audio cover via `lofty`, video via `ffmpeg -ss <t> -i <file> -frames:v 1` to PNG on stdout with timeout; timestamp as percent or seconds (default 10%, duration from `ffprobe`). ffmpeg missing → no video thumbnail.
- [x] Worker pool with priority and cancel; size limit; local files only by default (remote allowed by setting).
- [x] Example `--example thumb -- <file>` prints the cache path.
- [x] PROGRESS entry, INDEX line, commit `S017: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.

View file

@ -37,7 +37,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
## 06 Thumbnails
- [ ] [S017 — Thumbnail generation and cache](06%20Thumbnails/S017-thumbnail-crate.md) · Sonnet high
- [x] [S017 — Thumbnail generation and cache](06%20Thumbnails/S017-thumbnail-crate.md) · Sonnet high
- [ ] [S018 — Thumbnails in the views](06%20Thumbnails/S018-thumbnails-in-views.md) · Opus medium
## 07 Tag editor

View file

@ -4,3 +4,11 @@ version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
image.workspace = true
resvg.workspace = true
lofty.workspace = true
md-5.workspace = true
png.workspace = true
mime_guess.workspace = true

View file

@ -0,0 +1,54 @@
//! `cargo run -p tunal-thumbs --example thumb -- [--size normal|large|x-large] <file>...`
//! Prints the cache path of each file's thumbnail (honours `XDG_CACHE_HOME`).
use std::path::PathBuf;
use std::sync::mpsc;
use tunal_thumbs::{Config, Outcome, Priority, Request, ThumbSize, Thumbnailer};
fn main() {
let mut size = ThumbSize::Normal;
let mut files = Vec::new();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if arg == "--size" {
size = match args.next().as_deref() {
Some("normal") => ThumbSize::Normal,
Some("large") => ThumbSize::Large,
Some("x-large") => ThumbSize::XLarge,
_ => usage(),
};
} else {
files.push(arg);
}
}
if files.is_empty() {
usage();
}
let thumbnailer = Thumbnailer::new(Config::default());
let (tx, rx) = mpsc::channel();
for (i, file) in files.iter().enumerate() {
let path = std::path::absolute(PathBuf::from(file)).expect("absolute path");
let tx = tx.clone();
thumbnailer.request(Request {
path,
size,
priority: Priority::Normal,
remote: false,
done: Box::new(move |outcome| tx.send((i, outcome)).unwrap()),
});
}
let mut results: Vec<_> = (0..files.len()).map(|_| rx.recv().unwrap()).collect();
results.sort_by_key(|(i, _)| *i);
for (i, outcome) in results {
match outcome {
Outcome::Ready(p) => println!("{}: {}", files[i], p.display()),
other => println!("{}: {other:?}", files[i]),
}
}
}
fn usage() -> ! {
eprintln!("usage: thumb [--size normal|large|x-large] <file>...");
std::process::exit(1);
}

View file

@ -0,0 +1,176 @@
//! Freedesktop thumbnail cache: paths, validity checks and PNG writing with `Thumb::*` text.
use std::fs::{self, File};
use std::io::BufWriter;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use image::RgbaImage;
use md5::{Digest, Md5};
use crate::ThumbSize;
/// Name of our `fail/` subdirectory, so other apps' failures don't hide files from us.
fn fail_app() -> String {
format!("tunal-{}", env!("CARGO_PKG_VERSION"))
}
/// `$XDG_CACHE_HOME/thumbnails` (or `~/.cache/thumbnails`).
pub fn thumbnail_dir() -> PathBuf {
let base = std::env::var_os("XDG_CACHE_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
.unwrap_or_else(|| PathBuf::from("/tmp"));
base.join("thumbnails")
}
/// `file://` URI of an absolute path, percent-encoded as the spec's MD5 input requires.
pub(crate) fn file_uri(path: &Path) -> String {
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"-_.~/".contains(&b) {
uri.push(b as char);
} else {
uri.push_str(&format!("%{b:02X}"));
}
}
uri
}
fn md5_name(uri: &str) -> String {
let digest = Md5::digest(uri.as_bytes());
let mut name = String::with_capacity(36);
for b in digest {
name.push_str(&format!("{b:02x}"));
}
name.push_str(".png");
name
}
/// Where the thumbnail of `path` lives (or would live) in the cache.
pub fn cache_path(path: &Path, size: ThumbSize) -> PathBuf {
thumbnail_dir()
.join(size.dir_name())
.join(md5_name(&file_uri(path)))
}
fn fail_path(path: &Path) -> PathBuf {
thumbnail_dir()
.join("fail")
.join(fail_app())
.join(md5_name(&file_uri(path)))
}
pub(crate) fn in_cache(path: &Path) -> bool {
path.starts_with(thumbnail_dir())
}
pub(crate) fn mtime_secs(meta: &fs::Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs())
}
/// Reads the `Thumb::MTime` text of a cached PNG.
fn stored_mtime(png_path: &Path) -> Option<u64> {
let decoder = png::Decoder::new(std::io::BufReader::new(File::open(png_path).ok()?));
let reader = decoder.read_info().ok()?;
reader
.info()
.uncompressed_latin1_text
.iter()
.find(|t| t.keyword == "Thumb::MTime")
.and_then(|t| t.text.trim().parse().ok())
}
/// Existing, up-to-date thumbnail.
pub(crate) fn valid(path: &Path, size: ThumbSize, mtime: u64) -> Option<PathBuf> {
let cached = cache_path(path, size);
(stored_mtime(&cached) == Some(mtime)).then_some(cached)
}
/// An earlier failure recorded for this unchanged file.
pub(crate) fn known_failure(path: &Path, mtime: u64) -> bool {
stored_mtime(&fail_path(path)) == Some(mtime)
}
fn write_png(
dest: &Path,
width: u32,
height: u32,
rgba: &[u8],
texts: &[(&str, String)],
) -> std::io::Result<()> {
let dir = dest.parent().expect("cache files have a parent");
fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
let tmp = dir.join(format!(
".tunal-{}-{:x}.tmp",
std::process::id(),
rand_suffix()
));
let result = (|| {
let file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&tmp)?;
let mut encoder = png::Encoder::new(BufWriter::new(file), width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
for (key, value) in texts {
encoder
.add_text_chunk((*key).into(), value.clone())
.map_err(std::io::Error::other)?;
}
let mut writer = encoder.write_header().map_err(std::io::Error::other)?;
writer
.write_image_data(rgba)
.map_err(std::io::Error::other)?;
writer.finish().map_err(std::io::Error::other)?;
fs::rename(&tmp, dest)
})();
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
fn rand_suffix() -> u64 {
use std::hash::{BuildHasher, RandomState};
RandomState::new().hash_one(std::time::SystemTime::now())
}
/// Stores a finished thumbnail and returns its cache path.
pub(crate) fn store(
path: &Path,
size: ThumbSize,
meta: &fs::Metadata,
img: &RgbaImage,
) -> std::io::Result<PathBuf> {
let dest = cache_path(path, size);
let texts = [
("Thumb::URI", file_uri(path)),
("Thumb::MTime", mtime_secs(meta).to_string()),
("Thumb::Size", meta.len().to_string()),
("Software", format!("Tunal {}", env!("CARGO_PKG_VERSION"))),
];
write_png(&dest, img.width(), img.height(), img.as_raw(), &texts)?;
Ok(dest)
}
/// Records a failure (a 1x1 transparent PNG) so the file isn't retried until it changes.
pub(crate) fn store_failure(path: &Path, meta: &fs::Metadata) {
let texts = [
("Thumb::URI", file_uri(path)),
("Thumb::MTime", mtime_secs(meta).to_string()),
];
let _ = write_png(&fail_path(path), 1, 1, &[0, 0, 0, 0], &texts);
}

View file

@ -0,0 +1,275 @@
//! Thumbnail generators: raster images, SVG, embedded cover art and video frames.
use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use image::{DynamicImage, ImageDecoder, ImageReader, RgbaImage, imageops::FilterType};
use lofty::file::TaggedFileExt;
use lofty::picture::PictureType;
/// Which frame of a video to use.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VideoTime {
/// Percent of the duration (from `ffprobe`).
Percent(f64),
Seconds(f64),
}
pub(crate) enum GenError {
Cancelled,
Unsupported,
Failed(String),
}
impl<E: std::fmt::Display> From<E> for GenError {
fn from(e: E) -> Self {
Self::Failed(e.to_string())
}
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Raster,
Svg,
Audio,
Video,
}
fn kind_of(path: &Path) -> Option<Kind> {
let mime = mime_guess::from_path(path).first()?;
match (mime.type_().as_str(), mime.essence_str()) {
(_, "image/svg+xml") => Some(Kind::Svg),
(
_,
"image/png"
| "image/jpeg"
| "image/gif"
| "image/webp"
| "image/bmp"
| "image/tiff"
| "image/x-icon"
| "image/vnd.microsoft.icon",
) => Some(Kind::Raster),
("audio", _) => Some(Kind::Audio),
("video", _) => Some(Kind::Video),
_ => None,
}
}
/// Whether the file type is one we may thumbnail, and whether it is bounded by the size limit.
pub(crate) fn supported(path: &Path) -> Option<bool> {
kind_of(path).map(|k| matches!(k, Kind::Raster | Kind::Svg))
}
/// `ffmpeg` and `ffprobe` can both be started.
pub fn ffmpeg_available() -> bool {
static FOUND: OnceLock<bool> = OnceLock::new();
*FOUND.get_or_init(|| {
["ffmpeg", "ffprobe"].iter().all(|tool| {
Command::new(tool)
.arg("-version")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success())
})
})
}
pub(crate) struct Settings {
pub video_time: VideoTime,
pub tool_timeout: Duration,
}
pub(crate) fn generate(
path: &Path,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<RgbaImage, GenError> {
let img = match kind_of(path).ok_or(GenError::Unsupported)? {
Kind::Raster => raster(path)?,
Kind::Svg => svg(path, px)?,
Kind::Audio => cover(path)?,
Kind::Video => video(path, px, settings, cancel)?,
};
if cancel.load(Ordering::Relaxed) {
return Err(GenError::Cancelled);
}
Ok(fit(img, px))
}
/// Shrinks to fit `px` on the longest edge; never enlarges.
fn fit(img: DynamicImage, px: u32) -> RgbaImage {
if img.width() <= px && img.height() <= px {
img.into_rgba8()
} else {
img.resize(px, px, FilterType::Lanczos3).into_rgba8()
}
}
fn raster(path: &Path) -> Result<DynamicImage, GenError> {
let mut decoder = ImageReader::open(path)?
.with_guessed_format()?
.into_decoder()?;
let orientation = decoder.orientation()?;
let mut img = DynamicImage::from_decoder(decoder)?;
img.apply_orientation(orientation);
Ok(img)
}
fn svg(path: &Path, px: u32) -> Result<DynamicImage, GenError> {
use resvg::{tiny_skia, usvg};
static FONTS: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
let fonts = FONTS.get_or_init(|| {
let mut db = usvg::fontdb::Database::new();
db.load_system_fonts();
Arc::new(db)
});
let options = usvg::Options {
fontdb: fonts.clone(),
font_family: "sans-serif".into(),
..usvg::Options::default()
};
let tree = usvg::Tree::from_data(&std::fs::read(path)?, &options)?;
let size = tree.size();
let scale = px as f32 / size.width().max(size.height());
let width = ((size.width() * scale).round() as u32).max(1);
let height = ((size.height() * scale).round() as u32).max(1);
let mut pixmap = tiny_skia::Pixmap::new(width, height).ok_or("empty SVG")?;
resvg::render(
&tree,
tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
let mut out = RgbaImage::new(width, height);
for (dst, src) in out.pixels_mut().zip(pixmap.pixels()) {
let c = src.demultiply();
dst.0 = [c.red(), c.green(), c.blue(), c.alpha()];
}
Ok(DynamicImage::ImageRgba8(out))
}
fn cover(path: &Path) -> Result<DynamicImage, GenError> {
let tagged = lofty::read_from_path(path)?;
let pictures = || tagged.tags().iter().flat_map(|t| t.pictures());
let picture = pictures()
.find(|p| p.pic_type() == PictureType::CoverFront)
.or_else(|| pictures().next())
.ok_or(GenError::Unsupported)?;
Ok(image::load_from_memory(picture.data())?)
}
/// Runs a tool without a shell; kills it on timeout or cancel. Returns its stdout.
fn run_tool(mut cmd: Command, timeout: Duration, cancel: &AtomicBool) -> Result<Vec<u8>, GenError> {
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let mut stdout = child.stdout.take().expect("stdout is piped");
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.read_to_end(&mut buf);
buf
});
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
let cancelled = cancel.load(Ordering::Relaxed);
if cancelled || Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = reader.join();
return Err(if cancelled {
GenError::Cancelled
} else {
GenError::Failed("timed out".into())
});
}
std::thread::sleep(Duration::from_millis(15));
};
let out = reader.join().unwrap_or_default();
if status.success() {
Ok(out)
} else {
Err(GenError::Failed(format!(
"{:?} exited with {status}",
cmd.get_program()
)))
}
}
fn video_duration(path: &Path, settings: &Settings, cancel: &AtomicBool) -> Result<f64, GenError> {
let mut cmd = Command::new("ffprobe");
cmd.args([
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"csv=p=0",
])
.arg(path);
let out = run_tool(cmd, settings.tool_timeout, cancel)?;
Ok(String::from_utf8_lossy(&out).trim().parse()?)
}
fn video_frame(
path: &Path,
seconds: f64,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<Vec<u8>, GenError> {
let mut cmd = Command::new("ffmpeg");
cmd.args([
"-nostdin",
"-v",
"error",
"-ss",
&format!("{seconds:.3}"),
"-i",
])
.arg(path)
.args(["-frames:v", "1", "-vf"])
.arg(format!(
"scale={px}:{px}:force_original_aspect_ratio=decrease"
))
.args(["-f", "image2pipe", "-c:v", "png", "-"]);
run_tool(cmd, settings.tool_timeout, cancel)
}
fn video(
path: &Path,
px: u32,
settings: &Settings,
cancel: &AtomicBool,
) -> Result<DynamicImage, GenError> {
if !ffmpeg_available() {
return Err(GenError::Unsupported);
}
let seconds = match settings.video_time {
VideoTime::Seconds(s) => s,
// A missing duration (live or odd containers) falls back to the first frame.
VideoTime::Percent(p) => {
video_duration(path, settings, cancel).map_or(0.0, |d| d * p / 100.0)
}
};
let mut frame = video_frame(path, seconds.max(0.0), px, settings, cancel)?;
if frame.is_empty() && seconds > 0.0 {
// The seek point was past the last frame.
frame = video_frame(path, 0.0, px, settings, cancel)?;
}
if frame.is_empty() {
return Err(GenError::Failed("no frame".into()));
}
Ok(image::load_from_memory(&frame)?)
}

View file

@ -1 +1,55 @@
//! Thumbnails for images, video frames and embedded album art.
//! Thumbnails for images, SVG, embedded album art and video frames, stored in the shared
//! freedesktop thumbnail cache (`$XDG_CACHE_HOME/thumbnails`).
//!
//! [`Thumbnailer::request`] queues a file; the result comes back through a callback on a worker
//! thread as an [`Outcome`] holding the cache path of the PNG.
mod cache;
mod generate;
mod pool;
pub use cache::{cache_path, thumbnail_dir};
pub use generate::{VideoTime, ffmpeg_available};
pub use pool::{Config, Outcome, Priority, Request, Thumbnailer, Ticket};
/// The three cache sizes of the freedesktop spec (longest edge in pixels).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ThumbSize {
Normal,
Large,
XLarge,
}
impl ThumbSize {
pub fn pixels(self) -> u32 {
match self {
Self::Normal => 128,
Self::Large => 256,
Self::XLarge => 512,
}
}
pub(crate) fn dir_name(self) -> &'static str {
match self {
Self::Normal => "normal",
Self::Large => "large",
Self::XLarge => "x-large",
}
}
}
/// Why no thumbnail exists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Skip {
/// The file type has no generator, or the tool it needs (ffmpeg) is missing, or the audio
/// file has no cover.
Unsupported,
/// A remote location while remote thumbnails are off.
Remote,
/// Larger than [`Config::max_file_size`].
TooLarge,
/// The file lies inside the thumbnail cache.
InCache,
/// An earlier attempt failed and the file is unchanged.
KnownFailure,
}

View file

@ -0,0 +1,231 @@
//! Worker pool: prioritized, cancellable thumbnail requests.
use std::collections::BinaryHeap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
use crate::cache;
use crate::generate::{self, GenError, Settings, VideoTime};
use crate::{Skip, ThumbSize};
/// Higher runs first; equal priorities run in request order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
/// Prefetch outside the viewport.
Low,
/// Items on screen.
Normal,
/// The item under the pointer or selection.
High,
}
#[derive(Clone, Debug)]
pub struct Config {
pub workers: usize,
/// Images and SVG above this size are skipped (video and audio are read in part only).
pub max_file_size: u64,
/// Thumbnail files on remote locations (requests flagged `remote`).
pub allow_remote: bool,
pub video_time: VideoTime,
/// Limit for one ffmpeg/ffprobe run.
pub tool_timeout: Duration,
}
impl Default for Config {
fn default() -> Self {
Self {
workers: std::thread::available_parallelism().map_or(2, |n| n.get().clamp(1, 4)),
max_file_size: 64 << 20,
allow_remote: false,
video_time: VideoTime::Percent(10.0),
tool_timeout: Duration::from_secs(15),
}
}
}
/// Result of a request, delivered once.
#[derive(Debug, PartialEq, Eq)]
pub enum Outcome {
/// The PNG in the cache.
Ready(PathBuf),
/// No thumbnail, and that is expected.
Skipped(Skip),
/// Generation failed; recorded in `fail/` until the file changes.
Failed(String),
Cancelled,
}
pub struct Request {
/// Absolute path.
pub path: PathBuf,
pub size: ThumbSize,
pub priority: Priority,
/// The file is on a remote location (see [`Config::allow_remote`]).
pub remote: bool,
/// Runs on a worker thread; hand the result to the UI thread from there.
pub done: Box<dyn FnOnce(Outcome) + Send>,
}
/// Cancels a request that has not finished; dropping it does not cancel.
#[derive(Clone)]
pub struct Ticket(Arc<AtomicBool>);
impl Ticket {
/// A queued request is dropped (callback gets `Cancelled`); a running ffmpeg is killed.
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
}
struct Job {
priority: Priority,
seq: u64,
req: Request,
cancel: Arc<AtomicBool>,
}
impl PartialEq for Job {
fn eq(&self, other: &Self) -> bool {
self.seq == other.seq
}
}
impl Eq for Job {}
impl PartialOrd for Job {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Job {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.priority
.cmp(&other.priority)
.then(other.seq.cmp(&self.seq))
}
}
#[derive(Default)]
struct Queue {
heap: BinaryHeap<Job>,
next_seq: u64,
closed: bool,
}
struct Shared {
queue: Mutex<Queue>,
wake: Condvar,
config: Config,
}
/// Thumbnail service; workers stop when it is dropped (running jobs finish first).
pub struct Thumbnailer {
shared: Arc<Shared>,
}
impl Thumbnailer {
pub fn new(config: Config) -> Self {
let shared = Arc::new(Shared {
queue: Mutex::default(),
wake: Condvar::new(),
config,
});
for _ in 0..shared.config.workers.max(1) {
let shared = shared.clone();
std::thread::spawn(move || worker(&shared));
}
Self { shared }
}
pub fn request(&self, req: Request) -> Ticket {
let cancel = Arc::new(AtomicBool::new(false));
let mut queue = self.shared.queue.lock().unwrap();
let seq = queue.next_seq;
queue.next_seq += 1;
queue.heap.push(Job {
priority: req.priority,
seq,
req,
cancel: cancel.clone(),
});
drop(queue);
self.shared.wake.notify_one();
Ticket(cancel)
}
}
impl Drop for Thumbnailer {
fn drop(&mut self) {
self.shared.queue.lock().unwrap().closed = true;
self.shared.wake.notify_all();
}
}
fn worker(shared: &Shared) {
loop {
let job = {
let mut queue = shared.queue.lock().unwrap();
loop {
if queue.closed {
return;
}
if let Some(job) = queue.heap.pop() {
break job;
}
queue = shared.wake.wait(queue).unwrap();
}
};
let outcome = process(&job, &shared.config);
(job.req.done)(outcome);
}
}
fn process(job: &Job, config: &Config) -> Outcome {
let Request {
path, size, remote, ..
} = &job.req;
if job.cancel.load(Ordering::Relaxed) {
return Outcome::Cancelled;
}
if *remote && !config.allow_remote {
return Outcome::Skipped(Skip::Remote);
}
if cache::in_cache(path) {
return Outcome::Skipped(Skip::InCache);
}
let Some(bounded) = generate::supported(path) else {
return Outcome::Skipped(Skip::Unsupported);
};
let meta = match std::fs::metadata(path) {
Ok(m) if m.is_file() => m,
Ok(_) => return Outcome::Skipped(Skip::Unsupported),
Err(e) => return Outcome::Failed(e.to_string()),
};
let mtime = cache::mtime_secs(&meta);
if let Some(ready) = cache::valid(path, *size, mtime) {
return Outcome::Ready(ready);
}
if cache::known_failure(path, mtime) {
return Outcome::Skipped(Skip::KnownFailure);
}
if bounded && meta.len() > config.max_file_size {
return Outcome::Skipped(Skip::TooLarge);
}
let settings = Settings {
video_time: config.video_time,
tool_timeout: config.tool_timeout,
};
match generate::generate(path, size.pixels(), &settings, &job.cancel) {
Ok(img) => match cache::store(path, *size, &meta, &img) {
Ok(dest) => Outcome::Ready(dest),
Err(e) => Outcome::Failed(e.to_string()),
},
Err(GenError::Cancelled) => Outcome::Cancelled,
// No cover, or ffmpeg missing: not a failure of the file, so nothing is recorded.
Err(GenError::Unsupported) => Outcome::Skipped(Skip::Unsupported),
Err(GenError::Failed(reason)) => {
cache::store_failure(path, &meta);
Outcome::Failed(reason)
}
}
}

View file

@ -49,5 +49,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: motion (scale, slide, re-stack, sweep) not watched live (screenshots force reduced motion; software renderer ignores `transform-scale`, D-025); pointer outside-click and hover-open not exercised. Dialog content should hold one focus stop: a `TextField` with text has two (input + clear), so Shift+Tab from its clear button wraps to the last action.
- Later: focus doesn't return to the opener by itself (use `closed` / after `close()`); a menu opened from a button flips to end at the anchor point, not above the button.
## S017 — Thumbnail generation and cache
- Done: `tunal-thumbs`. `Thumbnailer::new(Config { workers, max_file_size (64 MiB, images/SVG only), allow_remote, video_time: VideoTime::Percent(10)|Seconds, tool_timeout (15 s) })`; `request(Request { path (absolute), size: ThumbSize::{Normal 128, Large 256, XLarge 512}, priority: Priority::{Low, Normal, High}, remote, done: Box<dyn FnOnce(Outcome) + Send> }) -> Ticket` (`cancel()`: queued job → `Cancelled`, running ffmpeg killed). `done` runs on a worker thread. `Outcome::{Ready(cache PNG path), Skipped(Skip::{Unsupported, Remote, TooLarge, InCache, KnownFailure}), Failed(String), Cancelled}`. Also `cache_path(path, size)`, `thumbnail_dir()`, `ffmpeg_available()`.
- Cache: `$XDG_CACHE_HOME/thumbnails/{normal,large,x-large}/<md5 of file URI>.png` with `Thumb::URI/MTime/Size`, atomic write, 0700/0600; a thumbnail is valid while `Thumb::MTime` matches; failures in `fail/tunal-<version>/` (1×1 PNG) until the file changes. Generators: `image` (EXIF orientation applied), `resvg` (system fonts), `lofty` cover (front cover first), `ffprobe` duration + `ffmpeg -ss … -frames:v 1` PNG on stdout (no shell, killed on timeout/cancel; seek past end → first frame). ffmpeg missing or audio without cover → `Skipped(Unsupported)`, no fail entry.
- Verified: build, clippy -D warnings (workspace), fmt --check; `XDG_CACHE_HOME=<scratch> --example thumb` on PNG, SVG, MP3 with cover, MP4 (looked at SVG and video PNGs), MP3 without cover (skipped), corrupt PNG (Failed, then KnownFailure), file inside the cache (skipped), missing ffmpeg via PATH (skipped), all three sizes. Workspace deps added: image, resvg, lofty, md-5.
- Not done: cancel and timeout paths not exercised (code only); SVG `<text>` did not render in the smoke run (system fonts not found in this environment; geometry fine); local files only — remote requests are gated by the flag, the pool reads `std::fs` (S018/UI must hand remote files over another way).
- Later: stale-thumbnail cleanup; video thumbnails of very short clips use first frame only when seek fails.
## Later
-