1use std::sync::Arc;
42use std::time::Duration;
43
44use egui_pop_api::files::preview::{Handles, Preview, PreviewProvider, PreviewRequest};
45use egui_pop_api::files::{self, FILES};
46use egui_pop_api::{Ctx, Plugin, PluginError};
47use egui_pop_model::ids::PluginId;
48
49pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.thumbnails");
51
52pub const PROVIDER: &str = "egui_pop.system_thumbnails";
54
55#[derive(Clone, Debug)]
57pub struct SystemThumbnails {
58 pub timeout: Duration,
60}
61
62impl Default for SystemThumbnails {
63 fn default() -> Self {
64 Self {
65 timeout: Duration::from_secs(10),
66 }
67 }
68}
69
70pub fn available() -> Result<(), String> {
72 if cfg!(target_arch = "wasm32") {
73 Err("the web has no system thumbnails".into())
74 } else if cfg!(target_os = "windows") {
75 Err("system thumbnails are not available on Windows yet".into())
76 } else if cfg!(target_os = "macos") {
77 Err("system thumbnails (QuickLook) are not available on macOS yet".into())
78 } else {
79 Ok(())
80 }
81}
82
83impl PreviewProvider for SystemThumbnails {
84 fn id(&self) -> &str {
85 PROVIDER
86 }
87
88 fn handles(&self) -> Handles {
89 Handles::new().mime(&["*/*"])
90 }
91
92 fn priority(&self) -> i32 {
93 -100
94 }
95
96 fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
97 if cfg!(target_arch = "wasm32") || !request.fs().is_native() {
98 return Ok(None);
99 }
100 available()?;
101 system(request, self.timeout)
102 }
103}
104
105#[cfg(all(
106 unix,
107 not(target_os = "macos"),
108 not(target_os = "ios"),
109 not(target_os = "android")
110))]
111fn system(request: &PreviewRequest, timeout: Duration) -> Result<Option<Preview>, String> {
112 freedesktop::preview(request, timeout)
113}
114
115#[cfg(not(all(
116 unix,
117 not(target_os = "macos"),
118 not(target_os = "ios"),
119 not(target_os = "android")
120)))]
121fn system(_request: &PreviewRequest, _timeout: Duration) -> Result<Option<Preview>, String> {
122 Ok(None)
123}
124
125#[derive(Clone, Debug, Default)]
127pub struct ThumbnailsPlugin {
128 provider: SystemThumbnails,
129}
130
131impl ThumbnailsPlugin {
132 pub fn timeout(mut self, timeout: Duration) -> Self {
134 self.provider.timeout = timeout;
135 self
136 }
137}
138
139impl Plugin for ThumbnailsPlugin {
140 fn id(&self) -> PluginId {
141 PLUGIN
142 }
143
144 fn title(&self) -> String {
145 "System thumbnails".into()
146 }
147
148 fn requires(&self) -> Vec<PluginId> {
149 vec![files::PLUGIN]
150 }
151
152 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
153 let files = ctx
154 .app()
155 .service(&FILES)
156 .ok_or_else(|| PluginError::Failed("the files plugin is not connected".into()))?;
157 files.previews().register(Arc::new(self.provider.clone()));
158 Ok(())
159 }
160}
161
162pub fn md5_hex(data: &[u8]) -> String {
164 const S: [u32; 64] = [
165 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5,
166 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10,
167 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
168 ];
169 const K: [u32; 64] = [
171 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
172 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
173 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
174 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
175 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
176 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
177 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
178 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
179 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
180 0xeb86d391,
181 ];
182 let mut msg = data.to_vec();
183 let bits = (data.len() as u64).wrapping_mul(8);
184 msg.push(0x80);
185 while msg.len() % 64 != 56 {
186 msg.push(0);
187 }
188 msg.extend_from_slice(&bits.to_le_bytes());
189 let (mut a0, mut b0, mut c0, mut d0) = (
190 0x6745_2301u32,
191 0xefcd_ab89u32,
192 0x98ba_dcfeu32,
193 0x1032_5476u32,
194 );
195 for chunk in msg.chunks(64) {
196 let m: Vec<u32> = chunk
197 .chunks(4)
198 .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]]))
199 .collect();
200 let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
201 for i in 0..64 {
202 let (f, g) = match i / 16 {
203 0 => ((b & c) | (!b & d), i),
204 1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
205 2 => (b ^ c ^ d, (3 * i + 5) % 16),
206 _ => (c ^ (b | !d), (7 * i) % 16),
207 };
208 let f = f.wrapping_add(a).wrapping_add(K[i]).wrapping_add(m[g]);
209 a = d;
210 d = c;
211 c = b;
212 b = b.wrapping_add(f.rotate_left(S[i]));
213 }
214 a0 = a0.wrapping_add(a);
215 b0 = b0.wrapping_add(b);
216 c0 = c0.wrapping_add(c);
217 d0 = d0.wrapping_add(d);
218 }
219 [a0, b0, c0, d0]
220 .iter()
221 .flat_map(|w| w.to_le_bytes())
222 .map(|b| format!("{b:02x}"))
223 .collect()
224}
225
226pub fn file_uri(path: &std::path::Path) -> String {
229 let mut out = String::from("file://");
230 for &b in path.to_string_lossy().as_bytes() {
231 let keep = b.is_ascii_alphanumeric()
232 || matches!(
233 b,
234 b'-' | b'_'
235 | b'.'
236 | b'~'
237 | b'/'
238 | b'!'
239 | b'$'
240 | b'&'
241 | b'\''
242 | b'('
243 | b')'
244 | b'*'
245 | b'+'
246 | b','
247 | b';'
248 | b'='
249 | b':'
250 | b'@'
251 );
252 if keep {
253 out.push(b as char);
254 } else {
255 out.push_str(&format!("%{b:02X}"));
256 }
257 }
258 out
259}
260
261pub fn png_texts(png: &[u8]) -> Vec<(String, String)> {
263 let mut out = Vec::new();
264 if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
265 return out;
266 }
267 let mut at = 8;
268 while at + 8 <= png.len() {
269 let len = u32::from_be_bytes([png[at], png[at + 1], png[at + 2], png[at + 3]]) as usize;
270 let kind = &png[at + 4..at + 8];
271 let Some(data) = png.get(at + 8..at + 8 + len) else {
272 break;
273 };
274 if kind == b"tEXt"
275 && let Some(nul) = data.iter().position(|b| *b == 0)
276 {
277 out.push((
278 String::from_utf8_lossy(&data[..nul]).into_owned(),
279 String::from_utf8_lossy(&data[nul + 1..]).into_owned(),
280 ));
281 }
282 if kind == b"IDAT" || kind == b"IEND" {
283 break;
284 }
285 at += 12 + len;
286 }
287 out
288}
289
290#[cfg(all(
291 unix,
292 not(target_os = "macos"),
293 not(target_os = "ios"),
294 not(target_os = "android")
295))]
296mod freedesktop {
297 use std::path::{Path, PathBuf};
298 use std::process::{Command, Stdio};
299 use std::sync::Arc;
300 use std::sync::atomic::{AtomicU64, Ordering};
301 use std::time::{Duration, Instant, SystemTime};
302
303 use egui_pop_api::files::preview::{self, Body, Preview, PreviewRequest};
304
305 use super::{file_uri, md5_hex, png_texts};
306
307 fn sizes(max_side: u32) -> [&'static str; 4] {
309 if max_side <= 128 {
310 ["normal", "large", "x-large", "xx-large"]
311 } else if max_side <= 256 {
312 ["large", "x-large", "normal", "xx-large"]
313 } else {
314 ["x-large", "xx-large", "large", "normal"]
315 }
316 }
317
318 fn home() -> Option<PathBuf> {
319 std::env::var_os("HOME").map(PathBuf::from)
320 }
321
322 fn cache_dir() -> Option<PathBuf> {
323 std::env::var_os("XDG_CACHE_HOME")
324 .map(PathBuf::from)
325 .filter(|p| p.is_absolute())
326 .or_else(|| home().map(|h| h.join(".cache")))
327 .map(|c| c.join("thumbnails"))
328 }
329
330 fn data_dirs() -> Vec<PathBuf> {
332 let mut out = Vec::new();
333 if let Some(d) = std::env::var_os("XDG_DATA_HOME")
334 .map(PathBuf::from)
335 .filter(|p| p.is_absolute())
336 .or_else(|| home().map(|h| h.join(".local/share")))
337 {
338 out.push(d);
339 }
340 let dirs = std::env::var("XDG_DATA_DIRS")
341 .ok()
342 .filter(|d| !d.is_empty())
343 .unwrap_or_else(|| "/usr/local/share:/usr/share".into());
344 out.extend(dirs.split(':').filter(|d| !d.is_empty()).map(PathBuf::from));
345 out
346 }
347
348 fn mtime(t: Option<SystemTime>) -> Option<u64> {
349 t?.duration_since(SystemTime::UNIX_EPOCH)
350 .ok()
351 .map(|d| d.as_secs())
352 }
353
354 fn decode(bytes: &[u8], request: &PreviewRequest) -> Result<Preview, String> {
357 let image = image::load_from_memory(bytes).map_err(|e| e.to_string())?;
358 let side = request.max_side;
359 let image = if image.width().max(image.height()) > side {
360 image.thumbnail(side, side)
361 } else {
362 image
363 };
364 let rgba = image.to_rgba8();
365 let pixels = egui::ColorImage::from_rgba_unmultiplied(
366 [rgba.width() as usize, rgba.height() as usize],
367 rgba.as_raw(),
368 );
369 let mut p = Preview::new(Body::Image(Arc::new(pixels)));
370 let texts = png_texts(bytes);
371 let get = |k: &str| {
372 texts
373 .iter()
374 .find(|(key, _)| key == k)
375 .and_then(|(_, v)| v.parse::<u32>().ok())
376 };
377 if let (Some(w), Some(h)) = (get("Thumb::Image::Width"), get("Thumb::Image::Height")) {
378 p = p.dimensions(w, h);
379 }
380 if let Some(n) = get("Thumb::Document::Pages") {
381 p = p.pages(n);
382 }
383 Ok(p)
384 }
385
386 fn cached(path: &Path, request: &PreviewRequest) -> Option<Preview> {
388 let dir = cache_dir()?;
389 let name = format!("{}.png", md5_hex(file_uri(path).as_bytes()));
390 let want = mtime(request.meta.modified)?;
391 for size in sizes(request.max_side) {
392 let Ok(bytes) = std::fs::read(dir.join(size).join(&name)) else {
393 continue;
394 };
395 let fresh = png_texts(&bytes)
396 .iter()
397 .any(|(k, v)| k == "Thumb::MTime" && v.parse::<u64>().ok() == Some(want));
398 if fresh && let Ok(p) = decode(&bytes, request) {
399 return Some(p);
400 }
401 }
402 None
403 }
404
405 fn mime_type(path: &Path) -> Option<String> {
408 let name = path.file_name()?.to_string_lossy().to_lowercase();
409 let mut best: Option<(u32, usize, String)> = None;
410 for dir in data_dirs() {
411 let Ok(text) = std::fs::read_to_string(dir.join("mime/globs2")) else {
412 continue;
413 };
414 for line in text.lines().filter(|l| !l.starts_with('#')) {
415 let mut parts = line.split(':');
416 let (Some(weight), Some(mime), Some(glob)) =
417 (parts.next(), parts.next(), parts.next())
418 else {
419 continue;
420 };
421 let Some(ext) = glob.strip_prefix('*') else {
422 continue;
423 };
424 if ext.contains(['*', '?', '[']) || !name.ends_with(&ext.to_lowercase()) {
425 continue;
426 }
427 let weight = weight.parse().unwrap_or(50);
428 let better = best
430 .as_ref()
431 .is_none_or(|(w, l, _)| (weight, ext.len()) > (*w, *l));
432 if better {
433 best = Some((weight, ext.len(), mime.to_string()));
434 }
435 }
436 if best.is_some() {
437 break;
438 }
439 }
440 best.map(|(_, _, m)| m)
441 .or_else(|| preview::mime_of(path).map(str::to_string))
442 }
443
444 fn which(program: &str) -> Option<PathBuf> {
446 let p = Path::new(program);
447 if p.is_absolute() {
448 return p.is_file().then(|| p.to_path_buf());
449 }
450 std::env::split_paths(&std::env::var_os("PATH")?)
451 .map(|d| d.join(program))
452 .find(|c| c.is_file())
453 }
454
455 fn thumbnailer(mime: &str) -> Option<String> {
457 for dir in data_dirs() {
458 let Ok(read) = std::fs::read_dir(dir.join("thumbnailers")) else {
459 continue;
460 };
461 let mut files: Vec<PathBuf> = read
462 .filter_map(Result::ok)
463 .map(|e| e.path())
464 .filter(|p| p.extension().is_some_and(|e| e == "thumbnailer"))
465 .collect();
466 files.sort();
467 for f in files {
468 let Ok(text) = std::fs::read_to_string(&f) else {
469 continue;
470 };
471 let field = |key: &str| {
472 text.lines()
473 .find_map(|l| l.strip_prefix(key)?.trim_start().strip_prefix('='))
474 .map(str::trim)
475 };
476 let handles = field("MimeType")
477 .is_some_and(|types| types.split(';').any(|t| t.trim() == mime));
478 if !handles {
479 continue;
480 }
481 if let Some(t) = field("TryExec")
482 && which(t).is_none()
483 {
484 continue;
485 }
486 if let Some(exec) = field("Exec") {
487 return Some(exec.to_string());
488 }
489 }
490 }
491 None
492 }
493
494 pub(super) fn arguments(exec: &str, input: &Path, output: &Path, size: u32) -> Vec<String> {
497 let mut words = Vec::new();
498 let mut word = String::new();
499 let mut quote: Option<char> = None;
500 let mut started = false;
501 let mut chars = exec.chars().peekable();
502 while let Some(c) = chars.next() {
503 match (c, quote) {
504 ('"' | '\'', None) => {
505 quote = Some(c);
506 started = true;
507 }
508 (c, Some(q)) if c == q => quote = None,
509 ('\\', _) => {
510 if let Some(n) = chars.next() {
511 word.push(n);
512 }
513 }
514 (' ' | '\t', None) => {
515 if started || !word.is_empty() {
516 words.push(std::mem::take(&mut word));
517 started = false;
518 }
519 }
520 ('%', _) => match chars.next() {
521 Some('i') => word.push_str(&input.to_string_lossy()),
522 Some('u') => word.push_str(&file_uri(input)),
523 Some('o') => word.push_str(&output.to_string_lossy()),
524 Some('s') => word.push_str(&size.to_string()),
525 Some('%') => word.push('%'),
526 _ => {}
527 },
528 (c, _) => word.push(c),
529 }
530 }
531 if started || !word.is_empty() {
532 words.push(word);
533 }
534 words
535 }
536
537 fn run(
539 exec: &str,
540 path: &Path,
541 request: &PreviewRequest,
542 timeout: Duration,
543 ) -> Result<Vec<u8>, String> {
544 static NEXT: AtomicU64 = AtomicU64::new(0);
545 let output = std::env::temp_dir().join(format!(
546 "egui-pop-thumbnail-{}-{}.png",
547 std::process::id(),
548 NEXT.fetch_add(1, Ordering::Relaxed)
549 ));
550 let size = if request.max_side <= 128 {
551 128
552 } else if request.max_side <= 256 {
553 256
554 } else {
555 512
556 };
557 let args = arguments(exec, path, &output, size);
558 let (program, rest) = args.split_first().ok_or("the thumbnailer has no command")?;
559 let mut child = Command::new(program)
560 .args(rest)
561 .stdin(Stdio::null())
562 .stdout(Stdio::null())
563 .stderr(Stdio::null())
564 .spawn()
565 .map_err(|e| format!("{program}: {e}"))?;
566 let started = Instant::now();
567 let status = loop {
568 if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
569 break status;
570 }
571 if request.cancelled() || started.elapsed() > timeout {
572 let _ = child.kill();
573 let _ = child.wait();
574 let _ = std::fs::remove_file(&output);
575 return Err(if request.cancelled() {
576 "cancelled".into()
577 } else {
578 format!("{program} took longer than {} s", timeout.as_secs())
579 });
580 }
581 std::thread::sleep(Duration::from_millis(20));
582 };
583 let bytes = std::fs::read(&output);
584 let _ = std::fs::remove_file(&output);
585 if !status.success() {
586 return Err(format!("{program} failed ({status})"));
587 }
588 bytes.map_err(|e| format!("{program} made no thumbnail: {e}"))
589 }
590
591 pub(super) fn preview(
592 request: &PreviewRequest,
593 timeout: Duration,
594 ) -> Result<Option<Preview>, String> {
595 let path = std::fs::canonicalize(&request.path).map_err(|e| e.to_string())?;
596 if let Some(p) = cached(&path, request) {
597 return Ok(Some(p));
598 }
599 let Some(mime) = mime_type(&path) else {
600 return Ok(None);
601 };
602 let Some(exec) = thumbnailer(&mime) else {
603 return Ok(None);
604 };
605 let bytes = run(&exec, &path, request, timeout)?;
606 decode(&bytes, request).map(Some)
607 }
608}
609
610#[cfg(test)]
611mod tests {
612 use super::*;
613
614 #[test]
615 fn md5_matches_the_rfc() {
616 assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
617 assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
618 assert_eq!(
619 md5_hex(
620 b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
621 ),
622 "57edf4a22be3c955ac49da2e2107b67a"
623 );
624 }
625
626 #[test]
627 fn uris_are_escaped_as_glib_does() {
628 assert_eq!(
629 file_uri(std::path::Path::new("/home/a b/été (1).png")),
630 "file:///home/a%20b/%C3%A9t%C3%A9%20(1).png"
631 );
632 }
633
634 #[test]
635 fn png_text_chunks_are_read() {
636 let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
637 let data = b"Thumb::MTime\x001700000000";
638 png.extend_from_slice(&(data.len() as u32).to_be_bytes());
639 png.extend_from_slice(b"tEXt");
640 png.extend_from_slice(data);
641 png.extend_from_slice(&[0, 0, 0, 0]);
642 assert_eq!(
643 png_texts(&png),
644 [("Thumb::MTime".to_string(), "1700000000".to_string())]
645 );
646 }
647
648 #[cfg(all(
649 unix,
650 not(target_os = "macos"),
651 not(target_os = "ios"),
652 not(target_os = "android")
653 ))]
654 #[test]
655 fn exec_lines_become_arguments() {
656 use std::path::Path;
657 assert_eq!(
658 freedesktop::arguments(
659 "thumb -s %s \"%u\" %o 100%%",
660 Path::new("/a b.pdf"),
661 Path::new("/tmp/o.png"),
662 256
663 ),
664 [
665 "thumb",
666 "-s",
667 "256",
668 "file:///a%20b.pdf",
669 "/tmp/o.png",
670 "100%"
671 ]
672 );
673 }
674}