Skip to main content

makeover_immediate/
lib.rs

1//! The immediate-mode renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Named for the mode, not the library, the way `makeover-tui` is named for
6//! the target and not for ratatui. Immediate mode is the constraint that
7//! actually separates this renderer from the other two, and egui is the
8//! backend it is written against.
9//!
10//! It is the harshest renderer the description has to survive: no
11//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
12//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
13//! A two-tone lit edge is not something egui can be configured into producing,
14//! so it gets painted by hand here, once, instead of in every consuming app.
15//!
16//! # What this crate does and does not own
17//!
18//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
19//! for a filled region. It owns no colours and no sizes, and no longer owns a
20//! substitution: it briefly supplied the page for a well, which was a stand-in
21//! for `surface-well` before makeover derived it, and every consumer reads the
22//! real token now. [`Palette`] is supplied by the caller,
23//! already resolved, and every radius, margin and stroke width arrives in
24//! [`FrameStyle`].
25//!
26//! That split is why the crate has no dependency on `makeover` itself: the app
27//! already resolves a theme, and coupling a renderer to a colour crate's
28//! version would buy nothing.
29//!
30//! # The cascade is the real difference
31//!
32//! A stylesheet can say "a pressed button inverts its bevel" once and let the
33//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
34//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
35//! the decision from being re-derived per widget.
36
37#![forbid(unsafe_code)]
38
39use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
40use makeover_layout::{Bevel, Depth, Edge, Fill};
41
42/// The resolved colours this renderer needs, as flat values.
43///
44/// Built by the app from whatever it already uses to resolve a theme, then
45/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
46/// painted per widget per frame, and a map lookup per edge is a cost with
47/// nothing to show for it.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct Palette {
50    /// `surface-page`.
51    pub page: Color32,
52    /// `surface-raised`.
53    pub raised: Color32,
54    /// `surface-overlay`.
55    pub overlay: Color32,
56    /// `surface-well`.
57    ///
58    /// Required, not optional. makeover derives it for every theme from 2.3.0,
59    /// so a resolved palette without a well is not a thing that exists here.
60    /// It was an `Option` while that was untrue, and this renderer substituted
61    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
62    /// since a terminal can have the colour and still be unable to show it.
63    pub well: Color32,
64    /// `surface-sunken`.
65    ///
66    /// A surface set back from the one it sits on, by colour and nothing else.
67    /// Not a well: a well is a hole with an edge, and this has no edge. An
68    /// immediate-mode renderer paints an arbitrary rect, so unlike
69    /// `makeover-tui` it has no excuse for declining this one.
70    ///
71    /// Required rather than optional, on the same footing as `well`: all 31
72    /// themes makeover embeds author it.
73    pub sunken: Color32,
74    /// `bevel-light`.
75    pub bevel_light: Color32,
76    /// `bevel-dark`.
77    pub bevel_dark: Color32,
78}
79
80impl Palette {
81    /// Resolve a surface intent, or `None` for one this renderer does not know.
82    ///
83    /// A plain lookup. There is still no substitution: the old one existed only
84    /// while `surface-well` was underived, and every consumer reads the real
85    /// token now.
86    ///
87    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
88    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
89    /// stay total by inventing a colour for a member it has never heard of.
90    /// That is the substitution this crate spent 0.2.0 removing, so the return
91    /// type moved instead. Every member the description has today is answered
92    /// with `Some`.
93    #[must_use]
94    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
95        match fill {
96            Fill::Page => Some(self.page),
97            Fill::Raised => Some(self.raised),
98            Fill::Overlay => Some(self.overlay),
99            Fill::Well => Some(self.well),
100            Fill::Sunken => Some(self.sunken),
101            _ => None,
102        }
103    }
104
105    /// Resolve a bevel edge intent.
106    #[must_use]
107    pub const fn edge(&self, edge: Edge) -> Color32 {
108        match edge {
109            Edge::Light => self.bevel_light,
110            Edge::Dark => self.bevel_dark,
111        }
112    }
113}
114
115/// The geometry a framed region is drawn with.
116///
117/// Every field is a value, which is why they all arrive from the caller:
118/// radius and border width belong to `makeover-geometry`, and margins come
119/// from its relational gaps.
120#[derive(Debug, Clone, Copy, PartialEq)]
121pub struct FrameStyle {
122    /// Corner radius. Square under the Platinum default.
123    pub radius: CornerRadius,
124    /// Inner margin between the frame and its contents.
125    pub margin: Margin,
126    /// Bevel stroke width, in points.
127    pub stroke: f32,
128}
129
130impl Default for FrameStyle {
131    /// A one-point square frame with no inner margin.
132    fn default() -> Self {
133        Self {
134            radius: CornerRadius::ZERO,
135            margin: Margin::ZERO,
136            stroke: 1.0,
137        }
138    }
139}
140
141/// Paint a two-tone edge just inside `rect`.
142///
143/// Fill first, bevel after: this adds two polylines and nothing else, so it
144/// composes over whatever is already there. That is what lets it go over an
145/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
146///
147/// Two three-point polylines meeting at opposite corners, rather than four
148/// segments, so egui mitres the corner joins instead of leaving a notch.
149///
150/// The dark polyline is drawn second, so the two corners where the runs meet
151/// take its tone. That is the right answer here rather than a concession.
152/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
153/// a renderer with room to divide one should; at the default one-point stroke
154/// the corner is a one-point square, so the division is sub-pixel and
155/// antialiasing resolves it to the same blend the mitre already gives. Splitting
156/// it would add a seam and no information. `makeover-tui` does split, because a
157/// terminal cell is large enough that not splitting costs a visible cell of edge
158/// weight — the same rule, at a resolution where it has something to say.
159pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
160    let (top_left, bottom_right) = bevel.edges();
161
162    // Inset by half a stroke so the line lands inside `rect` rather than
163    // straddling its edge, which on a fractional-scale display is the
164    // difference between one crisp pixel and two dim ones.
165    let r = rect.shrink(stroke / 2.0);
166
167    painter.add(Shape::line(
168        vec![r.left_bottom(), r.left_top(), r.right_top()],
169        Stroke::new(stroke, palette.edge(top_left)),
170    ));
171    painter.add(Shape::line(
172        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
173        Stroke::new(stroke, palette.edge(bottom_right)),
174    ));
175}
176
177/// Draw a region at a given [`Depth`]: its fill and its edge, together.
178///
179/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
180/// difference between level-with and painted-the-same-colour, and it is the
181/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
182/// page.
183pub fn frame<R>(
184    ui: &mut Ui,
185    depth: Depth,
186    palette: &Palette,
187    style: FrameStyle,
188    add_contents: impl FnOnce(&mut Ui) -> R,
189) -> R {
190    let mut f = egui::Frame::new()
191        .corner_radius(style.radius)
192        .inner_margin(style.margin);
193    // Two ways there is no fill to paint, and they collapse to the same
194    // outcome: the depth names none (Depth::Flat), or it names one this
195    // renderer cannot resolve. Either way the frame goes unfilled and the
196    // bevel below carries the depth on its own, which is the rule this
197    // module already documents for Flat.
198    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
199        f = f.fill(fill);
200    }
201    let framed = f.show(ui, add_contents);
202    if let Some(bevel) = depth.bevel() {
203        paint_bevel(
204            ui.painter(),
205            framed.response.rect,
206            bevel,
207            palette,
208            style.stroke,
209        );
210    }
211    framed.inner
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    fn palette(well: Color32) -> Palette {
219        Palette {
220            page: Color32::from_rgb(1, 1, 1),
221            raised: Color32::from_rgb(2, 2, 2),
222            overlay: Color32::from_rgb(3, 3, 3),
223            well,
224            sunken: Color32::from_rgb(4, 4, 4),
225            bevel_light: Color32::WHITE,
226            bevel_dark: Color32::BLACK,
227        }
228    }
229
230    #[test]
231    fn a_well_resolves_to_its_own_token() {
232        // No substitution left. The page-filled well was a stand-in for a
233        // token that did not exist yet; it exists now.
234        let w = Color32::from_rgb(9, 9, 9);
235        let p = palette(w);
236        assert_eq!(p.fill(Fill::Well), Some(w));
237        assert_ne!(p.fill(Fill::Well), Some(p.page));
238    }
239
240    #[test]
241    fn every_intent_is_a_plain_lookup() {
242        let p = palette(Color32::from_rgb(9, 9, 9));
243        assert_eq!(p.fill(Fill::Page), Some(p.page));
244        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
245        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
246    }
247
248    /// Sunken is its own colour, not the well's and not the page's. The two
249    /// are authored in opposite directions and an earlier cut of the
250    /// description conflated them.
251    #[test]
252    fn sunken_is_neither_the_well_nor_the_page() {
253        let p = palette(Color32::from_rgb(9, 9, 9));
254        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
255        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
256        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
257    }
258
259    #[test]
260    fn a_raised_region_never_resolves_to_the_well_fill() {
261        // The cross-app bug, asserted at the renderer boundary this time.
262        let p = palette(Color32::from_rgb(9, 9, 9));
263        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
264        let well = Depth::Well.fill().and_then(|f| p.fill(f));
265        assert_eq!(raised, Some(p.raised));
266        assert_ne!(raised, well);
267    }
268
269    #[test]
270    fn the_lit_edge_swaps_when_a_card_is_pressed() {
271        let p = palette(Color32::from_rgb(9, 9, 9));
272        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
273        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
274        assert_eq!(p.edge(tl), p.bevel_light);
275        assert_eq!(p.edge(ptl), p.bevel_dark);
276    }
277
278    #[test]
279    fn flat_asks_for_neither_fill_nor_edge() {
280        assert!(Depth::Flat.fill().is_none());
281        assert!(Depth::Flat.bevel().is_none());
282    }
283
284    #[test]
285    fn the_default_frame_is_square_and_one_point() {
286        let d = FrameStyle::default();
287        assert_eq!(d.radius, CornerRadius::ZERO);
288        assert_eq!(d.margin, Margin::ZERO);
289        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
290    }
291}