Skip to main content

egui_pop_views/library/
thumbs.rs

1//! The file browser's thumbnail contract in the library's views: one
2//! [`ThumbnailProvider`] serves the browser, the picker, the grid, the
3//! filmstrip and the comparison.
4//!
5//! [`ProviderThumbs`] is a [`ThumbSource`] over a provider, for one
6//! frame: made before the views are drawn (it begins the provider's
7//! frame), dropped after (it ends it, so what scrolled away leaves the
8//! provider's queue). The application says which file each key is.
9//!
10//! ```no_run
11//! use egui_pop_api::files::browser::{SourceEntry, ThumbnailProvider};
12//! use egui_pop_views::library::thumbs::ProviderThumbs;
13//!
14//! fn entry_of(key: &u64) -> Option<SourceEntry> { todo!() }
15//!
16//! fn ui(ui: &mut egui::Ui, provider: &dyn ThumbnailProvider) {
17//!     let thumbs = ProviderThumbs::begin(ui.ctx(), provider, entry_of);
18//!     // ThumbGrid::show(ui, state, items, &thumbs) …
19//!     drop(thumbs); // ends the provider's frame
20//! }
21//! ```
22//!
23//! Its badges meet the browser's the same way: a [`Badge`] is a
24//! [`MarkChip`] (`MarkChip::from(badge)`), both drawn as indicators.
25//! So does its zoom: a grid's [`Zoom`] and the browser's and picker's
26//! [`ThumbZoom`] are the same count per row, converted with `From`.
27
28use egui::Context;
29use egui_pop_api::files::browser::{
30    MarkChip, Priority, SourceEntry, ThumbRequest, ThumbState, ThumbZoom, ThumbnailProvider,
31};
32
33use super::grid::{Badge, Thumb, ThumbSource, Zoom};
34
35/// The browser's zoom as a grid's: the same count per row, or the same
36/// size in points still to convert.
37impl From<ThumbZoom> for Zoom {
38    fn from(zoom: ThumbZoom) -> Zoom {
39        match zoom {
40            ThumbZoom::PerRow(n) => Zoom::PerRow(n),
41            ThumbZoom::Points(p) => Zoom::Points(p),
42        }
43    }
44}
45
46/// A grid's zoom as the browser's.
47impl From<Zoom> for ThumbZoom {
48    fn from(zoom: Zoom) -> ThumbZoom {
49        match zoom {
50            Zoom::PerRow(n) => ThumbZoom::PerRow(n),
51            Zoom::Points(p) => ThumbZoom::Points(p),
52        }
53    }
54}
55
56/// A thumbnail as a provider has it, as the library draws it. A file
57/// with no image of its own ([`ThumbState::None`], a folder) and one
58/// that failed both show the grid's warning sign: the library shows
59/// images.
60impl From<&ThumbState> for Thumb {
61    fn from(state: &ThumbState) -> Thumb {
62        match state {
63            ThumbState::Ready(texture) => {
64                let [w, h] = texture.size();
65                Thumb::Ready {
66                    texture: texture.id(),
67                    size: [
68                        u32::try_from(w).unwrap_or(u32::MAX),
69                        u32::try_from(h).unwrap_or(u32::MAX),
70                    ],
71                }
72            }
73            ThumbState::Loading => Thumb::Pending { average: None },
74            ThumbState::None | ThumbState::Failed(_) => Thumb::Failed,
75        }
76    }
77}
78
79/// A library badge as the file browser's chip: its text, named by its
80/// text, of its tone, in the bottom right corner, where the library
81/// draws its badges.
82impl From<Badge> for MarkChip {
83    fn from(badge: Badge) -> MarkChip {
84        let name = badge.said().to_owned();
85        match badge.icon {
86            Some(icon) => MarkChip::icon(icon, name),
87            None => MarkChip::text(badge.text, name),
88        }
89        .tone(badge.tone)
90    }
91}
92
93/// Which file a key is ([`ProviderThumbs::begin`]).
94type EntryOf<'a, K> = dyn Fn(&K) -> Option<SourceEntry> + 'a;
95
96/// A [`ThumbSource`] over a [`ThumbnailProvider`] for one frame: made
97/// with [`ProviderThumbs::begin`], which begins the provider's frame,
98/// and dropped once the views are drawn, which ends it.
99pub struct ProviderThumbs<'a, K> {
100    ctx: Context,
101    provider: &'a dyn ThumbnailProvider,
102    entry: Box<EntryOf<'a, K>>,
103}
104
105impl<K> std::fmt::Debug for ProviderThumbs<'_, K> {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        f.debug_struct("ProviderThumbs").finish_non_exhaustive()
108    }
109}
110
111impl<'a, K> ProviderThumbs<'a, K> {
112    /// Begins `provider`'s frame. `entry` says which file a key is; a
113    /// key it does not know shows the warning sign.
114    pub fn begin(
115        ctx: &Context,
116        provider: &'a dyn ThumbnailProvider,
117        entry: impl Fn(&K) -> Option<SourceEntry> + 'a,
118    ) -> Self {
119        provider.begin_frame(ctx);
120        Self {
121            ctx: ctx.clone(),
122            provider,
123            entry: Box::new(entry),
124        }
125    }
126
127    fn ask(&self, key: &K, size: u32, priority: Priority) -> Thumb {
128        match (self.entry)(key) {
129            Some(entry) => Thumb::from(&self.provider.request(
130                &self.ctx,
131                &ThumbRequest {
132                    entry: &entry,
133                    size,
134                    priority,
135                },
136            )),
137            None => Thumb::Failed,
138        }
139    }
140}
141
142impl<K> ThumbSource<K> for ProviderThumbs<'_, K> {
143    /// Asks the provider, as on screen now.
144    fn thumb(&self, key: &K, size: u32) -> Thumb {
145        self.ask(key, size, Priority::Visible)
146    }
147
148    /// The images in view, already asked for by [`Self::thumb`]: asked
149    /// again, so that a view telling only what it wants keeps them in
150    /// the provider's queue this frame.
151    fn wanted(&self, keys: &[K], size: u32) {
152        for key in keys {
153            let _ = self.ask(key, size, Priority::Visible);
154        }
155    }
156}
157
158impl<K> Drop for ProviderThumbs<'_, K> {
159    fn drop(&mut self) {
160        self.provider.end_frame(&self.ctx);
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use crate::library::grid;
168    use egui_pop_api::files::browser::EntryKind;
169    use egui_pop_core::kit::Tone;
170    use std::path::{Path, PathBuf};
171    use std::sync::Mutex;
172
173    #[derive(Default)]
174    struct Log(Mutex<Vec<String>>);
175
176    impl ThumbnailProvider for Log {
177        fn begin_frame(&self, _ctx: &Context) {
178            self.0.lock().unwrap().push("begin".into());
179        }
180        fn request(&self, _ctx: &Context, request: &ThumbRequest<'_>) -> ThumbState {
181            self.0
182                .lock()
183                .unwrap()
184                .push(format!("{} {}", request.entry.name, request.size));
185            if request.entry.name == "broken.png" {
186                ThumbState::Failed("no".into())
187            } else {
188                ThumbState::Loading
189            }
190        }
191        fn end_frame(&self, _ctx: &Context) {
192            self.0.lock().unwrap().push("end".into());
193        }
194        fn cancel(&self, _path: &Path) {}
195    }
196
197    fn entry(name: &str) -> SourceEntry {
198        SourceEntry {
199            path: PathBuf::from("/shoot").join(name),
200            name: name.into(),
201            kind: EntryKind::File,
202            size: Some(1),
203            modified: None,
204            taken: None,
205            app_id: None,
206        }
207    }
208
209    #[test]
210    fn a_frame_asks_the_provider_between_its_begin_and_end() {
211        let ctx = Context::default();
212        let log = Log::default();
213        let names = ["a.png", "broken.png"];
214        {
215            let thumbs =
216                ProviderThumbs::begin(&ctx, &log, |k: &usize| names.get(*k).map(|n| entry(n)));
217            assert_eq!(thumbs.thumb(&0, 96), Thumb::Pending { average: None });
218            assert_eq!(thumbs.thumb(&1, 96), Thumb::Failed);
219            // A key the application does not know.
220            assert_eq!(thumbs.thumb(&7, 96), Thumb::Failed);
221        }
222        assert_eq!(
223            *log.0.lock().unwrap(),
224            ["begin", "a.png 96", "broken.png 96", "end"]
225        );
226    }
227
228    #[test]
229    fn a_badge_is_a_bottom_right_chip_of_its_tone() {
230        let chip = MarkChip::from(Badge::new("RAW").tone(Tone::Info));
231        assert_eq!(chip, MarkChip::text("RAW", "RAW").tone(Tone::Info));
232    }
233
234    #[test]
235    fn an_icon_badge_is_a_top_right_chip_under_its_name() {
236        let chip = MarkChip::from(Badge::icon("phosphor:plugs", "offline").tone(Tone::Warning));
237        assert_eq!(
238            chip,
239            MarkChip::icon("phosphor:plugs", "offline").tone(Tone::Warning)
240        );
241        let pair = MarkChip::from(Badge::new("R+J").named("RAW+JPG"));
242        assert_eq!(pair, MarkChip::text("R+J", "RAW+JPG"));
243    }
244
245    #[test]
246    fn the_browser_zoom_and_the_grid_zoom_are_one_count_per_row() {
247        assert_eq!(Zoom::from(ThumbZoom::PerRow(1)), Zoom::PerRow(1));
248        assert_eq!(ThumbZoom::from(Zoom::PerRow(8)), ThumbZoom::PerRow(8));
249        assert_eq!(Zoom::from(ThumbZoom::Points(128.0)), Zoom::Points(128.0));
250        assert_eq!(
251            ThumbZoom::from(Zoom::default()),
252            ThumbZoom::PerRow(grid::DEFAULT_PER_ROW)
253        );
254    }
255}