Skip to main content

egui_pop_api/files/
providers.rs

1//! The built-in preview providers, registered by the files plugin
2//! unless it is told not to ([`FilesPlugin::without_builtin_previews`]):
3//!
4//! - [`Images`] (feature `image-previews`, on by default): PNG and JPEG
5//!   decoded with the `image` crate, scaled down, with their dimensions;
6//! - [`Markdown`]: a Markdown document drawn simply (headings, items,
7//!   quotes, code, rules; emphasis and links as plain text): no Markdown
8//!   renderer is in the tree, this is a small one of its own;
9//! - [`Text`]: the first lines of a text or code file, in a monospace
10//!   font; any file that reads as UTF-8 text, at the lowest priority;
11//! - [`Folders`]: what a folder holds and its first images, as the
12//!   providers preview them.
13//!
14//! [`FilesPlugin::without_builtin_previews`]: super::FilesPlugin::without_builtin_previews
15
16use std::path::Path;
17use std::sync::Arc;
18
19use super::preview::{Block, Body, Handles, Preview, PreviewProvider, PreviewRequest, Probe};
20
21/// How much of a text is read.
22const TEXT_BYTES: usize = 64 * 1024;
23/// How many lines of a text are shown.
24const TEXT_LINES: usize = 40;
25/// How long a line of a text is shown.
26const LINE_CHARS: usize = 160;
27/// How many blocks of a document are shown.
28const BLOCKS: usize = 60;
29/// How many images of a folder are shown, from how many files.
30const THUMBNAILS: usize = 4;
31const THUMBNAIL_TRIES: usize = 16;
32/// The side of a folder's thumbnails, in pixels.
33const THUMBNAIL_SIDE: u32 = 112;
34
35/// The built-in providers, highest priority first.
36pub fn builtin() -> Vec<Arc<dyn PreviewProvider>> {
37    vec![
38        #[cfg(feature = "image-previews")]
39        Arc::new(Images),
40        Arc::new(Markdown),
41        Arc::new(Folders),
42        Arc::new(Text),
43    ]
44}
45
46/// PNG and JPEG images, decoded with the `image` crate.
47#[cfg(feature = "image-previews")]
48#[derive(Clone, Copy, Debug, Default)]
49pub struct Images;
50
51#[cfg(feature = "image-previews")]
52impl PreviewProvider for Images {
53    fn id(&self) -> &str {
54        "egui_pop.images"
55    }
56
57    fn handles(&self) -> Handles {
58        Handles::new()
59            .extensions(&["png", "jpg", "jpeg", "jpe"])
60            .mime(&["image/png", "image/jpeg"])
61            .magic(b"\x89PNG\r\n\x1a\n")
62            .magic(b"\xff\xd8\xff")
63    }
64
65    fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
66        let bytes = request.read()?;
67        let mut reader = image::ImageReader::new(std::io::Cursor::new(&bytes))
68            .with_guessed_format()
69            .map_err(|e| e.to_string())?;
70        let mut limits = image::Limits::default();
71        limits.max_alloc = Some(512 * 1024 * 1024);
72        reader.limits(limits);
73        let image = reader.decode().map_err(|e| e.to_string())?;
74        if request.cancelled() {
75            return Err("cancelled".into());
76        }
77        let (w, h) = (image.width(), image.height());
78        let side = request.max_side;
79        let small = if w.max(h) > side {
80            image.thumbnail(side, side)
81        } else {
82            image
83        };
84        let rgba = small.to_rgba8();
85        let pixels = egui::ColorImage::from_rgba_unmultiplied(
86            [rgba.width() as usize, rgba.height() as usize],
87            rgba.as_raw(),
88        );
89        Ok(Some(
90            Preview::new(Body::Image(Arc::new(pixels))).dimensions(w, h),
91        ))
92    }
93}
94
95/// Text and code: the first lines.
96#[derive(Clone, Copy, Debug, Default)]
97pub struct Text;
98
99/// Whether bytes read as text: UTF-8 (a character cut at the end
100/// allowed), no NUL.
101fn is_text(bytes: &[u8]) -> bool {
102    if bytes.contains(&0) {
103        return false;
104    }
105    match std::str::from_utf8(bytes) {
106        Ok(_) => true,
107        Err(e) => e.error_len().is_none(),
108    }
109}
110
111/// A text's first bytes as a string (a character cut at the end
112/// dropped).
113fn text_of(bytes: &[u8]) -> String {
114    match std::str::from_utf8(bytes) {
115        Ok(s) => s.to_string(),
116        Err(e) => String::from_utf8_lossy(&bytes[..e.valid_up_to()]).into_owned(),
117    }
118}
119
120impl PreviewProvider for Text {
121    fn id(&self) -> &str {
122        "egui_pop.text"
123    }
124
125    fn handles(&self) -> Handles {
126        // Any file: `accepts` keeps those that read as text.
127        Handles::new().mime(&["*/*"])
128    }
129
130    fn priority(&self) -> i32 {
131        -10
132    }
133
134    fn accepts(&self, probe: &Probe<'_>) -> bool {
135        probe.mime.is_some_and(|m| m.starts_with("text/"))
136            || probe.meta.len == 0
137            || (!probe.head.is_empty() && is_text(probe.head))
138    }
139
140    fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
141        let bytes = request.read_head(TEXT_BYTES)?;
142        if !is_text(&bytes) {
143            return Ok(None);
144        }
145        let all = text_of(&bytes);
146        let mut truncated = (bytes.len() as u64) < request.meta.len;
147        let mut text = String::new();
148        for (n, line) in all.lines().enumerate() {
149            if n == TEXT_LINES {
150                truncated = true;
151                break;
152            }
153            let line = line.trim_end_matches('\r');
154            match line.char_indices().nth(LINE_CHARS) {
155                Some((cut, _)) => {
156                    text.push_str(&line[..cut]);
157                    text.push('…');
158                }
159                None => text.push_str(line),
160            }
161            text.push('\n');
162        }
163        let text = text.trim_end_matches('\n').replace('\t', "    ");
164        Ok(Some(Preview::new(Body::Text { text, truncated })))
165    }
166}
167
168/// Markdown, drawn simply.
169#[derive(Clone, Copy, Debug, Default)]
170pub struct Markdown;
171
172impl PreviewProvider for Markdown {
173    fn id(&self) -> &str {
174        "egui_pop.markdown"
175    }
176
177    fn handles(&self) -> Handles {
178        Handles::new()
179            .extensions(&["md", "markdown"])
180            .mime(&["text/markdown"])
181    }
182
183    fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
184        let bytes = request.read_head(TEXT_BYTES)?;
185        if !is_text(&bytes) {
186            return Ok(None);
187        }
188        Ok(Some(Preview::new(Body::Markdown(markdown(&text_of(
189            &bytes,
190        ))))))
191    }
192}
193
194/// Emphasis, code marks and links as plain text.
195fn plain(s: &str) -> String {
196    let mut out = String::with_capacity(s.len());
197    let mut rest = s;
198    while let Some(open) = rest.find('[') {
199        out.push_str(&rest[..open]);
200        let after = &rest[open + 1..];
201        match after.find("](").and_then(|mid| {
202            let close = after[mid + 2..].find(')')?;
203            Some((mid, mid + 2 + close))
204        }) {
205            Some((mid, close)) => {
206                out.push_str(&after[..mid]);
207                rest = &after[close + 1..];
208            }
209            None => {
210                out.push('[');
211                rest = after;
212            }
213        }
214    }
215    out.push_str(rest);
216    out.replace("**", "").replace("__", "").replace('`', "")
217}
218
219/// A Markdown text as blocks: headings, paragraphs, items, quotes,
220/// code lines and rules.
221pub fn markdown(text: &str) -> Vec<Block> {
222    let mut out = Vec::new();
223    let mut paragraph: Vec<&str> = Vec::new();
224    let mut code = false;
225    let flush = |paragraph: &mut Vec<&str>, out: &mut Vec<Block>| {
226        if !paragraph.is_empty() {
227            out.push(Block::Paragraph(plain(&paragraph.join(" "))));
228            paragraph.clear();
229        }
230    };
231    for line in text.lines() {
232        if out.len() >= BLOCKS {
233            break;
234        }
235        let line = line.trim_end();
236        let t = line.trim_start();
237        if t.starts_with("```") || t.starts_with("~~~") {
238            flush(&mut paragraph, &mut out);
239            code = !code;
240            continue;
241        }
242        if code {
243            out.push(Block::Code(line.replace('\t', "    ")));
244            continue;
245        }
246        if t.is_empty() {
247            flush(&mut paragraph, &mut out);
248            continue;
249        }
250        let hashes = t.chars().take_while(|c| *c == '#').count();
251        if (1..=6).contains(&hashes) && t[hashes..].starts_with(' ') {
252            flush(&mut paragraph, &mut out);
253            let title = t[hashes..].trim().trim_end_matches('#').trim();
254            out.push(Block::Heading(hashes as u8, plain(title)));
255            continue;
256        }
257        let bare: String = t.chars().filter(|c| !c.is_whitespace()).collect();
258        if bare.len() >= 3
259            && (bare.chars().all(|c| c == '-')
260                || bare.chars().all(|c| c == '*')
261                || bare.chars().all(|c| c == '_'))
262        {
263            flush(&mut paragraph, &mut out);
264            out.push(Block::Rule);
265            continue;
266        }
267        let digits = t.chars().take_while(char::is_ascii_digit).count();
268        let item = ["- ", "* ", "+ "]
269            .iter()
270            .find_map(|m| t.strip_prefix(m))
271            .or_else(|| {
272                (digits > 0)
273                    .then(|| t[digits..].strip_prefix(". "))
274                    .flatten()
275            });
276        if let Some(item) = item {
277            flush(&mut paragraph, &mut out);
278            out.push(Block::Item(plain(item.trim())));
279            continue;
280        }
281        if let Some(q) = t.strip_prefix('>') {
282            flush(&mut paragraph, &mut out);
283            out.push(Block::Quote(plain(q.trim())));
284            continue;
285        }
286        paragraph.push(t);
287    }
288    if out.len() < BLOCKS {
289        flush(&mut paragraph, &mut out);
290    }
291    out
292}
293
294/// Folders: what they hold, and their first images.
295#[derive(Clone, Copy, Debug, Default)]
296pub struct Folders;
297
298impl PreviewProvider for Folders {
299    fn id(&self) -> &str {
300        "egui_pop.folders"
301    }
302
303    fn handles(&self) -> Handles {
304        Handles::new().folders()
305    }
306
307    fn preview(&self, request: &PreviewRequest) -> Result<Option<Preview>, String> {
308        let items = request
309            .fs()
310            .read_dir(&request.path)
311            .map_err(|e| e.to_string())?;
312        let items: Vec<_> = items
313            .into_iter()
314            .filter(|e| !e.name.starts_with('.'))
315            .collect();
316        let folders = items.iter().filter(|e| e.is_dir).count();
317        let mut files: Vec<&str> = items
318            .iter()
319            .filter(|e| !e.is_dir)
320            .map(|e| e.name.as_str())
321            .collect();
322        files.sort_by_key(|n| n.to_lowercase());
323        let mut thumbnails = Vec::new();
324        // Images, and files of no known type (an application's own).
325        let candidates = files.iter().filter(|n| {
326            super::preview::mime_of(Path::new(n)).is_none_or(|m| m.starts_with("image/"))
327        });
328        for name in candidates.take(THUMBNAIL_TRIES) {
329            if thumbnails.len() == THUMBNAILS || request.cancelled() {
330                break;
331            }
332            if let Some(Preview {
333                body: Body::Image(image),
334                ..
335            }) = request.preview_of(&request.path.join(name), THUMBNAIL_SIDE)
336            {
337                thumbnails.push(image);
338            }
339        }
340        Ok(Some(Preview::new(Body::Folder {
341            folders,
342            files: files.len(),
343            thumbnails,
344        })))
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use crate::files::fs::{MemoryFs, SharedFs};
352    use crate::files::preview::{Previews, Shown};
353
354    fn previews() -> Previews {
355        let p = Previews::default();
356        for provider in builtin() {
357            p.register(provider);
358        }
359        p
360    }
361
362    fn ready(shown: Shown) -> Arc<crate::files::preview::Ready> {
363        match shown {
364            Shown::Ready(r) => r,
365            other => panic!("not ready: {other:?}"),
366        }
367    }
368
369    #[test]
370    fn markdown_reads_as_blocks() {
371        let blocks = markdown(
372            "# Plan\n\nSome **bold** text\nand a [link](http://x).\n\n- one\n2. two\n> said\n\n---\n```\nlet a = 1;\n```\n",
373        );
374        assert_eq!(
375            blocks,
376            vec![
377                Block::Heading(1, "Plan".into()),
378                Block::Paragraph("Some bold text and a link.".into()),
379                Block::Item("one".into()),
380                Block::Item("two".into()),
381                Block::Quote("said".into()),
382                Block::Rule,
383                Block::Code("let a = 1;".into()),
384            ]
385        );
386    }
387
388    #[test]
389    fn texts_documents_and_folders_preview() {
390        let long: String = (0..100).map(|n| format!("line {n}\n")).collect();
391        let fs: SharedFs = Arc::new(
392            MemoryFs::new()
393                .file("/d/notes.txt", long.into_bytes())
394                .file("/d/README", b"plain words".to_vec())
395                .file("/d/plan.md", b"# Plan\n\nWords.".to_vec())
396                .file("/d/blob.bin", vec![0, 1, 2, 3])
397                .dir("/d/sub"),
398        );
399        let p = previews();
400        let r = ready(p.compute(&fs, Path::new("/d/notes.txt")));
401        assert_eq!(r.provider, "egui_pop.text");
402        let Body::Text { text, truncated } = &r.preview.body else {
403            panic!()
404        };
405        assert_eq!(text.lines().count(), TEXT_LINES);
406        assert!(truncated);
407        // No extension, but text.
408        assert_eq!(
409            ready(p.compute(&fs, Path::new("/d/README"))).provider,
410            "egui_pop.text"
411        );
412        let r = ready(p.compute(&fs, Path::new("/d/plan.md")));
413        assert_eq!(r.provider, "egui_pop.markdown");
414        assert!(matches!(&r.preview.body, Body::Markdown(b) if b.len() == 2));
415        // Binary: no provider.
416        assert!(matches!(
417            p.compute(&fs, Path::new("/d/blob.bin")),
418            Shown::Nothing
419        ));
420        let r = ready(p.compute(&fs, Path::new("/d")));
421        assert!(matches!(
422            r.preview.body,
423            Body::Folder {
424                folders: 1,
425                files: 4,
426                ..
427            }
428        ));
429    }
430
431    #[cfg(feature = "image-previews")]
432    #[test]
433    fn images_are_scaled_down_with_their_dimensions() {
434        let mut png = Vec::new();
435        image::RgbImage::from_pixel(600, 300, image::Rgb([200, 40, 40]))
436            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
437            .unwrap();
438        let fs: SharedFs = Arc::new(
439            MemoryFs::new()
440                .file("/d/red.png", png.clone())
441                // A PNG by its bytes, whatever its name.
442                .file("/d/red.data", png)
443                .file("/d/broken.png", b"\x89PNG\r\n\x1a\nnot really".to_vec()),
444        );
445        let p = previews();
446        let r = ready(p.compute(&fs, Path::new("/d/red.png")));
447        assert_eq!(r.preview.dimensions, Some([600, 300]));
448        let Body::Image(i) = &r.preview.body else {
449            panic!()
450        };
451        assert_eq!(i.size, [256, 128]);
452        assert_eq!(
453            ready(p.compute(&fs, Path::new("/d/red.data"))).provider,
454            "egui_pop.images"
455        );
456        assert!(matches!(
457            p.compute(&fs, Path::new("/d/broken.png")),
458            Shown::Failed(_)
459        ));
460        // A folder's first images.
461        let r = ready(p.compute(&fs, Path::new("/d")));
462        let Body::Folder { thumbnails, .. } = &r.preview.body else {
463            panic!()
464        };
465        assert_eq!(thumbnails.len(), 2);
466        assert_eq!(thumbnails[0].size[0], THUMBNAIL_SIDE as usize);
467    }
468}