Skip to main content

egui_pop_views/library/
marks.rs

1//! An image's marks: a rating (0 to 5 stars), colour labels and a pick
2//! or reject flag; the widgets editing them; the culling keys.
3//!
4//! The application owns the values: each widget takes the current one
5//! and says what the user asked for ([`MarkResponse::changed`]); the
6//! application applies it to its data (or not), and passes the new
7//! value at the next pass.
8//!
9//! ```
10//! use egui_pop_views::library::marks::{ColorLabels, FlagToggle, Flag, Labels, RatingStars};
11//!
12//! struct Photo { rating: u8, labels: Labels, flag: Flag }
13//!
14//! fn ui(ui: &mut egui::Ui, p: &mut Photo) {
15//!     if let Some(r) = RatingStars::new(p.rating).show(ui).changed {
16//!         p.rating = r;
17//!     }
18//!     if let Some(l) = ColorLabels::new(p.labels).show(ui).changed {
19//!         p.labels = l;
20//!     }
21//!     if let Some(f) = FlagToggle::new(p.flag).show(ui).changed {
22//!         p.flag = f;
23//!     }
24//! }
25//! ```
26
27use egui::{Key as EKey, Response, Role, Sense, Ui, WidgetInfo, vec2};
28use egui_pop_core::kit::{Kit, KitCx, Part, State};
29use egui_pop_core::rating;
30use egui_pop_core::strings::{StrKey, tr, tr_args};
31use egui_pop_core::theme::Tokens;
32use egui_pop_core::tooltip::TooltipExt as _;
33use serde::{Deserialize, Serialize};
34
35use super::paint::{self, LibraryTokens};
36use crate::strings as s;
37
38pub use egui_pop_core::rating::{EmptyStars, MAX_RATING};
39
40/// Picked, rejected, or neither.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "lowercase")]
43pub enum Flag {
44    #[default]
45    None,
46    Pick,
47    Reject,
48}
49
50impl Flag {
51    pub const ALL: [Flag; 3] = [Flag::Pick, Flag::Reject, Flag::None];
52
53    /// As in step arguments: `none`, `pick`, `reject`.
54    pub fn name(self) -> &'static str {
55        match self {
56            Flag::None => "none",
57            Flag::Pick => "pick",
58            Flag::Reject => "reject",
59        }
60    }
61
62    pub fn parse(text: &str) -> Option<Flag> {
63        Flag::ALL.into_iter().find(|f| f.name() == text)
64    }
65
66    /// Its name as shown (translated).
67    pub fn title(self, ctx: &egui::Context) -> String {
68        tr(
69            ctx,
70            match self {
71                Flag::None => &s::UNFLAGGED,
72                Flag::Pick => &s::PICK,
73                Flag::Reject => &s::REJECT,
74            },
75        )
76    }
77}
78
79/// One of the five colour labels.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
81#[serde(rename_all = "lowercase")]
82pub enum ColorLabel {
83    Red,
84    Yellow,
85    Green,
86    Blue,
87    Purple,
88}
89
90impl ColorLabel {
91    pub const ALL: [ColorLabel; 5] = [
92        ColorLabel::Red,
93        ColorLabel::Yellow,
94        ColorLabel::Green,
95        ColorLabel::Blue,
96        ColorLabel::Purple,
97    ];
98
99    /// As in step arguments: `red`, `yellow`, `green`, `blue`, `purple`.
100    pub fn name(self) -> &'static str {
101        match self {
102            ColorLabel::Red => "red",
103            ColorLabel::Yellow => "yellow",
104            ColorLabel::Green => "green",
105            ColorLabel::Blue => "blue",
106            ColorLabel::Purple => "purple",
107        }
108    }
109
110    pub fn parse(text: &str) -> Option<ColorLabel> {
111        ColorLabel::ALL.into_iter().find(|l| l.name() == text)
112    }
113
114    pub(crate) fn index(self) -> usize {
115        self as usize
116    }
117
118    fn key(self) -> &'static StrKey {
119        match self {
120            ColorLabel::Red => &s::RED,
121            ColorLabel::Yellow => &s::YELLOW,
122            ColorLabel::Green => &s::GREEN,
123            ColorLabel::Blue => &s::BLUE,
124            ColorLabel::Purple => &s::PURPLE,
125        }
126    }
127
128    /// Its name as shown (translated): "Red".
129    pub fn title(self, ctx: &egui::Context) -> String {
130        tr(ctx, self.key())
131    }
132}
133
134/// A set of colour labels.
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
136pub struct Labels(u8);
137
138impl Labels {
139    pub const NONE: Labels = Labels(0);
140
141    pub fn has(self, label: ColorLabel) -> bool {
142        self.0 & (1 << label.index()) != 0
143    }
144
145    /// With `label` on or off.
146    #[must_use]
147    pub fn with(self, label: ColorLabel, on: bool) -> Labels {
148        let bit = 1 << label.index();
149        Labels(if on { self.0 | bit } else { self.0 & !bit })
150    }
151
152    #[must_use]
153    pub fn toggled(self, label: ColorLabel) -> Labels {
154        self.with(label, !self.has(label))
155    }
156
157    pub fn is_empty(self) -> bool {
158        self.0 == 0
159    }
160
161    /// The labels set, red first.
162    pub fn iter(self) -> impl Iterator<Item = ColorLabel> {
163        ColorLabel::ALL.into_iter().filter(move |l| self.has(*l))
164    }
165}
166
167impl FromIterator<ColorLabel> for Labels {
168    fn from_iter<T: IntoIterator<Item = ColorLabel>>(iter: T) -> Self {
169        iter.into_iter().fold(Labels::NONE, |l, c| l.with(c, true))
170    }
171}
172
173/// An image's marks, as the application gives them to the grid.
174#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
175pub struct Marks {
176    /// 0 (none) to [`MAX_RATING`].
177    pub rating: u8,
178    pub labels: Labels,
179    pub flag: Flag,
180}
181
182/// What a culling key does.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum CullAction {
185    /// Sets the rating (0 clears it).
186    Rate(u8),
187    /// Sets the flag.
188    Flag(Flag),
189    /// Toggles a colour label.
190    Label(ColorLabel),
191    /// Expands or collapses the stack under the cursor.
192    ToggleStack,
193    /// Larger or smaller thumbnails (the grid only).
194    ZoomIn,
195    ZoomOut,
196}
197
198/// The keys a focused grid or filmstrip reads for marks, and whether
199/// marking moves to the next image (auto-advance).
200///
201/// Keys go through the key dispatcher first: a key the application
202/// binds to a command never reaches the view.
203#[derive(Clone, Debug, PartialEq)]
204pub struct CullKeymap {
205    pub bindings: Vec<(EKey, CullAction)>,
206    /// After a rating, a flag or a label, the cursor moves to the next
207    /// image (Lightroom's Caps Lock mode).
208    pub auto_advance: bool,
209}
210
211impl Default for CullKeymap {
212    fn default() -> Self {
213        CullKeymap::lightroom()
214    }
215}
216
217impl CullKeymap {
218    /// The culling keys of Lightroom Classic, which Capture One's
219    /// culling also uses for ratings: 0 to 5 rate, P picks, X rejects,
220    /// U unflags, 6 to 9 toggle red, yellow, green and blue; S expands
221    /// or collapses a stack, + and - change the thumbnails' size.
222    pub fn lightroom() -> CullKeymap {
223        use CullAction as A;
224        CullKeymap {
225            bindings: vec![
226                (EKey::Num0, A::Rate(0)),
227                (EKey::Num1, A::Rate(1)),
228                (EKey::Num2, A::Rate(2)),
229                (EKey::Num3, A::Rate(3)),
230                (EKey::Num4, A::Rate(4)),
231                (EKey::Num5, A::Rate(5)),
232                (EKey::P, A::Flag(Flag::Pick)),
233                (EKey::X, A::Flag(Flag::Reject)),
234                (EKey::U, A::Flag(Flag::None)),
235                (EKey::Num6, A::Label(ColorLabel::Red)),
236                (EKey::Num7, A::Label(ColorLabel::Yellow)),
237                (EKey::Num8, A::Label(ColorLabel::Green)),
238                (EKey::Num9, A::Label(ColorLabel::Blue)),
239                (EKey::S, A::ToggleStack),
240                (EKey::Plus, A::ZoomIn),
241                (EKey::Equals, A::ZoomIn),
242                (EKey::Minus, A::ZoomOut),
243            ],
244            auto_advance: false,
245        }
246    }
247
248    /// No culling keys (navigation and selection keys only).
249    pub fn none() -> CullKeymap {
250        CullKeymap {
251            bindings: Vec::new(),
252            auto_advance: false,
253        }
254    }
255
256    #[must_use]
257    pub fn auto_advance(mut self, on: bool) -> CullKeymap {
258        self.auto_advance = on;
259        self
260    }
261
262    /// Binds a key (replacing its binding).
263    #[must_use]
264    pub fn bind(mut self, key: EKey, action: CullAction) -> CullKeymap {
265        self.bindings.retain(|(k, _)| *k != key);
266        self.bindings.push((key, action));
267        self
268    }
269
270    /// What `key` does.
271    pub fn action(&self, key: EKey) -> Option<CullAction> {
272        self.bindings
273            .iter()
274            .find(|(k, _)| *k == key)
275            .map(|(_, a)| *a)
276    }
277}
278
279/// What a mark widget returns: its response and the value the user
280/// asked for.
281#[derive(Debug)]
282pub struct MarkResponse<T> {
283    pub response: Response,
284    pub changed: Option<T>,
285}
286
287/// Five stars: a click on a star gives that rating (on the current one,
288/// none); focused, 0 to 5 set it, arrows step it, Home and End go to
289/// the ends. A slider for assistive technologies. Under the pointer, the
290/// stars up to it preview the value a click gives and the current value
291/// stays as a ghost; each star's tooltip says what a click does.
292///
293/// The shared widget is [`egui_pop_core::rating::RatingStars`] (the
294/// grid's stars, the file dialog's preview and a table's column use it
295/// too); this one returns a [`MarkResponse`] like the other marks.
296#[derive(Clone, Debug)]
297#[must_use = "show it with `show`"]
298pub struct RatingStars {
299    inner: rating::RatingStars,
300}
301
302impl RatingStars {
303    pub fn new(value: u8) -> RatingStars {
304        RatingStars {
305            inner: rating::RatingStars::new(value),
306        }
307    }
308
309    /// Its accessible name ("Rating" by default).
310    pub fn label(mut self, label: impl Into<String>) -> RatingStars {
311        self.inner = self.inner.label(label);
312        self
313    }
314
315    /// One star's size in points (default: the inline icon size).
316    pub fn size(mut self, size: f32) -> RatingStars {
317        self.inner = self.inner.size(size);
318        self
319    }
320
321    /// Shown, not edited ([`rating::RatingStars::read_only`]).
322    pub fn read_only(mut self, read_only: bool) -> RatingStars {
323        self.inner = self.inner.read_only(read_only);
324        self
325    }
326
327    /// When empty stars show ([`EmptyStars::Always`] by default).
328    pub fn empty(mut self, empty: EmptyStars) -> RatingStars {
329        self.inner = self.inner.empty(empty);
330        self
331    }
332
333    pub fn show(self, ui: &mut Ui) -> MarkResponse<u8> {
334        let out = self.inner.show(ui);
335        MarkResponse {
336            response: out.response,
337            changed: out.changed,
338        }
339    }
340}
341
342/// A toggle button per colour label, each drawn in its colour (in the
343/// [`LabelStyle`](super::LabelStyle) in force). Each button's tooltip
344/// says what it is ("Red label"), with its key when given
345/// ([`ColorLabels::keys`]: "Red label (6)"), or the application's own
346/// text ([`ColorLabels::tooltip`]).
347#[derive(Clone, Debug)]
348#[must_use = "show it with `show`"]
349pub struct ColorLabels {
350    value: Labels,
351    size: Option<f32>,
352    keys: Option<CullKeymap>,
353    tips: Vec<(ColorLabel, String)>,
354}
355
356impl ColorLabels {
357    pub fn new(value: Labels) -> ColorLabels {
358        ColorLabels {
359            value,
360            size: None,
361            keys: None,
362            tips: Vec::new(),
363        }
364    }
365
366    /// One button's size in points.
367    pub fn size(mut self, size: f32) -> ColorLabels {
368        self.size = Some(size);
369        self
370    }
371
372    /// Names in each tooltip the key `keys` binds to toggling that label.
373    pub fn keys(mut self, keys: &CullKeymap) -> ColorLabels {
374        self.keys = Some(keys.clone());
375        self
376    }
377
378    /// `label`'s tooltip, instead of its name (and key).
379    pub fn tooltip(mut self, label: ColorLabel, text: impl Into<String>) -> ColorLabels {
380        self.tips.retain(|(l, _)| *l != label);
381        self.tips.push((label, text.into()));
382        self
383    }
384
385    pub fn show(self, ui: &mut Ui) -> MarkResponse<Labels> {
386        let t = Tokens::of(ui.ctx());
387        let lt = LibraryTokens::of(ui.ctx());
388        let side = self.size.unwrap_or(t.size.control_height);
389        let mut changed = None;
390        let inner = ui.horizontal(|ui| {
391            ui.spacing_mut().item_spacing.x = t.space.xs;
392            for label in ColorLabel::ALL {
393                let on = self.value.has(label);
394                let r = toggle(ui, side, on, |painter, rect| {
395                    let color = lt.label(label);
396                    let color = if on {
397                        color
398                    } else {
399                        color.gamma_multiply(0.45)
400                    };
401                    paint::label(painter, label, rect.center(), rect.height() * 0.28, color);
402                });
403                let name = tr_args(
404                    ui.ctx(),
405                    &s::LABEL_TOGGLE,
406                    &[("label", &label.title(ui.ctx()))],
407                );
408                let tip = tip_text(
409                    ui.ctx(),
410                    &name,
411                    &self.tips,
412                    label,
413                    self.keys.as_ref(),
414                    CullAction::Label(label),
415                );
416                r.widget_info(move || WidgetInfo::selected(Role::CheckBox, true, on, &name));
417                let r = r.tip(tip);
418                if r.clicked() {
419                    changed = Some(self.value.toggled(label));
420                }
421            }
422        });
423        MarkResponse {
424            response: inner.response,
425            changed,
426        }
427    }
428}
429
430/// Two toggle buttons: pick and reject (a click on the one set unflags).
431/// Each button's tooltip says what it is ("Pick"), with its key when
432/// given ([`FlagToggle::keys`]: "Pick (P)"), or the application's own
433/// text ([`FlagToggle::tooltip`]).
434#[derive(Clone, Debug)]
435#[must_use = "show it with `show`"]
436pub struct FlagToggle {
437    value: Flag,
438    size: Option<f32>,
439    keys: Option<CullKeymap>,
440    tips: Vec<(Flag, String)>,
441}
442
443impl FlagToggle {
444    pub fn new(value: Flag) -> FlagToggle {
445        FlagToggle {
446            value,
447            size: None,
448            keys: None,
449            tips: Vec::new(),
450        }
451    }
452
453    /// One button's size in points.
454    pub fn size(mut self, size: f32) -> FlagToggle {
455        self.size = Some(size);
456        self
457    }
458
459    /// Names in each tooltip the key `keys` binds to that flag.
460    pub fn keys(mut self, keys: &CullKeymap) -> FlagToggle {
461        self.keys = Some(keys.clone());
462        self
463    }
464
465    /// `flag`'s button tooltip (`Flag::Pick` or `Flag::Reject`), instead
466    /// of its name (and key).
467    pub fn tooltip(mut self, flag: Flag, text: impl Into<String>) -> FlagToggle {
468        self.tips.retain(|(f, _)| *f != flag);
469        self.tips.push((flag, text.into()));
470        self
471    }
472
473    pub fn show(self, ui: &mut Ui) -> MarkResponse<Flag> {
474        let t = Tokens::of(ui.ctx());
475        let lt = LibraryTokens::of(ui.ctx());
476        let side = self.size.unwrap_or(t.size.control_height);
477        let mut changed = None;
478        let inner = ui.horizontal(|ui| {
479            ui.spacing_mut().item_spacing.x = t.space.xs;
480            for flag in [Flag::Pick, Flag::Reject] {
481                let on = self.value == flag;
482                let r = toggle(ui, side, on, |painter, rect| {
483                    let icon = rect.shrink(rect.width() * 0.22);
484                    match flag {
485                        Flag::Pick => {
486                            paint::flag(painter, icon, if on { lt.pick } else { lt.star_empty })
487                        }
488                        _ => {
489                            paint::cross(painter, icon, if on { lt.reject } else { lt.star_empty })
490                        }
491                    }
492                });
493                let name = flag.title(ui.ctx());
494                let tip = tip_text(
495                    ui.ctx(),
496                    &name,
497                    &self.tips,
498                    flag,
499                    self.keys.as_ref(),
500                    CullAction::Flag(flag),
501                );
502                r.widget_info(move || WidgetInfo::selected(Role::CheckBox, true, on, &name));
503                let r = r.tip(tip);
504                if r.clicked() {
505                    changed = Some(if on { Flag::None } else { flag });
506                }
507            }
508        });
509        MarkResponse {
510            response: inner.response,
511            changed,
512        }
513    }
514}
515
516/// A mark button's tooltip: the application's text for `which`, else
517/// its name, with the first key `keys` binds to `action`.
518fn tip_text<T: PartialEq>(
519    ctx: &egui::Context,
520    name: &str,
521    tips: &[(T, String)],
522    which: T,
523    keys: Option<&CullKeymap>,
524    action: CullAction,
525) -> String {
526    if let Some((_, text)) = tips.iter().find(|(w, _)| *w == which) {
527        return text.clone();
528    }
529    let key = keys.and_then(|k| {
530        k.bindings
531            .iter()
532            .find(|(_, a)| *a == action)
533            .map(|(key, _)| key.symbol_or_name())
534    });
535    match key {
536        Some(key) => tr_args(ctx, &s::MARK_WITH_KEY, &[("mark", name), ("key", key)]),
537        None => name.to_string(),
538    }
539}
540
541/// A square toggle button (the kit's `mark-toggle`), its mark drawn by
542/// `paint`.
543fn toggle(
544    ui: &mut Ui,
545    side: f32,
546    on: bool,
547    paint: impl FnOnce(&egui::Painter, egui::Rect),
548) -> Response {
549    let (rect, r) = ui.allocate_exact_size(vec2(side, side), Sense::click());
550    if ui.is_rect_visible(rect) {
551        let painter = ui.painter();
552        // On wins over the pointer: its fill stays under it.
553        let state = State::REST
554            .with(State::SELECTED, on)
555            .with(State::HOVER, r.hovered() && !on)
556            .with(State::FOCUS, egui_pop_core::focus::shows_ring(&r));
557        if r.has_focus() {
558            egui_pop_core::focus::own_ring(ui.ctx(), r.id);
559        }
560        Kit::of(ui.ctx()).mark_toggle.paint(
561            &KitCx {
562                painter,
563                ppp: ui.ctx().pixels_per_point(),
564            },
565            &Part {
566                rect,
567                room: rect,
568                state,
569                label: None,
570            },
571        );
572        paint(painter, rect);
573    }
574    r
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn labels_toggle_and_names_round_trip() {
583        let l = Labels::NONE
584            .toggled(ColorLabel::Red)
585            .toggled(ColorLabel::Blue);
586        assert_eq!(
587            l.iter().collect::<Vec<_>>(),
588            [ColorLabel::Red, ColorLabel::Blue]
589        );
590        assert!(l.toggled(ColorLabel::Red).has(ColorLabel::Blue));
591        assert!(!l.toggled(ColorLabel::Red).has(ColorLabel::Red));
592        for c in ColorLabel::ALL {
593            assert_eq!(ColorLabel::parse(c.name()), Some(c));
594        }
595        for f in Flag::ALL {
596            assert_eq!(Flag::parse(f.name()), Some(f));
597        }
598    }
599
600    #[test]
601    fn the_lightroom_keys_rate_flag_and_label() {
602        let k = CullKeymap::lightroom();
603        assert_eq!(k.action(EKey::Num3), Some(CullAction::Rate(3)));
604        assert_eq!(k.action(EKey::X), Some(CullAction::Flag(Flag::Reject)));
605        assert_eq!(
606            k.action(EKey::Num8),
607            Some(CullAction::Label(ColorLabel::Green))
608        );
609        assert_eq!(k.action(EKey::Q), None);
610        let k = k.bind(EKey::Num9, CullAction::Label(ColorLabel::Purple));
611        assert_eq!(
612            k.action(EKey::Num9),
613            Some(CullAction::Label(ColorLabel::Purple))
614        );
615    }
616}