Skip to main content

egui_pop_api/files/
preview.rs

1//! Previews of files, from pluggable providers.
2//!
3//! A [`PreviewProvider`] says which files it handles ([`Handles`]: file
4//! extensions, MIME types, magic bytes, folders) and with what priority;
5//! plugins register theirs with [`Previews::register`] (the service is
6//! [`Files::previews`](super::Files::previews)). For a path, the
7//! providers that handle it are tried from the highest priority down:
8//! the first to give a preview wins, one may pass (`Ok(None)`) to the
9//! next, and a failure (an error, or a panic) is shown with its reason.
10//!
11//! - **Off the interface thread**: [`Previews::get`] answers from the
12//!   cache, else hands the path to a worker thread of its own and says
13//!   [`Shown::Loading`]; the frame never waits. Asking for another path
14//!   cancels the one asked before ([`PreviewRequest::cancelled`]). On
15//!   the web, which has no threads, the preview is made in the frame.
16//! - **Many at once**: a grid says which paths are in view each frame
17//!   ([`Previews::want`]) and reads what is made ([`Previews::thumbnail`]).
18//!   The worker makes them in that order, after the preview asked with
19//!   [`Previews::get`]; a path scrolled out of view leaves the queue, or is
20//!   cancelled in the making.
21//! - **Cached** by path, size and modification time, up to a size in
22//!   bytes ([`Previews::set_cache_bytes`], 64 MiB by default; the oldest
23//!   go first). Providers read at most [`PreviewRequest::max_bytes`].
24//!
25//! ```
26//! use std::path::Path;
27//! use std::sync::Arc;
28//! use egui_pop_api::files::fs::{MemoryFs, SharedFs};
29//! use egui_pop_api::files::preview::{
30//!     Body, Handles, Preview, PreviewProvider, PreviewRequest, Previews, Shown,
31//! };
32//!
33//! #[derive(Debug)]
34//! struct Shout;
35//! impl PreviewProvider for Shout {
36//!     fn id(&self) -> &str {
37//!         "shout"
38//!     }
39//!     fn handles(&self) -> Handles {
40//!         Handles::new().extensions(&["txt"])
41//!     }
42//!     fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
43//!         let text = String::from_utf8_lossy(&request.read()?).to_uppercase();
44//!         Ok(Some(Preview::new(Body::Text { text, truncated: false })))
45//!     }
46//! }
47//!
48//! let previews = Previews::default();
49//! previews.register(Arc::new(Shout));
50//! let fs: SharedFs = Arc::new(MemoryFs::new().file("/a.txt", b"hi".to_vec()));
51//! let Shown::Ready(ready) = previews.compute(&fs, Path::new("/a.txt")) else { panic!() };
52//! assert!(matches!(&ready.preview.body, Body::Text { text, .. } if text == "HI"));
53//! assert_eq!(ready.provider, "shout");
54//! ```
55
56use std::collections::{HashMap, HashSet, VecDeque};
57use std::fmt;
58use std::panic::{AssertUnwindSafe, catch_unwind};
59use std::path::{Path, PathBuf};
60use std::sync::atomic::{AtomicBool, Ordering};
61use std::sync::{Arc, Condvar, Mutex};
62use std::time::SystemTime;
63
64use egui::{ColorImage, RichText, TextureHandle, TextureOptions, Ui};
65use egui_pop_core::lock;
66use egui_pop_core::strings::{tr, tr_args};
67use egui_pop_core::theme::Tokens;
68use egui_pop_core::ui::UiPop as _;
69use serde_json::{Value as Json, json};
70
71use super::fs::{Meta, SharedFs};
72use crate::strings as txt;
73
74/// The longest side of a preview's image, by default, in pixels.
75pub const MAX_SIDE: u32 = 256;
76/// The most bytes a provider reads, by default.
77pub const MAX_BYTES: usize = 64 * 1024 * 1024;
78/// The cache's size, by default, in bytes.
79pub const CACHE_BYTES: usize = 64 * 1024 * 1024;
80/// How many bytes of a file the magic numbers are read from.
81const HEAD: usize = 64;
82
83/// Which files a provider handles: any of its extensions, MIME types or
84/// magic numbers, and folders when it says so.
85#[derive(Clone, Debug, Default, PartialEq, Eq)]
86pub struct Handles {
87    /// Extensions, lower case, without the dot.
88    pub extensions: Vec<String>,
89    /// MIME types (`image/png`), a whole family (`text/*`), or any file
90    /// (`*/*`); a file's type comes from its extension ([`mime_of`]).
91    pub mime: Vec<String>,
92    /// Bytes a file starts with.
93    pub magic: Vec<Vec<u8>>,
94    /// Folders.
95    pub folders: bool,
96}
97
98impl Handles {
99    pub fn new() -> Self {
100        Self::default()
101    }
102
103    pub fn extensions(mut self, extensions: &[&str]) -> Self {
104        self.extensions
105            .extend(extensions.iter().map(|e| e.to_lowercase()));
106        self
107    }
108
109    pub fn mime(mut self, types: &[&str]) -> Self {
110        self.mime.extend(types.iter().map(|t| t.to_string()));
111        self
112    }
113
114    pub fn magic(mut self, bytes: &[u8]) -> Self {
115        self.magic.push(bytes.to_vec());
116        self
117    }
118
119    pub fn folders(mut self) -> Self {
120        self.folders = true;
121        self
122    }
123
124    /// Whether a path is handled.
125    pub fn matches(&self, probe: &Probe<'_>) -> bool {
126        if probe.meta.is_dir {
127            return self.folders;
128        }
129        let ext = extension(probe.path);
130        ext.as_deref()
131            .is_some_and(|e| self.extensions.iter().any(|x| x == e))
132            || self.mime.iter().any(|x| x == "*/*")
133            || probe.mime.is_some_and(|m| {
134                self.mime.iter().any(|x| {
135                    x == m
136                        || x.strip_suffix("/*")
137                            .is_some_and(|family| m.split('/').next() == Some(family))
138                })
139            })
140            || self.magic.iter().any(|m| probe.head.starts_with(m))
141    }
142}
143
144/// What a provider is asked whether it handles: the path, its facts, its
145/// MIME type from the extension, and its first bytes.
146#[derive(Clone, Copy, Debug)]
147pub struct Probe<'a> {
148    pub path: &'a Path,
149    pub meta: &'a Meta,
150    pub mime: Option<&'static str>,
151    /// The first bytes of a file (none for a folder).
152    pub head: &'a [u8],
153}
154
155/// A path's extension, lower case.
156pub fn extension(path: &Path) -> Option<String> {
157    path.extension()
158        .and_then(|e| e.to_str())
159        .map(str::to_lowercase)
160}
161
162/// A file's MIME type, from its extension (the common ones).
163pub fn mime_of(path: &Path) -> Option<&'static str> {
164    Some(match extension(path)?.as_str() {
165        "png" => "image/png",
166        "jpg" | "jpeg" | "jpe" => "image/jpeg",
167        "gif" => "image/gif",
168        "webp" => "image/webp",
169        "bmp" => "image/bmp",
170        "tif" | "tiff" => "image/tiff",
171        "svg" => "image/svg+xml",
172        "avif" => "image/avif",
173        "heic" | "heif" => "image/heif",
174        "txt" | "text" | "log" => "text/plain",
175        "md" | "markdown" => "text/markdown",
176        "csv" => "text/csv",
177        "tsv" => "text/tab-separated-values",
178        "html" | "htm" => "text/html",
179        "css" => "text/css",
180        "xml" => "application/xml",
181        "json" => "application/json",
182        "toml" => "application/toml",
183        "yaml" | "yml" => "application/yaml",
184        "rs" => "text/rust",
185        "py" => "text/x-python",
186        "js" | "mjs" => "text/javascript",
187        "ts" => "text/typescript",
188        "c" | "h" => "text/x-c",
189        "cpp" | "cc" | "hpp" => "text/x-c++",
190        "sh" => "application/x-shellscript",
191        "pdf" => "application/pdf",
192        "doc" => "application/msword",
193        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
194        "odt" => "application/vnd.oasis.opendocument.text",
195        "mp4" => "video/mp4",
196        "webm" => "video/webm",
197        "mkv" => "video/x-matroska",
198        "mov" => "video/quicktime",
199        "mp3" => "audio/mpeg",
200        "ogg" => "audio/ogg",
201        "flac" => "audio/flac",
202        "wav" => "audio/wav",
203        "zip" => "application/zip",
204        _ => return None,
205    })
206}
207
208/// A preview: what to draw and the facts to say. Made with [`Preview::new`] and
209/// its builders.
210#[derive(Clone, Debug, Default)]
211#[non_exhaustive]
212pub struct Preview {
213    pub body: Body,
214    /// An image's or a page's width and height, in pixels.
215    pub dimensions: Option<[u32; 2]>,
216    /// A document's pages.
217    pub pages: Option<u32>,
218    /// What a photo's metadata says ([`PhotoFacts`]): shown in one order,
219    /// the same way whichever provider read it.
220    pub photo: Option<PhotoFacts>,
221    /// Further facts, a label and a value each, in the interface's
222    /// language.
223    pub facts: Vec<(String, String)>,
224}
225
226/// What a photo's metadata says (EXIF, XMP), as a provider reads it: the
227/// preview pane shows it in one order, as Dolphin's information panel and a
228/// photo application's loupe do, whichever provider read it. Made with
229/// [`PhotoFacts::default`] and its builders.
230#[derive(Clone, Debug, Default, PartialEq)]
231#[non_exhaustive]
232pub struct PhotoFacts {
233    /// When it was taken, as the camera says: its local time, without a
234    /// zone (`2026-01-15 10:04:00`).
235    pub taken: Option<String>,
236    /// The camera (make and model).
237    pub camera: Option<String>,
238    pub lens: Option<String>,
239    /// The exposure time, in seconds.
240    pub shutter: Option<f64>,
241    /// The aperture's f-number.
242    pub aperture: Option<f32>,
243    pub iso: Option<u32>,
244    /// The focal length, in millimetres.
245    pub focal_length: Option<f32>,
246    /// From 0 to 5 stars.
247    pub rating: Option<u8>,
248}
249
250impl PhotoFacts {
251    /// When it was taken. EXIF's form (`2026:01:15 10:04:00`) reads as a date
252    /// (`2026-01-15 10:04:00`); anything else is shown as given.
253    pub fn taken(mut self, when: &str) -> Self {
254        let when = when.trim();
255        let b = when.as_bytes();
256        let exif = b.len() >= 10
257            && b[4] == b':'
258            && b[7] == b':'
259            && b[..4]
260                .iter()
261                .chain(&b[5..7])
262                .chain(&b[8..10])
263                .all(u8::is_ascii_digit);
264        self.taken = Some(if exif {
265            format!(
266                "{}-{}-{}{}",
267                &when[..4],
268                &when[5..7],
269                &when[8..10],
270                &when[10..]
271            )
272        } else {
273            when.to_owned()
274        });
275        self
276    }
277
278    pub fn camera(mut self, camera: &str) -> Self {
279        self.camera = Some(camera.trim().to_owned());
280        self
281    }
282
283    pub fn lens(mut self, lens: &str) -> Self {
284        self.lens = Some(lens.trim().to_owned());
285        self
286    }
287
288    /// The exposure time, in seconds.
289    pub fn shutter(mut self, seconds: f64) -> Self {
290        self.shutter = Some(seconds);
291        self
292    }
293
294    /// The aperture's f-number.
295    pub fn aperture(mut self, f_number: f32) -> Self {
296        self.aperture = Some(f_number);
297        self
298    }
299
300    pub fn iso(mut self, iso: u32) -> Self {
301        self.iso = Some(iso);
302        self
303    }
304
305    /// The focal length, in millimetres.
306    pub fn focal_length(mut self, mm: f32) -> Self {
307        self.focal_length = Some(mm);
308        self
309    }
310
311    /// From 0 to 5 stars (more is 5).
312    pub fn rating(mut self, stars: u8) -> Self {
313        self.rating = Some(stars.min(5));
314        self
315    }
316
317    /// The exposure as one line: `1/250 s  f/5.6  ISO 200`; `None` without
318    /// any of the three.
319    pub fn exposure_text(&self) -> Option<String> {
320        let parts: Vec<String> = [
321            self.shutter.map(shutter_text),
322            self.aperture
323                .map(|f| format!("f/{}", short_number(f64::from(f)))),
324            self.iso.map(|iso| format!("ISO {iso}")),
325        ]
326        .into_iter()
327        .flatten()
328        .collect();
329        (!parts.is_empty()).then(|| parts.join("  "))
330    }
331
332    /// The metadata, as agents read it.
333    pub fn describe(&self) -> Json {
334        let mut d = json!({});
335        let mut put = |k: &str, v: Json| {
336            if !v.is_null() {
337                d[k] = v;
338            }
339        };
340        put("taken", json!(self.taken));
341        put("camera", json!(self.camera));
342        put("lens", json!(self.lens));
343        put("shutter", json!(self.shutter));
344        put("aperture", json!(self.aperture));
345        put("iso", json!(self.iso));
346        put("focal_length", json!(self.focal_length));
347        put("rating", json!(self.rating));
348        d
349    }
350}
351
352/// An exposure time as photographers say it: `1/250 s` under a second (the
353/// fraction rounded), `2 s` or `1.5 s` from a second.
354fn shutter_text(seconds: f64) -> String {
355    if seconds > 0.0 && seconds < 1.0 {
356        let n = (1.0 / seconds).round() as u64;
357        // 0.4 s is 1/2.5 s: a fraction that rounds far from it reads better as a number.
358        if ((1.0 / n as f64) - seconds).abs() / seconds < 0.1 {
359            return format!("1/{n} s");
360        }
361    }
362    format!("{} s", short_number(seconds))
363}
364
365/// A number with at most one decimal, none when it is whole: `8`, `5.6`.
366fn short_number(x: f64) -> String {
367    let r = (x * 10.0).round() / 10.0;
368    if r.fract() == 0.0 {
369        format!("{r:.0}")
370    } else {
371        format!("{r:.1}")
372    }
373}
374
375impl Preview {
376    pub fn new(body: Body) -> Self {
377        Self {
378            body,
379            ..Self::default()
380        }
381    }
382
383    pub fn dimensions(mut self, width: u32, height: u32) -> Self {
384        self.dimensions = Some([width, height]);
385        self
386    }
387
388    pub fn pages(mut self, pages: u32) -> Self {
389        self.pages = Some(pages);
390        self
391    }
392
393    /// What the photo's metadata says.
394    pub fn photo(mut self, facts: PhotoFacts) -> Self {
395        self.photo = Some(facts);
396        self
397    }
398
399    pub fn fact(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
400        self.facts.push((label.into(), value.into()));
401        self
402    }
403
404    /// About what it holds in memory.
405    pub fn bytes(&self) -> usize {
406        let image = |i: &ColorImage| i.pixels.len() * 4;
407        let facts: usize = self.facts.iter().map(|(a, b)| a.len() + b.len()).sum();
408        facts
409            + match &self.body {
410                Body::Empty => 0,
411                Body::Image(i) => image(i),
412                Body::Text { text, .. } => text.len(),
413                Body::Markdown(blocks) => blocks.iter().map(|b| b.text().len() + 8).sum(),
414                Body::Folder { thumbnails, .. } => thumbnails.iter().map(|i| image(i)).sum(),
415            }
416    }
417
418    /// The metadata, as agents read it (no pixels, no text).
419    pub fn describe(&self) -> Json {
420        let mut d = json!({ "kind": self.body.kind() });
421        if let Some([w, h]) = self.dimensions {
422            d["dimensions"] = json!([w, h]);
423        }
424        if let Some(p) = self.pages {
425            d["pages"] = json!(p);
426        }
427        if let Body::Folder {
428            folders,
429            files,
430            thumbnails,
431        } = &self.body
432        {
433            d["folders"] = json!(folders);
434            d["files"] = json!(files);
435            d["thumbnails"] = json!(thumbnails.len());
436        }
437        if let Body::Text { truncated, .. } = &self.body {
438            d["truncated"] = json!(truncated);
439        }
440        if let Some(photo) = &self.photo {
441            d["photo"] = photo.describe();
442        }
443        if !self.facts.is_empty() {
444            d["facts"] = self
445                .facts
446                .iter()
447                .map(|(k, v)| (k.clone(), json!(v)))
448                .collect::<serde_json::Map<_, _>>()
449                .into();
450        }
451        d
452    }
453}
454
455/// What a preview draws.
456#[derive(Clone, Debug, Default)]
457pub enum Body {
458    /// Nothing to draw: only facts.
459    #[default]
460    Empty,
461    /// An image, already scaled down.
462    Image(Arc<ColorImage>),
463    /// The first lines of a text, in a monospace font.
464    Text { text: String, truncated: bool },
465    /// A document drawn simply.
466    Markdown(Vec<Block>),
467    /// A folder: what it holds, and the first images in it.
468    Folder {
469        folders: usize,
470        files: usize,
471        thumbnails: Vec<Arc<ColorImage>>,
472    },
473}
474
475impl Body {
476    pub fn kind(&self) -> &'static str {
477        match self {
478            Body::Empty => "empty",
479            Body::Image(_) => "image",
480            Body::Text { .. } => "text",
481            Body::Markdown(_) => "markdown",
482            Body::Folder { .. } => "folder",
483        }
484    }
485}
486
487/// A block of a document drawn simply.
488#[derive(Clone, Debug, PartialEq, Eq)]
489pub enum Block {
490    /// A heading, of level 1 to 6.
491    Heading(u8, String),
492    Paragraph(String),
493    /// An item of a list.
494    Item(String),
495    /// A line of code.
496    Code(String),
497    Quote(String),
498    /// A thematic break.
499    Rule,
500}
501
502impl Block {
503    pub fn text(&self) -> &str {
504        match self {
505            Block::Heading(_, t)
506            | Block::Paragraph(t)
507            | Block::Item(t)
508            | Block::Code(t)
509            | Block::Quote(t) => t,
510            Block::Rule => "",
511        }
512    }
513}
514
515/// A provider of previews.
516pub trait PreviewProvider: Send + Sync + fmt::Debug {
517    /// Its id, for the bridge and the messages (`images`, `my_app.raw`).
518    fn id(&self) -> &str;
519
520    /// Which files it handles (read once, when it is registered).
521    fn handles(&self) -> Handles;
522
523    /// Higher first. The built-in providers are at 0 (text at -10), the
524    /// system's thumbnails at -100.
525    fn priority(&self) -> i32 {
526        0
527    }
528
529    /// Whether it takes a path its [`Handles`] match; all of them, by
530    /// default.
531    fn accepts(&self, probe: &Probe<'_>) -> bool {
532        let _ = probe;
533        true
534    }
535
536    /// The preview (on a worker thread): `Ok(None)` passes to the next
537    /// provider, an error is shown with its reason.
538    fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String>;
539}
540
541#[derive(Clone, Debug)]
542struct Registered {
543    provider: Arc<dyn PreviewProvider>,
544    handles: Handles,
545    priority: i32,
546}
547
548/// What a provider is asked for.
549#[derive(Clone, Debug)]
550pub struct PreviewRequest {
551    pub path: PathBuf,
552    pub meta: Meta,
553    pub mime: Option<&'static str>,
554    /// The longest side of an image, in pixels.
555    pub max_side: u32,
556    /// The most bytes to read.
557    pub max_bytes: usize,
558    fs: SharedFs,
559    cancel: Arc<AtomicBool>,
560    chain: Arc<[Registered]>,
561}
562
563impl PreviewRequest {
564    /// Where to read.
565    pub fn fs(&self) -> &SharedFs {
566        &self.fs
567    }
568
569    /// Whether the selection moved on: a long provider may stop.
570    pub fn cancelled(&self) -> bool {
571        self.cancel.load(Ordering::Relaxed)
572    }
573
574    /// The file's bytes, refused past [`PreviewRequest::max_bytes`].
575    pub fn read(&self) -> Result<Vec<u8>, String> {
576        if self.meta.len > self.max_bytes as u64 {
577            return Err(format!(
578                "too large to preview ({}, at most {})",
579                size_text(self.meta.len),
580                size_text(self.max_bytes as u64)
581            ));
582        }
583        self.read_head(self.max_bytes)
584    }
585
586    /// At most `limit` bytes from the start of the file.
587    pub fn read_head(&self, limit: usize) -> Result<Vec<u8>, String> {
588        self.fs
589            .read(&self.path, limit.min(self.max_bytes))
590            .map_err(|e| e.to_string())
591    }
592
593    /// The file's extension, lower case.
594    pub fn extension(&self) -> Option<String> {
595        extension(&self.path)
596    }
597
598    /// Another file's preview from the same providers, at most
599    /// `max_side` pixels (a folder's thumbnails); folders are skipped.
600    pub fn preview_of(&self, path: &Path, max_side: u32) -> Option<Preview> {
601        let meta = self.fs.metadata(path).ok().filter(|m| !m.is_dir)?;
602        let request = PreviewRequest {
603            path: path.to_path_buf(),
604            meta,
605            mime: mime_of(path),
606            max_side,
607            max_bytes: self.max_bytes,
608            fs: self.fs.clone(),
609            cancel: self.cancel.clone(),
610            chain: self.chain.clone(),
611        };
612        match run(&request) {
613            Shown::Ready(r) => Some(r.preview.clone()),
614            _ => None,
615        }
616    }
617}
618
619/// A preview made, with the facts of its file and its textures once
620/// drawn.
621pub struct Ready {
622    pub preview: Preview,
623    pub meta: Meta,
624    /// The provider that made it.
625    pub provider: String,
626    textures: Mutex<HashMap<usize, TextureHandle>>,
627}
628
629impl fmt::Debug for Ready {
630    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631        f.debug_struct("Ready")
632            .field("preview", &self.preview)
633            .field("meta", &self.meta)
634            .field("provider", &self.provider)
635            .field("textures", &lock(&self.textures).len())
636            .finish()
637    }
638}
639
640impl Ready {
641    pub fn new(preview: Preview, meta: Meta, provider: &str) -> Self {
642        Self {
643            preview,
644            meta,
645            provider: provider.into(),
646            textures: Mutex::default(),
647        }
648    }
649
650    /// The texture of its image (`0`), or of a folder's `n`th
651    /// thumbnail, made on the first call.
652    pub fn texture(&self, ctx: &egui::Context, n: usize) -> Option<TextureHandle> {
653        let image = match &self.preview.body {
654            Body::Image(i) if n == 0 => i.clone(),
655            Body::Folder { thumbnails, .. } => thumbnails.get(n)?.clone(),
656            _ => return None,
657        };
658        let mut t = lock(&self.textures);
659        Some(
660            t.entry(n)
661                .or_insert_with(|| {
662                    ctx.load_texture(
663                        format!("egui_pop.files.preview.{n}"),
664                        (*image).clone(),
665                        TextureOptions::LINEAR,
666                    )
667                })
668                .clone(),
669        )
670    }
671}
672
673/// Where a path's preview is.
674#[derive(Clone, Debug)]
675pub enum Shown {
676    /// No provider handles it.
677    Nothing,
678    /// A worker is making it.
679    Loading,
680    Ready(Arc<Ready>),
681    /// It could not be made: why.
682    Failed(String),
683}
684
685impl Shown {
686    pub fn state(&self) -> &'static str {
687        match self {
688            Shown::Nothing => "none",
689            Shown::Loading => "loading",
690            Shown::Ready(_) => "ready",
691            Shown::Failed(_) => "failed",
692        }
693    }
694
695    /// As agents read it: the state, the provider and the preview's
696    /// metadata.
697    pub fn describe(&self) -> Json {
698        let mut d = json!({ "state": self.state() });
699        match self {
700            Shown::Ready(r) => {
701                d["provider"] = json!(r.provider);
702                if let Json::Object(m) = r.preview.describe() {
703                    for (k, v) in m {
704                        d[k] = v;
705                    }
706                }
707            }
708            Shown::Failed(e) => d["reason"] = json!(e),
709            _ => {}
710        }
711        d
712    }
713
714    fn bytes(&self) -> usize {
715        match self {
716            Shown::Ready(r) => r.preview.bytes() + 256,
717            Shown::Failed(e) => e.len() + 64,
718            _ => 64,
719        }
720    }
721}
722
723/// A preview's cache key: the path, its size and modification time, the
724/// size asked.
725#[derive(Clone, Debug, PartialEq, Eq, Hash)]
726struct Key {
727    path: PathBuf,
728    len: u64,
729    modified: Option<SystemTime>,
730    max_side: u32,
731}
732
733#[derive(Debug)]
734struct Job {
735    key: Key,
736    request: PreviewRequest,
737}
738
739/// What the worker makes.
740#[derive(Debug)]
741struct Running {
742    key: Key,
743    cancel: Arc<AtomicBool>,
744    /// Asked by a grid: it stops when out of view.
745    thumbnail: bool,
746}
747
748#[derive(Debug)]
749struct State {
750    providers: Vec<Registered>,
751    cache: HashMap<Key, Shown>,
752    /// Oldest first.
753    order: VecDeque<Key>,
754    /// What a grid has in view: kept over the cache's cap, or a view larger
755    /// than the cache would make its thumbnails again for ever.
756    in_view: HashSet<Key>,
757    /// What a grid has in view and is not made yet, in its order.
758    thumbnails: VecDeque<Job>,
759    bytes: usize,
760    cap: usize,
761    max_side: u32,
762    max_bytes: usize,
763    /// Waiting for the worker (the last asked: those before are dropped).
764    job: Option<Job>,
765    running: Option<Running>,
766    worker: bool,
767    repaint: Option<egui::Context>,
768}
769
770impl Default for State {
771    fn default() -> Self {
772        Self {
773            providers: Vec::new(),
774            cache: HashMap::new(),
775            order: VecDeque::new(),
776            in_view: HashSet::new(),
777            thumbnails: VecDeque::new(),
778            bytes: 0,
779            cap: CACHE_BYTES,
780            max_side: MAX_SIDE,
781            max_bytes: MAX_BYTES,
782            job: None,
783            running: None,
784            worker: false,
785            repaint: None,
786        }
787    }
788}
789
790impl State {
791    fn put(&mut self, key: Key, shown: Shown) {
792        if let Some(old) = self.cache.remove(&key) {
793            self.bytes = self.bytes.saturating_sub(old.bytes());
794            self.order.retain(|k| *k != key);
795        }
796        let size = shown.bytes();
797        if size > self.cap {
798            return;
799        }
800        let mut kept = Vec::new();
801        while self.bytes + size > self.cap {
802            let Some(oldest) = self.order.pop_front() else {
803                break;
804            };
805            if self.in_view.contains(&oldest) {
806                kept.push(oldest);
807            } else if let Some(old) = self.cache.remove(&oldest) {
808                self.bytes = self.bytes.saturating_sub(old.bytes());
809            }
810        }
811        for k in kept.into_iter().rev() {
812            self.order.push_front(k);
813        }
814        self.bytes += size;
815        self.order.push_back(key.clone());
816        self.cache.insert(key, shown);
817    }
818
819    /// Whether `key` is being made, or waits to be.
820    fn asked(&self, key: &Key) -> bool {
821        self.running.as_ref().is_some_and(|r| r.key == *key)
822            || self.job.as_ref().is_some_and(|j| j.key == *key)
823    }
824
825    /// What the worker takes next: the preview asked, then what a grid has
826    /// in view. Says whether it is the latter.
827    fn next_job(&mut self) -> Option<(Job, bool)> {
828        self.job
829            .take()
830            .map(|j| (j, false))
831            .or_else(|| self.thumbnails.pop_front().map(|j| (j, true)))
832    }
833}
834
835#[derive(Debug, Default)]
836struct Shared {
837    state: Mutex<State>,
838    wake: Condvar,
839}
840
841/// The preview providers, their cache and their worker, as a service of
842/// [`Files`](super::Files).
843#[derive(Clone, Debug, Default)]
844pub struct Previews(Arc<Shared>);
845
846impl Previews {
847    /// Adds a provider.
848    pub fn register(&self, provider: Arc<dyn PreviewProvider>) {
849        let r = Registered {
850            handles: provider.handles(),
851            priority: provider.priority(),
852            provider,
853        };
854        let mut s = lock(&self.0.state);
855        s.providers.retain(|p| p.provider.id() != r.provider.id());
856        // Stable: among equals, the first registered first.
857        let at = s
858            .providers
859            .iter()
860            .position(|p| p.priority < r.priority)
861            .unwrap_or(s.providers.len());
862        s.providers.insert(at, r);
863        // What was made before may now come from another provider.
864        s.cache.clear();
865        s.order.clear();
866        s.bytes = 0;
867    }
868
869    /// The providers, highest priority first: id and priority.
870    pub fn providers(&self) -> Vec<(String, i32)> {
871        lock(&self.0.state)
872            .providers
873            .iter()
874            .map(|p| (p.provider.id().to_string(), p.priority))
875            .collect()
876    }
877
878    /// The cache's size in bytes; the oldest previews go first past it.
879    pub fn set_cache_bytes(&self, bytes: usize) {
880        let mut s = lock(&self.0.state);
881        s.cap = bytes;
882        while s.bytes > s.cap {
883            let Some(oldest) = s.order.pop_front() else {
884                break;
885            };
886            if let Some(old) = s.cache.remove(&oldest) {
887                s.bytes = s.bytes.saturating_sub(old.bytes());
888            }
889        }
890    }
891
892    /// The longest side of a preview's image, in pixels.
893    pub fn set_max_side(&self, pixels: u32) {
894        lock(&self.0.state).max_side = pixels.max(16);
895    }
896
897    /// The most bytes a provider reads.
898    pub fn set_max_bytes(&self, bytes: usize) {
899        lock(&self.0.state).max_bytes = bytes;
900    }
901
902    fn job(&self, fs: &SharedFs, path: &Path) -> Result<(Key, PreviewRequest), Shown> {
903        let meta = fs
904            .metadata(path)
905            .map_err(|e| Shown::Failed(e.to_string()))?;
906        let s = lock(&self.0.state);
907        let key = Key {
908            path: path.to_path_buf(),
909            len: meta.len,
910            modified: meta.modified,
911            max_side: s.max_side,
912        };
913        let request = PreviewRequest {
914            path: path.to_path_buf(),
915            meta,
916            mime: mime_of(path),
917            max_side: s.max_side,
918            max_bytes: s.max_bytes,
919            fs: fs.clone(),
920            cancel: Arc::default(),
921            chain: s.providers.clone().into(),
922        };
923        Ok((key, request))
924    }
925
926    /// A path's preview: from the cache, else asked of the worker
927    /// ([`Shown::Loading`]; the path asked before, unless it is done, is
928    /// cancelled). The context is woken when it is ready.
929    pub fn get(&self, ctx: &egui::Context, fs: &SharedFs, path: &Path) -> Shown {
930        let (key, request) = match self.job(fs, path) {
931            Ok(j) => j,
932            Err(shown) => return shown,
933        };
934        let mut s = lock(&self.0.state);
935        if let Some(shown) = s.cache.get(&key) {
936            return shown.clone();
937        }
938        if s.asked(&key) {
939            return Shown::Loading;
940        }
941        if s.providers.is_empty() {
942            return Shown::Nothing;
943        }
944        // Another path was asked before: it is not wanted any more. A
945        // thumbnail gives way too, and is asked again while in view.
946        if let Some(running) = &s.running {
947            running.cancel.store(true, Ordering::Relaxed);
948        }
949        s.repaint = Some(ctx.clone());
950        if cfg!(target_arch = "wasm32") {
951            drop(s);
952            let shown = run(&request);
953            lock(&self.0.state).put(key, shown.clone());
954            return shown;
955        }
956        s.job = Some(Job { key, request });
957        if !s.worker {
958            s.worker = true;
959            drop(s);
960            self.spawn();
961        } else {
962            drop(s);
963            self.0.wake.notify_all();
964        }
965        Shown::Loading
966    }
967
968    /// The paths a grid has in view, in the order it wants them, and their
969    /// facts (the frame reads no file here): replaces what it said before.
970    /// What is not made yet goes to the worker, one at a time, behind the
971    /// preview asked with [`Previews::get`], and the context is woken as each
972    /// is ready; what left the view leaves the queue, and is cancelled when
973    /// in the making. None: nothing is wanted any more.
974    pub fn want(&self, ctx: &egui::Context, fs: &SharedFs, wanted: &[(PathBuf, Meta)]) {
975        let mut s = lock(&self.0.state);
976        s.thumbnails.clear();
977        s.in_view.clear();
978        let (max_side, max_bytes) = (s.max_side, s.max_bytes);
979        // Only for what is not made: most frames have nothing to ask.
980        let mut chain: Option<Arc<[Registered]>> = None;
981        for (path, meta) in wanted {
982            let key = Key {
983                path: path.clone(),
984                len: meta.len,
985                modified: meta.modified,
986                max_side,
987            };
988            s.in_view.insert(key.clone());
989            if s.providers.is_empty() || s.cache.contains_key(&key) || s.asked(&key) {
990                continue;
991            }
992            let chain = chain
993                .get_or_insert_with(|| s.providers.clone().into())
994                .clone();
995            let request = PreviewRequest {
996                path: path.clone(),
997                meta: *meta,
998                mime: mime_of(path),
999                max_side,
1000                max_bytes,
1001                fs: fs.clone(),
1002                cancel: Arc::default(),
1003                chain,
1004            };
1005            s.thumbnails.push_back(Job { key, request });
1006        }
1007        if let Some(running) = &s.running
1008            && running.thumbnail
1009            && !s.in_view.contains(&running.key)
1010        {
1011            running.cancel.store(true, Ordering::Relaxed);
1012        }
1013        if s.thumbnails.is_empty() {
1014            return;
1015        }
1016        s.repaint = Some(ctx.clone());
1017        if cfg!(target_arch = "wasm32") {
1018            // No threads: one per frame, for the frames to go on.
1019            drop(s);
1020            self.make_one();
1021            ctx.request_repaint();
1022        } else if !s.worker {
1023            s.worker = true;
1024            drop(s);
1025            self.spawn();
1026        } else {
1027            drop(s);
1028            self.0.wake.notify_all();
1029        }
1030    }
1031
1032    /// A path's thumbnail as it is now, its facts given (the frame reads no
1033    /// file here): made, or [`Shown::Loading`] whether it was asked or not.
1034    pub fn thumbnail(&self, path: &Path, meta: &Meta) -> Shown {
1035        let s = lock(&self.0.state);
1036        let key = Key {
1037            path: path.to_path_buf(),
1038            len: meta.len,
1039            modified: meta.modified,
1040            max_side: s.max_side,
1041        };
1042        match s.cache.get(&key) {
1043            Some(shown) => shown.clone(),
1044            None if s.providers.is_empty() => Shown::Nothing,
1045            None => Shown::Loading,
1046        }
1047    }
1048
1049    /// Makes what comes next, on this thread.
1050    fn make_one(&self) {
1051        let job = lock(&self.0.state).next_job();
1052        if let Some((job, _)) = job {
1053            let shown = run(&job.request);
1054            lock(&self.0.state).put(job.key, shown);
1055        }
1056    }
1057
1058    /// What is known of a path's preview without asking for it.
1059    pub fn peek(&self, fs: &SharedFs, path: &Path) -> Shown {
1060        let (key, _) = match self.job(fs, path) {
1061            Ok(j) => j,
1062            Err(shown) => return shown,
1063        };
1064        let s = lock(&self.0.state);
1065        if let Some(shown) = s.cache.get(&key) {
1066            return shown.clone();
1067        }
1068        if s.asked(&key) {
1069            return Shown::Loading;
1070        }
1071        if s.providers.is_empty() {
1072            Shown::Nothing
1073        } else {
1074            Shown::Loading
1075        }
1076    }
1077
1078    /// A path's preview made now, on this thread (agents and tests), or
1079    /// from the cache; kept in the cache.
1080    pub fn compute(&self, fs: &SharedFs, path: &Path) -> Shown {
1081        let (key, request) = match self.job(fs, path) {
1082            Ok(j) => j,
1083            Err(shown) => return shown,
1084        };
1085        if let Some(shown) = lock(&self.0.state).cache.get(&key) {
1086            return shown.clone();
1087        }
1088        let shown = run(&request);
1089        lock(&self.0.state).put(key, shown.clone());
1090        shown
1091    }
1092
1093    /// Nothing is wanted any more (the picker closed): the preview in
1094    /// the making is cancelled.
1095    pub fn cancel(&self) {
1096        let mut s = lock(&self.0.state);
1097        s.job = None;
1098        s.thumbnails.clear();
1099        s.in_view.clear();
1100        if let Some(running) = &s.running {
1101            running.cancel.store(true, Ordering::Relaxed);
1102        }
1103    }
1104
1105    /// The providers and the cache, as the bridge shows them.
1106    pub fn describe(&self) -> Json {
1107        let s = lock(&self.0.state);
1108        json!({
1109            "providers": s.providers.iter().map(|p| json!({
1110                "id": p.provider.id(),
1111                "priority": p.priority,
1112                "extensions": p.handles.extensions,
1113                "mime": p.handles.mime,
1114                "folders": p.handles.folders,
1115            })).collect::<Vec<_>>(),
1116            "cached": s.cache.len(),
1117            "cache_bytes": s.bytes,
1118            "cache_cap": s.cap,
1119            "running": s.running.as_ref().map(|r| r.key.path.display().to_string()),
1120            "queued": s.thumbnails.len(),
1121        })
1122    }
1123
1124    fn spawn(&self) {
1125        let weak = Arc::downgrade(&self.0);
1126        let spawned = std::thread::Builder::new()
1127            .name("egui-pop-previews".into())
1128            .spawn(move || worker(&weak));
1129        if let Err(e) = spawned {
1130            log::warn!(target: "egui_pop", "files: no thread for previews: {e}");
1131            // Made in the frame, then.
1132            lock(&self.0.state).worker = false;
1133            self.make_one();
1134        }
1135    }
1136}
1137
1138/// The worker: makes the last preview asked, until the service is gone.
1139fn worker(weak: &std::sync::Weak<Shared>) {
1140    loop {
1141        let Some(shared) = weak.upgrade() else {
1142            return;
1143        };
1144        let job = {
1145            let mut s = lock(&shared.state);
1146            if s.job.is_none() && s.thumbnails.is_empty() {
1147                s = match shared
1148                    .wake
1149                    .wait_timeout(s, std::time::Duration::from_millis(500))
1150                {
1151                    Ok((s, _)) => s,
1152                    Err(e) => e.into_inner().0,
1153                };
1154            }
1155            let job = s.next_job();
1156            if let Some((j, thumbnail)) = &job {
1157                s.running = Some(Running {
1158                    key: j.key.clone(),
1159                    cancel: j.request.cancel.clone(),
1160                    thumbnail: *thumbnail,
1161                });
1162            }
1163            job
1164        };
1165        // Not held while waiting for the next one: the service may go.
1166        let Some((job, _)) = job else {
1167            continue;
1168        };
1169        let shown = run(&job.request);
1170        let repaint = {
1171            let mut s = lock(&shared.state);
1172            s.running = None;
1173            if !job.request.cancelled() || matches!(shown, Shown::Ready(_)) {
1174                s.put(job.key, shown);
1175            }
1176            s.repaint.clone()
1177        };
1178        if let Some(ctx) = repaint {
1179            ctx.request_repaint();
1180        }
1181    }
1182}
1183
1184/// The providers tried in turn for a request.
1185fn run(request: &PreviewRequest) -> Shown {
1186    let head = if request.meta.is_dir {
1187        Vec::new()
1188    } else {
1189        request.fs.read(&request.path, HEAD).unwrap_or_default()
1190    };
1191    let probe = Probe {
1192        path: &request.path,
1193        meta: &request.meta,
1194        mime: request.mime,
1195        head: &head,
1196    };
1197    for r in request.chain.iter() {
1198        if request.cancelled() {
1199            return Shown::Failed("cancelled".into());
1200        }
1201        if !r.handles.matches(&probe) || !r.provider.accepts(&probe) {
1202            continue;
1203        }
1204        match catch_unwind(AssertUnwindSafe(|| r.provider.preview(request))) {
1205            Ok(Ok(Some(p))) => {
1206                return Shown::Ready(Arc::new(Ready::new(p, request.meta, r.provider.id())));
1207            }
1208            Ok(Ok(None)) => {}
1209            Ok(Err(e)) => return Shown::Failed(e),
1210            Err(_) => {
1211                return Shown::Failed(format!("the `{}` previewer failed", r.provider.id()));
1212            }
1213        }
1214    }
1215    Shown::Nothing
1216}
1217
1218/// The width of the picker's preview pane (it shrinks when the list
1219/// would get too narrow).
1220pub const PANE_WIDTH: f32 = 240.0;
1221/// The height of a preview's drawing in the pane.
1222const PANE_HEIGHT: f32 = 180.0;
1223
1224/// Draws a preview pane: the entry's name, its preview and its facts
1225/// (a file's size and modification time, a folder's items, dimensions,
1226/// pages, the provider's).
1227pub fn pane(ui: &mut Ui, name: &str, meta: Option<&Meta>, shown: &Shown) {
1228    pane_for(ui, name, meta, shown, None);
1229}
1230
1231/// [`pane`], the preview possibly another file's: a member of the entry's group
1232/// standing in for it, named under the image. The size and the time stay the
1233/// entry's own.
1234pub(super) fn pane_for(
1235    ui: &mut Ui,
1236    name: &str,
1237    meta: Option<&Meta>,
1238    shown: &Shown,
1239    stand_in: Option<&str>,
1240) {
1241    let t = Tokens::of(ui.ctx());
1242    ui.add(egui::Label::new(RichText::new(name).strong()).truncate());
1243    ui.add_space(t.space.xs);
1244    let ready = match shown {
1245        Shown::Loading => {
1246            ui.weak(tr(ui.ctx(), &txt::FILES_PREVIEW_LOADING));
1247            None
1248        }
1249        Shown::Nothing => {
1250            ui.weak(tr(ui.ctx(), &txt::FILES_PREVIEW_NONE));
1251            None
1252        }
1253        Shown::Failed(reason) => {
1254            ui.colored_label(t.status.danger, tr(ui.ctx(), &txt::FILES_PREVIEW_FAILED));
1255            ui.add(egui::Label::new(RichText::new(reason).weak()).wrap());
1256            None
1257        }
1258        Shown::Ready(r) => {
1259            body(ui, r, name);
1260            if let Some(member) = stand_in {
1261                let said = tr_args(ui.ctx(), &txt::FILES_GROUP_STAND_IN, &[("name", member)]);
1262                ui.add(egui::Label::new(RichText::new(said).weak()).truncate());
1263            }
1264            Some(r)
1265        }
1266    };
1267    ui.add_space(t.space.s);
1268    let meta = if stand_in.is_some() {
1269        meta
1270    } else {
1271        ready.map(|r| &r.meta).or(meta)
1272    };
1273    let mut rows: Vec<(String, String)> = Vec::new();
1274    if let Some(m) = meta.filter(|m| !m.is_dir) {
1275        rows.push((tr(ui.ctx(), &txt::FILES_SIZE), size_text(m.len)));
1276    }
1277    if let Some(p) = ready.map(|r| &r.preview) {
1278        if let Body::Folder { folders, files, .. } = &p.body {
1279            rows.push((
1280                tr(ui.ctx(), &txt::FILES_ITEMS),
1281                (folders + files).to_string(),
1282            ));
1283        }
1284        if let Some([w, h]) = p.dimensions {
1285            rows.push((tr(ui.ctx(), &txt::FILES_DIMENSIONS), format!("{w} × {h}")));
1286        }
1287        if let Some(n) = p.pages {
1288            rows.push((tr(ui.ctx(), &txt::FILES_PAGES), n.to_string()));
1289        }
1290    }
1291    let photo = ready.and_then(|r| r.preview.photo.as_ref());
1292    if let Some(f) = photo {
1293        for (key, value) in [
1294            (&txt::FILES_TAKEN, f.taken.clone()),
1295            (&txt::FILES_CAMERA, f.camera.clone()),
1296            (&txt::FILES_LENS, f.lens.clone()),
1297            (&txt::FILES_EXPOSURE, f.exposure_text()),
1298            (
1299                &txt::FILES_FOCAL_LENGTH,
1300                f.focal_length
1301                    .map(|mm| format!("{} mm", short_number(f64::from(mm)))),
1302            ),
1303        ] {
1304            if let Some(v) = value.filter(|v| !v.is_empty()) {
1305                rows.push((tr(ui.ctx(), key), v));
1306            }
1307        }
1308    }
1309    // The rating ends the photo's facts: the rows after it are the file's.
1310    let rating = photo.and_then(|f| f.rating);
1311    let photo_end = rows.len();
1312    // A file's: a folder's changes with what is put in it.
1313    if let Some(at) = meta.filter(|m| !m.is_dir).and_then(|m| m.modified) {
1314        rows.push((tr(ui.ctx(), &txt::FILES_MODIFIED), time_text(at)));
1315    }
1316    if let Some(p) = ready.map(|r| &r.preview) {
1317        rows.extend(p.facts.iter().cloned());
1318    }
1319    let total = rows.len();
1320    egui::Grid::new("egui_pop.files.preview.facts")
1321        .num_columns(2)
1322        .spacing([t.space.m, t.space.xs])
1323        .show(ui, |ui| {
1324            for (n, (label, value)) in rows.into_iter().enumerate() {
1325                if n == photo_end
1326                    && let Some(stars) = rating
1327                {
1328                    ui.weak(tr(ui.ctx(), &txt::FILES_RATING));
1329                    rating_stars(ui, stars);
1330                    ui.end_row();
1331                }
1332                ui.weak(label);
1333                ui.label(value);
1334                ui.end_row();
1335            }
1336            if photo_end == total
1337                && let Some(stars) = rating
1338            {
1339                ui.weak(tr(ui.ctx(), &txt::FILES_RATING));
1340                rating_stars(ui, stars);
1341                ui.end_row();
1342            }
1343        });
1344}
1345
1346/// A rating as five stars, those rated filled, the rest outlines; read
1347/// as "3 of 5". Shown, not edited.
1348fn rating_stars(ui: &mut Ui, stars: u8) -> egui::Response {
1349    let side = ui.text_style_height(&egui::TextStyle::Body);
1350    egui_pop_core::rating::RatingStars::new(stars)
1351        .read_only(true)
1352        .size(side)
1353        .show(ui)
1354        .response
1355}
1356
1357/// A size that fits `image` in `area`, keeping its proportions, never
1358/// larger than it is.
1359fn fit(image: [usize; 2], area: egui::Vec2) -> egui::Vec2 {
1360    let (w, h) = (image[0].max(1) as f32, image[1].max(1) as f32);
1361    let k = (area.x / w).min(area.y / h).min(1.0);
1362    egui::vec2(w * k, h * k)
1363}
1364
1365fn body(ui: &mut Ui, ready: &Ready, name: &str) {
1366    let t = Tokens::of(ui.ctx());
1367    let area = egui::vec2(ui.available_width(), PANE_HEIGHT);
1368    match &ready.preview.body {
1369        Body::Empty => {}
1370        Body::Image(image) => {
1371            if let Some(tex) = ready.texture(ui.ctx(), 0) {
1372                let r = ui.image((tex.id(), fit(image.size, area)));
1373                egui_pop_core::a11y::name(&r, egui::Role::Image, name);
1374            }
1375        }
1376        Body::Text { text, truncated } => {
1377            // In the pane's own scroll area: the wheel stops here, as it does
1378            // over the list beside it.
1379            ui.scroll_area_contained(
1380                egui::ScrollArea::vertical()
1381                    .id_salt("egui_pop.files.preview.text")
1382                    .max_height(area.y)
1383                    .auto_shrink([false, true]),
1384                |ui| {
1385                    ui.add(egui::Label::new(RichText::new(text).monospace().small()).wrap());
1386                    if *truncated {
1387                        ui.weak("…");
1388                    }
1389                },
1390            );
1391        }
1392        Body::Markdown(blocks) => {
1393            ui.scroll_area_contained(
1394                egui::ScrollArea::vertical()
1395                    .id_salt("egui_pop.files.preview.document")
1396                    .max_height(area.y)
1397                    .auto_shrink([false, true]),
1398                |ui| {
1399                    for b in blocks {
1400                        match b {
1401                            Block::Heading(1, s) => {
1402                                ui.label(RichText::new(s).heading());
1403                            }
1404                            Block::Heading(_, s) => {
1405                                ui.label(RichText::new(s).strong());
1406                            }
1407                            Block::Paragraph(s) => {
1408                                ui.add(egui::Label::new(s.as_str()).wrap());
1409                            }
1410                            Block::Item(s) => {
1411                                ui.add(egui::Label::new(format!("• {s}")).wrap());
1412                            }
1413                            Block::Code(s) => {
1414                                ui.label(RichText::new(s).monospace().small());
1415                            }
1416                            Block::Quote(s) => {
1417                                ui.add(egui::Label::new(RichText::new(s).italics().weak()).wrap());
1418                            }
1419                            Block::Rule => {
1420                                ui.separator();
1421                            }
1422                        }
1423                    }
1424                },
1425            );
1426        }
1427        Body::Folder { thumbnails, .. } => {
1428            let side = ((area.x - t.space.xs) / 2.0).floor();
1429            ui.horizontal_wrapped(|ui| {
1430                ui.spacing_mut().item_spacing = egui::vec2(t.space.xs, t.space.xs);
1431                for (n, image) in thumbnails.iter().enumerate() {
1432                    if let Some(tex) = ready.texture(ui.ctx(), n) {
1433                        let size = fit(image.size, egui::vec2(side, side));
1434                        let (rect, r) =
1435                            ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
1436                        let at = egui::Rect::from_center_size(rect.center(), size);
1437                        ui.painter().image(
1438                            tex.id(),
1439                            at,
1440                            egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
1441                            egui::Color32::WHITE,
1442                        );
1443                        egui_pop_core::a11y::name(&r, egui::Role::Image, name);
1444                    }
1445                }
1446            });
1447        }
1448    }
1449}
1450
1451/// A size in bytes, as people read it (powers of 1000).
1452pub fn size_text(bytes: u64) -> String {
1453    const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
1454    if bytes < 1000 {
1455        return format!("{bytes} B");
1456    }
1457    let mut v = bytes as f64 / 1000.0;
1458    let mut unit = 0;
1459    while v >= 1000.0 && unit < UNITS.len() - 1 {
1460        v /= 1000.0;
1461        unit += 1;
1462    }
1463    if v < 10.0 {
1464        format!("{v:.1} {}", UNITS[unit])
1465    } else {
1466        format!("{v:.0} {}", UNITS[unit])
1467    }
1468}
1469
1470/// A time as `2026-01-15 10:04 UTC`.
1471pub fn time_text(t: SystemTime) -> String {
1472    let secs = match t.duration_since(SystemTime::UNIX_EPOCH) {
1473        Ok(d) => d.as_secs() as i64,
1474        Err(e) => -(e.duration().as_secs() as i64),
1475    };
1476    let days = secs.div_euclid(86_400);
1477    let rest = secs.rem_euclid(86_400);
1478    // Days to a civil date (Howard Hinnant's algorithm).
1479    let z = days + 719_468;
1480    let era = z.div_euclid(146_097);
1481    let doe = z.rem_euclid(146_097);
1482    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1483    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1484    let mp = (5 * doy + 2) / 153;
1485    let d = doy - (153 * mp + 2) / 5 + 1;
1486    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1487    let y = yoe + era * 400 + i64::from(m <= 2);
1488    format!(
1489        "{y:04}-{m:02}-{d:02} {:02}:{:02} UTC",
1490        rest / 3600,
1491        rest % 3600 / 60
1492    )
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497    use super::*;
1498
1499    #[test]
1500    fn a_photo_s_exposure_reads_as_photographers_say_it() {
1501        assert_eq!(shutter_text(1.0 / 250.0), "1/250 s");
1502        assert_eq!(shutter_text(1.0 / 3.0), "1/3 s");
1503        assert_eq!(shutter_text(0.4), "0.4 s");
1504        assert_eq!(shutter_text(2.0), "2 s");
1505        assert_eq!(shutter_text(1.5), "1.5 s");
1506        let f = PhotoFacts::default().aperture(8.0).iso(100);
1507        assert_eq!(f.exposure_text().as_deref(), Some("f/8  ISO 100"));
1508        assert_eq!(PhotoFacts::default().exposure_text(), None);
1509        assert_eq!(
1510            PhotoFacts::default()
1511                .taken("2026:01:15 10:04:00")
1512                .taken
1513                .as_deref(),
1514            Some("2026-01-15 10:04:00")
1515        );
1516        assert_eq!(
1517            PhotoFacts::default().taken("15 January").taken.as_deref(),
1518            Some("15 January")
1519        );
1520        assert_eq!(PhotoFacts::default().rating(9).rating, Some(5));
1521    }
1522    use crate::files::fs::MemoryFs;
1523    use std::time::{Duration, Instant};
1524
1525    /// A provider that says what it was asked, or fails as told.
1526    #[derive(Debug)]
1527    struct Fake {
1528        id: &'static str,
1529        handles: Handles,
1530        priority: i32,
1531        answer: fn(&PreviewRequest) -> Result<Option<Preview>, String>,
1532    }
1533
1534    impl PreviewProvider for Fake {
1535        fn id(&self) -> &str {
1536            self.id
1537        }
1538        fn handles(&self) -> Handles {
1539            self.handles.clone()
1540        }
1541        fn priority(&self) -> i32 {
1542            self.priority
1543        }
1544        fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
1545            (self.answer)(request)
1546        }
1547    }
1548
1549    fn fake(
1550        id: &'static str,
1551        handles: Handles,
1552        priority: i32,
1553        answer: fn(&PreviewRequest) -> Result<Option<Preview>, String>,
1554    ) -> Arc<dyn PreviewProvider> {
1555        Arc::new(Fake {
1556            id,
1557            handles,
1558            priority,
1559            answer,
1560        })
1561    }
1562
1563    fn named(r: &PreviewRequest) -> Result<Option<Preview>, String> {
1564        let name = r.path.file_name().unwrap().to_string_lossy().into_owned();
1565        Ok(Some(Preview::new(Body::Text {
1566            text: name,
1567            truncated: false,
1568        })))
1569    }
1570
1571    fn fs() -> SharedFs {
1572        Arc::new(
1573            MemoryFs::new()
1574                .file("/d/a.png", b"\x89PNG\r\n\x1a\nrest".to_vec())
1575                .file("/d/b.txt", b"words".to_vec())
1576                .file("/d/c.bin", b"\x00\x01".to_vec())
1577                .file("/d/d.dat", b"MAGIC and more".to_vec())
1578                .dir("/d/sub"),
1579        )
1580    }
1581
1582    fn provider_of(shown: &Shown) -> &str {
1583        match shown {
1584            Shown::Ready(r) => &r.provider,
1585            other => panic!("not ready: {other:?}"),
1586        }
1587    }
1588
1589    #[test]
1590    fn providers_are_chosen_by_extension_type_magic_and_priority() {
1591        let p = Previews::default();
1592        let fs = fs();
1593        p.register(fake("low", Handles::new().mime(&["*/*"]), -100, named));
1594        p.register(fake("text", Handles::new().mime(&["text/*"]), 0, named));
1595        p.register(fake("magic", Handles::new().magic(b"MAGIC"), 0, named));
1596        p.register(fake(
1597            "png",
1598            Handles::new().extensions(&["PNG"]),
1599            5,
1600            |_| Ok(None), // passes to the next
1601        ));
1602        p.register(fake("folders", Handles::new().folders(), 0, named));
1603        assert_eq!(p.providers()[0], ("png".into(), 5));
1604        assert_eq!(provider_of(&p.compute(&fs, Path::new("/d/b.txt"))), "text");
1605        assert_eq!(provider_of(&p.compute(&fs, Path::new("/d/d.dat"))), "magic");
1606        assert_eq!(provider_of(&p.compute(&fs, Path::new("/d/a.png"))), "low");
1607        assert_eq!(provider_of(&p.compute(&fs, Path::new("/d/sub"))), "folders");
1608        let other = Previews::default();
1609        other.register(fake("png", Handles::new().extensions(&["png"]), 0, named));
1610        assert!(matches!(
1611            other.compute(&fs, Path::new("/d/c.bin")),
1612            Shown::Nothing
1613        ));
1614        assert!(matches!(
1615            other.compute(&fs, Path::new("/d/missing")),
1616            Shown::Failed(_)
1617        ));
1618    }
1619
1620    #[test]
1621    fn a_failure_or_a_panic_is_a_reason_not_a_crash() {
1622        let p = Previews::default();
1623        let fs = fs();
1624        p.register(fake("bad", Handles::new().extensions(&["txt"]), 0, |_| {
1625            Err("broken header".into())
1626        }));
1627        p.register(fake(
1628            "panics",
1629            Handles::new().extensions(&["png"]),
1630            0,
1631            |_| panic!("boom"),
1632        ));
1633        let Shown::Failed(e) = p.compute(&fs, Path::new("/d/b.txt")) else {
1634            panic!()
1635        };
1636        assert_eq!(e, "broken header");
1637        let Shown::Failed(e) = p.compute(&fs, Path::new("/d/a.png")) else {
1638            panic!()
1639        };
1640        assert!(e.contains("panics"), "{e}");
1641    }
1642
1643    #[test]
1644    fn previews_come_from_a_worker_and_are_cached_until_the_file_changes() {
1645        let p = Previews::default();
1646        p.register(fake("text", Handles::new().mime(&["text/*"]), 0, named));
1647        let ctx = egui::Context::default();
1648        let fs = fs();
1649        let path = Path::new("/d/b.txt");
1650        assert!(matches!(p.get(&ctx, &fs, path), Shown::Loading));
1651        let deadline = Instant::now() + Duration::from_secs(10);
1652        let ready = loop {
1653            match p.get(&ctx, &fs, path) {
1654                Shown::Ready(r) => break r,
1655                Shown::Loading => {
1656                    assert!(Instant::now() < deadline, "the worker did not answer");
1657                    std::thread::sleep(Duration::from_millis(5));
1658                }
1659                other => panic!("{other:?}"),
1660            }
1661        };
1662        assert_eq!(ready.provider, "text");
1663        // From the cache now.
1664        let Shown::Ready(again) = p.get(&ctx, &fs, path) else {
1665            panic!()
1666        };
1667        assert!(Arc::ptr_eq(&ready, &again));
1668        assert_eq!(p.describe()["cached"], 1);
1669        // The same path, changed: made again.
1670        let changed: SharedFs = Arc::new(MemoryFs::new().file(path, b"other words".to_vec()));
1671        assert!(matches!(p.peek(&changed, path), Shown::Loading));
1672        // The cache's cap drops the oldest.
1673        p.set_cache_bytes(0);
1674        assert_eq!(p.describe()["cached"], 0);
1675    }
1676
1677    #[test]
1678    fn asking_for_another_path_cancels_the_one_before() {
1679        let p = Previews::default();
1680        p.register(fake("slow", Handles::new().mime(&["*/*"]), 0, |r| {
1681            // Waits until cancelled (or a while).
1682            let until = Instant::now() + Duration::from_secs(10);
1683            while !r.cancelled() && Instant::now() < until {
1684                std::thread::sleep(Duration::from_millis(2));
1685            }
1686            Ok(Some(
1687                Preview::new(Body::Empty).fact("cancelled", r.cancelled().to_string()),
1688            ))
1689        }));
1690        let ctx = egui::Context::default();
1691        let fs = fs();
1692        assert!(matches!(
1693            p.get(&ctx, &fs, Path::new("/d/b.txt")),
1694            Shown::Loading
1695        ));
1696        // Wait until the worker holds it.
1697        let deadline = Instant::now() + Duration::from_secs(10);
1698        while p.describe()["running"].is_null() {
1699            assert!(Instant::now() < deadline, "the worker did not start");
1700            std::thread::sleep(Duration::from_millis(2));
1701        }
1702        assert!(matches!(
1703            p.get(&ctx, &fs, Path::new("/d/c.bin")),
1704            Shown::Loading
1705        ));
1706        let deadline = Instant::now() + Duration::from_secs(10);
1707        loop {
1708            if let Shown::Ready(r) = p.peek(&fs, Path::new("/d/b.txt")) {
1709                assert_eq!(r.preview.facts, [("cancelled".into(), "true".into())]);
1710                break;
1711            }
1712            assert!(Instant::now() < deadline, "the cancel was not seen");
1713            std::thread::sleep(Duration::from_millis(2));
1714        }
1715    }
1716
1717    /// The paths in `/many`, with their facts.
1718    fn many(n: usize) -> (SharedFs, Vec<(PathBuf, Meta)>) {
1719        let mut memory = MemoryFs::new();
1720        for i in 0..n {
1721            memory = memory.file(format!("/many/{i}.txt"), b"x".to_vec());
1722        }
1723        let fs: SharedFs = Arc::new(memory);
1724        let wanted = (0..n)
1725            .map(|i| {
1726                let path = PathBuf::from(format!("/many/{i}.txt"));
1727                let meta = fs.metadata(&path).unwrap();
1728                (path, meta)
1729            })
1730            .collect();
1731        (fs, wanted)
1732    }
1733
1734    fn until(what: &str, mut done: impl FnMut() -> bool) {
1735        let deadline = Instant::now() + Duration::from_secs(10);
1736        while !done() {
1737            assert!(Instant::now() < deadline, "{what}");
1738            std::thread::sleep(Duration::from_millis(2));
1739        }
1740    }
1741
1742    #[test]
1743    fn a_grid_gets_all_it_has_in_view_and_only_that() {
1744        static MADE: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
1745        let p = Previews::default();
1746        p.register(fake("text", Handles::new().mime(&["text/*"]), 0, |r| {
1747            lock(&MADE).push(r.path.clone());
1748            named(r)
1749        }));
1750        let ctx = egui::Context::default();
1751        let (fs, all) = many(1000);
1752        let view = &all[..20];
1753        assert!(matches!(
1754            p.thumbnail(&view[0].0, &view[0].1),
1755            Shown::Loading
1756        ));
1757        p.want(&ctx, &fs, view);
1758        until("the worker made what is in view", || {
1759            view.iter()
1760                .all(|(path, meta)| matches!(p.thumbnail(path, meta), Shown::Ready(_)))
1761        });
1762        let made = lock(&MADE).clone();
1763        assert_eq!(made.len(), 20);
1764        assert_eq!(made[0], view[0].0, "in the order asked");
1765        // Already made: nothing more is asked.
1766        p.want(&ctx, &fs, view);
1767        assert_eq!(p.describe()["queued"], 0);
1768    }
1769
1770    #[test]
1771    fn what_leaves_the_view_leaves_the_queue_and_stops_in_the_making() {
1772        let p = Previews::default();
1773        p.register(fake("slow", Handles::new().mime(&["*/*"]), 0, |r| {
1774            let until = Instant::now() + Duration::from_secs(10);
1775            while !r.cancelled() && Instant::now() < until {
1776                std::thread::sleep(Duration::from_millis(2));
1777            }
1778            Err("stopped".into())
1779        }));
1780        let ctx = egui::Context::default();
1781        let (fs, all) = many(10);
1782        p.want(&ctx, &fs, &all[..5]);
1783        until("the worker started", || !p.describe()["running"].is_null());
1784        assert_eq!(p.describe()["queued"], 4);
1785        // Scrolled away: the first is cancelled, the others are not made.
1786        p.want(&ctx, &fs, &all[8..]);
1787        assert!(p.describe()["queued"].as_u64() <= Some(2));
1788        until("the cancel was seen", || {
1789            p.describe()["running"].as_str() != Some("/many/0.txt")
1790        });
1791        assert!(matches!(p.thumbnail(&all[0].0, &all[0].1), Shown::Loading));
1792        p.cancel();
1793        assert_eq!(p.describe()["queued"], 0);
1794    }
1795
1796    #[test]
1797    fn the_preview_asked_goes_before_a_grid_s_queue() {
1798        let p = Previews::default();
1799        p.register(fake("slow", Handles::new().mime(&["*/*"]), 0, |r| {
1800            let until = Instant::now() + Duration::from_secs(10);
1801            while !r.cancelled() && Instant::now() < until {
1802                std::thread::sleep(Duration::from_millis(2));
1803            }
1804            named(r)
1805        }));
1806        let ctx = egui::Context::default();
1807        let (fs, all) = many(10);
1808        p.want(&ctx, &fs, &all[..5]);
1809        until("the worker started", || !p.describe()["running"].is_null());
1810        // The pane asks: the thumbnail in the making gives way.
1811        assert!(matches!(p.get(&ctx, &fs, &all[9].0), Shown::Loading));
1812        until("the pane's preview was made", || {
1813            p.describe()["running"].as_str() == Some("/many/9.txt")
1814        });
1815        p.cancel();
1816    }
1817
1818    #[test]
1819    fn what_is_in_view_stays_over_the_cache_s_cap() {
1820        let p = Previews::default();
1821        p.register(fake("text", Handles::new().mime(&["text/*"]), 0, named));
1822        let ctx = egui::Context::default();
1823        let (fs, all) = many(8);
1824        // Room for less than the view.
1825        p.set_cache_bytes(1000);
1826        p.want(&ctx, &fs, &all);
1827        until("the worker made all of the view", || {
1828            all.iter()
1829                .all(|(path, meta)| matches!(p.thumbnail(path, meta), Shown::Ready(_)))
1830        });
1831        // Out of view, they go as soon as the room is needed.
1832        let (others, more) = many(16);
1833        p.want(&ctx, &others, &more[8..]);
1834        until("the old ones went", || {
1835            more[8..]
1836                .iter()
1837                .all(|(path, meta)| matches!(p.thumbnail(path, meta), Shown::Ready(_)))
1838        });
1839        assert!(matches!(p.thumbnail(&all[0].0, &all[0].1), Shown::Loading));
1840    }
1841
1842    #[test]
1843    fn sizes_and_times_read_as_people_read_them() {
1844        assert_eq!(size_text(999), "999 B");
1845        assert_eq!(size_text(1500), "1.5 KB");
1846        assert_eq!(size_text(25_000_000), "25 MB");
1847        let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_768_471_440);
1848        assert_eq!(time_text(t), "2026-01-15 10:04 UTC");
1849    }
1850}