Skip to main content

egui_pop_views/library/
grid.rs

1//! A virtualised thumbnail grid, and the filmstrip (the same view in one
2//! row), over images the application lists and thumbnails it supplies.
3//!
4//! The application gives:
5//!
6//! - its images ([`LibraryItems`]): how many, each one's key, name,
7//!   marks, stack and badges. Only the cells in view are asked for, so a
8//!   hundred thousand images cost what a screenful does;
9//! - their thumbnails ([`ThumbSource`]), asynchronously: a thumbnail not
10//!   there yet is [`Thumb::Pending`] and the cell shows a placeholder
11//!   (the image's average colour when known, else a skeleton block); the
12//!   source is told which images are in view ([`ThumbSource::wanted`])
13//!   so it loads those first, and asks for a repaint when one arrives.
14//!
15//! The grid does the layout (the zoom, [`Zoom`], is a count of
16//! thumbnails per row that share the panel's width, so it survives a
17//! resize, or with [`ThumbGrid::resize`] a size that keeps on a resize
18//! and gains columns: Ctrl and the wheel, or + and -), the keyboard (arrows, Page Up and Page Down, Home
19//! and End, Space, Ctrl+A, Enter), the selection (a click, Shift for a
20//! range, Ctrl to toggle, a rubber band dragged across the cells), the
21//! culling keys ([`CullKeymap`]: ratings, flags, labels, auto-advance),
22//! the overlays (rating, labels, flag, a stack's count and chevron,
23//! badges) and the stacks (collapsed to their top image, or expanded).
24//! Every change runs a step (see [`plugin`](super::plugin)); the marks
25//! are the application's, which applies the output's signals.
26//!
27//! A grid and a filmstrip drawn over the same [`LibraryState`] share its
28//! selection and its stacks.
29//!
30//! ```
31//! use egui_pop_views::library::grid::{LibraryItems, LibraryState, Thumb, ThumbGrid, ThumbSource};
32//! use egui_pop_views::library::marks::Marks;
33//!
34//! struct Shoot(Vec<(u64, String, u8)>);
35//!
36//! impl LibraryItems<u64> for Shoot {
37//!     fn len(&self) -> usize { self.0.len() }
38//!     fn key(&self, i: usize) -> u64 { self.0[i].0 }
39//!     fn label(&self, i: usize) -> String { self.0[i].1.clone() }
40//!     fn marks(&self, i: usize) -> Marks { Marks { rating: self.0[i].2, ..Marks::default() } }
41//! }
42//!
43//! struct Thumbs;
44//!
45//! impl ThumbSource<u64> for Thumbs {
46//!     fn thumb(&self, _key: &u64, _size: u32) -> Thumb {
47//!         Thumb::Pending { average: Some(egui::Color32::from_gray(90)) }
48//!     }
49//! }
50//!
51//! fn ui(ui: &mut egui::Ui, state: &mut LibraryState<u64>, shoot: &mut Shoot) {
52//!     let out = ThumbGrid::new("grid").show(ui, state, shoot, &Thumbs);
53//!     for signal in out.signals {
54//!         if let egui_pop_views::library::Signal::Rate { keys, rating } = signal {
55//!             for p in shoot.0.iter_mut().filter(|p| keys.contains(&p.0)) {
56//!                 p.2 = rating;
57//!             }
58//!         }
59//!     }
60//! }
61//! ```
62
63use std::collections::{HashMap, HashSet};
64
65use crate::app_link::AppHandle;
66use egui::{
67    Align2, Color32, Event, EventFilter, Id, Key as EKey, Modifiers, Rect, Response, Role,
68    ScrollArea, Sense, Stroke, StrokeKind, TextStyle, TextureId, Ui, Vec2, WidgetInfo, pos2, vec2,
69};
70use egui_pop_core::icon::Icon;
71use egui_pop_core::indicator::{Anchor, Indicator};
72use egui_pop_core::kit::{self, BoxStyle, Corners, Kit, KitCx, Part, Side, State};
73use egui_pop_core::placeholder::SkeletonTokens;
74use egui_pop_core::rating::RatingStars;
75use egui_pop_core::strings::{tr, tr_with};
76use egui_pop_core::theme::Tokens;
77pub use egui_pop_core::thumbnail::GridResize;
78use egui_pop_core::ui::UiPop as _;
79use egui_pop_model::ids::StepId;
80use serde_json::{Value as Json, json};
81
82use super::marks::{ColorLabel, CullAction, CullKeymap, EmptyStars, Flag, MAX_RATING, Marks};
83use super::paint::{self, LibraryTokens};
84use super::plugin::{self as lib, Request};
85use crate::select::{self, Key, Mode, Proposal, Selection};
86use crate::strings as s;
87use crate::{nav, rows};
88
89/// The smallest thumbnail in a grid, in points: it bounds how many fit
90/// in a row ([`Zoom::most_per_row`]).
91pub const MIN_SIZE: f32 = 48.0;
92/// The zoom at first: this many thumbnails per row.
93pub const DEFAULT_PER_ROW: u32 = 5;
94/// The counts per row the zoom steps through (+, -, Ctrl and the wheel);
95/// past the last, each step out adds a quarter.
96pub const PER_ROW_STEPS: [u32; 13] = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32];
97/// One step of a [`Zoom::Points`] zoom multiplies its size by this.
98const POINTS_STEP: f32 = 1.25;
99/// How far the pointer moves before a drag draws a rubber band.
100const BAND_MIN: f32 = 4.0;
101/// Below this size a cell shows no overlays.
102pub(super) const OVERLAY_MIN: f32 = 64.0;
103
104/// A grid's zoom: how many thumbnails fill a row.
105///
106/// The cells share the panel's inner width, gaps aside, so the zoom
107/// survives a resize: a panel made wider shows the same count of larger
108/// thumbnails. `PerRow(1)` fills the panel. A panel too narrow for `n`
109/// cells of [`MIN_SIZE`] shows as many as fit, and keeps `n` for when it
110/// grows again.
111///
112/// That is the [`GridResize::PerRow`] policy, the default. A grid built
113/// with [`ThumbGrid::resize`] and [`GridResize::FixedSize`] keeps the
114/// zoom as a size ([`Zoom::Points`]) instead: a panel made wider shows
115/// more columns of thumbnails that keep their size.
116#[derive(Clone, Copy, Debug, PartialEq)]
117pub enum Zoom {
118    /// This many thumbnails per row (at least one). Under
119    /// [`GridResize::FixedSize`], the grid's next pass turns it into the
120    /// size it gives at the panel's width and signals
121    /// [`Signal::ZoomSize`].
122    PerRow(u32),
123    /// A size in points: under [`GridResize::FixedSize`], the zoom
124    /// itself. Under [`GridResize::PerRow`], as an older setting kept it:
125    /// the grid's next pass turns it into the count per row it gave at
126    /// the panel's width ([`Zoom::from_points`]) and signals
127    /// [`Signal::Zoom`], for the application to store the count instead.
128    Points(f32),
129}
130
131impl Default for Zoom {
132    fn default() -> Self {
133        Zoom::PerRow(DEFAULT_PER_ROW)
134    }
135}
136
137impl Zoom {
138    /// The count per row a size in `points` gave in a panel `width`
139    /// points wide (its inner width, the scroll bar aside) with `gap`
140    /// points between cells (the theme's `space.s`): what an application
141    /// converts a stored size in points with, once.
142    pub fn from_points(points: f32, width: f32, gap: f32) -> Zoom {
143        let points = if points.is_finite() {
144            points.max(MIN_SIZE)
145        } else {
146            MIN_SIZE
147        };
148        Zoom::PerRow(per_row_fitting(points, width, gap))
149    }
150
151    /// How many thumbnails of at least [`MIN_SIZE`] fit in a row of a
152    /// panel `width` points wide with `gap` points between cells: the
153    /// most a zoom shows there (at least one).
154    pub fn most_per_row(width: f32, gap: f32) -> u32 {
155        per_row_fitting(MIN_SIZE, width, gap)
156    }
157
158    /// The width of a cell when `per_row` share a panel `width` points
159    /// wide with `gap` points between cells and at both ends.
160    pub fn cell_width(per_row: u32, width: f32, gap: f32) -> f32 {
161        ((width - gap) / per_row.max(1) as f32 - gap).max(1.0)
162    }
163
164    /// The count per row, unless it is still a size in points.
165    pub fn per_row(self) -> Option<u32> {
166        match self {
167            Zoom::PerRow(n) => Some(n.max(1)),
168            Zoom::Points(_) => None,
169        }
170    }
171
172    /// One step closer: fewer, larger thumbnails per row (down to one).
173    #[must_use]
174    pub fn zoomed_in(self) -> Zoom {
175        match self {
176            Zoom::PerRow(n) => Zoom::PerRow(
177                PER_ROW_STEPS
178                    .iter()
179                    .rev()
180                    .copied()
181                    .find(|&s| s < n)
182                    .unwrap_or(1),
183            ),
184            Zoom::Points(p) => Zoom::Points(p * POINTS_STEP),
185        }
186    }
187
188    /// One step out: more, smaller thumbnails per row.
189    #[must_use]
190    pub fn zoomed_out(self) -> Zoom {
191        match self {
192            Zoom::PerRow(n) => Zoom::PerRow(
193                PER_ROW_STEPS
194                    .iter()
195                    .copied()
196                    .find(|&s| s > n)
197                    .unwrap_or_else(|| (n as f32 * 1.25).ceil() as u32),
198            ),
199            Zoom::Points(p) => Zoom::Points((p / POINTS_STEP).max(MIN_SIZE)),
200        }
201    }
202}
203
204/// How many cells `size` points wide fit in `width` with `gap` between
205/// them and at both ends (at least one).
206fn per_row_fitting(size: f32, width: f32, gap: f32) -> u32 {
207    let n = ((width - gap) / (size + gap)).floor();
208    if n.is_finite() && n >= 1.0 {
209        n as u32
210    } else {
211        1
212    }
213}
214
215/// A thumbnail, as the source has it now.
216#[derive(Clone, Copy, Debug, PartialEq)]
217pub enum Thumb {
218    /// The image: a texture and its size in pixels (drawn fitted).
219    Ready { texture: TextureId, size: [u32; 2] },
220    /// On its way: the image's average colour when known (a flat
221    /// placeholder), else a skeleton block.
222    Pending { average: Option<Color32> },
223    /// It could not be made: a warning sign stands in.
224    Failed,
225}
226
227/// Where thumbnails come from; the application implements it, loading
228/// them asynchronously (a thread, its engine), caching them, and asking
229/// for a repaint when one arrives.
230pub trait ThumbSource<K> {
231    /// `key`'s thumbnail for a cell `size` pixels square. Not ready yet:
232    /// [`Thumb::Pending`], and the source starts making it.
233    fn thumb(&self, key: &K, size: u32) -> Thumb;
234
235    /// The images in view this pass (and the size wanted): what to make
236    /// first, and what may be dropped from a queue.
237    fn wanted(&self, keys: &[K], size: u32) {
238        let _ = (keys, size);
239    }
240}
241
242/// A stack an image belongs to: its top image's key, and how many
243/// images it holds. Members follow their top image in the application's
244/// order.
245#[derive(Clone, Debug, PartialEq, Eq)]
246pub struct Stack<K> {
247    pub top: K,
248    pub count: usize,
249}
250
251/// A badge's tone: egui-pop's one tone ([`egui_pop_core::kit::Tone`]).
252/// The default kit's `pill` gives `info`, `success`, `warning`,
253/// `danger` and `record`; a tone it does not give is drawn as its own
254/// (neutral) box.
255pub use egui_pop_core::kit::Tone;
256
257/// A badge in a corner of a cell: a short text (`RAW`, `HDR`, `2×`) or
258/// an icon of the icon registry (`phosphor:plugs` for "offline"). Its
259/// name is said after the cell's name and is its tooltip.
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub struct Badge {
262    /// The short text drawn without an icon.
263    pub text: String,
264    pub tone: Tone,
265    /// An icon of the icon registry, drawn instead of the text.
266    pub icon: Option<String>,
267    /// What it means, in words: its accessible name and its tooltip.
268    /// Empty: the text.
269    pub name: String,
270}
271
272impl Badge {
273    /// A short text, said as it reads.
274    pub fn new(text: impl Into<String>) -> Badge {
275        Badge {
276            text: text.into(),
277            tone: Tone::Neutral,
278            icon: None,
279            name: String::new(),
280        }
281    }
282
283    /// An icon (`phosphor:plugs`) named `name` ("offline").
284    pub fn icon(icon: impl Into<String>, name: impl Into<String>) -> Badge {
285        Badge {
286            text: String::new(),
287            tone: Tone::Neutral,
288            icon: Some(icon.into()),
289            name: name.into(),
290        }
291    }
292
293    #[must_use]
294    pub fn tone(mut self, tone: Tone) -> Badge {
295        self.tone = tone;
296        self
297    }
298
299    /// What it means in words, when its text says too little ("R+J"
300    /// named "RAW+JPG").
301    #[must_use]
302    pub fn named(mut self, name: impl Into<String>) -> Badge {
303        self.name = name.into();
304        self
305    }
306
307    /// What a screen reader says of it: its name, else its text.
308    pub fn said(&self) -> &str {
309        if self.name.is_empty() {
310            &self.text
311        } else {
312            &self.name
313        }
314    }
315}
316
317/// A cell's accessible name: the image's name, then what its badges
318/// mean, each once, as the file browser says its entries' marks
319/// (`IMG_0001.CR3 · offline · 3 versions`).
320fn cell_label(name: &str, badges: &[Badge]) -> String {
321    let mut label = name.to_owned();
322    let mut said: Vec<&str> = Vec::new();
323    for b in badges {
324        let s = b.said();
325        if s.is_empty() || said.contains(&s) {
326            continue;
327        }
328        said.push(s);
329        label.push_str(" · ");
330        label.push_str(s);
331    }
332    label
333}
334
335/// The images a library shows; the application owns them.
336pub trait LibraryItems<K: Key> {
337    fn len(&self) -> usize;
338
339    fn is_empty(&self) -> bool {
340        self.len() == 0
341    }
342
343    /// Image `index`'s key (the selection is kept by key).
344    fn key(&self, index: usize) -> K;
345
346    /// Its name: the cell's accessible name and caption.
347    fn label(&self, index: usize) -> String;
348
349    /// Its rating, labels and flag.
350    fn marks(&self, index: usize) -> Marks {
351        let _ = index;
352        Marks::default()
353    }
354
355    /// The stack it belongs to.
356    fn stack(&self, index: usize) -> Option<Stack<K>> {
357        let _ = index;
358        None
359    }
360
361    /// Its badges.
362    fn badges(&self, index: usize) -> Vec<Badge> {
363        let _ = index;
364        Vec::new()
365    }
366
367    /// Changes whenever stacks change without the count changing: the
368    /// view then works out again which images it shows.
369    fn revision(&self) -> u64 {
370        0
371    }
372}
373
374/// Which images a view shows, stacks collapsed: positions to indices.
375#[derive(Debug, Default)]
376struct Order {
377    /// What it was made from: the count, the revision, the stacks'.
378    made: Option<(usize, u64, u64)>,
379    /// `None`: every image, in order.
380    map: Option<Vec<usize>>,
381    len: usize,
382}
383
384/// One view's scrolling and gestures.
385#[derive(Clone, Debug, Default)]
386struct ViewMem {
387    offset: f32,
388    extent: f32,
389    reveal: Option<usize>,
390    cols: usize,
391    /// How many cells of [`MIN_SIZE`] fit in a row, as of the last pass.
392    fit: usize,
393    /// The panel's inner width and the gap between cells, as of the last
394    /// pass.
395    width: f32,
396    gap: f32,
397    /// Ctrl and the wheel, or a pinch, gathered (the log of the zoom
398    /// factor) until it makes a step.
399    pinch: f32,
400    /// A rubber band: where it started and where it is, in content
401    /// coordinates, and the modifiers it started with.
402    band: Option<(Vec2, Vec2, Modifiers)>,
403    /// How many images a drag out of the view carries, while it lasts.
404    carry: Option<usize>,
405    /// Where a press that may become a drag out landed, in content
406    /// coordinates, until the pointer has moved past the drag threshold
407    /// (a drag out) or is let go (a click).
408    armed: Option<Vec2>,
409}
410
411/// A library's state between passes: the selection, the stacks
412/// expanded, the grid's zoom, each view's scrolling.
413#[derive(Debug)]
414pub struct LibraryState<K: Key> {
415    id: String,
416    selection: Selection<K>,
417    expanded: HashSet<K>,
418    expanded_gen: u64,
419    zoom: Zoom,
420    size: f32,
421    order: Order,
422    views: HashMap<String, ViewMem>,
423    len: Option<usize>,
424    published: bool,
425}
426
427impl<K: Key> LibraryState<K> {
428    /// A library named `id` in steps, signals and commands.
429    pub fn new(id: impl Into<String>) -> Self {
430        Self {
431            id: id.into(),
432            selection: Selection::default(),
433            expanded: HashSet::new(),
434            expanded_gen: 0,
435            zoom: Zoom::default(),
436            size: 0.0,
437            order: Order::default(),
438            views: HashMap::new(),
439            len: None,
440            published: false,
441        }
442    }
443
444    pub fn id(&self) -> &str {
445        &self.id
446    }
447
448    pub fn selection(&self) -> &Selection<K> {
449        &self.selection
450    }
451
452    /// Sets the selection without running a step.
453    pub fn set_selection(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
454        self.selection.set(keys, cursor);
455        self.published = false;
456    }
457
458    /// The grid's zoom: how many thumbnails per row, or their size under
459    /// [`GridResize::FixedSize`].
460    pub fn zoom(&self) -> Zoom {
461        self.zoom
462    }
463
464    /// Sets the grid's zoom (at least one per row) without a signal. A
465    /// [`Zoom::Points`] is turned into a count at the grid's next pass.
466    pub fn set_zoom(&mut self, zoom: Zoom) {
467        self.zoom = match zoom {
468            Zoom::PerRow(n) => Zoom::PerRow(n.max(1)),
469            Zoom::Points(p) if p.is_finite() => Zoom::Points(p.max(MIN_SIZE)),
470            Zoom::Points(_) => Zoom::default(),
471        };
472    }
473
474    /// The grid's thumbnails' size in points, as of its last pass (0
475    /// before it): what the zoom gave at the panel's width.
476    pub fn size(&self) -> f32 {
477        self.size
478    }
479
480    pub fn is_expanded(&self, top: &K) -> bool {
481        self.expanded.contains(top)
482    }
483
484    /// Expands or collapses a stack (by its top image) without running
485    /// a step.
486    pub fn set_expanded(&mut self, top: K, expanded: bool) {
487        let changed = if expanded {
488            self.expanded.insert(top)
489        } else {
490            self.expanded.remove(&top)
491        };
492        if changed {
493            self.expanded_gen += 1;
494        }
495    }
496
497    /// How many cells the views show (stacks collapsed), as of the last
498    /// pass.
499    pub fn shown(&self) -> usize {
500        self.order.len
501    }
502
503    /// Brings the cursor into view in every view at the next pass.
504    pub fn reveal_cursor(&mut self) {
505        for v in self.views.values_mut() {
506            v.reveal = Some(usize::MAX);
507        }
508    }
509
510    fn refresh(&mut self, items: &dyn LibraryItems<K>) {
511        let made = (items.len(), items.revision(), self.expanded_gen);
512        if self.order.made == Some(made) {
513            return;
514        }
515        self.order.made = Some(made);
516        let n = items.len();
517        let mut map = Vec::new();
518        let mut stacked = false;
519        for i in 0..n {
520            match items.stack(i) {
521                None => map.push(i),
522                Some(st) => {
523                    stacked = true;
524                    if self.expanded.contains(&st.top) || items.key(i) == st.top {
525                        map.push(i);
526                    }
527                }
528            }
529        }
530        self.order.len = if stacked { map.len() } else { n };
531        self.order.map = stacked.then_some(map);
532    }
533
534    fn index(&self, position: usize) -> usize {
535        self.order.map.as_ref().map_or(position, |m| m[position])
536    }
537}
538
539/// What happened in a library view this pass.
540#[derive(Clone, Debug, PartialEq)]
541pub enum Signal<K> {
542    Select {
543        keys: Vec<K>,
544        cursor: Option<K>,
545    },
546    /// The user rated these images; the application rates them.
547    Rate {
548        keys: Vec<K>,
549        rating: u8,
550    },
551    /// A colour label put on (`on`) or taken off.
552    Label {
553        keys: Vec<K>,
554        label: ColorLabel,
555        on: bool,
556    },
557    Flag {
558        keys: Vec<K>,
559        flag: Flag,
560    },
561    Tag {
562        keys: Vec<K>,
563        add: Vec<String>,
564        remove: Vec<String>,
565    },
566    /// A stack expanded or collapsed.
567    Stack {
568        top: K,
569        expanded: bool,
570    },
571    /// An image opened (Enter, a double click).
572    Activate {
573        key: K,
574    },
575    /// A drag started on a cell of a view built with
576    /// [`ThumbGrid::drag_out`], once the pointer has moved past the drag
577    /// threshold (a click is not a drag): these images go, the selection when the
578    /// cell is in it, else that cell's image alone (the selection is
579    /// left as it is). The application sets its drag payload.
580    DragOut {
581        keys: Vec<K>,
582    },
583    /// The grid's zoom changed: this many thumbnails per row, for the
584    /// application to keep (a stored size in points converted included).
585    Zoom {
586        per_row: u32,
587    },
588    /// The zoom of a grid keeping the size on a resize
589    /// ([`GridResize::FixedSize`]) changed: thumbnails this many points
590    /// wide, for the application to keep (a stored count converted
591    /// included).
592    ZoomSize {
593        points: f32,
594    },
595    /// A step was vetoed.
596    Vetoed {
597        step: StepId,
598        reason: String,
599    },
600}
601
602/// What [`ThumbGrid::show`] returns.
603#[derive(Debug)]
604pub struct LibraryOutput<K> {
605    /// The view as one focusable widget.
606    pub response: Response,
607    pub signals: Vec<Signal<K>>,
608    /// How many cells were built this pass (those in view, pending cells
609    /// of [`ThumbGrid::expected_len`] included).
610    pub built: usize,
611    /// How many cells a row holds.
612    pub columns: usize,
613}
614
615#[derive(Clone, Copy, Debug, PartialEq, Eq)]
616enum Axis {
617    Grid,
618    Strip,
619}
620
621/// What the view does after drawing, in order.
622#[derive(Debug)]
623enum Op<K> {
624    Select(Proposal<K>),
625    /// Moves to the next image if the previous mark was not refused.
626    Advance(usize),
627    Run(StepId, Json),
628    /// A request that could not be read.
629    Fail(StepId, String),
630    Activate(K),
631    /// A drag out of the view started with these images.
632    DragOut(Vec<K>),
633    /// A zoom step: closer (`true`, fewer per row) or out.
634    Zoom(bool),
635}
636
637/// The thumbnail grid, or the filmstrip ([`ThumbGrid::filmstrip`]).
638#[derive(Debug)]
639pub struct ThumbGrid<'a> {
640    view: String,
641    axis: Axis,
642    label: Option<String>,
643    mode: Mode,
644    app: Option<&'a AppHandle>,
645    height: Option<f32>,
646    keymap: CullKeymap,
647    captions: bool,
648    overlays: bool,
649    empty_stars: EmptyStars,
650    drag_out: bool,
651    resize: GridResize,
652    expected: usize,
653}
654
655impl<'a> ThumbGrid<'a> {
656    /// A grid named `view` (a library may have several views).
657    pub fn new(view: impl Into<String>) -> Self {
658        Self {
659            view: view.into(),
660            axis: Axis::Grid,
661            label: None,
662            mode: Mode::Multiple,
663            app: None,
664            height: None,
665            keymap: CullKeymap::lightroom(),
666            captions: true,
667            overlays: true,
668            empty_stars: EmptyStars::OnHover,
669            drag_out: false,
670            resize: GridResize::PerRow,
671            expected: 0,
672        }
673    }
674
675    /// A filmstrip: one row, scrolled sideways; its cells fit its height.
676    pub fn filmstrip(view: impl Into<String>) -> Self {
677        Self {
678            axis: Axis::Strip,
679            captions: false,
680            ..Self::new(view)
681        }
682    }
683
684    /// Its accessible name.
685    pub fn label(mut self, label: impl Into<String>) -> Self {
686        self.label = Some(label.into());
687        self
688    }
689
690    /// How many images may be selected (several by default).
691    pub fn mode(mut self, mode: Mode) -> Self {
692        self.mode = mode;
693        self
694    }
695
696    /// Runs its moments as steps of this application, and registers the
697    /// library for commands.
698    #[cfg(feature = "api")]
699    pub fn app(mut self, app: &'a AppHandle) -> Self {
700        self.app = Some(app);
701        self
702    }
703
704    /// Its height (default: what is available for a grid, 120 points
705    /// for a filmstrip).
706    pub fn height(mut self, height: f32) -> Self {
707        self.height = Some(height);
708        self
709    }
710
711    /// The culling keys ([`CullKeymap::lightroom`] by default).
712    pub fn keymap(mut self, keymap: CullKeymap) -> Self {
713        self.keymap = keymap;
714        self
715    }
716
717    /// Each image's name under its thumbnail (on in a grid).
718    pub fn captions(mut self, on: bool) -> Self {
719        self.captions = on;
720        self
721    }
722
723    /// Ratings, labels, flags, stacks and badges over the thumbnails.
724    pub fn overlays(mut self, on: bool) -> Self {
725        self.overlays = on;
726        self
727    }
728
729    /// When an unrated cell's empty stars show: under the pointer
730    /// ([`EmptyStars::OnHover`], the default, as Lightroom's compact
731    /// cells), or on every cell ([`EmptyStars::Always`]: large cells, a
732    /// culling pass where every image gets a rating).
733    pub fn empty_stars(mut self, empty: EmptyStars) -> Self {
734        self.empty_stars = empty;
735        self
736    }
737
738    /// A drag that starts on a cell carries images out instead of
739    /// drawing a rubber band, which then starts from the space between
740    /// cells (off by default): the view signals [`Signal::DragOut`] once
741    /// the pointer has moved past egui's drag threshold (a press or a
742    /// click alone signals nothing), for the application to set its payload
743    /// (`egui::DragAndDrop::set_payload`) and its drop targets to take
744    /// it; while it lasts the cursor shows a carry and the pointer how
745    /// many images go.
746    pub fn drag_out(mut self, on: bool) -> Self {
747        self.drag_out = on;
748        self
749    }
750
751    /// What the zoom means when the panel is resized
752    /// ([`GridResize::PerRow`] by default): a count per row, so a wider
753    /// panel shows larger thumbnails; or a size
754    /// ([`GridResize::FixedSize`]), so a wider panel shows more columns,
755    /// the cells sharing what is left of a row. The zoom is the
756    /// [`LibraryState`]'s, kept in the policy's form; the application
757    /// keeps what [`Signal::Zoom`] or [`Signal::ZoomSize`] says.
758    pub fn resize(mut self, resize: GridResize) -> Self {
759        self.resize = resize;
760        self
761    }
762
763    /// How many images the application expects its items to hold once
764    /// they have all arrived (0 by default: no expectation). While
765    /// [`LibraryItems::len`] is below it, the view lays out the missing
766    /// cells as pending cells after the real ones, so its scrolling and
767    /// layout are final at once and nothing moves as rows arrive: each
768    /// real image takes the next pending cell's place.
769    ///
770    /// A pending cell is drawn as a skeleton (the kit's `skeleton`) and
771    /// said as "Loading image N of M"; it is not an item: it cannot be
772    /// selected, focused, opened or dragged, Ctrl+A and the rubber band
773    /// leave it out, the keyboard stops at the last real image, and it
774    /// emits no signal. Items as many as expected, or more, leave no
775    /// pending cell. Stacks collapsed, the real cells are those shown,
776    /// and the pending ones what the items still lack.
777    pub fn expected_len(mut self, total: usize) -> Self {
778        self.expected = total;
779        self
780    }
781
782    pub fn show<K: Key>(
783        self,
784        ui: &mut Ui,
785        state: &mut LibraryState<K>,
786        items: &dyn LibraryItems<K>,
787        source: &dyn ThumbSource<K>,
788    ) -> LibraryOutput<K> {
789        let id = Id::unique(("egui_pop_views::library", &state.id, &self.view));
790        let grid = self.axis == Axis::Grid;
791        let len = items.len();
792        let before = state.selection.len();
793        crate::list::retain(&mut state.selection, &mut state.len, len, &|i| items.key(i));
794        if state.selection.len() != before {
795            state.published = false;
796        }
797        state.refresh(items);
798        let n = state.order.len;
799        // The cells still to come: laid out and drawn, never items.
800        let pending = self.expected.saturating_sub(len);
801        let total = n + pending;
802        let t = Tokens::of(ui.ctx());
803        let lt = LibraryTokens::of(ui.ctx());
804        let kit = Kit::of(ui.ctx());
805        let gap = t.space.s;
806        let small = TextStyle::Small.resolve(ui.style());
807        let caption_h = if self.captions {
808            ui.text_style_height(&TextStyle::Small) + t.space.xs
809        } else {
810            0.0
811        };
812        let strip_h = self.height.unwrap_or(120.0);
813        let mut mem = state.views.remove(&self.view).unwrap_or_default();
814        // A zoom not in the policy's form becomes, at this width, the
815        // count a size gave (per row) or the size a count gives (fixed).
816        let mut converted = None;
817        let size = if grid {
818            let width = ui.available_width() - ui.spacing().scroll.allocated_width();
819            let fit = Zoom::most_per_row(width, gap);
820            let room = width >= MIN_SIZE + 2.0 * gap;
821            match (self.resize, state.zoom) {
822                (GridResize::PerRow, Zoom::Points(p)) if room => {
823                    state.zoom = Zoom::from_points(p, width, gap);
824                    converted = state.zoom.per_row().map(|per_row| Signal::Zoom { per_row });
825                }
826                (GridResize::FixedSize, Zoom::PerRow(n)) if room => {
827                    let points = Zoom::cell_width(n.min(fit), width, gap)
828                        .floor()
829                        .max(MIN_SIZE);
830                    state.zoom = Zoom::Points(points);
831                    converted = Some(Signal::ZoomSize { points });
832                }
833                _ => {}
834            }
835            mem.width = width;
836            mem.gap = gap;
837            let per_row = match state.zoom {
838                Zoom::PerRow(n) => n.max(1),
839                Zoom::Points(p) => per_row_fitting(p, width, gap),
840            }
841            .min(fit);
842            mem.cols = per_row as usize;
843            mem.fit = fit as usize;
844            let size = Zoom::cell_width(per_row, width, gap);
845            state.size = size;
846            size
847        } else {
848            mem.cols = 1;
849            (strip_h - caption_h - 2.0 * gap - ui.spacing().scroll.allocated_width())
850                .max(MIN_SIZE / 2.0)
851        };
852        let cell = vec2(size, size + caption_h);
853        let line = if grid { cell.y + gap } else { cell.x + gap };
854        let cols = mem.cols;
855        let lines = if grid { total.div_ceil(cols) } else { total };
856        let line_of = |p: usize| if grid { p / cols } else { p };
857        let key_at = |p: usize| items.key(state.index(p));
858        // Its arrows (Up and Down in a grid), pages, ends, Space and Enter
859        // reach it before a global binding of theirs.
860        let reads: &[EKey] = if grid {
861            &[
862                EKey::ArrowUp,
863                EKey::ArrowDown,
864                EKey::ArrowLeft,
865                EKey::ArrowRight,
866                EKey::PageUp,
867                EKey::PageDown,
868                EKey::Home,
869                EKey::End,
870                EKey::Space,
871                EKey::Enter,
872            ]
873        } else {
874            &[
875                EKey::ArrowLeft,
876                EKey::ArrowRight,
877                EKey::PageUp,
878                EKey::PageDown,
879                EKey::Home,
880                EKey::End,
881                EKey::Space,
882                EKey::Enter,
883            ]
884        };
885        egui_pop_core::focus::reads_keys(ui.ctx(), id, reads);
886        let focused = ui.memory(|m| m.has_focus(id));
887        let mut ops: Vec<Op<K>> = Vec::new();
888
889        // Requests from commands, before the user's keys.
890        let registry = lib::registry(self.app);
891        if let Some(reg) = &registry {
892            reg.touch(&state.id);
893            for r in reg.take(&state.id) {
894                ops.push(request(r));
895            }
896        }
897
898        // The cursor's position, when there is one in view.
899        let cursor = state
900            .selection
901            .cursor()
902            .and_then(|c| (0..n).find(|&p| key_at(p) == *c));
903        if focused && n > 0 {
904            let page_lines = ((mem.extent / line).floor() as usize)
905                .saturating_sub(1)
906                .max(1);
907            let page = if grid { page_lines * cols } else { page_lines };
908            let last = n - 1;
909            let events = ui.input(|i| i.events.clone());
910            for e in events {
911                let Event::Key {
912                    key,
913                    pressed: true,
914                    modifiers,
915                    ..
916                } = e
917                else {
918                    continue;
919                };
920                let c = cursor;
921                let to = match key {
922                    EKey::ArrowLeft => Some(c.map_or(0, |c| c.saturating_sub(1))),
923                    EKey::ArrowRight => Some(c.map_or(0, |c| (c + 1).min(last))),
924                    EKey::ArrowUp if grid => {
925                        Some(c.map_or(last, |c| if c >= cols { c - cols } else { c }))
926                    }
927                    EKey::ArrowDown if grid => {
928                        Some(c.map_or(0, |c| if c + cols <= last { c + cols } else { c }))
929                    }
930                    EKey::PageUp => Some(c.map_or(0, |c| c.saturating_sub(page))),
931                    EKey::PageDown => Some(c.map_or(0, |c| (c + page).min(last))),
932                    EKey::Home => Some(0),
933                    EKey::End => Some(last),
934                    _ => None,
935                };
936                if let Some(j) = to {
937                    ops.push(Op::Select(
938                        state.selection.move_to(self.mode, n, &key_at, j, modifiers),
939                    ));
940                    mem.reveal = Some(j);
941                    continue;
942                }
943                match key {
944                    EKey::Space if modifiers.command => {
945                        ops.extend(state.selection.toggle_cursor(self.mode).map(Op::Select));
946                    }
947                    EKey::Space => {
948                        if let Some(c) = c {
949                            ops.push(Op::Select(state.selection.move_to(
950                                self.mode,
951                                n,
952                                &key_at,
953                                c,
954                                Modifiers::NONE,
955                            )));
956                        }
957                    }
958                    EKey::A if modifiers.command && self.mode == Mode::Multiple => {
959                        ops.push(Op::Select(state.selection.all(n, &key_at)));
960                    }
961                    EKey::Enter => {
962                        if let Some(c) = c {
963                            ops.push(Op::Activate(key_at(c)));
964                        }
965                    }
966                    _ if !modifiers.command && !modifiers.alt => {
967                        if let Some(action) = self.keymap.action(key) {
968                            ops.extend(cull(action, &self.keymap, state, items, c, grid));
969                        }
970                    }
971                    _ => {}
972                }
973            }
974        }
975        if mem.reveal == Some(usize::MAX) {
976            mem.reveal = cursor;
977        }
978
979        // The views: rows of cells, or one row; only those in view built.
980        let label = self
981            .label
982            .clone()
983            .unwrap_or_else(|| tr(ui.ctx(), if grid { &s::LIBRARY } else { &s::FILMSTRIP }));
984        let mut area = if grid {
985            ScrollArea::vertical()
986        } else {
987            ScrollArea::horizontal()
988        }
989        .id_salt(id.with("scroll"))
990        .auto_shrink([false, !grid]);
991        if grid && let Some(h) = self.height {
992            area = area.max_height(h).min_scrolled_height(h);
993        }
994        if let Some(p) = mem.reveal.take() {
995            let o = nav::reveal(line_of(p), line, mem.offset, mem.extent);
996            if o != mem.offset {
997                area = if grid {
998                    area.vertical_scroll_offset(o.max(0.0))
999                } else {
1000                    area.horizontal_scroll_offset(o.max(0.0))
1001                };
1002            }
1003        }
1004        let px = (size * ui.ctx().pixels_per_point()).round().max(1.0) as u32;
1005        let mode = self.mode;
1006        let overlays = self.overlays && size >= OVERLAY_MIN;
1007        let captions = self.captions;
1008        let selection = &state.selection;
1009        let expanded = &state.expanded;
1010        let order = &state.order;
1011        let index = |p: usize| order.map.as_ref().map_or(p, |m| m[p]);
1012        let mut band = mem.band.take();
1013        let mut carry = mem.carry.take();
1014        let mut armed = mem.armed.take();
1015        let drag_out = self.drag_out;
1016        let expected = self.expected;
1017        let mut take_focus = false;
1018        let mut built = 0;
1019        let mut wanted: Vec<K> = Vec::new();
1020        let mut cell_ops: Vec<Op<K>> = Vec::new();
1021        let out = ui.scroll_area_viewport(area, |ui, viewport| {
1022            // The grid is the stop, around the area.
1023            egui_pop_core::focus::takes_keys(ui.ctx(), id);
1024            let origin = ui.max_rect().min;
1025            if grid {
1026                ui.set_min_size(vec2(ui.available_width(), lines as f32 * line));
1027            } else {
1028                ui.set_min_size(vec2(lines as f32 * line, cell.y + 2.0 * gap));
1029            }
1030            let (lo, hi) = if grid {
1031                (viewport.min.y, viewport.max.y)
1032            } else {
1033                (viewport.min.x, viewport.max.x)
1034            };
1035            let first = ((lo / line).floor().max(0.0) as usize).min(lines);
1036            let last = ((hi / line).ceil().max(0.0) as usize).min(lines);
1037            let rect_of = |p: usize| -> Rect {
1038                let min = if grid {
1039                    let (row, col) = (p / cols, p % cols);
1040                    origin
1041                        + vec2(
1042                            gap + col as f32 * (cell.x + gap),
1043                            gap / 2.0 + row as f32 * line,
1044                        )
1045                } else {
1046                    origin + vec2(gap / 2.0 + p as f32 * line, gap)
1047                };
1048                Rect::from_min_size(min, cell)
1049            };
1050            // The rubber band, under the cells: a drag from anywhere.
1051            let visible = Rect::from_min_size(origin + viewport.min.to_vec2(), viewport.size());
1052            let bg = ui.interact(visible, id.with("band"), Sense::DRAG);
1053            // A drag out starts on a cell: the selection when the cell is
1054            // in it, else the cell's image alone. A drag-only area starts
1055            // dragging on the press, so the press on a cell arms it and
1056            // the drag out starts once the pointer has moved past the drag
1057            // threshold: a click carries nothing.
1058            let on_cell = |at: Vec2| {
1059                let at = at.to_pos2();
1060                cells_in(Rect::from_min_max(at, at), grid, cols, n, cell, gap, line)
1061                    .first()
1062                    .copied()
1063            };
1064            if drag_out
1065                && bg.drag_started()
1066                && let Some(p) = bg.interact_pointer_pos()
1067                && on_cell(p - origin).is_some()
1068            {
1069                armed = Some(p - origin);
1070            }
1071            if !bg.dragged() {
1072                armed = None;
1073            }
1074            let decided = ui.input(|i| i.pointer.is_decidedly_dragging());
1075            let carried = armed
1076                .filter(|_| decided)
1077                .and_then(|at| {
1078                    armed = None;
1079                    on_cell(at).map(|q| items.key(index(q)))
1080                })
1081                .map(|key| {
1082                    if selection.contains(&key) {
1083                        selection.keys().to_vec()
1084                    } else {
1085                        vec![key]
1086                    }
1087                });
1088            if let Some(keys) = carried {
1089                carry = Some(keys.len());
1090                cell_ops.push(Op::DragOut(keys));
1091            }
1092            if carry.is_some() {
1093                if bg.dragged() {
1094                    egui_pop_core::pointer::hold_drag_cursor(
1095                        ui.ctx(),
1096                        egui_pop_core::pointer::DragKind::Carry,
1097                    );
1098                } else {
1099                    carry = None;
1100                }
1101            }
1102            if mode == Mode::Multiple && carry.is_none() && armed.is_none() {
1103                if bg.drag_started()
1104                    && let Some(p) = bg.interact_pointer_pos()
1105                {
1106                    let at = p - origin;
1107                    band = Some((at, at, click_modifiers(ui)));
1108                    take_focus = true;
1109                }
1110                if let (Some(b), Some(p)) = (band.as_mut(), bg.interact_pointer_pos())
1111                    && bg.dragged()
1112                {
1113                    b.1 = p - origin;
1114                }
1115            }
1116            if bg.dragged()
1117                && band
1118                    .as_ref()
1119                    .is_some_and(|(a, b, _)| (*b - *a).length() >= BAND_MIN)
1120            {
1121                egui_pop_core::pointer::hold_drag_cursor(
1122                    ui.ctx(),
1123                    egui_pop_core::pointer::DragKind::Select,
1124                );
1125            }
1126            // A drag-only area starts dragging on the press: a band is one
1127            // once the pointer has moved (a click is not a band).
1128            let band_cells: Vec<usize> = band
1129                .filter(|(a, b, _)| (*b - *a).length() >= BAND_MIN)
1130                .map(|(a, b, _)| {
1131                    cells_in(
1132                        Rect::from_two_pos(a.to_pos2(), b.to_pos2()),
1133                        grid,
1134                        cols,
1135                        n,
1136                        cell,
1137                        gap,
1138                        line,
1139                    )
1140                })
1141                .unwrap_or_default();
1142            let painter = ui.painter().clone();
1143            let cx = KitCx {
1144                painter: &painter,
1145                ppp: ui.ctx().pixels_per_point(),
1146            };
1147            for l in first..last {
1148                for col in 0..cols {
1149                    let p = if grid { l * cols + col } else { l };
1150                    if p >= total {
1151                        break;
1152                    }
1153                    built += 1;
1154                    if p >= n {
1155                        let rect = rect_of(p);
1156                        let number = len + (p - n) + 1;
1157                        pending_cell(ui, &cx, &kit, id, rect, size, number, expected);
1158                        continue;
1159                    }
1160                    let i = index(p);
1161                    let key = items.key(i);
1162                    let rect = rect_of(p);
1163                    let r = ui.interact(rect, id.with(("cell", &key)), Sense::CLICK);
1164                    let in_band = band_cells.binary_search(&p).is_ok();
1165                    let selected = selection.contains(&key) || in_band;
1166                    let is_cursor = focused && selection.cursor() == Some(&key);
1167                    let marks = items.marks(i);
1168                    let stack = items.stack(i);
1169                    let name = items.label(i);
1170                    let badges = items.badges(i);
1171                    // The cell's box (its outline and the cursor's ring
1172                    // too: nothing of the content overlaps them), then
1173                    // its image. A selected cell is not hovered.
1174                    let cell_state = State::REST
1175                        .with(State::SELECTED, selected)
1176                        .with(State::HOVER, r.hovered() && !selected)
1177                        .with(State::FOCUS, is_cursor);
1178                    let cell_part = Part {
1179                        rect,
1180                        room: rect,
1181                        state: cell_state,
1182                        label: None,
1183                    };
1184                    kit.thumb_cell.paint(&cx, &cell_part);
1185                    let cell_box = *kit.thumb_cell.style(cell_state);
1186                    let image = Rect::from_min_size(rect.min, vec2(size, size)).shrink(t.space.xs);
1187                    match source.thumb(&key, px) {
1188                        Thumb::Ready { texture, size } => {
1189                            painter.image(
1190                                texture,
1191                                crate::library::fitted(image, size),
1192                                Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
1193                                Color32::WHITE,
1194                            );
1195                        }
1196                        Thumb::Pending { average: Some(c) } => {
1197                            painter.rect_filled(image.shrink(size * 0.08), 0.0, c);
1198                        }
1199                        Thumb::Pending { average: None } => {
1200                            painter.rect_filled(
1201                                image.shrink(size * 0.08),
1202                                t.radius.widget,
1203                                SkeletonTokens::of(ui.ctx()).fill,
1204                            );
1205                        }
1206                        Thumb::Failed => {
1207                            let side = (size * 0.25).min(t.size.icon_panel);
1208                            Icon::Warning.paint(
1209                                &painter,
1210                                Rect::from_center_size(image.center(), vec2(side, side)),
1211                                kit.thumb_layer.style(State::REST).text,
1212                            );
1213                        }
1214                    }
1215                    wanted.push(key.clone());
1216                    let layer = |rect: Rect, tone: kit::Tone| {
1217                        kit.thumb_layer.paint(
1218                            &cx,
1219                            &Part {
1220                                rect,
1221                                room: rect,
1222                                state: State::REST.toned(tone),
1223                                label: None,
1224                            },
1225                        );
1226                    };
1227                    if marks.flag == Flag::Reject {
1228                        layer(image, kit::Tone::Muted);
1229                    }
1230                    // A member of an expanded stack: a bar on its left
1231                    // (the layer's indicator), under the cell's outline.
1232                    let member = stack.as_ref().is_some_and(|st| st.top != key);
1233                    if member {
1234                        layer(
1235                            Rect::from_min_size(rect.min, vec2(size, size)),
1236                            kit::Tone::Accent,
1237                        );
1238                        if cell_box.border_width > 0.0 {
1239                            let outline = BoxStyle {
1240                                fill: Color32::TRANSPARENT,
1241                                indicator_size: 0.0,
1242                                ..cell_box
1243                            };
1244                            kit::paint_box(&cx, rect, &outline, Corners::All, Side::Bottom);
1245                        }
1246                    }
1247                    if captions {
1248                        painter.with_clip_rect(rect.intersect(ui.clip_rect())).text(
1249                            pos2(rect.center().x, rect.bottom() - caption_h / 2.0),
1250                            Align2::CENTER_CENTER,
1251                            &name,
1252                            small.clone(),
1253                            cell_box.text,
1254                        );
1255                    }
1256                    if overlays {
1257                        let star = (size / 10.0).clamp(10.0, 16.0);
1258                        let stars_rect = Rect::from_min_size(
1259                            pos2(image.left() + star * 0.25, image.bottom() - star * 1.25),
1260                            RatingStars::size_for(star),
1261                        );
1262                        // The cell or its stars under the pointer: the
1263                        // stars' own hit areas take the cell's hover.
1264                        let hot = r.hovered() || ui.rect_contains_pointer(stars_rect);
1265                        overlay(
1266                            &cx,
1267                            &kit,
1268                            &lt,
1269                            &t,
1270                            image,
1271                            &marks,
1272                            hot || self.empty_stars == EmptyStars::Always,
1273                            star,
1274                        );
1275                        paint_badges(ui, &name, image.shrink(t.space.xs), &badges);
1276                        let stars = RatingStars::new(marks.rating)
1277                            .id(id.with(("stars", &key)))
1278                            .focusable(false)
1279                            .empty(self.empty_stars)
1280                            .item_hovered(hot)
1281                            .show_at(ui, stars_rect);
1282                        if let Some(rating) = stars.changed {
1283                            let keys = targets_of(selection, &key);
1284                            cell_ops.push(Op::Run(
1285                                lib::LIBRARY_RATE,
1286                                json!({ "keys": keys, "rating": rating }),
1287                            ));
1288                        }
1289                        if let Some(st) = stack.as_ref().filter(|st| st.top == key && st.count > 1)
1290                        {
1291                            let open = expanded.contains(&st.top);
1292                            let (chip, chip_text) = paint::pill(
1293                                &painter,
1294                                &kit.pill,
1295                                kit::Tone::Neutral,
1296                                image.left_top() + vec2(t.space.xs, t.space.xs + 18.0),
1297                                Align2::LEFT_TOP,
1298                                &format!("{}  ", st.count),
1299                                small.clone(),
1300                            );
1301                            let chevron = Rect::from_min_size(
1302                                pos2(chip.right() - chip.height(), chip.top()),
1303                                vec2(chip.height(), chip.height()),
1304                            );
1305                            let icon = if open {
1306                                Icon::ChevronDown
1307                            } else {
1308                                Icon::ChevronRight
1309                            };
1310                            icon.paint(&painter, chevron, chip_text);
1311                            let cr = ui.interact(chip, id.with(("stack", &key)), Sense::CLICK);
1312                            let cname = tr_with(
1313                                ui.ctx(),
1314                                if open {
1315                                    &s::COLLAPSE_STACK
1316                                } else {
1317                                    &s::EXPAND_STACK
1318                                },
1319                                &[("count", st.count.into())],
1320                            );
1321                            cr.widget_info(move || WidgetInfo::labeled(Role::Button, true, &cname));
1322                            if cr.clicked() {
1323                                cell_ops.push(Op::Run(
1324                                    lib::LIBRARY_STACK,
1325                                    json!({ "stack": st.top, "expanded": !open }),
1326                                ));
1327                            }
1328                        }
1329                    }
1330                    let a11y_name = cell_label(&name, &badges);
1331                    r.widget_info(move || {
1332                        WidgetInfo::selected(Role::Button, true, selected, &a11y_name)
1333                    });
1334                    if r.double_clicked() {
1335                        cell_ops.push(Op::Activate(key.clone()));
1336                    } else if r.clicked() {
1337                        take_focus = true;
1338                        let mods = click_modifiers(ui);
1339                        cell_ops.push(Op::Select(selection.click(
1340                            mode,
1341                            n,
1342                            &|q| items.key(index(q)),
1343                            p,
1344                            mods,
1345                        )));
1346                    }
1347                }
1348            }
1349            if let Some((a, b, _)) = band
1350                && (b - a).length() >= BAND_MIN
1351            {
1352                let r = Rect::from_two_pos(origin + a, origin + b);
1353                painter.rect_filled(r, 0.0, lt.band);
1354                painter.rect_stroke(
1355                    r,
1356                    0.0,
1357                    Stroke::new(1.0, lt.band_outline),
1358                    StrokeKind::Inside,
1359                );
1360            }
1361            if bg.drag_stopped()
1362                && let Some((_, _, mods)) = band.take()
1363                && !band_cells.is_empty()
1364            {
1365                let mut keys: Vec<K> = if mods.command || mods.shift {
1366                    selection.keys().to_vec()
1367                } else {
1368                    Vec::new()
1369                };
1370                for &p in &band_cells {
1371                    let k = items.key(index(p));
1372                    if !keys.contains(&k) {
1373                        keys.push(k);
1374                    }
1375                }
1376                let cursor = band_cells.last().map(|&p| items.key(index(p)));
1377                cell_ops.push(Op::Select(Proposal {
1378                    keys,
1379                    cursor: cursor.clone(),
1380                    anchor: cursor,
1381                }));
1382            }
1383        });
1384        ops.extend(cell_ops);
1385        mem.band = band;
1386        mem.carry = carry;
1387        mem.armed = armed;
1388        if let Some(count) = carry {
1389            rows::carry_count(ui, count);
1390        }
1391        egui_pop_core::ui::contain_wheel(ui, &out);
1392        if grid {
1393            mem.offset = out.state.clamped_offset().y;
1394            mem.extent = out.inner_rect.height();
1395        } else {
1396            mem.offset = out.state.clamped_offset().x;
1397            mem.extent = out.inner_rect.width();
1398        }
1399        let response = ui.interact(out.inner_rect, id, Sense::focusable_noninteractive());
1400        // Handed the keyboard, a panel gives it to the grid, not its filters.
1401        egui_pop_core::focus::prefer(ui.ctx(), id);
1402        egui_pop_core::a11y::name(&response, Role::Unknown, &label);
1403        if take_focus {
1404            response.request_focus();
1405        }
1406        if response.has_focus() {
1407            ui.memory_mut(|m| {
1408                m.set_focus_lock_filter(
1409                    id,
1410                    EventFilter {
1411                        horizontal_arrows: true,
1412                        vertical_arrows: true,
1413                        ..Default::default()
1414                    },
1415                )
1416            });
1417        }
1418        if response.has_focus() {
1419            egui_pop_core::focus::own_ring(ui.ctx(), id);
1420        }
1421        rows::paint_view(
1422            ui,
1423            &egui_pop_core::kit::Kit::of(ui.ctx()),
1424            out.inner_rect,
1425            egui_pop_core::focus::shows_ring(&response),
1426        );
1427        // Zoom: Ctrl and the wheel over a grid.
1428        if grid && ui.rect_contains_pointer(out.inner_rect) {
1429            let z = ui.input(|i| i.zoom_delta());
1430            if (z - 1.0).abs() > f32::EPSILON && z > 0.0 {
1431                // A wheel notch makes a step; a pinch steps as it grows.
1432                mem.pinch += z.ln();
1433                let step = POINTS_STEP.ln() * 0.5;
1434                if mem.pinch.abs() >= step {
1435                    ops.push(Op::Zoom(mem.pinch > 0.0));
1436                    mem.pinch = 0.0;
1437                }
1438            }
1439        }
1440        if !wanted.is_empty() {
1441            source.wanted(&wanted, px);
1442        }
1443
1444        let mut signals = self.run_ops(ops, state, items, &mut mem);
1445        if let Some(signal) = converted
1446            && !signals
1447                .iter()
1448                .any(|s| matches!(s, Signal::Zoom { .. } | Signal::ZoomSize { .. }))
1449        {
1450            signals.insert(0, signal);
1451        }
1452        if focused && let Some(reg) = &registry {
1453            reg.set_focused(&state.id);
1454        }
1455        if !state.published
1456            && let Some(reg) = &registry
1457        {
1458            let keys = state
1459                .selection
1460                .keys()
1461                .iter()
1462                .map(|k| serde_json::to_value(k).unwrap_or(Json::Null))
1463                .collect();
1464            let cursor = serde_json::to_value(state.selection.cursor()).unwrap_or(Json::Null);
1465            reg.publish(&state.id, n, keys, cursor);
1466            state.published = true;
1467        }
1468        state.views.insert(self.view.clone(), mem);
1469        if !signals.is_empty() {
1470            ui.ctx().request_repaint();
1471        }
1472        LibraryOutput {
1473            response,
1474            signals,
1475            built,
1476            columns: cols,
1477        }
1478    }
1479
1480    fn run_ops<K: Key>(
1481        &self,
1482        ops: Vec<Op<K>>,
1483        state: &mut LibraryState<K>,
1484        items: &dyn LibraryItems<K>,
1485        mem: &mut ViewMem,
1486    ) -> Vec<Signal<K>> {
1487        let app = self.app;
1488        let n = state.order.len;
1489        let mut out = Vec::new();
1490        let mut last_ok = true;
1491        for op in ops {
1492            let p = match op {
1493                Op::Select(p) => p,
1494                Op::Advance(from) => {
1495                    if !last_ok || from + 1 >= n {
1496                        continue;
1497                    }
1498                    mem.reveal = Some(from + 1);
1499                    let key_at = |q: usize| items.key(state.index(q));
1500                    state
1501                        .selection
1502                        .move_to(self.mode, n, &key_at, from + 1, Modifiers::NONE)
1503                }
1504                Op::Run(step, mut args) => {
1505                    complete(&step, &mut args, state, items);
1506                    args["library"] = json!(state.id);
1507                    match lib::report(app, &step, args)
1508                        .and_then(|a| signal_of(&step, &a, Some(&mut *state)))
1509                    {
1510                        Ok(signal) => {
1511                            last_ok = true;
1512                            out.push(signal);
1513                        }
1514                        Err(reason) => {
1515                            last_ok = false;
1516                            out.push(Signal::Vetoed { step, reason });
1517                        }
1518                    }
1519                    continue;
1520                }
1521                Op::Fail(step, reason) => {
1522                    out.push(Signal::Vetoed { step, reason });
1523                    continue;
1524                }
1525                Op::Activate(key) => {
1526                    out.push(Signal::Activate { key });
1527                    continue;
1528                }
1529                Op::DragOut(keys) => {
1530                    out.push(Signal::DragOut { keys });
1531                    continue;
1532                }
1533                Op::Zoom(closer) => {
1534                    // From what the view shows: a count wider than the
1535                    // panel fits steps from what fits.
1536                    let shown = Zoom::PerRow(mem.cols.max(1) as u32);
1537                    let to = if closer {
1538                        shown.zoomed_in()
1539                    } else {
1540                        shown.zoomed_out()
1541                    };
1542                    let to = to.per_row().unwrap_or(1).min(mem.fit.max(1) as u32);
1543                    if Some(to) != shown.per_row() {
1544                        match self.resize {
1545                            GridResize::PerRow => {
1546                                state.zoom = Zoom::PerRow(to);
1547                                out.push(Signal::Zoom { per_row: to });
1548                            }
1549                            // The size that shows `to` per row here.
1550                            GridResize::FixedSize => {
1551                                let points = Zoom::cell_width(to, mem.width, mem.gap)
1552                                    .floor()
1553                                    .max(MIN_SIZE);
1554                                state.zoom = Zoom::Points(points);
1555                                out.push(Signal::ZoomSize { points });
1556                            }
1557                        }
1558                    }
1559                    continue;
1560                }
1561            };
1562            if p.keys == state.selection.keys() && p.cursor.as_ref() == state.selection.cursor() {
1563                continue;
1564            }
1565            let id = state.id.clone();
1566            match select::run(
1567                app,
1568                &lib::LIBRARY_SELECT,
1569                "library",
1570                &id,
1571                &mut state.selection,
1572                p,
1573            ) {
1574                Ok(done) => {
1575                    state.published = false;
1576                    last_ok = true;
1577                    out.push(Signal::Select {
1578                        keys: done.keys,
1579                        cursor: done.cursor,
1580                    });
1581                }
1582                Err(reason) => {
1583                    last_ok = false;
1584                    out.push(Signal::Vetoed {
1585                        step: lib::LIBRARY_SELECT,
1586                        reason,
1587                    });
1588                }
1589            }
1590        }
1591        out
1592    }
1593}
1594
1595/// A change of marks or tags made outside a grid (a panel's stars, a
1596/// tag input), for [`change`].
1597#[derive(Clone, Debug, PartialEq)]
1598pub enum Change<K> {
1599    Rate {
1600        keys: Vec<K>,
1601        rating: u8,
1602    },
1603    Label {
1604        keys: Vec<K>,
1605        label: ColorLabel,
1606        on: bool,
1607    },
1608    Flag {
1609        keys: Vec<K>,
1610        flag: Flag,
1611    },
1612    Tag {
1613        keys: Vec<K>,
1614        add: Vec<String>,
1615        remove: Vec<String>,
1616    },
1617}
1618
1619/// Runs a change's step (`library.rate`, `library.label`,
1620/// `library.flag`, `library.tag`) for library `library`, as the grid
1621/// does: the signal to apply (with what a before-hook redirected it
1622/// to), or [`Signal::Vetoed`].
1623#[cfg(feature = "api")]
1624pub fn change<K: Key>(app: Option<&AppHandle>, library: &str, change: Change<K>) -> Signal<K> {
1625    let (step, mut args) = match change {
1626        Change::Rate { keys, rating } => (
1627            lib::LIBRARY_RATE,
1628            json!({ "keys": keys, "rating": rating.min(MAX_RATING) }),
1629        ),
1630        Change::Label { keys, label, on } => (
1631            lib::LIBRARY_LABEL,
1632            json!({ "keys": keys, "label": label.name(), "on": on }),
1633        ),
1634        Change::Flag { keys, flag } => (
1635            lib::LIBRARY_FLAG,
1636            json!({ "keys": keys, "flag": flag.name() }),
1637        ),
1638        Change::Tag { keys, add, remove } => (
1639            lib::LIBRARY_TAG,
1640            json!({ "keys": keys, "add": add, "remove": remove }),
1641        ),
1642    };
1643    args["library"] = json!(library);
1644    match lib::report(app, &step, args).and_then(|a| signal_of(&step, &a, None)) {
1645        Ok(signal) => signal,
1646        Err(reason) => Signal::Vetoed { step, reason },
1647    }
1648}
1649
1650/// What the marks act on: the selection, else the cursor.
1651fn targets<K: Key>(selection: &Selection<K>) -> Vec<K> {
1652    if selection.is_empty() {
1653        selection.cursor().cloned().into_iter().collect()
1654    } else {
1655        selection.keys().to_vec()
1656    }
1657}
1658
1659/// What a click on a cell's overlay acts on: the selection when the
1660/// cell is in it, else the cell alone.
1661fn targets_of<K: Key>(selection: &Selection<K>, key: &K) -> Vec<K> {
1662    if selection.contains(key) {
1663        selection.keys().to_vec()
1664    } else {
1665        vec![key.clone()]
1666    }
1667}
1668
1669/// The operations a culling key asks for.
1670#[allow(
1671    clippy::too_many_arguments,
1672    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1673)]
1674fn cull<K: Key>(
1675    action: CullAction,
1676    keymap: &CullKeymap,
1677    state: &LibraryState<K>,
1678    items: &dyn LibraryItems<K>,
1679    cursor: Option<usize>,
1680    grid: bool,
1681) -> Vec<Op<K>> {
1682    let keys = targets(&state.selection);
1683    let mut ops = Vec::new();
1684    let mark = match action {
1685        CullAction::Rate(r) => Some((
1686            lib::LIBRARY_RATE,
1687            json!({ "keys": keys, "rating": r.min(MAX_RATING) }),
1688        )),
1689        CullAction::Flag(f) => Some((lib::LIBRARY_FLAG, json!({ "keys": keys, "flag": f.name() }))),
1690        CullAction::Label(l) => {
1691            let on = cursor.is_none_or(|c| !items.marks(state.index(c)).labels.has(l));
1692            Some((
1693                lib::LIBRARY_LABEL,
1694                json!({ "keys": keys, "label": l.name(), "on": on }),
1695            ))
1696        }
1697        CullAction::ToggleStack => {
1698            if let Some(st) = cursor
1699                .and_then(|c| items.stack(state.index(c)))
1700                .filter(|st| st.count > 1)
1701            {
1702                let open = state.is_expanded(&st.top);
1703                ops.push(Op::Run(
1704                    lib::LIBRARY_STACK,
1705                    json!({ "stack": st.top, "expanded": !open }),
1706                ));
1707            }
1708            None
1709        }
1710        CullAction::ZoomIn if grid => {
1711            ops.push(Op::Zoom(true));
1712            None
1713        }
1714        CullAction::ZoomOut if grid => {
1715            ops.push(Op::Zoom(false));
1716            None
1717        }
1718        CullAction::ZoomIn | CullAction::ZoomOut => None,
1719    };
1720    if let Some((step, args)) = mark
1721        && !keys.is_empty()
1722    {
1723        ops.push(Op::Run(step, args));
1724        if keymap.auto_advance
1725            && let Some(c) = cursor
1726        {
1727            ops.push(Op::Advance(c));
1728        }
1729    }
1730    ops
1731}
1732
1733/// The operation a command's request asks for: its keys filled in
1734/// (else the selection), a label's `on` (else toggled from the
1735/// cursor's image).
1736fn request<K: Key>(r: Request) -> Op<K> {
1737    let Request { step, args } = r;
1738    if step != lib::LIBRARY_SELECT {
1739        return Op::Run(step, args);
1740    }
1741    let parsed = lib::parse::<Vec<K>>(&args["keys"], "keys").and_then(|keys| {
1742        let cursor: Option<K> = lib::parse(&args["cursor"], "cursor")?;
1743        Ok(Proposal {
1744            keys,
1745            cursor: cursor.clone(),
1746            anchor: cursor,
1747        })
1748    });
1749    match parsed {
1750        Ok(p) => Op::Select(p),
1751        Err(e) => Op::Fail(step, e),
1752    }
1753}
1754
1755/// Completes a mark's arguments when it runs: its keys (else the
1756/// selection), a label's `on` (else toggled from the cursor's image).
1757fn complete<K: Key>(
1758    step: &StepId,
1759    args: &mut Json,
1760    state: &LibraryState<K>,
1761    items: &dyn LibraryItems<K>,
1762) {
1763    if args.get("keys").is_none() {
1764        args["keys"] = json!(targets(&state.selection));
1765    }
1766    if *step == lib::LIBRARY_LABEL && args.get("on").is_none() {
1767        let label = args["label"].as_str().and_then(ColorLabel::parse);
1768        let cursor = state
1769            .selection
1770            .cursor()
1771            .and_then(|c| (0..state.order.len).find(|&p| items.key(state.index(p)) == *c));
1772        let on = match (label, cursor) {
1773            (Some(l), Some(c)) => !items.marks(state.index(c)).labels.has(l),
1774            _ => true,
1775        };
1776        args["on"] = json!(on);
1777    }
1778}
1779
1780/// The signal a mark's step gives, from the arguments it ran with; a
1781/// stack's step expands or collapses it.
1782fn signal_of<K: Key>(
1783    step: &StepId,
1784    a: &Json,
1785    state: Option<&mut LibraryState<K>>,
1786) -> Result<Signal<K>, String> {
1787    let keys = || lib::parse::<Vec<K>>(&a["keys"], "keys");
1788    if *step == lib::LIBRARY_RATE {
1789        let rating = a["rating"]
1790            .as_u64()
1791            .filter(|r| *r <= u64::from(MAX_RATING))
1792            .ok_or("`rating` is 0 to 5")? as u8;
1793        Ok(Signal::Rate {
1794            keys: keys()?,
1795            rating,
1796        })
1797    } else if *step == lib::LIBRARY_LABEL {
1798        let label = a["label"]
1799            .as_str()
1800            .and_then(ColorLabel::parse)
1801            .ok_or("`label` is red, yellow, green, blue or purple")?;
1802        let on = a["on"].as_bool().unwrap_or(true);
1803        Ok(Signal::Label {
1804            keys: keys()?,
1805            label,
1806            on,
1807        })
1808    } else if *step == lib::LIBRARY_FLAG {
1809        let flag = a["flag"]
1810            .as_str()
1811            .and_then(Flag::parse)
1812            .ok_or("`flag` is pick, reject or none")?;
1813        Ok(Signal::Flag {
1814            keys: keys()?,
1815            flag,
1816        })
1817    } else if *step == lib::LIBRARY_TAG {
1818        let list = |k: &str| -> Result<Vec<String>, String> {
1819            if a[k].is_null() {
1820                Ok(Vec::new())
1821            } else {
1822                lib::parse(&a[k], k)
1823            }
1824        };
1825        Ok(Signal::Tag {
1826            keys: keys()?,
1827            add: list("add")?,
1828            remove: list("remove")?,
1829        })
1830    } else if *step == lib::LIBRARY_STACK {
1831        let top: K = lib::parse(&a["stack"], "stack")?;
1832        let expanded = a["expanded"]
1833            .as_bool()
1834            .ok_or("`expanded` is true or false")?;
1835        if let Some(state) = state {
1836            state.set_expanded(top.clone(), expanded);
1837        }
1838        Ok(Signal::Stack { top, expanded })
1839    } else {
1840        Err(format!("`{step}` is not a library mark"))
1841    }
1842}
1843
1844/// A pending cell ([`ThumbGrid::expected_len`]): the cell's box at rest
1845/// and a skeleton where the image goes, said as "Loading image `number`
1846/// of `total`". It senses the pointer only to be in the accessibility
1847/// tree: no click, no focus, no drag.
1848#[allow(
1849    clippy::too_many_arguments,
1850    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1851)]
1852fn pending_cell(
1853    ui: &Ui,
1854    cx: &KitCx<'_>,
1855    kit: &Kit,
1856    id: Id,
1857    rect: Rect,
1858    size: f32,
1859    number: usize,
1860    total: usize,
1861) {
1862    let part = |rect: Rect| Part {
1863        rect,
1864        room: rect,
1865        state: State::REST,
1866        label: None,
1867    };
1868    kit.thumb_cell.paint(cx, &part(rect));
1869    let image = Rect::from_min_size(rect.min, vec2(size, size)).shrink(size * 0.08);
1870    kit.skeleton.paint(cx, &part(image));
1871    let r = ui.interact(rect, id.with(("pending", number)), Sense::hover());
1872    let name = tr_with(
1873        ui.ctx(),
1874        &s::LOADING_IMAGE,
1875        &[("number", number.into()), ("total", total.into())],
1876    );
1877    r.widget_info(move || WidgetInfo::labeled(Role::Image, true, &name));
1878    ui.ctx()
1879        .accesskit_node_builder(r.id, |node| node.set_busy());
1880}
1881
1882/// The positions of the cells a rectangle (in content coordinates)
1883/// touches, in order.
1884fn cells_in(
1885    rect: Rect,
1886    grid: bool,
1887    cols: usize,
1888    n: usize,
1889    cell: Vec2,
1890    gap: f32,
1891    line: f32,
1892) -> Vec<usize> {
1893    let range =
1894        |lo: f32, hi: f32, start: f32, extent: f32, step: f32, max: usize| -> (usize, usize) {
1895            let first = ((lo - start - extent) / step).ceil().max(0.0) as usize;
1896            let last = ((hi - start) / step).floor();
1897            if last < 0.0 {
1898                return (1, 0);
1899            }
1900            (first, (last as usize).min(max))
1901        };
1902    let mut out = Vec::new();
1903    if n == 0 {
1904        return out;
1905    }
1906    if grid {
1907        let (c0, c1) = range(rect.min.x, rect.max.x, gap, cell.x, cell.x + gap, cols - 1);
1908        let (r0, r1) = range(
1909            rect.min.y,
1910            rect.max.y,
1911            gap / 2.0,
1912            cell.y,
1913            line,
1914            (n - 1) / cols,
1915        );
1916        for r in r0..=r1 {
1917            for c in c0..=c1 {
1918                let p = r * cols + c;
1919                if p < n {
1920                    out.push(p);
1921                }
1922            }
1923        }
1924    } else {
1925        if rect.max.y < gap || rect.min.y > gap + cell.y {
1926            return out;
1927        }
1928        let (p0, p1) = range(rect.min.x, rect.max.x, gap / 2.0, cell.x, line, n - 1);
1929        out.extend(p0..=p1);
1930    }
1931    out
1932}
1933
1934/// A cell's overlays: its flag, labels, rating and badges.
1935#[allow(
1936    clippy::too_many_arguments,
1937    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1938)]
1939pub(super) fn overlay(
1940    cx: &KitCx<'_>,
1941    kit: &Kit,
1942    lt: &LibraryTokens,
1943    t: &Tokens,
1944    image: Rect,
1945    marks: &Marks,
1946    stars_shown: bool,
1947    star: f32,
1948) {
1949    let painter = cx.painter;
1950    let badge = |rect: Rect| {
1951        kit.thumb_overlay_badge.paint(
1952            cx,
1953            &Part {
1954                rect,
1955                room: rect,
1956                state: State::REST,
1957                label: None,
1958            },
1959        );
1960    };
1961    let pad = t.space.xs;
1962    let icon = 16.0;
1963    if marks.flag != Flag::None {
1964        let r = Rect::from_min_size(image.left_top() + vec2(pad, pad), vec2(icon, icon));
1965        badge(r);
1966        match marks.flag {
1967            Flag::Pick => paint::flag(painter, r.shrink(2.0), lt.pick),
1968            _ => paint::cross(painter, r.shrink(2.0), lt.reject),
1969        }
1970    }
1971    let labels: Vec<ColorLabel> = marks.labels.iter().collect();
1972    if !labels.is_empty() {
1973        let w = labels.len() as f32 * 13.0 + 3.0;
1974        let back = Rect::from_min_size(
1975            pos2(image.right() - pad - w, image.top() + pad),
1976            vec2(w, icon),
1977        );
1978        badge(back);
1979        for (k, l) in labels.iter().enumerate() {
1980            let c = pos2(back.left() + 8.0 + k as f32 * 13.0, back.center().y);
1981            paint::label(painter, *l, c, 5.0, lt.label(*l));
1982        }
1983    }
1984    // The box behind the stars; the stars are `RatingStars`, drawn over
1985    // it by the cell.
1986    if marks.rating > 0 || stars_shown {
1987        let back = Rect::from_min_size(
1988            pos2(image.left() + star * 0.25, image.bottom() - star * 1.25),
1989            vec2(star * f32::from(MAX_RATING) + star * 0.5, star),
1990        );
1991        badge(back);
1992    }
1993}
1994
1995/// A badge as an indicator: its icon or its text, of its tone, under an
1996/// id agents read (`library.badge:<image>:<text>`, the name for an
1997/// icon), as the file browser draws its marks.
1998fn badge_indicator(image: &str, badge: &Badge) -> Indicator {
1999    let (base, said) = match &badge.icon {
2000        Some(icon) => (Indicator::icon(icon.as_str()), badge.said()),
2001        None => (Indicator::text(badge.text.as_str()), badge.text.as_str()),
2002    };
2003    let base = base
2004        .tone(badge.tone)
2005        .overhang(false)
2006        .id(format!("library.badge:{image}:{said}"));
2007    if badge.name.is_empty() {
2008        base
2009    } else {
2010        base.tooltip(badge.name.clone())
2011    }
2012}
2013
2014/// A cell's badges from the bottom end of `host`, the last at the end,
2015/// as many as fit. They take no click: the cell under them does.
2016fn paint_badges(ui: &mut Ui, image: &str, host: Rect, badges: &[Badge]) {
2017    let gap = Tokens::of(ui.ctx()).space.xs;
2018    let mut host = host;
2019    for b in badges.iter().rev() {
2020        let mark = badge_indicator(image, b);
2021        let width = mark.measure(ui).x;
2022        if width > host.width() {
2023            break;
2024        }
2025        mark.paint_at(ui, host, Anchor::BottomEnd);
2026        host.set_right(host.right() - width - gap);
2027    }
2028}
2029
2030/// The modifiers of this pass's last pointer button event (a click's
2031/// own, even when the keys were let go in the same pass), else those
2032/// held now.
2033fn click_modifiers(ui: &Ui) -> Modifiers {
2034    ui.input(|i| {
2035        i.events
2036            .iter()
2037            .rev()
2038            .find_map(|e| match e {
2039                Event::PointerButton { modifiers, .. } => Some(*modifiers),
2040                _ => None,
2041            })
2042            .unwrap_or(i.modifiers)
2043    })
2044}
2045
2046#[cfg(test)]
2047mod tests {
2048    use super::*;
2049
2050    #[test]
2051    fn a_band_touches_the_cells_it_crosses() {
2052        let cell = vec2(100.0, 100.0);
2053        // Cells at x 10..110, 120..220, 230..330; rows 5..105, 115..215.
2054        let r = Rect::from_min_max(pos2(105.0, 50.0), pos2(125.0, 120.0));
2055        assert_eq!(cells_in(r, true, 3, 9, cell, 10.0, 110.0), [0, 1, 3, 4]);
2056        // In a gap: nothing.
2057        let r = Rect::from_min_max(pos2(111.0, 10.0), pos2(119.0, 20.0));
2058        assert!(cells_in(r, true, 3, 9, cell, 10.0, 110.0).is_empty());
2059        // Past the last image.
2060        let r = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 400.0));
2061        assert_eq!(cells_in(r, true, 3, 5, cell, 10.0, 110.0), [0, 1, 2, 3, 4]);
2062    }
2063}