Skip to main content

egui_pop_views/library/
mode.rs

1//! The library grid as a file browser's view mode: a folder shown the
2//! way the Library shows photos.
3//!
4//! [`LibraryGridMode`] lays the browser's entries out as its thumbnails
5//! mode does (the zoom as a count per row, the rubber band, the arrows,
6//! Page Up and Page Down, Home and End), and draws over each cell the
7//! library's marks: the flag top left, the colour labels top right, the
8//! rating's stars bottom left, a rejected image dimmed. The marks are the
9//! application's ([`LibraryGridMode::new`]); a screen reader hears them as
10//! the cell's description.
11//!
12//! The culling keys ([`CullKeymap`], Lightroom's by default) rate, flag
13//! and label the selection, else the focused entry. They do not change
14//! the marks: they give [`Signal`]s (`Rate`, `Flag`, `Label`, keyed by
15//! path) into a [`LibrarySignals`] handle the application drains and
16//! applies. With auto-advance, the focus then moves to the next entry.
17//!
18//! A browser's grouping ([`FileBrowser::with_grouping`]) stands for the
19//! library's stacks: a group is one entry, its members said by its chip.
20//!
21//! ```
22//! use egui_pop_api::files::browser::ViewModes;
23//! use egui_pop_views::library::marks::Marks;
24//! use egui_pop_views::library::mode::{LibraryGridMode, LibrarySignals};
25//!
26//! let signals = LibrarySignals::default();
27//! let modes = ViewModes::default();
28//! LibraryGridMode::new(|_entry| Marks::default())
29//!     .signals(signals.clone())
30//!     .register(&modes)
31//!     .unwrap();
32//! assert!(modes.ids().contains(&"library".to_string()));
33//! // Each frame, after the browser is drawn:
34//! for _signal in signals.drain() { /* apply it to the files' marks */ }
35//! ```
36//!
37//! [`FileBrowser::with_grouping`]: egui_pop_api::files::browser::FileBrowser::with_grouping
38
39use std::fmt;
40use std::path::PathBuf;
41use std::sync::{Arc, Mutex};
42
43use egui::{Modifiers, Rect, Ui, vec2};
44use egui_pop_api::files::browser::{
45    EntryDrawer, ModeContext, ModeInfo, ModeKey, ModeNeeds, ModeOutput, ModeSettings, PlainDrawer,
46    SourceEntry, ThumbState, ThumbnailsMode, ViewMode, ViewModes,
47};
48use egui_pop_core::kit::{self, Kit, KitCx, Part, State};
49use egui_pop_core::rating::RatingStars;
50use egui_pop_core::strings::tr_with;
51use egui_pop_core::theme::Tokens;
52
53use super::grid::{OVERLAY_MIN, Signal, overlay};
54use super::marks::{CullAction, CullKeymap, EmptyStars, Flag, Marks};
55use super::paint::LibraryTokens;
56use crate::strings as s;
57
58/// The library grid's id among a browser's modes.
59pub const MODE_LIBRARY: &str = "library";
60
61/// What gives an entry's library marks.
62pub type EntryLibraryMarks = dyn Fn(&SourceEntry) -> Marks + Send + Sync;
63
64/// Where a library grid's culling keys say what the person asked for:
65/// a shared queue the application drains, each frame, after drawing the
66/// browser. Clones share the queue.
67#[derive(Clone, Default)]
68pub struct LibrarySignals(Arc<Mutex<Vec<Signal<PathBuf>>>>);
69
70impl fmt::Debug for LibrarySignals {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.debug_tuple("LibrarySignals").field(&self.len()).finish()
73    }
74}
75
76impl LibrarySignals {
77    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Signal<PathBuf>>> {
78        self.0.lock().unwrap_or_else(|e| e.into_inner())
79    }
80
81    /// The signals given since the last drain, oldest first.
82    pub fn drain(&self) -> Vec<Signal<PathBuf>> {
83        std::mem::take(&mut *self.lock())
84    }
85
86    /// How many wait.
87    pub fn len(&self) -> usize {
88        self.lock().len()
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.len() == 0
93    }
94
95    fn push(&self, signal: Signal<PathBuf>) {
96        self.lock().push(signal);
97    }
98}
99
100/// The library grid, a file browser's view mode
101/// ([module docs](self)). Register it on a browser's [`ViewModes`] with
102/// [`LibraryGridMode::register`].
103#[derive(Clone)]
104pub struct LibraryGridMode {
105    marks: Arc<EntryLibraryMarks>,
106    keymap: CullKeymap,
107    signals: LibrarySignals,
108    grid: ThumbnailsMode,
109    /// A culling key taken, with the focus it was pressed on: turned into
110    /// a signal when the entries are next at hand (the draw that follows,
111    /// in the same frame).
112    pending: Vec<(Option<usize>, CullAction)>,
113}
114
115impl fmt::Debug for LibraryGridMode {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.debug_struct("LibraryGridMode")
118            .field("keymap", &self.keymap)
119            .field("signals", &self.signals)
120            .finish_non_exhaustive()
121    }
122}
123
124impl LibraryGridMode {
125    /// A library grid whose entries' marks `marks` gives, with
126    /// Lightroom's culling keys.
127    pub fn new(marks: impl Fn(&SourceEntry) -> Marks + Send + Sync + 'static) -> Self {
128        LibraryGridMode {
129            marks: Arc::new(marks),
130            keymap: CullKeymap::lightroom(),
131            signals: LibrarySignals::default(),
132            grid: ThumbnailsMode::default(),
133            pending: Vec::new(),
134        }
135    }
136
137    /// The culling keys ([`CullKeymap::none`] for none). The stack key
138    /// and the zoom keys are left to the browser.
139    #[must_use]
140    pub fn keymap(mut self, keymap: CullKeymap) -> Self {
141        self.keymap = keymap;
142        self
143    }
144
145    /// Where the culling keys' signals go (a fresh queue by default).
146    #[must_use]
147    pub fn signals(mut self, signals: LibrarySignals) -> Self {
148        self.signals = signals;
149        self
150    }
151
152    /// Adds the mode to `modes` under [`MODE_LIBRARY`]; each browser
153    /// made with them gets its own copy, all sharing the marks and the
154    /// signals' queue.
155    pub fn register(self, modes: &ViewModes) -> Result<(), String> {
156        modes.register(
157            MODE_LIBRARY,
158            Arc::new(move || Box::new(self.clone()) as Box<dyn ViewMode>),
159        )
160    }
161
162    /// The culling key's action, if `key` is one this mode takes.
163    fn takes(&self, key: egui::Key, modifiers: Modifiers) -> Option<CullAction> {
164        if !(modifiers.is_none() || modifiers == Modifiers::SHIFT) {
165            return None;
166        }
167        self.keymap.action(key).filter(|a| {
168            matches!(
169                a,
170                CullAction::Rate(_) | CullAction::Flag(_) | CullAction::Label(_)
171            )
172        })
173    }
174
175    /// Turns the culling keys taken into signals; the entry auto-advance
176    /// moves to, if any.
177    fn cull(&mut self, cx: &ModeContext<'_>) -> Option<usize> {
178        let mut advance = None;
179        for (focus, action) in std::mem::take(&mut self.pending) {
180            let focus = focus.filter(|&f| f < cx.entries.len());
181            // The selection, else the focused entry.
182            let keys: Vec<PathBuf> = if cx.selection.is_empty() {
183                focus
184                    .map(|f| cx.entries[f].path.clone())
185                    .into_iter()
186                    .collect()
187            } else {
188                cx.entries
189                    .iter()
190                    .filter(|e| cx.selection.contains(&e.path))
191                    .map(|e| e.path.clone())
192                    .collect()
193            };
194            if keys.is_empty() {
195                continue;
196            }
197            let signal = match action {
198                CullAction::Rate(r) => Signal::Rate {
199                    keys,
200                    rating: r.min(super::marks::MAX_RATING),
201                },
202                CullAction::Flag(flag) => Signal::Flag { keys, flag },
203                CullAction::Label(label) => {
204                    // Toggled from the focused entry's labels.
205                    let on = focus.is_none_or(|f| !(self.marks)(&cx.entries[f]).labels.has(label));
206                    Signal::Label { keys, label, on }
207                }
208                _ => continue,
209            };
210            self.signals.push(signal);
211            if self.keymap.auto_advance
212                && let Some(f) = focus
213                && f + 1 < cx.entries.len()
214            {
215                advance = Some(f + 1);
216            }
217        }
218        advance
219    }
220}
221
222impl ViewMode for LibraryGridMode {
223    fn describe(&self) -> ModeInfo {
224        let mut info = self.grid.describe();
225        info.id = MODE_LIBRARY.into();
226        info.label = "Library grid".into();
227        info.icon = "phosphor:images".into();
228        info.persist = MODE_LIBRARY.into();
229        info.keys.extend([
230            ("0 to 5".into(), "Rate".into()),
231            ("P, X, U".into(), "Pick, reject, unflag".into()),
232            ("6 to 9".into(), "Toggle a colour label".into()),
233        ]);
234        info.gestures.push("Drag: select with a band".into());
235        info.needs = ModeNeeds {
236            thumbnails: true,
237            ..ModeNeeds::default()
238        };
239        info
240    }
241
242    fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
243        let advance = self.cull(&cx);
244        if advance.is_some() {
245            ui.ctx().request_repaint();
246        }
247        let ModeContext {
248            entries,
249            selection,
250            focus,
251            thumbnails,
252            settings,
253            id,
254            reveal_focus,
255            max_height,
256            drawer,
257            name,
258            many,
259            place,
260            ancestors,
261            peek,
262            loading,
263            generation,
264            marks,
265        } = cx;
266        let mut plain = PlainDrawer {
267            entries,
268            selection,
269            focus,
270            marks,
271        };
272        let inner: &mut dyn EntryDrawer = match drawer {
273            Some(d) => d,
274            None => &mut plain,
275        };
276        let mut drawer = MarksDrawer {
277            inner,
278            entries,
279            marks: &*self.marks,
280            id,
281        };
282        let mut out = self.grid.show(
283            ui,
284            ModeContext {
285                entries,
286                selection,
287                focus,
288                thumbnails,
289                settings,
290                id,
291                reveal_focus,
292                max_height,
293                drawer: Some(&mut drawer),
294                name,
295                many,
296                place,
297                ancestors,
298                peek,
299                loading,
300                generation,
301                marks,
302            },
303        );
304        // Auto-advance: as a click on the next entry, which the browser
305        // selects and focuses.
306        if let Some(next) = advance {
307            out.clicked = Some((next, Modifiers::NONE));
308        }
309        out
310    }
311
312    fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
313        self.grid.step(from, count, key)
314    }
315
316    fn own_key(
317        &mut self,
318        key: egui::Key,
319        modifiers: Modifiers,
320        focus: Option<usize>,
321        _settings: &mut ModeSettings,
322    ) -> bool {
323        match self.takes(key, modifiers) {
324            Some(action) => {
325                self.pending.push((focus, action));
326                true
327            }
328            None => false,
329        }
330    }
331}
332
333/// The cell drawer of the browser (or of its host), with the library's
334/// marks over each cell.
335struct MarksDrawer<'a> {
336    inner: &'a mut dyn EntryDrawer,
337    entries: &'a [SourceEntry],
338    marks: &'a EntryLibraryMarks,
339    id: egui::Id,
340}
341
342impl EntryDrawer for MarksDrawer<'_> {
343    fn headers(&mut self, ui: &mut Ui, width: f32) {
344        self.inner.headers(ui, width);
345    }
346
347    fn empty(&mut self, ui: &mut Ui) {
348        self.inner.empty(ui);
349    }
350
351    fn row_size(&self, ui: &Ui, width: f32) -> egui::Vec2 {
352        self.inner.row_size(ui, width)
353    }
354
355    fn row(&mut self, ui: &mut Ui, n: usize, size: egui::Vec2) -> egui::Response {
356        self.inner.row(ui, n, size)
357    }
358
359    fn cell_size(&self, ui: &Ui, side: f32) -> egui::Vec2 {
360        self.inner.cell_size(ui, side)
361    }
362
363    fn cell(
364        &mut self,
365        ui: &mut Ui,
366        n: usize,
367        size: egui::Vec2,
368        thumbnail: ThumbState,
369    ) -> egui::Response {
370        let r = self.inner.cell(ui, n, size, thumbnail);
371        let Some(e) = self.entries.get(n) else {
372            return r;
373        };
374        if e.is_dir() {
375            return r;
376        }
377        let marks = (self.marks)(e);
378        if marks == Marks::default() {
379            return r;
380        }
381        if let Some(said) = spoken(ui.ctx(), &marks) {
382            ui.ctx()
383                .accesskit_node_builder(r.id, |node| node.set_description(said));
384        }
385        let side = size.x.min(r.rect.width());
386        if side >= OVERLAY_MIN {
387            let t = Tokens::of(ui.ctx());
388            let image = Rect::from_min_size(r.rect.min, vec2(side, side)).shrink(t.space.xs);
389            paint_marks(ui, image, &marks, self.id.with(("library.stars", &e.path)));
390        }
391        r
392    }
393}
394
395/// The library's marks over a cell's `image`: the grid's own overlays
396/// (flag, labels, the stars' box), a rejected image dimmed, and the
397/// stars, read only.
398fn paint_marks(ui: &mut Ui, image: Rect, marks: &Marks, id: egui::Id) {
399    let t = Tokens::of(ui.ctx());
400    let lt = LibraryTokens::of(ui.ctx());
401    let kit = Kit::of(ui.ctx());
402    let painter = ui.painter().clone();
403    let cx = KitCx {
404        painter: &painter,
405        ppp: ui.ctx().pixels_per_point(),
406    };
407    if marks.flag == Flag::Reject {
408        kit.thumb_layer.paint(
409            &cx,
410            &Part {
411                rect: image,
412                room: image,
413                state: State::REST.toned(kit::Tone::Muted),
414                label: None,
415            },
416        );
417    }
418    let star = (image.width() / 10.0).clamp(10.0, 16.0);
419    overlay(&cx, &kit, &lt, &t, image, marks, false, star);
420    if marks.rating > 0 {
421        let stars = Rect::from_min_size(
422            egui::pos2(image.left() + star * 0.25, image.bottom() - star * 1.25),
423            RatingStars::size_for(star),
424        );
425        let _ = RatingStars::new(marks.rating)
426            .id(id)
427            .focusable(false)
428            .read_only(true)
429            .empty(EmptyStars::OnHover)
430            .item_hovered(false)
431            .show_at(ui, stars);
432    }
433}
434
435/// The marks in words, as a screen reader says them after the entry's
436/// name: "Rated 3 of 5, Pick, Red"; `None` without any.
437pub fn spoken(ctx: &egui::Context, marks: &Marks) -> Option<String> {
438    let mut parts = Vec::new();
439    if marks.rating > 0 {
440        parts.push(tr_with(
441            ctx,
442            &s::LIBRARY_RATED,
443            &[("stars", i64::from(marks.rating).into())],
444        ));
445    }
446    if marks.flag != Flag::None {
447        parts.push(marks.flag.title(ctx));
448    }
449    parts.extend(marks.labels.iter().map(|l| l.title(ctx)));
450    (!parts.is_empty()).then(|| parts.join(", "))
451}