Skip to main content

egui_pop_views/library/
paint.rs

1//! The library's colours (from the theme) and the shapes its marks are
2//! drawn with: stars, flags, colour labels (same-shape swatches, as in
3//! Lightroom and darktable, or a shape each so a label never reads by its
4//! colour alone: [`LabelStyle`]), pills.
5
6use std::f32::consts::{PI, TAU};
7
8use egui::{Align2, Color32, CornerRadius, FontId, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2};
9use egui_pop_core::kit::{Component, KitCx, Part, State, Tone};
10use egui_pop_core::theme::Tokens;
11use egui_pop_core::tokens::Value;
12use serde_json::Value as Json;
13
14use super::marks::ColorLabel;
15
16/// The library's content colours, from the installed theme: optional
17/// component tokens (`library.*`) falling back on system ones, so every
18/// theme draws them without declaring anything. The boxes the marks sit
19/// on (cells, pills, chips, toggles, panes) are the kit's
20/// (`egui_pop_core::kit::Kit`: `thumb-cell`, `pill`, `tag-chip`...).
21#[derive(Clone, Debug, PartialEq)]
22pub struct LibraryTokens {
23    /// A star given (`library.star`, else `status.warning`). The rating
24    /// stars no longer read it: they are the kit's `rating-star`
25    /// (`egui_pop_core::rating`).
26    pub star: Color32,
27    /// A pick or reject toggle when off (`library.star-empty`, else
28    /// `text.muted`); the rating's empty stars are the kit's.
29    pub star_empty: Color32,
30    /// The pick flag (`library.pick`, else `text.strong`).
31    pub pick: Color32,
32    /// The reject mark (`library.reject`, else `status.danger`).
33    pub reject: Color32,
34    /// Red, yellow, green, blue and purple (`library.label-<name>`).
35    pub labels: [Color32; 5],
36    /// The rubber band (`library.band`) and its outline.
37    pub band: Color32,
38    pub band_outline: Color32,
39}
40
41impl LibraryTokens {
42    pub fn of(ctx: &egui::Context) -> LibraryTokens {
43        let t = Tokens::of(ctx);
44        let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
45        let purple = mix(t.status.danger, t.status.info);
46        LibraryTokens {
47            star: c("library.star", t.status.warning),
48            star_empty: c("library.star-empty", t.text.muted),
49            pick: c("library.pick", t.text.strong),
50            reject: c("library.reject", t.status.danger),
51            labels: [
52                c("library.label-red", t.status.danger),
53                c("library.label-yellow", t.status.warning),
54                c("library.label-green", t.status.success),
55                c("library.label-blue", t.status.info),
56                c("library.label-purple", purple),
57            ],
58            band: c("library.band", t.accent.default.gamma_multiply(0.18)),
59            band_outline: c("library.band-outline", t.accent.default),
60        }
61    }
62
63    /// A label's colour.
64    pub fn label(&self, label: ColorLabel) -> Color32 {
65        self.labels[label.index()]
66    }
67}
68
69/// Halfway between two colours.
70fn mix(a: Color32, b: Color32) -> Color32 {
71    let m = |x: u8, y: u8| ((u16::from(x) + u16::from(y)) / 2) as u8;
72    Color32::from_rgb(m(a.r(), b.r()), m(a.g(), b.g()), m(a.b(), b.b()))
73}
74
75/// The ten points of a five-pointed star, outer first, from the top.
76fn star_points(center: Pos2, outer: f32) -> Vec<Pos2> {
77    let inner = outer * 0.42;
78    (0..10usize)
79        .map(|k| {
80            let a = -PI / 2.0 + k as f32 * PI / 5.0;
81            let r = if k.is_multiple_of(2) { outer } else { inner };
82            center + vec2(a.cos(), a.sin()) * r
83        })
84        .collect()
85}
86
87/// A star, filled (its pentagon and its five tips, each convex) or
88/// outlined.
89pub fn star(painter: &Painter, center: Pos2, radius: f32, fill: Option<Color32>, outline: Color32) {
90    let p = star_points(center, radius);
91    match fill {
92        Some(color) => {
93            let inner: Vec<Pos2> = p.iter().skip(1).step_by(2).copied().collect();
94            painter.add(Shape::convex_polygon(inner, color, Stroke::NONE));
95            for k in (0..10).step_by(2) {
96                let tip = vec![p[(k + 9) % 10], p[k], p[k + 1]];
97                painter.add(Shape::convex_polygon(tip, color, Stroke::NONE));
98            }
99        }
100        None => {
101            painter.add(Shape::closed_line(p, Stroke::new(1.0, outline)));
102        }
103    }
104}
105
106/// A pennant on its pole, in `rect`.
107pub fn flag(painter: &Painter, rect: Rect, color: Color32) {
108    let x0 = rect.left() + rect.width() * 0.25;
109    let x1 = rect.right() - rect.width() * 0.1;
110    let top = rect.top() + rect.height() * 0.1;
111    let bottom = rect.bottom() - rect.height() * 0.05;
112    painter.line_segment([pos2(x0, top), pos2(x0, bottom)], Stroke::new(1.5, color));
113    painter.add(Shape::convex_polygon(
114        vec![
115            pos2(x0, top),
116            pos2(x1, top + rect.height() * 0.28),
117            pos2(x0, top + rect.height() * 0.56),
118        ],
119        color,
120        Stroke::NONE,
121    ));
122}
123
124/// A cross, in `rect`.
125pub fn cross(painter: &Painter, rect: Rect, color: Color32) {
126    let r = rect.shrink(rect.width() * 0.2);
127    let stroke = Stroke::new(2.0, color);
128    painter.line_segment([r.left_top(), r.right_bottom()], stroke);
129    painter.line_segment([r.right_top(), r.left_bottom()], stroke);
130}
131
132/// How colour labels are drawn, wherever they show (the marks bar, the
133/// grid's badges): the application's choice ([`LabelStyle::set`], a
134/// setting for colour-blind users, say), else the theme's
135/// (`library.label-style`: `swatch` or `shape`), else swatches.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum LabelStyle {
138    /// The same rounded square for every label, only its colour
139    /// differing (Lightroom's and darktable's).
140    #[default]
141    Swatch,
142    /// A shape each (red a circle, yellow a triangle, green a square,
143    /// blue a diamond, purple a hexagon), so a label never reads by its
144    /// colour alone.
145    Shape,
146}
147
148impl LabelStyle {
149    fn id() -> egui::Id {
150        egui::Id::unique("egui_pop_views::library::label_style")
151    }
152
153    /// The style in force in `ctx`.
154    pub fn of(ctx: &egui::Context) -> LabelStyle {
155        if let Some(style) = ctx.data(|d| d.get_temp::<LabelStyle>(Self::id())) {
156            return style;
157        }
158        match Tokens::of(ctx).resolved().value("library.label-style") {
159            Some(Value::Other(Json::String(s))) if s == "shape" => LabelStyle::Shape,
160            _ => LabelStyle::Swatch,
161        }
162    }
163
164    /// Sets the application's choice (`None`: back to the theme's).
165    pub fn set(ctx: &egui::Context, style: Option<LabelStyle>) {
166        ctx.data_mut(|d| match style {
167            Some(s) => {
168                d.insert_temp(Self::id(), s);
169            }
170            None => {
171                d.remove::<LabelStyle>(Self::id());
172            }
173        });
174    }
175}
176
177/// A colour label, in the [`LabelStyle`] of the painter's context: a
178/// rounded square swatch, or its own shape (red a circle, yellow a
179/// triangle, green a square, blue a diamond, purple a hexagon).
180pub fn label(painter: &Painter, label: ColorLabel, center: Pos2, radius: f32, color: Color32) {
181    if LabelStyle::of(painter.ctx()) == LabelStyle::Swatch {
182        painter.rect_filled(
183            Rect::from_center_size(center, vec2(radius, radius) * 1.7),
184            CornerRadius::same((radius * 0.4).round() as u8),
185            color,
186        );
187        return;
188    }
189    let poly = |n: usize, start: f32, r: f32| -> Vec<Pos2> {
190        (0..n)
191            .map(|k| {
192                let a = start + k as f32 * TAU / n as f32;
193                center + vec2(a.cos(), a.sin()) * r
194            })
195            .collect()
196    };
197    let shape = match label {
198        ColorLabel::Red => Shape::circle_filled(center, radius * 0.9, color),
199        ColorLabel::Yellow => {
200            Shape::convex_polygon(poly(3, -PI / 2.0, radius * 1.1), color, Stroke::NONE)
201        }
202        ColorLabel::Green => Shape::rect_filled(
203            Rect::from_center_size(center, vec2(radius, radius) * 1.6),
204            CornerRadius::ZERO,
205            color,
206        ),
207        ColorLabel::Blue => {
208            Shape::convex_polygon(poly(4, -PI / 2.0, radius * 1.05), color, Stroke::NONE)
209        }
210        ColorLabel::Purple => Shape::convex_polygon(poly(6, 0.0, radius), color, Stroke::NONE),
211    };
212    painter.add(shape);
213}
214
215/// A pill (the kit's `pill`) holding `text`, in `tone`, its corner
216/// `anchor` at `at`; returns its rectangle and its text's colour.
217pub fn pill(
218    painter: &Painter,
219    pill: &Component,
220    tone: Tone,
221    at: Pos2,
222    anchor: Align2,
223    text: &str,
224    font: FontId,
225) -> (Rect, Color32) {
226    let galley = painter.layout_no_wrap(text.to_string(), font, Color32::PLACEHOLDER);
227    let rect = anchor.anchor_size(at, pill.measure(galley.size()));
228    let part = Part {
229        rect,
230        room: rect,
231        state: State::REST.toned(tone),
232        label: Some(&galley),
233    };
234    pill.paint_part(
235        &KitCx {
236            painter,
237            ppp: painter.ctx().pixels_per_point(),
238        },
239        &part,
240    );
241    (rect, pill.style(part.state).text)
242}