1use 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#[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 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 pub fn image(mut self, texture: TextureId, size: [u32; 2]) -> Thumbnail {
69 self.image = Some((texture, size));
70 self
71 }
72
73 pub fn placeholder(mut self, color: Color32) -> Thumbnail {
76 self.placeholder = Some(color);
77 self
78 }
79
80 pub fn icon(mut self, icon: Icon) -> Thumbnail {
83 self.icon = Some(icon);
84 self
85 }
86
87 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 pub fn passive(mut self) -> Thumbnail {
105 self.passive = true;
106 self
107 }
108
109 pub fn size(mut self, size: Vec2) -> Thumbnail {
111 self.size = Some(size);
112 self
113 }
114}
115
116pub fn caption_height(ui: &Ui) -> f32 {
118 ui.text_style_height(&TextStyle::Small) + Tokens::of(ui.ctx()).space.xs
119}
120
121pub 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
239pub enum GridResize {
240 #[default]
243 PerRow,
244 FixedSize,
249}
250
251pub 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#[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#[derive(Clone, Debug, Default, PartialEq)]
290#[non_exhaustive]
291pub struct GridOutput {
292 pub per_row: usize,
294 pub band: Option<Band>,
296}
297
298#[derive(Clone, Debug, PartialEq)]
300#[non_exhaustive]
301pub struct Band {
302 pub cells: Vec<usize>,
304 pub modifiers: Modifiers,
306 pub finished: bool,
308}
309
310pub const BAND_MIN: f32 = 4.0;
313
314pub 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 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 pub fn rubber_band(mut self, on: bool) -> ThumbnailGrid {
366 self.band = on;
367 self
368 }
369
370 pub fn id_salt(mut self, salt: impl egui::AsIdSalt) -> ThumbnailGrid {
372 self.id_salt = Some(Id::unique(salt));
373 self
374 }
375
376 pub fn max_height(mut self, height: f32) -> ThumbnailGrid {
378 self.max_height = Some(height);
379 self
380 }
381
382 pub fn reveal(mut self, cell: Option<usize>) -> ThumbnailGrid {
385 self.reveal = cell;
386 self
387 }
388
389 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 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 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 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 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#[derive(Clone, Copy, Debug)]
476struct BandDrag {
477 from: Vec2,
478 to: Vec2,
479 modifiers: Modifiers,
480}
481
482fn rubber_band(
486 ui: &mut Ui,
487 id: Id,
488 origin: egui::Pos2,
489 cells: impl Fn(Rect) -> Vec<usize>,
490) -> Option<Band> {
491 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 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 assert_eq!(at((5.0, 5.0), (15.0, 15.0)), [0, 1, 3, 4]);
575 assert!(at((10.5, 0.0), (11.5, 30.0)).is_empty());
577 assert_eq!(at((0.0, 30.0), (100.0, 100.0)), [6]);
579 assert!(at((-20.0, -20.0), (-1.0, -1.0)).is_empty());
581 }
582}