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 /// `bevel-light`.
65 pub bevel_light: Color32,
66 /// `bevel-dark`.
67 pub bevel_dark: Color32,
68}
69
70impl Palette {
71 /// Resolve a surface intent.
72 ///
73 /// A plain lookup. There is no substitution here any more: it existed only
74 /// while `surface-well` was underived, and every consumer now reads the
75 /// real token.
76 #[must_use]
77 pub const fn fill(&self, fill: Fill) -> Color32 {
78 match fill {
79 Fill::Page => self.page,
80 Fill::Raised => self.raised,
81 Fill::Overlay => self.overlay,
82 Fill::Well => self.well,
83 }
84 }
85
86 /// Resolve a bevel edge intent.
87 #[must_use]
88 pub const fn edge(&self, edge: Edge) -> Color32 {
89 match edge {
90 Edge::Light => self.bevel_light,
91 Edge::Dark => self.bevel_dark,
92 }
93 }
94}
95
96/// The geometry a framed region is drawn with.
97///
98/// Every field is a value, which is why they all arrive from the caller:
99/// radius and border width belong to `makeover-geometry`, and margins come
100/// from its relational gaps.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub struct FrameStyle {
103 /// Corner radius. Square under the Platinum default.
104 pub radius: CornerRadius,
105 /// Inner margin between the frame and its contents.
106 pub margin: Margin,
107 /// Bevel stroke width, in points.
108 pub stroke: f32,
109}
110
111impl Default for FrameStyle {
112 /// A one-point square frame with no inner margin.
113 fn default() -> Self {
114 Self {
115 radius: CornerRadius::ZERO,
116 margin: Margin::ZERO,
117 stroke: 1.0,
118 }
119 }
120}
121
122/// Paint a two-tone edge just inside `rect`.
123///
124/// Fill first, bevel after: this adds two polylines and nothing else, so it
125/// composes over whatever is already there. That is what lets it go over an
126/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
127///
128/// Two three-point polylines meeting at opposite corners, rather than four
129/// segments, so egui mitres the corner joins instead of leaving a notch.
130pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
131 let (top_left, bottom_right) = bevel.edges();
132
133 // Inset by half a stroke so the line lands inside `rect` rather than
134 // straddling its edge, which on a fractional-scale display is the
135 // difference between one crisp pixel and two dim ones.
136 let r = rect.shrink(stroke / 2.0);
137
138 painter.add(Shape::line(
139 vec![r.left_bottom(), r.left_top(), r.right_top()],
140 Stroke::new(stroke, palette.edge(top_left)),
141 ));
142 painter.add(Shape::line(
143 vec![r.right_top(), r.right_bottom(), r.left_bottom()],
144 Stroke::new(stroke, palette.edge(bottom_right)),
145 ));
146}
147
148/// Draw a region at a given [`Depth`]: its fill and its edge, together.
149///
150/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
151/// difference between level-with and painted-the-same-colour, and it is the
152/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
153/// page.
154pub fn frame<R>(
155 ui: &mut Ui,
156 depth: Depth,
157 palette: &Palette,
158 style: FrameStyle,
159 add_contents: impl FnOnce(&mut Ui) -> R,
160) -> R {
161 let mut f = egui::Frame::new()
162 .corner_radius(style.radius)
163 .inner_margin(style.margin);
164 if let Some(fill) = depth.fill() {
165 f = f.fill(palette.fill(fill));
166 }
167 let framed = f.show(ui, add_contents);
168 if let Some(bevel) = depth.bevel() {
169 paint_bevel(
170 ui.painter(),
171 framed.response.rect,
172 bevel,
173 palette,
174 style.stroke,
175 );
176 }
177 framed.inner
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 fn palette(well: Color32) -> Palette {
185 Palette {
186 page: Color32::from_rgb(1, 1, 1),
187 raised: Color32::from_rgb(2, 2, 2),
188 overlay: Color32::from_rgb(3, 3, 3),
189 well,
190 bevel_light: Color32::WHITE,
191 bevel_dark: Color32::BLACK,
192 }
193 }
194
195 #[test]
196 fn a_well_resolves_to_its_own_token() {
197 // No substitution left. The page-filled well was a stand-in for a
198 // token that did not exist yet; it exists now.
199 let w = Color32::from_rgb(9, 9, 9);
200 let p = palette(w);
201 assert_eq!(p.fill(Fill::Well), w);
202 assert_ne!(p.fill(Fill::Well), p.page);
203 }
204
205 #[test]
206 fn every_intent_is_a_plain_lookup() {
207 let p = palette(Color32::from_rgb(9, 9, 9));
208 assert_eq!(p.fill(Fill::Page), p.page);
209 assert_eq!(p.fill(Fill::Raised), p.raised);
210 assert_eq!(p.fill(Fill::Overlay), p.overlay);
211 }
212
213 #[test]
214 fn a_raised_region_never_resolves_to_the_well_fill() {
215 // The cross-app bug, asserted at the renderer boundary this time.
216 let p = palette(Color32::from_rgb(9, 9, 9));
217 let raised = Depth::Raised.fill().map(|f| p.fill(f));
218 let well = Depth::Well.fill().map(|f| p.fill(f));
219 assert_eq!(raised, Some(p.raised));
220 assert_ne!(raised, well);
221 }
222
223 #[test]
224 fn the_lit_edge_swaps_when_a_card_is_pressed() {
225 let p = palette(Color32::from_rgb(9, 9, 9));
226 let (tl, _) = Depth::Raised.bevel().unwrap().edges();
227 let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
228 assert_eq!(p.edge(tl), p.bevel_light);
229 assert_eq!(p.edge(ptl), p.bevel_dark);
230 }
231
232 #[test]
233 fn flat_asks_for_neither_fill_nor_edge() {
234 assert!(Depth::Flat.fill().is_none());
235 assert!(Depth::Flat.bevel().is_none());
236 }
237
238 #[test]
239 fn the_default_frame_is_square_and_one_point() {
240 let d = FrameStyle::default();
241 assert_eq!(d.radius, CornerRadius::ZERO);
242 assert_eq!(d.margin, Margin::ZERO);
243 assert!((d.stroke - 1.0).abs() < f32::EPSILON);
244 }
245}