Skip to main content

egui_pop_core/
thumbnail.rs

1//! Thumbnails and a virtualised grid of them, from images the
2//! application supplies (a texture and its size), with a flat
3//! placeholder in the image's average colour until the image is there:
4//! no spinner per thumbnail. In this layer so that both the image tools
5//! (`egui_pop_viewport::thumbnail` re-exports it) and the file picker of
6//! the application API can draw them.
7//!
8//! <div class="warning">Experimental: may change in any release
9//! (docs/stability.md).</div>
10//!
11//! ```
12//! use egui_pop_core::thumbnail::{Thumbnail, thumbnail_grid};
13//!
14//! fn ui(ui: &mut egui::Ui, selected: &mut usize) {
15//!     thumbnail_grid(ui, 10_000, egui::vec2(96.0, 72.0), |ui, i| {
16//!         let r = ui.add(
17//!             Thumbnail::new(format!("Image {i}"))
18//!                 .placeholder(egui::Color32::from_gray(90))
19//!                 .selected(i == *selected),
20//!         );
21//!         if r.clicked() {
22//!             *selected = i;
23//!         }
24//!     });
25//! }
26//! ```
27
28use egui::{
29    Color32, Id, Modifiers, Rect, Response, Role, Sense, Stroke, StrokeKind, TextStyle,
30    TextWrapMode, TextureId, Ui, Vec2, Widget, WidgetInfo, WidgetText, pos2, vec2,
31};
32
33use crate::icon::Icon;
34use crate::kit::{Kit, KitCx, Part, State};
35use crate::theme::Tokens;
36use crate::ui::UiPop as _;
37
38/// One thumbnail.
39#[derive(Debug)]
40pub struct Thumbnail {
41    label: String,
42    image: Option<(TextureId, [u32; 2])>,
43    placeholder: Option<Color32>,
44    icon: Option<Icon>,
45    caption: Option<String>,
46    selected: bool,
47    size: Option<Vec2>,
48    passive: bool,
49}
50
51impl Thumbnail {
52    /// A thumbnail named `label` (its accessible name).
53    pub fn new(label: impl Into<String>) -> Thumbnail {
54        Thumbnail {
55            label: label.into(),
56            image: None,
57            placeholder: None,
58            icon: None,
59            caption: None,
60            selected: false,
61            size: None,
62            passive: false,
63        }
64    }
65
66    /// The image: a texture and its size in pixels (drawn fitted, its
67    /// aspect kept).
68    pub fn image(mut self, texture: TextureId, size: [u32; 2]) -> Thumbnail {
69        self.image = Some((texture, size));
70        self
71    }
72
73    /// The colour shown until the image is there (the image's average,
74    /// for example).
75    pub fn placeholder(mut self, color: Color32) -> Thumbnail {
76        self.placeholder = Some(color);
77        self
78    }
79
80    /// A sign over the placeholder, for what has no image: a folder, a
81    /// file without a preview, a failure.
82    pub fn icon(mut self, icon: Icon) -> Thumbnail {
83        self.icon = Some(icon);
84        self
85    }
86
87    /// A line of text under the image, cut to the thumbnail's width. Give
88    /// the thumbnail [`caption_height`] more room for it.
89    pub fn caption(mut self, caption: impl Into<String>) -> Thumbnail {
90        self.caption = Some(caption.into());
91        self
92    }
93
94    pub fn selected(mut self, selected: bool) -> Thumbnail {
95        self.selected = selected;
96        self
97    }
98
99    /// A picture only: drawn as usual, but it takes no click, drag or
100    /// keyboard focus, so the pointer reaches what is under it (a table
101    /// row, a list item that owns the click). It still senses the hover,
102    /// so a tooltip given to its response shows. Its accessible role is
103    /// an image, named by its label.
104    pub fn passive(mut self) -> Thumbnail {
105        self.passive = true;
106        self
107    }
108
109    /// The size in points (default: the grid cell, or 96 × 72).
110    pub fn size(mut self, size: Vec2) -> Thumbnail {
111        self.size = Some(size);
112        self
113    }
114}
115
116/// The room [`Thumbnail::caption`] takes under the image, in points.
117pub fn caption_height(ui: &Ui) -> f32 {
118    ui.text_style_height(&TextStyle::Small) + Tokens::of(ui.ctx()).space.xs
119}
120
121/// The largest rectangle of aspect `w:h` inside `outer`, centred.
122pub fn fitted(outer: Rect, size: [u32; 2]) -> Rect {
123    if size[0] == 0 || size[1] == 0 {
124        return outer;
125    }
126    let a = size[0] as f32 / size[1] as f32;
127    let (w, h) = if outer.width() / outer.height() > a {
128        (outer.height() * a, outer.height())
129    } else {
130        (outer.width(), outer.width() / a)
131    };
132    Rect::from_center_size(outer.center(), vec2(w, h))
133}
134
135impl Widget for Thumbnail {
136    fn ui(self, ui: &mut Ui) -> Response {
137        let size = self.size.unwrap_or_else(|| {
138            let s = ui.available_size_before_wrap();
139            if s.x.is_finite() && s.x > 0.0 && s.y.is_finite() && s.y > 0.0 && s.x < 400.0 {
140                s
141            } else {
142                vec2(96.0, 72.0)
143            }
144        });
145        let sense = if self.passive {
146            Sense::hover()
147        } else {
148            Sense::click()
149        };
150        let (rect, response) = ui.allocate_exact_size(size, sense);
151        let tokens = Tokens::of(ui.ctx());
152        let kit = Kit::of(ui.ctx());
153        // The kit's box (`thumbnail`): a selected thumbnail is not
154        // hovered. Painted unclipped, so the focus ring outside it shows.
155        let state = State::REST
156            .with(State::SELECTED, self.selected)
157            .with(
158                State::HOVER,
159                response.hovered() && !self.selected && !self.passive,
160            )
161            .with(State::FOCUS, crate::focus::shows_ring(&response));
162        if response.has_focus() {
163            crate::focus::own_ring(ui.ctx(), response.id);
164        }
165        kit.thumbnail.paint(
166            &KitCx {
167                painter: ui.painter(),
168                ppp: ui.ctx().pixels_per_point(),
169            },
170            &Part {
171                rect,
172                room: rect,
173                state,
174                label: None,
175            },
176        );
177        let painter = ui.painter_at(rect);
178        let mut inner = rect.shrink(tokens.space.xs.max(2.0));
179        let text = kit.thumbnail.style(state).text;
180        if let Some(caption) = &self.caption {
181            let room = caption_height(ui);
182            let line = Rect::from_min_max(pos2(inner.left(), inner.bottom() - room), inner.max);
183            inner.set_bottom(line.top());
184            let galley = WidgetText::from(caption.as_str()).into_galley(
185                ui,
186                Some(TextWrapMode::Truncate),
187                line.width(),
188                TextStyle::Small,
189            );
190            let at = pos2(
191                line.center().x - galley.size().x / 2.0,
192                line.bottom() - galley.size().y,
193            );
194            painter.galley(at, galley, text);
195        }
196        match (self.image, self.placeholder) {
197            (Some((id, px)), _) => {
198                painter.image(
199                    id,
200                    fitted(inner, px),
201                    Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
202                    Color32::WHITE,
203                );
204            }
205            (None, Some(c)) => {
206                painter.rect_filled(inner, 0.0, c);
207            }
208            (None, None) => {}
209        }
210        if let (None, Some(icon)) = (self.image, self.icon) {
211            let side = inner.width().min(inner.height()) / 2.0;
212            icon.paint(
213                &painter,
214                Rect::from_center_size(inner.center(), vec2(side, side)),
215                text,
216            );
217        }
218        let label = self.label;
219        let selected = self.selected;
220        let role = if self.passive {
221            Role::Image
222        } else {
223            Role::Button
224        };
225        response.widget_info(move || WidgetInfo::selected(role, true, selected, &label));
226        response
227    }
228}
229
230/// How a thumbnail grid's zoom answers a resize: what the zoom (its
231/// slider, `Ctrl` and `+` or `-`, `Ctrl` and the wheel) means, and so
232/// what a wider grid shows.
233///
234/// The application picks it for each grid: the file browser
235/// (`FileBrowser::with_resize`), the in-app picker
236/// (`FilesPlugin::grid_resize`) and the library grid
237/// (`ThumbGrid::resize`). Either way the zoom the person sets is kept.
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
239pub enum GridResize {
240    /// The zoom is a count per row: a wider grid shows the same count of
241    /// larger thumbnails (the default, egui-pop's behaviour since 0.16).
242    #[default]
243    PerRow,
244    /// The zoom is a size: a wider grid keeps the thumbnails' size and
245    /// shows more columns, as catalogue applications do. The cells share
246    /// what is left of a row, so a cell is drawn at most one column's
247    /// share larger than the size asked.
248    FixedSize,
249}
250
251/// A virtualised grid: only the rows in view are built, so ten thousand
252/// thumbnails cost what a screenful does. `item` draws cell `i`.
253pub fn thumbnail_grid(ui: &mut Ui, count: usize, cell: Vec2, item: impl FnMut(&mut Ui, usize)) {
254    ThumbnailGrid::new(count, cell).show(ui, item);
255}
256
257/// [`thumbnail_grid`] with its options: where it keeps its scrolling, how
258/// high it gets, and a cell to bring into view, drawn or not.
259///
260/// ```
261/// use egui_pop_core::thumbnail::{Thumbnail, ThumbnailGrid};
262///
263/// fn ui(ui: &mut egui::Ui, cursor: usize) {
264///     let columns = ThumbnailGrid::new(10_000, egui::vec2(96.0, 72.0))
265///         .id_salt("photos")
266///         .max_height(300.0)
267///         .reveal(Some(cursor))
268///         .show(ui, |ui, i| {
269///             ui.add(Thumbnail::new(format!("Image {i}")).selected(i == cursor));
270///         });
271///     // Up and Down move the cursor by `columns`.
272///     let _ = columns;
273/// }
274/// ```
275///
276/// Need (image): a grid of thumbnails.
277#[derive(Clone, Debug)]
278pub struct ThumbnailGrid {
279    count: usize,
280    cell: Vec2,
281    id_salt: Option<Id>,
282    max_height: Option<f32>,
283    reveal: Option<usize>,
284    band: bool,
285}
286
287/// What a [`ThumbnailGrid`] drawn with [`ThumbnailGrid::show_with_band`]
288/// tells.
289#[derive(Clone, Debug, Default, PartialEq)]
290#[non_exhaustive]
291pub struct GridOutput {
292    /// The number of cells in a row, what a move up or down skips.
293    pub per_row: usize,
294    /// A rubber band being drawn, or let go this frame.
295    pub band: Option<Band>,
296}
297
298/// A rubber band dragged across a grid ([`ThumbnailGrid::rubber_band`]).
299#[derive(Clone, Debug, PartialEq)]
300#[non_exhaustive]
301pub struct Band {
302    /// The cells it touches, in order, scrolled away or not.
303    pub cells: Vec<usize>,
304    /// The keys held when it started: Ctrl or Shift add to a selection.
305    pub modifiers: Modifiers,
306    /// Let go this frame: the selection it makes is final.
307    pub finished: bool,
308}
309
310/// How far the pointer moves before a drag draws a rubber band: a click is
311/// not a band.
312pub const BAND_MIN: f32 = 4.0;
313
314/// The cells of a grid `per_row` wide that `rect` touches, `rect` in the
315/// grid's own coordinates (its first cell's corner at the origin), each
316/// cell `cell` large, `gap` apart in a row and `pitch` from one row's top
317/// to the next's.
318pub fn cells_in(
319    rect: Rect,
320    per_row: usize,
321    count: usize,
322    cell: Vec2,
323    gap: f32,
324    pitch: f32,
325) -> Vec<usize> {
326    let per_row = per_row.max(1);
327    if count == 0 || rect.max.x < 0.0 || rect.max.y < 0.0 {
328        return Vec::new();
329    }
330    let step = cell.x + gap;
331    let rows = count.div_ceil(per_row);
332    let first_row = (rect.min.y.max(0.0) / pitch).floor() as usize;
333    let first_col = (rect.min.x.max(0.0) / step).floor() as usize;
334    let last_row = ((rect.max.y / pitch).floor() as usize).min(rows - 1);
335    let last_col = ((rect.max.x / step).floor() as usize).min(per_row - 1);
336    let mut out = Vec::new();
337    for row in first_row..=last_row {
338        for col in first_col..=last_col {
339            let i = row * per_row + col;
340            let min = pos2(col as f32 * step, row as f32 * pitch);
341            if i < count && Rect::from_min_size(min, cell).intersects(rect) {
342                out.push(i);
343            }
344        }
345    }
346    out
347}
348
349impl ThumbnailGrid {
350    /// A grid of `count` cells of size `cell`.
351    pub fn new(count: usize, cell: Vec2) -> ThumbnailGrid {
352        ThumbnailGrid {
353            count,
354            cell,
355            id_salt: None,
356            max_height: None,
357            reveal: None,
358            band: false,
359        }
360    }
361
362    /// A drag from the room around the cells draws a rubber band
363    /// (Finder's, Explorer's), which [`ThumbnailGrid::show_with_band`]
364    /// tells: the cells it touches, scrolled away or not.
365    pub fn rubber_band(mut self, on: bool) -> ThumbnailGrid {
366        self.band = on;
367        self
368    }
369
370    /// What tells its scrolling from another grid's in the same `Ui`.
371    pub fn id_salt(mut self, salt: impl egui::AsIdSalt) -> ThumbnailGrid {
372        self.id_salt = Some(Id::unique(salt));
373        self
374    }
375
376    /// The most it takes in height.
377    pub fn max_height(mut self, height: f32) -> ThumbnailGrid {
378        self.max_height = Some(height);
379        self
380    }
381
382    /// Scrolls by the least that shows this cell, which may not be drawn
383    /// yet: for a keyboard moving through a long grid.
384    pub fn reveal(mut self, cell: Option<usize>) -> ThumbnailGrid {
385        self.reveal = cell;
386        self
387    }
388
389    /// The room a grid drawn in `ui` lays its cells out in: its width
390    /// (the scroll bar aside) and the gap between cells. `n` cells of
391    /// `(width + gap) / n - gap` points fill a row.
392    pub fn room(ui: &Ui) -> (f32, f32) {
393        let gap = Tokens::of(ui.ctx()).space.xs;
394        let width = ui.available_width() - ui.spacing().scroll.allocated_width();
395        (width, gap)
396    }
397
398    /// Draws the rows in view, `item` drawing cell `i`. Gives the number of
399    /// cells in a row, what a move up or down skips.
400    pub fn show(self, ui: &mut Ui, item: impl FnMut(&mut Ui, usize)) -> usize {
401        self.show_with_band(ui, item).per_row
402    }
403
404    /// [`ThumbnailGrid::show`], telling the rubber band too.
405    pub fn show_with_band(self, ui: &mut Ui, mut item: impl FnMut(&mut Ui, usize)) -> GridOutput {
406        let ThumbnailGrid {
407            count,
408            cell,
409            id_salt,
410            max_height,
411            reveal,
412            band,
413        } = self;
414        let (width, gap) = ThumbnailGrid::room(ui);
415        let per_row = (((width + gap) / (cell.x + gap)).floor() as usize).max(1);
416        let rows = count.div_ceil(per_row);
417        let mut area = egui::ScrollArea::vertical()
418            .auto_shrink([false, false])
419            .animated(false);
420        if let Some(salt) = id_salt {
421            area = area.id_salt(salt);
422        }
423        if let Some(height) = max_height {
424            area = area.max_height(height);
425        }
426        // Rows lie one row height and the `Ui`'s spacing apart: the pitch
427        // `show_rows` works the first row in view out from.
428        let pitch = cell.y + ui.spacing().item_spacing.y;
429        let band_id = ui.scope_id().with(("thumbnail_grid.band", id_salt));
430        let mut told = None;
431        let out = ui.scroll_area_rows(area, cell.y, rows, |ui, range| {
432            if band {
433                // Under the cells, which take the clicks: the grid's own
434                // coordinates start at its first cell's corner.
435                let origin = ui.max_rect().min - vec2(0.0, range.start as f32 * pitch);
436                told = rubber_band(ui, band_id, origin, |r| {
437                    cells_in(r, per_row, count, cell, gap, pitch)
438                });
439            }
440            if let Some(i) = reveal {
441                let top = ui.max_rect().top() + ((i / per_row) as f32 - range.start as f32) * pitch;
442                let left = ui.max_rect().left();
443                ui.scroll_to_rect(
444                    Rect::from_min_size(pos2(left, top), vec2(cell.x, cell.y)),
445                    None,
446                );
447                ui.ctx().request_repaint();
448            }
449            for row in range {
450                ui.horizontal(|ui| {
451                    ui.spacing_mut().item_spacing = vec2(gap, gap);
452                    for col in 0..per_row {
453                        let i = row * per_row + col;
454                        if i >= count {
455                            break;
456                        }
457                        ui.allocate_ui(cell, |ui| {
458                            ui.set_min_size(cell);
459                            item(ui, i);
460                        });
461                    }
462                });
463            }
464        });
465        crate::ui::contain_wheel(ui, &out);
466        GridOutput {
467            per_row,
468            band: told,
469        }
470    }
471}
472
473/// A band's corners in the grid's coordinates, and the keys held when it
474/// started; kept between frames under the grid's id.
475#[derive(Clone, Copy, Debug)]
476struct BandDrag {
477    from: Vec2,
478    to: Vec2,
479    modifiers: Modifiers,
480}
481
482/// Reads and paints a rubber band over the room in view, `origin` the
483/// grid's first cell's corner on screen; `cells` says what a rectangle in
484/// the grid's coordinates touches.
485fn rubber_band(
486    ui: &mut Ui,
487    id: Id,
488    origin: egui::Pos2,
489    cells: impl Fn(Rect) -> Vec<usize>,
490) -> Option<Band> {
491    // The room in view, the grid's empty end included: the scroll area
492    // clips its rows only up and down, so the clip rect is narrowed to the
493    // grid's own width, never sensing what lies beside the grid.
494    let clip = ui.clip_rect();
495    let room = Rect::from_x_y_ranges(ui.max_rect().x_range(), clip.y_range()).intersect(clip);
496    let bg = ui.interact(room, id, Sense::drag());
497    let mut drag: Option<BandDrag> = ui.data(|d| d.get_temp(id));
498    if bg.drag_started()
499        && let Some(p) = bg.interact_pointer_pos()
500    {
501        let at = p - origin;
502        drag = Some(BandDrag {
503            from: at,
504            to: at,
505            modifiers: ui.input(|i| i.modifiers),
506        });
507    }
508    if bg.dragged()
509        && let (Some(d), Some(p)) = (drag.as_mut(), bg.interact_pointer_pos())
510    {
511        d.to = p - origin;
512    }
513    let finished = bg.drag_stopped();
514    let shown = drag.filter(|d| (d.to - d.from).length() >= BAND_MIN);
515    let told = shown.map(|d| {
516        let r = Rect::from_two_pos(d.from.to_pos2(), d.to.to_pos2());
517        if !finished {
518            let t = Tokens::of(ui.ctx());
519            let fill = t
520                .color("thumbnail.band")
521                .unwrap_or(t.accent.default.gamma_multiply(0.18));
522            let outline = t
523                .color("thumbnail.band-outline")
524                .unwrap_or(t.accent.default);
525            let on_screen = r.translate(origin.to_vec2());
526            let painter = ui.painter().clone();
527            painter.rect_filled(on_screen, 0.0, fill);
528            painter.rect_stroke(
529                on_screen,
530                0.0,
531                Stroke::new(1.0, outline),
532                StrokeKind::Inside,
533            );
534            crate::pointer::hold_drag_cursor(ui.ctx(), crate::pointer::DragKind::Select);
535        }
536        Band {
537            cells: cells(r),
538            modifiers: d.modifiers,
539            finished,
540        }
541    });
542    if finished || !(bg.dragged() || bg.drag_started()) {
543        drag = None;
544    }
545    ui.data_mut(|d| match drag {
546        Some(b) => {
547            d.insert_temp(id, b);
548        }
549        None => d.remove::<BandDrag>(id),
550    });
551    told
552}
553
554#[cfg(test)]
555mod band_tests {
556    use super::*;
557
558    #[test]
559    fn a_band_touches_the_cells_it_crosses_and_none_beyond_the_last() {
560        let cell = vec2(10.0, 10.0);
561        // Three a row, 2 apart; rows 12 apart.
562        let at = |a: (f32, f32), b: (f32, f32)| {
563            cells_in(
564                Rect::from_two_pos(pos2(a.0, a.1), pos2(b.0, b.1)),
565                3,
566                7,
567                cell,
568                2.0,
569                12.0,
570            )
571        };
572        assert_eq!(at((1.0, 1.0), (2.0, 2.0)), [0]);
573        // Across the first two cells of the first two rows.
574        assert_eq!(at((5.0, 5.0), (15.0, 15.0)), [0, 1, 3, 4]);
575        // In a gap alone: nothing.
576        assert!(at((10.5, 0.0), (11.5, 30.0)).is_empty());
577        // Down past the end: the short last row's cell only.
578        assert_eq!(at((0.0, 30.0), (100.0, 100.0)), [6]);
579        // Above and left of the grid.
580        assert!(at((-20.0, -20.0), (-1.0, -1.0)).is_empty());
581    }
582}